protected override void CopyMessageField(BaseMessage msg) { CreateRoomMessage copymsg = (CreateRoomMessage)msg; this.Name = copymsg.Name; this.Password = copymsg.Password; this.Capability = copymsg.Capability; }
public void SendToPlayers(BaseMessage msg) { foreach(GamePlayer p in mPlayers) { p.DispatchMessage(msg); } }
public async Task<BaseMessage> Get(BaseMessage msg) { //await Task.Delay(2000); try { //DecryptData msg.MsgJson = DecryptData(msg.MsgJson); var para = msg.GetData<IDPara>(); ValidStoreIDQuery(new List<int>() { para.LocationStoreID }); var c1 = UGUser.Claims; var principal = User as ClaimsPrincipal; var obj = from c in principal.Identities.First().Claims select new { c.Type, c.Value }; return PackageDataWWithSecurity(msg, obj); } catch (BaseException ex) { return GetBaseMessage(ex); } catch (Exception ex) { return GetBaseMessage(new UnknownException(ex)); } }
public string HandleAndGetResponse(BaseMessage message) { string response = ""; TextMessage textMsg = message as TextMessage; string content = textMsg.Content.Trim(); if (string.IsNullOrEmpty(content)) { response = "您什么都没输入,没法帮您啊,%>_<%。"; } //else if (SessionUtility.Contains(textMsg.FromUserName)) //{ // response = AuthUtility.GetAuthResult(textMsg); //} else { if (content.Contains("图文")) { return GetTuwenResponse(textMsg); } response = HandleOtherString(content); } TextMessage tm = new TextMessage(); tm.ToUserName = message.FromUserName; tm.FromUserName = message.ToUserName; tm.CreateTime = WeiXinHelper.GetNowTime(); tm.Content = response; string returnValue = tm.GetResponseString(); return returnValue; }
public static void HandleExtensionMessage(BaseMessage message) { if (message == null || !(message is ExtensionMessage)) return; ExtensionMessage extMessage = (ExtensionMessage) message; string extensionType = null; if (extMessage.Properties.ContainsKey("ext_msg_subtype")) { extensionType = (string) extMessage.Properties["ext_msg_subtype"]; } else if (extMessage.Properties.ContainsKey("ext_msg_type")) { Debug.LogWarning("Extension message with 'ext_msg_type' is deprecated. Please use 'ext_msg_subtype'"); extensionType = (string) extMessage.Properties["ext_msg_type"]; } else { Debug.LogWarning("Received extension message without a subtype"); return; } Debug.Log("Got extension message with type: " + extensionType); if (extensionHandlers.ContainsKey(extensionType)) { extMessage.Properties["ext_msg_subject_oid"] = extMessage.Oid; extMessage.Properties["ext_msg_target_oid"] = extMessage.TargetOid; extMessage.Properties["ext_msg_client_targeted"] = extMessage.ClientTargeted; List<ExtensionMessageHandler> handlers = extensionHandlers[extensionType]; Debug.Log("Got " + handlers.Count + " handlers for extension message"); foreach (ExtensionMessageHandler handler in handlers) handler(extMessage.Properties); } }
protected override void CopyMessageField(BaseMessage msg) { GameTurnMessage copymsg = (GameTurnMessage)msg; this.UserId = copymsg.UserId; this.EndTime = copymsg.EndTime; this.Text = copymsg.Text; }
static void Stuff2() { MemoryStream ms = new MemoryStream(); BaseMessage bm = new BaseMessage(); bm.value = 1234; Serializer.Serialize( ms, bm ); Console.WriteLine( "Length is {0}", ms.Length ); }
private void OnDataReceived(BaseMessage message) { if (message is LoginMessage) { if (_processor.OnLoginResponse != null) _processor.OnLoginResponse(message.Code, true); } }
public static Message Serialize(Type messageType, BaseMessage message) { if (WebOperationContext.Current != null) { var serializer = new DataContractJsonSerializer(messageType); return WebOperationContext.Current.CreateJsonResponse(message, serializer); } return null; }
public void PushMessage(BaseMessage message) { using (IConnection connection = _factory.CreateConnection()) using (IModel channel = connection.CreateModel()) { channel.ExchangeDeclare("attika_exchange", ExchangeType.Fanout); channel.BasicPublish("attika_exchange", "", null, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message))); } }
//private static readonly SoapFormatter _formatter = new SoapFormatter(); public static byte[] Serialize(BaseMessage msg) { MemoryStream memoryStream = new MemoryStream(); _formatter.Serialize(memoryStream, msg); byte[] serializedObj = memoryStream.ToArray(); //Console.WriteLine(Encoding.ASCII.GetString(serializedObj)); return serializedObj; }
public byte[] Encode(BaseMessage message) { var bytes = message.GetBytes(); var sendBytes = new byte[BaseMessage.HeaderLength + bytes.Length]; Array.Copy(BitConverter.GetBytes(bytes.Length), sendBytes, sizeof(int)); Array.Copy(bytes, 0, sendBytes, BaseMessage.HeaderLength, bytes.Length); return sendBytes; }
static void Stuff() { MemoryStream ms = new MemoryStream(); DerivedMessage dm = new DerivedMessage(); BaseMessage[] bma = new BaseMessage[1]; bma [0] = dm; //Protocol.RegisteredGameServer rs = new Protocol.RegisteredGameServer(); dm.value = 1234; Serializer.Serialize<BaseMessage[]>( ms, bma ); //Serializer.Serialize<BaseMessage>( ms, (BaseMessage)dm ); Console.WriteLine( "Length is {0}", ms.Length ); }
private void ReceiveMessage(BaseMessage message) { if(message.GetType() == typeof(LoginMessage)) { var loginMessage = message as LoginMessage; Console.WriteLine("Received LoginMessage(Username = {0})", loginMessage.UserName); if (OnLoginSuccess != null) OnLoginSuccess(loginMessage.UserName, _socket); _isAuthenticated = true; } }
private async void btnApiAccess_Click(object sender, EventArgs e) { var claim = await GetClaimsAsync(UserAccessInfo.AccessToken); var query = from info in claim where info.Item1 == UGConstants.ClaimTypes.PreferredUserName select info.Item2; string userName = string.Empty; if (query.Count() > 0) userName = query.First(); var client = new HttpClient(); client.SetBearerToken(UserAccessInfo.AccessToken); client.DefaultRequestHeaders.Add(UGConstants.HTTPHeaders.IOT_CLIENT_ID, IoTClientId); client.DefaultRequestHeaders.Add(UGConstants.HTTPHeaders.IOT_CLIENT_SECRET, IoTClientSecret); client.DefaultRequestHeaders.Add(UGConstants.ClaimTypes.PreferredUserName, userName); BaseMessage msg = new BaseMessage("", "", SSD.Framework.Exceptions.ErrorCode.IsSuccess, ""); msg.MsgJson = "{\"LocationStoreID\":1,\"ID\":1}"; StringContent queryString = new StringContent(msg.ToJson()); var response = await client.PostAsync(APIUri,queryString); if (response.IsSuccessStatusCode) { string contentStr = string.Empty; IEnumerable<string> lst; if (response.Content.Headers != null && response.Content.Headers.TryGetValues(UGConstants.HTTPHeaders.CONTENT_ENCODING, out lst) && lst.First().ToLower() == "deflate") { var bj = await response.Content.ReadAsByteArrayAsync(); using (var inStream = new MemoryStream(bj)) { using (var bigStreamsss = new DeflateStream(inStream, CompressionMode.Decompress, true)) { contentStr = await (new StreamReader(bigStreamsss)).ReadToEndAsync(); //using (var bigStreamOut = new MemoryStream()) //{ // bigStreamsss.CopyTo(bigStreamOut); // contentStr = Encoding.UTF8.GetString(bigStreamOut.ToArray(), 0, bigStreamOut.ToArray().Length); //} } } } else contentStr = await response.Content.ReadAsStringAsync(); MessageBox.Show(contentStr); } }
public async Task Send(BaseMessage msg) { var data = (WeChatMessage)msg; var api = ApiClient.GetInstance("xxy"); //接口限制: 用户不先在WX上发起对话,就没办法使用该功能! //{"errcode":45015,"errmsg":"response out of time limit or subscription is canceled hint: [h6kfKa0794age8]"} var method = new MessageSend() { OpenID = data.Receiver, Message = new TextMessage() { Content = data.Ctx } }; var result = await api.Execute(method); if (this.OnProcessed != null) { var ex = result.HasError ? new Exception(result.ErrorInfo) : null; this.OnProcessed(this, new ProcessedArgs(DbEntity.Enums.MsgTypes.WeChat, data.ID, ex)); } }
protected HttpResponseMessage InternalCheckPermission(string userName, IoTUserManagerBase iotMrg, HttpRequestMessage request, IEnumerable<UGFollowPermissionAttribute> lstAttAjaxAcction) { var user = iotMrg.GetUserCache(userName); UGFollowPermissionAttribute att = lstAttAjaxAcction.First() as UGFollowPermissionAttribute; if (!user.HasPermission(att.FollowKey)) { string keyName = string.Empty; var per = iotMrg.Permissions.Where(x => x.AcctionKey == att.FollowKey); if (per.Count() > 0) keyName = per.First().Description; //redirect to Accecc Diney string error = string.Format(UGConstants.Security.MsgValidAcctionPermission, keyName, att.FollowKey); var resultMsg = new BaseMessage("", "", SSD.Framework.Exceptions.ErrorCode.ActionPermission, error); HttpResponseMessage reply = request.CreateResponse<BaseMessage>(HttpStatusCode.OK, resultMsg); return reply; } return null; }
protected override HttpResponseMessage CheckPermission(HttpActionContext actionContext, IEnumerable<UGFollowPermissionAttribute> lstAttAjaxAcction) { var request = actionContext.Request; object obj; if (request.Properties.TryGetValue(UGConstants.HTTPHeaders.TOKEN_NAME, out obj)) { var token = obj as UGToken; if (token != null) { string userName = token.UID; return InternalCheckPermission(userName, IoTUserManager, request, lstAttAjaxAcction); } } //redirect to Accecc Diney var resultMsg = new BaseMessage("", "", SSD.Framework.Exceptions.ErrorCode.ActionPermission, UGConstants.Security.MsgMissingUGToken); HttpResponseMessage reply = request.CreateResponse<BaseMessage>(HttpStatusCode.OK, resultMsg); return reply; }
protected override HttpResponseMessage CheckPermission(HttpActionContext actionContext, IEnumerable<UGFollowPermissionAttribute> lstAttAjaxAcction) { var request = actionContext.Request; if(HttpContext.Current.User.Identity.IsAuthenticated) { //string userName = HttpContext.Current.User.GetUserName(); var headerUsername = request.Headers.GetValues(UGConstants.ClaimTypes.PreferredUserName); if (headerUsername != null && headerUsername.Count() > 0) { return InternalCheckPermission(headerUsername.First(), IoTUserManager, request, lstAttAjaxAcction); } else { var resultMsgUserName = new BaseMessage("", "", SSD.Framework.Exceptions.ErrorCode.ActionPermission, UGConstants.Security.MsgMissingUserName); HttpResponseMessage replyUserName = request.CreateResponse<BaseMessage>(HttpStatusCode.OK, resultMsgUserName); return replyUserName; } } //redirect to Accecc Diney var resultMsg = new BaseMessage("", "", SSD.Framework.Exceptions.ErrorCode.ActionPermission, UGConstants.Security.MsgValidLogin); HttpResponseMessage reply = request.CreateResponse<BaseMessage>(HttpStatusCode.OK, resultMsg); return reply; }
public RequestReponse GetXMLDocs([FromUri] string type) { RequestReponse result = new RequestReponse(); try { // XML document result will be passed in here as a string string messageDetail = string.Empty; string centralDBURL = ConfigurationManager.ConnectionStrings["LandseaDB"].ToString(); if (!LoadSettings()) { result.Success = false; result.Message = "Get XML Documents failed!"; result.MessageDetail = "Failed to read configuration settings."; return(result); } if (string.IsNullOrEmpty(type)) { result.Success = false; result.Message = "Get XML Documents failed!"; result.MessageDetail = "Document Type is missing."; return(result); } if (!GenerateBIPToken()) { result.Success = false; result.Message = "Get XML Documents failed!"; result.MessageDetail = "Internal security token generation failed"; return(result); } ProcessLogs.bipToken = bipToken; ProcessLogs.logFilePath = logFilePath; ProcessLogs.webApiUrl = bipAPIURL; #region Get CargoWise XML Documents using (SqlConnection conn = new SqlConnection(centralDBURL)) { if (conn.State != ConnectionState.Closed) { conn.Close(); } conn.Open(); try { using (SqlCommand sqlCommand = new SqlCommand("CargoWiseFileProcess", conn)) { sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.AddWithValue("@XMLType", type); SqlDataAdapter sda = new SqlDataAdapter(sqlCommand); DataTable dtResult = new DataTable(); sda.Fill(dtResult); conn.Close(); if (dtResult.Rows.Count > 0) { int messageID = int.Parse(dtResult.Rows[0]["MessageID"].ToString()); string xmlDoc = dtResult.Rows[0]["Message"].ToString(); var resultData = "{ \"MessageID\": " + messageID.ToString() + ", \"Message\": \"" + xmlDoc + "\" }"; // If successful result.Data = resultData; result.Success = true; result.Message = "Document successfully retrieved."; result.MessageDetail = "New CargoWise document was successfully retrieved."; ProcessLogs.UpdateProfileHistory(string.Join(" - ", result.Message, result.MessageDetail), BIP.Enum.EventLogType.Information, GetXMLDocsProfileID); } else { result.Success = true; result.Message = "No documents available."; result.MessageDetail = "No new CargoWise XML documents available at this moment. Please try again later."; ProcessLogs.UpdateProfileHistory(string.Join(" - ", result.Message, result.MessageDetail), BIP.Enum.EventLogType.Warning, GetXMLDocsProfileID); } } #region BIP Message //we need to create a new message in BIP BaseMessage bmessage = new BaseMessage(); List <MessageHistoryModel> newHistory = new List <MessageHistoryModel>(); using (DataSet ds = new DataSet("XMLDocs")) { using (DataTable dt = new DataTable("XMLDocsGet")) { dt.Columns.Add("RequestedType", typeof(string)); dt.Columns.Add("ResultMsg", typeof(string)); dt.Columns.Add("ResultData", typeof(string)); dt.Columns.Add("ResultDetailMsg", typeof(string)); dt.AcceptChanges(); DataRow dr = dt.NewRow(); dr["RequestedType"] = type; dr["ResultMsg"] = result.Message; dr["ResultData"] = result.Data; dr["ResultDetailMsg"] = result.MessageDetail; dt.Rows.Add(dr); dt.AcceptChanges(); ds.Tables.Add(dt); ds.AcceptChanges(); using (TextWriter write = new StringWriter()) { //convert the results into xml ds.WriteXml(write); //also convert the xml into byte arry bmessage.Context = new byte[write.ToString().Length *sizeof(char)]; System.Buffer.BlockCopy(write.ToString().ToCharArray(), 0, bmessage.Context, 0, bmessage.Context.Length); } } } if (result.Success) { bmessage.PublishMessageID = (int)InternalStatus.Processing; bmessage.MessageStatus = InternalStatus.Processing; newHistory.Add(new MessageHistoryModel { EventDesc = "Request received from LandSea XML API Service - Get XML Documents", ProfileProcessID = GetXMLDocsProfileID, EventTypeID = (byte)EventLogType.Information, MessageStatusID = 1, DoneBy = "LandSea API Service" }); } else { bmessage.PublishMessageID = (int)InternalStatus.Suspended; bmessage.MessageStatus = InternalStatus.Suspended; newHistory.Add(new MessageHistoryModel { EventDesc = result.Message + " Detail: " + result.MessageDetail, ProfileProcessID = GetXMLDocsProfileID, EventTypeID = (byte)EventLogType.Error, MessageStatusID = 2, DoneBy = "LandSea API Service" }); } bmessage.PromoteValue("SentType", type); bmessage.webApiUrl = bipAPIURL; bmessage.bipToken = bipToken; bmessage.AttachmentID = 0; bmessage.XMLContext = string.Empty; bmessage.ProfileID = GetXMLDocsProfileID; bmessage.CreatedBy = "LandSea XML API Service"; bmessage.ReProcessed = false; bmessage.PublishMessageID = null; bmessage.ProfileProcessID = GetXMLDocsProfileID; bool saveResult = true; using (UpdateMessage sMessage = new BIP.MessageUtils.UpdateMessage()) { saveResult = sMessage.SaveMessageDetail(bmessage, newHistory, BIP.Enum.MessageType.Incomming, ref messageDetail); } if (!saveResult) { result.Success = false; result.Message = "Failed to Update BIP process"; result.MessageDetail = messageDetail; } #endregion BIP Message } catch (Exception ex) { result.Success = false; result.Message = ex.Message; result.MessageDetail = ExceptionDetail.GetExceptionFullMessage(ex); ProcessLogs.UpdateProfileHistory(result.Message, BIP.Enum.EventLogType.Error, GetXMLDocsProfileID); } finally { conn.Close(); } } #endregion Get CargoWise XML Documents } catch (Exception ex) { result.Success = false; result.Message = ex.Message; result.MessageDetail = ExceptionDetail.GetExceptionFullMessage(ex); ProcessLogs.UpdateProfileHistory(result.Message, BIP.Enum.EventLogType.Error, GetXMLDocsProfileID); } return(result); }
bool LocalisationHandler(BaseMessage message) { SetLanguage(LocaliseText.Language); return(true); }
public async Task <CompanyRegisterResponse> CreateAsyncCompany(CompanyRegisterRequest companyRegister) { string passwordvalue = passwordGeneratorFactory.Create().GeneratePassword(); Random randomNumber = new Random(); int r = randomNumber.Next(100000, 1000000); List <MessageContent> messageContent = new List <MessageContent>(); bool IsValidEmail = messageSenderFactory.IsValid(companyRegister.CompanyRegister.Email); var user = new UserRegister { RegType = "company", UserName = companyRegister.CompanyRegister.Email, Email = IsValidEmail == true ? companyRegister.CompanyRegister.Email : null, PhoneNumber = IsValidEmail == false ? companyRegister.CompanyRegister.Email : null, PasswordHash = passwordvalue, CompanyInformation = new CompanyInformation { AddresseeName = companyRegister.CompanyRegister.AddresseeName, Email = companyRegister.CompanyRegister.Email, EconomicCode = companyRegister.CompanyRegister.EconomicCode, NationalId = companyRegister.CompanyRegister.NationalId, VerifyCode = r.ToString() } }; try { List <string> messages = new List <string>(); var result = await userManager.CreateAsync(user, passwordvalue); if (result.Succeeded) { if (IsValidEmail) { string ctoken = await userManager.GenerateEmailConfirmationTokenAsync(user); var request = httpcontextaccessor.HttpContext.Request; var queryparams = new Dictionary <string, string> { { "accepted", ctoken }, { "userId", user.UserName } }; var querystring = QueryHelpers.AddQueryString("https://localhost:44326/api/UserAuth/comfirmedEmail", queryparams); messages.Add($" {user.CompanyInformation.AddresseeName} Company <br>Please confirm your account by<br>your password:{passwordvalue}<br><br> <a href = '{HtmlEncoder.Default.Encode(querystring)}'> clicking here </a>."); BaseMessage baseMessage = new BaseMessage { Email = user.Email, Subject = "pleaseComfirmAccount", Messages = messages }; var data = messageSenderFactory.CreateMessage(baseMessage); messageContent.Add(new MessageContent { Message = data.Message, Code = null }); return(new CompanyRegisterResponse { ReturnObject = mapper.Map <CompanyRegisterViewModel>(user.CompanyInformation), responseMessage = messageContent, Success = true }); } } messageContent.AddRange(result.Errors.Select(a => new MessageContent { Code = a.Code, Message = a.Description })); //var registerResponse = requestResponseFactory.ProcessRequest<RegisterRequest, RegisterResponse>(userRegisterView); return(new CompanyRegisterResponse { ReturnObject = mapper.Map <CompanyRegisterViewModel>(user.CompanyInformation), responseMessage = messageContent, Success = result.Succeeded }); } catch (Exception ex) { return(new CompanyRegisterResponse { responseMessage = new List <MessageContent> { new MessageContent { Message = ex.Message, Code = null } } }); } }
bool AppRateHandler(BaseMessage message) { appRated = true; return(true); }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn protected virtual void AfterSendOperation(BaseMessage message) /// /// \brief After send operation. /// /// \par Description. /// This method is used for algorithm specific actions after a send of a message /// /// \par Algorithm. /// /// \par Usage Notes. /// /// \author Ilanh /// \date 05/04/2017 /// /// \param message (BaseMessage) - The message. //////////////////////////////////////////////////////////////////////////////////////////////////// protected override void AfterSendOperation(BaseMessage message) { }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn protected override BaseMessage BuildBaseAlgorithmMessage(dynamic messageType, string messageName, AttributeDictionary messageFields, int round, AttributeList targets) /// /// \brief Builds base message. /// /// \par Description. /// - This method is called in execution time. /// - The purpose of this method is to allow the algorithm to add fields to the Base Algorithm message /// - The following is the process of sending a base algorithm message /// -# During running time before/after a send/receive message the event is checked /// -# If the conditions are filled up this method is called with the base message data /// -# This message can add fields to the Base Message according to the status of the algorithm /// -# The base message is sent /// /// \par Algorithm. /// /// \par Usage Notes. /// /// \author Ilan Hindy /// \date 02/03/2017 /// /// \param messageType (dynamic) - Type of the message. /// \param messageName (string) - Name of the message. /// \param messageFields (AttributeDictionary) - The message fields. /// \param round (int) - The round. /// \param targets (List<Attribute>) - The targets. /// /// \return A BaseMessage. //////////////////////////////////////////////////////////////////////////////////////////////////// public override BaseMessage BuildBaseAlgorithmMessage(dynamic messageType, string messageName, AttributeDictionary messageFields, int round, AttributeList targets) { BaseMessage message = new BaseMessage(network, messageType, messageFields, new BaseChannel(), messageName, round); return(message); }
protected override void CopyMessageField(BaseMessage msg) { ServerInfoAbonentsMessage copymsg = (ServerInfoAbonentsMessage)msg; this.Abonents = copymsg.Abonents; }
public ModbusInverter(string tcpcontent, BaseMessage message) { base.deviceData = tcpcontent; this.analysis(); }
public Modbus16Cabinet(string tcpcontent, BaseMessage message) { base.deviceData = tcpcontent; this.analysis(); }
public override void ServerProcessMessage(BaseMessage message, ServerSharedStateObject sharedStateObj) { throw new NotImplementedException(); }
public override void ClientProcessMessage(BaseMessage message, ClientSharedStateObject sharedStateObj) { //sharedStateObj.ClientID = message.c message.ClientProcessMessage(sharedStateObj); }
public SystemMessage(String senderUserId, String[] targetId, String objectName, BaseMessage content, String pushContent, String pushData, int isPersisted, int isCounted, int contentAvailable) : base(senderUserId, targetId, objectName, content, pushContent, pushData) { this.isPersisted = isPersisted; this.isCounted = isCounted; this.contentAvailable = contentAvailable; }
public BaseMessage GetProfile(UserAuthen user) { if (user == null) throw new HttpResponseException(new HttpResponseMessage() { StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent("Please provide the credentials.") }); var userDb = IoTUserMrg.GetUserCache(user.UserName); if (userDb != null) { //Get data attach (List<int> storesId) - List store by User var lst = new List<int>() { 1 }; Profile p = new Profile(); p.Stores = lst; string profile = p.SerializeJson(); //Update profile IoTUserMrg.UpdateProfile(user.UserName, profile); BaseMessage msg = new BaseMessage("","",Framework.Exceptions.ErrorCode.IsSuccess,""); msg.SetData(profile); return msg; } else { throw new HttpResponseException(new HttpResponseMessage() { StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent("Invalid user name or password.") }); } }
/// <inheritdoc /> public string Deserialize(BaseMessage message) { return(((TextMessage)message).Body); }
public override void HandleMessage(BaseMessage message) { MasterLog.DebugWriteLine("It worked!"); }
public GrpcContext(BaseMessage message, ServerCallContext callContext) { Message = message ?? throw new ArgumentNullException("The message cannot be null!"); CallContext = callContext ?? throw new ArgumentNullException("The message call context cannot be null!"); Id = Guid.NewGuid(); }
public ResponseRSTS(BaseMessage req) : base(req) { }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn public override bool MessageProcessingCondition(BaseMessage message) /// /// \brief Decide whether to process the first message in the message queue /// /// \par Description. /// This method is activated before retrieving a message from the message queue /// It gives a chance stole the processing of the first message until a condition is fulfilled /// /// \par Algorithm. /// /// \par Usage Notes. /// /// \author Ilan Hindy /// \date 26/01/2017 /// /// \param destProcessId Identifier for the destination process. /// \param message The message. //////////////////////////////////////////////////////////////////////////////////////////////////// public override bool MessageProcessingCondition(BaseMessage message) { return(base.MessageProcessingCondition(message)); }
static void ProcessXMLFile(string path) { FileInfo fi = new FileInfo(path); bool isManipulator = true; bool isResponse = false; bool isEoE = false; bool isEvent = false; if (fi.Exists) { var configPath = fi.FullName.Substring(Environment.CurrentDirectory.Length); var folders = configPath.Split('\\'); if (folders[2].Equals("Manipulator")) { isManipulator = true; } else if (folders[2].Equals("PreAligner")) { isManipulator = false; } if (folders[3].Equals("Response")) { isResponse = true; } else if (folders[3].Equals("EndOfExecution")) { isEoE = true; } BaseResponse reply = null; var reqType = BaseMessage.GetType(isManipulator ? 1 : 2, isResponse? fi.Name.Substring(8, 4): fi.Name.Substring(9, 4), isResponse? CommandType.ReplyResponse: CommandType.ReplyEoE); reply = (BaseResponse)Activator.CreateInstance(reqType, new object[] { null }); if (reply != null) { XmlDocument replyDoc = new XmlDocument(); replyDoc.Load(fi.FullName); var replyDict = reply.ReadXML(replyDoc); if (isManipulator) { if (isResponse) { ManipulatorResponses.Remove(fi.Name.Substring(8, 4)); ManipulatorResponses.Add(fi.Name.Substring(8, 4), replyDict); } else { ManipulatorEoEs.Remove(fi.Name.Substring(9, 4)); ManipulatorEoEs.Add(fi.Name.Substring(9, 4), replyDict); } } else { if (isResponse) { PreAlignerResponses.Remove(fi.Name.Substring(8, 4)); PreAlignerResponses.Add(fi.Name.Substring(8, 4), replyDict); } else { PreAlignerEoEs.Remove(fi.Name.Substring(9, 4)); PreAlignerEoEs.Add(fi.Name.Substring(9, 4), replyDict); } } } } }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn protected virtual void BeforeSendOperation(BaseMessage message) /// /// \brief Before send operation. /// /// \par Description. /// This method is used for algorithm specific actions before a send of a message /// /// \par Algorithm. /// /// \par Usage Notes. /// /// \author Ilanh /// \date 05/04/2017 /// /// \param message (BaseMessage) - The message. //////////////////////////////////////////////////////////////////////////////////////////////////// protected override void BeforeSendOperation(BaseMessage message) { }
public ResponseNews(BaseMessage info) : this() { this.FromUserName = info.ToUserName; this.ToUserName = info.FromUserName; }
/// <summary> /// Convert a BaseMessage subclass into a FIX text message. /// </summary> public string ConvertFixObjectToFixMessage(BaseMessage message) { var fixFields = new Dictionary<string, string>() { { SENDERCOMPID_FIELD, message.SenderCompID }, { TARGETCOMPID_FIELD, message.TargetCompID }, { MSGSEQNUM_FIELD, message.MessageSequenceNumber.ToString() } }; if (message is LogonMessage) { var msg = (LogonMessage)message; fixFields[MESSAGETYPE_FIELD] = LOGON_MESSAGE; fixFields[HEARTBTINT_FIELD] = Convert.ToString((int)msg.HeartBeatInterval.TotalSeconds); } else if (message is HeartbeatMessage) { var msg = (HeartbeatMessage)message; fixFields[MESSAGETYPE_FIELD] = HEARTBEAT_MESSAGE; } else if (message is LogoutMessage) { fixFields[MESSAGETYPE_FIELD] = LOGOUT_MESSAGE; } else if (message is QuoteMessage) { var msg = (QuoteMessage)message; fixFields[MESSAGETYPE_FIELD] = QUOTE_MESSAGE; fixFields[QUOTEREQID_FIELD] = msg.QuoteReqID; fixFields[QUOTEID_FIELD] = msg.QuoteID; fixFields[SYMBOL_FIELD] = msg.Symbol; fixFields[OFFERPX_FIELD] = string.Format("{0:0.0000}", msg.OfferPx); } else if (message is TestRequestMessage) { var msg = (TestRequestMessage)message; fixFields[MESSAGETYPE_FIELD] = TESTREQUEST_MESSAGE; fixFields[TESTREQID_FIELD] = msg.TestReqID; } else { throw new ArgumentException("Unable to convert " + message.GetType().ToString() + " to FIX message."); } return CreateFixMessageFromDictionary(fixFields); }
protected override void CopyMessageField(BaseMessage msg) { AuthorizationMessage copymsg = (AuthorizationMessage)msg; this.Login = copymsg.Login; this.Password = copymsg.Password; }
private void OnServerMessage(NamedPipeConnection <BaseMessage, BaseMessage> connection, BaseMessage message) { // This is so gross, but unfortuantely we can't just switch on a type. // We can come up with a nice mapping system so we can do a switch, // but this can wait. if (Default.m_ipcQueue.HandleMessage(message)) { return; } if (m_ipcQueue.HandleMessage(message)) { return; } m_logger.Debug("Got IPC message from server."); var msgRealType = message.GetType(); if (msgRealType == typeof(AuthenticationMessage)) { AuthMessage = (AuthenticationMessage)message; m_logger.Debug("Server message is {0}", nameof(AuthenticationMessage)); var cast = (AuthenticationMessage)message; if (cast != null) { AuthenticationResultReceived?.Invoke(cast); } } else if (msgRealType == typeof(Messages.DeactivationMessage)) { m_logger.Debug("Server message is {0}", nameof(Messages.DeactivationMessage)); var cast = (Messages.DeactivationMessage)message; if (cast != null) { DeactivationResultReceived?.Invoke(cast.Command); } } else if (msgRealType == typeof(Messages.FilterStatusMessage)) { m_logger.Debug("Server message is {0}", nameof(Messages.FilterStatusMessage)); var cast = (Messages.FilterStatusMessage)message; if (cast != null) { StateChanged?.Invoke(new StateChangeEventArgs(cast)); } } else if (msgRealType == typeof(Messages.NotifyBlockActionMessage)) { m_logger.Debug("Server message is {0}", nameof(Messages.NotifyBlockActionMessage)); var cast = (Messages.NotifyBlockActionMessage)message; if (cast != null) { BlockActionReceived?.Invoke(cast); } } else if (msgRealType == typeof(Messages.RelaxedPolicyMessage)) { m_logger.Debug("Server message is {0}", nameof(Messages.RelaxedPolicyMessage)); var cast = (Messages.RelaxedPolicyMessage)message; if (cast != null) { switch (cast.Command) { case RelaxedPolicyCommand.Info: { RelaxedPolicyInfoReceived?.Invoke(cast); } break; case RelaxedPolicyCommand.Expired: { RelaxedPolicyExpired?.Invoke(); } break; } } } else if (msgRealType == typeof(Messages.ClientToClientMessage)) { m_logger.Debug("Server message is {0}", nameof(Messages.ClientToClientMessage)); var cast = (Messages.ClientToClientMessage)message; if (cast != null) { ClientToClientCommandReceived?.Invoke(cast); } } else if (msgRealType == typeof(Messages.ServerUpdateQueryMessage)) { m_logger.Debug("Server message is {0}", nameof(Messages.ServerUpdateQueryMessage)); var cast = (Messages.ServerUpdateQueryMessage)message; if (cast != null) { ServerAppUpdateRequestReceived?.Invoke(cast); } } else if (msgRealType == typeof(Messages.ServerUpdateNotificationMessage)) { m_logger.Debug("Server message is {0}", nameof(Messages.ServerUpdateNotificationMessage)); var cast = (Messages.ServerUpdateNotificationMessage)message; if (cast != null) { ServerUpdateStarting?.Invoke(); } } else if (msgRealType == typeof(Messages.CaptivePortalDetectionMessage)) { m_logger.Debug("Server message is {0}", nameof(Messages.CaptivePortalDetectionMessage)); var cast = (Messages.CaptivePortalDetectionMessage)message; if (cast != null) { CaptivePortalDetectionReceived?.Invoke(cast); } } else if (msgRealType == typeof(Messages.CertificateExemptionMessage)) { m_logger.Debug("Server message is {0}", nameof(Messages.CertificateExemptionMessage)); var cast = (Messages.CertificateExemptionMessage)message; if (cast != null) { AddCertificateExemptionRequest?.Invoke(cast); } } else if (msgRealType == typeof(Messages.DiagnosticsInfoMessage)) { m_logger.Debug("Server message is {0}", nameof(Messages.DiagnosticsInfoMessage)); var cast = (Messages.DiagnosticsInfoMessage)message; if (cast != null) { OnDiagnosticsInfo?.Invoke(cast); } } else { // Unknown type. m_logger.Info("Unknown type is {0}", msgRealType.Name); } }
protected override bool GetProcessedMessage(BaseMessage message) { WasProcessed = true; return(true); }
bool UserLogoutHandler(BaseMessage message) { Logout(); return(true); }
protected override Task <bool> GetProcessedMessageAsync(BaseMessage message) { WasProcessed = true; return(Task.FromResult(true)); }
public void Initialize(string userId, long lastActivity = 0) { try { _LastActivity = lastActivity; // we can only initialize if the user is registered if (string.IsNullOrEmpty(userId)) { return; } _UserId = userId; _Group = string.Format(CH_GROUP, _UserId); LobbyChannel = new Channel { Id = string.Format(CH_LOBBY, userId), Name = "Lobby" }; PNConfiguration config = new PNConfiguration(); config.PublishKey = _PublishKey; config.SubscribeKey = _SubscribeKey; config.Uuid = _UserId; config.Secure = true; _Pubnub = new Pubnub(config); SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt((pubnubObj, message) => { try { // get the message base to determine type BaseMessage m = Serializer.Deserialize <BaseMessage>(message.Message.ToString()); // deserialize to actual type m = (BaseMessage)Serializer.Deserialize(GetType().Assembly.GetType(m.Type), message.Message.ToString()); m.ChannelId = message.Channel; // let listeners know MessageReceived?.Invoke(this, new MessageEventArgs <BaseMessage>(m)); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(string.Format("*** ChatService.MessageReceived - Unable to deserialize message: {0}", message.Message.ToString())); } }, (pubnubObj, presence) => { // handle incoming presence data if (presence.Event.Equals("join")) { RaiseChannelJoined(presence.Channel, presence.Uuid); } else if (presence.Event.Equals("leave")) { RaiseChannelLeft(presence.Channel, presence.Uuid); } else if (presence.Event.Equals("state-change")) { // listen for status events - eg: typing, etc if ((presence.State == null) || (presence.State.Count == 0)) { return; } foreach (var key in presence.State.Keys) { var state = (ChatState)Enum.Parse(typeof(ChatState), presence.State[key].ToString()); RaiseChannelState(presence.Channel, presence.Uuid, state); } } else if (presence.Event.Equals("timeout")) { } else if (presence.Event.Equals("interval")) { // find the ids that have joined if ((presence.Join != null) && (presence.Join.Length > 0)) { foreach (var uuid in presence.Join) { RaiseChannelJoined(presence.Channel, uuid); } } if ((presence.Leave != null) && (presence.Leave.Length > 0)) { foreach (var uuid in presence.Leave) { RaiseChannelJoined(presence.Channel, uuid); } } } else if (presence.HereNowRefresh) { // TODO: request state for channels //GetState(); } }, (pubnubObj, status) => { if (status.Operation == PNOperationType.PNHeartbeatOperation) { Connected = !status.Error; ConnectedChanged?.Invoke(this, new EventArgs()); } else if ((status.Operation != PNOperationType.PNSubscribeOperation) && (status.Operation != PNOperationType.PNUnsubscribeOperation)) { return; } if (status.Category == PNStatusCategory.PNConnectedCategory) { // this is expected for a subscribe, this means there is no error or issue whatsoever } else if (status.Category == PNStatusCategory.PNReconnectedCategory) { // this usually occurs if subscribe temporarily fails but reconnects. This means // there was an error but there is no longer any issue } else if (status.Category == PNStatusCategory.PNDisconnectedCategory) { // this is the expected category for an unsubscribe. This means there // was no error in unsubscribing from everything } else if (status.Category == PNStatusCategory.PNUnexpectedDisconnectCategory) { // this is usually an issue with the internet connection, this is an error, handle appropriately } else if (status.Category == PNStatusCategory.PNAccessDeniedCategory) { // this means that PAM does allow this client to subscribe to this // channel and channel group configuration. This is another explicit error } }); _Pubnub.AddListener(listenerSubscribeCallack); // create and subscribe to the lobby channel _Pubnub .Subscribe <string>() .Channels(new string[] { LobbyChannel.Id }) .WithPresence() .Execute(); // now we subscribe to the group //_Pubnub.Subscribe<string>() // .ChannelGroups(new string[] { _Group }) // .WithPresence() // .Execute(); Initialized = true; InitializedChanged?.Invoke(this, new EventArgs()); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(string.Format("*** ChatService.Initialize - Exception: {0}", ex)); } }
protected override void CopyMessageField(BaseMessage msg) { ServerInfoRoomsMessage copymsg = (ServerInfoRoomsMessage)msg; this.Rooms = copymsg.Rooms; }
public override void HandleTypedMessage(BaseMessage msg) { this.HandleTypedMessageCore((dynamic)msg); }
public Task Send(BaseMessage msg) { throw new NotImplementedException(); }
public void ParsePublicRsp(BaseMessage bm) { short temp = bm.Seq; }
private void HandleTypedMessageCore(BaseMessage msg) { Console.WriteLine("Did nothing with " + msg.MessageType); }
public ResponseCSOL(BaseMessage req) : base(req) { }
public ResponseRPRM(BaseMessage req) : base(req) { }
protected override void MessageHandler(BaseMessage pMessage) { if (pMessage.Token == MessageToken.ReloadMessage) { Reset(); } }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn public override void ReceiveHandling(BaseMessage message) /// /// \brief Receive handling. /// /// \par Description. /// -# This method is activated when a new message arrived to the process /// -# The method processing is done according to their arrival order /// -# If you want to change the order of processing use the ArrangeMessageQ /// /// \par Algorithm. /// /// \par Usage Notes. /// Usually the algorithm of this method is: /// -# if message type is ... perform ... /// -# if message type is ... perform ... /// /// \author Ilan Hindy /// \date 26/01/2017 /// /// \param message The message. //////////////////////////////////////////////////////////////////////////////////////////////////// //public override void ReceiveHandling(BaseMessage message) //{ //ChandyLamport_NewStyleChannel channel = (ChandyLamport_NewStyleChannel)ChannelFrom(message); //ChandyLamport_NewStyleMessage msg = message as ChandyLamport_NewStyleMessage; //switch ((msg.MessageType) //{ // case BaseMessage: // // If the process performed snapshot but still did not get marker from all // // it's neighbors : // // Save the message - It will be sent as message in the channels // if (Recordered && !channel.Recorderd) // { // channel.State.Add(msg.Name); // } // break; // case (int)Marker: // // If the process received a marker: // // Add the weight in the marker // // Perform TakeSnapshot (If first Marker in round - Send Marker to all the neighbors) // Weight += msg.MarkerWeight; // TakeSnapshot(); // // Check if the round ended (Received Marker from all it's neighbors) // // Perform EndSnapshot (Send Report, reset variables) // channel.or[c.ork.Recorderd] = true; // if (InChannels.All(cnl => cnl.or[c.ork.Recorderd])) // { // EndSnapshot(); // } // // Change the text on the process because the weight changed // pp[bp.ppk.Text] = GetProcessDefaultName() + "\n" + or[p.ork.Weight]; // break; // case m.MessageTypes.Report: // // If received a Report Message // // If this is not the first report from the source processor in this round // // (or the previouse round because a report can come befor or after // // the marker throw the message // if (message[bm.pak.Round] < or[bp.ork.Round] - 1 || // ((AttributeList)or[p.ork.ReceivedMessageFrom]).Any((a => a.Value == (int)message[m.report.Id]))) // { // break; // } // else // { // or[p.ork.ReceivedMessageFrom].Add(message[m.report.Id]); // } // // If the process is the initiator // // Add the message to the results // // Add the weight to the process weight // // Check condition for end round (weight == 1) // // Check condition for end running (round = max rounds) // if (ea[bp.eak.Initiator]) // { // or[p.ork.Results].Add(message[m.report.Snapshot]); // or[p.ork.Weight] += message[m.report.ReportWeight]; // pp[bp.ppk.Text] = GetProcessDefaultName() + "\n" + or[p.ork.Weight]; // if (or[p.ork.Weight] == 1) // { // PrintResults(); // if (or[bp.ork.Round] < pa[p.pak.MaxRounds]) // { // TakeSnapshot(); // } // else // { // Terminate(); // } // } // } // // If the process is not the initiator // // Propagate the message to all the neighbors // else // { // SendToNeighbours(message, SelectingMethod.Exclude, new List<int> { (int)message[m.report.Id] }); // } // break; //} public override void ReceiveHandling(BaseMessage message) { ChandyLamport_NewStyleChannel channel = (ChandyLamport_NewStyleChannel)ChannelFrom(message); ChandyLamport_NewStyleMessage msg = null; msg = message as ChandyLamport_NewStyleMessage; switch (msg.MessageType) { case BaseMessage: // If the process performed snapshot but still did not get marker from all // it's neighbors : // Save the message - It will be sent as message in the channels if (Recorderd && !channel.Recorderd) { channel.State.Add(msg.Name); } break; case Marker: // If the process received a marker: // Add the weight in the marker // Perform TakeSnapshot (If first Marker in round - Send Marker to all the neighbors) Weight += msg.MarkerWeight; TakeSnapshot(); // Check if the round ended (Received Marker from all it's neighbors) // Perform EndSnapshot (Send Report, reset variables) channel.or[c.ork.Recorderd] = true; if (InChannels.All(cnl => ((ChandyLamport_NewStyleChannel)cnl).Recorderd)) { EndSnapshot(); } // Change the text on the process because the weight changed Text = GetProcessDefaultName() + "\n" + Weight; break; case Report: // If received a Report Message // If this is not the first report from the source processor in this round // (or the previouse round because a report can come befor or after // the marker throw the message if (msg.Round < Round - 1 || (ReceivedMessageFrom.Any(a => a.Value == msg.ReporterId))) { break; } else { ReceivedMessageFrom.Add(msg.ReporterId); } // If the process is the initiator // Add the message to the results // Add the weight to the process weight // Check condition for end round (weight == 1) // Check condition for end running (round = max rounds) if (Initiator) { Results.Add(msg.Snapshot); Weight += msg.ReportWeight; Text = GetProcessDefaultName() + "\n" + Weight; if (Weight == 1) { PrintResults(); if (Round < MaxRounds) { TakeSnapshot(); } else { Terminate(); } } } // If the process is not the initiator // Propagate the message to all the neighbors else { SendReport(MessageDataFor_Report(bm.PrmSource.Prms, null, msg.ReporterId, msg.Snapshot, msg.ReportWeight), SelectingMethod.Exclude, new List <int> { (int)msg.ReporterId }); //SendToNeighbours(msg, SelectingMethod.Exclude, new List<int> { (int)msg.ReporterId }); } break; } }
public void Process(BaseMessage message) { var instance = (dynamic) this; instance.Process((dynamic) message); }
protected override void CopyMessageField(BaseMessage msg) { }
protected override void CopyMessageField(BaseMessage msg) { GameStateMessage copymsg = (GameStateMessage)msg; this.StateName = copymsg.StateName; this.Text = copymsg.Text; }
public ResponseSSPD(BaseMessage req) : base(req) { }