Ejemplo n.º 1
0
        public static async void checkTemp(XBeeController controller, NodeData node, PictureBox pic, int index, int status, int tempmax)
        {
            var         address = node.getAddress(index);
            LongAddress x       = new LongAddress(Convert.ToUInt32(address.Substring(0, 8), 16), Convert.ToUInt32(address.Substring(8, 8), 16));
            NodeAddress a       = new NodeAddress(x);
            //NodeAddress x = new NodeAddress(serialNumber1);
            var remoteNode = await controller.GetRemoteAsync(a);

            var serialNumber2 = await remoteNode.GetTemperature();

            /*if (!checkOver9(serialNumber2.ToString()))
             * {*/
            if (Convert.ToInt32(serialNumber2.ToString(), 16) >= tempmax)
            {
                node.statusUpdate(index, status);
            }

            /*}
             * else
             * {
             *  node.statusUpdate(index, 3);
             * }*/
            pic.Invalidate();
            //MessageBox.Show(x.ToString());
        }
Ejemplo n.º 2
0
        public void Chart_ResetComboBoxAccount()
        {
            comboBoxGraphAccount.Items.Clear();
            string selectedCat    = (string)comboBoxGraphCategory.SelectedItem;
            string selectedInstit = (string)comboBoxGraphInstitution.SelectedItem;
            bool   Activate       = selectedInstit != ChartAllInstitutions &&
                                    selectedInstit != ChartNone;

            if (Activate)
            {
                comboBoxGraphAccount.Items.Add(ChartAllAccounts);
                NodeAddress na = new NodeAddress(NodeType.Institution,
                                                 selectedCat + NodeAddress.Separator + selectedInstit);
                var subNodes = Data.Map.GetSubNodes(na);
                foreach (var item in subNodes)
                {
                    comboBoxGraphAccount.Items.Add(item);
                }
                comboBoxGraphAccount.SelectedItem = ChartAllAccounts;
            }
            else
            {
                comboBoxGraphAccount.Items.Add(ChartNone);
                comboBoxGraphAccount.SelectedItem = ChartNone;
            }
        }
Ejemplo n.º 3
0
        public async Task TestThatThreeNodesRemainSynchronisedAfter10AddsToAllNodes()
        {
            _n1Address = new NodeAddress("127.0.0.1", 6131);
            _n2Address = new NodeAddress("127.0.0.1", 6132);
            _n3Address = new NodeAddress("127.0.0.1", 6133);

            _addresses = new List <NodeAddress> {
                _n1Address, _n2Address, _n3Address
            };

            _node1 = new Node(_n1Address, _addresses);
            _node2 = new Node(_n2Address, _addresses);
            _node3 = new Node(_n3Address, _addresses);

            _state1.WireUpNode(_node1);
            _state2.WireUpNode(_node2);
            _state3.WireUpNode(_node3);

            _state1.LocalAdd("someData1");
            _state2.LocalAdd("someData2");
            _state3.LocalAdd("someData3");
            _state1.LocalAdd("someData4");
            _state2.LocalAdd("someData5");
            _state3.LocalAdd("someData6");
            _state1.LocalAdd("someData7");
            _state2.LocalAdd("someData8");
            _state3.LocalAdd("someData9");
            _state1.LocalAdd("someData10");

            Assert.That(_state1.GetLatestBlock().Transaction.GetData <string>(), Is.EqualTo("someData10"));
            Assert.That(_state2.GetLatestBlock().Transaction.GetData <string>(), Is.EqualTo("someData10"));
            Assert.That(_state3.GetLatestBlock().Transaction.GetData <string>(), Is.EqualTo("someData10"));
        }
Ejemplo n.º 4
0
        public async Task TestThatThreeNodesRemainSynchronisedAfter3KAddsToAllNodesInSequence()
        {
            _n1Address = new NodeAddress("127.0.0.1", 6141);
            _n2Address = new NodeAddress("127.0.0.1", 6142);
            _n3Address = new NodeAddress("127.0.0.1", 6143);

            _addresses = new List <NodeAddress> {
                _n1Address, _n2Address, _n3Address
            };

            _node1 = new Node(_n1Address, _addresses);
            _node2 = new Node(_n2Address, _addresses);
            _node3 = new Node(_n3Address, _addresses);

            _state1.WireUpNode(_node1);
            _state2.WireUpNode(_node2);
            _state3.WireUpNode(_node3);

            var dataCounter = 0;

            for (var i = 0; i < 1000; i++)
            {
                _state1.LocalAdd($"someData{dataCounter++}");
                _state2.LocalAdd($"someData{dataCounter++}");
                _state3.LocalAdd($"someData{dataCounter++}");
            }

            var expected = $"someData{dataCounter - 1}";

            Assert.That(_state1.GetLatestBlock().Transaction.GetData <string>(), Is.EqualTo(expected));
            Assert.That(_state2.GetLatestBlock().Transaction.GetData <string>(), Is.EqualTo(expected));
            Assert.That(_state3.GetLatestBlock().Transaction.GetData <string>(), Is.EqualTo(expected));
        }
Ejemplo n.º 5
0
        public bool ChangeName(string before, string after, NodeAddress nodeTag)
        {
            bool test = false;
            var  data = GetData();

            if (nodeTag.NodeType == NodeType.Category)
            {
                if (!data.ContainsKey(after))
                {
                    Category cat = GetCategory(before);
                    cat.CategoryName = after;
                    //_Data[after] = _Data[before];
                    //_Data.Remove(before);
                    //_Data[after].CategoryName = after;
                    test = true;
                }
            }
            else
            {
                test = GetCategory(nodeTag.Address[0]).ChangeName(before, after, nodeTag);
            }
            if (test)
            {
                _Map.ChangeName(nodeTag, after);
            }
            return(test);
        }
Ejemplo n.º 6
0
 internal XBeeSeries1(XBeeControllerBase controller,
                      HardwareVersion hardwareVersion = HardwareVersion.XBeeSeries1,
                      ushort firmwareVersion          = 0,
                      XBeeProtocol protocol           = XBeeProtocol.Unknown,
                      NodeAddress address             = null) : base(controller, hardwareVersion, firmwareVersion, protocol, address)
 {
 }
Ejemplo n.º 7
0
 internal XBeePro900HP(XBeeControllerBase controller,
                       HardwareVersion hardwareVersion,
                       ushort firmwareVersion,
                       XBeeProtocol protocol,
                       NodeAddress address = null) : base(controller, hardwareVersion, firmwareVersion, protocol, address)
 {
 }
Ejemplo n.º 8
0
        public NodeAddress DeleteItem(NodeAddress na)
        {
            NodeAddress res;

            if (na.NodeType == NodeType.Category)
            {
                if (_Data.Count > 1)
                {
                    _Data.Remove(GetCategory(na.Address[0]));
                    res = _Map.DeleteNode(na);
                }
                else
                {
                    res = na;
                }
            }
            else
            {
                GetElement(na.GetParent()).Delete(na.GetLast());
                res = _Map.DeleteNode(na);
            }
            if (res.IsEqual(na))
            {
                MessageBox.Show($"You cannot delete {na.GetLast()} as it is the last element of [{na.GetParent().GetLabelText()}]!");
            }
            return(res);
        }
Ejemplo n.º 9
0
 public override int ReadPayload(MemoryStream stream, int length)
 {
     //Debug.Assert(length == NodeAddress.LEN + sizeof(short), "G2PacketD : supposed to read " + (NodeAddress.LEN + sizeof(short)) + " but has to read " + length);
     Node   = NodeAddress.ReadNodeAddress(stream);
     length = (short)BinaryUtils.getVariableIntLE(stream, 2);
     return(NodeAddress.LEN + 2);
 }
Ejemplo n.º 10
0
 internal void FillNodeAddress()
 {
     na = new NodeAddress()
     {
         NodeAddressId = Handshake.NodeListeningPort, NodeUId = Handshake.NodeUID, EndPointSID = this.EndPointSID
     };
 }
Ejemplo n.º 11
0
        public void SendToAll(eRaftSignalType signalType, byte[] data, NodeAddress senderNodeAddress, string entityName, bool highPriority = false)
        {
            try
            {
                List <TcpPeer> peers = null;
                _sync.EnterReadLock();
                try
                {
                    peers = Peers.Values.ToList();
                }
                catch (Exception ex)
                {
                    //throw;
                }
                finally
                {
                    _sync.ExitReadLock();
                }

                foreach (var peer in peers)
                {
                    peer.Write(cSprot1Parser.GetSprot1Codec(new byte[] { 00, 02 },
                                                            (
                                                                new TcpMsgRaft()
                    {
                        EntityName = entityName, RaftSignalType = signalType, Data = data
                    }
                                                            ).SerializeBiser()), highPriority);
                }
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 12
0
 public G2PacketS(Header h)
     : base(h)
 {
     this.type = G2PacketType.S;
     Node      = null;
     Timestamp = -1;
 }
Ejemplo n.º 13
0
        /// <summary>
        ///     Create a node.
        /// </summary>
        /// <param name="address">The address of the node or null for the controller node.</param>
        /// <param name="autodetectProtocol">If true query node for hardware version.  Otherwise assume controller version.</param>
        /// <returns>The specified node.</returns>
        public async Task <XBeeNode> GetNodeAsync(NodeAddress address = null, bool autodetectProtocol = true)
        {
            await InitializeAsync().ConfigureAwait(false);

            if (address == null)
            {
                return(Local);
            }

            HardwareVersion hardwareVersion;
            ushort          firmwareVersion;

            if (autodetectProtocol)
            {
                hardwareVersion = await
                                  TaskExtensions.Retry(async() => await GetHardwareVersionAsync(address), TimeSpan.FromSeconds(5),
                                                       typeof(TimeoutException), typeof(AtCommandException)).ConfigureAwait(false);

                firmwareVersion = await
                                  TaskExtensions.Retry(async() => await GetFirmwareVersionAsync(address), TimeSpan.FromSeconds(5),
                                                       typeof(TimeoutException), typeof(AtCommandException)).ConfigureAwait(false);
            }
            else
            {
                hardwareVersion = Local.HardwareVersion;
                firmwareVersion = Local.FirmwareVersion;
            }

            return(CreateNode(hardwareVersion, firmwareVersion, address));
        }
Ejemplo n.º 14
0
        private async Task OnNodeDiscovered(AtCommandResponseFrame frame, CancellationToken cancellationToken)
        {
            var discoveryData = (NetworkDiscoveryResponseData)frame.Content.Data;

            if (NodeDiscovered == null || discoveryData?.LongAddress == null || discoveryData.IsCoordinator)
            {
                return;
            }

            var address = new NodeAddress(discoveryData.LongAddress, discoveryData.ShortAddress);

            // XBees have trouble recovering from discovery
            await Task.Delay(1000, cancellationToken);

            try
            {
                var node = await GetNodeAsync(address);

                var signalStrength = discoveryData.ReceivedSignalStrengthIndicator?.SignalStrength;

                NodeDiscovered?.Invoke(this,
                                       new NodeDiscoveredEventArgs(discoveryData.Name, signalStrength,
                                                                   node));
            }
            catch (TimeoutException)
            {
                /* if we timeout getting the remote node info, no need to bubble up.
                 * We just won't include the node in discovery */
            }
        }
Ejemplo n.º 15
0
        private void CreateRemoteNode()
        {
            if (NodeAddressNumber >= RemoteAddressesList.Count)
            {
                throw new Exception("Node number is not correct, ");
            }
            NodeAddress = RemoteAddressesList[this.NodeAddressNumber];

            if (NodeAddressNumber == 0)
            {
                MainNode = true;
            }

            WorkingRemoteServersCount = RemoteAddressesList.Count;
            RemoteAddressesList.RemoveAt(NodeAddressNumber);


            NodePort = NodeAddress.Split(new[] { ":" }, StringSplitOptions.None)[1];

            foreach (var remoteServer in RemoteAddressesList)
            {
                var remotePushSocket = new PushSocket();
                RemoteServerSockets[remoteServer] = remotePushSocket;
                remotePushSocket.Connect("tcp://" + remoteServer);
            }
        }
Ejemplo n.º 16
0
        /// <summary>Starts the WCF host.</summary>
        /// <exception cref="InvalidOperationException">Occurs if you try to start the host when it is already running.</exception>
        public void Start()
        {
            if (IsStarted())
            {
                throw new InvalidOperationException("Service is already running. Use Stop first.");
            }

            Contract.EndContractBlock();

            try
            {
                StartService();
            }
            catch (Exception)
            {
                if ((StartupPolicy & StartupPolicy.FindNewAddressIfAlreadyInUse) == StartupPolicy.FindNewAddressIfAlreadyInUse)
                {
                    localAddress = GetDefaultNode();
                    ResetLocal();

                    StartService();
                }
                else
                {
                    throw;
                }
            }
        }
Ejemplo n.º 17
0
 internal async void TreeView_AfterLabelEdit(NodeLabelEditEventArgs e)
 {
     string before = e.Node.Text;
     string after  = e.Label;
     await Task.Run(() =>
     {
         bool test = false;
         if (after != null && after != "")
         {
             NodeAddress na = (NodeAddress)e.Node.Tag;
             if (_ad.ChangeName(before, after, na))
             {
                 na.ChangeAddress(after);
                 _view.ChangeActive(na);
                 test = true;
             }
         }
         else
         {
             e.CancelEdit = true;
         }
         _view.SetUpTree(_ad.Map);
         if (!test)
         {
             MessageBox.Show($"Unable to give the element [{before}] the name [{after}]");
         }
     });
 }
Ejemplo n.º 18
0
        /// <summary>Initializes a new instance of the <see cref="InProcessProxyNode"/> class.</summary>
        /// <param name="address">The address.</param>
        /// <param name="network">The network.</param>
        internal InProcessProxyNode(NodeAddress address, InProcessNetwork network)
            : base(address, network)
        {
            this.network = network;

            Id = Guid.NewGuid();
        }
Ejemplo n.º 19
0
        private void RegisterIpAddresses(int nodeId, NodeViewModel node)
        {
            if (node.Ips != null)
            {
                foreach (var ip in node.Ips)
                {
                    var newAddress = new NodeAddress
                    {
                        Ip     = ip,
                        Port   = node.Port,
                        NodeId = nodeId,
                        Type   = Enum.Parse <NodeAddressType>(node.Type)
                    };

                    this.db.NodeAddresses.Add(newAddress);
                    this.db.SaveChanges();
                }
            }
            else if (node.Ip != null)
            {
                var newAddress = new NodeAddress
                {
                    Ip     = node.Ip,
                    Port   = node.Port,
                    NodeId = nodeId,
                    Type   = Enum.Parse <NodeAddressType>(node.Type)
                };

                this.db.NodeAddresses.Add(newAddress);
                this.db.SaveChanges();
            }
        }
Ejemplo n.º 20
0
        public BlockchainDBRepository(
            ILogger logger,
            IAggregateState <ItemMetadata> aggregateState,
            IOptions <NodeAppSettingsOptions> nodeAppSettingsOptions,
            IOptions <NodeP2PSettingsOptions> nodeP2POptions,
            IAzureBlobStore azureBlobStore
            )
        {
            _logger = logger;
            _nodeAppSettingsOptions = nodeAppSettingsOptions.Value;

            _aggregateState = aggregateState;
            _aggregateState.PersistChain = true;

            _azureBlobStore = azureBlobStore;
            _azureBlobStore.Connect();

            var nodeAddress = new NodeAddress("127.0.0.1", nodeP2POptions.Value.Port);
            var addressList = new List <NodeAddress>();

            _p2PNode = new Node(nodeAddress, addressList);

            // wire up P2P behaviours
            _aggregateState.WireUpNode(_p2PNode);

            // setup indices
            _aggregateState.AddIndex(BlobRef_Idx, (item) => item.BlobRef);
            _aggregateState.AddIndex(Metadata_Name_Idx, (item) => item.Name);
            _aggregateState.AddIndex(Metadata_Value_Idx, (item) => item.Value);

            _aggregateState.InitialiseChainFromBlobs();
        }
Ejemplo n.º 21
0
        private static TestServer SetupTestServerForNode(NodeAddress serverNode)
        {
            SampleResponse serverResponse = new SampleResponse(serverNode.Id.ToString());
            var            testServer     = new TestServer(serverNode, serverResponse);

            return(testServer);
        }
Ejemplo n.º 22
0
        /**
         * Creates a new client end of a NetBarrier connected to the barrier with the given index on the given Node
         *
         * @param addr
         *            NodeAddres of the Node that the barrier is located
         * @param vbn
         *            Index of the barrier to connect to
         * @param enrolled
         *            The number of locally enrolled processes
         * @return A new client end of a NetBarrier
         * @//throws JCSPNetworkException
         *             Thrown if something goes wrong in the underlying architecture
         * @//throws ArgumentException
         *             Thrown if the number of enrolled processes is outside the defined range.
         */
        public static NetBarrier netBarrier(NodeAddress addr, int vbn, int enrolled)
        {
            // Get the Link with the given address
            Link link = LinkFactory.getLink(addr);

            NetBarrier barrierToReturn = null;

            try
            {
                barrierToReturn = NetBarrier.create(new NetBarrierLocation(link.remoteID, vbn), enrolled);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e);
            }
            catch (JCSPNetworkException e)
            {
                Console.WriteLine(e);
            }

            return(barrierToReturn);


            // Create a new NetBarrier
            //return NetBarrier.create(new NetBarrierLocation(link.remoteID, vbn), enrolled);
        }
Ejemplo n.º 23
0
        public void SendTo(NodeAddress nodeAddress, eRaftSignalType signalType, byte[] data, NodeAddress myNodeAddress)
        {
            Task.Run(() =>
            {
                foreach (var n in nodes)
                {
                    if (!n.Value.IsRunning)
                    {
                        continue;
                    }

                    if (n.Value.NodeAddress.NodeAddressId == myNodeAddress.NodeAddressId)
                    {
                        continue;       //Skipping sending to self
                    }
                    if (n.Value.NodeAddress.NodeAddressId == nodeAddress.NodeAddressId)
                    {
                        //May be put it all into new Threads or so
                        ((IRaftComReceiver)n.Value).IncomingSignalHandler(myNodeAddress, signalType, data);

                        break;
                    }
                }
            });
        }
Ejemplo n.º 24
0
        public NodeAddress AddItem(NodeAddress nodeAddress)
        {
            switch (nodeAddress.NodeType)
            {
            case NodeType.All:
                break;

            case NodeType.Category:
                Category newCat = AddNewCategory();
                Map.AddItem(nodeAddress, newCat);
                nodeAddress.ChangeAddress(newCat.CategoryName);
                return(nodeAddress);

            case NodeType.Institution:
                Institution newInstit = GetCategory(nodeAddress.Address[0]).AddNewInstitution();
                Map.AddItem(nodeAddress, newInstit);
                nodeAddress.ChangeAddress(newInstit.InstitutionName);
                return(nodeAddress);

            case NodeType.Account:
                Account newAccount = GetCategory(nodeAddress.Address[0]).GetInstitution(nodeAddress.Address[1]).AddNewAccount();
                Map.AddItem(nodeAddress, newAccount);
                nodeAddress.ChangeAddress(newAccount.AccountName);
                return(nodeAddress);

            default:
                break;
            }
            throw new Exception("Issue");
        }
Ejemplo n.º 25
0
        private void TreeViewAccounting_AfterCollapse(object sender, TreeViewEventArgs e)
        {
            NodeAddress            na   = (NodeAddress)e.Node.Tag;
            TreeViewMappingElement tvme = Data.Map.GetElement(na);

            tvme.Expand = false;
        }
Ejemplo n.º 26
0
        /**
         * Creates a new Link, or retrieves an existing one, from a NodeAddress
         *
         * @param addr
         *            The NodeAddress of the Node to connect to
         * @return A new Link connected to the node at the given NodeAddress
         * @//throws JCSPNetworkException
         *             Thrown if anything goes wrong during the connection
         */
        public static Link getLink(NodeAddress addr)
        ////throws JCSPNetworkException
        {
            // Log start of creation
            Node.log.log(typeof(LinkFactory), "Trying to get link to " + addr.toString());

            // Create Link from address
            Link toReturn = addr.createLink();

            Console.WriteLine("Finished creating link NodeID " + toReturn.remoteID);

            // Now attempt to connect the Link. If connect fails, then the opposite node already has a connection to us.
            // This may occur during connection if the opposite end registered its Link prior to us doing so. In such
            // a circumstance, the Link should eventually appear in the LinkManager.
            if (!toReturn.connect())
            {
                // Connect failed. Get NodeID of remote Node (this will have been set during the connect operation)
                NodeID remoteID = toReturn.getRemoteNodeID();

                // Log failed connect
                Node.log.log(typeof(LinkFactory), "Failed to connect to " + remoteID.toString());
                Console.WriteLine("Failed to connect to " + remoteID.toString());
                // Set the Link to return to null
                toReturn = null;

                // Loop until the Link is connected. This is a possible weakness. Although it is believed that the
                // opposite end will eventually connect, we may have a problem if this continually loops. For information,
                // log every attempt.
                while (toReturn == null)
                {
                    try
                    {
                        // Go to sleep for a bit, and give the Link a chance to register
                        Thread.Sleep(100);

                        // Log start of attempt
                        Node.log.log(typeof(LinkFactory), "Attempting to retrieve Link to " + remoteID.toString());

                        // Retrieve Link from LinkManager
                        toReturn = LinkManager.getInstance().requestLink(remoteID);
                    }
                    catch (ThreadInterruptedException ie)
                    {
                        // Ignore. Should never really happen
                    }
                }
                // Return the Link retrieved from the LinkManager
                return(toReturn);
            }

            // Connection succeeded. Register Link with the LinkManager
            toReturn.registerLink();

            // Now start the Link
            new ProcessManager(toReturn).start();

            // Return the Link
            return(toReturn);
        }
Ejemplo n.º 27
0
        /**
         * Creates a new NetSharedChannelOutput connected to the channel with the given vcn on the given Node which uses the
         * given filter to encode outgoing messages
         *
         * @param nodeAddr
         *            The NodeAddress of the Node to connect to
         * @param vcn
         *            The Virtual Channel Number of the input channel
         * @param filter
         *            The immunity to poison that the channel has
         * @return A new NetSharedChannelOutput
         * @//throws JCSPNetworkException
         *             Thrown if something goes wrong in the underlying architecture
         */
        public NetSharedChannelOutput any2net(NodeAddress nodeAddr, int vcn, NetworkMessageFilter.FilterTx filter)
        //throws JCSPNetworkException
        {
            NodeID             remoteNode = LinkFactory.getLink(nodeAddr).remoteID;
            NetChannelLocation loc        = new NetChannelLocation(remoteNode, vcn);

            return(Any2NetChannel.create(loc, Int32.MaxValue, filter));
        }
Ejemplo n.º 28
0
 public XBeeCellular(XBeeControllerBase controller,
                     HardwareVersion hardwareVersion,
                     ushort firmwareVersion,
                     XBeeProtocol protocol,
                     NodeAddress address = null)
     : base(controller, hardwareVersion, firmwareVersion, protocol, address)
 {
 }
Ejemplo n.º 29
0
        /**
         * Creates a new NetSharedChannelOutput connected to the channel with the given vcn on the given Node which has the
         * given poison immunity
         *
         * @param nodeAddr
         *            The NodeAddress of the Node to connect to
         * @param vcn
         *            The Virtual Channel Number of the input channel
         * @param immunityLevel
         *            The immunity to poison that the channel has
         * @return A new NetSharedChannelOutput
         * @//throws JCSPNetworkException
         *             Thrown if something goes wrong in the underlying architecture
         */
        public NetSharedChannelOutput any2net(NodeAddress nodeAddr, int vcn, int immunityLevel)
        //throws JCSPNetworkException
        {
            NodeID             remoteNode = LinkFactory.getLink(nodeAddr).remoteID;
            NetChannelLocation loc        = new NetChannelLocation(remoteNode, vcn);

            return(Any2NetChannel.create(loc, immunityLevel, new ObjectNetworkMessageFilter.FilterTX()));
        }
Ejemplo n.º 30
0
        internal NodeAddress DeleteNode(NodeAddress na)
        {
            NodeAddress            refNode = na.GetParent();
            TreeViewMappingElement tvme    = GetElement(refNode);

            refNode.AddLast(tvme.Delete(na.GetLast()));
            return(refNode);
        }
Ejemplo n.º 31
0
 public BindingDefinition(NodeAddress _sourceNA, string _sourceMember, NodeAddress _targetNA, string _targetMember, string _targetName = "", bool _twoWay = false)
 {
     SourceNA = _sourceNA;
     SourceMember = _sourceMember;
     TargetNA = _targetNA;
     TargetMember = _targetMember;
     TargetName = _targetName;
     TwoWay = _twoWay;
 }
Ejemplo n.º 32
0
        public MemberAddress(NodeAddress _address, MemberInfo _member)
        {
            Address = _address;
            member = _member;
            memberName = "";

            if (member != null)
                memberName = member.Name;
        }
Ejemplo n.º 33
0
        //        public string Name {
        //            get { return memberName; }
        //            set { memberName = value; }
        //        }
        public MemberAddress(NodeAddress _address, string _member, bool findMember = true)
        {
            Address = _address;
            memberName = _member;
            member = null;

            if (Address == null)
                return;
            if (Address.Count == 0)
                return;

            if (!findMember)
                return;
            if (!tryFindMember ())
                throw new Exception ("Member Not Found: " + memberName);
        }
Ejemplo n.º 34
0
        public static NodeAddress Parse(string addr)
        {
            var n = new NodeAddress();

            if (addr.Contains(":"))
            {
                var spl = addr.Split(':');

                n.Address = spl[0];
                n.Port = int.Parse(spl[1]);
            }
            else
            {
                n.Address = addr;
                n.Port = 1200;
            }
            return n;
        }
Ejemplo n.º 35
0
 public static void emitGetInstance(ILGenerator il, NodeAddress orig, NodeAddress dest)
 {
     int ptr = 0;
     while (orig [ptr] == dest [ptr]) {
         ptr++;
         if (ptr == orig.Count || ptr == dest.Count)
             break;
     }
     for (int i = 0; i < orig.Count - ptr; i++)
         il.Emit (OpCodes.Callvirt, CompilerServices.miGetLogicalParent);
     while (ptr < dest.Count) {
         emitGetChild (il, dest [ptr-1].CrowType, dest [ptr].Index);
         ptr++;
     }
 }
Ejemplo n.º 36
0
 public EventBinding(NodeAddress _sourceNA, EventInfo _sourceEvt, NodeAddress _targetNA, string _targetMember, string _targetName = "")
     : base(_sourceNA, _sourceEvt.Name, _targetNA, _targetMember, _targetName)
 {
     SourceEvent = _sourceEvt;
 }
Ejemplo n.º 37
0
        public void StorePropertyBinding(NodeAddress origNA, string origMember, NodeAddress destNA, string destMember)
        {
            Dictionary<string, List<MemberAddress>> nodeBindings = null;
            if (Bindings.ContainsKey (origNA))
                nodeBindings = Bindings [origNA];
            else {
                nodeBindings = new Dictionary<string, List<MemberAddress>> ();
                Bindings [origNA] = nodeBindings;
            }

            if (!nodeBindings.ContainsKey (origMember))
                nodeBindings [origMember] = new List<MemberAddress> ();
            nodeBindings [origMember].Add (new MemberAddress (destNA, destMember));
        }
Ejemplo n.º 38
0
 /// <summary>
 /// Emits cached delegate handler addition in the context of instantiator (ctx)
 /// </summary>
 public void emitCachedDelegateHandlerAddition(int index, EventInfo evt, NodeAddress address = null)
 {
     il.Emit(OpCodes.Ldloc_0);//load ref to current graphic object
     CompilerServices.emitGetInstance (il, address);
     il.Emit(OpCodes.Ldarg_0);//load ref to this instanciator onto the stack
     il.Emit(OpCodes.Ldfld, CompilerServices.fiCachedDel);
     il.Emit(OpCodes.Ldc_I4, index);//load delegate index
     il.Emit(OpCodes.Callvirt, CompilerServices.miGetDelegateListItem);
     il.Emit(OpCodes.Callvirt, evt.AddMethod);//call add event
 }
Ejemplo n.º 39
0
        public static Delegate compileDynEventHandler(EventInfo sourceEvent, string expression, NodeAddress currentNode = null)
        {
            #if DEBUG_BINDING
            Debug.WriteLine ("\tCompile Event {0}: {1}", sourceEvent.Name, expression);
            #endif

            Type lopType = null;

            if (currentNode == null)
                lopType = sourceEvent.DeclaringType;
            else
                lopType = currentNode.NodeType;

            #region Retrieve EventHandler parameter type
            MethodInfo evtInvoke = sourceEvent.EventHandlerType.GetMethod ("Invoke");
            ParameterInfo [] evtParams = evtInvoke.GetParameters ();
            Type handlerArgsType = evtParams [1].ParameterType;
            #endregion

            Type [] args = { CompilerServices.TObject, handlerArgsType };
            DynamicMethod dm = new DynamicMethod ("dyn_eventHandler",
                typeof(void),
                args, true);
            ILGenerator il = dm.GetILGenerator (256);
            il.Emit (OpCodes.Nop);

            string [] srcLines = expression.Trim ().Split (new char [] { ';' });

            foreach (string srcLine in srcLines) {
                string statement = srcLine.Trim ();

                string [] operandes = statement.Split (new char [] { '=' });
                if (operandes.Length < 2) //not an affectation
                {
                    //maybe we could handle here handler function name
                    continue;
                }

                string rop = operandes [operandes.Length - 1].Trim ();

                #region LEFT OPERANDES
                string [] lopParts = operandes [0].Trim ().Split ('/');
                MemberInfo lopMI = null;

                il.Emit (OpCodes.Ldarg_0);  //load sender ref onto the stack

                if (lopParts.Length > 1) {
                    NodeAddress lopNA = getNodeAdressFromBindingExp (currentNode, lopParts);
                    CompilerServices.emitGetInstance (il, currentNode, lopNA);
                    lopType = lopNA.NodeType;
                }

                string [] bindTrg = lopParts.Last().Split ('.');

                if (bindTrg.Length == 1)
                    lopMI = lopType.GetMember (bindTrg [0]).FirstOrDefault();
                else if (bindTrg.Length == 2) {
                    //named target
                    //TODO:
                    il.Emit(OpCodes.Ldstr, bindTrg[0]);
                    il.Emit(OpCodes.Callvirt, miFindByName);
                    lopMI = lopType.GetMember (bindTrg [1]).FirstOrDefault();
                } else
                    throw new Exception ("Syntax error in binding, expected 'go dot member'");

                if (lopMI == null)
                    throw new Exception (string.Format ("IML BINDING: Member not found"));

                OpCode lopSetOpCode;
                dynamic lopSetMI;
                Type lopT = null;
                switch (lopMI.MemberType) {
                case MemberTypes.Property:
                    lopSetOpCode = OpCodes.Callvirt;
                    PropertyInfo lopPi = lopMI as PropertyInfo;
                    lopT = lopPi.PropertyType;
                    lopSetMI = lopPi.GetSetMethod ();
                    break;
                case MemberTypes.Field:
                    lopSetOpCode = OpCodes.Stfld;
                    FieldInfo dstFi = lopMI as FieldInfo;
                    lopT = dstFi.FieldType;
                    lopSetMI = dstFi;
                    break;
                default:
                    throw new Exception (string.Format ("GOML:member type not handle"));
                }
                #endregion

                #region RIGHT OPERANDES
                if (rop.StartsWith ("\'")) {
                    if (!rop.EndsWith ("\'"))
                        throw new Exception (string.Format
                            ("GOML:malformed string constant in handler: {0}", rop));
                    string strcst = rop.Substring (1, rop.Length - 2);

                    il.Emit (OpCodes.Ldstr, strcst);

                } else {
                    if (lopT.IsEnum)
                        throw new NotImplementedException ();

                    MethodInfo lopParseMi = lopT.GetMethod ("Parse");
                    if (lopParseMi == null)
                        throw new Exception (string.Format
                            ("GOML:no parse method found in: {0}", lopT.Name));
                    il.Emit (OpCodes.Ldstr, rop);
                    il.Emit (OpCodes.Callvirt, lopParseMi);
                    il.Emit (OpCodes.Unbox_Any, lopT);
                }

                #endregion

                //emit left operand assignment
                il.Emit (lopSetOpCode, lopSetMI);
            }

            il.Emit (OpCodes.Ret);

            return dm.CreateDelegate (sourceEvent.EventHandlerType);
        }
Ejemplo n.º 40
0
 public static void emitGetInstance(ILGenerator il, NodeAddress dest)
 {
     if (dest == null)
         return;
     for (int i = 0; i < dest.Count - 1; i++)
         emitGetChild (il, dest [i].CrowType, dest [i + 1].Index);
 }
Ejemplo n.º 41
0
 public BindingDefinition(NodeAddress _sourceNA, string _sourceMember)
 {
     SourceNA = _sourceNA;
     SourceMember = _sourceMember;
 }
Ejemplo n.º 42
0
 /// <summary>
 /// replace the target node address with corresponding named node address, and clear the target name once resolved
 /// </summary>
 /// <param name="newTargetNA">Named Node</param>
 public void ResolveTargetName(NodeAddress newTargetNA)
 {
     TargetNA = newTargetNA;
     TargetName = "";
 }
Ejemplo n.º 43
0
        private void InitProxy()
        {
            NodeAddress storeAddress = new NodeAddress();
            storeAddress.Host = Configuration.Instance().Get<string>("ServiceStore", "Host", "localhost");
            storeAddress.Port = Configuration.Instance().Get<int>("ServiceStore", "Port", 19995);

            _proxy = new ServiceStore_Proxy(_transport.Connect(storeAddress.Host, storeAddress.Port));
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Gets the node adress from binding expression splitted with '/' starting at a given node
        /// </summary>
        public static NodeAddress getNodeAdressFromBindingExp(NodeAddress sourceAddr, string[] bindingExp)
        {
            int ptr = sourceAddr.Count - 1;

            //if exp start with '/' => Graphic tree parsing start at source
            if (string.IsNullOrEmpty (bindingExp [0])) {
                //TODO:
            } else if (bindingExp [0] == ".") { //search template root
                ptr--;
                while (ptr >= 0) {
                    if (typeof(TemplatedControl).IsAssignableFrom (sourceAddr [ptr].CrowType))
                        break;
                    ptr--;
                }
            } else if (bindingExp [0] == "..") { //search starting at current node
                int levelUp = bindingExp.Length - 1;
                if (levelUp > ptr + 1)
                    throw new Exception ("Binding error: try to bind outside IML source");
                ptr -= levelUp;
            }
            //TODO:change Template special address identified with Nodecount = 0 to something not using array count to 0,
            //here linq is working without limits checking in compile option
            //but defining a 0 capacity array with limits cheking enabled, cause 'out of memory' error
            return new NodeAddress (sourceAddr.Take(ptr+1).ToArray());//[ptr+1];
            //Array.Copy (sourceAddr.ToArray (), targetNode, ptr + 1);
            //return new NodeAddress (targetNode);
        }
Ejemplo n.º 45
0
        public async void EscanearRed()
        {
            try
            {
                if (instancia.ListNodes == null)
                {
                    if (MonitoreoEvent != null) MonitoreoEvent(this, new MonitoreoEventArgs("Escaneando Red...", ETipoEvento.Exitoso, 0, ""));
                    instancia.ListNodes = new List<NodosXbee>();
                }
                string _macNodoEncontrado;
                string _macImpresora = "";
                int _tiempoEspera = 0;
                int _idXbee = 0;
                Enumeraciones.TipoDispositivo _tipDisp;
                DataTable dtXbees;
                using (Generales modGEN = new Generales())
                {
                    dtXbees = modGEN.ObtenerTodosLosXbee();
                }
                foreach (DataRow _row in dtXbees.Rows)
                {
                    _macNodoEncontrado = (string)_row["macXbee"];
                    _macImpresora = (string)_row["impresoraXbee"];
                    _tiempoEspera = (int)_row["tiempoEspXbee"];
                    _idXbee = (int)_row["idXbee"];
                    _tipDisp = (Enumeraciones.TipoDispositivo)_row["tipoXbee"];
                    NodosXbee newDispositivo = new NodosXbee(null, (string)_row["nomXbee"].ToString(), _macNodoEncontrado, _macImpresora, _tiempoEspera, _tipDisp, _idXbee);

                    //Buscar nodo en red
                    ulong _ulong = Convert.ToUInt64(_row["macXbee"].ToString(), 16);
                    NodeAddress Address = new NodeAddress(new LongAddress(_ulong));
                    XBeeNode nodoXbee = null;
                    nodoXbee = await instancia.Controller.GetRemoteAsync(Address);
                    if (nodoXbee != null)
                    {
                        newDispositivo.Nodo = nodoXbee;
                        if (MonitoreoEvent != null) MonitoreoEvent(this, new MonitoreoEventArgs("Se conectó el dispositivo: " + newDispositivo.Nombre + " MAC:" + _macNodoEncontrado + "", ETipoEvento.Exitoso, newDispositivo.IdXbee, ""));
                        if (_tipDisp == Enumeraciones.TipoDispositivo.Dispensador)
                        {
                            ActualizarDatosDispensador(newDispositivo.IdXbee);
                        }
                    }
                    instancia.AgregarNodo(newDispositivo);
                }
            }
            catch (Exception e)
            {
                LocalLogManager.EscribeLog(e.Message, LocalLogManager.TipoImagen.TipoError);
                if (MonitoreoEvent != null) MonitoreoEvent(this, new MonitoreoEventArgs("Se detectó un error:\n" + e.Message, ETipoEvento.Error, 0, ""));
            }
        }
Ejemplo n.º 46
0
        void emitPropertyBindings(Context ctx, NodeAddress origine, Dictionary<string, List<MemberAddress>> bindings)
        {
            Type origineNodeType = origine.NodeType;

            //value changed dyn method
            DynamicMethod dm = new DynamicMethod ("dyn_valueChanged" + NewId,
                typeof (void), CompilerServices.argsValueChange, true);
            ILGenerator il = dm.GetILGenerator (256);

            System.Reflection.Emit.Label endMethod = il.DefineLabel ();

            il.DeclareLocal (CompilerServices.TObject);

            il.Emit (OpCodes.Nop);

            int i = 0;
            foreach (KeyValuePair<string, List<MemberAddress>> bindingCase in bindings ) {

                System.Reflection.Emit.Label nextTest = il.DefineLabel ();

                #region member name test
                //load source member name
                il.Emit (OpCodes.Ldarg_1);
                il.Emit (OpCodes.Ldfld, CompilerServices.fiVCMbName);

                il.Emit (OpCodes.Ldstr, bindingCase.Key);//load name to test
                il.Emit (OpCodes.Ldc_I4_4);//StringComparison.Ordinal
                il.Emit (OpCodes.Callvirt, CompilerServices.stringEquals);
                il.Emit (OpCodes.Brfalse, nextTest);//if not equal, jump to next case
                #endregion

                #region destination member affectations
                PropertyInfo piOrig = origineNodeType.GetProperty (bindingCase.Key);
                Type origineType = null;
                if (piOrig != null)
                    origineType = piOrig.PropertyType;
                foreach (MemberAddress ma in bindingCase.Value) {
                    //first we have to load destination instance onto the stack, it is access
                    //with graphic tree functions deducted from nodes topology
                    il.Emit (OpCodes.Ldarg_0);//load source instance of ValueChanged event

                    NodeAddress destination = ma.Address;

                    if (destination.Count == 0){//template reverse binding
                        //fetch destination instance (which is the template root)
                        for (int j = 0; j < origine.Count ; j++)
                            il.Emit(OpCodes.Callvirt, CompilerServices.miGetLogicalParent);
                    }else
                        CompilerServices.emitGetInstance (il, origine, destination);

                    if (origineType != null && destination.Count > 0){//else, prop less binding or reverse template bind, no init requiered
                        //for initialisation dynmeth, push destination instance loc_0 is root node in ctx
                        ctx.il.Emit(OpCodes.Ldloc_0);
                        CompilerServices.emitGetInstance (ctx.il, destination);

                        //init dynmeth: load actual value from origine
                        ctx.il.Emit (OpCodes.Ldloc_0);
                        CompilerServices.emitGetInstance (ctx.il, origine);
                        ctx.il.Emit (OpCodes.Callvirt, origineNodeType.GetProperty (bindingCase.Key).GetGetMethod());
                    }
                    //load new value
                    il.Emit (OpCodes.Ldarg_1);
                    il.Emit (OpCodes.Ldfld, CompilerServices.fiVCNewValue);

                    if (origineType == null)//property less binding, no init
                        CompilerServices.emitConvert (il, ma.Property.PropertyType);
                    else if (destination.Count > 0) {
                        if (origineType.IsValueType)
                            ctx.il.Emit(OpCodes.Box, origineType);

                        CompilerServices.emitConvert (ctx.il, origineType, ma.Property.PropertyType);
                        CompilerServices.emitConvert (il, origineType, ma.Property.PropertyType);

                        ctx.il.Emit (OpCodes.Callvirt, ma.Property.GetSetMethod());//set init value
                    } else {// reverse templateBinding
                        il.Emit (OpCodes.Ldstr, ma.memberName);//arg 3 of setValueWithReflexion
                        il.Emit (OpCodes.Call, CompilerServices.miSetValWithRefx);
                        continue;
                    }
                    il.Emit (OpCodes.Callvirt, ma.Property.GetSetMethod());//set value on value changes
                }
                #endregion
                il.Emit (OpCodes.Br, endMethod);
                il.MarkLabel (nextTest);

                i++;
            }

            il.MarkLabel (endMethod);
            il.Emit (OpCodes.Ret);

            //store and emit Add in ctx
            int dmIdx = cachedDelegates.Count;
            cachedDelegates.Add (dm.CreateDelegate (typeof(EventHandler<ValueChangeEventArgs>)));
            ctx.emitCachedDelegateHandlerAddition (dmIdx, CompilerServices.eiValueChange, origine);
        }
Ejemplo n.º 47
0
        /// <summary>
        /// Splits the binding expression
        /// </summary>
        /// <returns><c>true</c>, if it's a two way binding, <c>false</c> otherwise.</returns>
        /// <param name="sourceNA">Source Node address</param>
        /// <param name="expression">Expression.</param>
        /// <param name="targetNA">Target Node Address</param>
        /// <param name="targetMember">Target member name</param>
        /// <param name="targetName">Target node name</param>
        BindingDefinition splitBindingExp(NodeAddress sourceNA, string sourceMember, string expression)
        {
            BindingDefinition bindingDef = new BindingDefinition(sourceNA, sourceMember);
            if (string.IsNullOrEmpty (expression)) {
                return bindingDef;
            } else {
                if (expression.StartsWith ("²")) {
                    bindingDef.TwoWay = true;
                    expression = expression.Substring (1);
                }
                string[] bindingExp = expression.Split ('/');

                if (bindingExp.Length > 1)
                    bindingDef.TargetNA = CompilerServices.getNodeAdressFromBindingExp (sourceNA, bindingExp);

                string [] bindTrg = bindingExp.Last().Split ('.');

                if (bindTrg.Length == 1)
                    bindingDef.TargetMember = bindTrg [0];
                else if (bindTrg.Length == 2) {
                    //named target
                    bindingDef.TargetName = bindTrg[0];
                    bindingDef.TargetMember = bindTrg [1];
                } else
                    throw new Exception ("Syntax error in binding, expected 'go dot member'");
            }

            return bindingDef;
        }