private static void ImportMessageSoapAction(WsdlContractConversionContext contractContext, MessageDescription message, MessageBinding wsdlMessageBinding, bool isResponse)
        {
            string soapAction = SoapHelper.ReadSoapAction(wsdlMessageBinding.OperationBinding);

            if (contractContext != null)
            {
                OperationMessage wsdlOperationMessage = contractContext.GetOperationMessage(message);
                string           wsaAction            = WsdlImporter.WSAddressingHelper.FindWsaActionAttribute(wsdlOperationMessage);
                if (wsaAction == null && soapAction != null)
                {
                    if (isResponse)
                    {
                        message.Action = "*";
                    }
                    else
                    {
                        message.Action = soapAction;
                    }
                }
                //CONSIDER, hsomu: If WS-Addressing action was found, we should verify that it is the same as the SOAP action
                //      (for the request message).
            }
            else
            {
                //CONSIDER, hsomu: verify SOAP action matches referenced contract.operation.message
            }
        }
    private TreeNode MessageToTreeNode(OperationMessage omsg, SoapBindingUse use)
    {
        Message msg = _services.GetMessage(omsg.Message);

        TreeNode node = new TreeNode();

        WSDLParser.SchemaParser ngen = new WSDLParser.SchemaParser(_schemas);

        ngen.BindingUse = use;

        foreach (MessagePart part in msg.Parts)
        {
            if (part.Element == XmlQualifiedName.Empty)
            {
                TreeNode partNode = ngen.Translate(part.Type);
                partNode.ImageIndex         = 5;
                partNode.SelectedImageIndex = 5;

                partNode.Text = part.Name;
                node.Nodes.Add(partNode);
            }
            else
            {
                TreeNode partNode = ngen.Translate(part.Element);
                partNode.ImageIndex         = 5;
                partNode.SelectedImageIndex = 5;

                partNode.Text = part.Name;
                node.Nodes.Add(partNode);
            }
        }

        return(node);
    }
Example #3
0
        public string GenerateMessage(Port port, OperationBinding obin, Operation oper, string protocol, bool generateInput)
        {
            OperationMessage msg = null;

            foreach (OperationMessage opm in oper.Messages)
            {
                if (opm is OperationInput && generateInput)
                {
                    msg = opm;
                }
                else if (opm is OperationOutput && !generateInput)
                {
                    msg = opm;
                }
            }
            if (msg == null)
            {
                return(null);
            }

            switch (protocol)
            {
            case "Soap":
                return(GenerateHttpSoapMessage(port, obin, oper, msg));

            case "HttpGet":
                return(GenerateHttpGetMessage(port, obin, oper, msg));

            case "HttpPost":
                return(GenerateHttpPostMessage(port, obin, oper, msg));
            }
            return("Unknown protocol");
        }
Example #4
0
 private Task HandleMessageAsync(OperationMessage op, IConnectionContext connection)
 {
     return(_messagingProtocolHandler.HandleMessageAsync(
                new OperationMessageContext(
                    connection,
                    op)));
 }
        /// <summary>
        /// Contructor
        /// </summary>
        /// <param name="callingModule">Reference to the calling module</param>
        /// <param name="opcode">OPCode used for the outgoing messages</param>
        /// <param name="statusCodeType">Type of the enum for status code parsing on error</param>
        /// <param name="destinationAddress">Destination node address</param>
        /// <param name="content">Content to send in bytes</param>
        public FragmentWriteTransaction(ModuleBase callingModule, OperationMessage.OPCodes opcode, Type statusCodeType, ushort destinationAddress, byte[] content)
        {
            this.callingModule             = callingModule;
            this.operationResponseOPCode   = (OperationMessage.OPCodes)((int)opcode + 1);
            this.applicationStatusCodeType = statusCodeType;

            this.OpCode             = opcode;
            this.DestinationAddress = destinationAddress;

            this.outputBuffer = new List <OperationMessage>();

            this.totalFragments = (byte)(content.Length / MAX_CONTENT_SIZE);

            for (byte i = 0; i <= this.totalFragments; i++)
            {
                this.CurrentFrameSize = Math.Min(MAX_CONTENT_SIZE, content.Length - (i * MAX_CONTENT_SIZE));

                OperationMessage currentOp = new OperationMessage()
                {
                    SourceAddress      = 0x00,
                    DestinationAddress = destinationAddress,
                    OpCode             = OperationMessage.OPCodes.ConfigWrite,
                    Args = new byte[this.CurrentFrameSize + 2]
                };

                currentOp.Args[0] = (byte)((this.totalFragments << 4) | (i & 0xF));
                currentOp.Args[1] = (byte)this.CurrentFrameSize;
                Buffer.BlockCopy(content, (i * MAX_CONTENT_SIZE), currentOp.Args, 2, this.CurrentFrameSize);

                this.outputBuffer.Add(currentOp);
            }
        }
Example #6
0
        private async Task <bool> SendJoinAcceptResponse(string macAddress, ushort newAddress, Security security)
        {
            PendingNodeInfo info = this.PendingNodes.FirstOrDefault(n => n.MacAddress == macAddress);

            if (info == null)
            {
                throw new InvalidOperationException("There is no pending node with the specified MAC Address");
            }

            OperationMessage joinAcceptResponse = OperationMessage.JoinAcceptResponse(newAddress, (ushort)security.PanId, (byte)security.Channel, security.SecurityKey, info.TemporalAddress);

            bool result = await this.SendMessage(joinAcceptResponse);

            if (result)
            {
                Debug.WriteLine(string.Format("JOIN ACCEPTED {0} -> NEW ADDRESS: 0x{1:X2}", macAddress, newAddress));

                if (this.NodeJoined != null)
                {
                    NodeJoined(this, macAddress);
                }
            }
            else
            {
                Debug.WriteLine(string.Format("THE NODE {0} DOESN'T RECEIVE THE JOIN ACCEPT RESPONSE", macAddress));
            }

            this.PendingNodes.Remove(info);

            return(result);
        }
        public async Task Receive_start_query()
        {
            /* Given */
            _documentExecuter.ExecuteAsync(null, null, null, null, null).ReturnsForAnyArgs(
                new ExecutionResult());
            var expected = new OperationMessage
            {
                Type    = MessageType.GQL_START,
                Id      = "1",
                Payload = JObject.FromObject(new OperationMessagePayload
                {
                    Query = @"{
  human() {
        name
        height
    }
}"
                })
            };

            _transportReader.AddMessageToRead(expected);
            await _transportReader.Complete();

            /* When */
            await _server.OnConnect();

            /* Then */
            Assert.Empty(_server.Subscriptions);
            Assert.Contains(_transportWriter.WrittenMessages,
                            message => message.Type == MessageType.GQL_DATA);
            Assert.Contains(_transportWriter.WrittenMessages,
                            message => message.Type == MessageType.GQL_COMPLETE);
        }
    public void Writes_OperationMessage_Nulls(IGraphQLTextSerializer serializer)
    {
        var message  = new OperationMessage();
        var actual   = serializer.Serialize(message);
        var expected = @"{}";

        actual.ShouldBeCrossPlatJson(expected);
    }
        void StartOperation(OperationMessage message, IServiceProvider serviceProvider)
        {
            var tokenSource  = new CancellationTokenSource();
            var serviceScope = serviceProvider.CreateScope();

            _activeGraphqlOperations.Add(message.Id, new OperationContext(message.Id, serviceScope, tokenSource));
            ExecuteOperationAsync(message.Id, message.Payload.ToObject <GraphQlRequest>(), serviceScope.ServiceProvider, tokenSource.Token);
        }
 public MessageHandlingContext(IServerOperations server, OperationMessage message)
 {
     _server       = server;
     Reader        = server.TransportReader;
     Writer        = server.TransportWriter;
     Subscriptions = server.Subscriptions;
     Message       = message;
 }
Example #11
0
        public static OperationMessage PercentageDimmer(this Dimmable dimmable, float percentage, byte seconds = 0)
        {
            byte value = (byte)(percentage * 100);

            ushort destinationAddress = (ushort)(dimmable.Connector == null ? 0 : dimmable.Connector.Node.Address);

            return(OperationMessage.DimmerWrite((ushort)dimmable.Id, value, seconds, destinationAddress));
        }
Example #12
0
        /// <inheritdoc />
        public async Task <IGraphQLSubscriptionOperation <T> > ExecuteOperation <T>(params GraphQLQueryArgument[] arguments) where T : class
        {
            if (!IsConnected)
            {
                throw new InvalidOperationException("Websocket is not connected");
            }

            if (!IsInitilized)
            {
                throw new InvalidOperationException("GraphQLSubscriptionClient is not initilized");
            }

            // Get operationId
            long operationId;

            lock (_locker)
            {
                operationId = _operationCounter++;
            }

            // Get query
            var selectionSet = FieldBuilder.GenerateSelectionSet(typeof(T));
            var query        = QueryGenerator.GenerateQuery(GraphQLOperationType.Subscription, selectionSet, arguments);

            // Generate OperationMessage for starting the operation
            var message = new OperationMessage
            {
                Id      = operationId.ToString(),
                Type    = MessageType.GQL_START,
                Payload = JsonConvert.DeserializeObject(query)
            };

            // Generate stop message
            var stopMessage = new OperationMessage
            {
                Id   = operationId.ToString(),
                Type = MessageType.GQL_STOP
            };

            // Create GraphQLOperationSource
            var operationSource = new GraphQLOperationSource(() =>
            {
                // Generate stop
                return(SendOperationMessage(stopMessage));
            });

            // Create IGraphQLSubscriptionOperation
            var subscription = new GraphQLSubscriptionOperation <T>(operationSource, selectionSet, Deserialization);

            // Add to list
            _operations.Add(operationId.ToString(), operationSource);

            // Send subscribe message
            await SendOperationMessage(message).ConfigureAwait(false);

            // Return the subscription
            return(subscription);
        }
        private void executerCallback(OperationMessage message)
        {
            if (message.Type == OperationType.GraphqlError || message.Type == OperationType.GraphqlComplete)
            {
                CancelOperation(message.Id);
            }

            OnNewOperationMessage(message);
        }
    public static void Main()
    {
        try
        {
            // Read the 'MathService_Input_cs.wsdl' file.
            ServiceDescription myDescription =
                ServiceDescription.Read("MathService_Input_cs.wsdl");
            PortTypeCollection myPortTypeCollection = myDescription.PortTypes;
            // Get the 'OperationCollection' for 'SOAP' protocol.
            OperationCollection myOperationCollection =
                myPortTypeCollection[0].Operations;
            Operation myOperation = new Operation();
            myOperation.Name = "Add";
            OperationMessage myOperationMessageInput =
                (OperationMessage) new OperationInput();
            myOperationMessageInput.Message = new XmlQualifiedName
                                                  ("AddSoapIn", myDescription.TargetNamespace);
            OperationMessage myOperationMessageOutput =
                (OperationMessage) new OperationOutput();
            myOperationMessageOutput.Message = new XmlQualifiedName(
                "AddSoapOut", myDescription.TargetNamespace);
            myOperation.Messages.Add(myOperationMessageInput);
            myOperation.Messages.Add(myOperationMessageOutput);
            myOperationCollection.Add(myOperation);

            if (myOperationCollection.Contains(myOperation) == true)
            {
                Console.WriteLine("The index of the added 'myOperation' " +
                                  "operation is : " +
                                  myOperationCollection.IndexOf(myOperation));
            }

            myOperationCollection.Remove(myOperation);
            // Insert the 'myOpearation' operation at the index '0'.
            myOperationCollection.Insert(0, myOperation);
            Console.WriteLine("The operation at index '0' is : " +
                              myOperationCollection[0].Name);

            Operation[] myOperationArray = new Operation[
                myOperationCollection.Count];
            myOperationCollection.CopyTo(myOperationArray, 0);
            Console.WriteLine("The operation(s) in the collection are :");
            for (int i = 0; i < myOperationCollection.Count; i++)
            {
                Console.WriteLine(" " + myOperationArray[i].Name);
            }

            myDescription.Write("MathService_New_cs.wsdl");
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception caught!!!");
            Console.WriteLine("Source : " + e.Source);
            Console.WriteLine("Message : " + e.Message);
        }
    }
Example #15
0
        private async void button3_Click(object sender, EventArgs e)
        {
            var userMod = CommunicationManager.Instance.FindModule <UserModule>();

            Debug.WriteLine("Dimmer at " + dimmerValue);

            await userMod.SendMessage(OperationMessage.DimmerWrite(1, dimmerValue, 0, 0x02));

            dimmerValue = (byte)((dimmerValue + 10) % 130);
        }
        /// <summary>
        ///     Generate the a list item for a <see cref="OperationMessage" />.
        /// </summary>
        /// <param name="message">The <see cref="OperationMessage" /> instance.</param>
        /// <param name="useTwoLineMode">If the two line mode should be used.</param>
        /// <returns>The generated HTML content which represent as a HTML list item.</returns>
        private IHtmlContent GenerateNormalItem(OperationMessage message, bool useTwoLineMode)
        {
            var tag = new TagBuilder("li");

            tag.AddCssClass("list-group-item");
            tag.AddCssClass(LevelClassMapper.MapLevel(message.Level, MessageListStyle.List));
            tag.InnerHtml.AppendHtml(GenerateMessageContent(message, useTwoLineMode));

            return(tag);
        }
Example #17
0
        private int WriteOperationMessage(OperationMessage message, PipeWriter output)
        {
            var json = JsonConvert.SerializeObject(message, Formatting.None, _settings);

            json += '\n';
            var count  = Encoding.UTF8.GetByteCount(json);
            var memory = output.GetMemory(sizeHint: count);

            return(Encoding.UTF8.GetBytes(json, memory.Span));
        }
Example #18
0
        private OperationMessageContext CreateMessage(string type, object payload)
        {
            var op = new OperationMessage
            {
                Id      = Guid.NewGuid().ToString(),
                Type    = type,
                Payload = payload != null?JObject.FromObject(payload) : null
            };

            return(new OperationMessageContext(_connection, op));
        }
Example #19
0
        private async Task <bool> SendJoinRequestResponse(ushort destinationAddress)
        {
            byte[] RSAKey = new byte[16];
            Random r      = new Random();

            r.NextBytes(RSAKey);

            OperationMessage joinResponse = OperationMessage.JoinRequestResponse(RSAKey, destinationAddress);

            return(await this.SendMessage(joinResponse));
        }
Example #20
0
        private OperationMessageContext CreateMessage(string type, GraphQLQuery payload)
        {
            var op = new OperationMessage
            {
                Id      = Guid.NewGuid().ToString(),
                Type    = type,
                Payload = payload
            };

            return(new OperationMessageContext(_connection, op));
        }
        public override bool RunMethod(OperationMessage message)
        {
            var operation = message.Operation;

            if (operation.PlayerGameItemId == itemHolder.PlayerGameItem.Id)
            {
                //It's my message
                operation.Execute(jsComponent);
            }
            return(true);
        }
Example #22
0
 public SubscriptionHandle(OperationMessage op,
                           IObservable <object> stream,
                           IJsonMessageWriter messageWriter,
                           IDocumentWriter documentWriter)
 {
     Op              = op;
     Stream          = stream;
     _messageWriter  = messageWriter;
     _documentWriter = documentWriter;
     Unsubscribe     = stream.SubscribeAsync(OnNext, OnError, OnCompleted);
 }
Example #23
0
        private async Task HandleModifyOperationMessage(WebSocketClient client, OperationMessage modifyOperationMessage)
        {
            using (await Lock.LockAsync())
            {
                var modifiedOperation = await DbUtils.ModifyOperation(client, modifyOperationMessage.GetOperation());

                Broadcast(client.User.TeamId, new WebSocketServerMessage()
                {
                    ModifyOperationMessage = new OperationMessage(modifiedOperation)
                });
            }
        }
Example #24
0
        void WriteBody(XmlTextWriter xtw, Operation oper, OperationMessage opm, SoapBodyBinding sbb, SoapBindingStyle style)
        {
            Message msg = descriptions.GetMessage(opm.Message);

            if (msg.Parts.Count > 0 && msg.Parts[0].Name == "parameters")
            {
                MessagePart part = msg.Parts[0];
                if (part.Element == XmlQualifiedName.Empty)
                {
                    WriteTypeSample(xtw, part.Type);
                }
                else
                {
                    WriteRootElementSample(xtw, part.Element);
                }
            }
            else
            {
                string elemName = oper.Name;
                string ns       = "";
                if (opm is OperationOutput)
                {
                    elemName += "Response";
                }

                if (style == SoapBindingStyle.Rpc)
                {
                    xtw.WriteStartElement(elemName, sbb.Namespace);
                    ns = sbb.Namespace;
                }

                foreach (MessagePart part in msg.Parts)
                {
                    if (part.Element == XmlQualifiedName.Empty)
                    {
                        XmlSchemaElement elem = new XmlSchemaElement();
                        elem.SchemaTypeName = part.Type;
                        elem.Name           = part.Name;
                        WriteElementSample(xtw, ns, elem);
                    }
                    else
                    {
                        WriteRootElementSample(xtw, part.Element);
                    }
                }

                if (style == SoapBindingStyle.Rpc)
                {
                    xtw.WriteEndElement();
                }
            }
            WriteQueuedTypeSamples(xtw);
        }
Example #25
0
 /// <summary>
 /// Compare two messages in operations (with same name)
 /// </summary>
 /// <remarks></remarks>
 private bool MatchOperationMessages(OperationMessage x, OperationMessage y)
 {
     if (x == null && y == null)
     {
         return(true);
     }
     else if (x == null || y == null)
     {
         return(false);
     }
     return(MatchXmlQualifiedNames(x.Message, y.Message));
 }
        public void SendOperationMessage(OperationMessage operationMessage)
        {
            switch (operationMessage.Type)
            {
            case OperationType.GraphqlStart:
                StartOperation(operationMessage, _provider);
                break;

            case OperationType.GraphqlStop:
                CancelOperation(operationMessage.Id);
                break;
            }
        }
Example #27
0
 internal async ValueTask ReceiveMessageAsync(
     OperationMessage message,
     CancellationToken cancellationToken)
 {
     if (!_disposed)
     {
         try
         {
             await _channel.Writer.WriteAsync(message, cancellationToken).ConfigureAwait(false);
         }
         catch (ChannelClosedException) { }
     }
 }
Example #28
0
        private int WriteOperationMessage(OperationMessage message, PipeWriter output)
        {
            var jsonBytes = JsonSerializer.SerializeToUtf8Bytes(message, _messageSerializerOptions);

            byte[] messageBytes = new byte[jsonBytes.Length + 1];
            jsonBytes.CopyTo(messageBytes, 0);
            _separatorBytes.CopyTo(messageBytes, jsonBytes.Length);

            var memory = output.GetMemory(sizeHint: messageBytes.Length);

            messageBytes.CopyTo(memory);
            return(messageBytes.Length);
        }
Example #29
0
        public void Identify(bool resetCounter = true)
        {
            this.ConnectionState = ConnectionStates.Identifying;

            this.SendInternalMessage(OperationMessage.PingRequest());

            if (resetCounter)
            {
                this.retriesCount = 0;
            }

            identifyTimeoutTimer.Start();
        }
        void CheckOperationMessage(OperationMessage opmsg, string msg, Type type, string action)
        {
            Assert.AreEqual(type, opmsg.GetType(), "#com1");
            Assert.AreEqual(msg, opmsg.Message.ToString(), "#com2");
            Assert.AreEqual(0, opmsg.Extensions.Count, "#com3");
            Assert.AreEqual(1, opmsg.ExtensibleAttributes.Length, "#com4");
            Assert.IsNull(opmsg.Name, "#com5");

            XmlAttribute attr = opmsg.ExtensibleAttributes [0];

            Assert.AreEqual("Action", attr.LocalName, "#ca1");
            Assert.AreEqual("http://www.w3.org/2006/05/addressing/wsdl", attr.NamespaceURI, "#ca2");
            Assert.AreEqual(action, attr.Value, "#ca3");
        }
		/// <summary>
		///     Add a new message into the message collection.
		/// </summary>
		/// <param name="collection">The collection of messages to be adding the new message.</param>
		/// <param name="level">The level of the new message.</param>
		/// <param name="title">The title of the new message.</param>
		/// <param name="description">The detailed description of the new message.</param>
		/// <returns>The newly added <see cref="OperationMessage" /> object.</returns>
		/// <exception cref="ArgumentNullException"><paramref name="collection" /> is <c>null</c>.</exception>
		public static OperationMessage Add([NotNull] this ICollection<OperationMessage> collection,
			OperationMessageLevel level, [CanBeNull] [LocalizationRequired] string title,
			[CanBeNull] [LocalizationRequired] string description = null)
		{
			if (collection == null)
			{
				throw new ArgumentNullException(nameof(collection));
			}

			var item = new OperationMessage(level, title, description);
			collection.Add(item);

			return item;
		}
		/// <summary>
		///     Generate the HTML content for a <see cref="OperationMessage" />.
		/// </summary>
		/// <param name="message">The <see cref="OperationMessage" /> instance.</param>
		/// <param name="useTwoLineMode">If the two line mode should be used.</param>
		/// <returns>The generated HTML content.</returns>
		private static IHtmlContent GenerateMessageContent(OperationMessage message, bool useTwoLineMode)
		{
			var result = new DefaultTagHelperContent();

			// Title
			result.AppendHtml(GenerateTitle(message.Title));

			// If description exists, add it
			if (!string.IsNullOrEmpty(message.Description))
			{
				// Add a newline for two line mode.
				if (useTwoLineMode)
				{
					// TODO: Consider a better way
					result.Append("<br />");
				}

				result.AppendHtml(GenerateDescrption(message.Description));
			}

			return result;
		}
		/// <summary>
		///     Generate the a list item for a <see cref="OperationMessage" />.
		/// </summary>
		/// <param name="message">The <see cref="OperationMessage" /> instance.</param>
		/// <param name="useTwoLineMode">If the two line mode should be used.</param>
		/// <returns>The generated HTML content which represent as a HTML list item.</returns>
		private IHtmlContent GenerateNormalItem(OperationMessage message, bool useTwoLineMode)
		{
			var tag = new TagBuilder("li");

			tag.AddCssClass("list-group-item");
			tag.AddCssClass(LevelClassMapper.MapLevel(message.Level, MessageListStyle.List));
			tag.InnerHtml.AppendHtml(GenerateMessageContent(message, useTwoLineMode));

			return tag;
		}
		/// <summary>
		///     Generate the a alert dialog for a <see cref="OperationMessage" />.
		/// </summary>
		/// <param name="message">The <see cref="OperationMessage" /> instance.</param>
		/// <param name="isClosable">If the alert dialog is closable.</param>
		/// <param name="useTwoLineMode">If the two line mode should be used.</param>
		/// <returns>The generated HTML content which represent as a HTML alert dialog.</returns>
		private IHtmlContent GenerateAlertItem(OperationMessage message, bool isClosable, bool useTwoLineMode)
		{
			// Real style
			var listStyle = isClosable ? MessageListStyle.AlertDialogClosable : MessageListStyle.AlertDialog;

			var tag = new TagBuilder("div");

			tag.AddCssClass("alert");
			tag.AddCssClass(LevelClassMapper.MapLevel(message.Level, listStyle));

			// Closable handling
			if (isClosable)
			{
				tag.AddCssClass("alert-dismissible");
			}

			tag.MergeAttribute("role", "alert");

			var content = new DefaultTagHelperContent();

			if (isClosable)
			{
				// Close button
				// TODO: Localization the "label" text
				content.AppendHtml(
					"<button type =\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>");
			}

			content.AppendHtml(GenerateMessageContent(message, useTwoLineMode));

			// Internal content
			tag.InnerHtml.AppendHtml(content);

			return tag;
		}
	// Methods
	public int Add(OperationMessage operationMessage) {}
	public void Insert(int index, OperationMessage operationMessage) {}
	public int IndexOf(OperationMessage operationMessage) {}
	public bool Contains(OperationMessage operationMessage) {}
	public void Remove(OperationMessage operationMessage) {}
	public void CopyTo(OperationMessage[] array, int index) {}