Inheritance: MonoBehaviour
Example #1
1
        //Can only be called inside a service
        public static void PromoteException(Exception error,MessageVersion version,ref Message fault)
        {
            StackFrame frame = new StackFrame(1);

             Type serviceType = frame.GetMethod().ReflectedType;
             PromoteException(serviceType,error,version,ref fault);
        }
Example #2
1
        // DeckList && LibraryView
        public void handleMessage(Message msg)
        {
            if( msg is LibraryViewMessage && config.ContainsKey("user-id") ) {
                LibraryViewMessage viewMsg = (LibraryViewMessage) msg;
                if( !viewMsg.profileId.Equals(App.MyProfile.ProfileInfo.id) ) {
                    return;
                }

                inventoryCards.Clear();
                foreach( Card card in viewMsg.cards ) {
                    inventoryCards[card.id] = String.Format("{0},{1}", card.typeId, card.tradable ? 1 : 0);
                }

                if( dataPusher == null ) {
                    if( config.ContainsKey("last-card-sync") ) {
                        dataPusher = new Thread(new ThreadStart(DelayedPush));
                    } else {
                        dataPusher = new Thread(new ThreadStart(Push));
                    }

                    dataPusher.Start();
                }

            //} else if( msg is DeckCardsMessage ) {
            //    DeckCardsMessage deckMsg = (DeckCardsMessage)msg;
            //} else if( msg is DeckSaveMessage ) {
            }
        }
Example #3
0
        public ValidationNode Validate(Message message)
        {
            if (string.Equals(message.Type, Type, StringComparison.OrdinalIgnoreCase) == false)
            {
                return new ValidationNode(Status.NotInterested, string.Empty);
            }

            try
            {
                var obj = JObject.Parse(message.Body);

                IList<string> bodyMessages;
                IList<string> headerMessages;

                var bodyStatus = obj.IsValid(Body, out bodyMessages);
                var headerStatus = JObject.FromObject(message.Headers).IsValid(Header, out headerMessages);

                var status = bodyStatus && headerStatus
                    ? Status.Pass
                    : Status.Fail;

                return new ValidationNode(status, string.Join(Environment.NewLine, headerMessages.Concat(bodyMessages)));
            }
            catch (Exception ex)
            {
                return new ValidationNode(Status.Fail, ex.Message);
            }
        }
Example #4
0
 public object AfterReceiveRequest(ref Message request,
     IClientChannel channel,
     InstanceContext instanceContext)
 {
     request = TraceHttpRequestMessage(request.ToHttpRequestMessage());
     return null;
 }
 // Create a message and send it to IoT Hub.
 async Task SendEvent(string power)
 {
     string dataBuffer;
     dataBuffer = power;
     Message eventMessage = new Message(Encoding.UTF8.GetBytes(dataBuffer));
     await deviceClient.SendEventAsync(eventMessage);
 }
Example #6
0
            protected Request(RHost host, Message message) {
                Id = message.Id;
                MessageName = message.Name;
                Json = message.Json;

                host._requests[Id] = this;
            }
Example #7
0
File: OCD.cs Project: snosrap/nhapi
 ///<summary>
 /// Creates a OCD.
 /// <param name="message">The Message to which this Type belongs</param>
 ///</summary>
 public OCD(Message message, string description)
     : base(message, description)
 {
     data = new Type[2];
     data[0] = new ID(message, 0,"Occurrence code");
     data[1] = new DT(message,"Occurrence date");
 }
Example #8
0
    public void OnClick(string name )
    {
        Debug.Log("Click " + name );
        Message msg = new Message();
        msg.AddMessage("name", name);
        EventManager.Instance.PostEvent(EventDefine.TL_PRESS_BUTTON, msg);

        if (name == "Cone")
        {
            SpriteAction sa = coneEffect.GetComponent<SpriteAction>();
            SpriteRenderer render = coneEffect.GetComponent<SpriteRenderer>();

            render.color = new Color(Random.Range(0.5f , 1f) , Random.Range(0.5f , 1f) , Random.Range(0.5f , 1f) , 0.5f );
            sa.Do();
        }
        if (name == "Bubble")
        {
            bubbleEffect.enableEmission = true;
        }
        if (name == "Flower")
        {
            AudioSource[] audios = flowerEffect.GetComponents<AudioSource>();
            audios[Random.Range(0, audios.Length)].Play();
        }
    }
Example #9
0
File: CQ.cs Project: snosrap/nhapi
 ///<summary>
 /// Creates a CQ.
 /// <param name="message">The Message to which this Type belongs</param>
 ///</summary>
 public CQ(Message message, string description)
     : base(message, description)
 {
     data = new Type[2];
     data[0] = new NM(message,"Quantity");
     data[1] = new CE(message,"Units");
 }
Example #10
0
        /// <summary>
        /// Add token message at header to using NHibernate cache
        /// </summary>
        /// <param name="request"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            // add trace log for debug and performance tuning
            if (null != (request.Headers).MessageId && (request.Headers).MessageId.IsGuid)
            {
                ServiceStopWatch = Stopwatch.StartNew();
                Guid messageId;
                (request.Headers).MessageId.TryGetGuid(out messageId);

                CurrentTraceInfo = new TraceInfo()
                {
                    SessionId = (HttpContext.Current != null && HttpContext.Current.Session != null) ? HttpContext.Current.Session.SessionID : "",
                    TraceType = TraceType.WcfActionClientCall,
                    TraceName = request.Headers.Action,
                    TraceUniqueId = messageId.ToString()
                };

                TraceLogger.Instance.TraceServiceStart(CurrentTraceInfo, true);

                // Add a message header with sessionid
                MessageHeader<string> messageHeader = new MessageHeader<string>(CurrentTraceInfo.SessionId);
                MessageHeader untyped = messageHeader.GetUntypedHeader("sessionid", "ns");
                request.Headers.Add(untyped);
            }
            return null;
        }
Example #11
0
        /// <summary>
        /// Parses the JSON message from Amazon SNS into the Message object.
        /// </summary>
        /// <param name="messageText">The JSON text from an Amazon SNS message</param>
        /// <returns>The Message object with properties set from the JSON document</returns>
        public static Message ParseMessage(string messageText)
        {
            var message = new Message();

            var jsonData = JsonMapper.ToObject(messageText);

            Func<string, string> extractField = ((fieldName) =>
                {
                    if (jsonData[fieldName] != null && jsonData[fieldName].IsString)
                        return (string)jsonData[fieldName];
                    return null;
                });

            message.MessageId = extractField("MessageId");
            message.MessageText = extractField("Message");
            message.Signature = extractField("Signature");
            message.SignatureVersion = extractField("SignatureVersion");
            message.SigningCertURL = ValidateCertUrl(extractField("SigningCertURL"));
            message.SubscribeURL = extractField("SubscribeURL");
            message.Subject = extractField("Subject");
            message.TimestampString = extractField("Timestamp");
            message.Token = extractField("Token");
            message.TopicArn = extractField("TopicArn");
            message.Type = extractField("Type");
            message.UnsubscribeURL = extractField("UnsubscribeURL");

            return message;
        }
 public SecurityVerifiedMessage(Message messageToProcess, ReceiveSecurityHeader securityHeader)
     : base(messageToProcess)
 {
     this.securityHeader = securityHeader;
     if (securityHeader.RequireMessageProtection)
     {
         XmlDictionaryReader messageReader;
         BufferedMessage bufferedMessage = this.InnerMessage as BufferedMessage;
         if (bufferedMessage != null && this.Headers.ContainsOnlyBufferedMessageHeaders)
         {
             messageReader = bufferedMessage.GetMessageReader();
         }
         else
         {
             this.messageBuffer = new XmlBuffer(int.MaxValue);
             XmlDictionaryWriter writer = this.messageBuffer.OpenSection(this.securityHeader.ReaderQuotas);
             this.InnerMessage.WriteMessage(writer);
             this.messageBuffer.CloseSection();
             this.messageBuffer.Close();
             messageReader = this.messageBuffer.GetReader(0);
         }
         MoveToSecurityHeader(messageReader, securityHeader.HeaderIndex, true);
         this.cachedReaderAtSecurityHeader = messageReader;
         this.state = BodyState.Buffered;
     }
     else
     {
         this.envelopeAttributes = XmlAttributeHolder.emptyArray;
         this.headerAttributes = XmlAttributeHolder.emptyArray;
         this.bodyAttributes = XmlAttributeHolder.emptyArray;
         this.canDelegateCreateBufferedCopyToInnerMessage = true;
     }
 }
Example #13
0
 public static int AddMessage(Message obj)
 {
     int result;
     TMSDataLibrary.Message objMsg = new TMSDataLibrary.Message();
     result = objMsg.AddMessege(obj.BookingId, obj.ToId, obj.FromId, obj.Messagee);
     return result;
 }
 /// <summary>
 /// Apply default settings to the specified <paramref name="message" />.
 /// </summary>
 /// <param name="message">The message to update.</param>
 public void ApplyDefaults(Message message)
 {
     message.Name = Configuration.Name;
     message.RetryCount = Configuration.RetryCount;
     message.Priority = (int)Configuration.Priority;
     message.ResponseQueue = Configuration.ResponseQueue;
 }
Example #15
0
 public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
 {
     var reply = request.Headers.ReplyTo;
     OperationContext.Current.OutgoingMessageHeaders.To = reply.Uri;
     OperationContext.Current.OutgoingMessageHeaders.RelatesTo = request.Headers.MessageId;
     return null;
 }
Example #16
0
    private void HandleTreeDeath(Message message)
    {
        PlayerKilledMessage m = message as PlayerKilledMessage;

        //Destroy(m.Tree);
        m.NPC.SetActive(false);

        if (m.Tree.GetComponent<PossessableTree>().Active)
        {

        }
        else
        {
            // Spawn a killing axe man
            GameObject axeMan = (GameObject)Instantiate(AxeManKillInactive, m.Tree.transform.position + new Vector3(-1.14f, 0.091f), Quaternion.identity);

            axeMan.GetComponent<AxeManKillInactiveTree>().Instantiate(m.Tree, m.NPC, HandleCinematicFinished);
            m.Tree.GetComponent<PossessableTree>().AxeMan = axeMan;

            transform.position = new Vector3(m.Tree.transform.position.x, m.Tree.transform.position.y + 0.7f, -9f);
            cam.enabled = true;

            MessageCenter.Instance.Broadcast(new AxeManStartedChoppingTreeMessage());

            //m.Tree.GetComponent<PossessableTree>().ChangeState("InactiveDead", axeMan);
        }
    }
        private BufferSlice EncodeMessage(Message msg)
        {
            if (msg.Body.Length != 0)
                msg.Headers["Content-Length"] = msg.Body.Length.ToString();

            var buffer = new byte[65535];
            long length = 0;
            using (var stream = new MemoryStream(buffer))
            {
                stream.SetLength(0);
                using (var writer = new StreamWriter(stream))
                {
                    foreach (string key in msg.Headers)
                    {
                        writer.Write(string.Format("{0}: {1}\n", key, msg.Headers[key]));
                    }
                    writer.Write("\n");


                    writer.Flush();
                    stream.Write(stream.GetBuffer(), 0, (int) stream.Length);
                    length = stream.Length;
                }
            }

            var tmp = Encoding.ASCII.GetString(buffer, 0, (int) length);
            return new BufferSlice(buffer, 0, (int) length, (int) length);
        }
 private static void TraceMessage(Message message)
 {
     if (message != null)
     {
         message.TraceMessage();
     }
 }
        public void execMenuItem(ref Message msg)
        {
            if (msg.Msg == (int)WindowMessages.wmSysCommand)
            {
                switch (msg.WParam.ToInt32())
                {
                    case m_FormInfo:
                        {
                            RightClickTitleBarHelper.showFormInfo(this.form);
                            break;
                        }

                    case m_RefreshForm:
                        {
                            RightClickTitleBarHelper.refreshForm((IFormRefresh)this.form);
                            break;
                        }
                    case m_FURL:
                        {
                            RightClickTitleBarHelper.showFURL((IFormFURL)this.form);
                            break;
                        }
                    default:
                        {
                            break;
                        }
                }
            }
        }
 /// <summary>
 ///   Publishes a message.
 /// </summary>
 /// <param name = "message">The message instance.</param>
 /// <remarks>
 ///   Does not marshall the the publication to any special thread by default.
 /// </remarks>
 public virtual void Send(Message message)
 {
     if (message == null) {
         throw new ArgumentNullException("message");
     }
     Send(message, PublicationThreadMarshaller);
 }
Example #21
0
File: UVC.cs Project: snosrap/nhapi
 ///<summary>
 /// Creates a UVC.
 /// <param name="message">The Message to which this Type belongs</param>
 ///</summary>
 public UVC(Message message, string description)
     : base(message, description)
 {
     data = new Type[2];
     data[0] = new CNE(message,"Value Code");
     data[1] = new MO(message,"Value Amount");
 }
        /// <summary>
        ///     Called after the operation has returned but before the reply message is sent.
        /// </summary>
        /// <param name="reply">The reply message. This value is null if the operation is one way.</param>
        /// <param name="correlationState">
        ///     The correlation object returned from the
        ///     <see
        ///         cref="M:System.ServiceModel.Dispatcher.IDispatchMessageInspector.AfterReceiveRequest(System.ServiceModel.Channels.Message@,System.ServiceModel.IClientChannel,System.ServiceModel.InstanceContext)" />
        ///     method.
        /// </param>
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            var state = correlationState as CorsCorrelationState;
            if (state == null || state.IsEmpty)
            {
                return;
            }

            HttpResponseMessageProperty httpProp;
            if (reply.Properties.ContainsKey(HttpResponseMessageProperty.Name))
            {
                httpProp = (HttpResponseMessageProperty)reply.Properties[HttpResponseMessageProperty.Name];
            }
            else
            {
                httpProp = new HttpResponseMessageProperty();
                reply.Properties.Add(HttpResponseMessageProperty.Name, httpProp);
            }

            httpProp.Headers.Add(CorsConstants.AccessControlAllowOrigin, state.Origin);

            // https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Credentials
            if (state.Authorization != null)
            {
                httpProp.Headers.Add(CorsConstants.AccessControlAllowCredentials, "true");
            }
        }
Example #23
0
 public HotkeyMessage(Message messageType, Level messageLevel, IntPtr hWnd, int Data)
 {
     Message = messageType;
     level = messageLevel;
     handle = hWnd;
     data = Data;
 }
		private void FormattedHeaders(Message message, StringBuilder output)
		{
			foreach (var header in message.Headers)
			{
				output.AppendFormat("\n{0}\n", header);
			}
		}
		private void FormattedMessage(Message message, char format, StringBuilder output)
		{
			using (var writer = CreateWriter(message, format, output))
			{
				switch (format)
				{
					case 'b':
						message.WriteBody(writer);
						break;
					case 'B':
						message.WriteBodyContents(writer);
						break;
					case 's':
						message.WriteStartBody(writer);
						break;
					case 'S':
						message.WriteStartEnvelope(writer);
						break;
					case 'm':
					case 'M':
						message.WriteMessage(writer);
						break;
					default:
						return;
				}

				writer.Flush();
			}
		}
        public override bool CheckAccess(OperationContext operationContext, ref Message message)
        {
            // Open the request message using an xml reader
            XmlReader xr = OperationContext.Current.IncomingMessageHeaders.GetReaderAtHeader(0);

                // Split the URL at the API name--Parameters junction indicated by the '?' character - taking the first string will ignore all parameters
                string[] urlSplit = xr.ReadElementContentAsString().Split('/');
                // Extract just the API name and rest of the URL, which will be the last item in the split using '/'
                string[] apiSplit = urlSplit[3].Split('?');
                // Logging the username and API name
                Tracer.WriteUserLog(apiSplit[0] + " request from user: "******"CheckAccess: Authorized");
                return true;
            }
            else
            {
                Tracer.WriteUserLog("CheckAccess: NOT Authorized");
                return false;
            }
        }
        public void Should_not_overwrite_correlation_id()
        {
            var autoResetEvent = new AutoResetEvent(false);
            const string expectedCorrelationId = "abc_foo";
            var actualCorrelationId = "";

            var queue = EasyNetQ.Topology.Queue.DeclareDurable("myqueue");
            var exchange = EasyNetQ.Topology.Exchange.DeclareDirect("myexchange");
            queue.BindTo(exchange, "#");
            bus.Subscribe<MyMessage>(queue, (message, info) => Task.Factory.StartNew(() =>
            {
                actualCorrelationId = message.Properties.CorrelationId;
                autoResetEvent.Set();
            }));

            var messageToSend = new Message<MyMessage>(new MyMessage());
            messageToSend.Properties.CorrelationId = expectedCorrelationId;

            using (var channel = bus.OpenPublishChannel())
            {
                channel.Publish(exchange, "abc", messageToSend);
            }

            autoResetEvent.WaitOne(1000);

            actualCorrelationId.ShouldEqual(expectedCorrelationId);
        }
Example #28
0
        public static Message CreateSlackMessage(string text, IEnumerable<AttachmentField> fields, BotElement bot, string channel, string color, bool asUser)
        {
            if (text == null) return null;
            IEnumerable<Attachment> attachments = null;
            if (fields != null && fields.Any())
            {
                attachments = new[] {
                    new Attachment() {
                        Fallback = text,
                        Color = color,
                        Fields = fields
                    }
                };
            }
            var message = new Message()
            {
                Channel = channel,
                Text = text,
                Attachments = attachments
            };

            if (!asUser)
            {
                message.Username = bot.GetSetting("username");
                if (!string.IsNullOrEmpty(bot.GetSetting("iconUrl")))
                    message.IconUrl = bot.GetSetting("iconUrl");
                else if (!string.IsNullOrEmpty(bot.GetSetting("iconEmoji")))
                    message.IconEmoji = bot.GetSetting("iconEmoji");
            }

            return message;
        }
 public WSSecurityOneDotZeroSendSecurityHeader(Message message, string actor, bool mustUnderstand, bool relay,
     SecurityStandardsManager standardsManager,
     SecurityAlgorithmSuite algorithmSuite,
     MessageDirection direction)
     : base(message, actor, mustUnderstand, relay, standardsManager, algorithmSuite, direction)
 {
 }
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            bool shouldCompressResponse = false;

            object propObj;
            if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out propObj))
            {
                var prop = (HttpRequestMessageProperty)propObj;
                var accept = prop.Headers[HttpRequestHeader.Accept];
                if (accept != null)
                {
                    if (jsonContentTypes.IsMatch(accept))
                    {
                        WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
                    }
                    else if (xmlContentTypes.IsMatch(accept))
                    {
                        WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;
                    }
                }

                var acceptEncoding = prop.Headers[HttpRequestHeader.AcceptEncoding];
                if (acceptEncoding != null && acceptEncoding.Contains("gzip"))
                {
                    shouldCompressResponse = true;
                }
            }

            return shouldCompressResponse;
        }
 private async Task SendMessage(ServiceBusSender sender, Message message)
 {
     await sender.SendMessageAsync(BuildServiceBusMessage(message)).ConfigureAwait(false);
 }
Example #32
0
        internal static async Task <string> GetIdentityServerSignoutFrameCallbackUrlAsync(this HttpContext context, LogoutMessage logoutMessage = null)
        {
            var userSession = context.RequestServices.GetRequiredService <IUserSession>();
            var user        = await userSession.GetUserAsync();

            var currentSubId = user?.GetSubjectId();

            EndSession endSessionMsg = null;

            // if we have a logout message, then that take precedence over the current user
            if (logoutMessage?.ClientIds?.Any() == true)
            {
                var clientIds = logoutMessage?.ClientIds;

                // check if current user is same, since we might have new clients (albeit unlikely)
                if (currentSubId == logoutMessage?.SubjectId)
                {
                    clientIds = clientIds.Union(await userSession.GetClientListAsync());
                    clientIds = clientIds.Distinct();
                }

                endSessionMsg = new EndSession
                {
                    SubjectId = logoutMessage.SubjectId,
                    SessionId = logoutMessage.SessionId,
                    ClientIds = clientIds
                };
            }
            else if (currentSubId != null)
            {
                // see if current user has any clients they need to signout of
                var clientIds = await userSession.GetClientListAsync();

                if (clientIds.Any())
                {
                    endSessionMsg = new EndSession
                    {
                        SubjectId = currentSubId,
                        SessionId = await userSession.GetSessionIdAsync(),
                        ClientIds = clientIds
                    };
                }
            }

            if (endSessionMsg != null)
            {
                var clock = context.RequestServices.GetRequiredService <ISystemClock>();
                var msg   = new Message <EndSession>(endSessionMsg, clock.UtcNow.UtcDateTime);

                var endSessionMessageStore = context.RequestServices.GetRequiredService <IMessageStore <EndSession> >();
                var id = await endSessionMessageStore.WriteAsync(msg);

                var signoutIframeUrl = context.GetIdentityServerBaseUrl().EnsureTrailingSlash() + Constants.ProtocolRoutePaths.EndSessionCallback;
                signoutIframeUrl = signoutIframeUrl.AddQueryString(Constants.UIConstants.DefaultRoutePathParams.EndSessionCallback, id);

                return(signoutIframeUrl);
            }

            // no sessions, so nothing to cleanup
            return(null);
        }
Example #33
0
        public static void ReplaceSecurityId(this Message message, SecurityId securityId)
        {
            switch (message.Type)
            {
            //case MessageTypes.Position:
            //{
            //	var positionMsg = (PositionMessage)message;
            //	positionMsg.SecurityId = securityId;
            //	break;
            //}

            case MessageTypes.PositionChange:
            {
                var positionMsg = (PositionChangeMessage)message;
                positionMsg.SecurityId = securityId;
                break;
            }

            case MessageTypes.Execution:
            {
                var execMsg = (ExecutionMessage)message;
                execMsg.SecurityId = securityId;
                break;
            }

            case MessageTypes.Level1Change:
            {
                var level1Msg = (Level1ChangeMessage)message;
                level1Msg.SecurityId = securityId;
                break;
            }

            case MessageTypes.QuoteChange:
            {
                var quoteChangeMsg = (QuoteChangeMessage)message;
                quoteChangeMsg.SecurityId = securityId;
                break;
            }

            case MessageTypes.News:
            {
                var newsMsg = (NewsMessage)message;
                newsMsg.SecurityId = securityId;
                break;
            }

            case MessageTypes.OrderRegister:
            {
                var msg = (OrderRegisterMessage)message;
                msg.SecurityId = securityId;
                break;
            }

            case MessageTypes.OrderReplace:
            {
                var msg = (OrderReplaceMessage)message;
                msg.SecurityId = securityId;
                break;
            }

            case MessageTypes.OrderCancel:
            {
                var msg = (OrderCancelMessage)message;
                msg.SecurityId = securityId;
                break;
            }

            case MessageTypes.MarketData:
            {
                var msg = (MarketDataMessage)message;
                msg.SecurityId = securityId;
                break;
            }

            case MessageTypes.CandleTimeFrame:
            case MessageTypes.CandleRange:
            case MessageTypes.CandlePnF:
            case MessageTypes.CandleRenko:
            case MessageTypes.CandleTick:
            case MessageTypes.CandleVolume:
            {
                var msg = (CandleMessage)message;
                msg.SecurityId = securityId;
                break;
            }

            default:
                throw new ArgumentOutOfRangeException(nameof(message), message.Type, LocalizedStrings.Str2770);
            }
        }
 public async Task Handle(Message message)
 {
     _counter.Decrement();
 }
 private void OnGetBroadcastCoinOfPlayerDataMSSC(Message obj)
 {
     money_1_Text.text = playerData.playerZoo.playerCoin.GetCoinByScene(playerData.playerZoo.currSceneID).coinShow;
     //money_2_Text.text = "0";
 }
Example #36
0
        private void DoDevTypHandle(ref Message m, ref String text)
        {
#if DEBUG
            WindowsBluetoothDeviceInfo dev = null;
#endif
            DEV_BROADCAST_HANDLE hdrHandle = (DEV_BROADCAST_HANDLE)m.GetLParam(typeof(DEV_BROADCAST_HANDLE));
            var pData = Utils.Pointers.Add(m.LParam, _OffsetOfData);
            if (BluetoothDeviceNotificationEvent.BthPortDeviceInterface == hdrHandle.dbch_eventguid)
            {
                text += "GUID_BTHPORT_DEVICE_INTERFACE";
            }
            else if (BluetoothDeviceNotificationEvent.RadioInRange == hdrHandle.dbch_eventguid)
            {
                text += "GUID_BLUETOOTH_RADIO_IN_RANGE";
                BTH_RADIO_IN_RANGE inRange
                      = (BTH_RADIO_IN_RANGE)Marshal.PtrToStructure(pData, typeof(BTH_RADIO_IN_RANGE));
                text += String.Format(System.Globalization.CultureInfo.InvariantCulture,
                                      " 0x{0:X12}", inRange.deviceInfo.address);
                text += String.Format(System.Globalization.CultureInfo.InvariantCulture,
                                      " is ({0}) 0x{0:X}", inRange.deviceInfo.flags);
                text += String.Format(System.Globalization.CultureInfo.InvariantCulture,
                                      " was ({0}) 0x{0:X}", inRange.previousDeviceFlags);
                var bdi0 = BLUETOOTH_DEVICE_INFO.Create(inRange.deviceInfo);
                var e    = BluetoothWin32RadioInRangeEventArgs.Create(
                    inRange.previousDeviceFlags,
                    inRange.deviceInfo.flags, bdi0);
#if DEBUG
                dev = new WindowsBluetoothDeviceInfo(bdi0);
                Debug.WriteLine("InRange: " + dev.DeviceAddress);
#endif
                RaiseInRange(e);
            }
            else if (BluetoothDeviceNotificationEvent.RadioOutOfRange == hdrHandle.dbch_eventguid)
            {
                BTH_RADIO_OUT_OF_RANGE outOfRange
                      = (BTH_RADIO_OUT_OF_RANGE)Marshal.PtrToStructure(pData, typeof(BTH_RADIO_OUT_OF_RANGE));
                text += "GUID_BLUETOOTH_RADIO_OUT_OF_RANGE";
                text += String.Format(System.Globalization.CultureInfo.InvariantCulture,
                                      " 0x{0:X12}", outOfRange.deviceAddress);
                var e = BluetoothWin32RadioOutOfRangeEventArgs.Create(
                    outOfRange.deviceAddress);
                Debug.WriteLine("OutOfRange: " + outOfRange.deviceAddress);
                RaiseOutOfRange(e);
            }
            else if (BluetoothDeviceNotificationEvent.PinRequest == hdrHandle.dbch_eventguid)
            {
                text += "GUID_BLUETOOTH_PIN_REQUEST";
                // "This message should be ignored by the application.
                //  If the application must receive PIN requests, the
                //  BluetoothRegisterForAuthentication function should be used."
            }
            else if (BluetoothDeviceNotificationEvent.L2capEvent == hdrHandle.dbch_eventguid)
            {
                text += "GUID_BLUETOOTH_L2CAP_EVENT";
                // struct BTH_L2CAP_EVENT_INFO {
                //   BTH_ADDR bthAddress; USHORT psm; UCHAR connected; UCHAR initiated; }
#if DEBUG
                var l2capE = Marshal_PtrToStructure <BTH_L2CAP_EVENT_INFO>(pData);
                Debug.WriteLine(string.Format(CultureInfo.InvariantCulture,
                                              "L2CAP_EVENT: addr: {0:X}, psm: {1}, conn: {2}, init'd: {3}",
                                              l2capE.bthAddress, l2capE.psm, l2capE.connected, l2capE.initiated));
#endif
            }
            else if (BluetoothDeviceNotificationEvent.HciEvent == hdrHandle.dbch_eventguid)
            {
                text += "GUID_BLUETOOTH_HCI_EVENT";
                // struct BTH_HCI_EVENT_INFO {
                //   BTH_ADDR bthAddress; UCHAR connectionType; UCHAR connected; }
#if DEBUG
                var hciE = Marshal_PtrToStructure <BTH_HCI_EVENT_INFO>(pData);
                Debug.WriteLine(string.Format(CultureInfo.InvariantCulture,
                                              "HCI_EVENT: addr: {0:X}, type: {1}, conn: {2}",
                                              hciE.bthAddress, hciE.connectionType, hciE.connected));
#endif
            }
            // -- New somewhere after WinXP.
            else if (BluetoothDeviceNotificationEvent.AuthenticationRequestEvent == hdrHandle.dbch_eventguid)
            {
                text += "GUID_BLUETOOTH_AUTHENTICATION_REQUEST";
                // Same content as BluetoothRegisterForAuthenticationEx
            }
            else if (BluetoothDeviceNotificationEvent.KeyPressEvent == hdrHandle.dbch_eventguid)
            {
                text += "GUID_BLUETOOTH_KEYPRESS_EVENT";
                // struct BTH_HCI_KEYPRESS_INFO {
                //   BTH_ADDR  BTH_ADDR; UCHAR   NotificationType; // HCI_KEYPRESS_XXX value }
            }
            else if (BluetoothDeviceNotificationEvent.HciVendorEvent == hdrHandle.dbch_eventguid)
            {
                text += "GUID_BLUETOOTH_HCI_VENDOR_EVENT";
            }
            // -- Unknown
            else
            {
                text += "Unknown event: " + hdrHandle.dbch_eventguid;
            }
            Debug.WriteLine("Text: " + text);
        }
Example #37
0
 protected override void WndProc(ref Message m)
 {
     _parent.HandleMessage(ref m);
     base.WndProc(ref m);
 }
 public MyEvent MapToRequest(Message message)
 {
     return(JsonSerializer.Deserialize <MyEvent>(message.Body.Value, JsonSerialisationOptions.Options));
 }
 private void AddMessage()
 {
     Message.AddListener <SkinBuyInfoMsg>(SkinBuyInfo);
 }
 private void RemoveMessage()
 {
     Message.RemoveListener <SkinBuyInfoMsg>(SkinBuyInfo);
 }
Example #41
0
        public static void OnMessage(Entity entity, UOMessageEventArgs args)
        {
            switch (args.Type)
            {
            case MessageType.Regular:

                if (entity != null && entity.Serial.IsValid)
                {
                    entity.AddGameText(args.Type, args.Text, (byte)args.Font, args.Hue, args.IsUnicode);
                    Service.Get <JournalData>().AddEntry(args.Text, (byte)args.Font, args.Hue, entity.Name);
                }
                else
                {
                    Service.Get <ChatControl>().AddLine(args.Text, (byte)args.Font, args.Hue, args.IsUnicode);
                    Service.Get <JournalData>().AddEntry(args.Text, (byte)args.Font, args.Hue, "System");
                }

                break;

            case MessageType.System:
                Service.Get <ChatControl>().AddLine(args.Text, (byte)args.Font, args.Hue, args.IsUnicode);
                Service.Get <JournalData>().AddEntry(args.Text, (byte)args.Font, args.Hue, "System");

                break;

            case MessageType.Emote:

                if (entity != null && entity.Serial.IsValid)
                {
                    entity.AddGameText(args.Type, $"*{args.Text}*", (byte)args.Font, args.Hue, args.IsUnicode);
                    Service.Get <JournalData>().AddEntry($"*{args.Text}*", (byte)args.Font, args.Hue, entity.Name);
                }
                else
                {
                    Service.Get <JournalData>().AddEntry($"*{args.Text}*", (byte)args.Font, args.Hue, "System");
                }

                break;

            case MessageType.Label:

                if (entity != null && entity.Serial.IsValid)
                {
                    entity.AddGameText(args.Type, args.Text, (byte)args.Font, args.Hue, args.IsUnicode);
                }
                Service.Get <JournalData>().AddEntry(args.Text, (byte)args.Font, args.Hue, "You see");

                break;

            case MessageType.Focus:

                break;

            case MessageType.Whisper:

                break;

            case MessageType.Yell:

                break;

            case MessageType.Spell:

                if (entity != null && entity.Serial.IsValid)
                {
                    entity.AddGameText(args.Type, args.Text, (byte)args.Font, args.Hue, args.IsUnicode);
                    Service.Get <JournalData>().AddEntry(args.Text, (byte)args.Font, args.Hue, entity.Name);
                }

                break;

            case MessageType.Party:
                Service.Get <ChatControl>().AddLine($"[Party] [{entity.Name}]: {args.Text}", (byte)args.Font, args.Hue, args.IsUnicode);
                Service.Get <JournalData>().AddEntry(args.Text, (byte)args.Font, args.Hue, "Party");

                break;

            case MessageType.Guild:

                break;

            case MessageType.Alliance:

                break;

            case MessageType.Command:

                break;

            case MessageType.Encoded:

                break;

            default:

                throw new ArgumentOutOfRangeException();
            }

            Message.Raise(args, entity ?? _system);
        }
 protected override void OnLoad()
 {
     btnClose.onClick.AddListener(() => Message.Send <SkinBuyDialogCloseMsg>(new SkinBuyDialogCloseMsg()));
     btnBackGround.onClick.AddListener(() => Message.Send <SkinBuyDialogCloseMsg>(new SkinBuyDialogCloseMsg()));
     btnOK.onClick.AddListener(() => Message.Send <StorBuySkinMsg>(new StorBuySkinMsg(isBuy, index)));
 }
 protected override void WndProc(ref Message message)
 {
     if (message.Msg == 0x0084) // WM_NCHITTEST
         message.Result = (IntPtr)1;
     else base.WndProc(ref message);
 }
Example #44
0
        public Task HandleConsumer <TConsumer>(string topicPath, string subscriptionName, Message message, CancellationToken cancellationToken)
            where TConsumer : class, IConsumer
        {
            var receiver = CreateBrokeredMessageReceiver(topicPath, subscriptionName, cfg =>
            {
                cfg.ConfigureConsumer <TConsumer>(_registration);
            });

            return(receiver.Handle(message, cancellationToken));
        }
Example #45
0
 public GreetingCommand MapToRequest(Message message)
 {
     return JsonConvert.DeserializeObject<GreetingCommand>(message.Body.Value);
 }
Example #46
0
 private string GetMessage(Message message)
 {
     return(message.Body);
 }
Example #47
0
 /// <inheritdoc />
 public override bool CanHandle(Message message) => message is BlockMessage;
 void IClientMessageInspector.AfterReceiveReply(ref Message reply, object correlationState)
 { }
Example #49
0
		protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
		{
			if (keyData == Keys.Escape) 
				this.Close();
			return base.ProcessCmdKey(ref msg, keyData);
		}
Example #50
0
 public void GetHashThrowsIfNoKeyProperties()
 {
     Expect.Throws(() => new CompositeKeyRepoThrowsData().GetHashCode(), (ex) => Message.PrintLine("Exception thrown as expected: {0}", ConsoleColor.Green, ex.Message));
     Expect.Throws(() => new CompositeKeyRepoThrowsData().GetLongKeyHash(), (ex) => Message.PrintLine("Exception thrown as expected: {0}", ConsoleColor.Green, ex.Message));
 }
Example #51
0
 IMenuContactReplyToMessage IMenuContactCancellationToken.ReplyToMessage(int messageId)
 {
     ReplyToMessage = new Message {
         MessageId = messageId
     }; return(this);
 }
Example #52
0
 private void OpenMenu(Message msg)
 {
     OpenMenu();
 }
        private object SetupServiceConfig(InstanceContext instanceContext, Message message)
        {
            object obj2 = new CServiceConfig();
            IServiceThreadPoolConfig config = (IServiceThreadPoolConfig)obj2;

            switch (this.info.ThreadingModel)
            {
            case ThreadingModel.MTA:
                config.SelectThreadPool(System.ServiceModel.ComIntegration.ThreadPoolOption.MTA);
                break;

            case ThreadingModel.STA:
                config.SelectThreadPool(System.ServiceModel.ComIntegration.ThreadPoolOption.STA);
                break;

            default:
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.UnexpectedThreadingModel());
            }
            config.SetBindingInfo(System.ServiceModel.ComIntegration.BindingOption.BindingToPoolThread);
            if (this.info.HasUdts())
            {
                IServiceSxsConfig config2 = obj2 as IServiceSxsConfig;
                if (config2 == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.QFENotPresent());
                }
                lock (manifestLock)
                {
                    string directory = string.Empty;
                    try
                    {
                        directory = Path.GetTempPath();
                    }
                    catch (Exception exception)
                    {
                        if (Fx.IsFatal(exception))
                        {
                            throw;
                        }
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.CannotAccessDirectory(directory));
                    }
                    string path = directory + this.info.AppID.ToString() + @"\";
                    if (!Directory.Exists(path))
                    {
                        try
                        {
                            Directory.CreateDirectory(path);
                        }
                        catch (Exception exception2)
                        {
                            if (Fx.IsFatal(exception2))
                            {
                                throw;
                            }
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.CannotAccessDirectory(path));
                        }
                        Guid[] assemblies = this.info.Assemblies;
                        ComIntegrationManifestGenerator.GenerateManifestCollectionFile(assemblies, path + manifestFileName + ".manifest", manifestFileName);
                        foreach (Guid guid in assemblies)
                        {
                            System.Type[] types = this.info.GetTypes(guid);
                            if (types.Length > 0)
                            {
                                string assemblyName = guid.ToString();
                                ComIntegrationManifestGenerator.GenerateWin32ManifestFile(types, path + assemblyName + ".manifest", assemblyName);
                            }
                        }
                    }
                    config2.SxsConfig(CSC_SxsConfig.CSC_NewSxs);
                    config2.SxsName(manifestFileName + ".manifest");
                    config2.SxsDirectory(path);
                }
            }
            if (this.info.PartitionId != DefaultPartitionId)
            {
                IServicePartitionConfig config3 = (IServicePartitionConfig)obj2;
                config3.PartitionConfig(System.ServiceModel.ComIntegration.PartitionOption.New);
                config3.PartitionID(this.info.PartitionId);
            }
            IServiceTransactionConfig config4 = (IServiceTransactionConfig)obj2;

            config4.ConfigureTransaction(TransactionConfig.NoTransaction);
            if ((this.info.TransactionOption == TransactionOption.Required) || (this.info.TransactionOption == TransactionOption.Supported))
            {
                Transaction messageTransaction = null;
                messageTransaction = MessageUtil.GetMessageTransaction(message);
                if (messageTransaction != null)
                {
                    System.ServiceModel.ComIntegration.TransactionProxy item = new System.ServiceModel.ComIntegration.TransactionProxy(this.info.AppID, this.info.Clsid);
                    item.SetTransaction(messageTransaction);
                    instanceContext.Extensions.Add(item);
                    IServiceSysTxnConfig config5 = (IServiceSysTxnConfig)config4;
                    IntPtr pITxByot = TransactionProxyBuilder.CreateTransactionProxyTearOff(item);
                    config5.ConfigureBYOTSysTxn(pITxByot);
                    Marshal.Release(pITxByot);
                }
            }
            return(obj2);
        }
		public void Release(Message message) {
            pool.Free((MessageMbtQuotes)message);
		}
 protected void AssertMessageHandled(Message originalMessage, Message handledMessage)
 {
     var comparer = new MessageEqualityComparer(HeaderName.SecurityToken);
     Assert.NotNull(handledMessage);
     Assert.Equal(originalMessage, handledMessage, comparer);
 }
        public async Task SendMessage(Message message)
        {
            var sender = GetSender();

            await SendMessage(sender, message).ConfigureAwait(false);
        }
Example #57
0
        /// <summary>
        /// Wraps sending messages to the connected descriptor
        /// </summary>
        /// <param name="strings">the output</param>
        /// <returns>success status</returns>
        public bool SendOutput(IEnumerable <string> strings)
        {
            //TODO: Stop hardcoding this but we have literally no sense of injury/self status yet
            SelfStatus self = new SelfStatus
            {
                Body = new BodyStatus
                {
                    Health  = _currentPlayer.CurrentHealth == 0 ? 100 : 100 / (2M * _currentPlayer.CurrentHealth),
                    Stamina = _currentPlayer.CurrentStamina,
                    Overall = OverallStatus.Excellent,
                    Anatomy = new AnatomicalPart[] {
                        new AnatomicalPart {
                            Name    = "Arm",
                            Overall = OverallStatus.Good,
                            Wounds  = new string[] {
                                "Light scrape"
                            }
                        },
                        new AnatomicalPart {
                            Name    = "Leg",
                            Overall = OverallStatus.Excellent,
                            Wounds  = new string[] {
                            }
                        }
                    }
                },
                CurrentActivity = _currentPlayer.CurrentAction,
                Balance         = _currentPlayer.Balance.ToString(),
                CurrentArt      = _currentPlayer.LastAttack?.Name ?? "",
                CurrentCombo    = _currentPlayer.LastCombo?.Name ?? "",
                CurrentTarget   = _currentPlayer.GetTarget() == null ? ""
                                                                   : _currentPlayer.GetTarget() == _currentPlayer
                                                                        ? "Your shadow"
                                                                        : _currentPlayer.GetTarget().GetDescribableName(_currentPlayer),
                CurrentTargetHealth = _currentPlayer.GetTarget() == null || _currentPlayer.GetTarget() == _currentPlayer ? double.PositiveInfinity
                                                                        : _currentPlayer.GetTarget().CurrentHealth == 0 ? 100 : 100 / (2 * _currentPlayer.CurrentHealth),
                Position  = _currentPlayer.StancePosition.ToString(),
                Stance    = _currentPlayer.Stance,
                Stagger   = _currentPlayer.Stagger.ToString(),
                Qualities = string.Join("", _currentPlayer.Qualities.Where(quality => quality.Visible).Select(quality => string.Format("<div class='qualityRow'><span>{0}</span><span>{1}</span></div>", quality.Name, quality.Value))),
                CurrentTargetQualities = _currentPlayer.GetTarget() == null || _currentPlayer.GetTarget() == _currentPlayer ? ""
                                                                            : string.Join("", _currentPlayer.GetTarget().Qualities.Where(quality => quality.Visible).Select(quality => string.Format("<div class='qualityRow'><span>{0}</span><span>{1}</span></div>", quality.Name, quality.Value))),
                Mind = new MindStatus
                {
                    Overall = OverallStatus.Excellent,
                    States  = new string[]
                    {
                        "Fearful"
                    }
                }
            };

            IGlobalPosition currentLocation  = _currentPlayer.CurrentLocation;
            IContains       currentContainer = currentLocation.CurrentLocation();
            IZone           currentZone      = currentContainer.CurrentLocation.CurrentZone;
            ILocale         currentLocale    = currentLocation.CurrentLocale;
            IRoom           currentRoom      = currentLocation.CurrentRoom;
            IGaia           currentWorld     = currentZone.GetWorld();

            IEnumerable <string> pathways  = Enumerable.Empty <string>();
            IEnumerable <string> inventory = Enumerable.Empty <string>();
            IEnumerable <string> populace  = Enumerable.Empty <string>();
            string locationDescription     = string.Empty;

            LexicalContext lexicalContext = new LexicalContext(_currentPlayer)
            {
                Language    = _currentPlayer.Template <IPlayerTemplate>().Account.Config.UILanguage,
                Perspective = NarrativePerspective.SecondPerson,
                Position    = LexicalPosition.Near
            };

            Message toCluster = new Message(currentContainer.RenderToVisible(_currentPlayer));

            if (currentContainer != null)
            {
                pathways            = ((ILocation)currentContainer).GetPathways().Select(data => data.GetDescribableName(_currentPlayer));
                inventory           = currentContainer.GetContents <IInanimate>().Select(data => data.GetDescribableName(_currentPlayer));
                populace            = currentContainer.GetContents <IMobile>().Where(player => !player.Equals(_currentPlayer)).Select(data => data.GetDescribableName(_currentPlayer));
                locationDescription = toCluster.Unpack(TargetEntity.Actor, lexicalContext);
            }

            LocalStatus local = new LocalStatus
            {
                ZoneName            = currentZone?.TemplateName,
                LocaleName          = currentLocale?.TemplateName,
                RoomName            = currentRoom?.TemplateName,
                Inventory           = inventory.ToArray(),
                Populace            = populace.ToArray(),
                Exits               = pathways.ToArray(),
                LocationDescriptive = locationDescription
            };

            //The next two are mostly hard coded, TODO, also fix how we get the map as that's an admin thing
            ExtendedStatus extended = new ExtendedStatus
            {
                Horizon = new string[]
                {
                    "A hillside",
                    "A dense forest"
                },
                VisibleMap = currentLocation.CurrentRoom == null ? string.Empty : currentLocation.CurrentRoom.RenderCenteredMap(3, true)
            };

            string timeOfDayString = string.Format("The hour of {0} in the day of {1} in {2} in the year of {3}", currentWorld.CurrentTimeOfDay.Hour
                                                   , currentWorld.CurrentTimeOfDay.Day
                                                   , currentWorld.CurrentTimeOfDay.MonthName()
                                                   , currentWorld.CurrentTimeOfDay.Year);

            string sun              = "0";
            string moon             = "0";
            string visibilityString = "5";
            Tuple <string, string, string[]> weatherTuple = new Tuple <string, string, string[]>("", "", new string[] { });

            if (currentZone != null)
            {
                Tuple <PrecipitationAmount, PrecipitationType, HashSet <WeatherType> > forecast = currentZone.CurrentForecast();
                weatherTuple = new Tuple <string, string, string[]>(forecast.Item1.ToString(), forecast.Item2.ToString(), forecast.Item3.Select(wt => wt.ToString()).ToArray());

                visibilityString = currentZone.GetCurrentLuminosity().ToString();

                if (currentWorld != null)
                {
                    IEnumerable <ICelestial> bodies = currentZone.GetVisibileCelestials(_currentPlayer);
                    ICelestial theSun  = bodies.FirstOrDefault(cest => cest.Name.Equals("sun", StringComparison.InvariantCultureIgnoreCase));
                    ICelestial theMoon = bodies.FirstOrDefault(cest => cest.Name.Equals("moon", StringComparison.InvariantCultureIgnoreCase));

                    if (theSun != null)
                    {
                        ICelestialPosition celestialPosition = currentWorld.CelestialPositions.FirstOrDefault(celest => celest.CelestialObject == theSun);

                        sun = AstronomicalUtilities.GetCelestialLuminosityModifier(celestialPosition.CelestialObject, celestialPosition.Position, currentWorld.PlanetaryRotation
                                                                                   , currentWorld.OrbitalPosition, currentZone.Template <IZoneTemplate>().Hemisphere, currentWorld.Template <IGaiaTemplate>().RotationalAngle).ToString();
                    }

                    if (theMoon != null)
                    {
                        ICelestialPosition celestialPosition = currentWorld.CelestialPositions.FirstOrDefault(celest => celest.CelestialObject == theMoon);

                        moon = AstronomicalUtilities.GetCelestialLuminosityModifier(celestialPosition.CelestialObject, celestialPosition.Position, currentWorld.PlanetaryRotation
                                                                                    , currentWorld.OrbitalPosition, currentZone.Template <IZoneTemplate>().Hemisphere, currentWorld.Template <IGaiaTemplate>().RotationalAngle).ToString();
                    }
                }
            }

            EnvironmentStatus environment = new EnvironmentStatus
            {
                Sun         = sun,
                Moon        = moon,
                Visibility  = visibilityString,
                Weather     = weatherTuple,
                Temperature = currentZone.EffectiveTemperature().ToString(),
                Humidity    = currentZone.EffectiveHumidity().ToString(),
                TimeOfDay   = timeOfDayString
            };

            OutputStatus outputFormat = new OutputStatus
            {
                Occurrence  = EncapsulateOutput(strings),
                Self        = self,
                Local       = local,
                Extended    = extended,
                Environment = environment
            };

            Send(Utility.SerializationUtility.Serialize(outputFormat));

            return(true);
        }
Example #58
0
        private void Request <T>(RpcRequest request, ICallback <T> callback)
        {
            Transceiver t = transceiver;

            if (!t.IsConnected)
            {
                Monitor.Enter(handshakeLock);
                handshakeThread = Thread.CurrentThread;

                try
                {
                    if (!t.IsConnected)
                    {
                        var callFuture             = new CallFuture <T>(callback);
                        IList <MemoryStream> bytes = request.GetBytes(Local, this);
                        var transceiverCallback    = new TransceiverCallback <T>(this, request, callFuture, Local);

                        t.Transceive(bytes, transceiverCallback);

                        // Block until handshake complete
                        callFuture.Wait();
                        Message message = GetMessage(request);
                        if (message.Oneway.GetValueOrDefault())
                        {
                            Exception error = callFuture.Error;
                            if (error != null)
                            {
                                throw error;
                            }
                        }
                        return;
                    }
                }
                finally
                {
                    if (Thread.CurrentThread == handshakeThread)
                    {
                        handshakeThread = null;
                        Monitor.Exit(handshakeLock);
                    }
                }
            }

            if (GetMessage(request).Oneway.GetValueOrDefault())
            {
                t.LockChannel();
                try
                {
                    IList <MemoryStream> bytes = request.GetBytes(Local, this);
                    t.WriteBuffers(bytes);
                    if (callback != null)
                    {
                        callback.HandleResult(default(T));
                    }
                }
                finally
                {
                    t.UnlockChannel();
                }
            }
            else
            {
                IList <MemoryStream> bytes = request.GetBytes(Local, this);
                var transceiverCallback    = new TransceiverCallback <T>(this, request, callback, Local);

                t.Transceive(bytes, transceiverCallback);

                //if (Thread.CurrentThread == handshakeThread)
                //{
                //    Monitor.Exit(handshakeLock);
                //}
            }
        }
Example #59
0
 IMenuContactReplyToMessage IMenuContactCancellationToken.ReplyToMessage(Message message)
 {
     ReplyToMessage = message; return(this);
 }
Example #60
0
 public virtual void AfterReceiveReply(ref Message reply, object correlationState)
 {
     HttpResponseMessageProperty prop = (HttpResponseMessageProperty)reply.Properties[HttpResponseMessageProperty.Name];
     string body = General.ReadMessageBody(ref reply);
     logger(General.GetHttpResponseLog(prop.StatusCode.ToString(), prop.Headers, body));
 }