private void buttonSubmit_Click(object sender, EventArgs e)
        {
            using (Connection conn = new Connection("myConn"))
            {
                conn.Connect(textBoxServer.Text);
                conn.LogOn(textBoxUsername.Text, textBoxPassword.Text);

                DBObject dbObj = null;

                try
                {
                    int id = Convert.ToInt32(textBoxID.Text);
                    dbObj = conn.GetObject(new ObjectId(id));
                    if (dbObj == null) throw new Exception("Invalid object ID.");
                    if (!dbObj.IsGroup) throw new Exception("Object is not a group.");
                }

                catch (FormatException ex)
                {
                    MessageBox.Show("Enter a valid object ID.");
                    return;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }

                if (dbObj.ClassDefinition.Name == "CTemplateInstance") ProcessInstance(dbObj);
                else if (dbObj.ClassDefinition.Name == "CTemplate") ProcessTemplate(dbObj);

                conn.LogOff();
                conn.Disconnect();
            }
        }
 public static void Right()
 {
     Connection connection = new Connection();
     connection.ConnectionString = "DataSource=//MyMachine";
     connection.Connect();
     connection.Disconnect();
 }
Example #3
0
        // note: original HLAPI HandleBytes function handled >1 message in a while loop, but this wasn't necessary
        //       anymore because NetworkServer/NetworkClient Update both use while loops to handle >1 data events per
        //       frame already.
        //       -> in other words, we always receive 1 message per Receive call, never two.
        //       -> can be tested easily with a 1000ms send delay and then logging amount received in while loops here
        //          and in NetworkServer/Client Update. HandleBytes already takes exactly one.
        /// <summary>
        /// This function allows custom network connection classes to process data from the network before it is passed to the application.
        /// </summary>
        /// <param name="buffer">The data received.</param>
        internal void TransportReceive(ArraySegment <byte> buffer, int channelId)
        {
            // unpack message
            using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(buffer))
            {
                try
                {
                    int msgType = MessagePacker.UnpackId(networkReader);

                    if (msgType == MessagePacker.GetId <NotifyPacket>())
                    {
                        // this is a notify message, send to the notify receive
                        NotifyPacket notifyPacket = networkReader.ReadNotifyPacket();
                        ReceiveNotify(notifyPacket, networkReader, channelId);
                    }
                    else
                    {
                        // try to invoke the handler for that message
                        InvokeHandler(msgType, networkReader, channelId);
                    }
                }
                catch (InvalidDataException ex)
                {
                    logger.Log(ex.ToString());
                }
                catch (Exception ex)
                {
                    logger.LogError("Closed connection: " + this + ". Invalid message " + ex);
                    Connection?.Disconnect();
                }
            }
        }
 public void Disconnect(bool resetConnection = false)
 {
     openConnection?.Disconnect();
     if (resetConnection)
     {
         openConnection = null;
     }
 }
Example #5
0
        public void Dispose()
        {
            if (!Running)
            {
                return;
            }

            Connection?.Disconnect();

            Dispatcher?.Stop();

            Stop();
        }
Example #6
0
        public override void Stop()
        {
            if (!Running)
            {
                return;
            }

            Connection?.Disconnect();

            Dispatcher?.Stop();

            base.Stop();
        }
Example #7
0
 private void Button_Click_1(object sender, RoutedEventArgs e)
 {
     Connection.Disconnect();
     Application.Current.Shutdown();
 }
Example #8
0
 public void Stop()
 {
     _connection.Disconnect();
 }
Example #9
0
        public Boolean ReadHeader(Connection connection)
        {
            this.fFirstHeader = String.Empty;

            String lStart = HttpHeaders.ReadHttpMethodName(connection);

            if (lStart == null)
                return false;

            if (String.Equals(lStart, String.Empty, StringComparison.Ordinal))
                throw new HttpRequestInvalidException(500, "Invalid HTTP Request, 'POST', 'MERGE', 'GET', 'DELETE', 'PUT' or 'HEAD' header expected.");

            String lHeaderLine;
            do
            {
                lHeaderLine = connection.ReadLine();

                if (!String.IsNullOrEmpty(lHeaderLine))
                {
                    if (this.fFirstHeader.Length == 0)
                    {
                        this.fFirstHeader = lStart + lHeaderLine;
                    }
                    else
                    {
                        Int32 lPos = lHeaderLine.IndexOf(":");
                        if (lPos == -1)
                            throw new HttpHeaderException("Invalid HTTP Header Line \"" + lHeaderLine + "\"");

                        String lName = lHeaderLine.Substring(0, lPos);
                        String lValue = null;

                        // There should be a space after the ":" , but at least one custome said that this is not
                        // always true
                        // So we check if there is space after the ":"
                        if (lHeaderLine.Length > lPos + 1)
                        {
                            if (lHeaderLine[lPos + 1] == ' ')
                                lValue = lHeaderLine.Substring(lPos + 2);
                            else
                                lValue = lHeaderLine.Substring(lPos + 1);
                        }

                        HttpHeader lHeader = this[lName];
                        if (lHeader == null)
                        {
                            lHeader = new HttpHeader(lName, lValue);
                            fHeaders.Add(lName, lHeader);
                        }
                        else
                        {
                            lHeader.Add(lValue);
                        }
                    }
                }

                if (this.MaxHeaderLinesEnabled && this.fHeaders.Count > this.MaxHeaderLines - 1) // -1 because FirstHeader is not in hashtable
                {
                    connection.Disconnect();
                    throw new HttpHeaderException(String.Format("Too many header lines received (maximum is set to {0})", MaxHeaderLines));
                }
            }
            while (!String.IsNullOrEmpty(lHeaderLine));

            this.ParseFirstLine();

            return true;
        }
Example #10
0
 internal static void Disconnect()
 {
     Connection.Disconnect();
 }
Example #11
0
 public void Disconnect()
 {
     _connection.Disconnect();
     _router.Stop();
 }
Example #12
0
    private void ReceiveCallback(IAsyncResult ar)
    {
        Connection connection = (Connection)ar.AsyncState;
        Socket     socket     = connection.socket;
        int        bytesRead  = 0;

        try
        {
            bytesRead = socket.EndReceive(ar);
        }
        catch (Exception e)
        {
            Log.Red(new string[] { e.ToString() });
        }

        if (bytesRead > 0)
        {
            connection.message += Encoding.UTF8.GetString(connection.buffer, 0, bytesRead);

            if (connection.message.IndexOf("<EOF>") > -1)
            {
                // received the whole client message
                connection.message      = connection.message.Remove(connection.message.Length - 5);
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.Write($"[{connection.name}]");
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine($"{connection.message}");
                Console.ResetColor();

                if (connection.message.StartsWith("/", StringComparison.OrdinalIgnoreCase))
                {
                    if (connection.message.StartsWith("/sair", StringComparison.OrdinalIgnoreCase))
                    {
                        if (connection.socket.Connected)
                        {
                            connection.Disconnect();
                        }
                        Console.WriteLine("> {0} DISCONECTOU.", connection.name);
                        // informa para os outros usuários que o cliente saiu
                        SendToAllButOne(connection, connection.name + " disconectou.<EOF>");
                        connections.Remove(connection);
                        return;
                    }
                    else if (connection.message.StartsWith("/quem", StringComparison.OrdinalIgnoreCase))
                    {
                        string message = "";
                        foreach (Connection c in connections)
                        {
                            message += c.name + "\n";
                        }
                        Send(connection, message + "<EOF>");
                    }
                    else if (connection.message.StartsWith("/nome", StringComparison.OrdinalIgnoreCase))
                    {
                        string oldName    = connection.name;
                        string chosenName = connection.message.Remove(0, 6);

                        if (NameIsValid(chosenName))
                        {
                            connection.name = chosenName;
                        }
                        else
                        {
                            Send(connection, "Alguem ja possui esse nome<EOF>");
                        }

                        if (connection.nameChosen)
                        {
                            SendToAllButOne(connection, oldName + " mudou de nome para " + connection.name + "<EOF>");
                        }
                        else
                        {
                            // the user is setting its first name
                            Log.Yellow(new string[] { $"{oldName} entrou na sala como {connection.name}" });
                            Send(connection, $"##servernewname## {connection.name}<EOF>");
                            SendToAllButOne(connection, connection.name + " entrou no chat.<EOF>");
                            connection.nameChosen = true;
                        }
                    }
                    else
                    {
                        Send(connection, "[SERVER] Invalid command!<EOF>");
                    }
                }
                else if (connection.message.StartsWith("@", StringComparison.OrdinalIgnoreCase))
                {
                    string   temp       = connection.message.Remove(0, 1);
                    string[] nameAndMsg = temp.Split(new char[] { ' ' }, 2);
                    string   name       = nameAndMsg[0];
                    string   msg        = nameAndMsg[1];
                    bool     nameFound  = false;
                    foreach (Connection c in connections)
                    {
                        if (c.name == name)
                        {
                            Send(c, connection.name + ": " + msg + "<EOF>");
                            nameFound = true;
                        }
                    }
                    if (!nameFound)
                    {
                        Send(connection, "[SERVER] Nenhum cliente encontrado com esse nome.");
                    }
                }

                else
                {
                    SendToAllButOne(connection, connection.name + ": " + connection.message + "<EOF>");
                }
                connection.message = "";
            }
            socket.BeginReceive(connection.buffer, 0, connection.buffer.Length, 0, ReceiveCallback, connection);
        }
    }
Example #13
0
 /// <summary>
 /// Synchronously disconnects from the Ldap server.
 /// Before the object can perform Ldap operations again, it must
 /// reconnect to the server by calling connect.
 /// The disconnect method abandons any outstanding requests, issues an
 /// unbind request to the server, and then closes the socket.
 /// </summary>
 public void Disconnect()
 {
     // disconnect from API call
     _cts.Cancel();
     _conn.Disconnect();
 }
Example #14
0
 /// <inheritdoc />
 public override void Disconnect()
 {
     Connection.Disconnect();
 }
Example #15
0
 public void Logout()
 {
     Connection.Disconnect();
     Connection = null;
     LeaveRoom();
 }
Example #16
0
 /// <inheritdoc />
 public override void Disconnect(Action <bool> disconnectCompleted)
 {
     Connection.Disconnect();
 }
Example #17
0
        private void FTGet(string serverIP, string directoryName)
        {
            // clear the contents
            contentTextBox.Clear();

            try
            {
                Connection conn = new Connection(PRS_ADDRESS, PRS_PORT, "FT Server", serverIP);

                // send "get\n<directoryName>"
                conn.SocketWriter.WriteLine("get");
                conn.SocketWriter.WriteLine(directoryName);
                conn.SocketWriter.Flush();
                //Console.WriteLine("Sent get " + directoryName);

                // download the files that the server says are in the directory
                bool done = false;
                while (!done)
                {
                    // receive a message from the server
                    //Console.WriteLine("Waiting for msg from server");
                    string cmdString = conn.SocketReader.ReadLine();

                    //if (cmdString.Substring(0, 4) == "done")
                    if (cmdString == "done")
                    {
                        // server is done sending files
                        //Console.WriteLine("Received done");
                        done = true;
                    }
                    else
                    {
                        // server sent us a file name and file length
                        string filename = cmdString;
                        //Console.WriteLine("Received file name from server: " + filename);
                        string lengthstring = conn.SocketReader.ReadLine();
                        int    filelength   = System.Convert.ToInt32(lengthstring);
                        //Console.WriteLine("Received file length from server: " + filelength.ToString());

                        // read the file contents as a string, and write them to the local file
                        char[] buffer = new char[filelength];
                        int    result = conn.SocketReader.Read(buffer, 0, filelength);
                        if (result == filelength)
                        {
                            string fileContents = new string(buffer);
                            contentTextBox.AppendText(filename + "\r\n");
                            contentTextBox.AppendText(fileContents + "\r\n");
                            contentTextBox.AppendText("\r\n");
                            //File.WriteAllText(Path.Combine(directoryName, filename), fileContents);
                            //Console.WriteLine("Wrote " + result.ToString() + " bytes to " + filename + " in " + directoryName);
                        }
                        else
                        {
                            MessageBox.Show("Error: received " + result.ToString() + " bytes, but expected " + filelength.ToString() + " bytes!");
                        }
                    }
                }
                conn.Disconnect();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #18
0
 private void Disconnect()
 {
     Conn.Disconnect();
 }
 public static void Wrong1()
 {
     Connection connection = new Connection();
     connection.Connect();
     connection.Disconnect();
 }
Example #20
0
 public void disconnect()
 {
     if (!pioconnection.Connected)
         return;
     pioconnection.Disconnect();
 }
 public void TearDown()
 {
     // clean up the connection
     SQLConn.Disconnect();
 }
Example #22
0
        private void RunBuild(bool async)
        {
            DateTime buildTime   = DateTime.Now;
            String   buildId     = buildTime.ToString("MMddyyHHmmss");
            String   buildFolder = buildTime.ToString("MM-dd-yy_HHmmss");
            String   buildPath   = Path.Combine(mBuildFolderTxt.Text, buildFolder);

            int idx = 0;

            while ((Directory.Exists(buildPath)) && (idx < 26))
            {
                buildPath = Path.Combine(mBuildFolderTxt.Text, buildTime.ToString("MM-dd-yy HHmmss") + ((char)((int)'a' + idx)));
            }
            if (idx >= 26)
            {
                return;
            }

            string logFile = Path.Combine(buildPath, "BuildLog.txt");

            Directory.CreateDirectory(buildPath);

            String ConStr   = mServerConnection.Text;
            String User     = mUserText.Text;
            String Password = mPaswordTxt.Text;
            String Target   = mSolutionPath.Text;
            Server pServer  = new Server(new ServerAddress(ConStr));

            rep = new Repository(pServer);



            Connection con = rep.Connection;

            con.Connect(null);
            log = new StreamWriter(logFile);

            Client buildClient = new Client();

            buildClient.Name          = "p4apinet_solution_builder_sample_application_client";
            buildClient.OwnerName     = con.UserName;
            buildClient.ViewMap       = new ViewMap();
            buildClient.Root          = buildPath;
            buildClient.Options       = ClientOption.AllWrite;
            buildClient.LineEnd       = LineEnd.Local;
            buildClient.SubmitOptions = new ClientSubmitOptions(false, SubmitType.SubmitUnchanged);

            string depotPath = mSolutionPath.Text;

            IList <FileMetaData> fmd = null;

            try
            {
                fmd = rep.GetFileMetaData(null, FileSpec.DepotSpec(depotPath));
            }

            catch {}

            if ((fmd == null) || (fmd.Count != 1))
            {
                string message = string.Format("The solution file \"{0}\" does not exist in the depot.", depotPath);
                MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            if (mSolutionPath.Text.EndsWith(".sln"))
            {
                depotPath = mSolutionPath.Text.Substring(0, mSolutionPath.Text.LastIndexOf('/'));
            }
            string depotFolder = depotPath.Substring(depotPath.LastIndexOf('/') + 1);

            depotPath += "/...";

            String clientPath = String.Format("//{0}/{1}/...", buildClient.Name, depotFolder);

            MapEntry entry = new MapEntry(MapType.Include, new DepotPath(depotPath), new ClientPath(clientPath));

            buildClient.ViewMap.Add(entry);

            rep.CreateClient(buildClient);
            con.Client = rep.GetClient(buildClient.Name);

            string localPath = clientPath;

            localPath = localPath.TrimStart('/');
            localPath = localPath.TrimEnd('.');
            localPath = localPath.Substring(localPath.IndexOf('/') + 1);
            localPath = localPath.Replace('/', '\\');
            string solutionName = Target.Substring(depotPath.LastIndexOf('/'));

            solutionName = solutionName.TrimStart('/');
            localPath    = Path.Combine(buildPath, localPath, solutionName);


            int lastChange = GetLastChange();

            AsynchSetLastChange(lastChange);

            IList <Changelist> changes = GetChangesAfter(changeAtLastBuild, lastChange);

            changeAtLastBuild = lastChange;

            if (changes != null)
            {
                for (idx = 0; idx < changes.Count; idx++)
                {
                    AsynchAddLineToLog(changes[idx].ToString(true));
                }
            }


            if (async)
            {
                Thread buildThread = new Thread(new ParameterizedThreadStart(RunBuildProc));
                buildThread.IsBackground = true;
                buildThread.Start(localPath);
            }
            else
            {
                RunBuildProc(localPath);
            }

            con.Disconnect(null);
        }
Example #23
0
 /// <summary>
 /// Calls the close so that everything gets cleaned up
 /// </summary>
 public void Disconnect()
 {
     Close();
     Connection.Disconnect();
 }
Example #24
0
 protected override void OnDestroy()
 {
     base.OnDestroy();
     // Disconnect from room server
     Connection?.Disconnect();
 }
Example #25
0
        /// <summary>
        /// Disconnects this client.
        /// </summary>
        public void Disconnect()
        {
            heartBeatFunc.Stop();

            connection.Disconnect();
        }
Example #26
0
 /// <summary>
 /// Disconnect from server.
 /// <para>The disconnect message will be invoked.</para>
 /// </summary>
 public void Disconnect()
 {
     Connection?.Disconnect();
 }
Example #27
0
 public void Disconnect()
 {
     _connection.Disconnect();
 }
Example #28
0
 //[TestFixtureTearDown]
 public void PerFixtureTeardown()
 {
     dbConn.Disconnect();
     dbConn.Dispose();
 }
 public void Disconnect() => Connection?.Disconnect();
 public void Disconnect(string reason = "Disconnect")
 {
     Connection.Disconnect(reason);
 }
Example #31
0
 public void Connect()
 {
     Connection?.Disconnect();
     ShowConnectionView();
 }
        public void HandleMessage(Packet msg)
        {
            switch (msg.Type)
            {
            case PacketType.Voice:
                Server.SendMessageToAll(msg);
                break;

            case PacketType.DeclareWinner:
                Server.DeclareWinner(((DeclareWinner)msg).Id);
                Server.StartMatch(true);
                break;

            case PacketType.EndTurn:
            {
                EndTurn endTurn = (EndTurn)msg;
                SelectedCards.Clear();
                foreach (CardInfo info in endTurn.Cards)
                {
                    SelectedCards.Add(info.Value);
                }

                CardCount -= endTurn.Cards.Count;
                Ready      = true;

                Server.SendMessageToAllExcept(new SetStatus(Id, false), Id);
                break;
            }

            case PacketType.LobbyBeginGame:
                Server.SendMessageToAll(new BeginGame());
                Server.State = Server.States.InGame;
                Server.StartMatch(false);

                Server.Greet();
                break;

            case PacketType.ServerJoin:
            {
                ServerJoin serverJoin = (ServerJoin)msg;

                // Check version
                if (serverJoin.Version != Program.Version)
                {
                    Connection.Disconnect("Host is running on a different version.");
                    return;
                }

                Name = serverJoin.Name;

                Server.SendMessageToAllExcept(new PlayerNew(Name, Id), Id);
                foreach (ServerClient c in Server.Clients.Where(a => a.Id != Id))
                {
                    Connection.SendMessage(new PlayerNew(c.Name, c.Id));
                }

                Verified = true;

                Server.SendMessageToAllExcept(new ChatMessage(String.Format("{0} has joined the game!", Name)), Id);
                break;
            }

            case PacketType.ChatMessage:
            {
                ChatMessage chatMessage = (ChatMessage)msg;
                Server.SendMessageToAllExcept(new ChatMessage(chatMessage.Value), Id);
                break;
            }

            default:
                Console.WriteLine("Unhandled packet {0}", msg.Type.ToString());
                break;
            }
        }
Example #33
0
 public override bool Disconnect(bool joinThread = true)
 {
     Heart.Enabled = false;
     return(Connection.Disconnect());
 }
Example #34
0
 public void DeleteAndTidyUp()
 {
     m_DeviceInformation.Cancel();
     Connection.Disconnect();
 }