public override CSharpNewLineBeforeElseStyle Update(NodeInformation <ElseClauseSyntax> information)
    {
        if (information is null)
        {
            throw new ArgumentNullException(nameof(information));
        }

        var node = information.Node;

        if (!node.ContainsDiagnostics)
        {
            var parentStatement = node.FindParent <IfStatementSyntax>();

            if (parentStatement is not null)
            {
                var parentChildren = parentStatement.ChildNodes().ToArray();
                var nodeIndex      = Array.IndexOf(parentChildren, node);
                var previousNode   = parentChildren[nodeIndex - 1];

                var lastToken   = previousNode.ChildTokens().Last();
                var containsEol = lastToken.HasTrailingTrivia &&
                                  lastToken.TrailingTrivia.Any(_ => _.Kind() == SyntaxKind.EndOfLineTrivia);
                return(new CSharpNewLineBeforeElseStyle(this.Data.Update(containsEol), this.Severity));
            }
        }

        return(new CSharpNewLineBeforeElseStyle(this.Data, this.Severity));
    }
    public override CSharpStyleVarForBuiltInTypesStyle Update(NodeInformation <LocalDeclarationStatementSyntax> information)
    {
        if (information is null)
        {
            throw new ArgumentNullException(nameof(information));
        }

        var node = information.Node;

        if (!node.ContainsDiagnostics)
        {
            if (node.DescendantNodes()
                .Any(_ => _.Kind() == SyntaxKind.StringLiteralExpression ||
                     _.Kind() == SyntaxKind.NumericLiteralExpression))
            {
                var variableDeclaration = node.ChildNodes()
                                          .Single(_ => _.Kind() == SyntaxKind.VariableDeclaration);
                var identifierName = variableDeclaration.ChildNodes()
                                     .SingleOrDefault(_ => _.Kind() == SyntaxKind.IdentifierName);

                return(identifierName is not null ?
                       new CSharpStyleVarForBuiltInTypesStyle(this.Data.Update(((IdentifierNameSyntax)identifierName).IsVar), this.Severity) :
                       new CSharpStyleVarForBuiltInTypesStyle(this.Data.Update(false), this.Severity));
            }
        }

        return(new CSharpStyleVarForBuiltInTypesStyle(this.Data, this.Severity));
    }
    public override CSharpNewLineBeforeCatchStyle Update(NodeInformation <CatchClauseSyntax> information)
    {
        if (information is null)
        {
            throw new ArgumentNullException(nameof(information));
        }

        var node = information.Node;

        if (!node.ContainsDiagnostics)
        {
            var parentStatement = node.FindParent <TryStatementSyntax>();

            if (parentStatement is not null)
            {
                var parentChildren = parentStatement.ChildNodes().ToArray();
                var nodeIndex      = Array.IndexOf(parentChildren, node);
                var previousNode   = parentChildren[nodeIndex - 1];

                if (previousNode is not BlockSyntax block)
                {
                    block = (BlockSyntax)((CatchClauseSyntax)previousNode).ChildNodes().Last();
                }

                var closeToken  = block.ChildTokens().Single(_ => _.RawKind == (int)SyntaxKind.CloseBraceToken);
                var containsEol = closeToken.HasTrailingTrivia &&
                                  closeToken.TrailingTrivia.Any(_ => _.Kind() == SyntaxKind.EndOfLineTrivia);
                return(new CSharpNewLineBeforeCatchStyle(this.Data.Update(containsEol), this.Severity));
            }
        }

        return(new CSharpNewLineBeforeCatchStyle(this.Data, this.Severity));
    }
    public override CSharpSpaceBetweenParenthesesStyle Update(NodeInformation <SyntaxNode> information)
    {
        if (information is null)
        {
            throw new ArgumentNullException(nameof(information));
        }

        var node = information.Node;

        if (!node.ContainsDiagnostics)
        {
            if (node is ForStatementSyntax || node is ForEachStatementSyntax || node is IfStatementSyntax ||
                node is SwitchStatementSyntax || node is WhileStatementSyntax)
            {
                return(new CSharpSpaceBetweenParenthesesStyle(this.Data.UpdateControlFlow(node.HasParenthesisSpacing())));
            }
            else if (node is ParenthesizedExpressionSyntax)
            {
                return(new CSharpSpaceBetweenParenthesesStyle(this.Data.UpdateExpression(node.HasParenthesisSpacing())));
            }
            else if (node is CastExpressionSyntax)
            {
                return(new CSharpSpaceBetweenParenthesesStyle(this.Data.UpdateTypeCast(node.HasParenthesisSpacing())));
            }
        }

        return(new CSharpSpaceBetweenParenthesesStyle(this.Data));
    }
Esempio n. 5
0
        public void TestGetSynopsis()
        {
            var n = NodeInformation.CreateSelfNode(endpoint);

            n.Properties.Add(new Dictionary <string, VersionedProperty>
            {
                {
                    "test_key",
                    new VersionedProperty
                    {
                        Version        = 5,
                        StringProperty = "test_value"
                    }
                },
                {
                    "test_key2",
                    new VersionedProperty
                    {
                        Version        = 9,
                        StringProperty = "test_value2"
                    }
                }
            });

            var ns = n.GetSynopsis();

            Assert.Equal(endpoint, ns.Endpoint);
            Assert.Equal(Process.GetCurrentProcess().StartTime.ToFileTimeUtc(), ns.NodeVersion);
            Assert.Equal(9, ns.LastKnownPropertyVersion);
        }
Esempio n. 6
0
        private void OnGUI()
        {
            GUILayout.Label("所有节点说明", Utility.GetGuiStyle("Title"));
            GUILayout.Space(10);

            GUILayout.BeginHorizontal();
            GUILayout.Label("搜索: ", GUILayout.MaxWidth(30));
            searchString = GUILayout.TextField(searchString).ToLower();
            GUILayout.EndHorizontal();
            GUILayout.Space(10);

            scrollPosition = GUILayout.BeginScrollView(scrollPosition);

            for (int i = 0; i < nodeInfoList.Count; i++)
            {
                NodeInformation nodeInformation = nodeInfoList[i];

                if (!string.IsNullOrEmpty(searchString))
                {
                    if (nodeInformation.Contain(searchString))
                    {
                        DrawNodeAttribute(nodeInformation);
                        GUILayout.Space(10);
                    }
                }
                else
                {
                    DrawNodeAttribute(nodeInformation);
                    GUILayout.Space(10);
                }
            }

            GUILayout.EndScrollView();
        }
Esempio n. 7
0
        public void TestGetDeltaFromOldNode()
        {
            var n = NodeInformation.CreateSelfNode(endpoint);

            n.Properties.Add(new Dictionary <string, VersionedProperty>
            {
                {
                    "test_key",
                    new VersionedProperty
                    {
                        Version        = 5,
                        StringProperty = "test_value"
                    }
                },
                {
                    "test_key2",
                    new VersionedProperty
                    {
                        Version        = 9,
                        StringProperty = "test_value2"
                    }
                }
            });

            var n2 = new NodeInformationSynopsis
            {
                Endpoint = endpoint,
                LastKnownPropertyVersion = 100,
                NodeVersion = n.NodeVersion - 1
            };

            var deltaN = n.GetDelta(n2, logger);

            Assert.Equal(n, deltaN);
        }
Esempio n. 8
0
    private void Save(string fName)
    {
        dialogueObject = CreateDialogueObject.Create(fName);

        if (dialogueObject)
        {
            dialogueObject.dialogueid = 5;

            dialogueObject.ConversationSet = (GenerateDictionaryFromNode());

            //   dialogueObject.noders = nodes;

            foreach (Connections c in connections)
            {
                ConnectionStruct cs = new ConnectionStruct(c.inPoint, c.outPoint, c.OnClickRemoveConnection);

                dialogueObject.connectionList.Add(cs);
            }

            foreach (DialogNode node in nodes)
            {
                NodeInformation nNode = new NodeInformation(node.nodeID, node.rect, node.inPoint.id, node.outPoint.id, node.conversationText, node.isRoot);

                dialogueObject.nodeInfoList.Add(nNode);
            }
        }
    }
Esempio n. 9
0
    public static void Create()
    {
        var node        = SyntaxFactory.IdentifierName("f");
        var information = new NodeInformation <IdentifierNameSyntax>(node);

        Assert.That(information.Node, Is.SameAs(node));
    }
Esempio n. 10
0
        public static string ConvertGraphToDotString(CodeGraph codeGraph)
        {
            StringBuilder dotString = new StringBuilder();

            // Start line of dot string
            dotString.Append("digraph {");

            // Add nodes to dot string
            foreach (var node in codeGraph.Vocabulary)
            {
                NodeInformation nodeInfo  = node.Value;
                int             nodeLabel = nodeInfo.Encoding;
                string          nodeName  = nodeInfo.NodeName;
                string          nodeColor = codeGraph.ColorMap[nodeInfo.NodeType];

                string nodeEntry = $"{nodeLabel} [label=\"{nodeName}\" style=filled fillcolor=\"{nodeColor}\"];";
                dotString.Append(nodeEntry);
            }

            // Add edges to dot string
            foreach (var edge in codeGraph.EncodedEdges)
            {
                dotString.Append($"{edge.parentNode} -> {edge.childNode};");
            }

            // TO DO: find better way of showing key on output image.
            // Add key (for colormap) to dot string.
            dotString = AddKeyToDotString(dotString, codeGraph);

            // End line of dot string
            dotString.Append("}");

            return(dotString.ToString());
        }
Esempio n. 11
0
    public override CSharpPreferBracesStyle Update(NodeInformation <SyntaxNode> information)
    {
        if (information is null)
        {
            throw new ArgumentNullException(nameof(information));
        }

        var node = information.Node;

        if (!node.ContainsDiagnostics)
        {
            if (node is IfStatementSyntax || node is ElseClauseSyntax ||
                node is ForStatementSyntax || node is ForEachStatementSyntax ||
                node is WhileStatementSyntax)
            {
                if (node.ChildNodes().SingleOrDefault(_ => _.Kind() == SyntaxKind.Block) is BlockSyntax block)
                {
                    return(block.ChildNodes().Count() == 1 ?
                           new CSharpPreferBracesStyle(this.Data.Update(true), this.Severity) :
                           new CSharpPreferBracesStyle(this.Data, this.Severity));
                }
                else
                {
                    return(new CSharpPreferBracesStyle(this.Data.Update(false), this.Severity));
                }
            }
        }

        return(new CSharpPreferBracesStyle(this.Data, this.Severity));
    }
Esempio n. 12
0
        public void TestBumpVersion()
        {
            var n = NodeInformation.CreateSelfNode(endpoint);

            n.Properties.Add("test_key", new VersionedProperty
            {
                Version        = 5,
                StringProperty = "test_value"
            });

            Assert.Equal(5, n.LastKnownPropertyVersion);

            n.BumpVersion();
            Assert.Equal(6, n.LastKnownPropertyVersion);

            n.Properties.Add("test_key2", new VersionedProperty
            {
                Version        = 9,
                StringProperty = "test_value2"
            });

            Assert.Equal(9, n.LastKnownPropertyVersion);

            n.BumpVersion();
            Assert.Equal(10, n.LastKnownPropertyVersion);

            n.Properties["test_key"].Version = 7;
            Assert.Equal(10, n.LastKnownPropertyVersion);

            n.BumpVersion();
            Assert.Equal(11, n.LastKnownPropertyVersion);
        }
Esempio n. 13
0
 internal StoreObjectClient(KyruApplication app, NodeInformation targetNode, KademliaId objectId, byte[] bytes, Action<Error> done)
     : base(app, targetNode)
 {
     this.objectId = objectId;
     this.bytes = bytes;
     this.done = done;
 }
Esempio n. 14
0
        public static void HandleSearchMessage(Message message)
        {
            Message    UdpResponse            = new Message(NodeInformation.GetCurrentIP().ToString(), port, MessageType.SearchResponse);
            Socket     socketSendServerAdress = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(message.IPAdress), message.Port);

            socketSendServerAdress.SendTo(messageSerializer.Serialize(UdpResponse), endPoint);
        }
 public override CSharpStyleExpressionBodiedAccessorsStyle Update(NodeInformation <AccessorDeclarationSyntax> information)
 {
     if (information is null)
     {
         throw new ArgumentNullException(nameof(information));
     }
     return(new CSharpStyleExpressionBodiedAccessorsStyle(information.Node.Examine(this.Data), this.Severity));
 }
Esempio n. 16
0
        /// <summary>
        /// Create and Add Parse error to the current feed result.
        /// </summary>
        /// <param name="errorType">Type of parse error.</param>
        /// <param name="nodeInformation">Current node base information.</param>
        /// <param name="feed">Current feed result.</param>
        /// <param name="content">Current node content data. (Optonal)</param>
        /// <param name="message">Parse error message. (Optional)</param>
        protected void SetParseError(ParseErrorType errorType, NodeInformation nodeInformation, Feed feed, string?content = null, string?message = null)
        {
            //Create and Add Parse error to the current feed result
            var error = ParseError.Create(nodeInformation, ToString(), errorType, feed.CurrentParseType, content, message);

            (feed.ParseError ??= new List <ParseError>()).Add(error);
            Debug.WriteLine(error);
        }
Esempio n. 17
0
 void Start()
 {
     if (NodeInformation.isMaster())
     {
         state = MenuState.Main;
         refresh();
     }
 }
Esempio n. 18
0
 // Use this for initialization
 void Start()
 {
     if (!NodeInformation.isMaster())
     {
         enabled = false;
     }
     force = 5f;
     // initCubes();
 }
Esempio n. 19
0
 public Server()
 {
     nodeInformation  = new NodeInformation();
     serializer       = new Serializer();
     CommonDialog     = new DialogInfo("Common dialog", 0);
     Clients          = new Dictionary <int, Client>();
     ConnectionsCount = 0;
     Connections      = new Dictionary <int, Connection>();
 }
    public override DotnetSortSystemDirectivesFirstStyle Update(NodeInformation <CompilationUnitSyntax> information)
    {
        if (information is null)
        {
            throw new ArgumentNullException(nameof(information));
        }

        var node = information.Node;

        if (!node.ContainsDiagnostics)
        {
            var usingNodes = node.DescendantNodes().Where(_ => _.IsKind(SyntaxKind.UsingDirective))
                             .Select(_ => (UsingDirectiveSyntax)_).ToImmutableArray();

            if (usingNodes.Length > 1)
            {
                var foundBreakIndex = false;

                for (var i = 0; i < usingNodes.Length; i++)
                {
                    var usingNode = usingNodes[i];

                    if (!usingNode.Name.ToString().StartsWith("System", StringComparison.InvariantCulture))
                    {
                        foundBreakIndex = true;
                    }
                    else if (foundBreakIndex)
                    {
                        return(new DotnetSortSystemDirectivesFirstStyle(this.Data.Update(false), this.Severity));
                    }
                }

                var systemUsingNodes = usingNodes.Where(_ => _.Name.ToString().StartsWith("System", StringComparison.InvariantCulture))
                                       .ToImmutableArray();

                if (systemUsingNodes.Length > 1)
                {
                    for (var i = 1; i < systemUsingNodes.Length; i++)
                    {
                        if (string.Compare(systemUsingNodes[i - 1].Name.ToString(),
                                           systemUsingNodes[i].Name.ToString(), StringComparison.Ordinal) > 0)
                        {
                            return(new DotnetSortSystemDirectivesFirstStyle(this.Data.Update(false), this.Severity));
                        }
                    }

                    return(new DotnetSortSystemDirectivesFirstStyle(this.Data.Update(true), this.Severity));
                }
                else if (systemUsingNodes.Length == 1)
                {
                    return(new DotnetSortSystemDirectivesFirstStyle(this.Data.Update(true), this.Severity));
                }
            }
        }

        return(new DotnetSortSystemDirectivesFirstStyle(this.Data, this.Severity));
    }
Esempio n. 21
0
        public void TestSelfNodeInitialState()
        {
            var n = NodeInformation.CreateSelfNode(endpoint);

            Assert.Equal(endpoint, n.Endpoint);
            Assert.Equal(NodeState.Live, n.NodeState);
            Assert.Equal(Process.GetCurrentProcess().StartTime.ToFileTimeUtc(), n.NodeVersion);
            Assert.Equal(1, n.LastKnownPropertyVersion);
            Assert.Single(n.Properties);
        }
Esempio n. 22
0
        public void TestSeedNodeInitialState()
        {
            var n = NodeInformation.CreateSeedNode(endpoint);

            Assert.Equal(endpoint, n.Endpoint);
            Assert.Equal(NodeState.Unknown, n.NodeState);
            Assert.Equal(0, n.NodeVersion);
            Assert.Equal(0, n.LastKnownPropertyVersion);
            Assert.Single(n.Properties);
        }
Esempio n. 23
0
 public void settingsButton()
 {
     state = MenuState.Options;
     refresh();
     if (!settingsSpawned && NodeInformation.isMaster())
     {
         NetworkServer.Spawn(musicBtn);
         NetworkServer.Spawn(backBtn);
         settingsSpawned = true;
     }
 }
Esempio n. 24
0
 public void creditsButton()
 {
     state = MenuState.Credits;
     refresh();
     if (!creditSpawned && NodeInformation.isMaster())
     {
         NetworkServer.Spawn(creditText);
         NetworkServer.Spawn(backBtn);
         creditSpawned = true;
     }
 }
Esempio n. 25
0
 // Update is called once per frame
 void Update()
 {
     if (Input.GetKeyDown(KeyCode.R))
     {
         //Destroy(gameObject);
         if (NodeInformation.isMaster())
         {
             NetworkServer.Destroy(gameObject);
         }
     }
 }
Esempio n. 26
0
        public NodeService(NodeInformation nodeInformation)
        {
            this._nodeInformation             = nodeInformation;
            this._peersByAddress              = new ConcurrentDictionary <string, Peer>();
            this._confirmedTransactionsByHash = new ConcurrentDictionary <string, Transaction>();
            this._pendingTransactionsByHash   = new ConcurrentDictionary <string, Transaction>();
            this._addresses  = new ConcurrentDictionary <string, Address>();
            this._miningJobs = new ConcurrentDictionary <string, Block>();
            this._blockchain = new ConcurrentBag <Block>();

            this.ProcessGenesisBlock();
        }
Esempio n. 27
0
    // Update is called once per frame
    void Update()
    {
        if (NodeInformation.isMaster())
        {
            // Press w or q to change frame spawn time and s or a to change multiplicator.
            if (Input.GetKeyDown(KeyCode.W))
            {
                spawnSpeed += spawnSpeedIncrease;
            }
            else if (Input.GetKeyDown(KeyCode.Q))
            {
                spawnSpeed -= spawnSpeedIncrease;
                if (spawnSpeed < 1)
                {
                    spawnSpeed = 1;
                }
            }
            else if (Input.GetKeyDown(KeyCode.S))
            {
                multiplicator++;
            }
            else if (Input.GetKeyDown(KeyCode.A))
            {
                multiplicator--;
                if (multiplicator < 1)
                {
                    multiplicator = 1;
                }
            }

            if (Input.GetKeyDown(KeyCode.T))
            {
                toggle = !toggle;
            }

            // Checks whether the "E" key is pressed.
            if (Input.GetKey(KeyCode.E) || toggle)
            {
                // Checks whether the defined ammount of frames have passed.
                if (counter % (float)spawnSpeed == 0)
                {
                    for (int i = 0; i < multiplicator; i++)
                    {
                        // Spawns the object at the appropriate location with an random offset between 0 and 1 multiplied by an offset.
                        Transform spawnSpheresObjects = Instantiate(obj, new Vector3(transform.position.x + Random.value * 30, transform.position.y + Random.value * 8, transform.position.z + Random.value * 28), Quaternion.identity);
                        NetworkServer.Spawn(spawnSpheresObjects.gameObject);
                    }
                }
            }

            counter++;
        }
    }
Esempio n. 28
0
        /// <summary>
        /// Main Content parsing method.
        /// </summary>
        /// <param name="parent">Parent stack for current node.</param>
        /// <param name="reader">Current xml feed reader.</param>
        /// <param name="feed">Current feed result.</param>
        /// <param name="root">Flag indicating if parser is the default root parser.</param>
        /// <returns>Flag indicating if current node should be parsed or if next node should be retrieved.</returns>
        public override async Task <bool> Parse(Stack <NodeInformation> parent, XmlReader reader, Feed feed, bool root = true)
        {
            //Init
            bool result;

            //Verify Element Node
            if (result = reader.NodeType == XmlNodeType.Element && (!reader.IsEmptyElement || reader.HasAttributes))
            {
                //Init
                NodeInformation nodeInfo = reader.NodeInformation();

                //Add Content to feed content type.
                ICommonFeed feedTarget = feed.CurrentItem ?? (ICommonFeed)feed;
                feedTarget.ContentType |= FeedContentType.Content;

                //Set common feed target
                ICommonContent target = feed.CurrentItem ?? (ICommonContent)feed;

                //Identify node name
                switch (reader.LocalName)
                {
                    #region Common

                case "encoded":     //Contains the complete encoded content of the feed/item.
                {
                    //Attemp to get encoded content
                    target.Content = new FeedContent()
                    {
                        Type = "text/html"
                    };
                    target.Content.Text = await reader.ReadStartElementAndContentAsStringAsync(target.Content.Type).ConfigureAwait(false);

                    break;
                }

                    #endregion Common

                default:     //Unknown feed/item node, continue to next.
                {
                    result = false;
                    if (root)
                    {
                        SetParseError(ParseErrorType.UnknownNode, nodeInfo, feed);
                    }
                    break;
                }
                }
            }

            //Return result
            return(result);
        }
Esempio n. 29
0
 public void playButton()
 {
     state = MenuState.Player;
     refresh();
     if (!playSpawned && NodeInformation.isMaster())
     {
         NetworkServer.Spawn(twoPlayers);
         NetworkServer.Spawn(threePlayers);
         NetworkServer.Spawn(fourPlayers);
         NetworkServer.Spawn(backBtn);
         playSpawned = true;
     }
 }
Esempio n. 30
0
        public Node(TreeNode Parent, NodeInformation NodeInfo)
            : base(Parent)
        {
            this.nodeInfo = NodeInfo;

            if (nodeInfo.HasChildren)
            {
                this.children = new SortedDictionary <string, TreeNode>()
                {
                    { string.Empty, new Loading(this) }
                };
            }
        }
Esempio n. 31
0
    public void createTower()
    {
        if (NodeInformation.isMaster())
        {
            setSizes();

            for (int i = 0; i < nrOfRows; i++)
            {
                addRow();
            }

            Debug.Log("Tower created");
        }
        state = State.BlockPlacing;
    }
Esempio n. 32
0
 internal GetObjectClient(KyruApplication app, NodeInformation targetNode, KademliaId objectId, Action<Error, byte[]> done)
     : base(app, targetNode)
 {
     this.objectId = objectId;
     this.done = done;
 }
Esempio n. 33
0
        public DiffuseSimulation()
        {
            nodeInfos = new NodeInformation[numberOfNodes];
            for (int i = 0; i < numberOfNodes; i++)
                nodeInfos[i] = new NodeInformation(IPAddress.Loopback, (ushort)(startPortNumber + i), Network.localtest, string.Empty);

            for (int i = 0; i < numberOfNodes; i++)
                portNumberToIndex.Add(nodeInfos[i].portNumber, i);

            sn = new SimulationNetwork();
            sss = new SimulationSocket[numberOfNodes];
            cremlias = new Cremlia[numberOfNodes];
            randomNumss = numberOfNodes.PipeForever((non) => non.RandomNums()).Where((ns) => ns.Select((n, i) => new { n, i }).All((ni) => ni.n != ni.i)).Take(numberOfDiffuseNodes).ToArray();
            int receiveCounter = 0;
            for (int i = 0; i < numberOfNodes; i++)
            {
                sss[i] = new SimulationSocket(sn);
                sss[i].Bind(new IPEndPoint(IPAddress.Any, nodeInfos[i].portNumber));
                sss[i].Listen(100);

                cremlias[i] = new Cremlia(new CremliaIdFactorySha256(), new CremliaDatabaseIo(), new CremliaNetworkIoSimulation(sss[i]), new CremliaNodeInfomationSha256(nodeInfos[i]));
                int[] randomNums = numberOfNodes.RandomNums();
                for (int j = 0; j < numberOfNodes; j++)
                    if (randomNums[j] != i)
                        cremlias[i].UpdateNodeStateWhenJoin(new CremliaNodeInfomationSha256(nodeInfos[randomNums[j]]));

                int index = i;

                this.StartTask(string.Empty, string.Empty, () =>
                {
                    object l = new object();
                    int counter = 0;

                    while (true)
                    {
                        SimulationSocket ss = sss[index].Accept() as SimulationSocket;

                        bool flag = false;
                        lock (l)
                            if (counter++ == 0)
                                flag = true;

                        this.StartTask(string.Empty, string.Empty, () =>
                        {
                            NodeInformation ni = SHAREDDATA.FromBinary<NodeInformation>(ss.Read());
                            byte[] data = ss.Read();
                            ss.Close();

                            Thread.Sleep(connectWait);

                            if (flag && index != 0)
                            {
                                Received(this, ++receiveCounter);

                                this.ConsoleWriteLine(string.Join(",", receiveCounter.ToString(), stopwatch.ElapsedMilliseconds.ToString()));

                                if (receiveCounter == numberOfNodes)
                                    stopwatch.Stop();

                                //int[] nodes = SelectNodes1(index);
                                int[] nodes = SelectNodes2(index, ni);
                                for (int j = 0; j < nodes.Length; j++)
                                {
                                    SimulationSocket ss2 = new SimulationSocket(sn);

                                    Thread.Sleep(verifyWait);

                                    ss2.Connect(IPAddress.Loopback, (ushort)(startPortNumber + nodes[j]));

                                    connections.Add(ss2.localPortNumber, (ushort)(startPortNumber + nodes[j]));
                                    connections.Add(ss2.remotePortNumber, nodeInfos[index].portNumber);

                                    ss2.Write(nodeInfos[index].ToBinary());
                                    ss2.Write(new byte[1024]);
                                    ss2.Close();
                                }
                            }
                        });
                    }
                });
            }
        }
Esempio n. 34
0
        private int[] SelectNodes2(int myNodeIndex, NodeInformation prevNodeInfo)
        {
            if (prevNodeInfo == null)
            {
                List<int> nodes = new List<int>();
                for (int i = 255; i >= 0; i--)
                {
                    ICremliaNodeInfomation[] nodeInfos1 = cremlias[myNodeIndex].GetKbuckets(i);
                    if (nodeInfos1.Length != 0)
                        nodes.Add(portNumberToIndex[(nodeInfos1[nodeInfos1.Length.RandomNum()] as CremliaNodeInfomationSha256).nodeInfo.portNumber]);
                }
                return nodes.ToArray();
            }
            else
            {
                List<int> nodes = new List<int>();
                for (int i = cremlias[myNodeIndex].GetDistanceLevel(new CremliaId<Sha256Hash>(prevNodeInfo.Id)); i >= 0; i--)
                {
                    ICremliaNodeInfomation[] nodeInfos1 = cremlias[myNodeIndex].GetKbuckets(i);
                    if (nodeInfos1.Length != 0)
                        nodes.Add(portNumberToIndex[(nodeInfos1[nodeInfos1.Length.RandomNum()] as CremliaNodeInfomationSha256).nodeInfo.portNumber]);
                }
                return nodes.ToArray();
            }

            SortedList<ICremliaId, ICremliaNodeInfomation> findTable = new SortedList<ICremliaId, ICremliaNodeInfomation>();
            cremlias[myNodeIndex].GetNeighborNodesTable(new CremliaId<Sha256Hash>(nodeInfos[myNodeIndex].Id), findTable);
            int[] neighborNodes = new int[3];
            for (int i = 0; i < 3; i++)
                neighborNodes[i] = portNumberToIndex[(findTable[findTable.Keys[i]] as CremliaNodeInfomationSha256).nodeInfo.portNumber];
            return neighborNodes;
        }
Esempio n. 35
0
 protected ClientBase(KyruApplication app, NodeInformation targetNode)
 {
     App = app;
     TargetNode = targetNode;
 }
Esempio n. 36
0
 public void BasicSerialization(CustomObject x)
 {
     instanceName=x.name;
     instanceID=x.ObjectID;
     node= new NodeInformation(x.Node);
 }