internal Session CreateSession(string sessionName, string serverUrl, MessageSecurityMode securityMode, SecurityPolicy securityPolicy, MessageEncoding messageEncoding, UserIdentity userId) { Session session = new Session(serverUrl, securityMode, securityPolicy.ToString(), messageEncoding, userId, null); session.SessionName = sessionName; session.Connect(false, true); return session; }
public void brocast(byte type, int area, int command, object message, UserToken exToken = null) { byte[] value = MessageEncoding.encode(CreateSocketModel(type, area, command, message)); value = LengthEncoding.encode(value); foreach (UserToken item in list) { if (item != exToken) { byte[] bs = new byte[value.Length]; Array.Copy(value, 0, bs, 0, value.Length); item.write(bs); } } }
public async Task MessageEncodingDecodingTest_test() { //ARRANGE var source = "Text to encode"; var compressor = new DeflateCompressor(); var encoder = new MessageEncoding(compressor); //ACT var encoded = await encoder.EncodeMessage(source); var decoded = await encoder.DecodeMessage(encoded); //ASSERT Assert.AreEqual(decoded, source); }
public void Brocast(byte type, int area, int command, object message, UserToken exToken = null) { byte[] value = MessageEncoding.MessageEncode(CreateSocketModel(type, area, command, message)); value = LengthEncoding.Encode(value); foreach (UserToken item in userList) { if (item == exToken) { continue; } byte[] bs = new byte[value.Length]; //防治将元数据变更 Array.Copy(value, 0, bs, 0, value.Length); item.Write(bs); } }
private void HandleMessageHandled(byte[] payload, uint corrId, MessageEncoding encoding) { object response = null; if (encoding != MessageEncoding.Unkown) { // TODO: It may be the case that we cannot deserialize the response because the remote end defines it. response = _serializer.Deserialize(payload, encoding); } if (_responseTable.TryGetValue(corrId, out var completionSource)) { completionSource.TrySetResult(response); } }
public async Task MessageDecoding_test() { //ARRANGE var source = "Text to encode"; var compressor = new DeflateCompressor(); var encoder = new MessageEncoding(compressor); var encoded = await Helper.DeflateCompress(System.Text.Encoding.UTF8.GetBytes(source), compressor); var toString64 = Convert.ToBase64String(encoded); //ACT var decoded = await encoder.DecodeMessage(toString64); //ASSERT Assert.AreEqual(decoded, source); }
public async Task EncodeTooBigMessageTest(bool encodeBatchFlag, MessageEncoding encoding) { var maxMessageSize = 100; var messages = GenerateSampleMessages(3, encoding); var networkMessages = await(encodeBatchFlag ? _encoder.EncodeBatchAsync(messages, maxMessageSize) : _encoder.EncodeAsync(messages, maxMessageSize) ); Assert.Empty(networkMessages); Assert.Equal((uint)0, _encoder.NotificationsProcessedCount); Assert.Equal((uint)6, _encoder.NotificationsDroppedCount); Assert.Equal((uint)0, _encoder.MessagesProcessedCount); }
public int Get(int tag, string value, MessageEncoding encoder, Span <byte> into) { var encode = encoder.GetEncoder(); var currentOffset = IntegerToFixConverter.Instance.Convert(tag, into); int result = currentOffset; into = into.Slice(currentOffset); into[0] = Constants.EqualsByte; into = into.Slice(1); currentOffset = encode.GetBytes(value, into); result += currentOffset; into = into.Slice(currentOffset); into[0] = Constants.SOHByte; return(result + 2); }
public static async Task <SAMLForm> BuildRequestBindingContext(RequestContext requestContext) { string url = String.Empty; var builders = new List <IPostClauseBuilder>(); requestContext.RelyingState.Add("relayState", "Test state"); var xmlSerialiser = new XMLSerialiser(); var compressor = new DeflateCompressor(); var encoder = new MessageEncoding(compressor); var logger = new LogProviderMock(); var serialiser = new RequestSerialiser(xmlSerialiser, encoder, logger); var xmlSinatureManager = new XmlSignatureManager(); RequestHelper.GetAuthnRequestBuilders = AuthnRequestBuildersFactoryMock.GetAuthnRequestBuildersFactory(); var authnBuilder = new SamlRequestBuilder(serialiser); builders.Add(authnBuilder); //relay state builder var jsonSerialiser = new NSJsonSerializer(new DefaultSettingsProvider()); var relayStateSerialiser = new RelaystateSerialiser(jsonSerialiser, encoder, logger) as IRelayStateSerialiser; var relayStateBuilder = new RelayStateBuilder(relayStateSerialiser); builders.Add(relayStateBuilder); //signature builder var certificateManager = new CertificateManager(logger); var signatureBuilder = new SignatureBuilder(certificateManager, logger, xmlSinatureManager); builders.Add(signatureBuilder); var bindingContext = new RequestPostBindingContext(requestContext); foreach (var b in builders) { await b.Build(bindingContext); } var form = new SAMLForm(); var request = bindingContext.RequestParts[HttpRedirectBindingConstants.SamlRequest]; var base64Encoded = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(request)); var relyingStateSerialised = bindingContext.RequestParts[HttpRedirectBindingConstants.RelayState]; form.ActionURL = bindingContext.DestinationUri.AbsoluteUri; form.SetRequest(base64Encoded); form.SetRelatState(relyingStateSerialised); return(form); }
private static byte[] useskill() { SocketModel model = new SocketModel(); model.type = TypeProtocol.TYPE_BATTLE_ROOM; model.area = 0; model.command = BattleRoomProtocol.USE_SKILL_C; RoomDTO dto = new RoomDTO(); dto.roomId = roomDTO.roomId; dto.roomRoleId = roomDTO.roomRoleId; model.message = dto; var message = MessageEncoding.encode(model); return(LengthEncoding.encode(message)); }
public void writeToUsers(int[] users, int type, int area, int command, object message) { byte[] bs = MessageEncoding.Encode(createSocketModel(type, area, command, message)); bs = LengthEncoding.encode(bs); foreach (int item in users) { UserToken token = userBiz.getToken(item); if (token != null) { Console.WriteLine("群发给指定ID"); byte[] truebs = new byte[bs.Length]; Array.Copy(bs, 0, truebs, 0, bs.Length); token.write(truebs); } } }
public void writeToUsers(long[] users, byte type, int area, int command, ReturnDTO message) { byte[] value = MessageEncoding.encode(createSocketModel(type, area, command, message)); value = LengthEncoding.encode(value); foreach (var item in users) { UserToken token = getToken(item); if (token == null) { continue; } byte[] bs = new byte[value.Length]; Array.Copy(value, bs, value.Length); token.write(bs); } }
public void Encoding(MessageEncoding encoding) { switch (encoding) { case HareDu.MessageEncoding.Auto: MessageEncoding = "auto"; break; case HareDu.MessageEncoding.Base64: MessageEncoding = "base64"; break; default: throw new ArgumentOutOfRangeException(nameof(encoding), encoding, null); } }
public void writeToUsers(int[] users, byte type, int area, int command, object message) { byte[] value = MessageEncoding.encode(CreateSocketModel(type, area, command, message)); value = LengthEncoding.encode(value); foreach (int item in users) { UserToken token = userBiz.getToken(item); if (token == null) { continue; } byte[] bs = new byte[value.Length]; Array.Copy(value, 0, bs, 0, value.Length); token.write(bs); } }
static byte[] login() { AccountInfoDTO accountInfoDTO = new AccountInfoDTO(); accountInfoDTO.accountName = "admin"; accountInfoDTO.password = "******"; SocketModel model = new SocketModel(); model.type = TypeProtocol.TYPE_LOGIN; model.area = 0; model.command = LoginProtocol.LOGIN_CREQ; model.message = accountInfoDTO; var message = MessageEncoding.encode(model); return(LengthEncoding.encode(message)); }
public void exBrocast(UserToken token, int command, object message) { byte[] bs = MessageEncoding.Encode(createSocketModel(getType(), getArea(), command, message)); bs = LengthEncoding.encode(bs); Console.WriteLine("有排除模式群发"); //遍历当前模块所有用户 进行消息发送 foreach (UserToken item in list) { if (item.Equals(token)) { continue; } byte[] truebs = new byte[bs.Length]; Array.Copy(bs, 0, truebs, 0, bs.Length); item.write(truebs); } }
public MessageBuilder AddTag(int tag, string value, MessageEncoding encoding) { if (_encoding == null) { _encoding = encoding; } else if (_encoding != encoding) { throw new InvalidOperationException("Encoding is already set"); } int expectedLength = (int)Math.Floor(Math.Log10(tag) + 1) + encoding.GetEncoder().GetByteCount(value) + 2; EnsureSize(expectedLength); _currentLength += _converter.Get(tag, value, encoding, _builderArray.AsSpan(_currentLength)); return(this); }
void Initialize() { this.httpTransport = new HttpTransportBindingElement(); this.tcpTransport = new TcpTransportBindingElement(); this.namedPipeTransport = new NamedPipeTransportBindingElement(); this.textEncoding = new TextMessageEncodingBindingElement(); this.mtomEncoding = new MtomMessageEncodingBindingElement(); this.binaryEncoding = new BinaryMessageEncodingBindingElement(); this.httpTransport.ManualAddressing = true; this.tcpTransport.ManualAddressing = true; this.namedPipeTransport.ManualAddressing = true; this.transport = RouterTransport.Http; this.messageEncoding = MessageEncoding.Text; }
public void Save([NotNull] XmlTextWriter output) { Assert.ArgumentNotNull(output, nameof(output)); var blowFish = new BlowFish(BlowFish.CipherKey); var encryptedPassword = blowFish.Encrypt_ECB(Password); output.WriteStartElement(@"binding"); output.WriteAttributeString(@"hostName", HostName); output.WriteAttributeString(@"useWindowsAuth", UseWindowsAuth ? @"true" : @"false"); output.WriteAttributeString(@"userName", UserName); output.WriteAttributeString(@"password", encryptedPassword); output.WriteAttributeString(@"dataService", DataServiceName); output.WriteAttributeString(@"webRootPath", WebRootPath); output.WriteAttributeString(@"description", Description); output.WriteAttributeString(@"isRemoteSitecore", IsRemoteSitecore ? @"true" : @"false"); output.WriteAttributeString(@"automaticallyUpdate", AutomaticallyUpdate ? @"true" : @"false"); output.WriteAttributeString(@"isHidden", IsHidden ? @"true" : @"false"); output.WriteAttributeString(@"hostNameComparisonMode", HostNameComparisonMode.ToString()); output.WriteAttributeString(@"receiveTimeout", ReceiveTimeout.ToString()); output.WriteAttributeString(@"sendTimeout", SendTimeout.ToString()); output.WriteAttributeString(@"openTimeout", OpenTimeout.ToString()); output.WriteAttributeString(@"closeTimeout", CloseTimeout.ToString()); output.WriteAttributeString(@"maxReceivedMessageSize", MaxReceivedMessageSize.ToString()); output.WriteAttributeString(@"maxBufferSize", MaxBufferSize.ToString()); output.WriteAttributeString(@"maxBufferPoolSize", MaxBufferPoolSize.ToString()); output.WriteAttributeString(@"maxStringContentLength", MaxStringContentLength.ToString()); output.WriteAttributeString(@"transferMode", TransferMode.ToString()); output.WriteAttributeString(@"messageEncoding", MessageEncoding.ToString()); output.WriteAttributeString(@"textEncoding", TextEncoding.WebName); output.WriteAttributeString(@"bypassProxyOnLocal", BypassProxyOnLocal ? @"true" : @"false"); output.WriteAttributeString(@"useDefaultWebProxy", UseDefaultWebProxy ? @"true" : @"false"); if (ProxyAddress != null) { output.WriteAttributeString(@"proxyAddress", ProxyAddress.ToString()); } else { output.WriteAttributeString(@"proxyAddress", string.Empty); } output.WriteEndElement(); }
private void OnPublishMessage(string message) { try { var msg = new MqttApplicationMessage() { Topic = PublishTopic, Payload = MessageEncoding.GetBytes(message), QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce, Retain = false }; _mqttClient?.PublishAsync(msg); } catch (Exception e) { OnErrorMessage?.Invoke(e.Message); } }
/// <summary> /// Produce Monitored Item Messages from the data set message model for the specified encoding /// </summary> /// <param name="messages"></param> /// <param name="encoding"></param> /// <param name="context"></param> private IEnumerable <MonitoredItemMessage> GetMonitoredItemMessages( IEnumerable <DataSetMessageModel> messages, MessageEncoding encoding, IServiceMessageContext context) { if (context?.NamespaceUris == null) { // declare all notifications in messages dropped foreach (var message in messages) { NotificationsDroppedCount += (uint)(message?.Notifications?.Count() ?? 0); } yield break; } foreach (var message in messages) { if (message.WriterGroup?.MessageType.GetValueOrDefault(MessageEncoding.Json) == encoding) { foreach (var notification in message.Notifications) { var result = new MonitoredItemMessage { MessageContentMask = (message.Writer?.MessageSettings? .DataSetMessageContentMask).ToMonitoredItemMessageMask( message.Writer?.DataSetFieldContentMask), ApplicationUri = message.ApplicationUri, EndpointUrl = message.EndpointUrl, ExtensionFields = message.Writer?.DataSet?.ExtensionFields, NodeId = notification.NodeId, Timestamp = message.TimeStamp ?? DateTime.UtcNow, Value = notification.Value, DisplayName = notification.DisplayName, SequenceNumber = notification.SequenceNumber.GetValueOrDefault(0) }; // force published timestamp into to source timestamp for the legacy heartbeat compatibility if (notification.IsHeartbeat && ((result.MessageContentMask & (uint)MonitoredItemMessageContentMask.Timestamp) == 0) && ((result.MessageContentMask & (uint)MonitoredItemMessageContentMask.SourceTimestamp) != 0)) { result.Value.SourceTimestamp = result.Timestamp; } yield return(result); } } } }
public async Task GetPlainAsertion_Test() { //ARRANGE var foo = "lVRLj9owEL5X6n%2BIfM87IWARVhRUCamtEKx66GXlOANrKbFT2wH239fOBsKyLdpex5%2F9PWbG04dTXTkHkIoJnqPQC9DD7POnqSJ11eB5q5%2F5Bn63oLRjgFxhe5CjVnIsiGIKc1KDwpri7fz7Nxx5ASZKgdTmOeSslGphxZUmXOcoCsLMDUM3TB%2FDBAchTjIvDbNxmsa%2FkLM0HIwT3el41rpR2PePUIStBzUQby9F23hEV0RR0VDhUVH7zMjxVaP81eaLb6VFgV%2BJPbPcyxwBJU%2BjXVJkUVy6WVyGblJA4o4hHLlBmk3CeFJGZQFPaVyMIoDCDYIxcZNxGblklyQuzUbJhMQBTUiEnJ%2FnmIxN5MzPPheCq7YGuQV5YNT4LeGUI4vQWrKi1fCKYHz%2FDvJVSApdzDnakUqBDW1tImQHuFSG5Jv70TdSaEFFhUwLHadrIu56IC1RTfT967bCSnfXQTFwzfQLml16cTx6JlCXcQ3ytVGksl2Y%2BldEA3ODf5j3Vsu1qBh9ceZVJY4LCUQPxv5flJaEK2akIce%2FMmkCLplVpLriuTxvS4OlsDGzJRm1gP78FvFhl5cLPY9%2Fl6g%2FvpHXx9MvFpRd%2Fw1Gw0k7C1E3RDJl5wxOhGp0Y2nALswuqA3sZnfXkWJqcaZs5%2BooZLk2YwLUED%2FaNBsh9cXGXx4ffPxD8rWnrdlNM%2BeOoTi9LERr9z5442B4RK6WH4397aVrRT2h%2FbP895%2FW7A8%3D"; var unescaped = Uri.UnescapeDataString(foo); var request = "SAMLRequest=lVRLj9owEL5X6n%2BIfM87IWARVhRUCamtEKx66GXlOANrKbFT2wH239fOBsKyLdpex5%2F9PWbG04dTXTkHkIoJnqPQC9DD7POnqSJ11eB5q5%2F5Bn63oLRjgFxhe5CjVnIsiGIKc1KDwpri7fz7Nxx5ASZKgdTmOeSslGphxZUmXOcoCsLMDUM3TB%2FDBAchTjIvDbNxmsa%2FkLM0HIwT3el41rpR2PePUIStBzUQby9F23hEV0RR0VDhUVH7zMjxVaP81eaLb6VFgV%2BJPbPcyxwBJU%2BjXVJkUVy6WVyGblJA4o4hHLlBmk3CeFJGZQFPaVyMIoDCDYIxcZNxGblklyQuzUbJhMQBTUiEnJ%2FnmIxN5MzPPheCq7YGuQV5YNT4LeGUI4vQWrKi1fCKYHz%2FDvJVSApdzDnakUqBDW1tImQHuFSG5Jv70TdSaEFFhUwLHadrIu56IC1RTfT967bCSnfXQTFwzfQLml16cTx6JlCXcQ3ytVGksl2Y%2BldEA3ODf5j3Vsu1qBh9ceZVJY4LCUQPxv5flJaEK2akIce%2FMmkCLplVpLriuTxvS4OlsDGzJRm1gP78FvFhl5cLPY9%2Fl6g%2FvpHXx9MvFpRd%2Fw1Gw0k7C1E3RDJl5wxOhGp0Y2nALswuqA3sZnfXkWJqcaZs5%2BooZLk2YwLUED%2FaNBsh9cXGXx4ffPxD8rWnrdlNM%2BeOoTi9LERr9z5442B4RK6WH4397aVrRT2h%2FbP895%2FW7A8%3D&RelayState=tVFLi8IwEP4rEjx2oyvCYm5S9yGrWKi3IhjTUbOkSclMxSL%2B9013q%2B7jspe9TeZ7hjmxLtUlMMHSGgkKHjtjQJF2FvkzWPBa8Yn%2BWEhfrwdZ1hJT8truok6BynmjN6vogiw2b8HhC7K6zSxiW8jBy8YwkZ7qaR7Cx2Qkxq5ULhAkIvgGj0OJqgCfgj9oBcjE6S91ZxppfZ9lr%2BAtGP50zeNzIDmRJIPMbvWuatePNk%2BctsSnNocj5Jf3N1bU%2BeX342PdgzRV0zK71fz3DiFXNwom%2BmHCCWxlZYgJ8hVEbBOwcKVQpPJWOIkahZUFoCAl0vF8Jga8L1oWipflMrlLFukyuBqnPgME2xOVotdrNmbvkMRwNHoY9tosLrE8BoEHLMMZYHYV2sqY8%2Bp8fgc%3D&SigAlg=http%3A%2F%2Fwww.w3.org%2F2000%2F09%2Fxmldsig%23rsa-sha1&Signature=fSYSDEFSQs2E1lko89N6yhZWd9lptNVuKdI%2BdoKJ0nB%2FI13Mfwv2omvuaa0uaYKjF7hbBHCA1gYg7QTx1UXmyMEhbYk4c0thvvyF3HYlToQeiS9BD1tUTXA305bU0BRIf3kLTuRZzT6Rf5kS9XctAg1NZeBW02ro61YJ01E8Rxxt80GmHcQbEDkc7fIua31xqz%2FYxlz5fwIPmfQgH%2Fei2U7Cabf55GozXcffV7MefhbkyYPm9a2dpGo7Tb1t7THURBrwkUjIbYtcFSbTBVQ52nzGJ%2FoqR8SsJ7bIdgzXjKJdZqVZCxEBpXi69A1xL4llLVUrZmwKKDqplP1jkI9foA%3D%3D"; var messageEncoding = new MessageEncoding(new DeflateCompressor()); var decoded = await messageEncoding.DecodeMessage(unescaped); var federationMetadataSerialiser = new FederationMetadataSerialiser(new CertificateValidatorMock(), new LogProviderMock()); var metadataXml = XmlReader.Create(@"D:\Dan\Software\ECA-Interenational\ECA_SPMetadata_20171114.xml"); var metadata = federationMetadataSerialiser.Deserialise(metadataXml) as EntityDescriptor; var spDescriptor = metadata.RoleDescriptors.OfType <ServiceProviderSingleSignOnDescriptor>().First(); var i = request.IndexOf("Signature"); var data = request.Substring(0, i - 1); var sgn = Uri.UnescapeDataString(request.Substring(i + 10)); var certificateManager = new CertificateManager(new LogProviderMock()); //ACT var keyDescriptors = spDescriptor.Keys.Where(k => k.Use == KeyType.Signing); var validated = false; foreach (var k in keyDescriptors.SelectMany(x => x.KeyInfo)) { var binaryClause = k as BinaryKeyIdentifierClause; if (binaryClause == null) { throw new InvalidOperationException(String.Format("Expected type: {0} but it was: {1}", typeof(BinaryKeyIdentifierClause), k.GetType())); } var certContent = binaryClause.GetBuffer(); var cert = new X509Certificate2(certContent); validated = this.VerifySignature(request, cert, certificateManager); if (validated) { break; } } //ASSERT Assert.True(validated); }
/// <summary> /// 쿼리문과 변수를 받아 데이터 셋을 리턴합니다. /// </summary> /// <param name="Query">쿼리</param> /// <param name="dtParameter">변수정보.</param> /// <returns>결과 데이터 텟</returns> /// <example> /// <code> /// DataTable dt = DataLayer.GetDataTableParameter(DataLayer.DatatableStyle.Parameter); /// /// dt.Rows.Add(new object[] { ":P1", "2" }); /// dt.Rows.Add(new object[] { ":P2", "B" }); /// /// DataSet ds = DataLayer.ExecuteDataset("SELECT * FROM TEST WHERE C1 = :P1 AND C2 = :P2", dt, DataLayer.MessageEncoding.Default); /// </code> /// </example> public static DataSet ExecuteDataset(string Query, DataTable dtParameter, MessageEncoding Binding) { DataSet dsParm = new DataSet(); try { DataSet ds = new DataSet(); dsParm.Tables.Add(dtParameter); using (Data.SCOSClient Data = new Data.SCOSClient(GetMesageEncoding(Binding), GetEndpointAddress(Binding))) { Data.ClientCredentials.Windows.ClientCredential.UserName = mService.AuthId; Data.ClientCredentials.Windows.ClientCredential.Password = mService.AuthPwd; string str = Data.ExecuteDataset2(Query, dsParm); ds = Decompress.DecompressDataSet(str); } return(ds); } catch (TimeoutException ex) { throw new Exception("서버연결시간이 초과 되었습니다." + System.Environment.NewLine + ex.Message); } catch (FaultException <Data.DataServiceMyException> greetingFault) { throw new Exception(greetingFault.Detail.Message); } catch (FaultException ex) { throw new Exception("알 수 없는 에레 입니다." + System.Environment.NewLine + ex.Message); } catch (CommunicationException ex) { throw new Exception("서버와의 통신상태를 확인하세요" + System.Environment.NewLine + ex.Message); } catch (Exception ex) { throw ex; } finally { dsParm.Dispose(); dsParm = null; } }
public static async Task <RequestBindingContext> BuildRequestBindingContext(RequestContext requestContext) { string url = String.Empty; var builders = new List <IRedirectClauseBuilder>(); requestContext.RelyingState.Add("relayState", "Test state"); var xmlSerialiser = new XMLSerialiser(); var compressor = new DeflateCompressor(); var encoder = new MessageEncoding(compressor); var logger = new LogProviderMock(); var serialiser = new RequestSerialiser(xmlSerialiser, encoder, logger); RequestHelper.GetAuthnRequestBuilders = AuthnRequestBuildersFactoryMock.GetAuthnRequestBuildersFactory(); var authnBuilder = new SamlRequestBuilder(serialiser); builders.Add(authnBuilder); //request compression builder var encodingBuilder = new RequestEncoderBuilder(encoder); builders.Add(encodingBuilder); //relay state builder var jsonSerialiser = new NSJsonSerializer(new DefaultSettingsProvider()); var relayStateSerialiser = new RelaystateSerialiser(jsonSerialiser, encoder, logger) as IRelayStateSerialiser; var relayStateBuilder = new RelayStateBuilder(relayStateSerialiser); builders.Add(relayStateBuilder); //signature builder var certificateManager = new CertificateManager(logger); var signatureBuilder = new SignatureBuilder(certificateManager, logger); builders.Add(signatureBuilder); var bindingContext = new RequestBindingContext(requestContext); foreach (var b in builders) { await b.Build(bindingContext); } return(bindingContext); }
public override void Serialize(object message, Stream stream) { string typeName = message.GetType().AssemblyQualifiedName; StringBuilder str = new StringBuilder(); str.AppendFormat("{0}\r\n", typeName); byte[] nameBytes = MessageEncoding.GetBytes(str.ToString()); stream.Write(nameBytes, 0, nameBytes.Length); MemoryStream memoryStream = new MemoryStream(); Serializer.NonGeneric.Serialize(memoryStream, message); byte[] data = memoryStream.ToArray(); stream.Write(data.Length.Serialize()); stream.Write(data); stream.Flush(); }
public async Task SerialiseDeserialiseTest() { //ARRANGE var relayState = new Dictionary <string, object> { { "relayState", "Test state" } }; var compressor = new DeflateCompressor(); var messageEncoder = new MessageEncoding(compressor); var jsonSerialiser = new NSJsonSerializer(new DefaultSettingsProvider()); var logger = new LogProviderMock(); var serialiser = new RelaystateSerialiser(jsonSerialiser, messageEncoder, logger) as IRelayStateSerialiser; //ACT var serialised = await serialiser.Serialize(relayState); var deserialised = await serialiser.Deserialize(serialised) as Dictionary <string, object>; //ASSERT Assert.AreEqual(relayState.Count, deserialised.Count); Assert.AreEqual(relayState["relayState"], deserialised["relayState"]); }
virtual public void OnDeserialize(String s, MessageEncoding encoding) { Dictionary <String, Object> vals; switch (encoding) { case MessageEncoding.XML: break; case MessageEncoding.JSON: var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); vals = jsonSerializer.Deserialize <Dictionary <String, Object> >(s); AssignValue <String>(ref ID, "ID", vals); AssignValue <String>(ref ResponseID, "ResponseID", vals); AssignValue <String>(ref Target, "Target", vals); AssignValue <String>(ref Sender, "Sender", vals); AssignValue <MessageType>(ref Type, "Type", vals); AssignValue <int>(ref SubType, "SubType", vals); AssignValue <String>(ref Signature, "Signature", vals); AddValues(vals); break; case MessageEncoding.QUERY_STRING: vals = Utilities.Convert.ParseQueryString(s); AssignValue <String>(ref ID, "ID", vals); AssignValue <String>(ref ResponseID, "ResponseID", vals); AssignValue <String>(ref Target, "Target", vals); AssignValue <String>(ref Sender, "Sender", vals); AssignValue <MessageType>(ref Type, "Type", vals); AssignValue <int>(ref SubType, "SubType", vals); AssignValue <String>(ref Signature, "Signature", vals); AddValues(vals); break; case MessageEncoding.BYTES_ARRAY: break; default: throw new Exception("Unrecongnised encoding " + encoding); } }
/// <summary> /// 异步连接MQTT /// </summary> /// <returns></returns> private async Task ConnectAsync() { // create client instance _mqttClient = new MqttFactory().CreateMqttClient() as MqttClient; if (_mqttClient == null) { return; } _mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e => { OnMessageReceived(e); }); _mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e => { OnMqttConnected(); }); _mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(e => { OnMqttDisconnected(); }); try { var willMsg = new MqttApplicationMessage() { Topic = PublishTopic, Payload = MessageEncoding.GetBytes(WillMessage ?? string.Empty), QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce, Retain = false }; var options = new MqttClientOptionsBuilder() .WithTcpServer(BrokerAddress, BrokerPort) .WithCredentials(BrokerUserName, BrokerPassword) .WithClientId(_clientId) .WithWillMessage(willMsg) .WithCleanSession() .Build(); await _mqttClient.ConnectAsync(options); } catch (Exception e) { MqttConnected = false; OnErrorMessage?.Invoke(e.Message); } }
public async Task RelayStateBuilder_test() { ////ARRANGE var relayState = new Dictionary <string, object> { { "relayState", "Test state" } }; var compressor = new DeflateCompressor(); var messageEncoder = new MessageEncoding(compressor); var jsonSerialiser = new NSJsonSerializer(new DefaultSettingsProvider()); var logger = new LogProviderMock(); var serialiser = new RelaystateSerialiser(jsonSerialiser, messageEncoder, logger) as IRelayStateSerialiser; var context = new BindingContext(relayState, new Uri("localhost:")); var builder = new RelayStateBuilder(serialiser); //ACT await builder.Build(context); ////ASSERT Assert.AreEqual(1, context.RequestParts.Count); Assert.IsTrue(context.RequestParts.ContainsKey(HttpRedirectBindingConstants.RelayState)); }
private static byte[] usecard() { SocketModel model = new SocketModel(); model.type = TypeProtocol.TYPE_BATTLE_ROOM; model.area = 0; model.command = BattleRoomProtocol.USE_CARD_C; RoomDTO dto = new RoomDTO(); dto.roomId = roomDTO.roomId; dto.roomRoleId = roomDTO.roomRoleId; dto.map.Add(CommonFieldProtocol.useCardId, selfInfo[0].cardIds[0]); dto.map.Add(CommonFieldProtocol.targetIds, new List <string> { otherInfo[0].roomRoleId }); model.message = dto; var message = MessageEncoding.encode(model); return(LengthEncoding.encode(message)); }
private static Encoding GetEncoding(MessageEncoding encodingChoice, string encodingName) { switch (encodingChoice) { case MessageEncoding.ASCII: return(Encoding.ASCII); case MessageEncoding.UTF8: return(Encoding.UTF8); case MessageEncoding.Unicode: return(Encoding.Unicode); case MessageEncoding.UTF32: return(Encoding.UTF32); case MessageEncoding.Other: default: return(Encoding.GetEncoding(encodingName)); } }