Пример #1
0
    public void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
    {
        Vector3 pos = observedTransform.position;
        Quaternion rot = observedTransform.rotation;

        if (stream.isWriting) {
            //Debug.Log("Server is writing");
            stream.Serialize(ref pos);
            stream.Serialize(ref rot);
        }
        else {
            //This code takes care of the local client!
            stream.Serialize(ref pos);
            stream.Serialize(ref rot);
            receiver.serverPosition = pos;
            receiver.serverRotation = rot;
            //Smoothly correct clients position
            //receiver.lerpToTarget();

            //Take care of data for interpolating remote objects movements
            // Shift up the buffer
            for ( int i = serverStateBuffer.Length - 1; i >= 1; i-- ) {
                serverStateBuffer[i] = serverStateBuffer[i-1];
            }
            //Override the first element with the latest server info
            serverStateBuffer[0] = new NetworkState((float)info.timestamp, pos, rot);
        }
    }
Пример #2
0
 public void PressClient()
 {
     var client = NetworkManager.singleton.StartClient();
     client.Connect("localhost", 7777);
     Debug.Log("Press Client");
     CurrentState = NetworkState.IsClient;
 }
		public MediaStateChangedEventArgs(BufferState bufferState, NetworkState networkState, PlaybackState playbackState, SeekState seekState)
		{
			this.bufferState = bufferState;
			this.networkState = networkState;
			this.playbackState = playbackState;
			this.seekState = seekState;
		}
Пример #4
0
    public override void OnJoinedLobby()
    {
        networkState = NetworkState.Connected;

        gameSession = FindObjectOfType<ExampleGameSession>();
        if (gameSession) {
            gameSession.OnJoinedLobby();
        }
    }
Пример #5
0
 public bool IsPlaying()
 {
     if (networkState != NetworkState.Playing) {
         if (players.AllReady()) {
             networkState = NetworkState.Playing;
         }
     }
     return networkState == NetworkState.Playing;
 }
 public static void DispatchStatusEvent(NetworkState status)
 {
     //只有允许输入时才派发事件
     if (IsActive)
     {
         InitPool();
         InputNetworkConnectStatusEvent e = GetConnectMsgEvent(status);
         InputManager.Dispatch<InputNetworkConnectStatusEvent>(e);
     }
 }
Пример #7
0
        private NetworkState state; //Current state of connection with the server

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Constructs a new Connect4Client
        /// </summary>
        public Connect4Client(Connect4ClientGame ga)
        {
            client = new TcpClient();
            outBuffer = new byte[1024];
            inBuffer = new byte[1024];
            incomingMessage = "";
            pendingSends = "";
            isSending = false;
            lastBadCommand = null;
            state = NetworkState.gameOver;
            owner = ga;
        }
    static InputNetworkConnectStatusEvent GetConnectMsgEvent(NetworkState status)
    {
        InputNetworkConnectStatusEvent msg = m_connectMsgPool[m_connectIndex];
        msg.Reset();
        msg.m_status = status;

        m_connectIndex++;

        if (m_connectIndex >= m_connectMsgPool.Length)
        {
            m_connectIndex = 0;
        }

        return msg;
    }
Пример #9
0
        public Form1()
        {
            netState = NetworkState.DISCONNECTED;
            clockState = ClockState.STOPPED;
            simulationTime = 0;
            updateFrequency = 1000;
            InitializeComponent();
            ofd = new OpenFileDialog();
            ofd.Filter = "XML File(*.xml)|*.xml";
            ofd2 = new OpenFileDialog();
            ofd2.Filter = "Text File(*.txt)|*.txt";
            sfd = new SaveFileDialog();

            simModel = null;
            netClient = null;
        }
Пример #10
0
		public async Task<BusinessLayer.Session>   GetSessionAsync (string name ,string password, string mandant, NetworkState networkstate)
		{

			if (networkstate == NetworkState.Disconnected) 
			{
				return await GetSessionAsync (name, password,mandant, true);

			}


			Stream dataStream;
			DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(BusinessLayer.Session)); 

			// Use the ServiceManager to build send the data to the SOA services			
			// The ServiceManager is responsible to send the data to the SOA services 		
			// Run the service and return the value as a Datastream							
			//SOAServiceManager sm = new SOAServiceManager ("https://92.79.164.245:443/authenticationsession.json","", DataAccessLayer.HTTPMethod.POST);					
			SOAServiceManager sm = new SOAServiceManager ( DataAccessLayer.Utilities.ServerIP + "/authenticationsession.json","", DataAccessLayer.HTTPMethod.POST);					

            // https://92.79.164.245
			// Add the Values 																
			sm.AddCriteriaValue ("name",name);												
			sm.AddCriteriaValue ("password",password);	
			sm.AddCriteriaValue ("mandant", mandant);


			// Now it's show time	
//			dataStream =await sm.CommitPostAsync ();													
            dataStream = await System.Threading.Tasks.Task.Run(() => sm.CommitPost());

			if (dataStream == null)
			{
				// Then there is a connection failure
				BusinessLayer.Session temp = BusinessLayer.Session.Create ();
				temp.Success = SOAResult.Disconnected;
				return temp;
			}
            Console.WriteLine("Disposed 5");

			var mySession = (BusinessLayer.Session)ser.ReadObject(dataStream);		

			return mySession;

		}
Пример #11
0
 private void UpdateNetworkState()
 {
     var connectivityManager = (ConnectivityManager)Context.GetSystemService(ConnectivityService);
     var activeNetworkInfo = connectivityManager.ActiveNetworkInfo;
     if (activeNetworkInfo == null)
     {
         networkState = NetworkState.Disconnected;
         return;
     }
     if (activeNetworkInfo.IsConnectedOrConnecting)
     {
         networkState = activeNetworkInfo.Type == ConnectivityType.Wifi ?
             NetworkState.ConnectedWifi : NetworkState.ConnectedData;
     }
     else
     {
         networkState = NetworkState.Disconnected;
     }
 }
Пример #12
0
		public void UpdateNetworkStatus() {
			_state = NetworkState.Unknown;

			// Retrieve the connectivity manager service
			var connectivityManager = (ConnectivityManager)
				Application.Context.GetSystemService (
					Context.ConnectivityService);

			// Check if the network is connected or connecting.
			// This means that it will be available,
			// or become available in a few seconds.
			var activeNetworkInfo = connectivityManager.ActiveNetworkInfo;

			if (activeNetworkInfo != null && activeNetworkInfo.IsConnectedOrConnecting) {
				// Now that we know it's connected, determine if we're on WiFi or something else.
				_state = activeNetworkInfo.Type == ConnectivityType.Wifi ?
					NetworkState.ConnectedWifi : NetworkState.ConnectedData;
			} else {
				_state = NetworkState.Disconnected;
			}
		}
Пример #13
0
 public override void OnPhotonPlayerConnected(PhotonPlayer player)
 {
     state = NetworkState.PLAYING;
     Application.LoadLevel("Main");
     switch (state)
     {
         case NetworkState.IDLE:
             Debug.LogError("Players shoudln't connect while we aren't in lobby");
             break;
         case NetworkState.IN_LOBBY:
             Debug.LogError("Players shoudln't connect while we aren't in a room");
             break;
         case NetworkState.WAITING_IN_ROOM:
             state = NetworkState.PLAYING;
             Application.LoadLevel("Main");
             break;
         case NetworkState.PLAYING:
             Debug.LogError("Players shoudln't connect while we are playing");
             break;
     }
 }
        void Verify_EnvironmentConnection_NetworkStateChanged(NetworkState fromState, NetworkState toState)
        {
            //------------Setup for test--------------------------
            var workspaceID = Guid.NewGuid();
            var dataListID = Guid.Empty;

            var serializer = new Dev2JsonSerializer();
            var requestResult = serializer.SerializeToBuilder(new SecuritySettingsTO());

            StringBuilder actualRequest = null;

            var connection = new Mock<IEnvironmentConnection>();
            connection.Setup(c => c.ServerEvents).Returns(new Mock<IEventPublisher>().Object);
            connection.Setup(c => c.WorkspaceID).Returns(workspaceID);
            connection.Setup(c => c.IsConnected).Returns(true);
            connection.Setup(c => c.ExecuteCommand(It.IsAny<StringBuilder>(), workspaceID))
                .Callback((StringBuilder xmlRequest, Guid wsID) => { actualRequest = xmlRequest; })
                .Returns(requestResult)
                .Verifiable();

            new ClientSecurityService(connection.Object);

            //------------Execute Test---------------------------
            connection.Raise(c => c.NetworkStateChanged += null, new NetworkStateEventArgs(fromState, toState));

            // wait for ReadAsync to finish
            Thread.Sleep(1000);

            //------------Assert Results-------------------------
            if(toState == NetworkState.Online)
            {
                connection.Verify(c => c.ExecuteCommand(It.IsAny<StringBuilder>(), workspaceID), Times.Never());
                Assert.IsNull(actualRequest);
            }
            else
            {
                connection.Verify(c => c.ExecuteCommand(It.IsAny<StringBuilder>(), workspaceID), Times.Never());
                Assert.IsNull(actualRequest);
            }
        }
Пример #15
0
		public SOAResult   GetSession (ref   BusinessLayer.Session mySession, string name ,string password, string mandant, NetworkState networkstate)
		{

			if (networkstate == NetworkState.Disconnected) 
			{
				return GetSession (ref mySession, name, password,mandant, true);

			}

			Stream dataStream;
			DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(BusinessLayer.Session)); 

			// Use the ServiceManager to build send the data to the SOA services			
			// The ServiceManager is responsible to send the data to the SOA services 		
			// Run the service and return the value as a Datastream							
			//SOAServiceManager sm = new SOAServiceManager ("https://92.79.164.245:443/authenticationsession.json","", DataAccessLayer.HTTPMethod.POST);					
			SOAServiceManager sm = new SOAServiceManager (DataAccessLayer.Utilities.ServerIP + "/authenticationsession.json","", DataAccessLayer.HTTPMethod.POST);					
			// https://92.79.164.245
			// Add the Values 																
			sm.AddCriteriaValue ("name",name);												
			sm.AddCriteriaValue ("password",password);	
			sm.AddCriteriaValue ("mandant", mandant);


			// Now it's show time	
			dataStream = sm.CommitPost ();													

			if (dataStream == null)
			{
				// Then there is a connection failure
				return SOAResult.Disconnected;
			}

			mySession = (BusinessLayer.Session)ser.ReadObject(dataStream);		

			return mySession.Success;
					
		}
Пример #16
0
 void OnGUI()
 {
     Debug.Log(state);
     switch (state)
     {
         case NetworkState.IDLE:
             GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
             break;
         case NetworkState.IN_LOBBY:
             GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
             GUI.Label(new Rect(500, 0, 150, 50), "ROOMS");
             roomList = PhotonNetwork.GetRoomList();
             int y = 60;
             foreach (RoomInfo room in roomList)
             {
                 if (GUI.Button(new Rect(350, y, 300, 50), room.name))
                 {
                     PhotonNetwork.JoinRoom(room.name);
                     state = NetworkState.PLAYING;
                     Application.LoadLevel("Main");
                 }
                 y += 60;
             }
             if (GUI.Button(new Rect(10, 60, 300, 50), "CreateNewRoom"))
             {
                 PhotonNetwork.CreateRoom(roomName);
                 state = NetworkState.WAITING_IN_ROOM;
             }
             break;
         case NetworkState.WAITING_IN_ROOM:
             GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
             GUI.Label(new Rect(500, 0, 150, 50), "Waiting for another player");
             break;
         case NetworkState.PLAYING:
             break;
     }
 }
    public void Connect()
	{
        try
        {
            m_NetworkState = NetworkState.Identifying;

            m_ClientSocket = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp);

            m_ClientSocket.BeginConnect(new IPEndPoint(IPAddress.Parse(k_ServerHostName),
                k_ServerPort),
                new AsyncCallback(ConnectCallback), 
                null);
        }
        catch (Exception ex)
        {
            Debug.LogError(ex.Message);
            if (OnNetworkError != null)
                OnNetworkError(ex.Message);

            Connect();
        }
    }
Пример #18
0
        private void RecordNetworkState(bool logChanges)
        {
            NetworkInterface[] adapters;
            try
            {
                // This "Only works on Linux and Windows" under Mono, so do in a try/catch to be safe.
                adapters = NetworkInterface.GetAllNetworkInterfaces();
            }
            catch
            {
                UnregisterNetworkEvents(); // Disable further network logging?
                return;
            }

            lock (m_NetworkStatesLock)
            {
                //now check each one (except loopback) to see if it's in our collection.
                foreach (NetworkInterface adapter in adapters)
                {
                    if ((adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback) &&
                        (adapter.NetworkInterfaceType != NetworkInterfaceType.Tunnel))
                    {
                        NetworkState previousState;

                        if (m_NetworkStates.TryGetValue(adapter.Id, out previousState) == false)
                        {
                            //it's brand new - need to add it and record it as new.
                            previousState = new NetworkState(adapter);
                            m_NetworkStates.Add(previousState.Id, previousState);

                            if (logChanges)
                            {
                                string interfaceInfo = FormatNetworkAdapterState(previousState);
                                LogEvent(LogMessageSeverity.Verbose, "System.Events.Network", "Network Interface Detected", interfaceInfo);
                            }
                        }
                        else
                        {
                            //see if it changed.
                            bool   hasChanged = false;
                            string changes    = string.Empty;

                            NetworkState newState = new NetworkState(adapter);

                            if (newState.OperationalStatus != previousState.OperationalStatus)
                            {
                                hasChanged = true;
                                changes   += string.Format(CultureInfo.InvariantCulture, "Operational Status Changed from {0} to {1}\r\n", previousState.OperationalStatus, newState.OperationalStatus);
                            }

                            if (newState.Speed != previousState.Speed)
                            {
                                hasChanged = true;
                                changes   += string.Format(CultureInfo.InvariantCulture, "Speed Changed from {0} to {1}\r\n",
                                                           FormatDataRate(previousState.Speed), FormatDataRate(newState.Speed));
                            }

                            //find any IP configuration change.
                            if (IPConfigurationChanged(previousState, newState))
                            {
                                hasChanged = true;
                                changes   += "TCP/IP Configuration Changed.\r\n";
                            }

                            if (hasChanged)
                            {
                                //replace the item in the collection with the new item
                                m_NetworkStates.Remove(previousState.Id);
                                m_NetworkStates.Add(newState.Id, newState);

                                if (logChanges)
                                {
                                    string interfaceInfo = FormatNetworkAdapterState(newState);
                                    LogEvent(LogMessageSeverity.Information, "System.Events.Network", "Network Interface Changes Detected", "\r\n{0}\r\nNew State:\r\n{1}", changes, interfaceInfo);
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #19
0
        /// <summary>
        /// Examines the given expression and returns the resulting output type from the expression
        /// </summary>
        /// <returns>The expression type.</returns>
        /// <param name="network">The top-level network.</param>
        /// <param name="proc">The process where the method is located.</param>
        /// <param name="method">The method where the statement is found.</param>
        /// <param name="statement">The statement where the expression is found.</param>
        /// <param name="expression">The expression to examine.</param>
        protected TypeReference ResolveExpressionType(NetworkState network, ProcessState proc, MethodState method, Statement statement, ICSharpCode.Decompiler.CSharp.Syntax.Expression expression)
        {
            if (expression is ICSharpCode.Decompiler.CSharp.Syntax.AssignmentExpression)
            {
                return(ResolveExpressionType(network, proc, method, statement, (expression as ICSharpCode.Decompiler.CSharp.Syntax.AssignmentExpression).Left));
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.IdentifierExpression)
            {
                return(LocateDataElement(network, proc, method, statement, expression as ICSharpCode.Decompiler.CSharp.Syntax.IdentifierExpression).CecilType);
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.MemberReferenceExpression)
            {
                var el = TryLocateElement(network, proc, method, statement, expression as ICSharpCode.Decompiler.CSharp.Syntax.MemberReferenceExpression);
                if (el == null)
                {
                    throw new Exception($"Location failed for expression {expression}");
                }
                else if (el is DataElement)
                {
                    return(((DataElement)el).CecilType);
                }
                else if (el is Method)
                {
                    var rv = ((Method)el).ReturnVariable;
                    if (rv == null)
                    {
                        return(null);
                    }

                    return(rv.CecilType);
                }
                else
                {
                    throw new Exception($"Unexpected result for {expression} {el.GetType().FullName}");
                }
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.PrimitiveExpression)
            {
                return(LoadType((expression as ICSharpCode.Decompiler.CSharp.Syntax.PrimitiveExpression).Value.GetType()));
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.BinaryOperatorExpression)
            {
                var e  = expression as ICSharpCode.Decompiler.CSharp.Syntax.BinaryOperatorExpression;
                var op = e.Operator;
                if (op.IsCompareOperator() || op.IsLogicalOperator())
                {
                    return(LoadType(typeof(bool)));
                }



                var lefttype = ResolveExpressionType(network, proc, method, statement, e.Left);
                //var righttype = ResolveExpressionType(network, proc, method, statement, e.Right);

                if (op.IsArithmeticOperator() || op.IsBitwiseOperator())
                {
                    var righttype = ResolveExpressionType(network, proc, method, statement, e.Right);

                    // Custom resolve of the resulting type as dictated by the .Net rules
                    if (righttype.IsSameTypeReference <double>() || lefttype.IsSameTypeReference <double>())
                    {
                        return(lefttype.LoadType(typeof(double)));
                    }
                    if (righttype.IsSameTypeReference <float>() || lefttype.IsSameTypeReference <float>())
                    {
                        return(lefttype.LoadType(typeof(float)));
                    }
                    if (righttype.IsSameTypeReference <ulong>() || lefttype.IsSameTypeReference <ulong>())
                    {
                        return(lefttype.LoadType(typeof(ulong)));
                    }
                    if (righttype.IsSameTypeReference <long>() || lefttype.IsSameTypeReference <long>())
                    {
                        return(lefttype.LoadType(typeof(long)));
                    }

                    if (righttype.IsSameTypeReference <uint>() || lefttype.IsSameTypeReference <uint>())
                    {
                        if (lefttype.IsSameTypeReference <sbyte>() || lefttype.IsSameTypeReference <short>() || righttype.IsSameTypeReference <sbyte>() || righttype.IsSameTypeReference <short>())
                        {
                            return(lefttype.LoadType(typeof(long)));
                        }
                        else
                        {
                            return(lefttype.LoadType(typeof(uint)));
                        }
                    }

                    if (righttype.IsSameTypeReference <int>() || lefttype.IsSameTypeReference <int>())
                    {
                        if (righttype.IsSameTypeReference <uint>() || lefttype.IsSameTypeReference <uint>())
                        {
                            return(lefttype.LoadType(typeof(uint)));
                        }
                        else
                        {
                            return(lefttype.LoadType(typeof(int)));
                        }
                    }

                    if (righttype.IsSameTypeReference <ushort>() || lefttype.IsSameTypeReference <ushort>())
                    {
                        return(lefttype.LoadType(typeof(int)));
                    }
                    if (righttype.IsSameTypeReference <short>() || lefttype.IsSameTypeReference <short>())
                    {
                        return(lefttype.LoadType(typeof(int)));
                    }
                    if (righttype.IsSameTypeReference <sbyte>() || lefttype.IsSameTypeReference <sbyte>())
                    {
                        return(lefttype.LoadType(typeof(int)));
                    }
                    if (righttype.IsSameTypeReference <byte>() || lefttype.IsSameTypeReference <byte>())
                    {
                        return(lefttype.LoadType(typeof(int)));
                    }


                    Console.WriteLine("Warning: unable to determine result type for operation {0} on types {1} and {2}", op, lefttype, righttype);
                    //TODO: Return a larger type, double the bits?
                    return(lefttype);
                }
                else
                {
                    // TODO: Find the largest type?
                    return(lefttype);
                }
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.UnaryOperatorExpression)
            {
                return(ResolveExpressionType(network, proc, method, statement, (expression as ICSharpCode.Decompiler.CSharp.Syntax.UnaryOperatorExpression).Expression));
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.IndexerExpression)
            {
                var arraytype = ResolveExpressionType(network, proc, method, statement, (expression as ICSharpCode.Decompiler.CSharp.Syntax.IndexerExpression).Target);
                return(arraytype.GetArrayElementType());
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.CastExpression)
            {
                return(LoadType((expression as ICSharpCode.Decompiler.CSharp.Syntax.CastExpression).Type, method));
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.ConditionalExpression)
            {
                return(ResolveExpressionType(network, proc, method, statement, (expression as ICSharpCode.Decompiler.CSharp.Syntax.ConditionalExpression).TrueExpression));
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.InvocationExpression)
            {
                var si = expression as ICSharpCode.Decompiler.CSharp.Syntax.InvocationExpression;
                var mt = si.Target as ICSharpCode.Decompiler.CSharp.Syntax.MemberReferenceExpression;

                // Catch common translations
                if (mt != null && (expression as ICSharpCode.Decompiler.CSharp.Syntax.InvocationExpression).Arguments.Count == 1)
                {
                    if (mt.MemberName == "op_Implicit" || mt.MemberName == "op_Explicit")
                    {
                        var mtm = Decompile(network, proc, method, statement, mt);
                        return(ResolveExpressionType(network, proc, method, statement, new ICSharpCode.Decompiler.CSharp.Syntax.CastExpression(ICSharpCode.Decompiler.CSharp.Syntax.AstType.Create(mtm.SourceResultType.FullName), si.Arguments.First().Clone())));
                    }
                    else if (mt.MemberName == "op_Increment")
                    {
                        return(ResolveExpressionType(network, proc, method, statement, new ICSharpCode.Decompiler.CSharp.Syntax.UnaryOperatorExpression(ICSharpCode.Decompiler.CSharp.Syntax.UnaryOperatorType.Increment, si.Arguments.First().Clone())));
                    }
                    else if (mt.MemberName == "op_Decrement")
                    {
                        return(ResolveExpressionType(network, proc, method, statement, new ICSharpCode.Decompiler.CSharp.Syntax.UnaryOperatorExpression(ICSharpCode.Decompiler.CSharp.Syntax.UnaryOperatorType.Decrement, si.Arguments.First().Clone())));
                    }
                }

                var m = proc.CecilType.Resolve().GetMethods().FirstOrDefault(x => x.Name == mt.MemberName);
                if (m != null)
                {
                    return(m.ReturnType);
                }

                return(ResolveExpressionType(network, proc, method, statement, (expression as ICSharpCode.Decompiler.CSharp.Syntax.InvocationExpression).Target));
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.ParenthesizedExpression)
            {
                return(ResolveExpressionType(network, proc, method, statement, (expression as ICSharpCode.Decompiler.CSharp.Syntax.ParenthesizedExpression).Expression));
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.NullReferenceExpression)
            {
                return(null);
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.ArrayCreateExpression)
            {
                return(ResolveExpressionType(network, proc, method, statement, (expression as ICSharpCode.Decompiler.CSharp.Syntax.ArrayCreateExpression).Initializer.FirstChild as ICSharpCode.Decompiler.CSharp.Syntax.Expression));
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.CheckedExpression)
            {
                return(ResolveExpressionType(network, proc, method, statement, (expression as ICSharpCode.Decompiler.CSharp.Syntax.CheckedExpression).Expression));
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.UncheckedExpression)
            {
                return(ResolveExpressionType(network, proc, method, statement, (expression as ICSharpCode.Decompiler.CSharp.Syntax.UncheckedExpression).Expression));
            }
            else if (expression == ICSharpCode.Decompiler.CSharp.Syntax.Expression.Null)
            {
                return(null);
            }
            else
            {
                throw new Exception(string.Format("Unsupported expression: {0} ({1})", expression, expression.GetType().FullName));
            }
        }
Пример #20
0
		public void RefreshNetworkState()
		{
			NetworkState nextNetworkState = networkState;
		
			if (sound != null && sound.Channel != null)
			{
				if (sound.OpenState == OpenState.Connecting)
					nextNetworkState = NetworkState.Connecting;
				else if (sound.OpenState == OpenState.Ready)
					nextNetworkState = NetworkState.Streaming;
				else if (sound.OpenState == OpenState.Error)
					nextNetworkState = NetworkState.Error;
				else nextNetworkState = NetworkState.None;
			}
			else nextNetworkState = NetworkState.None;

			if (networkState != nextNetworkState)
			{
				networkState = nextNetworkState;
				if (NetworkStateChanged != null)
					NetworkStateChanged(this, new MediaStateChangedEventArgs(BufferState, NetworkState, PlaybackState, SeekState));
			}
		}
Пример #21
0
        private static bool IPConfigurationChanged(NetworkState previousState, NetworkState newState)
        {
            //Gateways
            if ((previousState.GatewayAddresses != null) && (newState.GatewayAddresses == null))
            {
                return(true);
            }

            if ((previousState.GatewayAddresses == null) && (newState.GatewayAddresses != null))
            {
                return(true);
            }

            if ((previousState.GatewayAddresses != null) && (newState.GatewayAddresses != null))
            {
                //need to check addresses.
                if (previousState.GatewayAddresses.Count != newState.GatewayAddresses.Count)
                {
                    return(true);
                }

                foreach (GatewayIPAddressInformation ipAddressInformation in newState.GatewayAddresses)
                {
                    bool foundOurAddress = false;
                    foreach (GatewayIPAddressInformation previousAddress in newState.GatewayAddresses)
                    {
                        //if this address is our previous address, we're ready to check the next address.
                        if (ipAddressInformation.Address.Equals(previousAddress.Address))
                        {
                            foundOurAddress = true;
                            break;
                        }
                    }

                    if (foundOurAddress == false)
                    {
                        //if we got through all of the gateways and didn't find our address, this is a change.
                        return(true);
                    }
                }
            }

            //IP Addresses
            if ((previousState.UnicastIPAddresses != null) && (newState.UnicastIPAddresses == null))
            {
                return(true);
            }

            if ((previousState.UnicastIPAddresses == null) && (newState.UnicastIPAddresses != null))
            {
                return(true);
            }

            if ((previousState.UnicastIPAddresses != null) && (newState.UnicastIPAddresses != null))
            {
                //need to check addresses.
                if (previousState.UnicastIPAddresses.Count != newState.UnicastIPAddresses.Count)
                {
                    return(true);
                }

                foreach (UnicastIPAddressInformation ipAddressInformation in newState.UnicastIPAddresses)
                {
                    bool foundOurAddress = false;
                    foreach (UnicastIPAddressInformation previousAddress in newState.UnicastIPAddresses)
                    {
                        //if this address is our previous address, we're ready to check the next address.
                        if (ipAddressInformation.Address.Equals(previousAddress.Address))
                        {
                            foundOurAddress = true;
                            break;
                        }
                    }

                    if (foundOurAddress == false)
                    {
                        //if we got through all of the gateways and didn't find our address, this is a change.
                        return(true);
                    }
                }
            }

            //DNS
            if ((previousState.DnsAddresses != null) && (newState.DnsAddresses == null))
            {
                return(true);
            }

            if ((previousState.DnsAddresses == null) && (newState.DnsAddresses != null))
            {
                return(true);
            }

            if ((previousState.DnsAddresses != null) && (newState.DnsAddresses != null))
            {
                //need to check addresses.
                if (previousState.DnsAddresses.Count != newState.DnsAddresses.Count)
                {
                    return(true);
                }

                foreach (IPAddress ipAddressInformation in newState.DnsAddresses)
                {
                    bool foundOurAddress = false;
                    foreach (IPAddress previousAddress in newState.DnsAddresses)
                    {
                        //if this address is our previous address, we're ready to check the next (outer) address.
                        if (ipAddressInformation.Equals(previousAddress))
                        {
                            foundOurAddress = true;
                            break;
                        }
                    }

                    if (foundOurAddress == false)
                    {
                        //if we got through all of the gateways and didn't find our address, this is a change.
                        return(true);
                    }
                }
            }

            //WINS
            if ((previousState.WinsServersAddresses != null) && (newState.WinsServersAddresses == null))
            {
                return(true);
            }

            if ((previousState.WinsServersAddresses == null) && (newState.WinsServersAddresses != null))
            {
                return(true);
            }

            if ((previousState.WinsServersAddresses != null) && (newState.WinsServersAddresses != null))
            {
                //need to check addresses.
                if (previousState.WinsServersAddresses.Count != newState.WinsServersAddresses.Count)
                {
                    return(true);
                }

                foreach (IPAddress ipAddressInformation in newState.WinsServersAddresses)
                {
                    bool foundOurAddress = false;
                    foreach (IPAddress previousAddress in newState.WinsServersAddresses)
                    {
                        //if this address is our previous address, we're ready to check the next (outer) address.
                        if (ipAddressInformation.Equals(previousAddress))
                        {
                            foundOurAddress = true;
                            break;
                        }
                    }

                    if (foundOurAddress == false)
                    {
                        //if we got through all of the gateways and didn't find our address, this is a change.
                        return(true);
                    }
                }
            }


            return(false); //if we got this far with nothing, no changes.
        }
Пример #22
0
        void Verify_EnvironmentConnection_NetworkStateChanged(NetworkState fromState, NetworkState toState)
        {
            //------------Setup for test--------------------------
            var workspaceID = Guid.NewGuid();
            var dataListID  = Guid.Empty;

            var serializer    = new Dev2JsonSerializer();
            var requestResult = serializer.SerializeToBuilder(new SecuritySettingsTO());

            StringBuilder actualRequest = null;

            var connection = new Mock <IEnvironmentConnection>();

            connection.Setup(c => c.ServerEvents).Returns(new Mock <IEventPublisher>().Object);
            connection.Setup(c => c.WorkspaceID).Returns(workspaceID);
            connection.Setup(c => c.IsConnected).Returns(true);
            connection.Setup(c => c.ExecuteCommand(It.IsAny <StringBuilder>(), workspaceID))
            .Callback((StringBuilder xmlRequest, Guid wsID) => { actualRequest = xmlRequest; })
            .Returns(requestResult)
            .Verifiable();

            new ClientSecurityService(connection.Object);

            //------------Execute Test---------------------------
            connection.Raise(c => c.NetworkStateChanged += null, new NetworkStateEventArgs(fromState, toState));

            // wait for ReadAsync to finish
            Thread.Sleep(1000);

            //------------Assert Results-------------------------
            if (toState == NetworkState.Online)
            {
                connection.Verify(c => c.ExecuteCommand(It.IsAny <StringBuilder>(), workspaceID), Times.Never());
                Assert.IsNull(actualRequest);
            }
            else
            {
                connection.Verify(c => c.ExecuteCommand(It.IsAny <StringBuilder>(), workspaceID), Times.Never());
                Assert.IsNull(actualRequest);
            }
        }
Пример #23
0
        /// <summary>
        /// Parses a a field reference and returns the associated variable
        /// </summary>
        /// <returns>The constant element.</returns>
        /// <param name="network">The top-level network.</param>
        /// <param name="proc">The process where the method is located.</param>
        /// <param name="field">The field to parse.</param>
        protected virtual DataElement RegisterVariable(NetworkState network, ProcessState proc, FieldDefinition field)
        {
            DataElement res;

            var    ceciltype    = proc.ResolveGenericType(field.FieldType);
            object defaultvalue = null;

            proc.SourceInstance.Initialization.TryGetValue(field.Name, out defaultvalue);
            defaultvalue = field.Constant ?? defaultvalue;


            if (field.IsLiteral)
            {
                var c = new Constant()
                {
                    CecilType    = ceciltype,
                    DefaultValue = defaultvalue,
                    Name         = field.Name,
                    Source       = field,
                    Parent       = proc
                };
                res = c;
                network.ConstantLookup.Add(field, c);
            }
            else if (field.IsStatic && field.IsInitOnly)
            {
                var c = new Constant()
                {
                    CecilType    = ceciltype,
                    DefaultValue = defaultvalue,
                    Name         = field.Name,
                    Source       = field,
                    Parent       = proc
                };
                res = c;
                network.ConstantLookup[field] = c;
            }
            else if (field.IsStatic)
            {
                //Don't care
                res = null;
            }
            else if (field.GetAttribute <Signal>() == null)
            {
                var c = new Variable()
                {
                    CecilType    = ceciltype,
                    DefaultValue = defaultvalue,
                    Name         = field.Name,
                    Source       = field,
                    Type         = null,
                    Parent       = proc
                };
                res = c;
                proc.Variables.Add(field.Name, c);
            }
            else
            {
                var c = new Signal()
                {
                    CecilType    = ceciltype,
                    DefaultValue = defaultvalue,
                    Name         = field.Name,
                    Source       = field,
                    Type         = null,
                    Parent       = proc
                };
                res = c;
                proc.Signals.Add(field.Name, c);
            }

            return(res);
        }
Пример #24
0
        /// <summary>
        /// Processes a single method and extracts all the statements in it
        /// </summary>
        /// <param name="network">The top-level network.</param>
        /// <param name="proc">The process where the method is located.</param>
        /// <param name="method">The method to decompile.</param>
        protected virtual Statement[] Decompile(NetworkState network, ProcessState proc, MethodState method)
        {
            var sx = proc.DecompilerContext.Decompile(method.SourceMethod);

            foreach (var s in sx.Members.Where(x => x is UsingDeclaration).Cast <UsingDeclaration>())
            {
                proc.Imports.Add(s.Import.ToString());
            }

            var methodnode = sx.Members.Where(x => x is MethodDeclaration).FirstOrDefault() as MethodDeclaration;

            if (methodnode == null)
            {
                return(null);
            }

            method.ReturnVariable =
                (
                    method.SourceMethod.ReturnType.FullName == typeof(void).FullName
                    ||
                    method.SourceMethod.ReturnType.FullName == typeof(System.Threading.Tasks.Task).FullName
                )
                ? null
                : RegisterTemporaryVariable(network, proc, method, method.SourceMethod.ReturnType, method.SourceMethod);

            if (method.ReturnVariable != null)
            {
                method.ReturnVariable.Parent = method;
            }

            var statements   = new List <Statement>();
            var instructions = methodnode.Body.Children;

            //if (method.IsStateMachine)
            //{
            //    var initial = instructions.FirstOrDefault(x => x.NodeType == NodeType.Statement);
            //    if (!(initial is ICSharpCode. .WhileStatement))
            //        throw new Exception("The first statement in a state process must be a while statement");

            //    instructions = (initial as AST.WhileStatement).Children.Skip(1);
            //    if (instructions.First() is ICSharpCode.Decompiler.CSharp.Syntax.BlockStatement && instructions.Count() == 1)
            //        instructions = instructions.First().Children;

            //}

            foreach (var n in instructions)
            {
                if (n.NodeType == NodeType.Statement)
                {
                    try
                    {
                        statements.Add(Decompile(network, proc, method, n));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Failed to process statement: {n} -> {ex}");
                        statements.Add(new CommentStatement($"Failed to process statement: {n} -> {ex}"));
                    }
                }
                else
                {
                    throw new Exception(string.Format("Unsupported construct: {0}", n));
                }
            }

            return(statements.ToArray());
        }
Пример #25
0
 public NetworkState ReadPacket(PacketByteBuf packet, NetworkState state, NetworkSide side)
 {
     return(state);
 }
Пример #26
0
 private void HandleNetworkStateChange(NetworkState state)
 {
     NetworkState = state;
     ConnectionManager.HandleNetworkStateChange(state);
 }
Пример #27
0
        /// <summary>
        /// Decompile the specified process, using the specified entry method
        /// </summary>
        /// <param name="network">The top-level network.</param>
        /// <param name="proc">The process where the method is located.</param>
        /// <param name="method">The entry method to start decompilation from.</param>
        protected virtual void Decompile(NetworkState network, ProcessState proc, System.Reflection.MethodInfo method)
        {
            var statements = new List <Statement>();

            if (proc.CecilType == null)
            {
                proc.CecilType = LoadType(proc.SourceType);
            }

            var proctype = proc.CecilType.Resolve();

            proc.DecompilerContext =
                new CSharpDecompiler(
                    proc.CecilType.Module,
                    new DecompilerSettings()
            {
                AsyncAwait      = true,
                UseDebugSymbols = true,
            }
                    );

            var m = proctype.Methods.FirstOrDefault(x => x.Name == method.Name && x.Parameters.Count == method.GetParameters().Length);

            if (m == null)
            {
                throw new Exception($"Unable to find a method with the name {method.Name} in type {proc.CecilType.FullName}");
            }

            proc.MainMethod = Decompile(network, proc, m);

            // If we have comments from the constructors, add them here
            if (statements.Count > 0)
            {
                statements.AddRange(proc.MainMethod.Statements);
                proc.MainMethod.Statements = statements.ToArray();
            }

            var methods = new List <MethodState>();

            while (proc.MethodTargets.Count > 0)
            {
                var tp = proc.MethodTargets.Dequeue();
                var ix = tp.Item3;

                var ic = (ix.SourceExpression as ICSharpCode.Decompiler.CSharp.Syntax.InvocationExpression);
                var r  = ic.Target as ICSharpCode.Decompiler.CSharp.Syntax.MemberReferenceExpression;

                // TODO: Maybe we can support overloads here as well
                var dm = methods.FirstOrDefault(x => x.Name == r.MemberName);
                if (dm == null)
                {
                    var mr = proctype.Methods.FirstOrDefault(x => x.Name == r.MemberName);
                    if (mr == null)
                    {
                        throw new Exception($"Unable to resolve method call to {r}");
                    }
                    dm = Decompile(network, proc, mr);
                    methods.Add(dm);
                }

                proc.Methods        = methods.ToArray();
                ix.Target           = dm;
                ix.TargetExpression = new MethodReferenceExpression()
                {
                    Parent           = ix,
                    SourceExpression = ix.SourceExpression,
                    SourceResultType = dm.ReturnVariable.CecilType,
                    Target           = dm
                };
                ix.SourceResultType = ix.TargetExpression.SourceResultType;
            }

            methods.Reverse();
            proc.Methods         = methods.ToArray();
            proc.SharedSignals   = proc.Signals.Values.ToArray();
            proc.SharedVariables = proc.Variables.Values.ToArray();
        }
Пример #28
0
 private void NetworkStateChanged(NetworkState state)
 {
     this.changedNetState = state;
     this.netStateChanged = true;
 }
Пример #29
0
 private void HandleAbort()
 {
     AssociationMessenger.SendAbort(this);
     State = NetworkState.CLOSING_ASSOCIATION;
 }
Пример #30
0
 /// <summary>
 /// Sets the default value for a field
 /// </summary>
 /// <param name="network">The top-level network.</param>
 /// <param name="proc">The process where the method is located.</param>
 /// <param name="item">The data element to set the default value for.</param>
 /// <param name="value">The value to set.</param>
 /// <param name="is_static">A flag indicating if the variable default is statically defined.</param>
 protected virtual void SetDataElementDefaultValue(NetworkState network, ProcessState proc, DataElement item, object value, bool is_static)
 {
     item.DefaultValue = value;
 }
Пример #31
0
 private void NetworkConnect()
 {
     if (netClient.Connect(hostnameTextBox.Text, Int32.Parse(portTextBox.Text)))
     {
         netState = NetworkState.CONNECTED;
         hostnameTextBox.Enabled = false;
         portTextBox.Enabled = false;
         connectButton.Text = "Disconnect";
         connectTextBox.Text = netState.ToString();
         ClockEnable();
         
         networkCheckTimer.Start();
     }
     else
     {
         NetworkInitialize();
         NetworkEnable();
         MessageBox.Show("Unable to connect to server.");
     }
     FormUpdate();
 }
Пример #32
0
 public override void OnLeftRoom()
 {
     networkState = NetworkState.InLobby;
     base.OnLeftRoom();
 }
Пример #33
0
 public override void OnJoinedRoom()
 {
     networkState = NetworkState.InRoom;
     base.OnJoinedRoom();
 }
Пример #34
0
 /// <summary>
 /// Create a new NetStateMachine.
 /// </summary>
 /// <param name="startingState">The state to begin the NetStateMachine in.</param>
 public NetworkStateMachine(NetworkState startingState)
 {
     CurrentState = startingState;
     TransitionTable = new Dictionary<Tuple<NetworkState,TransitionEvent>,Tuple<NetworkState,TransitionAction>>();
     return;
 }
Пример #35
0
 public ConnectionStatusChangeEventArgs(NetworkState newState)
 {
     NewState = newState;
 }
        static void TestConnectionEvents(NetworkState toState)
        {

            var environmentConnection = new Mock<IEnvironmentConnection>();
            environmentConnection.Setup(connection => connection.IsConnected).Returns(true);
            environmentConnection.Setup(connection => connection.ServerEvents).Returns(EventPublishers.Studio);

            var repo = new Mock<IResourceRepository>();
            var envModel = new EnvironmentModel(Guid.NewGuid(), environmentConnection.Object, repo.Object, new Mock<IStudioResourceRepository>().Object);

            envModel.IsConnectedChanged += (sender, args) => Assert.AreEqual(toState == NetworkState.Online, args.IsConnected);

            environmentConnection.Raise(c => c.NetworkStateChanged += null, new NetworkStateEventArgs(NetworkState.Connecting, toState));
        }
Пример #37
0
 /// <summary>
 /// 网络状态改变
 /// </summary>
 /// <param name="state">State.</param>
 public void ChangeNetworkState(NetworkState state)
 {
     networkState = state;
     OnNetworkStateChanged?.Invoke(state, this.LastError);
 }
Пример #38
0
        /// <summary>
        /// Locates the target for an expression.
        /// </summary>
        /// <returns>The data element.</returns>
        /// <param name="network">The top-level network.</param>
        /// <param name="proc">The process where the method is located.</param>
        /// <param name="method">The method where the statement is found.</param>
        /// <param name="statement">The statement where the expression is found.</param>
        /// <param name="expression">The expression to examine.</param>
        protected ASTItem TryLocateElement(NetworkState network, ProcessState proc, MethodState method, Statement statement, ICSharpCode.Decompiler.CSharp.Syntax.Expression expression)
        {
            if (expression is ICSharpCode.Decompiler.CSharp.Syntax.InvocationExpression)
            {
                var e      = expression as ICSharpCode.Decompiler.CSharp.Syntax.InvocationExpression;
                var target = e.Target;
                return(LocateDataElement(network, proc, method, statement, target));
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.IndexerExpression)
            {
                var e      = expression as ICSharpCode.Decompiler.CSharp.Syntax.IndexerExpression;
                var target = e.Target;
                return(LocateDataElement(network, proc, method, statement, target));
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.IdentifierExpression)
            {
                var e    = expression as ICSharpCode.Decompiler.CSharp.Syntax.IdentifierExpression;
                var name = e.Identifier;

                Variable variable;
                if (method != null && method.TryGetVariable(name, out variable))
                {
                    return(variable);
                }

                if (method != null)
                {
                    var p = method.Parameters.FirstOrDefault(x => x.Name == name);
                    if (p != null)
                    {
                        return(p);
                    }
                }

                if (proc.Variables.TryGetValue(name, out variable))
                {
                    return(variable);
                }

                Signal signal;
                if (proc != null && proc.Signals.TryGetValue(name, out signal))
                {
                    return(signal);
                }

                return(null);
            }
            else if (expression is ICSharpCode.Decompiler.CSharp.Syntax.MemberReferenceExpression)
            {
                var e = expression as ICSharpCode.Decompiler.CSharp.Syntax.MemberReferenceExpression;

                ASTItem current = null;

                var parts = new List <string>();
                ICSharpCode.Decompiler.CSharp.Syntax.Expression ec = e;
                while (ec != null)
                {
                    if (ec is ICSharpCode.Decompiler.CSharp.Syntax.MemberReferenceExpression)
                    {
                        parts.Add(((ICSharpCode.Decompiler.CSharp.Syntax.MemberReferenceExpression)ec).MemberName);
                        ec = ((ICSharpCode.Decompiler.CSharp.Syntax.MemberReferenceExpression)ec).Target;
                    }
                    else if (ec is ICSharpCode.Decompiler.CSharp.Syntax.ThisReferenceExpression)
                    {
                        //parts.Add("this");
                        ec = null;
                        break;
                    }
                    else if (ec is ICSharpCode.Decompiler.CSharp.Syntax.IdentifierExpression)
                    {
                        parts.Add(((ICSharpCode.Decompiler.CSharp.Syntax.IdentifierExpression)ec).Identifier);
                        ec = null;
                        break;
                    }
                    else if (ec is ICSharpCode.Decompiler.CSharp.Syntax.TypeReferenceExpression)
                    {
                        TypeDefinition dc = null;
                        if (method != null)
                        {
                            dc = method.SourceMethod.DeclaringType;
                        }
                        else if (proc != null)
                        {
                            dc = proc.CecilType.Resolve();
                        }

                        var ecs = ec.ToString();

                        if (dc != null)
                        {
                            if (ecs == dc.FullName || ecs == dc.Name)
                            {
                                ec = null;
                                //parts.Add("this");
                                break;
                            }

                            var targetproc = network.Processes.FirstOrDefault(x => x.CecilType.Name == ecs || x.CecilType.FullName == ecs);
                            if (targetproc != null)
                            {
                                // This is a static reference
                                current = null;                                 //targetproc;
                                break;
                            }

                            var bt = LoadTypeByName(ecs, dc.Module);
                            if (bt == null)
                            {
                                bt = LoadTypeByName(dc.FullName + "." + ecs, method.SourceMethod.Module);
                            }
                            if (bt == null)
                            {
                                bt = LoadTypeByName(dc.Namespace + "." + ecs, method.SourceMethod.Module);
                            }
                            // In some cases dc.Namespace is empty ...
                            if (bt == null && proc != null && proc.SourceType != null)
                            {
                                bt = LoadTypeByName(proc.SourceType.Namespace + "." + ecs, method.SourceMethod.Module);
                            }

                            if (bt != null && parts.Count == 1)
                            {
                                var br = bt.Resolve();
                                var px = br.Fields.FirstOrDefault(x => x.Name == parts[0]);

                                // Enum flags are encoded as constants
                                if (br.IsEnum)
                                {
                                    if (px == null)
                                    {
                                        throw new Exception($"Unable to find enum value {parts[0]} in {br.FullName}");
                                    }

                                    return(new Constant()
                                    {
                                        CecilType = bt,
                                        DefaultValue = px,
                                        Source = expression
                                    });
                                }
                                else
                                {
                                    // This is a constant of sorts
                                    var pe = network.ConstantLookup.Keys.FirstOrDefault(x => x.Name == parts[0]);
                                    if (pe != null)
                                    {
                                        return(network.ConstantLookup[pe]);
                                    }

                                    return(network.ConstantLookup[px] = new Constant()
                                    {
                                        CecilType = px.FieldType,
                                        Name = parts[0],
                                        Source = px,
                                        Parent = network
                                    });
                                }

                                //parts.AddRange(bt.FullName.Split('.').Reverse());
                            }


                            break;
                        }

                        // Likely a static reference, which is stored as a global constant
                        ec = null;
                    }
                    else
                    {
                        throw new Exception($"Unexpected element in reference chain: {ec.GetType().FullName}");
                    }
                }

                parts.Reverse();
                var fullname = string.Join(".", parts);


                if (parts.First() == "this")
                {
                    parts.RemoveAt(0);
                    if (proc == null)
                    {
                        throw new Exception("Attempting to do a resolve of \this\" but no process context is provided");
                    }
                    current = proc;
                }

                var first = true;
                foreach (var el in parts)
                {
                    var isIsFirst = first;
                    first = false;

                    if (current == null)
                    {
                        var pe = network.ConstantLookup.Keys.FirstOrDefault(x => x.Name == el);
                        if (pe != null)
                        {
                            current = network.ConstantLookup[pe];
                            continue;
                        }
                    }

                    if (current is MethodState || (isIsFirst && current == null))
                    {
                        //if (method.LocalRenames.ContainsKey(el))
                        //	el = method.LocalRenames[el];

                        var mt = current as MethodState ?? method;
                        if (mt != null)
                        {
                            Variable temp;
                            if (mt.TryGetVariable(el, out temp))
                            {
                                current = temp;
                                continue;
                            }

                            var p = mt.Parameters.FirstOrDefault(x => x.Name == el);
                            if (p != null)
                            {
                                current = p;
                                continue;
                            }

                            if (mt.ReturnVariable != null && !string.IsNullOrWhiteSpace(mt.ReturnVariable.Name) && el == mt.ReturnVariable.Name)
                            {
                                current = mt.ReturnVariable;
                                continue;
                            }
                        }
                    }

                    if (current is ProcessState || (isIsFirst && current == null))
                    {
                        var pr = current as ProcessState ?? proc;

                        if (pr != null)
                        {
                            if (pr.BusInstances.ContainsKey(el))
                            {
                                current = pr.BusInstances[el];
                                continue;
                            }

                            if (pr.Signals.ContainsKey(el))
                            {
                                current = pr.Signals[el];
                                continue;
                            }

                            if (pr.Variables.ContainsKey(el))
                            {
                                current = pr.Variables[el];
                                continue;
                            }

                            if (pr.Methods != null)
                            {
                                var p = pr.Methods.FirstOrDefault(x => x.Name == el);
                                if (p != null)
                                {
                                    current = p;
                                    continue;
                                }
                            }
                        }
                    }

                    if (current is Bus)
                    {
                        current = ((Bus)current).Signals.FirstOrDefault(x => x.Name == el);
                        if (current != null)
                        {
                            continue;
                        }
                    }

                    if (current is Variable)
                    {
                        var fi = ((Variable)current).CecilType.Resolve().Fields.FirstOrDefault(x => x.Name == el);
                        if (fi != null)
                        {
                            current = new Variable()
                            {
                                Name         = el,
                                Parent       = current,
                                Source       = fi,
                                CecilType    = fi.FieldType,
                                DefaultValue = null
                            };

                            continue;
                        }

                        var pi = ((Variable)current).CecilType.Resolve().Properties.FirstOrDefault(x => x.Name == el);
                        if (pi != null)
                        {
                            current = new Variable()
                            {
                                Name         = el,
                                Parent       = current,
                                Source       = fi,
                                CecilType    = fi.FieldType,
                                DefaultValue = null
                            };

                            continue;
                        }
                    }

                    if (el == "Length" && (current is DataElement) && ((DataElement)current).CecilType.IsArrayType())
                    {
                        return(new Constant()
                        {
                            ArrayLengthSource = current as DataElement,
                            CecilType = LoadType(typeof(int)),
                            DefaultValue = null,
                            Source = (current as DataElement).Source
                        });
                    }

                    throw new Exception($"Failed lookup at {el} in {fullname}");
                }

                if (current == null)
                {
                    throw new Exception($"Failed to fully resolve {fullname}");
                }

                return(current);
            }
            else
            {
                throw new Exception($"Unable to find a data element for an expression of type {expression.GetType().FullName}");
            }
        }
Пример #39
0
 /// <summary>
 /// Register a new transition inside the state machine.
 /// </summary>
 /// <param name="previousState">The state being transitioned out of.</param>
 /// <param name="eventPacket">The type of packet received over the network.</param>
 /// <param name="nextState">The state to transition into.</param>
 /// <param name="action">An action to perform before transitioning.</param>
 public void RegisterTransition(NetworkState previousState, TransitionEvent transEvent, NetworkState nextState, TransitionAction action)
 {
     TransitionTable.Add(new Tuple<NetworkState, TransitionEvent>(previousState, transEvent), new Tuple<NetworkState, TransitionAction>(nextState, action));
     return;
 }
Пример #40
0
 public ConnectionInfo(DateTime connectionOpenedTime, long latency, long nack, long ack, long acksSent, long fails, long resends, long bytesIn, long bytesOut, long packetsIn, long packetsOut, NetworkState state = NetworkState.Ok)
 {
     ConnectionOpenedTime = connectionOpenedTime;
     Latency    = latency;
     Nak        = nack;
     Ack        = ack;
     AckSent    = acksSent;
     Fails      = fails;
     Resends    = resends;
     BytesIn    = bytesIn;
     BytesOut   = bytesOut;
     PacketsIn  = packetsIn;
     PacketsOut = packetsOut;
     State      = state;
 }
Пример #41
0
        private static string FormatNetworkAdapterState(NetworkState adapterState)
        {
            StringBuilder stringBuild = new StringBuilder(1024);

            stringBuild.AppendFormat("Name: {0}\r\n", adapterState.Name);
            stringBuild.AppendFormat("Interface Type: {0}\r\n", adapterState.NetworkInterfaceType);
            stringBuild.AppendFormat("Description: {0}\r\n", adapterState.Description);


            string displayStatus;

            switch (adapterState.OperationalStatus)
            {
            case OperationalStatus.Up:
                displayStatus = "UP: The network interface is up; it can transmit data packets.";
                break;

            case OperationalStatus.Down:
                displayStatus = "DOWN: The network interface is unable to transmit data packets.";
                break;

            case OperationalStatus.Testing:
                displayStatus = "TESTING: The network interface is running tests.";
                break;

            case OperationalStatus.Unknown:
                displayStatus = "UNKNOWN: The network interface status is not known.";
                break;

            case OperationalStatus.Dormant:
                displayStatus = "DORMANT: The network interface is not in a condition to transmit data packets; it is waiting for an external event.";
                break;

            case OperationalStatus.NotPresent:
                displayStatus = "NOT PRESENT: The network interface is unable to transmit data packets because of a missing component, typically a hardware component.";
                break;

            case OperationalStatus.LowerLayerDown:
                displayStatus = "LOWER LAYER DOWN: The network interface is unable to transmit data packets because it runs on top of one or more other interfaces, and at least one of these 'lower layer' interfaces is down.";
                break;

            default:
                displayStatus = adapterState.OperationalStatus.ToString();
                break;
            }

            stringBuild.AppendFormat("Status: {0}\r\n", displayStatus);

            if (adapterState.OperationalStatus == OperationalStatus.Up)
            {
                //convert speed to Kbps
                stringBuild.AppendFormat("Maximum Speed: {0}\r\n", FormatDataRate(adapterState.Speed));

                //since we have at least one IP protocol, output general IP stuff
                stringBuild.AppendFormat("DNS Servers: {0}\r\n", FormatIPAddressList(adapterState.DnsAddresses));
                stringBuild.AppendFormat("WINS Servers: {0}\r\n", FormatIPAddressList(adapterState.WinsServersAddresses));
                stringBuild.AppendFormat("Gateways: {0}\r\n", FormatGatewayIPAddressList(adapterState.GatewayAddresses));

                stringBuild.AppendFormat("IPv4 Addresses: {0}\r\n", FormatUnicastAddressList(adapterState.UnicastIPAddresses, AddressFamily.InterNetwork));
                stringBuild.AppendFormat("IPV6 Addresses: {0}\r\n", FormatUnicastAddressList(adapterState.UnicastIPAddresses, AddressFamily.InterNetworkV6));

                //check the quality of the IP addresses:
                if (adapterState.UnicastIPAddresses != null)
                {
                    foreach (UnicastIPAddressInformation addressInformation in adapterState.UnicastIPAddresses)
                    {
                        if ((addressInformation.DuplicateAddressDetectionState != DuplicateAddressDetectionState.Preferred) &&
                            (addressInformation.DuplicateAddressDetectionState != DuplicateAddressDetectionState.Deprecated))
                        {
                            string reason;

                            switch (addressInformation.DuplicateAddressDetectionState)
                            {
                            case DuplicateAddressDetectionState.Invalid:
                                reason = "the address is not valid. A nonvalid address is expired and no longer assigned to an interface; applications should not send data packets to it.";
                                break;

                            case DuplicateAddressDetectionState.Tentative:
                                reason = "the duplicate address detection procedure's evaluation of the address has not completed successfully. Applications should not use the address because it is not yet valid and packets sent to it are discarded.";
                                break;

                            case DuplicateAddressDetectionState.Duplicate:
                                reason = "the address is not unique. This address should not be assigned to the network interface.";
                                break;

                            default:
                                reason = addressInformation.DuplicateAddressDetectionState.ToString();
                                break;
                            }

                            stringBuild.AppendFormat("\r\nThe IP address {0} is not currently usable because {1}\r\n", addressInformation.Address, reason);
                        }
                    }
                }
            }

            return(stringBuild.ToString());
        }
Пример #42
0
 static void Dispatch(NetworkState status)
 {
     InputNetworkEventProxy.DispatchStatusEvent(status);
 }
 public void ReportNetworkStateChange(NetworkState networkState)
 {
 }
Пример #44
0
    public void Start()
    {
        networkState = NetworkState.Offline;

        ClientScene.RegisterPrefab(gameSessionPrefab);
    }
Пример #45
0
 public void PressHost()
 {
     NetworkManager.singleton.StartHost();
     Debug.Log("Press Host");
     CurrentState = NetworkState.IsHost;
 }
Пример #46
0
 /// <summary>
 /// Raises the <see cref="NetworkUp"/> or <see cref="NetworkDown"/> event.
 /// </summary>
 /// <param name="sender">The <see cref="NetworkModule"/> that raised the event.</param>
 /// <param name="state">The state of the network.</param>
 protected virtual void OnNetworkEvent(NetworkModule sender, NetworkState state)
 {
     if (_OnNetwork == null) _OnNetwork = new NetworkEventHandler(OnNetworkEvent);
     if (Program.CheckAndInvoke(state == NetworkState.Up ? _NetworkUp : _NetworkDown, _OnNetwork, sender, state))
     {
         switch (state)
         {
             case NetworkState.Up:
                 _NetworkUp(sender, state);
                 break;
             case NetworkState.Down:
                 _NetworkDown(sender, state);
                 break;
         }
     }
 }
Пример #47
0
 public void PressBack()
 {
     NetworkManager.singleton.StartHost();
     CurrentState = NetworkState.None;
 }
Пример #48
0
        private void NetworkInitialize()
        {
            hostnameTextBox.Text = System.Net.Dns.GetHostName();
            hostnameTextBox.Enabled = false;
            portTextBox.Text = "9999";
            portTextBox.Enabled = false;
            connectButton.Text = "Connect";
            connectButton.Enabled = false;
            connectTextBox.Text = netState.ToString();
            netState = NetworkState.DISCONNECTED;

            if (netClient != null)
            {
                netClient.Disconnect();
                netClient = null;
            }

            netClient = new NetworkClient();

            ClockInitialize();
        }
 private void setState(NetworkState _ns)
 {
     networkState = _ns;
 }
Пример #50
0
 public void MapLoaded()
 {
     state = NetworkState.Ready;
 }
Пример #51
0
 public override void OnStopConnecting()
 {
     networkState           = NetworkState.Offline;
     networkStateField.text = "";
 }
Пример #52
0
    public override void OnLeftLobby()
    {
        networkState = NetworkState.Offline;

        gameSession.OnLeftLobby();
    }
		public ConnectionStatusChangeEventArgs (NetworkState newState)
		{
			NewState = newState;
		}
Пример #54
0
 /// <summary>
 /// 数据接收
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void PortDataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     Thread.Sleep(50);
     ////禁止接收事件时直接退出
     //if (OnReceive==null) return;
                 if (this.WasDisposed)
     {
         return;
     }
                                    //如果正在关闭,忽略操作,直接返回,尽快的完成串口监听线程的一次循环
                 try
     {
         IsParsing = true;  //设置标记,说明已经开始处理数据,一会儿要使用系统UI
                         int n = Listener.BytesToRead;
         if (n < 1)
         {
             IsParsing = false;
             return;
         }
         string log = "";
         //检查未处理的缓冲区数据是否超时
         networkState.CheckPraseTimeOut();
         networkState.RawBuffer = new byte[n];
         Listener.Read(networkState.RawBuffer, 0, n);
         networkState.Buffer.WriteBytes(networkState.RawBuffer, 0, n);
         ReactorConnectionAdapter adapter = ((ReactorConnectionAdapter)ConnectionAdapter);
         while (networkState.Buffer.ReadableBytes > 0)
         {
             if (networkState.CheckPraseTimeOut())
             {
                 return;
             }
             FrameBase frame = adapter.ParsingReceivedData(networkState.Buffer.ToArray());
             if (frame != null)
             {
                 //触发整条记录的处理
                 INode       node       = null;
                 IConnection connection = adapter.GetConnection(frame);
                 if (connection != null)
                 {
                     connection.RemoteHost.TaskTag = connection.ControlCode;
                     node = connection.RemoteHost;
                 }
                 else
                 {
                     node         = this.LocalEndpoint;
                     node.TaskTag = "none";
                 }
                 NetworkState state = CreateNetworkState(Listener, node);
                 if (frame.MatchOffset != 0)
                 {
                     byte[] removeByte = networkState.Buffer.ReadBytes(frame.MatchOffset);
                     log = String.Format("{0}:串口丢弃数据-->>{1}", DateTime.Now.ToString("hh:mm:ss"),
                                         this.Encoder.ByteEncode(removeByte));
                     Console.WriteLine(log);
                 }
                 if (frame.FrameBytes != null && frame.FrameBytes.Length > 0)
                 {
                     state.RawBuffer = networkState.Buffer.ReadBytes(frame.FrameBytes.Length);
                     this.ReceiveCallback(state);
                 }
             }
             else
             {
                 log = String.Format("{0}:串口未处理数据-->>{1}", DateTime.Now.ToString("hh:mm:ss"), this.Encoder.ByteEncode(networkState.Buffer.ToArray()));
                 Console.WriteLine(log);
                 break;
             }
         }
         if (networkState.Buffer.WritableBytes == 0)
         {
             log = String.Format("{0}:串口丢弃数据-->>{1}", DateTime.Now.ToString("hh:mm:ss"),
                                 this.Encoder.ByteEncode(networkState.Buffer.ToArray()));
             Console.WriteLine(log);
         }
     }
     catch (Exception ex)
     {
         string enmsg = string.Format("Serial Port {0} Communication Fail\r\n" + ex.ToString(), Listener.PortName);
         Console.WriteLine(enmsg);
     }
     finally
     {
         IsParsing = false;   //监听完毕, UI可关闭串口
                    
     }
 }
Пример #55
0
 private void NetworkEnable()
 {
     hostnameTextBox.Text = System.Net.Dns.GetHostName();
     hostnameTextBox.Enabled = true;
     portTextBox.Text = "9999";
     portTextBox.Enabled = true;
     connectButton.Text = "Connect";
     connectButton.Enabled = true;
     connectTextBox.Text = netState.ToString();
     netState = NetworkState.DISCONNECTED;
     //ClockInitialize();
 }
Пример #56
0
 static void ConnectStatusChange(NetworkState status)
 {
     s_statusList.Add(status);
 }
Пример #57
0
 public override void OnStartConnecting()
 {
     networkState = NetworkState.Connecting;
 }
Пример #58
0
 // CALL BACK ======================
 public override void OnConnectedToMaster()
 {
     networkState = NetworkState.InLobby;
     base.OnConnectedToMaster();
 }
Пример #59
0
 public override void OnStopConnecting()
 {
     networkState = NetworkState.Offline;
 }
Пример #60
0
 public override void OnStartConnecting()
 {
     networkState           = NetworkState.Connecting;
     networkStateField.text = "Searching";
     StartCoroutine(Searching());
 }