public override void RemovedFromDocument(GH_Document document)
        {
            try
            {
                // Clean up generated objects in both the active and background models:
                Core.Instance?.ActiveDocument?.Model?.History?.DeleteAllFromSource(InstanceGuid.ToString());

                GH_Document doc = OnPingDocument();
                if (doc != null)
                {
                    ModelDocument modelDoc = GrasshopperManager.Instance.BackgroundDocument(doc);
                    modelDoc?.Model?.History?.DeleteAllFromSource(InstanceGuid.ToString());
                }
                else
                {
                    //If we can't lookup the document, we'll have to clear it from all of them!
                    foreach (var kvp in GrasshopperManager.Instance.BackgroundDocuments)
                    {
                        kvp.Value?.Model?.History?.DeleteAllFromSource(InstanceGuid.ToString());
                    }
                }
            }
            catch
            { }

            base.RemovedFromDocument(document);
        }
Exemplo n.º 2
0
        public void Connect(string host = "0.0.0.0", ushort port = DEFAULT_PORT, string natHost = "", ushort natPort = NatHolePunch.DEFAULT_NAT_SERVER_PORT)
        {
            if (Disposed)
            {
                throw new ObjectDisposedException("UDPServer", "此对象已被处置且不能用于连接,请使用新的UDPServer。This object has been disposed and can not be used to connect, please use a new UDPServer");
            }

            try
            {
                Client = new CachedUdpClient(port);
                Client.EnableBroadcast = true;
                Me = new NetworkingPlayer(ServerPlayerCounter++, host, true, ResolveHost(host, port), this);
                Me.InstanceGuid = InstanceGuid.ToString();

                //在成功绑定的结果中执行任何通用初始化
                // Do any generic initialization in result of the successful bind
                OnBindSuccessful();

                //创建将监听来自连接客户端的新数据并开始执行的线程
                // Create the thread that will be listening for new data from connected clients and start its execution
                Task.Queue(ReadClients);

                // 创建将检查播放器超时的线程
                // Create the thread that will check for player timeouts
                Task.Queue(() =>
                {
                    commonServerLogic.CheckClientTimeout((player) =>
                    {
                        Disconnect(player, true);
                        OnPlayerTimeout(player);
                        CleanupDisconnections();
                    });
                });

                //让我知道我连接成功
                //Let myself know I connected successfully
                OnPlayerConnected(Me);

                //将自己设置为连接的客户端
                // Set myself as a connected client
                Me.Connected = true;

                //Set the port
                SetPort((ushort)((IPEndPoint)Client.Client.LocalEndPoint).Port);

                if (!string.IsNullOrEmpty(natHost))
                {
                    nat.Register((ushort)Me.IPEndPointHandle.Port, natHost, natPort);
                    nat.clientConnectAttempt += NatClientConnectAttempt;
                }
            }
            catch (Exception e)
            {
                Logging.BMSLog.LogException(e);
                // Do any generic initialization in result of the binding failure
                OnBindFailure();

                throw new FailedBindingException("Failed to bind to host/port, see inner exception", e);
            }
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Host.EnsureInitialisation();
            LastExecuted = null;
            if (ActionType != null)
            {
                IAction action = (IAction)Activator.CreateInstance(ActionType, true);
                if (action != null)
                {
                    if (action is IModelDocumentAction && !GrasshopperManager.Instance.AutoBake)
                    {
                        IModelDocumentAction mDAction = (IModelDocumentAction)action;
                        mDAction.Document = GrasshopperManager.Instance.BackgroundDocument(OnPingDocument());
                    }

                    if (ExtractInputs(action, DA))
                    {
                        ExecutionInfo exInfo = new ExecutionInfo(InstanceGuid.ToString(), DA.Iteration);
                        if (action.PreExecutionOperations(exInfo))
                        {
                            if (action.Execute(exInfo))
                            {
                                if (action.PostExecutionOperations(exInfo))
                                {
                                    ExtractOutputs(action, DA, exInfo);
                                    LastExecuted      = action;
                                    LastExecutionInfo = exInfo;
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var launch = false;

            if (!DA.GetData(0, ref launch))
            {
                return;
            }
            DA.DisableGapLogic();
            const string url = "https://energyplus.net/weather";

            if (launch)
            {
                QueueManager.addToQueue(url, () =>
                {
                    try
                    {
                        Process.Start(url);
                    }
                    catch (Exception e)
                    {
                        StringCache.setCache(InstanceGuid.ToString(), e.Message);
                    }
                });
            }

            var errors = StringCache.getCache(InstanceGuid.ToString());

            if (errors != null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, errors);
            }
        }
Exemplo n.º 5
0
        private void PollDownloadContent(
            string inputJson,
            string downloadPath,
            string localPath,
            string overrides,
            bool reload,
            string cacheKey
            )
        {
            var queueName = "Download" + cacheKey;

            // Get queue lock
            var queueLock  = StringCache.getCache(queueName);
            var downloaded = false;
            var inputData  = new Inputs().FromJson(inputJson);

            if (reload)
            {
                StringCache.setCache(InstanceGuid.ToString(), "");
            }

            if (queueLock != "true" && inputData.Task != null)
            {
                StringCache.setCache(queueName, "true");
                StringCache.setCache(cacheKey, null);
                QueueManager.addToQueue(queueName, () => {
                    try
                    {
                        while (!downloaded)
                        {
                            StringCache.setCache(cacheKey + "progress", "Downloading...");
                            ExpireSolutionThreadSafe(true);

                            downloaded = DownloadContent.Download(inputJson, downloadPath, localPath, overrides);
                            StringCache.setCache(cacheKey, downloaded.ToString());

                            if (!downloaded)
                            {
                                StringCache.setCache(cacheKey + "progress", "Waiting for results...");
                                ExpireSolutionThreadSafe(true);
                                Thread.Sleep(60000);
                            }
                            else
                            {
                                StringCache.setCache(cacheKey + "progress", "Downloaded files");
                            }
                            ExpireSolutionThreadSafe(true);
                        }
                    }
                    catch (Exception e)
                    {
                        StringCache.setCache(InstanceGuid.ToString(), e.Message);
                        StringCache.setCache(cacheKey, "error");
                    }
                    ExpireSolutionThreadSafe(true);
                    Thread.Sleep(2000);
                    StringCache.setCache(queueName, "");
                });
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// This will begin the connection for TCP, this is a thread blocking operation until the connection
        /// is either established or has failed
        /// </summary>
        /// <param name="hostAddress">[127.0.0.1] Ip Address to host from</param>
        /// <param name="port">[15937] Port to allow connections from</param>
        public void Connect(string hostAddress = "0.0.0.0", ushort port = DEFAULT_PORT)
        {
            if (string.IsNullOrEmpty(hostAddress))
            {
                throw new BaseNetworkException("An ip address must be specified to bind to. If you are unsure, you can set to 127.0.0.1");
            }

            // Check to see if this server is being bound to a "loopback" address, if so then bind to any, otherwise bind to specified address
            if (hostAddress == "0.0.0.0" || hostAddress == "localhost")
            {
                ipAddress = IPAddress.Any;
            }
            else
            {
                ipAddress = IPAddress.Parse(hostAddress);
            }

            try
            {
                // Setup and start the base C# TcpListner
                listener = new TcpListener(ipAddress, port);
                //listener.Start();

                Me = new NetworkingPlayer(ServerPlayerCounter++, "0.0.0.0", true, listener, this);
                Me.InstanceGuid = InstanceGuid.ToString();

                // Create the thread that will be listening for clients and start its execution
                //Thread connectionThread = new Thread(new ThreadStart(ListenForConnections));
                //connectionThread.Start();
                //Task.Queue(ListenForConnections);
                listener.Start();
                listener.BeginAcceptTcpClient(ListenForConnections, listener);

                // Create the thread that will be listening for new data from connected clients and start its execution
                Task.Queue(ReadClients);

                // Create the thread that will check for player timeouts
                Task.Queue(CheckClientTimeout);

                // Do any generic initialization in result of the successful bind
                OnBindSuccessful();

                //Let myself know I connected successfully
                OnPlayerConnected(Me);
                // Set myself as a connected client
                Me.Connected = true;

                //Set the port
                SetPort((ushort)((IPEndPoint)listener.LocalEndpoint).Port);
            }
            catch (Exception e)
            {
                Logging.BMSLog.LogException(e);
                // Do any generic initialization in result of the binding failure
                OnBindFailure();

                throw new FailedBindingException("Failed to bind to host/port, see inner exception", e);
            }
        }
Exemplo n.º 7
0
        //public override GH_Exposure Exposure => GH_Exposure.hidden;

        //public override bool Obsolete => true;

        protected void HandleErrors()
        {
            var errors = StringCache.getCache(InstanceGuid.ToString());

            if (!string.IsNullOrEmpty(errors))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, errors);
            }
        }
        /// <summary>
        /// Start the Forge Networking server on this Facepunch Steamworks client
        /// </summary>
        /// <param name="haveLobby">Boolean used internally to tell whether we have already created the lobby</param>
        public void Host(bool haveLobby = false)
        {
            if (Disposed)
            {
                throw new ObjectDisposedException("FacepunchP2PServer", "This object has been disposed and can not be used to connect, please use a new FacepunchP2PServer");
            }

            try
            {
                if (!haveLobby)
                {
                    CreateLobby();
                    return;
                }

                var selfSteamId = SteamClient.SteamId;
                Client = new CachedFacepunchP2PClient(selfSteamId);
                Me     = new NetworkingPlayer(ServerPlayerCounter++, selfSteamId, true, this)
                {
                    InstanceGuid = InstanceGuid.ToString()
                };

                // Do any generic initialization in result of the successful bind
                OnBindSuccessful();

                // Create the thread that will be listening for new data from connected clients and start its execution
                Task.Queue(ReadClients);

                // Create the thread that will check for player timeouts
                Task.Queue(() =>
                {
                    commonServerLogic.CheckClientTimeout((player) =>
                    {
                        Disconnect(player, true);
                        OnPlayerTimeout(player);
                        CleanupDisconnections();
                    });
                });

                // Let myself know I connected successfully
                OnPlayerConnected(Me);
                // Set myself as a connected client
                Me.Connected = true;
                OnServerCreated();
                StartAcceptingConnections();
            }
            catch (Exception e)
            {
                Logging.BMSLog.LogException(e);
                // Do any generic initialization in result of the binding failure
                OnBindFailure();

                throw new FailedBindingException("Failed to bind to SteamClient.SteamId, see inner exception", e);
            }
        }
Exemplo n.º 9
0
        public void Host(CSteamID selfSteamId, ELobbyType lobbyType, OnLobbyReady func = null)
        {
            if (Disposed)
            {
                throw new ObjectDisposedException("SteamP2PServer", "This object has been disposed and can not be used to connect, please use a new SteamP2PServer");
            }

            try
            {
                Client          = new CachedSteamP2PClient(selfSteamId);
                Me              = new NetworkingPlayer(ServerPlayerCounter++, selfSteamId, true, this);
                Me.InstanceGuid = InstanceGuid.ToString();

                m_CallbackLobbyCreated = Callback <LobbyCreated_t> .Create((LobbyCreated_t data) =>
                {
                    LobbyID = (CSteamID)data.m_ulSteamIDLobby;
                    if (func != null)
                    {
                        func();
                    }
                });

                m_CreateLobbyResult = SteamMatchmaking.CreateLobby(lobbyType, 5);
                // Do any generic initialization in result of the successful bind
                OnBindSuccessful();

                // Create the thread that will be listening for new data from connected clients and start its execution
                Task.Queue(ReadClients);

                // Create the thread that will check for player timeouts
                Task.Queue(() =>
                {
                    commonServerLogic.CheckClientTimeout((player) =>
                    {
                        Disconnect(player, true);
                        OnPlayerTimeout(player);
                        CleanupDisconnections();
                    });
                });

                //Let myself know I connected successfully
                OnPlayerConnected(Me);
                // Set myself as a connected client
                Me.Connected = true;
                StartAcceptingConnections();
            }
            catch (Exception e)
            {
                Logging.BMSLog.LogException(e);
                // Do any generic initialization in result of the binding failure
                OnBindFailure();

                throw new FailedBindingException("Failed to bind to host/port, see inner exception", e);
            }
        }
Exemplo n.º 10
0
        // Should validate the handshake response from the server
        private void ReceiveAsync_Completed(object sender, SocketAsyncEventArgs e)
        {
            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                int          bytesAlreadyProcessed = 0; // Count of the total freshly transferred bytes processed so far
                ReceiveToken token = (ReceiveToken)e.UserToken;
                if (!headerExchanged)
                {
                    byte[] header = HandleHttpHeader(e, ref bytesAlreadyProcessed);
                    token = (ReceiveToken)e.UserToken;
                    if (header == null)
                    {
                        DoRead(e);
                        return;
                    }
                    else if (Websockets.ValidateResponseHeader(headerHash, header))
                    {
                        headerExchanged       = true;
                        token.maxAllowedBytes = int.MaxValue;
                        e.UserToken           = token;

                        // Ping the server to finalize the player's connection
                        Send(Text.CreateFromString(Time.Timestep, InstanceGuid.ToString(), true, Receivers.Server,
                                                   MessageGroupIds.NETWORK_ID_REQUEST, true));
                    }
                    else
                    {
                        // Improper header, so a disconnect is required
                        Disconnect(true);
                        return;
                    }
                }

                while (bytesAlreadyProcessed < e.BytesTransferred)
                {
                    byte[] data = HandleData(e, true, ref bytesAlreadyProcessed);
                    if (data == null)
                    {
                        break;
                    }

                    FrameStream frame = Factory.DecodeMessage(data, false, MessageGroupIds.TCP_FIND_GROUP_ID, Server);

                    FireRead(frame, Server);
                }

                DoRead(e);
            }
            else
            {
                Disconnect(true);
            }
        }
Exemplo n.º 11
0
        private void CompleteHeaderExchange()
        {
            initialConnectHeaderExchanged = true;

            // TODO:  When getting the user id, it should also get the server time by using
            // the current time in the payload and getting it back along with server time

            // Ping the server to finalize the player's connection
            var textFrame = Text.CreateFromString(Time.Timestep, InstanceGuid.ToString(), false,
                                                  Receivers.Server, MessageGroupIds.NETWORK_ID_REQUEST, false);

            Send(textFrame, true);
        }
Exemplo n.º 12
0
        private void RunRadiance(string inputJson, List <GH_Mesh> geometry, string cacheKey, bool compute)
        {
            var geometryFile = Export.STLObject(geometry);
            var results      = Compute.Create(
                inputJson,
                geometryFile,
                "Probe",
                compute
                );

            StringCache.setCache(cacheKey, results);
            StringCache.setCache(InstanceGuid.ToString(), "");
            if (compute)
            {
                StringCache.setCache(cacheKey + "create", "true");
            }
        }
Exemplo n.º 13
0
        public void PutOnQueue(FunctionToQueue functionToQueue, string cachedValues, bool create)
        {
            if (cachedValues != null && !create)
            {
                return;
            }

            // Get queue lock
            var queueLock = StringCache.getCache(QueueName);

            if (queueLock == "true")
            {
                return;
            }

            StringCache.setCache(QueueName, "true");
            StringCache.setCache(CacheKey, null);
            QueueManager.addToQueue(QueueName, () =>
            {
                try
                {
                    cachedValues = functionToQueue();
                    StringCache.setCache(CacheKey, cachedValues);
                    if (create)
                    {
                        StringCache.setCache(CacheKey + "create", "true");
                    }
                }
                catch (NoObjectFoundException)
                {
                    StringCache.setCache(CacheKey + "create", "");
                }
                catch (Exception e)
                {
                    StringCache.setCache(InstanceGuid.ToString(), e.Message);
                    StringCache.setCache(CacheKey, "error");
                    StringCache.setCache(CacheKey + "create", "");
                }


                ExpireSolutionThreadSafe(true);
                Thread.Sleep(2000);
                StringCache.setCache(QueueName, "");
            });
        }
Exemplo n.º 14
0
        private void RunCFD(string inputJson, List <GH_Mesh> geometry, string cacheKey, bool compute)
        {
            var geometryFile       = Export.STLObject(geometry);
            var refinementGeometry = Export.RefinementRegionsToSTL(geometry);
            var results            = Compute.Create(
                inputJson,
                geometryFile,
                refinementGeometry,
                compute
                );

            StringCache.setCache(cacheKey, results);
            StringCache.setCache(InstanceGuid.ToString(), "");
            if (compute)
            {
                StringCache.setCache(cacheKey + "create", "true");
            }
        }
        public void Connect(string host = "0.0.0.0", ushort port = DEFAULT_PORT, string natHost = "", ushort natPort = NatHolePunch.DEFAULT_NAT_SERVER_PORT)
        {
            try
            {
                Client = new CachedUdpClient(port);
                Client.EnableBroadcast = true;
                Me = new NetworkingPlayer(ServerPlayerCounter++, host, true, ResolveHost(host, port), this);
                Me.InstanceGuid = InstanceGuid.ToString();

                // Create the thread that will be listening for new data from connected clients and start its execution
                Task.Queue(ReadClients);

                // Create the thread that will check for player timeouts
                Task.Queue(CheckClientTimeout);

                // Do any generic initialization in result of the successful bind
                OnBindSuccessful();

                //Let myself know I connected successfully
                OnPlayerConnected(Me);
                // Set myself as a connected client
                Me.Connected = true;

                //Set the port
                SetPort((ushort)((IPEndPoint)Client.Client.LocalEndPoint).Port);

                if (!string.IsNullOrEmpty(natHost))
                {
                    nat.Register((ushort)Me.IPEndPointHandle.Port, natHost, natPort);
                    nat.clientConnectAttempt += NatClientConnectAttempt;
                }
            }
            catch (Exception e)
            {
                Logging.BMSLog.LogException(e);
                // Do any generic initialization in result of the binding failure
                OnBindFailure();

                throw new FailedBindingException("Failed to bind to host/port, see inner exception", e);
            }
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string inputJson = null;
            var    mesh      = new GH_Structure <GH_Mesh>();
            var    points    = new GH_Structure <GH_Point>();
            var    normals   = new GH_Structure <GH_Vector>();
            var    names     = new List <string>();
            var    create    = false;

            if (!DA.GetData(0, ref inputJson))
            {
                return;
            }
            if (!DA.GetDataTree(1, out mesh))
            {
                return;
            }
            if (!DA.GetDataTree(2, out points))
            {
                return;
            }
            if (!DA.GetDataTree(3, out normals))
            {
                return;
            }
            if (!DA.GetDataList(4, names))
            {
                for (var i = 0; i < points.Branches.Count; i++)
                {
                    names.Add($"set{i.ToString()}");
                }
            }

            DA.GetData(5, ref create);



            // Get Cache to see if we already did this
            var cacheKey     = string.Join("", points) + string.Join("", names) + inputJson;
            var cachedValues = StringCache.getCache(cacheKey);

            DA.DisableGapLogic();

            if (cachedValues == null || create)
            {
                var queueName = "radiationProbe";

                // Get queue lock
                var queueLock = StringCache.getCache(queueName);
                if (queueLock != "true")
                {
                    StringCache.setCache(queueName, "true");
                    StringCache.setCache(cacheKey, null);
                    QueueManager.addToQueue(queueName, () =>
                    {
                        try
                        {
                            var meshFile = Export.MeshToObj(mesh, names);
                            var results  = Probe.RadiationProbes(
                                inputJson,
                                Geometry.ConvertPointsToList(points),
                                Geometry.ConvertPointsToList(normals),
                                names,
                                meshFile,
                                create
                                );
                            cachedValues = results;
                            StringCache.setCache(cacheKey, cachedValues);
                            if (create)
                            {
                                StringCache.setCache(cacheKey + "create", "true");
                            }
                        }
                        catch (NoObjectFoundException)
                        {
                            StringCache.setCache(cacheKey + "create", "");
                        }
                        catch (Exception e)
                        {
                            StringCache.setCache(InstanceGuid.ToString(), e.Message);
                            StringCache.setCache(cacheKey, "error");
                            StringCache.setCache(cacheKey + "create", "");
                        }


                        ExpireSolutionThreadSafe(true);
                        Thread.Sleep(2000);
                        StringCache.setCache(queueName, "");
                    });
                }
            }

            // Handle Errors
            var errors = StringCache.getCache(InstanceGuid.ToString());

            if (errors != null)
            {
                if (errors.Contains("No object found"))
                {
                    Message = "No Probe Task found.";
                }
                else
                {
                    throw new Exception(errors);
                }
            }

            // Read from Cache
            Message = "";
            if (cachedValues != null)
            {
                var outputs = cachedValues;
                DA.SetData(0, outputs);
                if (StringCache.getCache(cacheKey + "create") == "true")
                {
                    Message = "Task Created";
                }
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string folder  = null;
            var    refresh = false;

            if (!DA.GetData(0, ref folder))
            {
                return;
            }
            DA.GetData(1, ref refresh);

            // Get Cache to see if we already did this
            var cacheKey     = folder;
            var cachedValues = StringCache.getCache(cacheKey);

            DA.DisableGapLogic();

            if (cachedValues == null || refresh)
            {
                const string queueName = "radiationProbeResults";
                StringCache.setCache(InstanceGuid.ToString(), "");

                // Get queue lock
                var queueLock = StringCache.getCache(queueName);
                if (queueLock != "true")
                {
                    StringCache.setCache(queueName, "true");
                    StringCache.setCache(cacheKey + "progress", "Loading...");

                    QueueManager.addToQueue(queueName, () =>
                    {
                        try
                        {
                            var results  = RadiationProbeResult.ReadResults(folder);
                            probeResults = ConvertToDataTree(results);
                            info         = UpdateInfo(results);
                            StringCache.setCache(cacheKey + "progress", "Done");
                            StringCache.setCache(cacheKey, "results");
                        }
                        catch (Exception e)
                        {
                            StringCache.setCache(InstanceGuid.ToString(), e.Message);
                            StringCache.setCache(cacheKey, "error");
                            StringCache.setCache(cacheKey + "progress", "");
                        }

                        ExpireSolutionThreadSafe(true);
                        Thread.Sleep(2000);
                        StringCache.setCache(queueName, "");
                    });
                    ExpireSolutionThreadSafe(true);
                }
            }

            HandleErrors();

            if (info != null)
            {
                DA.SetDataTree(0, info);
            }

            if (probeResults != null)
            {
                DA.SetDataTree(1, probeResults);
            }

            Message = StringCache.getCache(cacheKey + "progress");
        }
Exemplo n.º 18
0
        /// <summary>
        /// Infinite loop listening for new data from all connected clients on a separate thread.
        /// This loop breaks when readThreadCancel is set to true
        /// </summary>
        private void ReadNetwork()
        {
            CSteamID messageFrom = default(CSteamID);

            try
            {
                BMSByte packet = null;
                // Intentional infinite loop
                while (IsBound)
                {
                    // If the read has been flagged to be canceled then break from this loop
                    if (readThreadCancel)
                    {
                        return;
                    }

                    try
                    {
                        uint msgSize = 0;

                        if (SteamNetworking.IsP2PPacketAvailable(out msgSize))
                        {
                            packet = Client.Receive(msgSize, out messageFrom);
                        }
                        else
                        {
                            Thread.Sleep(1);
                            continue;
                        }
                        // Read a packet from the network


                        if (PacketLossSimulation > 0.0f && new Random().NextDouble() <= PacketLossSimulation)
                        {
                            // Skip this message
                            continue;
                        }

                        BandwidthIn += (ulong)packet.Size;
                    }
                    catch (SocketException ex)
                    {
                        // This is a common exception when we exit the blocking call
                        Logging.BMSLog.LogException(ex);
                        Disconnect(true);
                    }

                    // Check to make sure a message was received
                    if (packet == null || packet.Size <= 0)
                    {
                        continue;
                    }

                    // Check to see if the headers have been exchanged
                    if (!headerExchanged)
                    {
                        if (Websockets.ValidateResponseHeader(headerHash, packet.CompressBytes()))
                        {
                            headerExchanged = true;

                            // TODO:  When getting the user id, it should also get the server time
                            // by using the current time in the payload and getting it back along with server time

                            // Ping the server to finalize the player's connection
                            Send(Text.CreateFromString(Time.Timestep, InstanceGuid.ToString(), false, Receivers.Server, MessageGroupIds.NETWORK_ID_REQUEST, false), true);
                        }
                        else if (packet.Size != 1 || packet[0] != 0)
                        {
                            Logging.BMSLog.LogWarning("DISCONNECTED: RECEIVED UNKNOWN PACKET BEFORE HEADERS WERE EXCHANGED!");
                            Disconnect(true);
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (packet.Size < 17)
                        {
                            continue;
                        }

                        // Format the byte data into a UDPPacket struct
                        UDPPacket formattedPacket = TranscodePacket(Server, packet);

                        // Check to see if this is a confirmation packet, which is just
                        // a packet to say that the reliable packet has been read
                        if (formattedPacket.isConfirmation)
                        {
                            if (formattedPacket.groupId == MessageGroupIds.DISCONNECT)
                            {
                                CloseConnection();
                                return;
                            }

                            OnMessageConfirmed(server, formattedPacket);
                            continue;
                        }

                        // Add the packet to the manager so that it can be tracked and executed on complete
                        packetManager.AddPacket(formattedPacket, PacketSequenceComplete, this);
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.BMSLog.LogException(ex);
                Disconnect(true);
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Infinite loop listening for new data from all connected clients on a separate thread.
        /// This loop breaks when readThreadCancel is set to true
        /// </summary>
        /// <summary>
        ///无限循环在单独的线程上监听来自所有连接客户端的新数据。
        ///当readThreadCancel设置为true时,此循环中断
        /// </ summary>
        private void ReadNetwork()
        {
            IPEndPoint groupEP          = new IPEndPoint(IPAddress.Any, 0);
            string     incomingEndpoint = string.Empty;

            try
            {
                BMSByte packet = null;
                // Intentional infinite loop
                while (IsBound)
                {
                    //如果读取已被标记为取消,则从此循环中断开
                    // If the read has been flagged to be canceled then break from this loop
                    if (readThreadCancel)
                    {
                        return;
                    }

                    try
                    {
                        // Read a packet from the network
                        packet = Client.Receive(ref groupEP, ref incomingEndpoint);

                        if (PacketLossSimulation > 0.0f && new Random().NextDouble() <= PacketLossSimulation)
                        {
                            // Skip this message
                            continue;
                        }

                        BandwidthIn += (ulong)packet.Size;
                    }
                    catch (SocketException /*ex*/)
                    {
                        // This is a common exception when we exit the blocking call
                        //Logging.BMSLog.LogException(ex);
                        Disconnect(true);
                    }

                    // Check to make sure a message was received
                    if (packet == null || packet.Size <= 0)
                    {
                        continue;
                    }

                    // This message was not from the server
                    if (groupEP.Address != Server.IPEndPointHandle.Address &&
                        groupEP.Port != Server.IPEndPointHandle.Port)
                    {
                        if (packet.Size == 1 && (packet[0] == SERVER_BROADCAST_CODE || packet[1] == CLIENT_BROADCAST_CODE))
                        {
                        }
                        else if (packet.Size.Between(2, 4) && packet[0] == BROADCAST_LISTING_REQUEST_1 && packet[1] == BROADCAST_LISTING_REQUEST_2 && packet[2] == BROADCAST_LISTING_REQUEST_3)
                        {
                            //这可能是一个本地列表请求,所以用客户端标志字节进行响应
                            // This may be a local listing request so respond with the client flag byte
                            Client.Send(new byte[] { CLIENT_BROADCAST_CODE }, 1, groupEP);
                        }

                        continue;
                    }

                    // Check to see if the headers have been exchanged
                    if (!headerExchanged)
                    {
                        if (Websockets.ValidateResponseHeader(headerHash, packet.CompressBytes()))
                        {
                            headerExchanged = true;

                            // TODO:  When getting the user id, it should also get the server time
                            // by using the current time in the payload and getting it back along with server time

                            // Ping the server to finalize the player's connection
                            Send(Text.CreateFromString(Time.Timestep, InstanceGuid.ToString(), false, Receivers.Server, MessageGroupIds.NETWORK_ID_REQUEST, false), true);
                        }
                        else if (packet.Size != 1 || packet[0] != 0)
                        {
                            Disconnect(true);
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (packet.Size < 17)
                        {
                            continue;
                        }

                        // 格式的字节数据到一个udppacket结构
                        // Format the byte data into a UDPPacket struct
                        UDPPacket formattedPacket = TranscodePacket(Server, packet);

                        // Check to see if this is a confirmation packet, which is just
                        // a packet to say that the reliable packet has been read
                        if (formattedPacket.isConfirmation)
                        {
                            if (formattedPacket.groupId == MessageGroupIds.DISCONNECT)
                            {
                                CloseConnection();
                                return;
                            }

                            OnMessageConfirmed(server, formattedPacket);
                            continue;
                        }

                        //将数据包添加到管理器,以便可以在完成时跟踪和执行
                        // Add the packet to the manager so that it can be tracked and executed on complete
                        packetManager.AddPacket(formattedPacket, PacketSequenceComplete, this);
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.BMSLog.LogException(ex);
                Disconnect(true);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Infinite loop listening for new data from all connected clients on a separate thread.
        /// This loop breaks when readThreadCancel is set to true
        /// </summary>
        private void ReadNetwork()
        {
            IPEndPoint groupEP          = new IPEndPoint(IPAddress.Any, 0);
            string     incomingEndpoint = string.Empty;

            try
            {
                BMSByte packet = null;
                // Intentional infinite loop
                while (IsBound)
                {
                    // If the read has been flagged to be canceled then break from this loop
                    if (readThreadCancel)
                    {
                        return;
                    }

                    try
                    {
                        // Read a packet from the network
                        packet = Client.Receive(ref groupEP, ref incomingEndpoint);

                        if (PacketLossSimulation > 0.0f && new Random().NextDouble() <= PacketLossSimulation)
                        {
                            // Skip this message
                            continue;
                        }

                        BandwidthIn += (ulong)packet.Size;
                    }
                    catch (SocketException /*ex*/)
                    {
                        // This is a common exception when we exit the blocking call
                        //Logging.BMSLog.LogException(ex);
                        Disconnect(true);
                    }

                    // Check to make sure a message was received
                    if (packet == null || packet.Size <= 0)
                    {
                        continue;
                    }

                    // This message was not from the server
                    if (groupEP.Address != Server.IPEndPointHandle.Address &&
                        groupEP.Port != Server.IPEndPointHandle.Port)
                    {
                        if (packet.Size == 1 && (packet[0] == SERVER_BROADCAST_CODE || packet[1] == CLIENT_BROADCAST_CODE))
                        {
                        }
                        else if (packet.Size.Between(2, 4) && packet[0] == BROADCAST_LISTING_REQUEST_1 && packet[1] == BROADCAST_LISTING_REQUEST_2 && packet[2] == BROADCAST_LISTING_REQUEST_3)
                        {
                            // This may be a local listing request so respond with the client flag byte
                            Client.Send(new byte[] { CLIENT_BROADCAST_CODE }, 1, groupEP);
                        }

                        continue;
                    }

                    // Check to see if the headers have been exchanged
                    if (!headerExchanged)
                    {
                        if (Websockets.ValidateResponseHeader(headerHash, packet.CompressBytes()))
                        {
                            headerExchanged = true;

                            // TODO:  When getting the user id, it should also get the server time
                            // by using the current time in the payload and getting it back along with server time

                            // Ping the server to finalize the player's connection
                            Send(Text.CreateFromString(Time.Timestep, InstanceGuid.ToString(), false, Receivers.Server, MessageGroupIds.NETWORK_ID_REQUEST, false), true);
                        }
                        else if (packet.Size >= MINIMUM_FRAME_SIZE)
                        {
                            // The server sent us a message before sending a responseheader to validate
                            // This happens if the server is not accepting connections or the max connection count has been reached
                            // We will get two messages. The first one is either a MAX_CONNECTIONS or NOT_ACCEPT_CONNECTIONS group message.
                            // The second one will be the DISCONNECT message
                            UDPPacket formattedPacket = TranscodePacket(Server, packet);

                            if (formattedPacket.groupId == MessageGroupIds.MAX_CONNECTIONS)
                            {
                                Logging.BMSLog.LogWarning("Max Players Reached On Server");
                                // Wait for the second message (Disconnect)
                                continue;
                            }

                            if (formattedPacket.groupId == MessageGroupIds.NOT_ACCEPT_CONNECTIONS)
                            {
                                Logging.BMSLog.LogWarning("The server is busy and not accepting connections");
                                // Wait for the second message (Disconnect)
                                continue;
                            }

                            if (formattedPacket.groupId == MessageGroupIds.DISCONNECT)
                            {
                                CloseConnection();
                                return;
                            }

                            // Received something unexpected so do the same thing as the if below
                            Disconnect(true);
                            break;
                        }
                        else if (packet.Size != 1 || packet[0] != 0)
                        {
                            Disconnect(true);
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (packet.Size < MINIMUM_FRAME_SIZE)
                        {
                            continue;
                        }

                        // Format the byte data into a UDPPacket struct
                        UDPPacket formattedPacket = TranscodePacket(Server, packet);

                        // Check to see if this is a confirmation packet, which is just
                        // a packet to say that the reliable packet has been read
                        if (formattedPacket.isConfirmation)
                        {
                            if (formattedPacket.groupId == MessageGroupIds.DISCONNECT)
                            {
                                CloseConnection();
                                return;
                            }

                            OnMessageConfirmed(server, formattedPacket);
                            continue;
                        }

                        if (formattedPacket.groupId == MessageGroupIds.AUTHENTICATION_FAILURE)
                        {
                            Logging.BMSLog.LogWarning("The server rejected the authentication attempt");
                            // Wait for the second message (Disconnect)
                            continue;
                        }

                        // Add the packet to the manager so that it can be tracked and executed on complete
                        packetManager.AddPacket(formattedPacket, PacketSequenceComplete, this);
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.BMSLog.LogException(ex);
                Disconnect(true);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// This will begin the connection for TCP, this is a thread blocking operation until the connection
        /// is either established or has failed
        /// </summary>
        /// <param name="hostAddress">[127.0.0.1] Ip Address to host from</param>
        /// <param name="port">[15937] Port to allow connections from</param>
        public void Connect(string hostAddress = "0.0.0.0", ushort port = DEFAULT_PORT)
        {
            if (Disposed)
            {
                throw new ObjectDisposedException("TCPServer", "This object has been disposed and can not be used to connect, please use a new TCPServer");
            }

            if (string.IsNullOrEmpty(hostAddress))
            {
                throw new BaseNetworkException("An ip address must be specified to bind to. If you are unsure, you can set to 127.0.0.1");
            }

            // Check to see if this server is being bound to a "loopback" address, if so then bind to any, otherwise bind to specified address
            if (hostAddress == "0.0.0.0" || hostAddress == "localhost")
            {
                ipAddress = IPAddress.Any;
            }
            else
            {
                ipAddress = IPAddress.Parse(hostAddress);
            }

            try
            {
                // Setup and start the base C# TcpListner
                listener = new TcpListener(ipAddress, port);
                //listener.Start();

                Me = new NetworkingPlayer(ServerPlayerCounter++, "0.0.0.0", true, listener, this);
                Me.InstanceGuid = InstanceGuid.ToString();

                // Create the thread that will be listening for clients and start its execution
                //Thread connectionThread = new Thread(new ThreadStart(ListenForConnections));
                //connectionThread.Start();
                //Task.Queue(ListenForConnections);
                listener.Start();
                listener.BeginAcceptTcpClient(ListenForConnections, listener);

                //在成功绑定的结果中执行任何通用初始化
                // Do any generic initialization in result of the successful bind
                OnBindSuccessful();

                //创建将监听来自连接客户端的新数据并开始执行的线程
                // Create the thread that will be listening for new data from connected clients and start its execution
                Task.Queue(ReadClients);

                // 创建将检查播放器超时的线程
                // Create the thread that will check for player timeouts
                Task.Queue(() =>
                {
                    // TODO ZF 关闭检测超时
                    //commonServerLogic.CheckClientTimeout((player) =>
                    //{
                    //    Disconnect(player, true);
                    //    OnPlayerTimeout(player);
                    //    CleanupDisconnections();
                    //});
                });

                //让我知道我连接成功
                //Let myself know I connected successfully
                OnPlayerConnected(Me);
                //将自己设置为连接的客户端
                // Set myself as a connected client
                Me.Connected = true;

                //设置端口
                //Set the port
                SetPort((ushort)((IPEndPoint)listener.LocalEndpoint).Port);
            }
            catch (Exception e)
            {
                BMSLog.LogException(e);
                // Do any generic initialization in result of the binding failure
                OnBindFailure();

                throw new FailedBindingException("Failed to bind to host/port, see inner exception", e);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string inputJson   = null;
            var    points      = new GH_Structure <GH_Point>();
            var    names       = new List <string>();
            var    fields      = new List <string>();
            var    mesh        = new GH_Structure <GH_Mesh>();
            var    cpus        = 1;
            var    dependentOn = "VirtualWindTunnel";
            var    caseDir     = "VWT";
            var    overrides   = "";
            var    create      = false;

            if (!DA.GetData(0, ref inputJson))
            {
                return;
            }
            if (!DA.GetDataTree(1, out points))
            {
                return;
            }
            if (!DA.GetDataList(2, names))
            {
                for (var i = 0; i < points.Branches.Count; i++)
                {
                    names.Add($"set{i.ToString()}");
                }
            }
            else
            {
                foreach (var name in names)
                {
                    ValidateName(name);
                }
            }

            if (!DA.GetDataList(3, fields))
            {
                fields.Add("U");
            }

            DA.GetDataTree(4, out mesh);
            DA.GetData(5, ref cpus);
            DA.GetData(6, ref dependentOn);
            DA.GetData(7, ref caseDir);
            DA.GetData(8, ref overrides);
            DA.GetData(9, ref create);

            var convertedPoints = Geometry.ConvertPointsToList(points);

            caseDir = caseDir.TrimEnd('/');

            // Get Cache to see if we already did this
            var cacheKey     = inputJson + string.Join("", points) + string.Join("", fields) + string.Join("", names);
            var cachedValues = StringCache.getCache(cacheKey);

            DA.DisableGapLogic();

            if (cachedValues == null || create)
            {
                var queueName = "probe";

                // Get queue lock
                var queueLock = StringCache.getCache(queueName);
                if (queueLock != "true")
                {
                    StringCache.setCache(queueName, "true");
                    StringCache.setCache(cacheKey, null);
                    QueueManager.addToQueue(queueName, () =>
                    {
                        try
                        {
                            var meshFile = Export.MeshToObj(mesh, names);
                            var results  = Probe.ProbePoints(
                                inputJson,
                                convertedPoints,
                                fields,
                                names,
                                ComponentUtils.ValidateCPUs(cpus),
                                meshFile,
                                dependentOn,
                                caseDir,
                                overrides,
                                create
                                );
                            cachedValues = results;
                            StringCache.setCache(cacheKey, cachedValues);
                            if (create)
                            {
                                StringCache.setCache(cacheKey + "create", "true");
                            }
                        }
                        catch (NoObjectFoundException)
                        {
                            StringCache.setCache(cacheKey + "create", "");
                        }
                        catch (Exception e)
                        {
                            StringCache.setCache(InstanceGuid.ToString(), e.Message);
                            StringCache.setCache(cacheKey, "error");
                            StringCache.setCache(cacheKey + "create", "");
                        }


                        ExpireSolutionThreadSafe(true);
                        Thread.Sleep(2000);
                        StringCache.setCache(queueName, "");
                    });
                }
            }

            HandleErrors();
            Message = "";

            if (cachedValues != null)
            {
                DA.SetData(0, cachedValues);

                if (StringCache.getCache(cacheKey + "create") == "true")
                {
                    Message = "Task Created";
                }
            }
        }
Exemplo n.º 23
0
        protected void ButtonPostComment_Click(object sender, EventArgs e)
        {
            // check the Honeypot
            if (TextBoxPhone.Text == string.Empty && this.InstanceGuid != Guid.Empty)
            {
                int indexUrl = Request.Url.AbsoluteUri.IndexOf(":" + Request.Url.Port.ToString());
                if (indexUrl <= 0)
                {
                    indexUrl = Request.Url.AbsoluteUri.IndexOf(Request.Url.AbsolutePath);
                }
                string siteUrl = Request.Url.AbsoluteUri.Substring(0, indexUrl) + Request.ApplicationPath + "/";
                using (MainDataSetTableAdapters.CommentTableAdapter taComment = new MainDataSetTableAdapters.CommentTableAdapter())
                {
                    Organization currOrganization           = null;
                    MainDataSet.Mc_InstanceRow currInstance = null;
                    using (MainDataSetTableAdapters.Mc_InstanceTableAdapter taInstance = new MainDataSetTableAdapters.Mc_InstanceTableAdapter())
                    {
                        MainDataSet.Mc_InstanceDataTable instances = taInstance.GetDataByInstanceId(this.InstanceGuid);
                        if (instances.Count > 0)
                        {
                            currInstance     = instances[0];
                            currOrganization = Micajah.Common.Bll.Providers.OrganizationProvider.GetOrganization(currInstance.OrganizationId);
                        }
                    }
                    DateTime dtNow = DateTime.Now;
                    if (this.ArticleGuid == Guid.Empty)
                    {
                        // create a reqest
                        Guid newId = Guid.NewGuid();
                        // create a request
                        if (this.ArticleTableAdapter.Insert(newId,
                                                            this.InstanceGuid,
                                                            new Guid?(),
                                                            ArticleType.Request.ToString(),
                                                            (this.AlternateId != string.Empty) ? this.AlternateId : HttpUtility.HtmlEncode(Utils.ShortCommentText(TextBoxComment.Text, 50)),
                                                            (string)this.GetLocalResourceObject("BodyNotArticle"),
                                                            string.Empty,
                                                            0,
                                                            0,
                                                            0,
                                                            false,
                                                            new DateTime?(),
                                                            new DateTime?(),
                                                            new DateTime?(),
                                                            new Guid?(),
                                                            new Guid?(),
                                                            new Guid?()) > 0)
                        {
                            MainDataSet.CommentDataTable commentDataTable = taComment.InsertComment(newId,
                                                                                                    TextBoxName.Text,
                                                                                                    TextBoxEmail.Text,
                                                                                                    string.Format("{0} ({1})", Request.UserHostName, Request.UserHostAddress),
                                                                                                    HttpUtility.HtmlEncode(Utils.ShortCommentText(TextBoxComment.Text, 50)),
                                                                                                    HttpUtility.HtmlEncode(TextBoxComment.Text),
                                                                                                    false,
                                                                                                    true,
                                                                                                    DateTime.Now, true);
                            if (commentDataTable != null && commentDataTable.Rows.Count > 0)
                            {
                                if (CommentPosted != null)
                                {
                                    CommentPosted(this, new ArticleEventArgs(newId, true));
                                }
                                if (currOrganization != null && currInstance != null)
                                {
                                    string subj;
                                    Micajah.Common.Dal.OrganizationDataSet.UserDataTable users = Micajah.Common.Bll.Providers.UserProvider.GetUsers(
                                        currOrganization.OrganizationId,
                                        this.InstanceGuid,
                                        new string[] { "InstAdmin" });

                                    ArrayList admins = new ArrayList();
                                    ArrayList SendTo = new ArrayList();

                                    admins.AddRange(this.InputListAdmin);

                                    foreach (Micajah.Common.Dal.OrganizationDataSet.UserRow row in users)
                                    {
                                        admins.Add(row.Email);
                                    }

                                    SendTo.AddRange(admins);

                                    MainDataSetTableAdapters.EmailsTableAdapter emailsTableAdapter = new MainDataSetTableAdapters.EmailsTableAdapter();
                                    foreach (DataRow row in emailsTableAdapter.GetArticleEmails(ArticleGuid).Rows)
                                    {
                                        if (!SendTo.Contains(row["UserEmail"].ToString()))
                                        {
                                            SendTo.Add(row["UserEmail"].ToString());
                                        }
                                    }

                                    foreach (DataRow row in emailsTableAdapter.GetUnsubscribedEmails(ArticleGuid, this.InstanceGuid).Rows)
                                    {
                                        SendTo.Remove(row["UserEmail"].ToString());
                                    }

                                    string SendToList = string.Empty;
                                    bool   separated  = false;
                                    for (int i = 0; i < SendTo.Count; i++)
                                    {
                                        if (!separated && !admins.Contains(SendTo[i].ToString()))
                                        {
                                            SendToList += "<br><br>Commentors:<br>" + SendTo[i].ToString();
                                            separated   = true;
                                        }
                                        else
                                        {
                                            SendToList += ", " + SendTo[i].ToString();
                                        }
                                    }
                                    SendToList = SendToList.Remove(0, 1);

                                    if (SendTo.Count > 0)
                                    {
                                        for (int i = 0; i < SendTo.Count; i++)
                                        {
                                            subj = (this.AlternateId != string.Empty) ? this.AlternateId : HttpUtility.HtmlEncode(Utils.ShortCommentText(TextBoxComment.Text, 50));
                                            StringBuilder body = new StringBuilder((string)this.GetLocalResourceObject("EmailBody_Request"));
                                            body.Replace("{OrgName}", currOrganization.Name);
                                            body.Replace("{InstName}", currInstance.Name);
                                            body.Replace("{ArticleName}", subj);
                                            body.Replace("{ArticleUrl}", siteUrl + string.Format(CultureInfo.CurrentCulture, "?i={0}&t={1}", this.InstanceGuid.ToString("N"), newId.ToString("N")));
                                            body.Replace("{ArticleText}", HttpUtility.HtmlEncode(TextBoxComment.Text));
                                            body.Replace("{AuthorName}", TextBoxName.Text);
                                            body.Replace("{AuthorEmail}", string.IsNullOrEmpty(TextBoxEmail.Text) ? string.Empty : string.Format(CultureInfo.CurrentCulture, "<a href=\"mailto:{0}\" target=\"_blank\">{0}</a>", TextBoxEmail.Text));
                                            body.Replace("{ImageUrl}", siteUrl + Micajah.Common.Configuration.FrameworkConfiguration.Current.WebApplication.Copyright.CompanyLogoImageUrl);
                                            if (body.Length > 0)
                                            {
                                                string encrypted = Utils.Encrypt(String.Format("{0}&{1}&{2}&{3}&{4}", SendTo[i].ToString(), 1, commentDataTable[0].CommentId.ToString(CultureInfo.InvariantCulture), InstanceGuid.ToString(), UserContext.SelectedOrganizationId.ToString()), "Dshd*&^*@dsdss", "237w&@2d", "SHA1", 2, "&s2hfyDjuf372*73", 256);
                                                string url       = siteUrl + String.Format("Unsubscribe.aspx?token={0}", encrypted);
                                                body.Replace("{UnsubscribeFromArticleUrl}", url);
                                                encrypted = Utils.Encrypt(String.Format("{0}&{1}&{2}&{3}&{4}", SendTo[i].ToString(), 2, commentDataTable[0].CommentId.ToString(CultureInfo.InvariantCulture), InstanceGuid.ToString(), UserContext.SelectedOrganizationId.ToString()), "Dshd*&^*@dsdss", "237w&@2d", "SHA1", 2, "&s2hfyDjuf372*73", 256);
                                                url       = siteUrl + String.Format("Unsubscribe.aspx?token={0}", encrypted);
                                                body.Replace("{UnsubscribeFromAllUrl}", url);
                                                if (admins.Contains(SendTo[i]))
                                                {
                                                    body.Replace("{SendToList}", "This message was also sent to:<br>" + SendToList);
                                                }
                                                else
                                                {
                                                    body.Replace("{SendToList}", string.Empty);
                                                }
                                                Utils.SendEmail("*****@*****.**", SendTo[i].ToString(), string.Format((string)this.GetLocalResourceObject("EmailSubjectRequest"), subj), body.ToString(), true, Micajah.Common.Configuration.FrameworkConfiguration.Current.WebApplication.Email.SmtpServer, true);
                                            }
                                        }
                                    }
                                }
                                ResetData();
                            }
                        }
                    }
                    else
                    {
                        // post to article
                        MainDataSet.CommentDataTable commentDataTable = taComment.InsertComment(this.ArticleGuid,
                                                                                                TextBoxName.Text,
                                                                                                TextBoxEmail.Text,
                                                                                                string.Format("{0} ({1})", Request.UserHostName, Request.UserHostAddress),
                                                                                                HttpUtility.HtmlEncode(Utils.ShortCommentText(TextBoxComment.Text, 50)),
                                                                                                HttpUtility.HtmlEncode(TextBoxComment.Text),
                                                                                                false,
                                                                                                true,
                                                                                                dtNow, true);
                        if (commentDataTable != null && commentDataTable.Rows.Count > 0)
                        {
                            if (CommentPosted != null)
                            {
                                CommentPosted(this, new ArticleEventArgs(this.ArticleGuid, false));
                            }
                            MainDataSet.ArticleRow articleRow = this.GetCurrentArticle();
                            if (currOrganization != null && articleRow != null && !articleRow.IsUpdatedByNull() && currInstance != null)
                            {
                                string author = string.Empty, subj;
                                subj = string.Format((string)this.GetLocalResourceObject("EmailSubjectComment"), articleRow.Subject);

                                System.Data.DataRow mcuser = Micajah.Common.Bll.Providers.UserProvider.GetUserRow(articleRow.UpdatedBy, currOrganization.OrganizationId);
                                if (mcuser != null)
                                {
                                    author = (string)mcuser["Email"];
                                }

                                Micajah.Common.Dal.OrganizationDataSet.UserDataTable users = Micajah.Common.Bll.Providers.UserProvider.GetUsers(
                                    currOrganization.OrganizationId,
                                    this.InstanceGuid,
                                    new string[] { "InstAdmin" });

                                ArrayList admins           = new ArrayList();
                                ArrayList SendTo           = new ArrayList();

                                admins.AddRange(this.InputListAdmin);
                                foreach (Micajah.Common.Dal.OrganizationDataSet.UserRow row in users)
                                {
                                    admins.Add(row.Email);
                                }
                                SendTo.AddRange(admins);

                                if (!string.IsNullOrEmpty(author) && !SendTo.Contains(author))
                                {
                                    SendTo.Add(author);
                                }

                                MainDataSetTableAdapters.EmailsTableAdapter emailsTableAdapter = new MainDataSetTableAdapters.EmailsTableAdapter();
                                foreach (DataRow row in emailsTableAdapter.GetArticleEmails(ArticleGuid).Rows)
                                {
                                    if (!SendTo.Contains(row["UserEmail"].ToString()))
                                    {
                                        SendTo.Add(row["UserEmail"].ToString());
                                    }
                                }

                                foreach (DataRow row in emailsTableAdapter.GetUnsubscribedEmails(ArticleGuid, this.InstanceGuid).Rows)
                                {
                                    SendTo.Remove(row["UserEmail"].ToString());
                                }

                                string SendToList = string.Empty;
                                bool   separated  = false;
                                for (int i = 0; i < SendTo.Count; i++)
                                {
                                    if (!separated && !admins.Contains(SendTo[i].ToString()))
                                    {
                                        SendToList += "<br><br>Commentors:<br>" + SendTo[i].ToString();
                                        separated   = true;
                                    }
                                    else
                                    {
                                        SendToList += ", " + SendTo[i].ToString();
                                    }
                                }
                                SendToList = SendToList.Remove(0, 1);

                                if (SendTo.Count > 0)
                                {
                                    for (int i = 0; i < SendTo.Count; i++)
                                    {
                                        StringBuilder body = new StringBuilder((string)this.GetLocalResourceObject("EmailBody_PostToArticle"));
                                        body.Replace("{OrgName}", currOrganization.Name);
                                        body.Replace("{InstName}", currInstance.Name);
                                        body.Replace("{ArticleName}", articleRow.Subject);
                                        body.Replace("{ArticleUrl}", siteUrl + string.Format(CultureInfo.CurrentCulture, "?i={0}&t={1}", this.InstanceGuid.ToString("N"), this.ArticleGuid.ToString("N")));
                                        body.Replace("{ArticleText}", HttpUtility.HtmlEncode(TextBoxComment.Text));
                                        body.Replace("{AuthorName}", TextBoxName.Text);
                                        body.Replace("{AuthorEmail}", string.IsNullOrEmpty(TextBoxEmail.Text) ? string.Empty : string.Format(CultureInfo.CurrentCulture, "<a href=\"mailto:{0}\" target=\"_blank\">{0}</a>", TextBoxEmail.Text));
                                        body.Replace("{ImageUrl}", siteUrl + Micajah.Common.Configuration.FrameworkConfiguration.Current.WebApplication.Copyright.CompanyLogoImageUrl);
                                        if (admins.Contains(SendTo[i]))
                                        {
                                            body.Replace("{SendToList}", "This message was also sent to:<br>" + SendToList);
                                        }
                                        else
                                        {
                                            body.Replace("{SendToList}", string.Empty);
                                        }

                                        if (body.Length > 0)
                                        {
                                            string encrypted = Utils.Encrypt(String.Format("{0}&{1}&{2}&{3}&{4}", SendTo[i].ToString(), 1, commentDataTable[0].CommentId.ToString(CultureInfo.InvariantCulture), InstanceGuid.ToString(), UserContext.SelectedOrganizationId.ToString()), "Dshd*&^*@dsdss", "237w&@2d", "SHA1", 2, "&s2hfyDjuf372*73", 256);
                                            string url       = siteUrl + String.Format("Unsubscribe.aspx?token={0}", encrypted);
                                            body.Replace("{UnsubscribeFromArticleUrl}", url);
                                            encrypted = Utils.Encrypt(String.Format("{0}&{1}&{2}&{3}&{4}", SendTo[i].ToString(), 2, commentDataTable[0].CommentId.ToString(CultureInfo.InvariantCulture), InstanceGuid.ToString(), UserContext.SelectedOrganizationId.ToString()), "Dshd*&^*@dsdss", "237w&@2d", "SHA1", 2, "&s2hfyDjuf372*73", 256);
                                            url       = siteUrl + String.Format("Unsubscribe.aspx?token={0}", encrypted);
                                            body.Replace("{UnsubscribeFromAllUrl}", url);
                                            Utils.SendEmail("*****@*****.**", SendTo[i].ToString(), subj, body.ToString(), true, Micajah.Common.Configuration.FrameworkConfiguration.Current.WebApplication.Email.SmtpServer, true);
                                        }
                                    }
                                }
                            }
                            ResetData();
                        }
                    }
                }
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string auth            = null;
            string projectName     = null;
            int?   projectNumber   = null;
            var    excludeChildren = true;
            var    refresh         = false;

            if (!DA.GetData(0, ref auth))
            {
                return;
            }
            if (!DA.GetData(1, ref projectName))
            {
                return;
            }
            DA.GetData(2, ref projectNumber);
            DA.GetData(3, ref excludeChildren);
            DA.GetData(4, ref refresh);

            // Get Cache to see if we already did this
            var cacheKey     = projectName + projectNumber + excludeChildren;
            var cachedValues = StringCache.getCache(cacheKey);

            DA.DisableGapLogic();

            if (cachedValues == null || refresh == true)
            {
                var queueName = "ListTasks" + cacheKey;

                // Get queue lock
                var queueLock = StringCache.getCache(queueName);
                if (queueLock != "true")
                {
                    StringCache.setCache(queueName, "true");
                    StringCache.setCache(cacheKey, null);
                    QueueManager.addToQueue(queueName, () =>
                    {
                        try
                        {
                            cachedValues = ProjectAndTask.GetTasks(
                                auth,
                                projectName,
                                projectNumber,
                                excludeChildren
                                );
                            StringCache.setCache(cacheKey, cachedValues);
                            StringCache.setCache(this.InstanceGuid.ToString(), "");
                        }
                        catch (NoObjectFoundException)
                        {
                            StringCache.setCache(cacheKey + "create", "");
                        }
                        catch (Exception e)
                        {
                            StringCache.setCache(InstanceGuid.ToString(), e.Message);
                            StringCache.setCache(cacheKey, "error");
                        }

                        ExpireSolutionThreadSafe(true);
                        Thread.Sleep(2000);
                        StringCache.setCache(queueName, "");
                    });
                }
            }

            HandleErrors();

            // Read from Cache
            if (cachedValues != null)
            {
                var outputs = cachedValues.Split(';');
                if (outputs.Length > 1)
                {
                    outputs = outputs.OrderBy(task => task).ToArray();
                }
                DA.SetDataList(0, outputs);
            }
        }
Exemplo n.º 25
0
 /// <summary>
 /// Logs software start with category InstanceGuid and insert three newlines.
 /// </summary>
 /// <param name="appName">The name of the app.</param>
 public static void LogStarting(string appName) => Log(LogLevel.Info, $"{appName} is starting...", category: InstanceGuid.ToString(), additionalEntrySeparators: 3, additionalEntrySeparatorsLogFileOnlyMode: true);
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string inputJson   = null;
            var    epwFile     = "";
            var    method      = 0;
            var    probes      = new List <string>();
            var    thresholds  = new List <string>();
            var    cpus        = 4;
            var    dependentOn = "Probe";
            var    create      = false;

            if (!DA.GetData(0, ref inputJson))
            {
                return;
            }
            if (inputJson == "error")
            {
                return;
            }
            if (!DA.GetData(1, ref epwFile))
            {
                return;
            }
            DA.GetData(2, ref method);
            if (!DA.GetDataList(3, probes))
            {
                return;
            }

            DA.GetDataList(4, thresholds);
            DA.GetData(5, ref cpus);

            DA.GetData(6, ref dependentOn);
            DA.GetData(8, ref create);

            // Get Cache to see if we already did this
            var cacheKey     = string.Join("", probes) + epwFile + inputJson + method;
            var cachedValues = StringCache.getCache(cacheKey);

            DA.DisableGapLogic();

            if (cachedValues == null || create)
            {
                const string queueName = "outdoorComfortSimulation";

                // Get queue lock
                var queueLock = StringCache.getCache(queueName);
                if (queueLock != "true")
                {
                    StringCache.setCache(queueName, "true");
                    StringCache.setCache(InstanceGuid.ToString(), "");
                    StringCache.setCache(cacheKey, null);
                    QueueManager.addToQueue(queueName, () =>
                    {
                        try
                        {
                            cachedValues = OutdoorComfort.CreateComfortTask(
                                inputJson,
                                epwFile,
                                Presets[method],
                                probes,
                                thresholds,
                                ComponentUtils.ValidateCPUs(cpus),
                                dependentOn,
                                create
                                );
                            StringCache.setCache(cacheKey, cachedValues);
                            if (create)
                            {
                                StringCache.setCache(cacheKey + "create", "true");
                            }
                        }
                        catch (NoObjectFoundException)
                        {
                            StringCache.setCache(cacheKey + "create", "");
                        }
                        catch (Exception e)
                        {
                            StringCache.AppendCache(InstanceGuid.ToString(), e.Message + "\n");
                            StringCache.setCache(cacheKey, "error");
                            StringCache.setCache(cacheKey + "create", "");
                        }


                        ExpireSolutionThreadSafe(true);
                        Thread.Sleep(2000);
                        StringCache.setCache(queueName, "");
                    });
                }
            }

            HandleErrors();

            // Read from Cache
            if (cachedValues != null)
            {
                DA.SetData(0, cachedValues);
                Message = "";
                if (StringCache.getCache(cacheKey + "create") == "true")
                {
                    Message = "Task Created";
                }
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string inputJson   = null;
            var    epwFile     = "";
            var    patches     = new List <string>();
            var    thresholds  = new List <string>();
            var    cpus        = 4;
            var    dependentOn = "Probe";
            var    create      = false;

            if (!DA.GetData(0, ref inputJson))
            {
                return;
            }
            if (inputJson == "error")
            {
                return;
            }
            if (!DA.GetData(1, ref epwFile))
            {
                return;
            }
            if (!DA.GetDataList(2, patches))
            {
                patches.Add("set1");
            }

            DA.GetDataList(3, thresholds);
            DA.GetData(4, ref cpus);

            DA.GetData(5, ref dependentOn);
            DA.GetData(6, ref create);

            // Get Cache to see if we already did this
            var cacheKey     = string.Join("", patches) + epwFile + inputJson;
            var cachedValues = StringCache.getCache(cacheKey);

            DA.DisableGapLogic();

            if (cachedValues == null || create)
            {
                var queueName = "windThreshold";

                // Get queue lock
                var queueLock = StringCache.getCache(queueName);
                if (queueLock != "true")
                {
                    StringCache.setCache(queueName, "true");
                    StringCache.setCache(InstanceGuid.ToString(), "");
                    StringCache.setCache(cacheKey, null);
                    QueueManager.addToQueue(queueName, () =>
                    {
                        try
                        {
                            var results = WindThreshold.ComputeWindThresholds(
                                inputJson,
                                epwFile,
                                patches,
                                thresholds,
                                ComponentUtils.ValidateCPUs(cpus),
                                dependentOn,
                                create
                                );
                            cachedValues = results;
                            StringCache.setCache(cacheKey, cachedValues);
                            if (create)
                            {
                                StringCache.setCache(cacheKey + "create", "true");
                            }
                        }
                        catch (NoObjectFoundException)
                        {
                            StringCache.setCache(cacheKey + "create", "");
                        }
                        catch (Exception e)
                        {
                            StringCache.setCache(InstanceGuid.ToString(), e.Message);
                            StringCache.setCache(cacheKey, "error");
                            StringCache.setCache(cacheKey + "create", "");
                        }


                        ExpireSolutionThreadSafe(true);
                        Thread.Sleep(2000);
                        StringCache.setCache(queueName, "");
                    });
                }
            }

            HandleErrors();

            // Read from Cache
            if (cachedValues != null)
            {
                DA.SetData(0, cachedValues);
                Message = "";
                if (StringCache.getCache(cacheKey + "create") == "true")
                {
                    Message = "Task Created";
                }
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Infinite loop listening for new data from all connected clients on a separate thread.
        /// This loop breaks when readThreadCancel is set to true
        /// </summary>
        protected ReadState Read()
        {
            if (disconnectedSelf)
            {
                return(ReadState.Disconnect);
            }

            NetworkStream stream = client.GetStream();

            if (stream == null)             //Some reason the stream is null!
            {
                return(ReadState.Continue);
            }

            // If the stream no longer can read then disconnect
            if (!stream.CanRead)
            {
                Disconnect(true);
                return(ReadState.Disconnect);
            }

            // If there isn't any data available, then free up the CPU by sleeping the thread
            if (!stream.DataAvailable)
            {
                return(ReadState.Continue);
            }

            int available = client.Available;

            if (available == 0)
            {
                return(ReadState.Continue);
            }

            // Determine if this client has been accepted by the server yet
            if (!headerExchanged)
            {
                // Read all available bytes in the stream as this client hasn't connected yet
                byte[] bytes = new byte[available];
                stream.Read(bytes, 0, bytes.Length);

                // The first packet response from the server is going to be a string
                if (Websockets.ValidateResponseHeader(headerHash, bytes))
                {
                    headerExchanged = true;

                    // Ping the server to finalize the player's connection
                    Send(Text.CreateFromString(Time.Timestep, InstanceGuid.ToString(), true, Receivers.Server, MessageGroupIds.NETWORK_ID_REQUEST, true));
                }
                else
                {
                    // Improper header, so a disconnect is required
                    Disconnect(true);
                    return(ReadState.Disconnect);
                }
            }
            else
            {
                byte[] messageBytes = GetNextBytes(stream, available, false);

                // Get the frame that was sent by the server, the server
                // does not send masked data, only the client so send false for mask
                FrameStream frame = Factory.DecodeMessage(messageBytes, false, MessageGroupIds.TCP_FIND_GROUP_ID, Server);

                if (frame is ConnectionClose)
                {
                    // Close our CachedUDPClient so that it can no longer be used
                    client.Close();
                    return(ReadState.Disconnect);
                }

                // A message has been successfully read from the network so relay that
                // to all methods registered to the event
                OnMessageReceived(Server, frame);
            }

            return(ReadState.Void);
        }
Exemplo n.º 29
0
        /// <summary>
        /// 无限循环在单独的线程上监听来自所有连接客户端的新数据。
        /// readThreadCancel设置为true时,此循环会中断
        ///
        /// Infinite loop listening for new data from all connected clients on a separate thread.
        /// This loop breaks when readThreadCancel is set to true
        /// </summary>
        protected ReadState Read()
        {
            if (disconnectedSelf)
            {
                return(ReadState.Disconnect);
            }

            NetworkStream stream = client.GetStream();

            if (stream == null)             //Some reason the stream is null! //某些原因流为空!
            {
                return(ReadState.Continue);
            }

            //如果流不再可读,则断开连接
            // If the stream no longer can read then disconnect
            if (!stream.CanRead)
            {
                Disconnect(true);
                return(ReadState.Disconnect);
            }

            //如果没有可用的数据,则通过休眠线程释放CPU
            // If there isn't any data available, then free up the CPU by sleeping the thread
            if (!stream.DataAvailable)
            {
                return(ReadState.Continue);
            }

            int available = client.Available;

            if (available == 0)
            {
                return(ReadState.Continue);
            }

            //确定这个客户端是否已被服务器接受
            // Determine if this client has been accepted by the server yet
            if (!headerExchanged)
            {
                //读取流中所有可用的字节,因为这个客户端还没有连接
                // Read all available bytes in the stream as this client hasn't connected yet
                byte[] bytes = new byte[available];
                stream.Read(bytes, 0, bytes.Length);

                //来自服务器的第一个数据包响应将是一个字符串
                // The first packet response from the server is going to be a string
                if (Websockets.ValidateResponseHeader(headerHash, bytes))
                {
                    headerExchanged = true;

                    //通过Ping服务器来确定玩家的连接
                    // Ping the server to finalize the player's connection
                    Send(Text.CreateFromString(Time.Timestep, InstanceGuid.ToString(), true, Receivers.Server, MessageGroupIds.NETWORK_ID_REQUEST, true));
                }
                else
                {
                    // Improper header, so a disconnect is required
                    Disconnect(true);
                    return(ReadState.Disconnect);
                }
            }
            else
            {
                byte[] messageBytes = GetNextBytes(stream, available, false);

                //获取由服务器,服务器发送的帧
                //不发送被屏蔽的数据,只有客户端发送false为掩码
                // Get the frame that was sent by the server, the server
                // does not send masked data, only the client so send false for mask
                FrameStream frame = Factory.DecodeMessage(messageBytes, false, MessageGroupIds.TCP_FIND_GROUP_ID, Server);

                FireRead(frame, Server);
            }

            return(ReadState.Void);
        }
Exemplo n.º 30
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var inputJson = "";
            var exclude   = "";
            var include   = "";
            var rerun     = false;

            if (!DA.GetData(0, ref inputJson))
            {
                return;
            }
            DA.GetData(1, ref exclude);
            DA.GetData(2, ref include);
            DA.GetData(3, ref rerun);

            // Get Cache to see if we already did this
            var cacheKey     = inputJson + "exc" + exclude + "inc" + include;
            var cachedValues = StringCache.getCache(cacheKey);

            DA.DisableGapLogic();

            if (cachedValues == null || rerun == true)
            {
                var queueName = "FileList" + cacheKey;

                // Get queue lock
                var queueLock = StringCache.getCache(queueName);
                if (queueLock != "true")
                {
                    StringCache.setCache(queueName, "true");
                    StringCache.setCache(cacheKey, null);
                    QueueManager.addToQueue(queueName, () =>
                    {
                        try
                        {
                            var results = FileList.GetFileList(
                                inputJson,
                                exclude,
                                include
                                );
                            cachedValues = results;
                            StringCache.setCache(cacheKey, cachedValues);
                            StringCache.setCache(InstanceGuid.ToString(), "");
                        }
                        catch (Exception e)
                        {
                            StringCache.setCache(InstanceGuid.ToString(), e.Message);
                            StringCache.setCache(cacheKey, "error");
                        }

                        ExpireSolutionThreadSafe(true);
                        Thread.Sleep(2000);
                        StringCache.setCache(queueName, "");
                    });
                }
            }

            // Read from Cache
            if (cachedValues != null)
            {
                var outputs = cachedValues.Split(',');
                if (outputs.Length > 1)
                {
                    outputs = outputs.OrderBy(file => file).ToArray();
                }
                DA.SetDataList(0, outputs);
            }

            HandleErrors();
        }