private bool Handshake(string uuid, string username, string sessionID, string host, int port) { //array byte[] data = new byte[10 + (username.Length + host.Length) * 2]; //packet id data[0] = (byte)2; //Protocol Version data[1] = (byte)protocolversion; //short len byte[] sh = BitConverter.GetBytes((short)username.Length); Array.Reverse(sh); sh.CopyTo(data, 2); //username byte[] bname = Encoding.BigEndianUnicode.GetBytes(username); bname.CopyTo(data, 4); //short len sh = BitConverter.GetBytes((short)host.Length); Array.Reverse(sh); sh.CopyTo(data, 4 + (username.Length * 2)); //host byte[] bhost = Encoding.BigEndianUnicode.GetBytes(host); bhost.CopyTo(data, 6 + (username.Length * 2)); //port sh = BitConverter.GetBytes(port); Array.Reverse(sh); sh.CopyTo(data, 6 + (username.Length * 2) + (host.Length * 2)); Send(data); byte[] pid = new byte[1]; Receive(pid, 0, 1, SocketFlags.None); while (pid[0] == 0xFA) //Skip some early plugin messages { processPacket(pid[0]); Receive(pid, 0, 1, SocketFlags.None); } if (pid[0] == 0xFD) { string serverID = readNextString(); byte[] PublicServerkey = readNextByteArray(); byte[] token = readNextByteArray(); if (serverID == "-") { ConsoleIO.WriteLineFormatted("§8Server is in offline mode."); } else if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted("§8Handshake successful. (Server ID: " + serverID + ')'); } return(StartEncryption(uuid, username, sessionID, token, serverID, PublicServerkey)); } else { return(false); } }
public void Execute() { OrderManager manager = OrderManagerFactory.Create(); Order order = new Order(); bool orderExists; EditOrderInFile editInFile = new EditOrderInFile(); DateTime orderDate = new DateTime().Date; Calculations caluclate = new Calculations(); PrintReceipt print = new PrintReceipt(); OrderLookupResponse lookupResponse = new OrderLookupResponse(); EditOrderResponse editResponse = new EditOrderResponse(); EditOrderRule editRules = new EditOrderRule(); List <Order> Orders = new List <Order>(); bool exception = false; while (true) { while (true) { Console.Clear(); Console.WriteLine("Edit an order"); Console.WriteLine(TextHelper.ConsoleBar); Console.WriteLine("Please enter the following information...."); Console.WriteLine(); Console.WriteLine("Date of order: "); if (DateTime.TryParse(Console.ReadLine(), out orderDate)) { order.Date = orderDate; break; } else { Console.WriteLine("You did not enter a valid date format. Press any key to continue..."); Console.ReadKey(); Console.Clear(); } } try { lookupResponse = manager.LookupOrder(order.Date); if (lookupResponse != null) { Orders = lookupResponse.Orders; } } catch (Exception ex) { Console.WriteLine("You cannot proceed. Please contact IT."); Console.WriteLine(ex.Message); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); exception = true; break; } if (lookupResponse.success) { break; } else { Console.WriteLine("An error occurred."); Console.WriteLine(lookupResponse.message); continue; } } if (exception == false) { while (true) { Console.Clear(); ConsoleIO.DisplayOrderDetails(lookupResponse.Orders); int orderNumber; Console.WriteLine("Order number: "); if (int.TryParse(Console.ReadLine(), out orderNumber)) { order.OrderNumber = orderNumber; } else { Console.WriteLine("You did not enter a number. Press any key to continue..."); Console.ReadKey(); } string filePath = FilePath.GetFilePath(order.Date); Orders = ReadOrdersFromFile.ReadOrders(filePath); orderExists = editInFile.CheckOrderNumberExists(Orders, order.OrderNumber); if (!orderExists) { Console.WriteLine("That order number does not exist for the date you entered. Press any key to continue..."); Console.ReadKey(); continue; } else { Order singleOrder = Orders.Where(ord => ord.OrderNumber == order.OrderNumber).Single(); order = singleOrder; } order = editInFile.GetNewOrderInfoFromUser(order); order = caluclate.EditCalculations(order, order.Date, order.CustomerName, order.State, order.ProductType, order.Area); editResponse = editRules.EditRules(order.Date, order.CustomerName, order.State, order.ProductType, order.Area, editResponse); if (!editResponse.success) { Console.WriteLine("An error occurred: "); Console.WriteLine(editResponse.message); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } else { break; } } while (true) { print.Print(order); Console.WriteLine("Is the updated order correct (Y/N)?"); string userInput = Console.ReadLine().ToUpper(); switch (userInput) { case "Y": EditOrderFile editOrder = new EditOrderFile(); editOrder.EditOrderToFile(Orders, order.Date); Console.WriteLine("Edit has been saved! Press any key to continue..."); Console.ReadKey(); break; case "N": Console.WriteLine("Edit has been canceled. Press any key to continue..."); Console.ReadKey(); break; default: Console.WriteLine("That was not a valid entry! Press any key to continue..."); Console.ReadKey(); continue; } break; } } }
public void Execute() { Console.Clear(); OrderManager orderManager = OrderManagerFactory.Create(); Console.Clear(); Console.WriteLine("Edit an Order"); Console.WriteLine("-------------------------"); bool goodDate = false; string orderDate; do { //must be in the future Console.Write("Enter the date you are interested in (use MMDDYYYY format):\n"); orderDate = Console.ReadLine(); if (orderDate != null && orderDate.Count() == 8) { goodDate = true; continue; } else { Console.WriteLine("Please enter a date in correct format."); goodDate = false; } } while (goodDate == false); bool goodNumber = false; int orderNumber; do { //must be in the future Console.Write("Enter Order Number you wish to edit:\n"); orderNumber = int.Parse(Console.ReadLine()); if (orderNumber <= 0 || orderNumber > 0) { goodNumber = true; continue; } else { Console.WriteLine("Please enter a good order number."); goodNumber = false; } } while (goodNumber == false); Orders passOrderEdit = new Orders(); List <Orders> lastOrders = new List <Orders>(); lastOrders = orderManager._orderRepository.FindOrder(orderDate); if (lastOrders == null) { Console.WriteLine("There are no orders for order number provided. "); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); Menu.Start(); } else { foreach (var order in lastOrders) { if (order.OrderNumber == orderNumber) { passOrderEdit.OrderNumber = order.OrderNumber; passOrderEdit.CustomerName = order.CustomerName; passOrderEdit.State = order.State; passOrderEdit.TaxRate = order.TaxRate; passOrderEdit.ProductType = order.ProductType; passOrderEdit.Area = order.Area; passOrderEdit.CostPerSquareFoot = order.CostPerSquareFoot; passOrderEdit.LaborCostPerSquareFoot = order.LaborCostPerSquareFoot; passOrderEdit.MaterialCost = order.MaterialCost; passOrderEdit.LaborCost = order.LaborCost; passOrderEdit.Tax = order.Tax; passOrderEdit.Total = order.Total; break; } else { continue; } } } Orders userEdit = new Orders(); Console.Write($"Edit CustomerName ({passOrderEdit.CustomerName}):\n"); string editCustomerName = Console.ReadLine(); if (editCustomerName == null) { userEdit.CustomerName = passOrderEdit.CustomerName; } else { userEdit.CustomerName = editCustomerName; } string editState; //decimal editTaxRate; Tax taxChoice = null; bool goodTax = false; do { Console.Write($"Edit State ({passOrderEdit.State}):\n"); editState = Console.ReadLine(); var taxdownload = orderManager._orderRepository.LookUpTax(editState); if (editState == taxdownload.StateName) { taxChoice = taxdownload; userEdit.TaxRate = taxdownload.TaxRate; userEdit.State = taxdownload.StateName; Console.Write($"{taxdownload.StateName} TaxRate is: {taxdownload.TaxRate}\n"); Console.Write($"\n"); goodTax = true; } else if (editState == null) { userEdit.TaxRate = passOrderEdit.TaxRate; userEdit.State = passOrderEdit.State; goodTax = true; } else { Console.Write("Sorry, we cannot sell to this state at this time."); //editTaxRate = 0; goodTax = false; } } while (goodTax == false); string editProductType; Console.Write($"Edit Product Type ({passOrderEdit.ProductType}):\n"); var productDown = orderManager._orderRepository.LookUpProducts(); foreach (var product in productDown) { Console.WriteLine("{0}, {1}, {2}", product.ProductType, product.LaborCostPerSquareFoot, product.CostPerSquareFoot); Console.Write(""); } Console.Write($"\n"); editProductType = Console.ReadLine(); bool goodProduct = false; Products editConfirmedChoice = null; do { //Products confirmedChoice; Console.WriteLine(""); if (editProductType == null) { userEdit.ProductType = passOrderEdit.ProductType; } else { var productChoice = orderManager._orderRepository.ChooseProduct(editProductType); if (productChoice != null) { editConfirmedChoice = productChoice; userEdit.ProductType = productChoice.ProductType; userEdit.CostPerSquareFoot = productChoice.CostPerSquareFoot; userEdit.LaborCostPerSquareFoot = productChoice.LaborCostPerSquareFoot; goodProduct = true; } else { Console.Write("\n You have made an incorrect choice, please choose again."); goodProduct = false; }; } } while (goodProduct == false); bool goodArea = false; decimal editArea; do { Console.Write($"Edit Area ({passOrderEdit.Area}):\n"); editArea = Convert.ToDecimal(Console.ReadLine()); if (editArea >= 100M) { if (editArea.ToString().Count() == 0) { userEdit.Area = passOrderEdit.Area; } else { userEdit.Area = editArea; } goodArea = true; continue; } else { Console.WriteLine("\nArea entered must be positive and greater than 100 sq feet."); goodArea = false; } } while (goodArea == false); decimal costPerSquareFoot; decimal laborCostPerSquareFoot; decimal materialCost; decimal laborCost; decimal tax; decimal total; costPerSquareFoot = editConfirmedChoice.CostPerSquareFoot; laborCostPerSquareFoot = editConfirmedChoice.LaborCostPerSquareFoot; materialCost = userEdit.Area * editConfirmedChoice.CostPerSquareFoot; laborCost = userEdit.Area * editConfirmedChoice.LaborCostPerSquareFoot; tax = ((userEdit.Area * editConfirmedChoice.CostPerSquareFoot) + (userEdit.Area * editConfirmedChoice.LaborCostPerSquareFoot)) * (taxChoice.TaxRate / 100); total = (userEdit.Area * editConfirmedChoice.CostPerSquareFoot) + (userEdit.Area * editConfirmedChoice.LaborCostPerSquareFoot) + (((userEdit.Area * editConfirmedChoice.CostPerSquareFoot) + (userEdit.Area * editConfirmedChoice.LaborCostPerSquareFoot)) * (taxChoice.TaxRate / 100)); userEdit.OrderNumber = orderNumber; userEdit.LaborCost = laborCost; userEdit.MaterialCost = materialCost; userEdit.Tax = tax; userEdit.Total = total; Console.Write($"\nOrderDate is {orderDate}"); Console.Write($"\nOrderNumber is {orderNumber}"); Console.Write($"\nCustomerName is {userEdit.CustomerName}"); Console.Write($"\nStateName is {taxChoice.StateAbbreviation}"); Console.Write($"\nTaxRate is {taxChoice.TaxRate}"); Console.Write($"\nProductType is {userEdit.ProductType}"); Console.Write($"\nCostPerSquareFoot is {costPerSquareFoot}"); Console.Write($"\nLaborCostPerSquareFoot is {laborCostPerSquareFoot}"); Console.Write($"\nMaterialCost: {materialCost}"); Console.Write($"\nLaborCost: {laborCost}"); Console.Write($"\nTax: {tax}"); Console.Write($"\nTotal: {total}"); Console.Write("\n Please review changes above. \n If info seems right, please type Edit to continue or anything else to go back to main menu. \n"); string resp = Console.ReadLine(); if (resp == "Edit") { OrderEditResponse response = orderManager.Edit(userEdit, orderDate, orderNumber); if (response.Success) { ConsoleIO.DisplayOrderDetails(response.Orders, orderDate); } else { Console.WriteLine("An error occurred: "); Console.WriteLine(response.Message); } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } else { Menu.Start(); } }
/// <summary> /// Allows to login to a premium Minecraft account using the Yggdrasil authentication scheme. /// </summary> /// <param name="user">Login</param> /// <param name="pass">Password</param> /// <param name="session">In case of successful login, will contain session information for multiplayer</param> /// <returns>Returns the status of the login (Success, Failure, etc.)</returns> public static LoginResult GetLogin(string user, string pass, out SessionToken session) { session = new SessionToken() { ClientID = Guid.NewGuid().ToString().Replace("-", "") }; try { string result = ""; string json_request = "{\"agent\": { \"name\": \"Minecraft\", \"version\": 1 }, \"username\": \"" + JsonEncode(user) + "\", \"password\": \"" + JsonEncode(pass) + "\", \"clientToken\": \"" + JsonEncode(session.ClientID) + "\" }"; int code = DoHTTPSPost("authserver.mojang.com", "/authenticate", json_request, ref result); if (code == 200) { if (result.Contains("availableProfiles\":[]}")) { return(LoginResult.NotPremium); } else { Json.JSONData loginResponse = Json.ParseJson(result); if (loginResponse.Properties.ContainsKey("accessToken") && loginResponse.Properties.ContainsKey("selectedProfile") && loginResponse.Properties["selectedProfile"].Properties.ContainsKey("id") && loginResponse.Properties["selectedProfile"].Properties.ContainsKey("name")) { session.ID = loginResponse.Properties["accessToken"].StringValue; session.PlayerID = loginResponse.Properties["selectedProfile"].Properties["id"].StringValue; session.PlayerName = loginResponse.Properties["selectedProfile"].Properties["name"].StringValue; return(LoginResult.Success); } else { return(LoginResult.InvalidResponse); } } } else if (code == 403) { if (result.Contains("UserMigratedException")) { return(LoginResult.AccountMigrated); } else { return(LoginResult.WrongPassword); } } else if (code == 503) { return(LoginResult.ServiceUnavailable); } else { ConsoleIO.WriteLineFormatted(Translations.Get("error.http_code", code)); return(LoginResult.OtherError); } } catch (System.Security.Authentication.AuthenticationException e) { if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted("§8" + e.ToString()); } return(LoginResult.SSLError); } catch (System.IO.IOException e) { if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted("§8" + e.ToString()); } if (e.Message.Contains("authentication")) { return(LoginResult.SSLError); } else { return(LoginResult.OtherError); } } catch (Exception e) { if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted("§8" + e.ToString()); } return(LoginResult.OtherError); } }
/// <summary> /// Reads cache file and loads SessionTokens into SessionCache. /// </summary> /// <returns>True if data is successfully loaded</returns> private static bool LoadFromDisk() { //Grab sessions in the Minecraft directory if (File.Exists(SessionCacheFileMinecraft)) { if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted(Translations.Get("cache.loading", Path.GetFileName(SessionCacheFileMinecraft))); } Json.JSONData mcSession = new Json.JSONData(Json.JSONData.DataType.String); try { mcSession = Json.ParseJson(File.ReadAllText(SessionCacheFileMinecraft)); } catch (IOException) { /* Failed to read file from disk -- ignoring */ } if (mcSession.Type == Json.JSONData.DataType.Object && mcSession.Properties.ContainsKey("clientToken") && mcSession.Properties.ContainsKey("authenticationDatabase")) { Guid temp; string clientID = mcSession.Properties["clientToken"].StringValue.Replace("-", ""); Dictionary <string, Json.JSONData> sessionItems = mcSession.Properties["authenticationDatabase"].Properties; foreach (string key in sessionItems.Keys) { if (Guid.TryParseExact(key, "N", out temp)) { Dictionary <string, Json.JSONData> sessionItem = sessionItems[key].Properties; if (sessionItem.ContainsKey("displayName") && sessionItem.ContainsKey("accessToken") && sessionItem.ContainsKey("username") && sessionItem.ContainsKey("uuid")) { string login = sessionItem["username"].StringValue.ToLower(); try { SessionToken session = SessionToken.FromString(String.Join(",", sessionItem["accessToken"].StringValue, sessionItem["displayName"].StringValue, sessionItem["uuid"].StringValue.Replace("-", ""), clientID )); if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted(Translations.Get("cache.loaded", login, session.ID)); } sessions[login] = session; } catch (InvalidDataException) { /* Not a valid session */ } } } } } } //Serialized session cache file in binary format if (File.Exists(SessionCacheFileSerialized)) { if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted(Translations.Get("cache.converting", SessionCacheFileSerialized)); } try { using (FileStream fs = new FileStream(SessionCacheFileSerialized, FileMode.Open, FileAccess.Read, FileShare.Read)) { Dictionary <string, SessionToken> sessionsTemp = (Dictionary <string, SessionToken>)formatter.Deserialize(fs); foreach (KeyValuePair <string, SessionToken> item in sessionsTemp) { if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted(Translations.Get("cache.loaded", item.Key, item.Value.ID)); } sessions[item.Key] = item.Value; } } } catch (IOException ex) { ConsoleIO.WriteLineFormatted(Translations.Get("cache.read_fail", ex.Message)); } catch (SerializationException ex2) { ConsoleIO.WriteLineFormatted(Translations.Get("cache.malformed", ex2.Message)); } } //User-editable session cache file in text format if (File.Exists(SessionCacheFilePlaintext)) { if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted(Translations.Get("cache.loading_session", SessionCacheFilePlaintext)); } try { foreach (string line in FileMonitor.ReadAllLinesWithRetries(SessionCacheFilePlaintext)) { if (!line.Trim().StartsWith("#")) { string[] keyValue = line.Split('='); if (keyValue.Length == 2) { try { string login = keyValue[0].ToLower(); SessionToken session = SessionToken.FromString(keyValue[1]); if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted(Translations.Get("cache.loaded", login, session.ID)); } sessions[login] = session; } catch (InvalidDataException e) { if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted(Translations.Get("cache.ignore_string", keyValue[1], e.Message)); } } } else if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted(Translations.Get("cache.ignore_line", line)); } } } } catch (IOException e) { ConsoleIO.WriteLineFormatted(Translations.Get("cache.read_fail_plain", e.Message)); } } return(sessions.Count > 0); }
public virtual bool RunAndContinue() { try { //to store last user answer string lastAnswer = string.Empty; //all posible answers var userAnswersDict = new Dictionary <FarmerPazle_Answers, string>(_rulesProvider.AnswersDict); //to store all correct answers as string StringBuilder enteredCorrectAnsw = new StringBuilder(); //get last pressed key info ConsoleKeyInfo keyInfo = default(ConsoleKeyInfo); //resize console window ConsoleIO.ResizeConsoleWindow(Console.WindowWidth, Console.WindowHeight + 10); //for getting the time of user game Stopwatch sw = new Stopwatch(); // start the stopwatch sw.Start(); do // while user answer number < MAX attempts And until user find the right answer / key { //Clear console and show task header and rules description Console.Clear(); ConsoleIO.WriteColorTextNewLine(this.ToString(), ConsoleColor.Cyan); ConsoleIO.WriteColorTextNewLine(_rulesProvider.RulesDescription); //Show all posible answers userAnswersDict.ToList().ForEach(x => ConsoleIO.WriteColorTextNewLine(String.Format(x.Value, string.Empty), ConsoleColor.White, Rules.CorrectAnswerLabel.ToString(), ConsoleColor.DarkGreen)); ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator); //Check and show the object that must be tranfer to the other bank of river and which have been already transferred there _transferProvider.ShowCurrentTransferStatus(lastAnswer); //check if last answer was incorrect if (_rulesProvider.CurrenAttempt > 0 && String.IsNullOrWhiteSpace(lastAnswer)) { ConsoleIO.WriteColorTextNewLine("Incorrect entered value!", ConsoleColor.Red); } //show how many lifes user has ConsoleIO.WriteColorText("Lifes count: ", ConsoleColor.White); ConsoleIO.WriteColorTextNewLine(_rulesProvider.MaxAttemptsCount - _rulesProvider.CurrenAttempt, _rulesProvider.GetCurrentAttemptColor()); //show already enered correct answers / keys ConsoleIO.WriteColorText("Entered correct keys: ", ConsoleColor.White); ConsoleIO.WriteColorTextNewLine(enteredCorrectAnsw.ToString(), ConsoleColor.Green); //show last enered key char if (keyInfo != default(ConsoleKeyInfo)) { ConsoleIO.WriteColorTextNewLine(string.Format("Last entered key: '{0}", keyInfo.KeyChar)); } //show text separator (by default: ------------) ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator); //chech if user has already found the right answer / key. If Yes then exit from do {...}while(...); if (_rulesProvider.IsAlreadyWin(enteredCorrectAnsw)) { break; } //read key keyInfo = Console.ReadKey(); //check if current answer is correct (compare with the dictionary of keys) lastAnswer = GetCorrectAnswer(keyInfo.KeyChar.ToString(), userAnswersDict, ref enteredCorrectAnsw); } while (!_rulesProvider.IsMaxAttempt()); //check if user answer number < MAX attempts sw.Stop(); // stop the stopwatch if (_rulesProvider.IsMaxAttempt()) //check if user answer number >= MAX attempts { ConsoleIO.WriteColorTextNewLine("\n-!-!-!-!-!-!-!GAME OVER!-!-!-!-!-!-!-\n", ConsoleColor.Red); } else //user find the right answer / key { ConsoleIO.WriteColorTextNewLine("\n-!-!-!-!-!-!-!Well Done!-!-!-!-!-!-!-\n", ConsoleColor.Green); ConsoleIO.WriteColorTextNewLine(string.Format("{0}!, you are a winner! Your Time is: '{1}' sec\n", Environment.UserName, sw.Elapsed.Seconds), ConsoleColor.Green); } //show the suggestion of pressing any key to return to the main menu ConsoleIO.Console_ToMainMenu(); return(true); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(false); }
private void FightPhase() { turnOrder = new List <Entity>(8); setTurnOrder(turnOrder); int turn = 0; bool fighting = true; while (fighting) { if (CurrentUser.Party.Count == 0 || room.Enemies.Count == 0) { fighting = false; } else { if (turnOrder[turn % turnOrder.Count] is Minion) { //view things to select an action string[] options = { ActionType.Attack.ToString(), ActionType.Heal.ToString() }; List <string> enemies = new List <string>(); List <string> minions = new List <string>(); //for (int i = 0; i < room.Enemies.Count; i++) //{ // enemies[i] = room.Enemies[i].Name; //} foreach (Enemy e in room.Enemies) { enemies.Add(e.Name); } foreach (Minion m in CurrentUser.Party) { minions.Add(m.Name); } Console.WriteLine("It is " + turnOrder[turn % turnOrder.Count].Name + "'s turn"); if (turnOrder[turn % turnOrder.Count] is Minion) { Console.WriteLine($"{turnOrder[turn % turnOrder.Count].Name}'s Stats\n{turnOrder[turn % turnOrder.Count].Health}"); } switch (ConsoleIO.PromptForMenuSelection(options, false, "Select an action: ")) { case 1: AttackAction(turnOrder[turn % turnOrder.Count], room.Enemies[ConsoleIO.PromptForMenuSelection(enemies.ToArray(), false, "Select an enemy to attack: ") - 1]); break; case 2: HealAction(turnOrder[turn % turnOrder.Count], CurrentUser.Party[ConsoleIO.PromptForMenuSelection(minions.ToArray(), false, "Select a member of your party to heal: ") - 1]); break; default: break; } } else { Console.WriteLine("It is " + turnOrder[turn % turnOrder.Count].Name + "'s turn"); AttackAction(turnOrder[turn % turnOrder.Count], CurrentUser.Party[rand.Next(CurrentUser.Party.Count)]); } } turn++; } }
public void Execute() { OrderManager manager = OrderManagerFactory.Create(); StateManager stateManager = StateManagerFactory.Create(); ProductManager productManager = ProductManagerFactory.Create(); ConsoleIO.OrderHeader("Edit an Order:"); Console.WriteLine("Please enter the date of the order you would like to edit."); var repo = manager.GetAllOrders(ConsoleIO.GetDateFromUser()); if (repo.Success) { ConsoleIO.OrderHeader("Edit an Order:"); ConsoleIO.DisplayAllOdersForDate(repo.Orders); Console.WriteLine(ConsoleIO.SeparatorBar); Console.WriteLine(); int orderNumber = ConsoleIO.GetOrderNumberFromUser("Which order number would you like to edit?: "); var ordertoedit = manager.LookupOrder(ConsoleIO.OrderDate, orderNumber); if (ordertoedit.Success) { ConsoleIO.OrderHeader("Edit an Order:"); Console.WriteLine("Type the information to edit in the following prompts.\n If you wish to keep the information in parenthesis simply press enter."); string name = ConsoleIO.GetCustomerNameEdit(ordertoedit.Order.Name); if (!string.IsNullOrEmpty(name)) { ordertoedit.Order.Name = name; } var response = stateManager.ListAllStates(); if (response.Success) { ConsoleIO.OrderHeader("Edit an Order:Type the information to edit in the following prompts.\n If you wish to keep the information in parenthesis simply press enter."); ConsoleIO.DisplayAllStates(response.StateList); Console.WriteLine(); while (true) { string state = ConsoleIO.GetStateForEdit(ordertoedit.Order.State); if (!string.IsNullOrEmpty(state)) { var StateTax = stateManager.LookupState(state); if (StateTax.Success) { ordertoedit.Order.State = StateTax.StateTax.State; ordertoedit.Order.TaxRate = StateTax.StateTax.TaxRate; break; } else { Console.WriteLine(StateTax.Message); ConsoleIO.EnterKeyToContinue(); } } break; } } ConsoleIO.OrderHeader("Edit an Order:Type the information to edit in the following prompts.\n If you wish to keep the information in parenthesis simply press enter."); var productresponse = productManager.ProductList(); if (productresponse.Success) { ConsoleIO.DisplayAllProducts(productresponse.Products); Console.WriteLine(); while (true) { string product = ConsoleIO.GetProductTypeForEdit(ordertoedit.Order.PrductType); if (!string.IsNullOrEmpty(product)) { var customerProduct = productManager.ChooseProduct(product); if (customerProduct.Success) { ordertoedit.Order.PrductType = customerProduct.Product.ProductType; ordertoedit.Order.CostPerSqureFoot = customerProduct.Product.CostPerSquareFoot; ordertoedit.Order.LaborCostPerSquareFoot = customerProduct.Product.LaborCostPerSquareFoot; break; } else { Console.WriteLine(customerProduct.Message); ConsoleIO.EnterKeyToContinue(); } } break; } while (true) { decimal area; ConsoleIO.OrderHeader("Edit an Order:Type the information to edit in the following prompts. \nIf you wish to keep the information in parenthesis simply press enter."); Console.Write($"Enter the squarefootage for the floor ({ordertoedit.Order.Area}): "); string input = Console.ReadLine(); if (string.IsNullOrEmpty(input)) { break; } if (!decimal.TryParse(input, out area)) { Console.WriteLine("You must enter valid number."); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } if (area < 100) { Console.WriteLine("The square foot area must be at least 100 square feet."); ConsoleIO.EnterKeyToContinue(); } else { ordertoedit.Order.Area = area; break; } } ConsoleIO.OrderHeader("Edit an Order:"); ConsoleIO.DisplayOrders(ordertoedit.Order); string answer = ConsoleIO.GetYesNoAnswerFromUser("Would you like to update this order?: "); if (answer == "Y") { var editResponse = manager.EditOrder(ordertoedit.Order, ConsoleIO.OrderDate); if (editResponse.Success) { Console.WriteLine("The order was updated!"); ConsoleIO.EnterKeyToContinue(); } else { Console.WriteLine(editResponse.Message); ConsoleIO.EnterKeyToContinue(); } } else { Console.WriteLine("The edit was cancelled."); ConsoleIO.EnterKeyToContinue(); } ordertoedit.Order.MaterialCost = ordertoedit.Order.Area * ordertoedit.Order.CostPerSqureFoot; ordertoedit.Order.LaborCost = ordertoedit.Order.Area * ordertoedit.Order.LaborCostPerSquareFoot; ordertoedit.Order.Tax = (ordertoedit.Order.MaterialCost + ordertoedit.Order.LaborCost) * (ordertoedit.Order.TaxRate / 100); ordertoedit.Order.Total = ordertoedit.Order.MaterialCost + ordertoedit.Order.LaborCost + ordertoedit.Order.Tax; Console.Clear(); ConsoleIO.DisplayOrders(ordertoedit.Order); Console.WriteLine(ConsoleIO.SeparatorBar); } else { Console.WriteLine(response.Message); ConsoleIO.EnterKeyToContinue(); } } else { Console.WriteLine(ordertoedit.Message); ConsoleIO.EnterKeyToContinue(); } } else { Console.WriteLine(repo.Message); ConsoleIO.EnterKeyToContinue(); } }
/// <summary> /// Allows to login to a premium Minecraft account using the Yggdrasil authentication scheme. /// </summary> /// <param name="user">Login</param> /// <param name="pass">Password</param> /// <param name="accesstoken">Will contain the access token returned by Minecraft.net, if the login is successful</param> /// <param name="uuid">Will contain the player's UUID, needed for multiplayer</param> /// <returns>Returns the status of the login (Success, Failure, etc.)</returns> public static LoginResult GetLogin(ref string user, string pass, ref string accesstoken, ref string uuid) { try { string result = ""; string json_request = "{\"agent\": { \"name\": \"Minecraft\", \"version\": 1 }, \"username\": \"" + jsonEncode(user) + "\", \"password\": \"" + jsonEncode(pass) + "\" }"; int code = doHTTPSPost("authserver.mojang.com", "/authenticate", json_request, ref result); if (code == 200) { if (result.Contains("availableProfiles\":[]}")) { return(LoginResult.NotPremium); } else { string[] temp = result.Split(new string[] { "accessToken\":\"" }, StringSplitOptions.RemoveEmptyEntries); if (temp.Length >= 2) { accesstoken = temp[1].Split('"')[0]; } temp = result.Split(new string[] { "name\":\"" }, StringSplitOptions.RemoveEmptyEntries); if (temp.Length >= 2) { user = temp[1].Split('"')[0]; } temp = result.Split(new string[] { "availableProfiles\":[{\"id\":\"" }, StringSplitOptions.RemoveEmptyEntries); if (temp.Length >= 2) { uuid = temp[1].Split('"')[0]; } return(LoginResult.Success); } } else if (code == 403) { if (result.Contains("UserMigratedException")) { return(LoginResult.AccountMigrated); } else { return(LoginResult.WrongPassword); } } else if (code == 503) { return(LoginResult.ServiceUnavailable); } else { ConsoleIO.WriteLineFormatted("§8Got error code from server: " + code); return(LoginResult.OtherError); } } catch (System.Security.Authentication.AuthenticationException) { return(LoginResult.SSLError); } catch (System.IO.IOException e) { if (e.Message.Contains("authentication")) { return(LoginResult.SSLError); } else { return(LoginResult.OtherError); } } catch { return(LoginResult.OtherError); } }
public void Execute() { bool notValidOrder = true; while (notValidOrder) { OrderManager orderManager = OrderManagerFactory.Create(); Order order = new Order(); Console.Clear(); bool notValidDate = true; while (notValidDate) { DateTime orderDate; Console.WriteLine("Please Enter the Order Date You Would Like to Remove: (MMDDYYYY): "); string userDate = Console.ReadLine(); string format = "MMddyyyy"; if (DateTime.TryParseExact(userDate, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out orderDate)) { order.OrderDate = orderDate; notValidDate = false; } else { Console.WriteLine(); Console.WriteLine("That is Not a Valid Date. Please Re-Enter Correct Order Date."); notValidDate = true; } } Console.WriteLine(); bool notValidNumber = true; while (notValidNumber) { Console.WriteLine("Please Enter the Order Number You Want to Remove: "); string oNum = Console.ReadLine(); if (int.TryParse(oNum, out int orderNumber)) { order.OrderNumber = orderNumber; notValidNumber = false; } else { Console.WriteLine("That is Not a Valid Order Number. Please Re-Enter."); notValidNumber = true; } } OrderLookupResponse lookupOrder = orderManager.LookupOrder(order.OrderDate); if (lookupOrder.Success) { ConsoleIO.DisplayOrderDetails(lookupOrder.Order); bool notYesOrNo = true; while (notYesOrNo) { Console.WriteLine("Are You Sure You Want to Remove This Order (Y/N)?"); string input = Console.ReadLine().ToUpper(); if (input == "Y") { RemoveOrderResponse removeOrder = orderManager.RemoveOrder(order, order.OrderDate, order.OrderNumber); if (removeOrder.Success) { Console.Clear(); Console.WriteLine("Order Removed!"); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); notValidOrder = false; break; } else { Console.Clear(); Console.WriteLine("An error occured: "); Console.WriteLine(removeOrder.Message); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); notValidOrder = true; } } if (input == "N") { Environment.Exit(1); } else { Console.WriteLine("Please Enter Y or N."); notYesOrNo = true; } } } else { Console.WriteLine("An error occured: "); Console.WriteLine(lookupOrder.Message); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); notValidOrder = true; } } }
public void Execute() { OrderManager manager = OrderManagerFactory.Create(); Console.Clear(); Console.WriteLine("Remove an order"); Console.WriteLine("-------------------------------------"); Console.Write("Enter the order date: "); string date = Console.ReadLine(); OrderLookupResponse response; if (DateTime.TryParse(date, out DateTime orderDate)) { response = manager.LookupOrderDate(orderDate); if (!response.Success) { Console.Write("Error: "); Console.WriteLine(response.Message); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); return; } } else { Console.WriteLine("Error: The date entered is not a valid date"); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); return; } Console.Write("Enter the order number:"); string orderNumCheck = Console.ReadLine(); if (int.TryParse(orderNumCheck, out int orderNumber)) { response = manager.LookupOrderNumber(orderNumber); if (!response.Success) { Console.Write("Error: "); Console.WriteLine(response.Message); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); return; } } else { Console.WriteLine("Error: Invalid input"); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); return; } Order order = response.Order; Console.WriteLine("Order details"); Console.WriteLine("*******************"); ConsoleIO.DisplayOrderDetails(order); Console.WriteLine("*******************"); Console.Write("Delete this order? This cannot be undone. Y/N: "); while (true) { string userSelection = Console.ReadLine(); if (userSelection == "Y") { manager.RemoveOrder(order); Console.WriteLine("Order deleted. Press any key to continue"); Console.ReadKey(); return; } else if (userSelection == "N") { Console.WriteLine("Order deletion cancelled. Press any key to continue..."); Console.ReadKey(); return; } else { Console.Write("Invalid input. Enter Y or N: "); } } }
public override void Log(LogEntryType type, string message, params object[] args) { var msg = string.Format(message, args); ConsoleIO.WriteOutput(string.Format("{0}: {1}: {2}", type, DateTime.Now, msg), _colors[type]); }
public Order GetEdits(Order OrderToEdit) { //Order EditedOrder = new Order(); // Edit Customer Name Console.Write($"Customer Name ({OrderToEdit.CustomerName}), "); CommonIO.MessageToUserInBlue("press Enter for no change."); String newCustomerName = ConsoleIO.AskForNewCustomerName(); if (newCustomerName == "") { Console.WriteLine("Name Unchanged\n"); } else { OrderToEdit.CustomerName = newCustomerName; } // Edit State Console.WriteLine($"Order State ({OrderToEdit.State}):"); CommonIO.MessageToUserInBlue(" 0. No change"); String newState = ConsoleIO.AskForNewStateAbbr(); if (newState != null) { Console.WriteLine("State Unchanged"); } else { OrderToEdit.State = newState; } // Edit Product Console.WriteLine($"Product ({OrderToEdit.ProductType}):"); CommonIO.MessageToUserInBlue(" 0. No change"); Product EditedProduct = ConsoleIO.AskForNewProduct(); if (newState == null) { Console.WriteLine("Product Unchanged"); } else { OrderToEdit.State = newState; } // Edit Area Console.WriteLine($"Area ({OrderToEdit.Area}), "); CommonIO.MessageToUserInBlue("Enter 0 for no change."); //Decimal editedArea = ConsoleIO.AskForArea(); decimal editedArea = 0; int min = 100, max = 100000; bool intCk = false; do { intCk = decimal.TryParse(Console.ReadLine(), out editedArea); if (!intCk) { editedArea = 1; } if (editedArea == 0) { CommonIO.MessageToUserInBlue("Area unchanged."); break; } else if (editedArea < min) { CommonIO.MessageToUserInBlue($"Please enter a number between {min} and {max}"); //CommonIO.Continue(); } } while (editedArea < min || editedArea > max); if (editedArea != 0) { OrderToEdit.Area = editedArea; } CommonIO.MessageToUserInBlue("Editing order is complete. Next, you'll view the edited order and decide if you want to save it."); CommonIO.Continue(); Console.Clear(); ConsoleIO.DisplayOrderDetails(OrderToEdit); //• CustomerName, State, ProductType, Area return(OrderToEdit); }
public AIPlayer(ConsoleIO consoleIO, List<TicTacToeStrategy> strategies, char mark) { this.consoleIO = consoleIO; this.strategies = strategies; this.Mark = mark; }
public void Execute() { OrderManager manager = OrderFactory.Create(); Console.Clear(); Console.WriteLine("Edit an Order"); Console.WriteLine("-----------------------"); bool flag1 = true; int orderNum = 0; while (flag1) { Console.Write("Enter an order number: "); string number = Console.ReadLine(); if (number == null || number == "") { Console.WriteLine("Not a valid Order Number"); ConsoleIO.PressAnyKey(); Console.Clear(); Console.WriteLine("Remove an Order"); Console.WriteLine("-----------------------"); continue; } if (!int.TryParse(number, out orderNum)) { Console.WriteLine("Not a valid Order Number"); ConsoleIO.PressAnyKey(); Console.Clear(); Console.WriteLine("Lookup an Order"); Console.WriteLine("-----------------------"); continue; } else { flag1 = false; } } bool flag2 = true; DateTime time = new DateTime(); while (flag2) { Console.Write("Enter an order date(MM-dd-yyyy): "); string date = Console.ReadLine(); if (date == null || date == "") { Console.WriteLine("Not a Valid Date. Try again"); ConsoleIO.PressAnyKey(); Console.Clear(); continue; } if (!DateTime.TryParse(date, out time)) { Console.WriteLine("Not a valid Date. Try again"); ConsoleIO.PressAnyKey(); Console.Clear(); continue; } else { flag2 = false; } } OrderLookupResponse response = manager.LookupOrder(orderNum, time); if (response.Success)//if it successful then we can edit it { ConsoleIO.DisplayOrderDetails(response.Order); ConsoleIO.PressAnyKey(); Console.Clear(); AskName(response); ConsoleIO.PressAnyKey(); Console.Clear(); AskState(response); ConsoleIO.PressAnyKey(); Console.Clear(); AskProduct(response); ConsoleIO.PressAnyKey(); Console.Clear(); AskArea(response); ConsoleIO.PressAnyKey(); Console.Clear(); Console.WriteLine("Updated Order"); ConsoleIO.DisplayOrderDetails(response.Order); bool change = AskConfirmation(); if (change) { manager.EditOrder(response.Order); } else { Console.WriteLine("No Changes Will Be Made"); ConsoleIO.PressAnyKey(); Console.Clear(); } } else { Console.Clear(); Console.WriteLine(response.Message); ConsoleIO.PressAnyKey(); return; } //ConsoleIO.DisplayOrderDetails(response.Order); }
public void Execute() { AccountManager manager = AccountManagerFactory.Create(); Console.Clear(); Console.WriteLine("Display an Order"); Console.WriteLine($"{Menu.stars}"); string orderDate; // Validates Date and parses to DateTime do { // resets date Date.OrderDate = Convert.ToDateTime(Date.DATE_TIME_ORIGIN); try { Date.OrderDate = DateTime.Parse(ConsoleInput.ConsoleInput.GetStringFromUser(Date.DatePrompt)); } catch { Console.WriteLine("Date must be a legitimate date in the future."); } } while (Date.OrderDate.Date.ToString() == Date.DATE_TIME_ORIGIN); orderDate = Date.OrderDate.ToString(); // Sends response to the Data Layer to see if the file exists to be edited or deleted OrderLookupResponse displayListResponse = manager.DisplayOrder(orderDate); // Outputs what is returned from Data Layer ConsoleIO.DisplayOrderListDetails(displayListResponse.Order); string orderNumber = ConsoleInput.ConsoleInput.GetStringFromUser("Enter the order number of the order you would like to edit or delete: "); // Sends another response to edit a certain field or delete an order AddEditOrDeleteOrderResponse responseCheck = manager.EditOrDeleteOrderSelection(orderDate, orderNumber); if (responseCheck.Success) { Console.WriteLine($"1. {responseCheck.Order.CustomerName}"); Console.WriteLine($"2. {responseCheck.Order.State}"); Console.WriteLine($"3. {responseCheck.Order.ProductType}"); Console.WriteLine($"4. {responseCheck.Order.Area}"); Console.WriteLine("5. Delete Order"); //int editNumber = ConsoleInput.ConsoleInput.GetIntFromUser("Enter the item you would like to edit or hit 5 to delete an order: ", 1, _fiveForDelete); string editNumber = GetEditStringFromUser("Enter the item you would like to edit or hit 5 to delete an order: "); // Validates the user's responses and assigns them to the appropriate Order properties switch (editNumber) { case "1": do { responseCheck.Order.CustomerName = ConsoleInput.ConsoleInput.GetStringFromUser("Enter customer's name (a-z 0-9 , or . are excepted): "); } while (!(Regex.IsMatch(responseCheck.Order.CustomerName, @"^[a-zA-Z0-9., ]+$"))); break; case "2": do { responseCheck.Order.State = ConsoleInput.ConsoleInput.GetStringFromUser("Enter the state abbreviation (PA, OH, MI, or IN): ").ToUpper(); } while (!(responseCheck.Order.State == Taxes.statePA || responseCheck.Order.State == Taxes.stateOH || responseCheck.Order.State == Taxes.stateMI || responseCheck.Order.State == Taxes.stateIN)); break; case "3": do { responseCheck.Order.ProductType = ConsoleInput.ConsoleInput.GetStringFromUser("Enter a product ( Carpet, Laminate, Tile, or Wood ): "); } while (!(responseCheck.Order.ProductType.ToUpper() == Products.typeCarpet || responseCheck.Order.ProductType.ToUpper() == Products.typeLaminate || responseCheck.Order.ProductType.ToUpper() == Products.typeTile || responseCheck.Order.ProductType.ToUpper() == Products.typeWood)); break; case "4": responseCheck.Order.Area = ConsoleInput.ConsoleInput.GetDecimalFromUser("Enter your changes: ", Order.MIN_AREA, MAX_INT); break; case "5": responseCheck.Order.CustomerName = $"{responseCheck.Order.CustomerName} DELETE"; break; //Doesn't edit anything. case "": break; default: return; } // Displays what you are editing or deleting ConsoleIO.DisplayOrderDetails(responseCheck.Order); // Prompts you to confirm string response; do { response = ConsoleInput.ConsoleInput.GetStringFromUser("Would you like to continue with the changes above? (Yes or No) ").ToUpper(); } while (response != "YES" && response != "NO"); // If yes then send to the Data Layer to edit or delete if (response == "YES") { AddEditOrDeleteOrderResponse responseEdit = manager.EditOrDeleteOrder(responseCheck.Order); if (responseEdit.Success) { ConsoleIO.DisplayOrderDetails(responseEdit.Order); } else { Console.WriteLine("An error occurred: "); Console.WriteLine(responseEdit.Message); } } } else { Console.WriteLine("An error occurred: "); Console.WriteLine(responseCheck.Message); } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); }
public void Execute() { OrderManager orderManager = OrderManagerFactory.Create(); ProductManager productManager = ProductManagerFactory.Create(); TaxManager taxManager = TaxManagerFactory.Create(); Console.Clear(); Console.WriteLine("Place an order"); Console.WriteLine(ConsoleIO.LineBar); Console.WriteLine(); Console.WriteLine("Press any key to start your order."); Console.ReadKey(); Console.Clear(); Order newOrder = new Order(); newOrder.OrderDate = AddOrderCheck.GetDate("Enter a future order date (MMDDYYYY): "); newOrder.CustomerName = AddOrderCheck.GetName("Enter customer name: "); newOrder.State = AddOrderCheck.GetState("Enter your State location (ex. OH for Ohio): "); newOrder.ProductType = AddOrderCheck.GetProduct("Enter product you would like to order: "); newOrder.Area = decimal.Parse(AddOrderCheck.GetArea("Enter area amount you would like to order (minimum of 100sq ft): ")); var productLookup = productManager.ReturnProduct(newOrder.ProductType); newOrder.CostPerSquareFoot = productLookup.CostPerSquareFoot; newOrder.LaborCostPerSqareFoot = productLookup.LaborCostPerSqareFoot; var taxesLookup = taxManager.LoadTax(newOrder.State); newOrder.TaxRate = taxesLookup.TaxRate; newOrder.MaterialCost = newOrder.MaterialCostCalc(newOrder.Area, newOrder.CostPerSquareFoot); newOrder.LaborCost = newOrder.LaborCostCalc(newOrder.Area, newOrder.LaborCostPerSqareFoot); newOrder.Tax = newOrder.TaxCalc(newOrder.MaterialCost, newOrder.LaborCost, newOrder.TaxRate); newOrder.Total = newOrder.TotalCalc(newOrder.MaterialCost, newOrder.LaborCost, newOrder.Tax); AddOrderResponse response = orderManager.AddOrder(newOrder, newOrder.OrderDate); Console.Clear(); if (response.Success) { ConsoleIO.DisplayOrderDetails(response.NewOrder); bool keepLooping = true; do { Console.WriteLine(); Console.WriteLine("Would you like to save your new order? Y for Yes or N for No: "); string input = Console.ReadLine(); if (input.ToUpper() == "Y" || input.ToUpper() == "Yes") { Console.WriteLine(); Console.WriteLine("Your order has been placed."); keepLooping = false; } else if (input.ToUpper() == "N" || input.ToUpper() == "No") { orderManager.RemoveOrder(newOrder, newOrder.OrderDate, newOrder.OrderNumber); Console.WriteLine(); Console.WriteLine("Your order has been cancelled."); keepLooping = false; } else { Console.WriteLine(); Console.WriteLine("You pressed an incorrect key. Press enter to try again..."); Console.ReadKey(); keepLooping = true; } } while (keepLooping == true); } else { Console.WriteLine(); Console.WriteLine("An error occurred: "); Console.WriteLine(response.Message); } Console.WriteLine(); Console.WriteLine("Press any key to return to the main menu..."); Console.ReadKey(); }
public void Execute() { //bool invalidDate; //do //{ // invalidDate = true; ConsoleIO.Header("\t~Remove Order~"); DateTime orderDate = ConsoleIO.DateLookupPrompt(); FlooringManager flooringManager = FlooringManagerFactory.Create(orderDate); IOrderRepository orderRepo = flooringManager.orderRepository; IProductRepository productRepository = flooringManager.productRepository; ITaxRepository taxRepository = flooringManager.taxRepository; ConsoleIO.Header("\t~Remove Order~"); Dictionary <int, Order> orderDictionary = flooringManager.GetAllOrders(orderDate); //if (!orderRepo.FileExists()) //{ // //Console.WriteLine(); // //ConsoleIO.InvalidDate(); // ConsoleIO.TryAgain(); // Console.ReadKey(); //} //else if (orderRepo.FileExists()) { if (orderRepo.LastOrder() == true) { ConsoleIO.DisplayAllOrders(orderDictionary, false, true, orderDate); Console.WriteLine(); string input = ConsoleIO.YOrNMessage("remove"); if (input == "Y") { orderRepo.DeleteOrderFile(); Console.WriteLine(); ConsoleIO.OrderRemoved(0, true); ConsoleIO.KeyToContinue(); Console.ReadKey(); } else { Console.WriteLine(); ConsoleIO.ReturnMenu("removing"); ConsoleIO.KeyToContinue(); Console.ReadKey(); } } else { ConsoleIO.Header("\t~Remove Order~"); int orderNumber = ConsoleIO.GetIntFromUser(ConsoleIO.OrderLookup()); DisplaySingleResponse response = flooringManager.LookupOrder(orderNumber, orderDate); //if (response.Success) //{ ConsoleIO.DisplaySingleOrder(response.Order, true); Console.WriteLine(); string input = ConsoleIO.YOrNMessage("remove"); if (input == "Y") { while (orderRepo.RemoveOrder(response.Order.OrderNumber) == false) { ConsoleIO.InvalidOrder(); ConsoleIO.TryAgain(); } //{ // ConsoleIO.InvalidOrder(orderNumber.ToString()); // ConsoleIO.TryAgain(); //} while (orderRepo.RemoveOrder(orderNumber) == false); Console.WriteLine(); ConsoleIO.OrderRemoved(orderNumber, false); orderRepo.CloseRepo(response.Order); ConsoleIO.KeyToContinue(); Console.ReadKey(); } } //invalidDate = false; //} //else //{ // ConsoleIO.ErrorOccurred(); // Console.WriteLine(response.Message); //} } else { ConsoleIO.KeyToContinue(); Console.ReadKey(); } //} while (invalidDate); }
public void Execute() { ProductManager myProductManager = new ProductManager(); ConsoleIO.PrintAllProducts(myProductManager.GetAllProducts()); }
/// <summary> /// Internal rule initialization method. Looks for local rule file or download it from Mojang asset servers. /// </summary> private static void InitRules() { //Small default dictionnary of translation rules TranslationRules["chat.type.admin"] = "[%s: %s]"; TranslationRules["chat.type.announcement"] = "§d[%s] %s"; TranslationRules["chat.type.emote"] = " * %s %s"; TranslationRules["chat.type.text"] = "<%s> %s"; TranslationRules["multiplayer.player.joined"] = "§e%s joined the game."; TranslationRules["multiplayer.player.left"] = "§e%s left the game."; TranslationRules["commands.message.display.incoming"] = "§7%s whispers to you: %s"; TranslationRules["commands.message.display.outgoing"] = "§7You whisper to %s: %s"; //Language file in a subfolder, depending on the language setting if (!System.IO.Directory.Exists("lang")) { System.IO.Directory.CreateDirectory("lang"); } string Language_File = "lang" + (Program.isUsingMono ? '/' : '\\') + Settings.Language + ".lang"; //File not found? Try downloading language file from Mojang's servers? if (!System.IO.File.Exists(Language_File)) { ConsoleIO.WriteLineFormatted("§e[信息]§8正在从Mojang服务器下载 '" + Settings.Language + ".lang'"); try { string assets_index = DownloadString(Settings.TranslationsFile_Website_Index); string[] tmp = assets_index.Split(new string[] { "minecraft/lang/" + Settings.Language.ToLower() + ".json" }, StringSplitOptions.None); tmp = tmp[1].Split(new string[] { "hash\": \"" }, StringSplitOptions.None); string hash = tmp[1].Split('"')[0]; //Translations file identifier on Mojang's servers string translation_file_location = Settings.TranslationsFile_Website_Download + '/' + hash.Substring(0, 2) + '/' + hash; if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted("§e[信息]§8正在提交请求 " + translation_file_location); } StringBuilder stringBuilder = new StringBuilder(); foreach (KeyValuePair <string, Json.JSONData> entry in Json.ParseJson(DownloadString(translation_file_location)).Properties) { stringBuilder.Append(entry.Key + "=" + entry.Value.StringValue + Environment.NewLine); } System.IO.File.WriteAllText(Language_File, stringBuilder.ToString()); ConsoleIO.WriteLineFormatted("§e[信息]§8语言文件已保存至 '" + Language_File + '\''); } catch { ConsoleIO.WriteLineFormatted("§c[错误]§8下载语言文件发生错误."); } } //Download Failed? Defaulting to en_GB.lang if the game is installed if (!System.IO.File.Exists(Language_File) && //Try en_GB.lang System.IO.File.Exists(Settings.TranslationsFile_FromMCDir)) { Language_File = Settings.TranslationsFile_FromMCDir; ConsoleIO.WriteLineFormatted("§e[信息]§8已选择您Minecraft目录中的en_us.lang"); } //Load the external dictionnary of translation rules or display an error message if (System.IO.File.Exists(Language_File)) { string[] translations = System.IO.File.ReadAllLines(Language_File); foreach (string line in translations) { if (line.Length > 0) { string[] splitted = line.Split('='); if (splitted.Length == 2) { TranslationRules[splitted[0]] = splitted[1]; } } } if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted("§e[信息]§8语言文件已加载."); } } else //No external dictionnary found. { ConsoleIO.WriteLineFormatted("§c[错误]§8语言 文件未找到: \"" + Language_File + "\""); } }
public void Execute() { InputRules inputManager = new InputRules(); OrderManager manager = OrderManagerFactory.Create(); TaxStateManager stateManager = TaxStateManagerFactory.Create(); ProductManager productManager = ProductManagerFactory.Create(); Order order = new Order(); DateTime orderDate; string stateInput, productInput, tempAreaInput; Console.Clear(); Console.WriteLine("Edit an Order"); Console.WriteLine("--------------------"); //Get order date file Console.WriteLine("Please enter the Order Date you would like to edit"); while (!DateTime.TryParse(Console.ReadLine(), out orderDate)) { Console.WriteLine("That is not a valid format, please try again"); } //display all orders OrderLookupResponse fileResponse = manager.AllOrderLookup(orderDate); if (fileResponse.Success) { foreach (Order entry in fileResponse.Orders) { ConsoleIO.DisplayOrder(entry); } } Console.WriteLine(); //get order number and make edits int orderNumberInput; Console.WriteLine("Enter the Order Number you'd like to edit:"); while (!int.TryParse(Console.ReadLine(), out orderNumberInput)) { Console.WriteLine("That is not a valid input. Try again"); } OrderLookupResponse response = manager.OrderLookup(orderDate, orderNumberInput); if (response.Success) { ConsoleIO.DisplayOrder(response.Order); order = response.Order; Console.WriteLine(); Console.WriteLine("Please enter new values, entering nothing will keep current value."); //Edit Name NameCheckResponse nameResponse = new NameCheckResponse(); Console.Write("Enter the Customer's Name: "); string nameInput = Console.ReadLine().Replace(',', '|').Trim(); nameResponse = inputManager.NameCheck(nameInput); if (nameInput != "") { while (!nameResponse.Success) { nameResponse = inputManager.NameCheck(nameInput); if (!nameResponse.Success) { Console.WriteLine(nameResponse.Message); Console.Write("Name: "); nameInput = Console.ReadLine(); } } order.CustomerName = nameInput; } Console.Clear(); //Display States Console.WriteLine("These are the states in our system, please enter which state."); foreach (TaxState entry in stateManager.GetTaxStates()) { Console.WriteLine(entry.StateName); } //Edit State TaxStateLookupResponse stateResponse = new TaxStateLookupResponse(); StateInputCheckResponse stateInputResponse = new StateInputCheckResponse(); Console.WriteLine("Please enter new values, entering nothing will keep current value."); Console.Write("State: "); stateInput = Console.ReadLine(); stateInputResponse = inputManager.StateCheck(stateInput); if (stateInputResponse.Success) { stateResponse.Success = false; while (!stateResponse.Success) { stateResponse = stateManager.FindTaxState(stateInput); if (!stateResponse.Success) { Console.WriteLine(stateResponse.Message); Console.Write("State: "); stateInput = Console.ReadLine(); } } order.State = stateInput; } Console.Clear(); //Display Products Console.WriteLine("These are the materials availbale to choose from:"); foreach (Product entry in productManager.GetProducts()) { Console.WriteLine(string.Format("{0}, Labor Cost: {1}, Material Cost: {2}", entry.ProductType, entry.LaborCostPerSquareFoot, entry.CostPerSquareFoot)); } //Edit Product ProductLookupResposnse productResponse = new ProductLookupResposnse(); ProductInputCheckResponse productInputResponse = new ProductInputCheckResponse(); Console.WriteLine("Please enter new values, entering nothing will keep current value."); Console.Write("Product Type: "); productInput = Console.ReadLine(); productInputResponse = inputManager.ProductCheck(productInput); if (productInputResponse.Success) { productResponse.Success = false; while (!productResponse.Success) { productResponse = productManager.FindProduct(productInput); if (!productResponse.Success) { Console.WriteLine(productResponse.Message); Console.Write("Product Type: "); productInput = Console.ReadLine(); } } order.ProductType = productInput; } Console.Clear(); //Edit Area AreaCheckResponse areaResponse = new AreaCheckResponse(); Console.Write("Area: "); decimal areaInput; tempAreaInput = Console.ReadLine(); if (tempAreaInput != "") { areaResponse.Success = false; while (!decimal.TryParse(tempAreaInput, out areaInput)) { Console.WriteLine("That is not a valid input."); Console.Write("Area: "); tempAreaInput = Console.ReadLine(); } while (!areaResponse.Success) { areaResponse = inputManager.AreaCheck(areaInput); Console.WriteLine(areaResponse.Message); } order.Area = areaInput; } Console.Clear(); if (stateInput == "" && productInput == "" && tempAreaInput == "") { order = OrderCreation.EditedOrder(order.OrderDate, order.OrderNumber, order.CustomerName, order.State, order.StateAbv, order.TaxRate, order.ProductType, order.Area, order.CostPerSqaureFoot, order.LaborCostPerSquareFoot, order.MaterialCost, order.LaborCost, order.Tax, order.Total); } else { order = OrderCreation.CreateOrder(order.OrderDate, order.OrderNumber, order.CustomerName, order.State, order.ProductType, order.Area); } ConsoleIO.DisplayOrder(order); Console.WriteLine(); string answer = null; while (answer == null) { Console.WriteLine("Do you want to save this order? (Y/N)"); answer = Console.ReadLine().ToUpper(); switch (answer) { case "Y": manager.UpdateOrder(order); Console.WriteLine("Order Saved"); break; case "N": Console.WriteLine("Order Not Saved"); break; default: Console.WriteLine("That is not a valid input, try again"); answer = null; break; } } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); return; } else { Console.WriteLine("That Order does not currently exist in our system"); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); return; } }
public void Execute() { Console.Clear(); IFileOrderRepo fileOrderRepo; Orders newOrder = new Orders(); Console.WriteLine("Edit Order Form"); Console.WriteLine("--------------------------"); Console.WriteLine("Enter a date: "); string userInputDate = Console.ReadLine(); if (string.IsNullOrEmpty(userInputDate)) { Console.WriteLine("Error: User input was invalid...Hit any key to return to menu..."); Console.ReadKey(); return; } var path = ConsoleIO.UserDateValidateToString(userInputDate); OrderManager manager = OrderManagerFactory.Create(path); OrderLookupResponse respose = manager.LookupOrders(path); if (respose.Success) { ConsoleIO.DisplayOrderDetails(respose.orders, path); } else { Console.WriteLine("An error has occurred: "); Console.WriteLine(respose.Message); } int orderNumber = ConsoleIO.StringToInt("Which order would you like to edit? (Choose order by it's ORDER NUMBER): "); Console.Clear(); fileOrderRepo = new FileOrderRepo(path); fileOrderRepo.LoadOrder(); Orders oldOrder = fileOrderRepo.ReadByOrderNumber(orderNumber); ConsoleIO.DisplayOrderDetails(new List <Orders> { oldOrder }, path); string newName = ConsoleIO.ValidateCompanyName("Enter new NAME or hit enter to continue: "); if (string.IsNullOrEmpty(newName)) { newOrder.CustomerName = oldOrder.CustomerName; } else { newOrder.CustomerName = newName; } ConsoleIO.DisplayStateAbbreviation(FileTaxRepo.LoadTaxes()); Console.WriteLine("Enter new STATE or hit enter to continue:"); Console.WriteLine("REMINDER: States MUST be abbreviated!!"); string newState = Console.ReadLine(); if (string.IsNullOrEmpty(newState)) { newOrder.State = oldOrder.State; } else { newOrder.State = newState; } ConsoleIO.DisplayProducts(FileProductsRepo.LoadProducts()); Console.WriteLine("Enter new PRODUCT TYPE or hit enter to continue:"); string newProduct = Console.ReadLine(); if (string.IsNullOrEmpty(newProduct)) { newOrder.ProductType = oldOrder.ProductType; } else { newOrder.ProductType = newProduct; } Console.WriteLine("Enter new AREA or hit enter to continue:"); Console.WriteLine("REMINDER: Area MUST be at minimum 100"); string newArea = Console.ReadLine(); if (string.IsNullOrEmpty(newArea)) { newOrder.Area = oldOrder.Area; } else { newOrder.Area = ConsoleIO.StringToDecimal(newArea); } DateTime.TryParse(userInputDate, CultureInfo.GetCultureInfo("en-us"), DateTimeStyles.NoCurrentDateDefault, out DateTime dateTime); NewOrderResponse response = new NewOrderResponse(); response = NewOrderRules.NewOrder(dateTime, newOrder.State, newOrder.ProductType); if (response.Success == false) { Console.WriteLine(response.Message); Console.ReadKey(); } else { newOrder.TaxRate = response.Tax; newOrder.CostPerSquareFoot = response.CostPerSquareFoot; newOrder.LaborCostPerSquareFoot = response.LaborCostPerSquareFoot; newOrder.OrderNumber = response.OrderNumber; Console.Clear(); Console.WriteLine("Summary"); Console.WriteLine("-------------------------------------------------------------"); Console.WriteLine("OLD ORDER"); Console.WriteLine("*************************************************************"); ConsoleIO.DisplayOrderDetails(new List <Orders> { oldOrder }, path); Console.WriteLine("*************************************************************"); Console.WriteLine("NEW ORDER"); Console.WriteLine("-------------------------------------------------------------"); ConsoleIO.DisplayOrderDetails(new List <Orders> { newOrder }, path); Console.WriteLine("-------------------------------------------------------------"); if (ConsoleIO.Exit("Do you want to SAVE edited order? [Y/N]") == false) { return; } else { fileOrderRepo.Delete(oldOrder.OrderNumber, oldOrder); fileOrderRepo.Create(newOrder); } } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); }
private static void ShowMainMenu() { try { ushort delay = 3000; byte attemptCount = 0; IOperationType selectedOperation = null; StringBuilder attemptStr = new StringBuilder(); ConsoleKeyInfo keyInfo = default(ConsoleKeyInfo); string mainMemu = Properties.Settings.Default.MainMenu; int consoleWindowWidth = Console.WindowWidth, consoleWindowHeight = Console.WindowHeight; do { //Resize console window size to default width and height ConsoleIO.ResizeConsoleWindow(consoleWindowWidth, consoleWindowHeight); attemptCount = 0; attemptStr.Clear(); do { if (attemptCount < 5) { Console.Clear(); ConsoleIO.WriteColorTextNewLine(string.Format(mainMemu, "\t", "\n", ConsoleIO.ConsoleRowSeparator)); if (attemptCount > 0) { ConsoleIO.WriteColorTextNewLine("Invalid input data!", ConsoleColor.Red); ConsoleIO.WriteColorText("Attempt count: "); ConsoleIO.WriteColorTextNewLine(attemptCount.ToString(), ConsoleColor.Red); ConsoleIO.WriteColorTextNewLine(string.Format("Entered keys: {0}{1}{2}", attemptStr, "\n", ConsoleIO.ConsoleRowSeparator)); } else { ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator); } keyInfo = Console.ReadKey(); if (keyInfo.Key == ConsoleKey.Q) { return; } selectedOperation = OperationFactory.GetSelectedOperation(keyInfo.Key); if (selectedOperation == default(IOperationType)) { Console.Beep(); } attemptStr.AppendFormat((attemptCount > 0 ? ", " : string.Empty) + "'{0}'", keyInfo.KeyChar); attemptCount++; } else { ConsoleIO.WriteColorTextNewLine("\nIt looks like that you don't know what are you doing or maybe you are an idiot!", ConsoleColor.Red); Console.ReadKey(); return; } } while (selectedOperation == default(IOperationType)); ConsoleIO.WriteColorTextNewLine(string.Format("\nNice choice! \nYou'll be redirected to the {0} after '{1}'sec", selectedOperation.ToString(), delay / 1000), ConsoleColor.Green); System.Threading.Thread.Sleep(delay); } while (selectedOperation.RunAndContinue()); } catch (Exception ex) { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }
/// <summary> /// Internal rule initialization method. Looks for local rule file or download it from Mojang asset servers. /// </summary> private static void InitRules() { //Small default dictionnary of translation rules TranslationRules["chat.type.admin"] = "[%s: %s]"; TranslationRules["chat.type.announcement"] = "§d[%s] %s"; TranslationRules["chat.type.emote"] = " * %s %s"; TranslationRules["chat.type.text"] = "<%s> %s"; TranslationRules["multiplayer.player.joined"] = "§e%s joined the game."; TranslationRules["multiplayer.player.left"] = "§e%s left the game."; TranslationRules["commands.message.display.incoming"] = "§7%s whispers to you: %s"; TranslationRules["commands.message.display.outgoing"] = "§7You whisper to %s: %s"; //Language file in a subfolder, depending on the language setting if (!System.IO.Directory.Exists("lang")) { System.IO.Directory.CreateDirectory("lang"); } string Language_File = "lang" + (Program.isUsingMono ? '/' : '\\') + Settings.Language + ".lang"; //File not found? Try downloading language file from Mojang's servers? if (!System.IO.File.Exists(Language_File)) { ConsoleIO.WriteLineFormatted("§8Downloading '" + Settings.Language + ".lang' from Mojang servers..."); try { string assets_index = DownloadString(Settings.TranslationsFile_Website_Index); string[] tmp = assets_index.Split(new string[] { "minecraft/lang/" + Settings.Language + ".lang" }, StringSplitOptions.None); tmp = tmp[1].Split(new string[] { "hash\": \"" }, StringSplitOptions.None); string hash = tmp[1].Split('"')[0]; //Translations file identifier on Mojang's servers System.IO.File.WriteAllText(Language_File, DownloadString(Settings.TranslationsFile_Website_Download + '/' + hash.Substring(0, 2) + '/' + hash)); ConsoleIO.WriteLineFormatted("§8Done. File saved as '" + Language_File + '\''); } catch { ConsoleIO.WriteLineFormatted("§8Failed to download the file."); } } //Download Failed? Defaulting to en_GB.lang if the game is installed if (!System.IO.File.Exists(Language_File) && //Try en_GB.lang System.IO.File.Exists(Settings.TranslationsFile_FromMCDir)) { Language_File = Settings.TranslationsFile_FromMCDir; ConsoleIO.WriteLineFormatted("§8Defaulting to en_GB.lang from your Minecraft directory."); } //Load the external dictionnary of translation rules or display an error message if (System.IO.File.Exists(Language_File)) { string[] translations = System.IO.File.ReadAllLines(Language_File); foreach (string line in translations) { if (line.Length > 0) { string[] splitted = line.Split('='); if (splitted.Length == 2) { TranslationRules[splitted[0]] = splitted[1]; } } } if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted("§8Translations file loaded."); } } else //No external dictionnary found. { ConsoleIO.WriteLineFormatted("§8Translations file not found: \"" + Language_File + "\"" + "\nSome messages won't be properly printed without this file."); } }
public void onTelegramMessage(string chat, string Suser, string text, bool mention, int usermention) { int user = int.Parse(Suser); if (!chat.Equals(Suser)) { if (text.Equals("ajuda")) { response.sendHelp(); } if (Regex.IsMatch(text, "^ajuda ([1-9])$", RegexOptions.IgnoreCase)) { response.sendHelp(Regex.Match(text, "^ajuda ([1-9])$", RegexOptions.IgnoreCase).Groups[1].Value); } if (text.Equals("changelog")) { response.sendChangelog(); } if (text.Equals("status")) { Telegram.SendTypingStatus(); response.sendStatus(vars.loggedIn); } if (Regex.IsMatch(text, "^add (.+)", RegexOptions.IgnoreCase)) { Match nick = Regex.Match(text, "^add (.+)", RegexOptions.IgnoreCase); Telegram.SendTypingStatus(); if (nick.Groups[1].Value.Contains(" ")) { response.sendNickSpace(); return; } List <Account> accs = data.GetAccountList(user); foreach (Account acc in accs) { if (acc.getNick().ToLower().Equals(nick.Groups[1].Value.ToLower())) { response.sendAccountAlreadyAdded(); return; } } data.addNewAccount(user, nick.Groups[1].Value); ConsoleIO.WriteLineFormatted("§d[Banco de dados] §2Adicionando o nick " + nick.Groups[1].Value + " id(" + user + ") Ao banco de dados!"); } /*if (Regex.IsMatch(text, "^tadd ([0-9]+) (.+)")) * { * Match nick = Regex.Match(text, "^tadd ([0-9]+) (.+)"); * data.addTreasure(int.Parse(nick.Groups[1].Value), nick.Groups[2].Value); * }*/ if (Regex.IsMatch(text, "^notificar (.+) (.+)", RegexOptions.IgnoreCase)) { Match notify = Regex.Match(text, "^notificar (.+) (.+)", RegexOptions.IgnoreCase); data.addNotification(notify.Groups[1].Value, notify.Groups[2].Value); } if (text.ToLower().Equals("tesouros")) { response.sendTreasures(user); } if (text.ToLower().Equals("link")) { Telegram.SendHtmlMessage(vars.emjinfo + " Link do grupo:%0Ahttps://t.me/joinchat/IcsdwkZ2PD3HdWCJCunNGQ"); } if (text.ToLower().Equals("mensagens")) { response.sendNotifications(user); } if (text.ToLower().Equals("limparmensagens")) { response.sendNotificationsClear(user); } if (text.ToLower().Equals("limpartesouros")) { response.sendTreasuresClear(user); } if (Regex.IsMatch(text, "^del (.+)", RegexOptions.IgnoreCase)) { Match nick = Regex.Match(text, "^del (.+)", RegexOptions.IgnoreCase); Telegram.SendTypingStatus(); if (nick.Groups[1].Value.Contains(" ")) { response.sendNickSpace(); return; } data.removeAccount(user, nick.Groups[1].Value); ConsoleIO.WriteLineFormatted("§d[Banco de dados] §2Removendo o nick " + nick.Groups[1].Value + " id(" + user + ") Do banco de dados!"); } if (Regex.IsMatch(text, "^cargo (.+) (user|moderador|admin)$", RegexOptions.IgnoreCase)) { Match match = Regex.Match(text, "^cargo (.+) (user|moderador|admin)$", RegexOptions.IgnoreCase); string name = match.Groups[1].Value; string cargo = match.Groups[2].Value; bool ok = false; Telegram.SendTypingStatus(); if (!mention) { Telegram.SendHtmlMessage(vars.emjerror + " Mencione alguem para usar este comando!"); } if (Telegram.isAdmin(user)) { Admin adm = Telegram.getAdmin(user); if (adm.canPromoteMembers()) { ok = Telegram.promoteUser(usermention, cargo); } else { Telegram.SendHtmlMessage(vars.emjerror + " Desculpe, você nao pode alterar cargos!"); } } else { Telegram.SendHtmlMessage(vars.emjerror + " Apenas Admins podem usar este comando!"); } if (ok) { Telegram.SendHtmlMessage(vars.emjok + " Cargo de " + name + " Definido para " + cargo); } else { Telegram.SendHtmlMessage(vars.emjerror + " Erro ao processar a solicitação"); } } if (Regex.IsMatch(text, "^contas (.+)$", RegexOptions.IgnoreCase)) { Match match = Regex.Match(text, "^contas (.+)$", RegexOptions.IgnoreCase); string name = match.Groups[1].Value; bool ok = false; Telegram.SendTypingStatus(); if (!mention) { Telegram.SendHtmlMessage(vars.emjerror + " Mencione alguem para usar este comando!"); return; } if (Telegram.isAdmin(user)) { Admin adm = Telegram.getAdmin(user); if (adm.canPromoteMembers()) { response.sendNicknames(usermention); } else { Telegram.SendHtmlMessage(vars.emjerror + " Apenas Admins podem usar este comando!"); } } else { Telegram.SendHtmlMessage(vars.emjerror + " Apenas Admins podem usar este comando!"); } } if (Regex.IsMatch(text, "^protect$", RegexOptions.IgnoreCase)) { response.sendProtectedNicknames(user); } if (Regex.IsMatch(text, "^protect (.+) (on|off)$", RegexOptions.IgnoreCase)) { Match match = Regex.Match(text, "^protect (.+) (on|off)$", RegexOptions.IgnoreCase); string name = match.Groups[1].Value; bool protect = match.Groups[2].Value.ToLower().Equals("on"); Telegram.SendTypingStatus(); Telegram.data.Protect(name, true, protect, user); } if (Regex.IsMatch(text, "^reconectar$", RegexOptions.IgnoreCase)) { Telegram.SendTypingStatus(); if (Telegram.isAdmin(user)) { Admin adm = Telegram.getAdmin(user); if (adm.canPromoteMembers()) { Program.Client.SendText("/ativar reiniciandohtbot"); Program.Restart(); Telegram.SendHtmlMessage(vars.emjok + " Reconectando ao servidor!"); } else { Telegram.SendHtmlMessage(vars.emjerror + " Desculpe, você não tem permissão para isso!"); } } else { Telegram.SendHtmlMessage(vars.emjerror + " Apenas Admins podem usar este comando!"); } } if (Regex.IsMatch(text, "^reiniciar$", RegexOptions.IgnoreCase)) { Telegram.SendTypingStatus(); if (Telegram.isAdmin(user)) { Admin adm = Telegram.getAdmin(user); if (adm.canPromoteMembers()) { new Thread(new ThreadStart(delegate { Telegram.SendHtmlMessage(vars.emjok + " Reiniciando o bot!"); Program.Client.SendText("/ativar reiniciandohtbot"); Thread.Sleep(2000); Environment.Exit(0); })).Start(); } else { Telegram.SendHtmlMessage(vars.emjerror + " Desculpe, você não tem permissão para isso!"); } } else { Telegram.SendHtmlMessage(vars.emjerror + " Apenas Admins podem usar este comando!"); } } if (text.ToLower().Equals("contas")) { response.sendNicknames(user); } if (vars.loggedIn) { if (Regex.IsMatch(text, "^online ([a-zA-Z0-9-_]+)$", RegexOptions.IgnoreCase)) { Match nick = Regex.Match(text, "^online ([a-zA-Z0-9-_]+)$", RegexOptions.IgnoreCase); bool isOnline = false; Telegram.SendTypingStatus(); foreach (string player in Program.Client.GetOnlinePlayers()) { if (player.ToLower().Equals(nick.Groups[1].Value.ToLower())) { isOnline = true; response.sendOnline(isOnline, player); } } if (!isOnline) { foreach (string player in Program.Client.GetOnlinePlayers()) { if (player.ToLower().Contains(nick.Groups[1].Value.ToLower())) { isOnline = true; response.sendOtherOnline(player); break; } } if (!isOnline) { response.sendOnline(isOnline, nick.Groups[1].Value); } } } if (Regex.IsMatch(text, "^money (.+)", RegexOptions.IgnoreCase)) { Match nick = Regex.Match(text, "^money (.+)", RegexOptions.IgnoreCase); Telegram.SendTypingStatus(); if (nick.Groups[1].Value.Contains(" ")) { if (nick.Groups[1].Value.Contains("rank ")) { vars.checkMoneyRank = true; Program.Client.SendText("/money " + nick.Groups[1].Value); return; } else { response.sendNickSpace(); return; } } if (nick.Groups[1].Value.ToLower().Equals("top")) { vars.tmoney = true; Program.Client.SendText("/money " + nick.Groups[1].Value); return; } vars.tmoney = true; Program.Client.SendText("/money @" + nick.Groups[1].Value); } if (Regex.IsMatch(text, "^inspect (.+)", RegexOptions.IgnoreCase)) { vars.resetVars(); Match nick = Regex.Match(text, "^inspect (.+)", RegexOptions.IgnoreCase); Telegram.SendTypingStatus(); vars.atualUser = user; if (nick.Groups[1].Value.Contains(" ")) { response.sendNickSpace(); return; } vars.checkSkills = true; Program.Client.SendText("/inspect " + nick.Groups[1].Value); } if (Regex.IsMatch(text, "^mctop (.+)", RegexOptions.IgnoreCase)) { Match skill = Regex.Match(text, "^mctop (.+)", RegexOptions.IgnoreCase); Telegram.SendTypingStatus(); vars.checkmctop = true; Program.Client.SendText("/mctop " + skill.Groups[1].Value); vars.mctopskill = skill.Groups[1].Value; } if (Regex.IsMatch(text, "^mctop$", RegexOptions.IgnoreCase)) { Match skill = Regex.Match(text, "^mctop$", RegexOptions.IgnoreCase); Telegram.SendTypingStatus(); vars.checkmctop = true; Program.Client.SendText("/mctop"); vars.mctopskill = "Geral"; } if (Regex.IsMatch(text, "^mcrank (.+)", RegexOptions.IgnoreCase)) { Match check = Regex.Match(text, "^mcrank (.+)", RegexOptions.IgnoreCase); Telegram.SendTypingStatus(); vars.checkmcrank = true; Program.Client.SendText("/mcrank " + check.Groups[1].Value); vars.atualNick = check.Groups[1].Value; } if (Regex.IsMatch(text, "^(Acrobacia|Reparaçao|Machado|Arqueiro|Espadas|Domar|Desarmado|Escavaçao|Pescador|Herbalismo|Mineraçao|Lenhador)$", RegexOptions.IgnoreCase)) { Match skill = Regex.Match(text, "^(Acrobacia|Reparaçao|Machado|Arqueiro|Espadas|Domar|Desarmado|Escavaçao|Pescador|Herbalismo|Mineraçao|Lenhador)$", RegexOptions.IgnoreCase); string Skill = skill.Groups[1].Value; vars.resetVars(); List <Account> accounts = Telegram.data.GetAccountList(user); vars.checkingSkill = Skill; vars.singleSkillCheck = true; vars.atualUser = user; vars.multipleskillscheck = accounts.Count; vars.checkedNicksCount = 0; Telegram.SendTypingStatus(); vars.skills.Add("Skill: <code>" + vars.checkingSkill + "</code> :%0A════════════════════%0A"); if (accounts.Count > 0) { foreach (Account account in accounts) { string acc = account.getNick(); wait(500); Program.Client.SendText("/inspect " + acc); wait(500); } } else { Telegram.SendHtmlMessage(vars.emjerror + " Antes de usar esse comando %0AUse /add <code>nick</code> para adicionar suas contas!"); } } if (Regex.IsMatch(text, "^inspect$", RegexOptions.IgnoreCase)) { Telegram.SendTypingStatus(); vars.resetVars(); vars.checkMultipleSkills = true; vars.atualUser = user; List <Account> accounts = Telegram.data.GetAccountList(user); vars.multipleskillscheck = accounts.Count; vars.checkedNicksCount = 0; if (Telegram.data.getTimestamp() < 1558148400) { if (accounts.Count > 0) { foreach (Account account in accounts) { string acc = account.getNick(); wait(500); Program.Client.SendText("/inspect " + acc); wait(500); } } else { Telegram.SendHtmlMessage(vars.emjerror + " Antes de usar esse comando %0AUse /add <code>nick</code> para adicionar suas contas!"); } } else { Telegram.SendHtmlMessage(vars.emjerror + " Este comando está obsoleto e foi descontinuado!%0AComo alternativa teste /nomedaskill%0AExemplo: /pescador"); } } if (Regex.IsMatch(text, "^money$", RegexOptions.IgnoreCase)) { Telegram.SendTypingStatus(); vars.checkMultipleMoney = true; List <Account> accounts = Telegram.data.GetAccountList(user); vars.multiplemoneycheck = accounts.Count; vars.checkedmoneycount = 0; if (accounts.Count > 0) { foreach (Account account in accounts) { string acc = account.getNick(); wait(500); Program.Client.SendText("/money @" + acc); wait(500); } } else { Telegram.SendHtmlMessage(vars.emjerror + " Antes de usar esse comando %0AUse /add <code>nick</code> para adicionar suas contas!"); } } if (Regex.IsMatch(text, "^online$", RegexOptions.IgnoreCase)) { Telegram.SendTypingStatus(); response.sendOnlineNicknames(user); } if (Regex.IsMatch(text, "^verificar (.+)$", RegexOptions.IgnoreCase)) { Match match = Regex.Match(text, "^verificar (.+)$", RegexOptions.IgnoreCase); string nick = match.Groups[1].Value; List <Account> accounts = Telegram.data.GetAccountList(user); Telegram.SendTypingStatus(); if (accounts.Count > 0) { bool found = false; string acc = ""; bool verifyed = false; int Token = 0; foreach (Account account in accounts) { if (account.getNick().ToLower().Equals(nick.ToLower())) { found = true; acc = account.getNick(); verifyed = account.getVerify(); Token = account.getToken(); break; } } if (!found) { Telegram.SendHtmlMessage(vars.emjerror + " Conta nao encontrada!"); return; } if (verifyed) { Telegram.SendHtmlMessage(vars.emjerror + " A conta já estava verificada!"); return; } if ((found) && (!verifyed)) { if (Telegram.SendPrivateMessage(user, vars.emjok + " Para verificar sua conta " + nick + ", envie um tell <b>dela</b>%0AAssim: <code>/tell htbot verificar " + Token + "</code>", "Verificação de conta", true)) { Telegram.SendHtmlMessage(vars.emjok + " Te enviei uma mensagem privada.%0AVerifique-a para confirmar a posse da sua conta!"); } } } else { Telegram.SendHtmlMessage(vars.emjerror + " Antes de usar esse comando %0AUse /add <code>nick</code> para adicionar suas contas!"); } } if (Regex.IsMatch(text, "^tell ([A-z0-9_-]{1,16}) (.+)$", RegexOptions.IgnoreCase)) { Match tell = Regex.Match(text, "^tell ([A-z0-9_-]{1,16}) (.+)$", RegexOptions.IgnoreCase); string nick = tell.Groups[1].Value; string msg = tell.Groups[2].Value; List <Account> accounts = Telegram.data.GetAccountList(user); Telegram.SendTypingStatus(); if (accounts.Count > 0) { bool found = false; bool verifyed = false; int Token = 0; bool isOnline = false; foreach (var player in Program.Client.GetOnlinePlayers()) { if (player.ToLower().Equals(nick)) { isOnline = true; } } foreach (Account account in accounts) { if (account.getNick().ToLower().Equals(nick.ToLower())) { found = true; verifyed = account.getVerify(); Token = account.getToken(); break; } } if (!found) { Telegram.SendHtmlMessage(vars.emjerror + " Conta nao encontrada!"); return; } if (!verifyed) { Telegram.SendHtmlMessage(vars.emjerror + "Desculpe, Você não tem permissão pra isso!%0AEssa conta é sua? " + vars.emjthinking); return; } if (!isOnline) { Telegram.SendHtmlMessage(vars.emjerror + " Conta Offline!"); return; } Program.Client.SendText("/tell " + nick + " 0 " + Token + " " + msg); Telegram.data.ResponseLimit(Token, true); Telegram.SendHtmlMessage(vars.emjok + " Mensagem enviada!"); } else { Telegram.SendHtmlMessage(vars.emjerror + " Antes de usar esse comando %0AUse /add <code>nick</code> para adicionar suas contas!"); } } if (text.ToLower().Equals("wm")) { vars.sendWM = true; Program.Client.SendText("/wm"); } } else { } } else { if (Regex.IsMatch(text, "^tell ([A-z0-9_-]{1,16}) (.+)$", RegexOptions.IgnoreCase)) { Match tell = Regex.Match(text, "^tell ([A-z0-9_-]{1,16}) (.+)$", RegexOptions.IgnoreCase); string nick = tell.Groups[1].Value; string msg = tell.Groups[2].Value; List <Account> accounts = Telegram.data.GetAccountList(user); Telegram.SendTypingStatus(user.ToString()); if (accounts.Count > 0) { bool found = false; bool verifyed = false; int Token = 0; bool isOnline = false; foreach (var player in Program.Client.GetOnlinePlayers()) { if (player.ToLower().Equals(nick)) { isOnline = true; } } foreach (Account account in accounts) { if (account.getNick().ToLower().Equals(nick.ToLower())) { found = true; verifyed = account.getVerify(); Token = account.getToken(); break; } } if (!found) { Telegram.SendPrivateMessage(user, vars.emjerror + " Conta nao encontrada!"); return; } if (!verifyed) { Telegram.SendPrivateMessage(user, vars.emjerror + "Desculpe, Você não tem permissão pra isso!%0AEssa conta é sua? " + vars.emjthinking); return; } if (!isOnline) { Telegram.SendPrivateMessage(user, vars.emjerror + " Conta Offline!"); return; } Program.Client.SendText("/tell " + nick + " 1 " + Token + " " + msg); Telegram.data.ResponseLimit(Token, true); Telegram.SendPrivateMessage(user, vars.emjok + " Mensagem enviada!"); } else { Telegram.SendPrivateMessage(user, vars.emjerror + " Antes de usar esse comando %0AUse /add <code>nick</code> para adicionar suas contas!"); } } else if (text.ToLower().Equals("start")) { Telegram.SendPrivateMessage(user, vars.emjok + " Olá, se você veio aqui pela verificação de conta%0APode voltar ao grupo e concluir a verificação%0AVocê tbm pode me mandar o comando <b>/tell <nick> <mensagem></b> por aqui"); } else { Telegram.SendPrivateMessage(user, vars.emjerror + " Por favor, use o bot no grupo!"); } } }
/// <summary> /// Manual HTTPS request since we must directly use a TcpClient because of the proxy. /// This method connects to the server, enables SSL, do the request and read the response. /// </summary> /// <param name="headers">Request headers and optional body (POST)</param> /// <param name="host">Host to connect to</param> /// <param name="result">Request result</param> /// <returns>HTTP Status code</returns> private static int DoHTTPSRequest(List <string> headers, string host, ref string result) { string postResult = null; int statusCode = 520; Exception exception = null; AutoTimeout.Perform(() => { try { if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted(Translations.Get("debug.request", host)); } TcpClient client = ProxyHandler.newTcpClient(host, 443, true); SslStream stream = new SslStream(client.GetStream()); stream.AuthenticateAsClient(host); if (Settings.DebugMessages) { foreach (string line in headers) { ConsoleIO.WriteLineFormatted("§8> " + line); } } stream.Write(Encoding.ASCII.GetBytes(String.Join("\r\n", headers.ToArray()))); System.IO.StreamReader sr = new System.IO.StreamReader(stream); string raw_result = sr.ReadToEnd(); if (Settings.DebugMessages) { ConsoleIO.WriteLine(""); foreach (string line in raw_result.Split('\n')) { ConsoleIO.WriteLineFormatted("§8< " + line); } } if (raw_result.StartsWith("HTTP/1.1")) { postResult = raw_result.Substring(raw_result.IndexOf("\r\n\r\n") + 4); statusCode = Settings.str2int(raw_result.Split(' ')[1]); } else { statusCode = 520; //Web server is returning an unknown error } } catch (Exception e) { if (!(e is System.Threading.ThreadAbortException)) { exception = e; } } }, TimeSpan.FromSeconds(30)); result = postResult; if (exception != null) { throw exception; } return(statusCode); }
public void Execute() { Console.Clear(); Console.WriteLine("Adding an order"); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~"); DateTime date; Console.WriteLine("When do you want it delived? Example 03/01/2020: "); string input = Console.ReadLine(); DateTime.TryParse(input, out date); while (date <= DateTime.Now) { Console.WriteLine("Order date needs to be a future date"); Console.WriteLine("Please enter a valid date."); input = Console.ReadLine(); DateTime.TryParse(input, out date); } Console.WriteLine("Please enter your name"); string CustomerName = Console.ReadLine(); Console.WriteLine("What state would you like the service for? We service Ohio, Pennsylvania, Michigan, and Indiana"); string state = Console.ReadLine().ToLower(); while (state != "ohio" && state != "pennsylvania" && state != "michigan" && state != "indiana") { Console.WriteLine("Sorry we do not service that state"); Console.WriteLine("please enter a valid state. We service Ohio, Pennsylvania, Michigan, and Indiana"); state = Console.ReadLine().ToLower(); } Console.WriteLine("What product type are you looking for? We offer Carpet, Laminate, Tile, Wood"); string productType = Console.ReadLine().ToLower(); while (productType != "carpet" && productType != "laminate" && productType != "tile" && productType != "wood") { Console.WriteLine("We do not offer that product."); Console.WriteLine("Please enter one of the products we offer. We offer Carpet, Laminate, Tile, Wood"); productType = Console.ReadLine().ToLower(); } Console.WriteLine("Enter the area (square footage) that you need. Minimun of 100 square feet please"); string areaNum = Console.ReadLine(); decimal.TryParse(areaNum, out decimal area); while (area < 100) { Console.WriteLine("Area square footage needed to be 100 square footage or more."); Console.WriteLine("Enter the area square footage minumun of 100"); areaNum = Console.ReadLine(); decimal.TryParse(areaNum, out area); } CreateOrderResponse response = manager.Calculation(date, CustomerName, state, productType, area); ConsoleIO.DisplayOrderDetails(response.order); if (response.Success) { Console.WriteLine("Do you want to place the Order? y/n"); string answer = Console.ReadLine().ToLower(); if (answer == "y") { CreateOrderResponse newResponse = manager.CreateOrder(response.order); Console.WriteLine("Your order has been created and added"); } else if (answer == "n") { Console.WriteLine("Order has been canceled"); } else { response.Message = "An error has occured: "; Console.WriteLine(response.Message); } Console.WriteLine("Press any key to continue.."); Console.ReadKey(); } }
private bool processPacket(byte id) { int nbr = 0; switch (id) { case 0x00: byte[] keepalive = new byte[5] { 0, 0, 0, 0, 0 }; Receive(keepalive, 1, 4, SocketFlags.None); handler.OnServerKeepAlive(); Send(keepalive); break; case 0x01: readData(4); readNextString(); readData(5); break; case 0x02: readData(1); readNextString(); readNextString(); readData(4); break; case 0x03: string message = readNextString(); handler.OnTextReceived(message, protocolversion >= 72); break; case 0x04: readData(16); break; case 0x05: readData(6); readNextItemSlot(); break; case 0x06: readData(12); break; case 0x07: readData(9); break; case 0x08: if (protocolversion >= 72) { readData(10); } else { readData(8); } break; case 0x09: readData(8); readNextString(); break; case 0x0A: readData(1); break; case 0x0B: readData(33); break; case 0x0C: readData(9); break; case 0x0D: readData(41); break; case 0x0E: readData(11); break; case 0x0F: readData(10); readNextItemSlot(); readData(3); break; case 0x10: readData(2); break; case 0x11: readData(14); break; case 0x12: readData(5); break; case 0x13: if (protocolversion >= 72) { readData(9); } else { readData(5); } break; case 0x14: readData(4); readNextString(); readData(16); readNextEntityMetaData(); break; case 0x16: readData(8); break; case 0x17: readData(19); readNextObjectData(); break; case 0x18: readData(26); readNextEntityMetaData(); break; case 0x19: readData(4); readNextString(); readData(16); break; case 0x1A: readData(18); break; case 0x1B: if (protocolversion >= 72) { readData(10); } break; case 0x1C: readData(10); break; case 0x1D: nbr = (int)readNextByte(); readData(nbr * 4); break; case 0x1E: readData(4); break; case 0x1F: readData(7); break; case 0x20: readData(6); break; case 0x21: readData(9); break; case 0x22: readData(18); break; case 0x23: readData(5); break; case 0x26: readData(5); break; case 0x27: if (protocolversion >= 72) { readData(9); } else { readData(8); } break; case 0x28: readData(4); readNextEntityMetaData(); break; case 0x29: readData(8); break; case 0x2A: readData(5); break; case 0x2B: readData(8); break; case 0x2C: if (protocolversion >= 72) { readNextEntityProperties(protocolversion); } break; case 0x33: readData(13); nbr = readNextInt(); readData(nbr); break; case 0x34: readData(10); nbr = readNextInt(); readData(nbr); break; case 0x35: readData(12); break; case 0x36: readData(14); break; case 0x37: readData(17); break; case 0x38: readNextChunkBulkData(); break; case 0x3C: readData(28); nbr = readNextInt(); readData(3 * nbr); readData(12); break; case 0x3D: readData(18); break; case 0x3E: readNextString(); readData(17); break; case 0x3F: if (protocolversion > 51) { readNextString(); readData(32); } break; case 0x46: readData(2); break; case 0x47: readData(17); break; case 0x64: readNextWindowData(protocolversion); break; case 0x65: readData(1); break; case 0x66: readData(7); readNextItemSlot(); break; case 0x67: readData(3); readNextItemSlot(); break; case 0x68: readData(1); for (nbr = readNextShort(); nbr > 0; nbr--) { readNextItemSlot(); } break; case 0x69: readData(5); break; case 0x6A: readData(4); break; case 0x6B: readData(2); readNextItemSlot(); break; case 0x6C: readData(2); break; case 0x82: readData(10); readNextString(); readNextString(); readNextString(); readNextString(); break; case 0x83: readData(4); nbr = readNextShort(); readData(nbr); break; case 0x84: readData(11); nbr = readNextShort(); if (nbr > 0) { readData(nbr); } break; case 0x85: if (protocolversion >= 74) { readData(13); } break; case 0xC8: if (readNextInt() == 2022) { ConsoleIO.WriteLineFormatted("§MCC: You are dead. Type /reco to respawn & reconnect."); } if (protocolversion >= 72) { readData(4); } else { readData(1); } break; case 0xC9: string name = readNextString(); bool online = readNextByte() != 0x00; readData(2); Guid FakeUUID = new Guid(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(name)).Take(16).ToArray()); if (online) { handler.OnPlayerJoin(FakeUUID, name); } else { handler.OnPlayerLeave(FakeUUID); } break; case 0xCA: if (protocolversion >= 72) { readData(9); } else { readData(3); } break; case 0xCB: autocomplete_result = readNextString(); autocomplete_received = true; break; case 0xCC: readNextString(); readData(4); break; case 0xCD: readData(1); break; case 0xCE: if (protocolversion > 51) { readNextString(); readNextString(); readData(1); } break; case 0xCF: if (protocolversion > 51) { readNextString(); readData(1); readNextString(); } readData(4); break; case 0xD0: if (protocolversion > 51) { readData(1); readNextString(); } break; case 0xD1: if (protocolversion > 51) { readNextTeamData(); } break; case 0xFA: string channel = readNextString(); byte[] payload = readNextByteArray(); handler.OnPluginChannelMessage(channel, payload); break; case 0xFF: string reason = readNextString(); handler.OnConnectionLost(ChatBot.DisconnectReason.InGameKick, reason); break; default: return(false); //unknown packet! } return(true); //packet has been successfully skipped }
public void Execute() { bool edited; int orderNumber; ConsoleIO.Header(); Console.WriteLine("Edit an Order"); Console.WriteLine(); do { DateTime editDate = ConsoleIO.GetOrderDateFromUser("Please enter a date for the order you wish you edit (MM/DD/YYYY): "); ConsoleIO.Header(); Console.WriteLine("Edit an Order"); Console.WriteLine(); List <Order> orders = ConsoleIO.PrintOrderList(editDate); Console.WriteLine(ConsoleIO.Separator); Console.WriteLine(); if (orders == null) { Console.WriteLine("Press any key to continue."); Console.ReadKey(); return; } Console.WriteLine("Please enter the order number you wish to edit: "); int.TryParse(Console.ReadLine(), out orderNumber); if (orderNumber <= 0) { Console.WriteLine("Order Number is not valid."); Console.WriteLine("Press any key to continue"); Console.ReadKey(); return; } for (int i = 0; i < orders.Count; i++) { if (orderNumber == orders[i].OrderNumber) { break; } else if ((i == orders.Count - 1) && (orders[i].OrderNumber != orderNumber)) { Console.WriteLine("Order Number {0} does not exist on {1}", orderNumber, editDate); Console.WriteLine("Press any key to continue"); Console.ReadKey(); return; } } Order oldOrder = orders[orderNumber - 1]; oldOrder.Name = ConsoleIO.GetOrderNameFromUser(String.Format("Please enter name for the order. Current name : ({0}) ", oldOrder.Name)); oldOrder.State = ConsoleIO.GetOrderStateFromUser(String.Format("Please enter your state initials. Current state: ({0}) ", oldOrder.State)); oldOrder.TaxRate = TaxRepository.GetTaxRate(oldOrder.State); oldOrder.OrderDate = editDate; oldOrder.Type = ConsoleIO.GetProductFromUser(oldOrder.Type); oldOrder.Area = ConsoleIO.GetAreaFromUser(String.Format("Please enter new area amount. Current Area: ({0}) ", oldOrder.Area)); oldOrder.CostLabor = Math.Round(Calculations.GetLaborCost(oldOrder.Type, oldOrder.Area), 2, MidpointRounding.AwayFromZero); oldOrder.CostMaterial = Math.Round(Calculations.GetProductCost(oldOrder.Type, oldOrder.Area), 2, MidpointRounding.AwayFromZero); oldOrder.Tax = Math.Round(ConsoleIO.JustTax(oldOrder.TaxRate, oldOrder.Type, oldOrder.Area, oldOrder.State), 2, MidpointRounding.AwayFromZero); oldOrder.TotalCost = Math.Round(ConsoleIO.GetTotal(oldOrder.TaxRate, oldOrder.Type, oldOrder.Area, oldOrder.State), 2, MidpointRounding.AwayFromZero); string confirmFormat = "{0, -16} {1} \n{2, -16} {3} \n{4, -16} {5:d} \n{6, -16} {7} \n{8, -16} {9} \n \n{10, -16} {11} \n{12, -16} {13} \n{14, -16} {15} \n{16, -16} {17}"; while (true) { string editOrder = ConsoleIO.GetYesNoAnswerFromUser($"Is this information correct? ({oldOrder.Name}, {oldOrder.State}, {oldOrder.Type}, {oldOrder.Area})"); if ((editOrder.ToUpper() == "Y") || (editOrder.ToUpper() == "YES")) { ConsoleIO.Header(); OrderManager orderManager = OrderManagerFactory.Create(); OrderEditResponse response = orderManager.EditOrder(oldOrder, orderNumber); Console.WriteLine(confirmFormat, "Customer Name:", oldOrder.Name, "Customer State:", oldOrder.State, "Order Date:", oldOrder.OrderDate, "Flooring Type:", oldOrder.Type, "Area:", oldOrder.Area + "(sqft)", "Product Cost:", oldOrder.CostMaterial, "Labor Cost:", oldOrder.CostLabor, "Tax:", oldOrder.Tax, "Total:", oldOrder.TotalCost); Console.WriteLine(ConsoleIO.Separator); Console.WriteLine(); Console.WriteLine("Press any key to continue."); Console.ReadKey(); edited = true; break; } else if ((editOrder.ToUpper() == "N") || (editOrder.ToUpper() == "NO")) { ConsoleIO.Header(); Console.WriteLine("Edit cancelled."); Console.WriteLine("Press any key to continue."); Console.ReadKey(); edited = false; return; } else { edited = false; ConsoleIO.Header(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Please enter Y/N only."); Console.ResetColor(); Console.WriteLine(); } } }while (!edited); }
static void Main(string[] args) { IUserIO userIO = new ConsoleIO(); MathHelper helper = new MathHelper(userIO); helper.FindProblem(); }
//MVC-horror, i know, I want to pubblish something today so i will fix that later static void Main() { ConsoleIO.Run(); }
public HumanPlayer(ConsoleIO consoleIO, char mark) { this.consoleIO = consoleIO; this.Mark = mark; }
public void Execute() { OrderManager manager = OrderManagerFactory.Create(); DateTime orderDate = new DateTime().Date; Order order = new Order(); List <Order> Orders = new List <Order>(); OrderLookupResponse lookupResponse = new OrderLookupResponse(); bool orderExists; EditOrderInFile editInFile = new EditOrderInFile(); PrintReceipt print = new PrintReceipt(); EditOrderFile editFile = new EditOrderFile(); Console.Clear(); Console.WriteLine("Edit an order"); Console.WriteLine(TextHelper.ConsoleBar); Console.WriteLine("Please enter the following information...."); Console.WriteLine(); while (true) { Console.WriteLine("Date of order: "); if (DateTime.TryParse(Console.ReadLine(), out orderDate)) { order.Date = orderDate; break; } Console.WriteLine("You did not enter a valid date format. Press any key to continue..."); Console.ReadKey(); } while (true) { lookupResponse = manager.LookupOrder(order.Date); if (lookupResponse != null) { Orders = lookupResponse.Orders; } if (lookupResponse.success) { break; } else { Console.WriteLine("An error occurred."); Console.WriteLine(lookupResponse.message); continue; } } while (true) { Console.Clear(); ConsoleIO.DisplayOrderDetails(lookupResponse.Orders); int orderNumber; Console.WriteLine("Order number: "); if (int.TryParse(Console.ReadLine(), out orderNumber)) { order.OrderNumber = orderNumber; } else { Console.WriteLine("You did not enter a number. Press any key to continue..."); Console.ReadKey(); } string filePath = FilePath.GetFilePath(order.Date); Orders = ReadOrdersFromFile.ReadOrders(filePath); orderExists = editInFile.CheckOrderNumberExists(Orders, order.OrderNumber); if (!orderExists) { Console.WriteLine("That order number does not exist for the date you entered. Press any key to continue..."); Console.ReadKey(); continue; } else { Order singleOrder = Orders.Where(ord => ord.OrderNumber == order.OrderNumber).Single(); order = singleOrder; } while (true) { print.Print(order); Console.WriteLine("Are you sure you want to delete this order? (Y/N)?"); string userInput = Console.ReadLine().ToUpper(); switch (userInput) { case "Y": RemoveOrderFile remove = new RemoveOrderFile(); remove.RemoveOrderFromList(Orders, order, order.Date); editFile.EditOrderToFile(Orders, order.Date); Console.WriteLine("Remove has been saved! Press any key to continue..."); Console.ReadKey(); break; case "N": Console.WriteLine("Remove has been canceled. Press any key to continue..."); Console.ReadKey(); break; default: Console.WriteLine("That was not a valid entry! Press any key to continue..."); Console.ReadKey(); continue; } break; } break; } }