Ejemplo n.º 1
0
        /// <summary>
        /// Callback that will has been calling during widow closing.
        /// Will terminate all registred async operations, stop transmissions, stop server instances.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // Unsubscribe from events.
            SizeChanged -= MainWindow_SizeChanged;
            try { logonScreen.LogonPanel_LoginCallback -= LogonScreen_LoginButton; } catch { }
            try { logonScreen.RegPanel_ContinueCallback -= LogonScreen_RegistrationButton; } catch { }

            // Close lines.
            ClientAPI.CloseAllTransmissionLines();
            // Close servers.
            PipesProvider.Server.ServerAPI.StopAllServers();

            // Terminate async operations.
            AuthorityController.Session.Current.TerminationTokenSource.Cancel();
            BaseClient.TerminationTokenSource.Cancel();
        }
        static void Main(string[] args)
        {
            #region Encryption test.
            //string enc = PipesProvider.Security.Crypto.EncryptString("Encryption Test", PipesProvider.Security.Crypto.PublicKey);
            //string dec = PipesProvider.Security.Crypto.DecryptString(enc);

            //Console.WriteLine("Result: {0}",dec);
            //Console.ReadLine();
            #endregion

            // This part has no any effect on application in future. Valid routing table would be loaded from "resources\routing\ROUTING.xml".
            //
            // Client could has a numbers of connections to different servers.
            // Connection to each server can have differend params.
            //
            // Cases:
            // Some servers can require system login to pas LSA of Windows NT.
            // Some could require in application authorization.
            #region Routing table serialization example
            // Create table with differend delivered instruction's types.
            routingTable.intructions = new System.Collections.Generic.List <Instruction>(new Instruction[]
            {
                new Instruction()
                {
                    routingIP   = "localhost",
                    pipeName    = "THB_QUERY_SERVER",
                    logonConfig = new LogonConfig(null, null, "WORKGROUP"),
                    title       = "Query server",
                    commentary  = "Server that reciving all queries from clients and then forwarding them to target servers."
                },
                new PartialAuthorizedInstruction()
                {
                    guestChanel = "guest",
                    routingIP   = "localhost",
                    title       = "Guest auth server",
                    commentary  = "Authority Server that maintaining broadcast of guest tokens."
                }
            });
            RoutingTable.SaveRoutingTable(routingTable, "resources/sample", "ROUTING"); // Save table as recommended sample for this client.
            routingTable = new RoutingTable();                                          // Drop from memory to allow clear loading of customer's routing tables.
            #endregion

            #region Init
            // React on uniform arguments.
            UniformClient.ClientAppConfigurator.ArgsReactor(args);

            // Check direcroties
            UniformDataOperator.AssembliesManagement.AssembliesHandler.LoadAssemblies(
                AppDomain.CurrentDomain.BaseDirectory + "libs\\");

            // Looking for replaced types that could be used by handlers.
            UniformDataOperator.AssembliesManagement.Modifiers.TypeReplacer.RescanAssemblies();

            // Loading roting tables to detect servers.
            LoadRoutingTables(AppDomain.CurrentDomain.BaseDirectory + "plugins\\");
            Thread.Sleep(50);

            Console.WriteLine("Preparetion finished. Client strated.");
            #endregion

            // This client has only one server so we just looks on first included instruction in routing table,
            // to detect the target params.
            routingInstruction = routingTable.intructions[0];

            // Set loaded config to firlds.
            // Provided only for code simplifying and showing example of hard coded data using.
            // In normal way I recommend to use direct call of ServerMeta's fields and properties.
            SERVER_NAME      = routingInstruction.routingIP;
            SERVER_PIPE_NAME = routingInstruction.pipeName;


            // Try to make human clear naming of server. In case of local network we will get the machine name.
            // This is optional and not required for stable work, just little helper for admins.
            PipesProvider.Networking.Info.TryGetHostName(SERVER_NAME, ref SERVER_NAME);
            Console.WriteLine("Work with a server by the route: " + SERVER_NAME + "." + SERVER_PIPE_NAME);


            // Check server exist. When connection will be established will be called shared delegate.
            // Port 445 required for named pipes work.
            Console.WriteLine("Ping the host server via the 445 port...");
            PipesProvider.Networking.Info.PingHost(
                SERVER_NAME, 445,
                delegate(string uri, int port)
            {
                // Log about success ping operation.
                Console.WriteLine("PING COMPLITED | HOST AVAILABLE | {0}:{1}\n", uri, port);

                #region Recive guest token from server
                // Trying to get instruction in partial authorized format.
                if (routingInstruction is PartialAuthorizedInstruction partialAuthorizedInstruction)
                {
                    // Trying to recive guest token from server.
                    _ = partialAuthorizedInstruction.TryToGetGuestTokenAsync(
                        AuthorityController.Session.Current.TerminationTokenSource.Token);     // Using Sesstion termination token as uniform
                                                                                               //to provide possibility to stop all async operation before application exit.
                }
                else
                {
                    Console.WriteLine(
                        "ERROR: Invalid cast. For this example routing " +
                        "instruction by 0 index must by delivered from" +
                        " PartialAuthorizedInstruction. Application terminated.");
                    Thread.Sleep(2000);
                    return;
                }

                // Wait until authorization.
                Console.WriteLine("Waiting for a guest token from server's authority system...");
                while (!partialAuthorizedInstruction.GuestTokenHandler.IsAutorized)
                {
                    Thread.Sleep(50);
                }
                Console.WriteLine("Authorized. Token: " + partialAuthorizedInstruction.GuestToken);
                #endregion

                // Send few example queries to server.
                TransmissionsBlock();
            });

            #region Main loop
            while (true)
            {
                if (Console.KeyAvailable)
                {
                    Console.Write("Enter command: ");
                    string tmp = Console.ReadLine();

                    // Skip empty requests.
                    if (string.IsNullOrEmpty(tmp))
                    {
                        continue;
                    }

                    // Close application by command.
                    if (tmp == "close")
                    {
                        break;
                    }
                    else
                    {
                        // If included counter then spawn a echo in loop.
                        if (Int32.TryParse(tmp, out int repeaterRequest))
                        {
                            for (int i = 1; i < repeaterRequest + 1; i++)
                            {
                                SendOneWayQuery("ECHO" + i + "/" + repeaterRequest);
                            }
                        }
                        // Share custom query.
                        else
                        {
                            // Send as duplex.
                            if (tmp.StartsWith("DPX:"))
                            {
                                EnqueueDuplexQueryViaPP(SERVER_NAME, SERVER_PIPE_NAME,
                                                        new Query(tmp.Substring(4)), ServerAnswerHandler_RSAPublicKey).
                                TryLogonAs(routingInstruction.logonConfig);
                            }
                            // Send as one way
                            else
                            {
                                SendOneWayQuery(tmp);
                            }
                        }
                    }
                }
            }
            #endregion

            // Close all active lines. Without this operation thread will be hanged.
            ClientAPI.CloseAllTransmissionLines();

            // Whait until close.
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }