public void StartSession()
 {
     ISession session = SessionFactory.OpenSession();
     session.BeginTransaction();
     var cache = new SessionCache();
     cache.CacheSession(session);
 }
        public SessionCacheTester()
        {
            theResolverMock = Substitute.For<IBuildSession>();

            theCache = new SessionCache(theResolverMock);

            thePipeline = Substitute.For<IPipelineGraph>();
            thePipeline.ToModel().Returns(new Container().Model);

            instanceGraphMock = Substitute.For<IInstanceGraph>();
            thePipeline.Instances.Returns(instanceGraphMock);
        }
Example #3
0
        public void SetUp()
        {
            theResolver = MockRepository.GenerateMock<IBuildSession>();

            theCache = new SessionCache(theResolver);

            thePipeline = MockRepository.GenerateMock<IPipelineGraph>();
            thePipeline.Stub(x => x.ToModel()).Return(new Container().Model);

            theInstances = MockRepository.GenerateMock<IInstanceGraph>();
            thePipeline.Stub(x => x.Instances).Return(theInstances);
        }
        public void EndSession()
        {
            var cache = new SessionCache();
            ISession session = cache.GetSession();
            ITransaction transaction = session.Transaction;
            if (transaction.IsActive)
            {
                transaction.Commit();
            }

            session.Dispose();
        }
        public SessionCacheTester()
        {
            theResolverMock = new Mock<IBuildSession>();

            theCache = new SessionCache(theResolverMock.Object);

            var thePipelineMock = new Mock<IPipelineGraph>();
            thePipelineMock.Setup(x => x.ToModel()).Returns(new Container().Model);
            thePipeline = thePipelineMock.Object;

            instanceGraphMock = new Mock<IInstanceGraph>();
            thePipelineMock.Setup(x => x.Instances).Returns(instanceGraphMock.Object);
        }
        public void explicit_wins_over_instance_in_try_get_default()
        {
            var foo1 = new Foo();

            var args = new ExplicitArguments();
            args.Set<IFoo>(foo1);

            theCache = new SessionCache(theResolverMock, args);

            var instance = new ConfiguredInstance(typeof(Foo));
            instanceGraphMock.GetDefault(typeof(IFoo)).Returns(instance);

            var foo2 = new Foo();

            theResolverMock.ResolveFromLifecycle(typeof(IFoo), instance).Returns(foo2);

            theCache.GetDefault(typeof(IFoo), thePipeline)
                .ShouldBeTheSameAs(foo1);
        }
        public void explicit_wins_over_instance_in_try_get_default()
        {
            var foo1 = new Foo();

            var args = new ExplicitArguments();
            args.Set<IFoo>(foo1);

            theCache = new SessionCache(theResolver, args);

            var instance = new ConfiguredInstance(typeof (Foo));
            theInstances.Stub(x => x.GetDefault(typeof (IFoo))).Return(instance);

            var foo2 = new Foo();

            theResolver.Expect(x => x.ResolveFromLifecycle(typeof (IFoo), instance)).Return(foo2)
                .Repeat.Once();

            theCache.GetDefault(typeof (IFoo), thePipeline)
                .ShouldBeTheSameAs(foo1);
        }
        public void Should_get_two_most_recent_visitors()
        {
            var config = new DataConfig();
            config.PerformStartup();

            Visitor visitor1 =
                CreateVisitor(new DateTime(2000, 1, 1));
            Visitor visitor2 =
                CreateVisitor(new DateTime(2000, 1, 2));
            Visitor visitor3 =
                CreateVisitor(new DateTime(2000, 1, 3));
            config.StartSession();
            using (
                ISession session1 =
                    new SessionCache().GetSession())
            {
                session1.SaveOrUpdate(visitor1);
                session1.SaveOrUpdate(visitor2);
                session1.SaveOrUpdate(visitor3);
                session1.Flush();
                config.EndSession();
            }

            config.StartSession();

            var repository = new VisitorRepository();
            Visitor[] recentVisitors =
                repository.GetRecentVisitors(2);
            config.EndSession();

            Assert.That(recentVisitors.Length, Is.EqualTo(2));
            IEnumerable<Guid> idList =
                recentVisitors.Select(x => x.Id);
            Assert.That(idList.Contains(visitor3.Id), Is.True);
            Assert.That(idList.Contains(visitor2.Id), Is.True);
            Assert.That(idList.Contains(visitor1.Id), Is.False);
        }
 public ActionResult Logout()
 {
     SessionCache.DestroySession();
     return(RedirectToAction("Index", "Home"));
 }
Example #10
0
        /// <summary>
        /// The main entry point of Minecraft Console Client
        /// </summary>
        static void Main(string[] args)
        {
            Console.WriteLine("Minecraft Console Client v{0} - for MC {1} to {2} - Github.com/MCCTeam", Version, MCLowestVersion, MCHighestVersion);

            //Build information to facilitate processing of bug reports
            if (BuildInfo != null)
            {
                ConsoleIO.WriteLineFormatted("§8" + BuildInfo);
            }

            //Debug input ?
            if (args.Length == 1 && args[0] == "--keyboard-debug")
            {
                ConsoleIO.WriteLine("Keyboard debug mode: Press any key to display info");
                ConsoleIO.DebugReadInput();
            }

            //Setup ConsoleIO
            ConsoleIO.LogPrefix = "§8[MCC] ";
            if (args.Length >= 1 && args[args.Length - 1] == "BasicIO" || args.Length >= 1 && args[args.Length - 1] == "BasicIO-NoColor")
            {
                if (args.Length >= 1 && args[args.Length - 1] == "BasicIO-NoColor")
                {
                    ConsoleIO.BasicIO_NoColor = true;
                }
                ConsoleIO.BasicIO = true;
                args = args.Where(o => !Object.ReferenceEquals(o, args[args.Length - 1])).ToArray();
            }

            //Take advantage of Windows 10 / Mac / Linux UTF-8 console
            if (isUsingMono || WindowsVersion.WinMajorVersion >= 10)
            {
                Console.OutputEncoding = Console.InputEncoding = Encoding.UTF8;
            }

            //Process ini configuration file
            if (args.Length >= 1 && System.IO.File.Exists(args[0]) && System.IO.Path.GetExtension(args[0]).ToLower() == ".ini")
            {
                Settings.LoadFile(args[0]);

                //remove ini configuration file from arguments array
                List <string> args_tmp = args.ToList <string>();
                args_tmp.RemoveAt(0);
                args = args_tmp.ToArray();
            }
            else if (System.IO.File.Exists("MinecraftClient.ini"))
            {
                Settings.LoadFile("MinecraftClient.ini");
            }
            else
            {
                Settings.WriteDefaultSettings("MinecraftClient.ini");
            }

            //Load external translation file. Should be called AFTER settings loaded
            Translations.LoadExternalTranslationFile(Settings.Language);

            //Other command-line arguments
            if (args.Length >= 1)
            {
                if (args.Contains("--help"))
                {
                    Console.WriteLine("Command-Line Help:");
                    Console.WriteLine("MinecraftClient.exe <username> <password> <server>");
                    Console.WriteLine("MinecraftClient.exe <username> <password> <server> \"/mycommand\"");
                    Console.WriteLine("MinecraftClient.exe --setting=value [--other settings]");
                    Console.WriteLine("MinecraftClient.exe --section.setting=value [--other settings]");
                    Console.WriteLine("MinecraftClient.exe <settings-file.ini> [--other settings]");
                    return;
                }

                try
                {
                    Settings.LoadArguments(args);
                }
                catch (ArgumentException e)
                {
                    Settings.interactiveMode = false;
                    HandleFailure(e.Message);
                    return;
                }
            }

            if (Settings.ConsoleTitle != "")
            {
                Settings.Username = "******";
                Console.Title     = Settings.ExpandVars(Settings.ConsoleTitle);
            }

            //Test line to troubleshoot invisible colors
            if (Settings.DebugMessages)
            {
                ConsoleIO.WriteLineFormatted(Translations.Get("debug.color_test", "[0123456789ABCDEF]: [§00§11§22§33§44§55§66§77§88§99§aA§bB§cC§dD§eE§fF§r]"));
            }

            //Load cached sessions from disk if necessary
            if (Settings.SessionCaching == CacheType.Disk)
            {
                bool cacheLoaded = SessionCache.InitializeDiskCache();
                if (Settings.DebugMessages)
                {
                    Translations.WriteLineFormatted(cacheLoaded ? "debug.session_cache_ok" : "debug.session_cache_fail");
                }
            }

            //Asking the user to type in missing data such as Username and Password
            bool useBrowser = Settings.AccountType == ProtocolHandler.AccountType.Microsoft && Settings.LoginMethod == "browser";

            if (Settings.Login == "" && !useBrowser)
            {
                Console.Write(ConsoleIO.BasicIO ? Translations.Get("mcc.login_basic_io") + "\n" : Translations.Get("mcc.login"));
                Settings.Login = Console.ReadLine();
            }
            if (Settings.Password == "" &&
                (Settings.SessionCaching == CacheType.None || !SessionCache.Contains(Settings.Login.ToLower())) &&
                !useBrowser)
            {
                RequestPassword();
            }

            // Setup exit cleaning code
            ExitCleanUp.Add(delegate()
            {
                // Do NOT use Program.Exit() as creating new Thread cause program to freeze
                if (client != null)
                {
                    client.Disconnect(); ConsoleIO.Reset();
                }
                if (offlinePrompt != null)
                {
                    offlinePrompt.Abort(); offlinePrompt = null; ConsoleIO.Reset();
                }
                if (Settings.playerHeadAsIcon)
                {
                    ConsoleIcon.revertToMCCIcon();
                }
            });


            startupargs = args;
            InitializeClient();
        }
        /// <summary>
        /// The main entry point of Minecraft Console Client
        /// </summary>
        static void Main(string[] args)
        {
            Console.WriteLine("Console Client for MC {0} to {1} - v{2} - By ORelio & Contributors", MCLowestVersion, MCHighestVersion, Version);

            //Build information to facilitate processing of bug reports
            if (BuildInfo != null)
            {
                ConsoleIO.WriteLineFormatted("§8" + BuildInfo);
            }

            //Debug input ?
            if (args.Length == 1 && args[0] == "--keyboard-debug")
            {
                ConsoleIO.WriteLine("Keyboard debug mode: Press any key to display info");
                ConsoleIO.DebugReadInput();
            }

            //Setup ConsoleIO
            ConsoleIO.LogPrefix = "§8[MCC] ";
            if (args.Length >= 1 && args[args.Length - 1] == "BasicIO" || args.Length >= 1 && args[args.Length - 1] == "BasicIO-NoColor")
            {
                if (args.Length >= 1 && args[args.Length - 1] == "BasicIO-NoColor")
                {
                    ConsoleIO.BasicIO_NoColor = true;
                }
                ConsoleIO.BasicIO = true;
                args = args.Where(o => !Object.ReferenceEquals(o, args[args.Length - 1])).ToArray();
            }

            //Take advantage of Windows 10 / Mac / Linux UTF-8 console
            if (isUsingMono || WindowsVersion.WinMajorVersion >= 10)
            {
                Console.OutputEncoding = Console.InputEncoding = Encoding.UTF8;
            }

            //Process ini configuration file
            if (args.Length >= 1 && System.IO.File.Exists(args[0]) && System.IO.Path.GetExtension(args[0]).ToLower() == ".ini")
            {
                Settings.LoadSettings(args[0]);

                //remove ini configuration file from arguments array
                List <string> args_tmp = args.ToList <string>();
                args_tmp.RemoveAt(0);
                args = args_tmp.ToArray();
            }
            else if (System.IO.File.Exists("MinecraftClient.ini"))
            {
                Settings.LoadSettings("MinecraftClient.ini");
            }
            else
            {
                Settings.WriteDefaultSettings("MinecraftClient.ini");
            }

            //Load external translation file. Should be called AFTER settings loaded
            Translations.LoadExternalTranslationFile(Settings.Language);

            //Other command-line arguments
            if (args.Length >= 1)
            {
                Settings.Login = args[0];
                if (args.Length >= 2)
                {
                    Settings.Password = args[1];
                    if (args.Length >= 3)
                    {
                        Settings.SetServerIP(args[2]);

                        //Single command?
                        if (args.Length >= 4)
                        {
                            Settings.SingleCommand = args[3];
                        }
                    }
                }
            }

            if (Settings.ConsoleTitle != "")
            {
                Settings.Username = "******";
                Console.Title     = Settings.ExpandVars(Settings.ConsoleTitle);
            }

            //Test line to troubleshoot invisible colors
            if (Settings.DebugMessages)
            {
                ConsoleIO.WriteLineFormatted(Translations.Get("debug.color_test", "[0123456789ABCDEF]: [§00§11§22§33§44§55§66§77§88§99§aA§bB§cC§dD§eE§fF§r]"));
            }

            //Load cached sessions from disk if necessary
            if (Settings.SessionCaching == CacheType.Disk)
            {
                bool cacheLoaded = SessionCache.InitializeDiskCache();
                if (Settings.DebugMessages)
                {
                    Translations.WriteLineFormatted(cacheLoaded ? "debug.session_cache_ok" : "debug.session_cache_fail");
                }
            }

            //Asking the user to type in missing data such as Username and Password
            bool useBrowser = Settings.AccountType == ProtocolHandler.AccountType.Microsoft && Settings.LoginMethod == "browser";

            if (Settings.Login == "")
            {
                if (useBrowser)
                {
                    ConsoleIO.WriteLine("Press Enter to skip session cache checking and continue sign-in with browser");
                }
                Console.Write(ConsoleIO.BasicIO ? Translations.Get("mcc.login_basic_io") + "\n" : Translations.Get("mcc.login"));
                Settings.Login = Console.ReadLine();
            }
            if (Settings.Password == "" &&
                (Settings.SessionCaching == CacheType.None || !SessionCache.Contains(Settings.Login.ToLower())) &&
                !useBrowser)
            {
                RequestPassword();
            }


            startupargs = args;
            InitializeClient();
        }
 private ISession GetSession()
 {
     var cache = new SessionCache();
     ISession session = cache.GetSession();
     return session;
 }
Example #13
0
        private void OnSendingRequest2(object sender, SendingRequest2EventArgs sendingRequest2EventArgs)
        {
            var token = new SessionCache().Read("AccessToken#Microsoft.CRM");

            sendingRequest2EventArgs.RequestMessage.SetHeader("Authorization", "Bearer " + token);
        }
        /// <summary>
        /// Start a new Client
        /// </summary>
        private static void InitializeClient()
        {
            SessionToken session = new SessionToken();

            ProtocolHandler.LoginResult result = ProtocolHandler.LoginResult.LoginRequired;

            if (Settings.Password == "-")
            {
                Translations.WriteLineFormatted("mcc.offline");
                result             = ProtocolHandler.LoginResult.Success;
                session.PlayerID   = "0";
                session.PlayerName = Settings.Login;
            }
            else
            {
                // Validate cached session or login new session.
                if (Settings.SessionCaching != CacheType.None && SessionCache.Contains(Settings.Login.ToLower()))
                {
                    session = SessionCache.Get(Settings.Login.ToLower());
                    result  = ProtocolHandler.GetTokenValidation(session);
                    if (result != ProtocolHandler.LoginResult.Success)
                    {
                        Translations.WriteLineFormatted("mcc.session_invalid");
                        if (Settings.Password == "")
                        {
                            RequestPassword();
                        }
                    }
                    else
                    {
                        ConsoleIO.WriteLineFormatted(Translations.Get("mcc.session_valid", session.PlayerName));
                    }
                }

                if (result != ProtocolHandler.LoginResult.Success)
                {
                    Translations.WriteLine("mcc.connecting", Settings.AccountType == ProtocolHandler.AccountType.Mojang ? "Minecraft.net" : "Microsoft");
                    result = ProtocolHandler.GetLogin(Settings.Login, Settings.Password, Settings.AccountType, out session);

                    if (result == ProtocolHandler.LoginResult.Success && Settings.SessionCaching != CacheType.None)
                    {
                        SessionCache.Store(Settings.Login.ToLower(), session);
                    }
                }
            }

            if (result == ProtocolHandler.LoginResult.Success)
            {
                Settings.Username = session.PlayerName;

                if (Settings.ConsoleTitle != "")
                {
                    Console.Title = Settings.ExpandVars(Settings.ConsoleTitle);
                }

                if (Settings.playerHeadAsIcon)
                {
                    ConsoleIcon.setPlayerIconAsync(Settings.Username);
                }

                if (Settings.DebugMessages)
                {
                    Translations.WriteLine("debug.session_id", session.ID);
                }

                //ProtocolHandler.RealmsListWorlds(Settings.Username, PlayerID, sessionID); //TODO REMOVE

                if (Settings.ServerIP == "")
                {
                    Translations.Write("mcc.ip");
                    Settings.SetServerIP(Console.ReadLine());
                }

                //Get server version
                int       protocolversion = 0;
                ForgeInfo forgeInfo       = null;

                if (Settings.ServerVersion != "" && Settings.ServerVersion.ToLower() != "auto")
                {
                    protocolversion = Protocol.ProtocolHandler.MCVer2ProtocolVersion(Settings.ServerVersion);

                    if (protocolversion != 0)
                    {
                        ConsoleIO.WriteLineFormatted(Translations.Get("mcc.use_version", Settings.ServerVersion, protocolversion));
                    }
                    else
                    {
                        ConsoleIO.WriteLineFormatted(Translations.Get("mcc.unknown_version", Settings.ServerVersion));
                    }

                    if (useMcVersionOnce)
                    {
                        useMcVersionOnce       = false;
                        Settings.ServerVersion = "";
                    }
                }

                //Retrieve server info if version is not manually set OR if need to retrieve Forge information
                if (protocolversion == 0 || Settings.ServerAutodetectForge || (Settings.ServerForceForge && !ProtocolHandler.ProtocolMayForceForge(protocolversion)))
                {
                    if (protocolversion != 0)
                    {
                        Translations.WriteLine("mcc.forge");
                    }
                    else
                    {
                        Translations.WriteLine("mcc.retrieve");
                    }
                    if (!ProtocolHandler.GetServerInfo(Settings.ServerIP, Settings.ServerPort, ref protocolversion, ref forgeInfo))
                    {
                        HandleFailure(Translations.Get("error.ping"), true, ChatBots.AutoRelog.DisconnectReason.ConnectionLost);
                        return;
                    }
                }

                //Force-enable Forge support?
                if (Settings.ServerForceForge && forgeInfo == null)
                {
                    if (ProtocolHandler.ProtocolMayForceForge(protocolversion))
                    {
                        Translations.WriteLine("mcc.forgeforce");
                        forgeInfo = ProtocolHandler.ProtocolForceForge(protocolversion);
                    }
                    else
                    {
                        HandleFailure(Translations.Get("error.forgeforce"), true, ChatBots.AutoRelog.DisconnectReason.ConnectionLost);
                        return;
                    }
                }

                //Proceed to server login
                if (protocolversion != 0)
                {
                    try
                    {
                        //Start the main TCP client
                        if (Settings.SingleCommand != "")
                        {
                            client = new McClient(session.PlayerName, session.PlayerID, session.ID, Settings.ServerIP, Settings.ServerPort, protocolversion, forgeInfo, Settings.SingleCommand);
                        }
                        else
                        {
                            client = new McClient(session.PlayerName, session.PlayerID, session.ID, protocolversion, forgeInfo, Settings.ServerIP, Settings.ServerPort);
                        }

                        //Update console title
                        if (Settings.ConsoleTitle != "")
                        {
                            Console.Title = Settings.ExpandVars(Settings.ConsoleTitle);
                        }
                    }
                    catch (NotSupportedException) { HandleFailure(Translations.Get("error.unsupported"), true); }
                }
                else
                {
                    HandleFailure(Translations.Get("error.determine"), true);
                }
            }
            else
            {
                string failureMessage = Translations.Get("error.login");
                string failureReason  = "";
                switch (result)
                {
                case ProtocolHandler.LoginResult.AccountMigrated: failureReason = "error.login.migrated"; break;

                case ProtocolHandler.LoginResult.ServiceUnavailable: failureReason = "error.login.server"; break;

                case ProtocolHandler.LoginResult.WrongPassword: failureReason = "error.login.blocked"; break;

                case ProtocolHandler.LoginResult.InvalidResponse: failureReason = "error.login.response"; break;

                case ProtocolHandler.LoginResult.NotPremium: failureReason = "error.login.premium"; break;

                case ProtocolHandler.LoginResult.OtherError: failureReason = "error.login.network"; break;

                case ProtocolHandler.LoginResult.SSLError: failureReason = "error.login.ssl"; break;

                case ProtocolHandler.LoginResult.UserCancel: failureReason = "error.login.cancel"; break;

                default: failureReason = "error.login.unknown"; break;
                }
                failureMessage += Translations.Get(failureReason);

                if (result == ProtocolHandler.LoginResult.SSLError && isUsingMono)
                {
                    Translations.WriteLineFormatted("error.login.ssl_help");
                    return;
                }
                HandleFailure(failureMessage, false, ChatBot.DisconnectReason.LoginRejected);
            }
        }
Example #15
0
        public void start_with_explicit_args()
        {
            var foo1 = new Foo();

            var args = new ExplicitArguments();
            args.Set<IFoo>(foo1);

            theCache = new SessionCache(theResolver, args);

            thePipeline.Stub(x => x.GetDefault(typeof (IFoo))).Throw(new NotImplementedException());

            theCache.GetDefault(typeof (IFoo), thePipeline)
                    .ShouldBeTheSameAs(foo1);
        }
        public void When_saving_should_write_to_database()
        {
            var config = new DataConfig();
            config.PerformStartup();
            config.StartSession();

            var visitor = new Visitor
                              {
                                  Browser = "1",
                                  IpAddress = "2",
                                  LoginName = "3",
                                  PathAndQuerystring = "4",
                                  VisitDate =
                                      new DateTime(2000, 1, 1)
                              };

            var repository = new VisitorRepository();
            repository.Save(visitor);

            config.EndSession();
            config.StartSession();

            ISession session = new SessionCache().GetSession();
            var loadedVisitor = session.Load<Visitor>(visitor.Id);

            Assert.That(loadedVisitor, Is.Not.Null);
            Assert.That(loadedVisitor.Browser, Is.EqualTo("1"));
            Assert.That(loadedVisitor.IpAddress, Is.EqualTo("2"));
            Assert.That(loadedVisitor.LoginName, Is.EqualTo("3"));
            Assert.That(loadedVisitor.PathAndQuerystring,
                        Is.EqualTo("4"));
            Assert.That(loadedVisitor.VisitDate,
                        Is.EqualTo(new DateTime(2000, 1, 1)));
        }
 /// <summary>
 /// Releases a lock on the session in a data store.
 /// </summary>
 /// <param name="sessionId">
 /// Session key for the current request.
 /// </param>
 /// <param name="lockId">
 /// The lock identifier for the current request.
 /// </param>
 public virtual void ReleaseSession(SessionKey sessionId, long lockId)
 {
     SessionCache.Invoke(sessionId, new ReleaseSessionProcessor(lockId));
 }
 /// <summary>
 /// Reset session timeout.
 /// </summary>
 /// <param name="sessionId">Session key.</param>
 public virtual void ResetSessionTimeout(SessionKey sessionId)
 {
     SessionCache.Invoke(sessionId, new ResetSessionTimeoutProcessor());
 }
 /// <summary>
 /// Delete session from the cache.
 /// </summary>
 /// <param name="sessionId">Session key.</param>
 public virtual void RemoveSession(SessionKey sessionId)
 {
     SessionCache.Remove(sessionId);
 }
Example #20
0
 public SessionUsage(SessionCache sessionCache)
 {
     _sessionCache = sessionCache;
 }
        /// <summary>
        /// Start a new Client
        /// </summary>
        private static void InitializeClient()
        {
            SessionToken session = new SessionToken();

            ProtocolHandler.LoginResult result = ProtocolHandler.LoginResult.LoginRequired;

            if (Settings.Password == "-")
            {
                ConsoleIO.WriteLineFormatted("§8You chose to run in offline mode.");
                result             = ProtocolHandler.LoginResult.Success;
                session.PlayerID   = "0";
                session.PlayerName = Settings.Login;
            }
            else
            {
                // Validate cached session or login new session.
                if (Settings.SessionCaching != CacheType.None && SessionCache.Contains(Settings.Login.ToLower()))
                {
                    session = SessionCache.Get(Settings.Login.ToLower());
                    result  = ProtocolHandler.GetTokenValidation(session);
                    if (result != ProtocolHandler.LoginResult.Success)
                    {
                        ConsoleIO.WriteLineFormatted("§8Cached session is invalid or expired.");
                        if (Settings.Password == "")
                        {
                            RequestPassword();
                        }
                    }
                    else
                    {
                        ConsoleIO.WriteLineFormatted("§8Cached session is still valid for " + session.PlayerName + '.');
                    }
                }

                if (result != ProtocolHandler.LoginResult.Success)
                {
                    Console.WriteLine("Connecting to Minecraft.net...");
                    result = ProtocolHandler.GetLogin(Settings.Login, Settings.Password, out session);

                    if (result == ProtocolHandler.LoginResult.Success && Settings.SessionCaching != CacheType.None)
                    {
                        SessionCache.Store(Settings.Login.ToLower(), session);
                    }
                }
            }

            if (result == ProtocolHandler.LoginResult.Success)
            {
                Settings.Username = session.PlayerName;

                if (Settings.ConsoleTitle != "")
                {
                    Console.Title = Settings.ExpandVars(Settings.ConsoleTitle);
                }

                if (Settings.playerHeadAsIcon)
                {
                    ConsoleIcon.setPlayerIconAsync(Settings.Username);
                }

                if (Settings.DebugMessages)
                {
                    Console.WriteLine("Success. (session ID: " + session.ID + ')');
                }

                //ProtocolHandler.RealmsListWorlds(Settings.Username, PlayerID, sessionID); //TODO REMOVE

                if (Settings.ServerIP == "")
                {
                    Console.Write("Server IP : ");
                    Settings.SetServerIP(Console.ReadLine());
                }

                //Get server version
                int       protocolversion = 0;
                ForgeInfo forgeInfo       = null;

                if (Settings.ServerVersion != "" && Settings.ServerVersion.ToLower() != "auto")
                {
                    protocolversion = Protocol.ProtocolHandler.MCVer2ProtocolVersion(Settings.ServerVersion);

                    if (protocolversion != 0)
                    {
                        ConsoleIO.WriteLineFormatted("§8Using Minecraft version " + Settings.ServerVersion + " (protocol v" + protocolversion + ')');
                    }
                    else
                    {
                        ConsoleIO.WriteLineFormatted("§8Unknown or not supported MC version '" + Settings.ServerVersion + "'.\nSwitching to autodetection mode.");
                    }

                    if (useMcVersionOnce)
                    {
                        useMcVersionOnce       = false;
                        Settings.ServerVersion = "";
                    }
                }

                if (protocolversion == 0)
                {
                    Console.WriteLine("Retrieving Server Info...");
                    if (!ProtocolHandler.GetServerInfo(Settings.ServerIP, Settings.ServerPort, ref protocolversion, ref forgeInfo))
                    {
                        HandleFailure("Failed to ping this IP.", true, ChatBots.AutoRelog.DisconnectReason.ConnectionLost);
                        return;
                    }
                }

                if (protocolversion != 0)
                {
                    try
                    {
                        //Start the main TCP client
                        if (Settings.SingleCommand != "")
                        {
                            Client = new McTcpClient(session.PlayerName, session.PlayerID, session.ID, Settings.ServerIP, Settings.ServerPort, protocolversion, forgeInfo, Settings.SingleCommand);
                        }
                        else
                        {
                            Client = new McTcpClient(session.PlayerName, session.PlayerID, session.ID, protocolversion, forgeInfo, Settings.ServerIP, Settings.ServerPort);
                        }

                        //Update console title
                        if (Settings.ConsoleTitle != "")
                        {
                            Console.Title = Settings.ExpandVars(Settings.ConsoleTitle);
                        }
                    }
                    catch (NotSupportedException) { HandleFailure("Cannot connect to the server : This version is not supported !", true); }
                }
                else
                {
                    HandleFailure("Failed to determine server version.", true);
                }
            }
            else
            {
                string failureMessage = "Minecraft Login failed : ";
                switch (result)
                {
                case ProtocolHandler.LoginResult.AccountMigrated: failureMessage += "Account migrated, use e-mail as username."; break;

                case ProtocolHandler.LoginResult.ServiceUnavailable: failureMessage += "Login servers are unavailable. Please try again later."; break;

                case ProtocolHandler.LoginResult.WrongPassword: failureMessage += "Incorrect password, blacklisted IP or too many logins."; break;

                case ProtocolHandler.LoginResult.InvalidResponse: failureMessage += "Invalid server response."; break;

                case ProtocolHandler.LoginResult.NotPremium: failureMessage += "User not premium."; break;

                case ProtocolHandler.LoginResult.OtherError: failureMessage += "Network error."; break;

                case ProtocolHandler.LoginResult.SSLError: failureMessage += "SSL Error."; break;

                default: failureMessage += "Unknown Error."; break;
                }
                if (result == ProtocolHandler.LoginResult.SSLError && isUsingMono)
                {
                    ConsoleIO.WriteLineFormatted("§8It appears that you are using Mono to run this program."
                                                 + '\n' + "The first time, you have to import HTTPS certificates using:"
                                                 + '\n' + "mozroots --import --ask-remove");
                    return;
                }
                HandleFailure(failureMessage, false, ChatBot.DisconnectReason.LoginRejected);
            }
        }
Example #22
0
        public void SetUp()
        {
            theResolver = MockRepository.GenerateMock<IBuildSession>();
            theCache = new SessionCache(theResolver);

            thePipeline = MockRepository.GenerateMock<IPipelineGraph>();
        }
        /// <summary>
        /// The main entry point of Minecraft Console Client
        /// </summary>
        static void Main(string[] args)
        {
            Console.WriteLine("Console Client for MC {0} to {1} - v{2} - By ORelio & Contributors", MCLowestVersion, MCHighestVersion, Version);

            //Build information to facilitate processing of bug reports
            if (BuildInfo != null)
            {
                ConsoleIO.WriteLineFormatted("§8" + BuildInfo);
            }

            //Debug input ?
            if (args.Length == 1 && args[0] == "--keyboard-debug")
            {
                Console.WriteLine("Keyboard debug mode: Press any key to display info");
                ConsoleIO.DebugReadInput();
            }

            //Setup ConsoleIO
            ConsoleIO.LogPrefix = "§8[MCC] ";
            if (args.Length >= 1 && args[args.Length - 1] == "BasicIO")
            {
                ConsoleIO.BasicIO = true;
                args = args.Where(o => !Object.ReferenceEquals(o, args[args.Length - 1])).ToArray();
            }

            //Take advantage of Windows 10 / Mac / Linux UTF-8 console
            if (isUsingMono || WindowsVersion.WinMajorVersion >= 10)
            {
                Console.OutputEncoding = Console.InputEncoding = Encoding.UTF8;
            }

            //Process ini configuration file
            if (args.Length >= 1 && System.IO.File.Exists(args[0]) && System.IO.Path.GetExtension(args[0]).ToLower() == ".ini")
            {
                Settings.LoadSettings(args[0]);

                //remove ini configuration file from arguments array
                List <string> args_tmp = args.ToList <string>();
                args_tmp.RemoveAt(0);
                args = args_tmp.ToArray();
            }
            else if (System.IO.File.Exists("MinecraftClient.ini"))
            {
                Settings.LoadSettings("MinecraftClient.ini");
            }
            else
            {
                Settings.WriteDefaultSettings("MinecraftClient.ini");
            }

            //Other command-line arguments
            if (args.Length >= 1)
            {
                Settings.Login = args[0];
                if (args.Length >= 2)
                {
                    Settings.Password = args[1];
                    if (args.Length >= 3)
                    {
                        Settings.SetServerIP(args[2]);

                        //Single command?
                        if (args.Length >= 4)
                        {
                            Settings.SingleCommand = args[3];
                        }
                    }
                }
            }

            if (Settings.ConsoleTitle != "")
            {
                Settings.Username = "******";
                Console.Title     = Settings.ExpandVars(Settings.ConsoleTitle);
            }

            //Load cached sessions from disk if necessary
            if (Settings.SessionCaching == CacheType.Disk)
            {
                bool cacheLoaded = SessionCache.InitializeDiskCache();
                if (Settings.DebugMessages)
                {
                    ConsoleIO.WriteLineFormatted(cacheLoaded ? "§8Session data has been successfully loaded from disk." : "§8No sessions could be loaded from disk");
                }
            }

            //Asking the user to type in missing data such as Username and Password

            if (Settings.Login == "")
            {
                Console.Write(ConsoleIO.BasicIO ? "Please type the username or email of your choice.\n" : "Login : "******"" && (Settings.SessionCaching == CacheType.None || !SessionCache.Contains(Settings.Login.ToLower())))
            {
                RequestPassword();
            }

            startupargs = args;
            InitializeClient();
        }
Example #24
0
        public void try_get_default_with_explicit_arg()
        {
            var foo1 = new Foo();

            var args = new ExplicitArguments();
            args.Set<IFoo>(foo1);

            theCache = new SessionCache(theResolver, args);

            theCache.GetDefault(typeof (IFoo), thePipeline)
                    .ShouldBeTheSameAs(foo1);
        }
Example #25
0
 private void LoginStatus1_LoggedOut(object sender, EventArgs e)
 {
     SessionCache.SaveSiteList(Session, null);
     Session[SessionCache.USER_PLAN] = null;
 }