public void OnRequest(IDataObjectOutputStream outStream, Query query, IZone zone, IMessageInfo info) { // To be a successful publisher of data using the ADK, follow these steps // 1) Examine the query conditions. If they are too complex for your agent, // throw the appropriate SIFException // This example agent uses the autoFilter() capability of DataObjectOutputStream. Using // this capability, any object can be written to the output stream and the stream will // filter out any objects that don't meet the conditions of the Query. However, a more // robust agent with large amounts of data would want to pre-filter the data when it does its // initial database query. outStream.Filter = query; Console.WriteLine("Responding to SIF_Request for StudentPersonal"); // 2) Write any data to the output stream foreach (StudentPersonal sp in fData) { outStream.Write(sp); } }
private int AddContactToMandrillSentMessage(IMessageInfo messageInfo, Mandrill.EmailResult emailResult) { if (emailResult == null) { return(0); } EmailResultStatus emailResultStatus = emailResult.Status; BulkEmailResponseCode response; try { response = emailResultStatus.GetBulkEmailResponseCode(); } catch (InvalidCastException) { return(0); } Guid mandrillId; if (!Guid.TryParse(emailResult.Id, out mandrillId)) { return(0); } var recipientInfo = messageInfo.Recipients.FirstOrDefault() as BulkEmailRecipientInfo; var insert = new Insert(_userConnection) .Into("MandrillSentMessage") .Set("MandrillId", Column.Parameter(mandrillId)) .Set("BulkEmailRId", Column.Parameter(messageInfo.MessageRId)) .Set("ContactRId", Column.Parameter(recipientInfo.ContactRId)) .Set("ResponseCode", Column.Parameter((int)response)) .Set("MailingStartTS", Column.Parameter(messageInfo.MailingStartTS)); return(insert.Execute()); }
/// <summary> /// Initalizes email data. /// </summary> /// <param name="bulkEmail">Email instance.</param> /// <param name="messageInfo">Data nexessary for email sending.</param> private EmailMessage InitEmailMessage(IMessageInfo messageInfo) { var instantMessageInfo = messageInfo as InstantMessageInfo; BulkEmail bulkEmail = instantMessageInfo.BulkEmail; var messageImages = new List <image>(); var message = new EmailMessage { subject = bulkEmail.TemplateSubject, from_email = bulkEmail.SenderEmail, from_name = bulkEmail.SenderName, html = bulkEmail.TemplateBody, track_clicks = true, track_opens = true, images = messageImages, inline_css = true, important = true }; var macrosHelper = new MarketingMacrosHelper(_userConnection); string templateCode = GetTemplate(bulkEmail, messageInfo, messageImages, macrosHelper); var bulkEmailId = bulkEmail.GetTypedColumnValue <Guid>("Id"); PrepareRecipient(messageInfo, macrosHelper, message, bulkEmailId); message.html = templateCode; if (_isMetadataInitialized) { message.AddMetadata(BulkEmailMetadataValue, messageInfo.MessageId.ToString("N")); } if (macrosHelper.GlobalMergeVars.Any()) { message.InitGlobalVariable(); message.global_merge_vars.AddRange(macrosHelper.GlobalMergeVars); } return(message); }
public void OnRequest( IDataObjectOutputStream outStream, Query query, IZone zone, IMessageInfo info ) { // To be a successful publisher of data using the ADK, follow these steps // 1) Examine the query conditions. If they are too complex for your agent, // throw the appropriate SIFException // This example agent uses the autoFilter() capability of DataObjectOutputStream. Using // this capability, any object can be written to the output stream and the stream will // filter out any objects that don't meet the conditions of the Query. However, a more // robust agent with large amounts of data would want to pre-filter the data when it does its // initial database query. outStream.Filter = query; Console.WriteLine( "Responding to SIF_Request for StudentPersonal" ); // 2) Write any data to the output stream foreach ( StudentPersonal sp in fData ) { outStream.Write( sp ); } }
public Message(long id, IMessageInfo messageInfo) { _id = id; _authorId = messageInfo.AuthorId; _value = messageInfo.Text; _categoryIds = messageInfo.CategoryIds; }
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); } } }
public void CheckConnectedClientsWaitingForAll() { int count = m_simulator.LeftPlayersCount + m_simulator.RightPlayersCount; bool[] recv = new bool[count]; for (int i = 0; i < count; ++i) { try { while (!recv[i] && !m_simulator.IsGameStopped) { if (m_connectedClients[i].DataAvailable) { recv[i] = true; string str = m_connectedClients[i].ReadString(); IMessageInfo mi = MessageParser.ParseInputMessage(str); if (mi.MessageType == MessageTypes.Hold) { var act = new SoccerAction(ActionTypes.Hold, -1); m_simulator.UpdateActionForPlayer(i, act); } else if (mi.MessageType == MessageTypes.Move) { var movmsg = mi as MoveMessage; var act = new SoccerAction(movmsg.ActionType, -1); m_simulator.UpdateActionForPlayer(i, act); } else if (mi.MessageType == MessageTypes.Pass) { var pmsg = mi as PassMessage; m_simulator.UpdateActionForPlayer(i, new SoccerAction(ActionTypes.Pass, pmsg.DstUnum)); } else if (mi.MessageType == MessageTypes.Home) { var hmsg = mi as HomeMessage; if (!m_simulator.SetHomePos(i, hmsg.R, hmsg.C)) { m_connectedClients[i].WriteString("(error could-not-set-home)"); } } else if (mi.MessageType == MessageTypes.EpisodeTimeout) { var etmsg = mi as EpisodeTimeoutMessage; m_simulator.EpisodeTimeout(i, etmsg.IsOur, etmsg.IsPass); } else { m_connectedClients[i].WriteString("(error)"); } } } } catch { } } }
public void SendMessage(IMessageInfo message) { AmazonSimpleNotificationServiceClient client = InitializeClient(); using (client) { } }
public void OnQueryPending(IMessageInfo info, IZone zone) { Adk.Log.Info (string.Format ("Requested {0} from zone: {1}", ((SifMessageInfo)info).SIFRequestObjectType.Name, zone.ZoneId)); }
public void SendMessage(IMessageInfo message) { MailMessage mailMessage = GetMailMessage(message); SmtpClient client = InitializeClient(); client.Send(mailMessage); }
/// <summary> /// Determines whether the specified <see cref="MessageInfoBase"/> is equal to the current. /// </summary> /// <param name="other"></param> /// <returns>bool</returns> public bool Equals(IMessageInfo other) { if (other == null) { return(false); } return(Id == other.Id && Category == other.Category && Description == other.Description && Comments == other.Comments && Data == other.Data); }
/// <summary> /// Creates the specified message info. /// </summary> /// <param name="messageInfo">The message info.</param> /// <param name="reinjectionTime">The reinjection time.</param> /// <returns></returns> public static ReinjectionMessage Create(IMessageInfo messageInfo, TimeSpan reinjectionTime) { return(new ReinjectionMessage { CreatedAt = DateTime.Now, MessageInfo = messageInfo, ReinjectionTime = reinjectionTime }); }
/// <summary> /// Creates the specified message info. /// </summary> /// <param name="messageInfo">The message info.</param> /// <param name="reinjectionTime">The reinjection time.</param> /// <returns></returns> public static ReinjectionMessage Create(IMessageInfo messageInfo, TimeSpan reinjectionTime) { return new ReinjectionMessage { CreatedAt = DateTime.Now, MessageInfo = messageInfo, ReinjectionTime = reinjectionTime }; }
public void OnQueryPending(IMessageInfo info, IZone zone) { Adk.Log.Info ( string.Format ("Requested {0} from {1}", ((SifMessageInfo)info).SIFRequestObjectType.Name, zone.ZoneId)); }
public void OnEvent(Event evnt, IZone zone, IMessageInfo info) { // Demonstrates basic handling of a SIF Event Console.WriteLine("Received a " + evnt.ActionString + " event for LearnerPersonal"); LearnerPersonal sp = (LearnerPersonal)evnt.Data.ReadDataObject(); // Simply write the XML of the event object to System.out Console.WriteLine(sp.ToXml()); Console.WriteLine("End Event"); }
public void SendMessage(IMessageInfo message) { AmazonSimpleEmailServiceClient client = InitializeClient(); using (client) { SendEmailRequest request = CreateSendRequest(message); client.SendEmail(request); } }
/// <summary> /// Deep copies content from src instance to this. /// <param name="source">Source for copy.</param> /// <returns>this.</returns> /// </summary> protected virtual IRecordInterface CopyFromImpl(IRecordInfo source) { if (typeof(IMessageInfo).IsInstanceOfType(source)) { IMessageInfo typedSource = (IMessageInfo)source; this.NanoTime = typedSource.NanoTime; this.Symbol = typedSource.Symbol; } return(this); }
private void PrepareRecipient(IMessageInfo messageInfo, MarketingMacrosHelper macrosHelper, EmailMessage emailMessage, Guid bulkEmailId) { var recipientInfo = messageInfo.Recipients.FirstOrDefault() as BulkEmailRecipientInfo; var emailAddress = new EmailAddress(recipientInfo.EmailAddress); emailMessage.InitRecipientVariable(); var merge = macrosHelper.GetRecipientMacros(recipientInfo.Id, recipientInfo.EmailAddress, bulkEmailId); emailMessage.merge_vars.Add(merge); emailMessage.to = new EmailAddress[] { emailAddress }; }
public void OnEvent( Event evnt, IZone zone, IMessageInfo info ) { // Demonstrates basic handling of a SIF Event Console.WriteLine( "Received a " + evnt.ActionString + " event for LearnerPersonal" ); StudentPersonal sp = (StudentPersonal) evnt.Data.ReadDataObject(); // Simply write the XML of the event object to System.out Console.WriteLine( sp.ToXml() ); Console.WriteLine( "End Event" ); }
protected ClientBase(string serverAddr, int serverPort, string teamname, int unum) { if (String.IsNullOrEmpty(teamname)) { throw new Exception("Invalid team name", null); } m_socket = new TcpClient(serverAddr, serverPort) { NoDelay = true }; Send(String.Format("(init {0} {1})", teamname, unum)); string msg = Read(); IMessageInfo mi = ServerMessageParser.ParseInputMessage(msg); if (mi.MessageType != MessageTypes.InitOK) { throw new Exception("expected init-ok but received " + mi.MessageType); } var okmi = mi as InitOKMessage; Debug.Assert(okmi != null); this.MySide = okmi.Side; this.MyTeamName = teamname; this.MyUnum = unum; msg = Read(); mi = ServerMessageParser.ParseInputMessage(msg); if (mi.MessageType != MessageTypes.Settings) { throw new Exception("expected settings but received " + mi.MessageType); } ParseSettings(((SettingsMessage)mi).SettingsMsgTokens); BallPosition = new Position(); LastSeePlayers = new int[2 * EnvMaxPlayers]; PlayerPositions = new Position[2 * EnvMaxPlayers]; for (int i = 0; i < PlayerPositions.Length; ++i) { PlayerPositions[i] = new Position(); } PlayerAvailabilities = new bool[2 * EnvMaxPlayers]; m_myIndex = GetPlayerIndex(MySide, MyUnum); m_goalUpperRow = CalculateGoalUpperRow(); m_goalLowerRow = CalculateGoalLowerRow(); }
/// <summary> /// ########## ######## # ######### Email ########. /// </summary> /// <param name="messageInfo">###### ### ######## ######</param> /// <returns>######### ########## ######## # ######### Email ########</returns> private int AddContactToBulkEmailAudience(IMessageInfo messageInfo) { var recipientInfo = messageInfo.Recipients.FirstOrDefault() as BulkEmailRecipientInfo; var insert = new Insert(_userConnection) .Into("MandrillRecipient") .Set("BulkEmailRId", Column.Parameter(messageInfo.MessageRId)) .Set("ContactRId", Column.Parameter(recipientInfo.ContactRId)) .Set("EmailAddress", Column.Parameter(recipientInfo.EmailAddress)) .Set("IsSent", Column.Const(true)) .Set("Timestamp", Column.Parameter(messageInfo.MailingStartTS)); return(insert.Execute()); }
/// <summary> /// Sends the specified message. /// </summary> /// <param name="message">The message.</param> /// <param name="messageInfo">The message info.</param> /// <returns></returns> public override int Send(byte[] message, IMessageInfo messageInfo) { try { SenderEndPoint.Send(message, messageInfo.Header.Priority); return(message.Length); } catch (Exception ex) { Logger.Fatal("Error Send Message", ex); return(0); } }
public void OnQueryPending(IMessageInfo info, IZone zone) { SifMessageInfo smi = (SifMessageInfo)info; fPendingRequestInfo = smi.SIFRequestInfo; // TODO: should we test error handling in the onQueryPending handler? //doBehavior( zone ); Assert.IsNotNull(fPendingRequestInfo, "RequestInfo should not be null in onQueryPending()"); if (RequestStateObject != null) { Assert.AreEqual(RequestStateObject, fPendingRequestInfo.UserData, "Custom State in onQueryPending()"); } }
public void PostMessage(IMessageInfo message) { var msg = MessageFactoryService.CreateMessage(message); _messagesById.Add(msg.Id, msg); // Post the message to each category it is tagged with foreach (var categoryId in msg.CategoryIds) { IList<long> msgIds; if (!_messageIdsByCategoryId.TryGetValue(categoryId, out msgIds)) msgIds = new List<long>(); msgIds.Add(msg.Id); } }
/// <summary> /// This method is called when a SIF Event is received by the Subscriber. /// </summary> /// <param name="evnt">SIF Event received.</param> /// <param name="zone">Zone that SIF Event was received.</param> /// <param name="info">Information on the received message.</param> void ISubscriber.OnEvent(Event evnt, IZone zone, IMessageInfo info) { // Although not generally the case, it is possible that more than 1 SIF Data Object is received with the // SIF Event. while (evnt.Data.Available) { T sifDataObject = (T)evnt.Data.ReadDataObject(); EventAction eventAction = evnt.Action; SifEvent <T> sifEvent = new SifEvent <T>(sifDataObject, eventAction); if (PreProcessEvent(sifEvent, zone)) { ProcessEvent(sifEvent, zone); } } }
public bool OnDispatchError(SifMessagePayload message, IZone zone, IMessageInfo info) { try { doBehavior(zone); } catch (SifException sifex) { throw sifex; } catch (AdkException adke) { throw new SifException(0, 0, "This shouldn't happen", zone, adke); } return(false); }
private string GetTemplate(BulkEmail bulkEmail, IMessageInfo messageInfo, List <image> messageImages, MarketingMacrosHelper macrosHelper) { string templateBodyWithMacros = macrosHelper.SetTemplateBody(bulkEmail.TemplateBody, bulkEmail.OwnerId, bulkEmail.Id, messageInfo.ApplicationUrl); string templateCode = InlineimagesProcessing(templateBodyWithMacros, messageImages, messageInfo.ApplicationUrl); if (string.IsNullOrEmpty(templateCode)) { return(string.Empty); } templateCode = UtmHelper.GetTemplateCodeWithUtmLabel(bulkEmail.ConvertToUtmData(templateCode), messageInfo.MessageRId, macrosHelper.UnsubscribeMacrosAliases); int templateSize = MandrillUtilities.GetTemplateSize(templateCode, messageImages); return(templateSize > MandrillMaxTemplateSize ? string.Empty : templateCode); }
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); } }
private static MailMessage GetMailMessage(IMessageInfo message) { MailMessage mailMessage = new MailMessage { Body = message.Body, From = new MailAddress(message.Sender), IsBodyHtml = true }; mailMessage.Sender = mailMessage.From; mailMessage.Subject = message.Title; foreach (string recipient in message.Recipients) { mailMessage.To.Add(new MailAddress(recipient)); } return(mailMessage); }
/// <summary> /// Sending of instant trigger message. /// </summary> /// <param name="messageInfo">Object that holds information about message.</param> public void Send(IMessageInfo messageInfo) { messageInfo.PrepareMessage(_userConnection); if (!messageInfo.Validate()) { return; } bool sendMessageResult = false; try { sendMessageResult = ExecuteSendMessage(messageInfo); } catch (Exception e) { Log.ErrorFormat("[Send]: {0} Error while sending message instant message with Id {1}", e, messageInfo.MessageId); } AddContactToBulkEmailAudience(messageInfo); UpdateBulkEmailData(messageInfo.MessageId, messageInfo.SendDate, !sendMessageResult); }
public void OnEvent(Event evnt, IZone zone, IMessageInfo info) { bool logToconsole = fAgent.getChameleonProperty(zone, "logConsole", false); SifMessageInfo smi = (SifMessageInfo)info; string debug = string.Format ("Received {0} Event from {1} in Zone: {2}", evnt.ActionString, smi.SourceId, zone.ZoneId); zone.ServerLog.Log (LogLevel.INFO, debug, null, "1003", LogEntryCodes.CATEGORY_SUCCESS, LogEntryCodes.CODE_SUCCESS, smi, null); Adk.Log.Info(debug); Log (fDir + Path.DirectorySeparatorChar + zone.ZoneId + Path.DirectorySeparatorChar + "Events\\" + evnt.ObjectType.Name + "\\" + evnt.ObjectType.Name + DateTime.Now.ToFileTime().ToString() + ".xml", evnt.Data, smi, logToconsole); }
public void OnMessageProcessed(SifMessageType messageType, IMessageInfo info) { string fileName = null; SifMessageInfo smi = (SifMessageInfo)info; if (messageType == SifMessageType.SIF_Response) { // Log Query responses in the standard OpenADK Message tracing format //N-ObjectType-ZoneID-SourceID-PacketNum|”error”.txt fileName = string.Format ("{0:00000}-{1}-{2}-{3}-{4}.txt", fResponseOrdinal++, smi.SIFRequestObjectType.Name, smi.Zone.ZoneId, smi.SourceId, smi.PacketNumber); } else if (messageType == SifMessageType.SIF_Event) { fileName = string.Format ("{0:00000}-{1}-{2}-{3}-SIF_Event.txt", fResponseOrdinal++, "ChangeThis", smi.Zone.ZoneId, smi.SourceId); } if (fileName != null) { try { FileInfo file = new FileInfo(fDir + "\\Raw\\" + fileName); file.Directory.Create(); using ( StreamWriter writer = new StreamWriter(file.FullName, true, Encoding.UTF8) ) { writer.Write(smi.Message); writer.Close(); } } catch (Exception ex) { Adk.Log.Warn(ex.Message, ex); } } }
public IMessageInfo CreateObject(string type) { IMessageInfo msg = null; switch (type) { case "sms": msg = new SMSClass(); break; case "mail": msg = new MailClass(); break; default: break; } return(msg); }
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"); } }
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.PersonInfo.Name; Console.WriteLine ( fObjectCount + ") Refid:{" + sp.RefId + "} Name: " + stuName.GivenName + " " + stuName.FamilyName ); } // 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" ); } }
private SendEmailRequest CreateSendRequest(IMessageInfo message) { SendEmailRequest request = new SendEmailRequest(); request.Destination = new Destination(message.Recipients); request.Message = new Message { Subject = new Content(message.Title) }; request.Message.Body = new Body(); request.Message.Body.Html = new Content(message.Body); request.ReplyToAddresses = new List <string>() { message.Sender }; request.Source = message.Sender; return(request); }
public void Handle(ResetPasswordCommand command) { UserInfo searchCriteria = new UserInfo(); searchCriteria.EmailAddress = command.EmailAddress; UserInfo userData = m_SearchRepository.Search(searchCriteria).FirstOrDefault(); if (userData == null) { throw new MissingMemberException(ErrorMessages.UserNotFoundByEmail); } userData.PasswordHash = GetUserPasswordHash(Guid.NewGuid().ToString(), userData.Id); m_UserRepository.Add(userData); //send email IMessageInfo message = GetResetPasswordMessage(userData, command.Source); m_Messager.SendMessage(message); }
/// <summary> /// Sends an instant message to the specified subscriber. /// </summary> /// <param name="messageInfo">The message info.</param> /// <param name="subscriber">The subscriber.</param> /// <returns>The result of the sending operation.</returns> public override SendResult SendMessage(IMessageInfo messageInfo, ISubscriberRequest subscriber) { throw new NotSupportedException("The SendGrid sender does not support sending a single email."); }
/// <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); } } } }
/// <summary> Wakes up the thread, dispatches the event to Subscriber.onEvent, /// then returns the appropriate SIF_Ack code. If onEvent() completes /// processing without invoking SMB, this method returns once onEvent() /// is finished. If, however, onEvent() invokes SMB by instantiating a /// TrackQueryResults object, this method returns at the time the /// TrackQueryResults constructor is called. /// </summary> internal virtual int dispatch(ISubscriber target, Event evnt, ZoneImpl zone, ITopic topic, IMessageInfo msgInfo) { _target = target; _event = evnt; _zone = zone; _topic = topic; _msgInfo = msgInfo; // TODO: Implement SMB //_smb = null; _state._ack = -1; _state._exception = null; this.Run(); return waitForAckCode(); }
public void OnMessageSent(SifMessageType messageType, IMessageInfo info, object receipt) { }
/// <summary> Respond to a SIF_Event received from a zone.</summary> /// <param name="evnt">The event data</param> /// <param name="zone">The zone from which this event originated</param> /// <param name="info">Information about the SIF_Event message</param> public void OnEvent( Event evnt, IZone zone, IMessageInfo info ) { throw new NotImplementedException(); }
public void OnQueryPending(IMessageInfo info, IZone zone) { SifMessageInfo smi = (SifMessageInfo)info; Console.WriteLine( "Sending SIF Request with MsgId " + smi.MsgId + " to zone " + zone.ZoneId ); }
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(); }
public void PostMessage(IMessageInfo message) { MessageService.PostMessage(message); }
//////////////////////////////////////////////////////////////////////////////// // // QueryResults interface // public void OnQueryPending( IMessageInfo info, IZone zone ) { // Not used by this agent. }
/// <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> 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(); } }
/// <summary> Called by the ADK when a SIF_Request is successfully sent to a zone /// </summary> public virtual void OnQueryPending( IMessageInfo info, IZone zone ) { // Nothing to do. }
public bool OnSendingMessage(SifMessageType messageType, IMessageInfo info, StringBuilder message) { return true; }
public void OnEvent(Event evnt, IZone zone, IMessageInfo info) { throw new Exception("The method or operation is not implemented."); }
public void Enqueue(IMessageInfo messageInfo, TimeSpan reinjectionTime) { }
public IMessage CreateMessage(IMessageInfo messageInfo) { return new Message(GetNextIndex(), messageInfo); }