Exemplo n.º 1
0
        /// <summary>
        /// Sort list of books by tag.
        /// </summary>
        /// <param name="tag">Tag.</param>
        public void SortByTag(string tag)
        {
            tag = tag.ToLower(CultureInfo.CreateSpecificCulture("en-US"));
            List <string> tags = new List <string> {
                "isbn", "author", "name", "publishing", "year", "pages", "price"
            };

            try
            {
                if (!tags.Contains(tag))
                {
                    throw new BookException("Incorrect tag.");
                }
            }
            catch (BookException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            var a = this.books.ToArray();

            switch (tag)
            {
            case "isbn":
            {
                Array.Sort(a, Book.SortIsbn());
                this.books = a.ToList();
            }

            break;

            case "author":
            {
                Array.Sort(a, Book.SortAuthor());
                this.books = a.ToList();
            }

            break;

            case "name":
            {
                Array.Sort(a, Book.SortName());
                this.books = a.ToList();
            }

            break;

            case "publishing":
            {
                Array.Sort(a, Book.SortPublishing());
                this.books = a.ToList();
            }

            break;

            case "year":
            {
                Array.Sort(a, Book.SortYear());
                this.books = a.ToList();
            }

            break;

            case "pages":
            {
                Array.Sort(a, Book.SortPages());
                this.books = a.ToList();
            }

            break;

            case "price":
            {
                Array.Sort(a, Book.SortPrice());
                this.books = a.ToList();
            }

            break;
            }

            BookListStorage.SaveSortToFile(this.books);
        }
Exemplo n.º 2
0
 public static string ConvertLongMoney(string text)
 {
     text = string.Format(CultureInfo.CreateSpecificCulture("vi-VN"), "{0:#,##}", decimal.Parse(text));
     return(text);
 }
Exemplo n.º 3
0
    public static bool tryParseNum(string text, out UInt32 val, bool enableFloat)
    {
        string textOrig = text;

        text = text.ToUpper();
        val  = 0;
        UInt64 _val = 0;

        if (enableFloat && text.Contains("."))
        {
            double vDouble;
            if (Double.TryParse(text, NumberStyles.Number, CultureInfo.CreateSpecificCulture("en-US"), out vDouble))
            {
                val = double2flm(vDouble);
                return(true);
            }
        }


        // === check minus sign ===
        bool negate = false;

        if (text.StartsWith("-"))
        {
            if (text.Length < 2)
            {
                return(false);
            }
            negate = true;
            text   = text.Substring(1);
        }

        // === all numbers must start with 0..9 (includes 0x etc prefixes) ===
        char c1 = text[0];

        if ((c1 < '0') || (c1 > '9'))
        {
            return(false);
        }

        // === determine base ===
        UInt32 b = 10;

        if (text.StartsWith("0B"))
        {
            b = 2; text = text.Substring(2);
        }
        else if (text.StartsWith("0O"))
        {
            b = 8; text = text.Substring(2); // octal, non-standard
        }
        else if (text.StartsWith("0X"))
        {
            b = 16; text = text.Substring(2);
        }

        // === parse resulting value ===
        for (int ix = 0; ix < text.Length; ++ix)
        {
            _val *= b;
            int charVal;
            if (!parseChar.TryGetValue(text[ix], out charVal))
            {
                throw new Exception("invalid character in number: >>>" + text + "<<<");
            }
            ;
            if (charVal >= b)
            {
                throw new Exception("number digit out of range in >>>" + text + "<<<");
            }
            _val += (UInt32)charVal;
        }

        // === apply two's complement negation ===
        if (negate)
        {
            if (_val > (UInt64)UInt32.MaxValue + 1)
            {
                throw new Exception("constant '" + textOrig + "' exceeds 32-bit range");
            }
            val = (UInt32)(~_val + 1);
        }
        else
        {
            if (_val > UInt32.MaxValue)
            {
                throw new Exception("constant '" + textOrig + "' exceeds 32-bit range");
            }
            val = (UInt32)_val;
        }

        return(true);
    }
Exemplo n.º 4
0
        public void LoadProfilePath(String path)
        {
            try
            {
                _profileText = File.ReadAllText(path);
                var profileText = _profileText;
                //Parse and update values.
                var nameClassRegex = new Regex("([^=]+)=\"?([^\r\n\"]+)\"?");
                var specRegex      = new Regex("spec=(\\w+)");
                var ilvlRegex      = new Regex("gear_ilvl=(\\d+.?\\d*)");
                var tierRegex      = new Regex("set_bonus=tier(\\d+)_(\\d)pc=1");
                var potionRegex    = new Regex("potion=(\\w+)");
                var flaskRegex     = new Regex("flask=(\\w+)");
                var foodRegex      = new Regex("food=(\\w+)");
                var augmentRegex   = new Regex("augmentation=(\\w+)");

                var nameClassMatch = nameClassRegex.Match(profileText);
                Name  = nameClassMatch.Groups[2].Value;
                Class = nameClassMatch.Groups[1].Value.UppercaseWords().Replace("Deathk", "Death K").Replace("Demonh", "Demon H").UppercaseWords();
                Spec  = specRegex.Match(profileText).Groups[1].Value.UppercaseWords().Replace("Beastm", "Beast M");
                var fixedCulture = CultureInfo.CreateSpecificCulture("en-US");
                ILvl = float.Parse(ilvlRegex.Match(profileText).Groups[1].Value, fixedCulture); // Easy fix to convert EU to US style decimal notation.
                // Ring 1
                Ring1.Add("None");
                Ring1.Add("");
                Ring1.Add("- " + Class + " -");
                Ring1.Add("    - " + Spec + " -");
                AzeriteMapping[Class.ToLower().Replace(" ", "_")][Spec.ToLower().Replace(" ", "_")].ForEach(x => { Ring1.Add(x.Name); Ring1Mapping.Add(x); });
                Ring1.Add("");
                Ring1.Add("- PVE -");
                Ring1.Add("    - Magni -");
                AzeriteMapping["pve"]["magni"].ForEach(x => { Ring1.Add(x.Name); Ring1Mapping.Add(x); });
                Ring1.Add("");
                Ring1.Add("    - Uldir -");
                AzeriteMapping["pve"]["uldir"].ForEach(x => { Ring1.Add(x.Name); Ring1Mapping.Add(x); });
                Ring1.Add("");
                Ring1.Add("    - World -");
                AzeriteMapping["pve"]["location"].ForEach(x => { Ring1.Add(x.Name); Ring1Mapping.Add(x); });
                Ring1.Add("");
                Ring1.Add("    - Dungeons -");
                AzeriteMapping["pve"]["dungeon"].ForEach(x => { Ring1.Add(x.Name); Ring1Mapping.Add(x); });
                Ring1.Add("");
                Ring1.Add("- PVP -");
                Ring1.Add("    - Horde -");
                AzeriteMapping["pvp"]["horde"].ForEach(x => { Ring1.Add(x.Name); Ring1Mapping.Add(x); });
                Ring1.Add("");
                Ring1.Add("    - Alliance -");
                AzeriteMapping["pvp"]["alliance"].ForEach(x => { Ring1.Add(x.Name); Ring1Mapping.Add(x); });
                Ring1.Add("");
                Ring1.Add("- Professions -");
                Ring1.Add("    - Engineering -");
                AzeriteMapping["profession"]["engineering"].ForEach(x => { Ring1.Add(x.Name); Ring1Mapping.Add(x); });
                // Ring 2
                Ring2.Add("None");
                Ring2.Add("");
                Ring2.Add("- Role -");
                if (new List <String> {
                    "Demon Hunter", "Death Knight", "Monk", "Paladin", "Druid", "Warrior"
                }.Contains(Class))
                {
                    Ring2.Add("    - Tank -");
                    AzeriteMapping["role"]["tank"].ForEach(x => { Ring2.Add(x.Name); Ring2Mapping.Add(x); });
                    Ring2.Add("");
                }
                if (new List <String> {
                    "Paladin", "Priest", "Shaman", "Monk", "Druid"
                }.Contains(Class))
                {
                    Ring2.Add("    - Healer -");
                    AzeriteMapping["role"]["healer"].ForEach(x => { Ring2.Add(x.Name); Ring2Mapping.Add(x); });
                    Ring2.Add("");
                }
                Ring2.Add("    - DPS -");
                AzeriteMapping["role"]["dps"].ForEach(x => { Ring2.Add(x.Name); Ring2Mapping.Add(x); });
                Ring2.Add("");
                Ring2.Add("    - Any -");
                AzeriteMapping["role"]["any"].ForEach(x => { Ring2.Add(x.Name); Ring2Mapping.Add(x); });
                // Ring 4
                Ring4.Add("None");
                AzeriteMapping["generic"]["center"].ForEach(x => { Ring4.Add(x.Name); Ring4Mapping.Add(x); });

                HeadRing1      = "None";
                HeadRing2      = "None";
                HeadRing4      = "None";
                ChestRing1     = "None";
                ChestRing2     = "None";
                ChestRing4     = "None";
                ShouldersRing1 = "None";
                ShouldersRing2 = "None";
                ShouldersRing4 = "None";

                var potionName = potionRegex.Match(profileText).Groups[1].Value;
                var flaskName  = flaskRegex.Match(profileText).Groups[1].Value;
                var foodName   = foodRegex.Match(profileText).Groups[1].Value;
                var runeName   = augmentRegex.Match(profileText).Groups[1].Value;
                if (PotionNameMapping.Exists(x => x.simc_names.Contains(potionName)))
                {
                    Potion = PotionNameMapping.First(x => x.simc_names.Contains(potionName)).name;
                }
                if (FlaskNameMapping.Exists(x => x.simc_names.Contains(flaskName)))
                {
                    Flask = FlaskNameMapping.First(x => x.simc_names.Contains(flaskName)).name;
                }
                if (FoodNameMapping.Exists(x => x.simc_names.Contains(foodName)))
                {
                    Food = FoodNameMapping.First(x => x.simc_names.Contains(foodName)).name;
                }
                if (AugmentNameMapping.Exists(x => x.simc_names.Contains(runeName)))
                {
                    Rune = AugmentNameMapping.First(x => x.simc_names.Contains(runeName)).name;
                }
                if (PotionNameMapping.Exists(x => x.simc_names.Contains(potionName)))
                {
                    Potion = PotionNameMapping.First(x => x.simc_names.Contains(potionName)).name;
                }
                LoadAzerite(profileText);

                var tierMatches = tierRegex.Matches(profileText);
                for (int i = 0; i < tierMatches.Count; i++)
                {
                    var match = tierMatches[i];
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Ran into an issue loading your profile: " + e.Message, "Error", MessageBoxButton.OK);
            }
        }
Exemplo n.º 5
0
        public void Issue_124()
        {
            Console.WriteLine("Test Start.");

            Sqlite3.sqlite3 db = null;
            Sqlite3.sqlite3_open(":memory:", out db);
            Sqlite3.Vdbe stmt = null;
            string       zero = null;
            string       val;

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            //create table
            {
                Sqlite3.sqlite3_prepare_v2(db, "create table Test (val REAL NOT NULL)", -1, ref stmt, ref zero);
                Sqlite3.sqlite3_step(stmt);
                Sqlite3.sqlite3_finalize(stmt);
            }

            //insert 0.1
            {
                Sqlite3.sqlite3_prepare_v2(db, "insert into Test(val) values ('0.1')", -1, ref stmt, ref zero);
                Sqlite3.sqlite3_step(stmt);
                Sqlite3.sqlite3_finalize(stmt);
            }
            //insert 0.1
            {
                Sqlite3.sqlite3_prepare_v2(db, "insert into Test(val) values ('0.2')", -1, ref stmt, ref zero);
                Sqlite3.sqlite3_step(stmt);
                Sqlite3.sqlite3_finalize(stmt);
            }

            //insert 0.000000001
            {
                Sqlite3.sqlite3_prepare_v2(db, "insert into Test(val) values ('0.000000001')", -1, ref stmt, ref zero);
                Sqlite3.sqlite3_step(stmt);
                Sqlite3.sqlite3_finalize(stmt);
            }

            //invariant culture
            {
                System.Console.WriteLine("invariant culture");
                Sqlite3.sqlite3_prepare_v2(db, "select val from Test", -1, ref stmt, ref zero);
                Sqlite3.sqlite3_step(stmt);
                val = Sqlite3.sqlite3_column_text(stmt, 0);
                System.Console.WriteLine("value: " + val);
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("ru");
                Sqlite3.sqlite3_step(stmt);
                val = Sqlite3.sqlite3_column_text(stmt, 0);
                System.Console.WriteLine("value: " + val);
                Sqlite3.sqlite3_step(stmt);
                val = Sqlite3.sqlite3_column_text(stmt, 0);
                System.Console.WriteLine("value: " + val);
                Sqlite3.sqlite3_finalize(stmt);
            }

            //ru-ru culture
            {
                System.Console.WriteLine("ru");
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("ru");
                Sqlite3.sqlite3_prepare_v2(db, "select val from Test", -1, ref stmt, ref zero);
                Sqlite3.sqlite3_step(stmt);
                val = Sqlite3.sqlite3_column_text(stmt, 0);
                System.Console.WriteLine("value: " + val);
                Sqlite3.sqlite3_step(stmt);
                val = Sqlite3.sqlite3_column_text(stmt, 0);
                System.Console.WriteLine("value: " + val);
                Sqlite3.sqlite3_finalize(stmt);
            }


            Console.WriteLine("Test Done.");
        }
Exemplo n.º 6
0
        public void GenerateCMR(
            string template,
            string savePath,
            BatchTableC batchTbl,
            CodesTableC codesTbl,

            Car car,
            Driver driver,
            string number,

            string city)
        {
            XLWorkbook   workbook;
            IXLWorksheet ws;

            try
            {
                workbook = new XLWorkbook(template);
                ws       = workbook.Worksheet(1);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw new ArgumentException("[PackingGeneratorC] Error in file: " + template);
            }

            Common.setCellString(ws, cmrTemplateMap.carNumberAndDate_0, car.numberShort + DateTime.Now.ToString("ddMM"));

            Common.setCellString(ws, cmrTemplateMap.senderCity_4, city);
            Common.setCellString(ws, cmrTemplateMap.dayAndMonth_4, DateTime.Now.ToString("dd MMMM", CultureInfo.CreateSpecificCulture("ru-RU")));
            Common.setCellString(ws, cmrTemplateMap.year_4, DateTime.Now.ToString("yyyyг.", CultureInfo.CreateSpecificCulture("ru-RU")));

            Common.setCellString(ws, cmrTemplateMap.specificationNumber_5, number);
            Common.setCellString(ws, cmrTemplateMap.shortDate_spec_5, DateTime.Now.ToString("dd.MM.yy."));

            Common.setCellString(ws, cmrTemplateMap.totalPlaces_6, totalPlaces + " мешка п/п (интернет заказы для личного пользования)");
            Common.setCellString(ws, cmrTemplateMap.totalGrossWeight_11, totalGross.ToString("0.000"));
            Common.setCellString(ws, cmrTemplateMap.totalPrice_13, totalPrice.ToString());

            Common.setCellString(ws, cmrTemplateMap.driverName_23, driver.name);
            Common.setCellString(ws, cmrTemplateMap.driverPassport_23, "пас. " + driver.passport);

            Common.setCellString(ws, cmrTemplateMap.carNumberFull_25, car.number);
            Common.setCellString(ws, cmrTemplateMap.carBrand_26, car.name);

            Common.Log("Сохранение СМР в '" + savePath + "'");
            workbook.SaveAs(savePath + "\\" + Common.fileCMR);
        }
Exemplo n.º 7
0
        void getWeatherDetails()
        {
            using (WebClient web = new WebClient())
            {
                string cityCode            = "588409";
                string apiKey              = "8e4dcb3a1ab522971456c7b7bbfb55da";
                string uri                 = string.Format("http://api.openweathermap.org/data/2.5/weather?id={0}&appid={1}&units=metric", cityCode, apiKey);
                var    json                = web.DownloadString(uri);
                WeatherDetails.root outPut = JsonConvert.DeserializeObject <WeatherDetails.root>(json);


                lbl_City.Text = outPut.name + ", " + string.Format("{0}", outPut.sys.country);

                double temp = outPut.main.temp;
                lbl_temp.Text      = String.Format("{0} \u00B0C", Convert.ToString(Math.Round(temp, 0)));
                lbl_windspeed.Text = string.Format("{0} m/s", outPut.wind.speed);
                lbl_pressure.Text  = string.Format("{0} hPa", outPut.main.pressure);
                lbl_humidity.Text  = string.Format("{0 }%", outPut.main.humidity);

                String culture = "et-EE";
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);

                //convert unix to datetime - Current Time
                DateTime localDateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(string.Format("{0}", outPut.dt))).DateTime.ToLocalTime();
                // convert unix to time - sunrise & set
                DateTime sunRise = DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(string.Format("{0}", outPut.sys.sunrise))).DateTime.ToLocalTime();
                DateTime sunSet  = DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(string.Format("{0}", outPut.sys.sunset))).DateTime.ToLocalTime();

                lbl_dateTime.Text = Convert.ToString(localDateTimeOffset);
                lbl_sunrise.Text  = String.Format("{0:t}", sunRise);
                lbl_sunset.Text   = String.Format("{0:t}", sunSet);

                string iconName = string.Format("{0}", outPut.weather[0].icon);
                if (iconName.Contains("01"))
                {
                    lbl_icon.Image = Properties.Resources.Lighter_Heat;
                    lbl_desc.Text  = string.Format("{0}", "Selge");
                }
                else if (iconName.Contains("02"))
                {
                    lbl_icon.Image = Properties.Resources.Sun_Behind_Clouds;
                    lbl_desc.Text  = string.Format("{0}", "Vähene pilvisus");
                }
                else if (iconName.Contains("03"))
                {
                    lbl_icon.Image = Properties.Resources.Cloud;
                    lbl_desc.Text  = string.Format("{0}", "Mõõdukas pilvisus");
                }
                else if (iconName.Contains("04"))
                {
                    lbl_icon.Image = Properties.Resources.Cloud_with_Outlined_Cloud;
                    lbl_desc.Text  = string.Format("{0}", "Pilves");
                }
                else if (iconName.Contains("09"))
                {
                    lbl_icon.Image = Properties.Resources.Rain_with_Clouds;
                    lbl_desc.Text  = string.Format("{0}", "Vähene sadu");
                }
                else if (iconName.Contains("10"))
                {
                    lbl_icon.Image = Properties.Resources.Rain;
                    lbl_desc.Text  = string.Format("{0}", "Vihm");
                }
                else
                {
                    lbl_icon.Image = Properties.Resources.Snow;
                    lbl_desc.Text  = string.Format("{0}", "Lumi");
                }
            }
        }
Exemplo n.º 8
0
        public IEnumerator Handle(Dialogue.RunnerResult result, YarnDialogManager manager)
        {
            var dialogue = manager.GetDialogue();

            if (dialogue == null || string.IsNullOrEmpty(dialogue.currentNode))
            {
                yield break;
            }

            if (_currentNode.Equals(dialogue.currentNode))
            {
                yield break;
            }
            _currentNode = dialogue.currentNode;

            var tags = dialogue.GetTagsForNode(_currentNode);

            foreach (var tag in tags)
            {
                // The split to work should be formated as [target].emotion.[emotion].[intensity]

                var tagSplit = tag.Split('.');

                // Does it have 4 elements
                if (tagSplit.Length != 4)
                {
                    continue;
                }

                // Is the second element `emotion`
                var action = tagSplit[1].ToLower();
                if (!action.Equals("emotion"))
                {
                    continue;
                }

                // What is the emotion?
                var         emotion = tagSplit[2];
                EmotionEnum emotionEnum;
                try
                {
                    emotionEnum = (EmotionEnum)Enum.Parse(typeof(EmotionEnum), emotion, true);
                }
                catch (OverflowException)
                {
                    // If unable to convert, skip
                    continue;
                }

                // What is the emotion's intention?
                var   intentityStr = tagSplit[3];
                float intensity;
                if (!float.TryParse(intentityStr, NumberStyles.Any, CultureInfo.CreateSpecificCulture("pt-PT"),
                                    out intensity))
                {
                    continue;
                }

                var target = tagSplit[0];
                if (target.ToLower().Equals("user"))
                {
                    // Update background
                }
                else
                {
                    var tutor = manager.GetTutor(target);
                    if (tutor == null)
                    {
                        continue;
                    }
                    tutor.Emotion = new Emotion(emotionEnum, intensity);
                    manager.ModuleManager.Feel(tutor, BubbleSystem.Reason.ReasonEnum.None);
                }
            }
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            #region Основные параметры
            var serviceProvider = new ServiceCollection()
                                  .AddSingleton <IRepository, EFRepository>()
                                  .BuildServiceProvider();

            CultureInfo culture;
            var         cultureNames = new string[] { "ru-RU", "en-US" };
            int         pos          = Array.IndexOf(args, cultureNames[0]);
            if (pos > -1)
            {
                culture = CultureInfo.CreateSpecificCulture(args[pos]);
            }
            else
            {
                culture = CultureInfo.CreateSpecificCulture("en-US");
            }

            var resourceManager = new ResourceManager("L2C.Budget.CMD.Resources.Lang", typeof(Program).Assembly);
            Console.OutputEncoding = Encoding.UTF8;
            #endregion

            Console.WriteLine(resourceManager.GetString("Hello", culture));

            var            userName   = GetUserInput(resourceManager.GetString("EnterName", culture));
            IRepository    repo       = serviceProvider.GetService <IRepository>();
            UserController controller = new UserController(repo);

            //Аутентифицируем пользователя.
            do
            {
                try
                {
                    controller.AuthenUser(userName);
                }
                catch (ArgumentNullException)
                {
                    Console.WriteLine(resourceManager.GetString("ErrorWrongUserName", culture));
                    userName = GetUserInput(resourceManager.GetString("EnterName", culture));
                    continue;
                }
                catch (NewUserException)
                {
                    Console.WriteLine(resourceManager.GetString("ErrorUserExist", culture) + userName);
                    var genderName = GetUserInput($"{userName}, " + resourceManager.GetString("RegisterGender", culture));

                    DateTime birthday = GetUserBirthDate(culture, resourceManager);

                    var budgetName = GetUserInput(resourceManager.GetString("RegisterBudgetName", culture));
                    try
                    {
                        controller.CreateNewUser(userName, genderName, birthday, budgetName);
                    }
                    catch (ArgumentException except)
                    {
                        switch (except.Message)
                        {
                        case "userName":
                            Console.WriteLine(resourceManager.GetString("ErrorUserName", culture));
                            break;

                        case "genderName":
                            Console.WriteLine(resourceManager.GetString("ErrorGenderName", culture));
                            break;

                        case "birthday":
                            Console.WriteLine(resourceManager.GetString("ErrorBirthday", culture));
                            break;

                        case "budgetName":
                            Console.WriteLine(resourceManager.GetString("ErrorBudgetName", culture));
                            break;

                        default:
                            break;
                        }
                        Console.WriteLine(resourceManager.GetString("RegisterRestart", culture));
                        userName = Console.ReadLine();
                        continue;
                    }
                }
            }while (!controller.IsUserAuthen);

            //Основной  цикл
            while (true)
            {
                try
                {
                    var userState = controller.GetUserBalance();
                    Console.WriteLine(resourceManager.GetString("HelpQuit", culture));
                    Console.WriteLine(resourceManager.GetString("HelpAddMoney", culture));
                    Console.WriteLine(resourceManager.GetString("HelpWithdrawMoney", culture));
                    Console.WriteLine($"{userState.userName}" +
                                      resourceManager.GetString("DisplayState", culture) +
                                      $" {userState.budgetName} {userState.balance:c}");
                    var key = Console.ReadKey();
                    switch (key.Key)
                    {
                    case ConsoleKey.Q:
                        Environment.Exit(0);
                        break;

                    case ConsoleKey.A:
                        Console.WriteLine(resourceManager.GetString("AddMoney", culture));
                        var   addAmount  = Console.ReadLine();
                        float AddAmountF = 0f;
                        if (float.TryParse(addAmount, out AddAmountF))
                        {
                            try
                            {
                                controller.AddMoney(AddAmountF);
                            }
                            catch (ArgumentException ex)
                            {
                                switch (ex.Message)
                                {
                                case "amount":
                                    Console.WriteLine(resourceManager.GetString("ErrorAddMoneyAmount", culture));
                                    break;

                                case "Name":
                                    Console.WriteLine(resourceManager.GetString("ErrorUser", culture));
                                    break;

                                default:
                                    break;
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine(resourceManager.GetString("ErrorAmount", culture));
                        }
                        break;

                    case ConsoleKey.R:
                        Console.WriteLine(resourceManager.GetString("WithdrawMoney", culture));
                        var   removeAmount  = Console.ReadLine();
                        float removeAmountF = 0f;
                        if (float.TryParse(removeAmount, out removeAmountF))
                        {
                            try
                            {
                                controller.RemoveMoney(removeAmountF);
                            }

                            catch (ArgumentException ex)
                            {
                                switch (ex.Message)
                                {
                                case "amount":
                                    Console.WriteLine(resourceManager.GetString("ErrorWithdrawMoneyAmount", culture));
                                    break;

                                case "Name":
                                    Console.WriteLine(resourceManager.GetString("ErrorUser", culture));
                                    break;

                                default:
                                    break;
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine(resourceManager.GetString("ErrorAmount", culture));
                        }
                        break;

                    default:
                        Console.WriteLine(resourceManager.GetString("ErrorInput", culture));
                        break;
                    }
                }
                catch
                {
                    Console.WriteLine(resourceManager.GetString("ErrorUserState", culture));
                    continue;
                }
            }
        }
Exemplo n.º 10
0
        private IDictionary <string, MasterDataLine> readMasterData()
        {
            IDictionary <string, MasterDataLine> masterData = new Dictionary <string, MasterDataLine>();

            using (SpreadsheetDocument ssd = SpreadsheetDocument.Open(this.textBoxMasterDataFile.Text, false))
            {
                WorkbookPart workbookPart = ssd.WorkbookPart;
                // Sheet sheet = workbookPart.Workbook.Descendants<Sheet>().FirstOrDefault();


                Sheet sheet = workbookPart.Workbook.Descendants <Sheet>().Where(s => s.Name == textBoxSheetNameMasterData.Text).FirstOrDefault();

                // Throw an exception if there is no sheet.
                if (sheet == null)
                {
                    MessageBox.Show("Text Box Sheet Name Master Data is invalid: Sheet " + textBoxSheetNameMasterData.Text + " does not exist!");
                    return(null);
                }

                WorksheetPart wsPart = workbookPart.GetPartById(sheet.Id) as WorksheetPart;

                if (wsPart == null)
                {
                    MessageBox.Show("No WorksheetPart Found!");
                    return(null);
                }


                int countNullValues = 0;

                for (int i = int.Parse(textBoxRowFromMasterData.Text) - 1; i < int.Parse(textBoxRowToMasterData.Text); i++)
                {
                    Application.DoEvents();
                    Cell cellArticleNumber = wsPart.Worksheet.Descendants <Cell>().
                                             Where(c => c.CellReference == (textBoxArticleNumberColumnMasterData.Text + i)).FirstOrDefault();

                    if (cellArticleNumber == null)
                    {
                        countNullValues++;
                    }
                    else
                    {
                        countNullValues = 0;
                    }

                    if (countNullValues == 20)
                    {
                        break;
                    }

                    Cell cellLength = wsPart.Worksheet.Descendants <Cell>().
                                      Where(c => c.CellReference == (textBoxLengthColumn.Text + i)).FirstOrDefault();

                    Cell cellWidth = wsPart.Worksheet.Descendants <Cell>().
                                     Where(c => c.CellReference == (textBoxWidthColumn.Text + i)).FirstOrDefault();

                    Cell cellThickness = wsPart.Worksheet.Descendants <Cell>().
                                         Where(c => c.CellReference == (textBoxThicknesColumn.Text + i)).FirstOrDefault();

                    if (cellArticleNumber != null)
                    {
                        MasterDataLine masterDataLine = new MasterDataLine();

                        string artNr = GetCellValue(cellArticleNumber);

                        if (!string.IsNullOrWhiteSpace(artNr))
                        {
                            if (masterData.ContainsKey(artNr.ToUpper()))
                            {
                                MessageBox.Show("The Article Number " + artNr + " occures more than once!");
                            }

                            masterDataLine.ArtikelNr = artNr;

                            double d = 0;

                            if (cellLength != null)
                            {
                                double.TryParse(GetCellValue(cellLength), NumberStyles.Number, CultureInfo.CreateSpecificCulture("en-US"), out d);
                                masterDataLine.Length = d;
                            }

                            if (cellWidth != null)
                            {
                                double.TryParse(GetCellValue(cellWidth), NumberStyles.Number, CultureInfo.CreateSpecificCulture("en-US"), out d);
                                masterDataLine.Width = d;
                            }

                            if (cellThickness != null)
                            {
                                double.TryParse(GetCellValue(cellThickness), NumberStyles.Number, CultureInfo.CreateSpecificCulture("en-US"), out d);
                                masterDataLine.Thickness = d;
                            }

                            masterData[masterDataLine.ArtikelNr.ToUpper()] = masterDataLine;
                        }
                    }
                }
            }
            return(masterData);
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            // Initialize values
            // Assumption look for 5 nearest coordinates/events
            int      NumOfNearestEvents = 5;
            DataSeed DataSeed           = new DataSeed();

            // Generate Data
            List <Coordinate> CoordinatesList = new List <Coordinate>();

            CoordinatesList = DataSeed.GenerateData();

            // Get location points
            Console.Write("Please Input Coordinates:");
            string inputCoordinates = Console.ReadLine();

            // Parse location

            string PointX       = null;
            string PointY       = null;
            int    TargetPointX = 0;
            int    TargetPointY = 0;

            try {
                string[] splitedCoordinates = inputCoordinates.Split(',');
                PointX       = (string)splitedCoordinates.GetValue(0);
                PointY       = (string)splitedCoordinates.GetValue(1);
                TargetPointX = Int32.Parse(PointX);
                TargetPointY = Int32.Parse(PointY);

                if (CoordinatesList.Count != 0)
                {
                    foreach (var coordinate in CoordinatesList)
                    {
                        coordinate.CalculateDistance(TargetPointX, TargetPointY);
                    }
                }
                else
                {
                    Console.WriteLine("String could not be parsed.");
                }
            }

            catch (Exception)
            {
                Console.WriteLine("Wrong data or data format.\n Use format: 7,1");
                Console.WriteLine("Using default values for coordinates " +
                                  "x:{0} and y:{1}", TargetPointX, TargetPointY);
            }



            // Sort Coordinates
            CoordinatesList.Sort((p, q) => p.Distance1.CompareTo(q.Distance1));

            // Get nearest Coordinates
            List <Coordinate> NearestCoordinates = CoordinatesList.GetRange(0, NumOfNearestEvents);

            foreach (var nearestCoordinate in NearestCoordinates)
            {
                // Get all tickets for the event
                List <Ticket> Tickets = nearestCoordinate.ViagogoEvent1.TicketsList1;
                // Sort Tickets
                Tickets.Sort((p, q) => p.Price.CompareTo(q.Price));
                // Display Event Id
                Console.Write(" Event {0:000} - ", nearestCoordinate.ViagogoEvent1.Id1);
                // Display Cheapest Ticket
                if (Tickets.Count == 0)
                {
                    Console.Write("No tickets for the event");
                }
                else
                {
                    Console.Write(Tickets[0].Price.ToString("C", CultureInfo.CreateSpecificCulture("en-US")));
                }

                //Display Distance
                Console.WriteLine(", Distance {0}", nearestCoordinate.Distance1);
            }
        }
Exemplo n.º 12
0
 /// <summary>
 /// Sets the culture info.
 /// </summary>
 /// <param name="selectedLanguage">The selected language.</param>
 public static void SetCultureInfo(string selectedLanguage)
 {
     Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture(selectedLanguage);
     Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedLanguage);
 }
Exemplo n.º 13
0
    public string ObtenerProdDatos(string contextKey)
    {
        // strParams[0] - Producto ID
        // strParams[1] - Usuario Ventas
        // strParams[2] - Usuario Compras
        // strParams[3] - Nombre
        // strParams[4] - Imagen Principal
        // strParams[5] - Código
        // strParams[6] - Esconder precios
        // strParams[7] - Sales
        string[]        strParms      = contextKey.Split('~');
        CProducto_Datos objProd_Datos = new CProducto_Datos();

        objProd_Datos.intProductoID = int.Parse(strParms[0]);
        objProd_Datos.Leer();
        StringBuilder strTemp = new StringBuilder();

        strTemp.Append("<br/><br/><br/><br/><br/><br/><br/><table style='border-collapse: collapse;overflow:hidden; word-wrap:break-word;'>" +
                       "<tr><td style='width:50px'></td><td style='width:50px'></td><td style='width:50px'></td><td style='width:50px'></td><td style='width:50px'></td><td style='width:50px'></td></tr>" +
                       "<tr style='height:130px'><td class='CellInfoB' colspan='4' valign='middle' align='center' style='height:130px'>");
        if (!string.IsNullOrEmpty(strParms[4]))
        {
            strTemp.Append("<img src='../fotos/" + strParms[4] + "' height='100%'>");
        }
        else
        {
            strTemp.Append("No image");
        }
        strTemp.Append("</td><td class='CellInfoB' colspan='4' valign='middle' align='left' style='height:130px'>" +
                       strParms[3] +
                       "<br/><br/>" +
                       strParms[7] +
                       "<br/><br/>" +
                       "Código: " + strParms[5] + "<br/>" +
                       "Existencia: " + objProd_Datos.dcmExistencia.Value.ToString("0.##") +
                       "</td></tr>");
        strTemp.Append("<tr style='height:80px'><td class='CellInfo' colspan='3' style='height:80px' valign='middle' align='left'>");

        if (strParms[6].Equals("0") && strParms[1].Equals("1"))
        {
            if ((objProd_Datos.intFacturaID.HasValue || objProd_Datos.intNotaID.HasValue) && strParms[1].Equals("1"))
            {
                if (objProd_Datos.intFacturaID.HasValue && objProd_Datos.intNotaID.HasValue)
                {
                    if (objProd_Datos.dtFactura_fecha >= objProd_Datos.dtNota_fecha)
                    {
                        strTemp.Append("Precio: " + objProd_Datos.dcmFactura_costo.Value.ToString("c") + "<br/>");
                    }
                    else
                    {
                        strTemp.Append("Precio: " + objProd_Datos.dcmNota_costo.Value.ToString("c") + "<br/>");
                    }
                }
                else
                if (objProd_Datos.intFacturaID.HasValue)
                {
                    strTemp.Append("Precio: " + objProd_Datos.dcmFactura_costo.Value.ToString("c") + "<br/>");
                }
                else
                {
                    strTemp.Append("Precio: " + objProd_Datos.dcmNota_costo.Value.ToString("c") + "<br/>");
                }
            }
            else
            {
                strTemp.Append("Precio: $0.00<br/>");
            }
            if (objProd_Datos.dcmVenta_promedio.HasValue)
            {
                strTemp.Append("Precio promedio: " + objProd_Datos.dcmVenta_promedio.Value.ToString("c"));
            }
            else
            {
                strTemp.Append("Precio promedio: $0.00");
            }
        }

        strTemp.Append("</td><td class='CellInfo' colspan='3' style='height:80px' valign='middle' align='left'>");

        if (strParms[6].Equals("0") && strParms[2].Equals("1"))
        {
            if (objProd_Datos.intCompraID.HasValue)
            {
                strTemp.Append("Costo: " + objProd_Datos.dcmCompra_costo.Value.ToString("c") + "<br/>");
            }
            else
            {
                strTemp.Append("Costo: $0.00<br/>");
            }
            if (objProd_Datos.dcmCompra_promedio.HasValue)
            {
                strTemp.Append("Costo promedio: " + objProd_Datos.dcmCompra_promedio.Value.ToString("c"));
            }
            else
            {
                strTemp.Append("Costo promedio: $0.00");
            }
            if (objProd_Datos.dtCompra_fecha.HasValue)
            {
                strTemp.Append("<br/>Últ. compra: " +
                               objProd_Datos.dtCompra_fecha.Value.ToString("dd/MMM/yyyy", CultureInfo.CreateSpecificCulture("es-MX")).ToUpper());
            }

            string strQuery = "SELECT 1" +
                              " FROM precios P" +
                              " INNER JOIN proveedores V" +
                              " ON V.lista_precios_ID = P.lista_precios_ID" +
                              " AND P.producto_ID = " + strParms[0] +
                              " AND V.cobra_paqueteria = 1" +
                              " LIMIT 1";
            DataSet objDataResult = CComunDB.CCommun.Ejecutar_SP(strQuery);
            if (objDataResult.Tables[0].Rows.Count > 0)
            {
                strTemp.Append("<br/>Cobra Paq: Sí");
            }
            else
            {
                strTemp.Append("<br/>Cobra Paq: No");
            }
        }

        strTemp.Append("</td></tr>" +
                       "</table>");

        return(strTemp.ToString());
    }
Exemplo n.º 14
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            if (date == null || date == DateTimeOffset.MinValue)
            {
                yield return(new ValidationResult("Tanggal harus diisi", new List <string> {
                    "date"
                }));
            }
            else if (!string.IsNullOrWhiteSpace(unit) && !string.IsNullOrWhiteSpace(storage))
            {
                IGarmentStockOpnameFacade _facade = validationContext.GetService <IGarmentStockOpnameFacade>();
                var lastData = _facade.GetLastDataByUnitStorage(unit, storage);
                if (lastData != null)
                {
                    if (date <= lastData.Date)
                    {
                        IdentityService _identityService = validationContext.GetService <IdentityService>();
                        yield return(new ValidationResult("Tanggal harus lebih dari " + lastData.Date.ToOffset(new TimeSpan(_identityService.TimezoneOffset, 0, 0)).ToString("dd MMMM yyyy", CultureInfo.CreateSpecificCulture("id-ID")), new List <string> {
                            "date"
                        }));
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(unit))
            {
                yield return(new ValidationResult("Unit harus diisi", new List <string> {
                    "unit"
                }));
            }

            if (string.IsNullOrWhiteSpace(storage))
            {
                yield return(new ValidationResult("Storage harus diisi", new List <string> {
                    "storage"
                }));
            }
        }
Exemplo n.º 15
0
        static Boolean exportFile(List <Hashtable> sourceFileHashList, string outputPath)
        {
            try
            {
                //create file
                Hashtable bofHash         = sourceFileHashList[0];
                string    format          = "ddd MMM dd HH:mm:ss yyyy";
                string    format1         = "yyyy/MM/dd HH:mm:ss";
                string    titleTimeString = "";
                string    startTimeString = "";
                string    stopTimeString  = "";
                DateTime  outputTime      = DateTime.Now;
                int       siteCount       = 0;
                //time
                if (bofHash["Start Date/Time"] != null)
                {
                    titleTimeString = Convert.ToString(bofHash["Start Date/Time"]);
                    startTimeString = Convert.ToString(bofHash["Start Date/Time"]);
                    stopTimeString  = Convert.ToString(bofHash["Stop Date/Time"]);
                }
                else
                {
                    titleTimeString = Convert.ToString(bofHash["Stop Date/Time"]);
                    stopTimeString  = Convert.ToString(bofHash["Stop Date/Time"]);
                }

                //siteCount
                if (bofHash["SITE NUM"] != null)
                {
                    siteCount = Convert.ToInt32(bofHash["SITE NUM"]);
                }

                if (DateTime.TryParseExact(titleTimeString, format, CultureInfo.CreateSpecificCulture("en-US"),
                                           System.Globalization.DateTimeStyles.None, out outputTime))
                {
                    titleTimeString = outputTime.ToString("yyyyMMddHHmmss");
                    if (startTimeString != "")
                    {
                        startTimeString = DateTime.ParseExact(startTimeString, format, CultureInfo.CreateSpecificCulture("en-US")).ToString("yyyy/MM/dd HH:mm:ss");
                    }
                    if (stopTimeString != "")
                    {
                        stopTimeString = DateTime.ParseExact(stopTimeString, format, CultureInfo.CreateSpecificCulture("en-US")).ToString("yyyy/MM/dd HH:mm:ss");
                    }
                }
                else
                {
                    outputTime      = DateTime.ParseExact(titleTimeString, format1, CultureInfo.CreateSpecificCulture("en-US"));
                    titleTimeString = outputTime.ToString("yyyyMMddHHmmss");
                    if (startTimeString != "")
                    {
                        startTimeString = DateTime.ParseExact(startTimeString, format1, CultureInfo.CreateSpecificCulture("en-US")).ToString("yyyy/MM/dd HH:mm:ss");
                    }
                    if (stopTimeString != "")
                    {
                        stopTimeString = DateTime.ParseExact(stopTimeString, format1, CultureInfo.CreateSpecificCulture("en-US")).ToString("yyyy/MM/dd HH:mm:ss");
                    }
                }
                //DateTime temp = DateTime.Parse(temp1);

                outputPath = outputPath + bofHash["Spil_lot_no"] + "_" + titleTimeString + "_" + bofHash["Tester"] + "." + bofHash["Stage"] + ".FT";
                using (StreamWriter sw = new StreamWriter(outputPath))
                {
                    //BOF
                    sw.WriteLine("[BOF]");
                    sw.WriteLine("DEVICE ID           :  " + bofHash["Device_Name"]);
                    sw.WriteLine("LOT ID              :  " + bofHash["Spil_lot_no"]);
                    sw.WriteLine("CUSTOMER DEVICE ID  :  " + bofHash["Device_Name"]);
                    sw.WriteLine("CUSTOMER LOT ID     :  " + bofHash["Customer_No"]);
                    sw.WriteLine("STAGE               :  " + bofHash["Stage"]);
                    sw.WriteLine("STEP                :  " + bofHash["Process"]);
                    sw.WriteLine("START TIME          :  " + startTimeString);
                    sw.WriteLine("STOP TIME           :  " + stopTimeString);
                    sw.WriteLine("TEST SITE           :  HS03");
                    sw.WriteLine("TEST BIN            :  " + bofHash["Testbin/all"]);
                    sw.WriteLine("TEST PROGRAM        :  " + bofHash["TestProgram_Name"]);
                    sw.WriteLine("TESTER ID           :  " + bofHash["Tester_ID"]);
                    sw.WriteLine("HANDLER ID          :  " + bofHash["Prober/handler"]);
                    sw.WriteLine("LOAD BOARD ID       :  " + bofHash["ProbeCard/FixBoard"]);
                    sw.WriteLine("SITE NUM            :  " + bofHash["SITE NUM"]);
                    sw.WriteLine("ADAPTOR ID          :  ");
                    sw.WriteLine("TOP SOCKET ID       :  " + bofHash["Socket_No"]);
                    sw.WriteLine("SOCKET ID           :  " + bofHash["Socket_No"]);
                    sw.WriteLine("CHANGE KIT ID       :  ");
                    sw.WriteLine("TEST VERSION        :  ");
                    sw.WriteLine("TEMPERATURE         :  " + bofHash["Temperature"]);
                    sw.WriteLine("SOFTWARE VERSION    :  ");
                    sw.WriteLine("SOAK TIME           :  ");
                    sw.WriteLine("TECH ID             :  " + bofHash["OP_id"]);
                    sw.WriteLine("TESTED DIE          :  " + bofHash["TESTED DIE"]);
                    sw.WriteLine("PASS DIE            :  " + bofHash["PASS DIE"]);
                    sw.WriteLine("YIELD               :  " + bofHash["YIELD"]);
                    sw.WriteLine("");
                    //BOF end
                    //Soft bin
                    sw.WriteLine("[SOFT BIN]");
                    string siteString = "";
                    for (int i = 0; i < siteCount; i++)
                    {
                        siteString += String.Format("{0,8},", "SITE" + i + "");
                    }
                    sw.WriteLine(String.Format("{0,12},{1,8},{2,8},{3,8},{4,8},{5}{6},{7}",
                                               "SW_BIN", "HW_BIN", "NUMBER", "YIELD", "TYPE", siteString, "SW_DESCRIPTION", "HW_DESCRIPTION"));
                    for (int i = 1; i < sourceFileHashList.Count; i++)
                    {
                        Hashtable currentHT = sourceFileHashList[i];
                        siteString = "";
                        string s = Convert.ToString(currentHT["DESCRIPTION"]);
                        for (int j = 0; j < siteCount; j++)
                        {
                            siteString += String.Format("{0,8},", Convert.ToString(currentHT["site" + j]));
                        }
                        sw.WriteLine(String.Format("{0,12},{1,8},{2,8},{3,8},{4,8},{5}{6}{7}{8},{9}{10}{11}"
                                                   , currentHT["SW_BIN"], currentHT["HW_BIN"], currentHT["NUMBER"], currentHT["YIELD"], currentHT["TYPE"]
                                                   , siteString, "{[", s.Substring(0, Math.Min(s.Length, 100)), "]}", "{[", s.Substring(0, Math.Min(s.Length, 100)), "]}"));
                    }
                    sw.WriteLine("");
                    //Soft bin end

                    sw.WriteLine("[EXTENSION]");
                    sw.WriteLine("");
                    sw.WriteLine("[EOF]");
                    sw.WriteLine("");
                }
            }
            catch (Exception e)
            {
                return(false);
            }
            return(true);
        }
Exemplo n.º 16
0
        public uc_Excel_ErroriRilevatiRiepilogo()
        {
            CultureInfo culture = CultureInfo.CreateSpecificCulture("it-IT");

            InitializeComponent();
        }
Exemplo n.º 17
0
        public void LocaleTest()
        {
            string actual = "A STRING".HeaderCase(CultureInfo.CreateSpecificCulture("tr"));

            Assert.AreEqual("A-Strıng", actual);
        }
Exemplo n.º 18
0
        public static void RunBotWithParameters(Action <ISession, StatisticsAggregator> onBotStarted, string[] args)
        {
            var ioc = TinyIoC.TinyIoCContainer.Current;

            //Setup Logger for API
            APIConfiguration.Logger = new APILogListener();

            //Application.EnableVisualStyles();
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2 Loading";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    _ignoreKillSwitch = false;
                    break;

                case "false":
                    _ignoreKillSwitch = true;
                    break;
                }
            }

            bool excelConfigAllow = false;

            if (commandLine["provider"] != null && commandLine["provider"] == "excel")
            {
                excelConfigAllow = true;
            }

            //
            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");
            var excelConfigFile   = Path.Combine(profileConfigPath, "config.xlsm");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                settings = GlobalSettings.Load(_subPath, _enableJsonValidation);
                if (excelConfigAllow)
                {
                    if (!File.Exists(excelConfigFile))
                    {
                        Logger.Write(
                            "Migrating existing json confix to excel config, please check the config.xlsm in your config folder"
                            );

                        ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                    }
                    else
                    {
                        settings = ExcelConfigHelper.ReadExcel(settings, excelConfigFile);
                    }

                    Logger.Write("Bot will run with your excel config, loading excel config");
                }
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }
            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var options = new Options();

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                // Values are available here
                if (options.Init)
                {
                    settings.GenerateAccount(options.IsGoogle, options.Template, options.Start, options.End, options.Password);
                }
            }
            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    //If lastcoord is snipe coord, bot start from default location

                    if (LocationUtils.CalculateDistanceInMeters(lat, lng, settings.LocationConfig.DefaultLatitude, settings.LocationConfig.DefaultLongitude) < 2000)
                    {
                        settings.LocationConfig.DefaultLatitude  = lat;
                        settings.LocationConfig.DefaultLongitude = lng;
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            if (!_ignoreKillSwitch)
            {
                if (CheckMKillSwitch() || CheckKillSwitch())
                {
                    return;
                }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            TinyIoC.TinyIoCContainer.Current.Register <ITranslation>(translation);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    )
                                .OrderBy(pt => pt.Distance)
                                .FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }
            IElevationService elevationService = new ElevationService(settings);

            //validation auth.config
            if (boolNeedsSetup)
            {
                AuthAPIForm form = new AuthAPIForm(true);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    settings.Auth.APIConfig = form.Config;
                }
            }
            else
            {
                var apiCfg = settings.Auth.APIConfig;

                if (apiCfg.UsePogoDevAPI)
                {
                    if (string.IsNullOrEmpty(apiCfg.AuthAPIKey))
                    {
                        Logger.Write(
                            "You have selected PogoDev API but you have not provided an API Key, please press any key to exit and correct you auth.json, \r\n The Pogodev API key can be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer",
                            LogLevel.Error
                            );

                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                    try
                    {
                        HttpClient client = new HttpClient();
                        client.DefaultRequestHeaders.Add("X-AuthToken", apiCfg.AuthAPIKey);
                        var maskedKey = apiCfg.AuthAPIKey.Substring(0, 4) + "".PadLeft(apiCfg.AuthAPIKey.Length - 8, 'X') + apiCfg.AuthAPIKey.Substring(apiCfg.AuthAPIKey.Length - 4, 4);
                        HttpResponseMessage response = client.PostAsync("https://pokehash.buddyauth.com/api/v133_1/hash", null).Result;

                        string   AuthKey             = response.Headers.GetValues("X-AuthToken").FirstOrDefault();
                        string   MaxRequestCount     = response.Headers.GetValues("X-MaxRequestCount").FirstOrDefault();
                        DateTime AuthTokenExpiration = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(Convert.ToDouble(response.Headers.GetValues("X-AuthTokenExpiration").FirstOrDefault()));
                        TimeSpan Expiration          = AuthTokenExpiration - DateTime.UtcNow;
                        string   Result = $"Key: {maskedKey} RPM: {MaxRequestCount} Expiration Date: {AuthTokenExpiration.Month}/{AuthTokenExpiration.Day}/{AuthTokenExpiration.Year} ({Expiration.Days} Days {Expiration.Hours} Hours {Expiration.Minutes} Minutes)";
                        Logger.Write(Result, LogLevel.Info, ConsoleColor.Green);
                        AuthKey         = null;
                        MaxRequestCount = null;
                        Expiration      = new TimeSpan();
                        Result          = null;
                    }
                    catch
                    {
                        Logger.Write("The HashKey is invalid or has expired, please press any key to exit and correct you auth.json, \r\n The Pogodev API key can be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer", LogLevel.Error);
                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                }
                else if (apiCfg.UseLegacyAPI)
                {
                    Logger.Write(
                        "You bot will start after 15 seconds, You are running bot with Legacy API (0.45), but it will increase your risk of being banned and triggering captchas. Config Captchas in config.json to auto-resolve them",
                        LogLevel.Warning
                        );

#if RELEASE
                    Thread.Sleep(15000);
#endif
                }
                else
                {
                    Logger.Write(
                        "At least 1 authentication method must be selected, please correct your auth.json.",
                        LogLevel.Error
                        );
                    Console.ReadKey();
                    Environment.Exit(0);
                }
            }

            _session = new Session(settings,
                                   new ClientSettings(settings, elevationService), logicSettings, elevationService,
                                   translation
                                   );
            ioc.Register <ISession>(_session);

            Logger.SetLoggerContext(_session);

            MultiAccountManager accountManager = new MultiAccountManager(settings, logicSettings.Bots);
            ioc.Register(accountManager);

            if (boolNeedsSetup)
            {
                StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile);
                if (configForm.ShowDialog() == DialogResult.OK)
                {
                    var fileName = Assembly.GetEntryAssembly().Location;

                    Process.Start(fileName);
                    Environment.Exit(0);
                }

                //if (GlobalSettings.PromptForSetup(_session.Translation))
                //{
                //    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                //    var fileName = Assembly.GetExecutingAssembly().Location;
                //    Process.Start(fileName);
                //    Environment.Exit(0);
                //}
                else
                {
                    GlobalSettings.Load(_subPath, _enableJsonValidation);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = _session.RuntimeStatistics;

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);
            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);
            onBotStarted?.Invoke(_session, aggregator);

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();
            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (session, lat, lng, speed) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng, Speed = speed
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += LoadSaveState.SaveLocationToDisk;

            ProgressBar.Fill(100);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            var bot = accountManager.GetStartUpAccount();

            _session.ReInitSessionWithNextBot(bot);

            machine.AsyncStart(new VersionCheckState(), _session, _subPath, excelConfigAllow);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            Logger.Write(
                $"(Start-Up Stats) User: {bot.Username} | XP: {bot.CurrentXp} | SD: {bot.Stardust}",
                LogLevel.Info, ConsoleColor
                .Magenta
                );

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.EnableHumanWalkingSnipe &&
                _session.LogicSettings.HumanWalkingSnipeUseFastPokemap)
            {
                HumanWalkSnipeTask.StartFastPokemapAsync(_session,
                                                         _session.CancellationTokenSource.Token).ConfigureAwait(false); // that need to keep data live
            }

            if (_session.LogicSettings.UseSnipeLocationServer ||
                _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }


            if (_session.LogicSettings.DataSharingConfig.EnableSyncData)
            {
                BotDataSocketClient.StartAsync(_session, Properties.Resources.EncryptKey);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, certificate, chain, sslPolicyErrors) => true;
                //temporary disable MSniper connection because site under attacking.
                //MSniperServiceTask.ConnectToService();
                //_session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }

            // jjskuld - Don't await the analytics service since it starts a worker thread that never returns.
#pragma warning disable 4014
            _session.AnalyticsService.StartAsync(_session, _session.CancellationTokenSource.Token);
#pragma warning restore 4014
            _session.EventDispatcher.EventReceived += evt => AnalyticsService.Listen(evt, _session);

            var trackFile = Path.GetTempPath() + "\\necrobot2.io";

            if (!File.Exists(trackFile) || File.GetLastWriteTime(trackFile) < DateTime.Now.AddDays(-1))
            {
                Thread.Sleep(10000);
                Thread mThread = new Thread(delegate()
                {
                    var infoForm = new InfoForm();
                    infoForm.ShowDialog();
                });
                File.WriteAllText(trackFile, DateTime.Now.Ticks.ToString());
                mThread.SetApartmentState(ApartmentState.STA);

                mThread.Start();
            }

            QuitEvent.WaitOne();
        }
 private void AboutForm_Load(object sender, EventArgs e)
 {
     lVersion.Text   += Common.VersionString;
     lBuildDate.Text += DateTime.Parse(Properties.Resources.BuildDate).ToString("dddd, MMMM d, yyyy", CultureInfo.CreateSpecificCulture("en-US"));
 }
Exemplo n.º 20
0
        static void Main(string[] args)
        {
            var culture         = CultureInfo.CreateSpecificCulture("en-us");
            var resourceManager = new ResourceManager("CodeBlogFitness.CMD.Languages.Messages", typeof(Program).Assembly);

            Console.WriteLine(resourceManager.GetString("Hello", culture));
            Console.WriteLine(resourceManager.GetString("EnterName", culture));
            var name               = Console.ReadLine();
            var userController     = new UserController(name);
            var eatingController   = new EatingController(userController.CurrentUser);
            var exerciseController = new ExerciseController(userController.CurrentUser);

            if (userController.IsNewUser)
            {
                Console.Write("Введите пол: ");
                var    gender    = Console.ReadLine();
                var    birthDate = ParseDateTime("дату рождения");
                double weight    = ParseDouble("вес");
                double height    = ParseDouble("рост");

                userController.SetNewUserData(gender, birthDate, weight, height);
            }
            Console.WriteLine(userController.CurrentUser);

            while (true)
            {
                Console.WriteLine("Что вы хотите сделать?");
                Console.WriteLine("Е - ввести прием пищи");
                Console.WriteLine("A - ввести упражнение");
                Console.WriteLine("Q - выход");
                var key = Console.ReadKey();
                Console.WriteLine();
                switch (key.Key)
                {
                case ConsoleKey.E:
                {
                    var foods = EnterEating();
                    eatingController.Add(foods.Food, foods.Weight);

                    foreach (var item in eatingController.Eating.Foods)
                    {
                        Console.WriteLine($"\t{item.Key} - {item.Value}");
                    }
                    break;
                }

                case ConsoleKey.A:
                {
                    var exe = EnterExercise();
                    exerciseController.Add(exe.Activity, exe.Begin, exe.End);

                    foreach (var item in exerciseController.Exercises)
                    {
                        Console.WriteLine($"\t{item.Activity} с {item.Start.ToShortTimeString()} до {item.Finish.ToShortTimeString()}");
                    }
                    break;
                }

                case ConsoleKey.Q:
                {
                    Environment.Exit(0);
                    break;
                }
                }
                Console.ReadLine();
            }
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            string input;
            double a, b, c, d;



            Console.WriteLine("Welcome, please enter your first currency amount here:");
            input = Console.ReadLine();
            a     = Convert.ToDouble(input);

            b = Convert.ToDouble(input);
            Console.WriteLine("Thank you, now please enter your second currency amount here:");
            Console.ReadLine();


            Console.WriteLine("Thanks again (last one, now please enter your third currency amount here:");
            input = Console.ReadLine();
            c     = Convert.ToDouble(input);

            Console.WriteLine("The total amount of your currencies is: " + (a + b + c));

            d = (a + b + c);


            Console.WriteLine("The average amount of your currencies is: " + Math.Round(d / 3));



            double[] input2 = { a, b, c };

            double lowest  = input2.Min();
            double highest = input2.Max();

            Console.OutputEncoding = System.Text.Encoding.UTF8;
            CultureInfo.CreateSpecificCulture("da-DK");


            Console.WriteLine("The smallest currency amount you have entered is: " + lowest);
            Console.WriteLine("The highest currency amount you have entered is: " + highest);

            Console.WriteLine("The total amount of currency you have entered in USD (United States Dollar) is: $" + d.ToString("n2"));
            d = Convert.ToInt32(d);
            Console.WriteLine("The total amount of currency you have entered in SEK (Swedish Krona) is: " + d.ToString("C3",
                                                                                                                       CultureInfo.CreateSpecificCulture("da-DK")));
            d = Convert.ToInt32(d);
            Console.WriteLine("The total amount of currency you have entered in YEN (Japanese Yen) is: ¥" + d);
            Console.WriteLine("The total amount of currency you have entered in THB (Thai Baht) is: ฿" + d.ToString("n2"));



            Console.ReadLine();
        }
Exemplo n.º 22
0
 private void tabPage6_Enter(object sender, EventArgs e)
 {
     DepenseStatsBindingSource.DataSource = from uneDepense in dataContext.Depenses.Where(v => v.DateDepense.Year == DateTime.Now.Year)
                                            select new
     {
         idAbonnement = uneDepense.IdAbonnement,
         montant      = uneDepense.Montant,
         Mois         = recevoirMoisAvecMaj(uneDepense.DateDepense.ToString("MMMM", CultureInfo.CreateSpecificCulture("fr")))
     };
     this.reportViewer6.RefreshReport();
 }
Exemplo n.º 23
0
        public List <CotacaoMoedaEntidade> Cotar()
        {
            List <CotacaoMoedaEntidade> lista = new List <CotacaoMoedaEntidade>();

            try
            {
                DolarRealEntidade retorno = Cotar("https://api.vitortec.com/currency/converter/v1.2/?from=USD&to=BRL&value=1");
                lista.Add(CriarRegistroRetorno(TipoCrypto.Real, Convert.ToDouble(retorno.data.resultSimple, CultureInfo.CreateSpecificCulture("en-US"))));
            }
            catch
            {
                lista.Add(CriarRegistroRetorno(TipoCrypto.Real, 3.3));
            }
            return(lista);
        }
Exemplo n.º 24
0
 private void tabPage2_Enter(object sender, EventArgs e)
 {
     AbonneStatsBindingSource.DataSource = from unAbonnement in dataContext.Abonnements.Where(v => v.DateAbonnement.Year == DateTime.Now.Year)
                                           select new
     {
         nbAbonnee      = 1,
         typeAbonnement = recevoirDescriptionAbonnement(unAbonnement.NoTypeAbonnement),
         Mois           = recevoirMoisAvecMaj(unAbonnement.DateAbonnement.ToString("MMMM", CultureInfo.CreateSpecificCulture("fr")))
     };
     this.reportViewer2.RefreshReport();
 }
Exemplo n.º 25
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //if (selectedLanguage == "en-US")
        //{
        //    gvDataGrid.PagerSettings.FirstPageText = "<< First";
        //    gvDataGrid.PagerSettings.PreviousPageText = "< Previous ";
        //    gvDataGrid.PagerSettings.NextPageText = " Next >";
        //    gvDataGrid.PagerSettings.LastPageText = "Last >>";
        //}
        //else
        //{
        //    gvDataGrid.PagerSettings.FirstPageText = "<< diyige";
        //    gvDataGrid.PagerSettings.PreviousPageText = "< shangyige ";
        //    gvDataGrid.PagerSettings.NextPageText = " xiayege >";
        //    gvDataGrid.PagerSettings.LastPageText = "zuihou >>";
        //}

        //if(gvDataGrid.PageIndex == 0)
        //{

        //}


        if (!Page.IsPostBack)
        {
            string selectedLanguage = "en-US";
            //string selectedLanguage = "zh-CN";



            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(selectedLanguage);
            Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture(selectedLanguage);

            //LoadEntityTypeList();
            //GetAllEntities();

            LoadEntityTypeList();
            GetAllEntities();
            ViewState["Language"] = CultureInfo.CurrentUICulture.Name;



            //if (CultureInfo.CurrentUICulture.Name == "en-US")
            //{
            //    gvDataGrid.PagerSettings.FirstPageText = "<< First";
            //}
            //else
            //{
            //    gvDataGrid.PagerSettings.FirstPageText = "<< diyige";
            //}

            //ViewState.Add("Language", CultureInfo.CurrentUICulture.Name);
        }
        //else
        //{

        //    if (CultureInfo.CurrentUICulture.Name != ViewState["Language"].ToString())
        //    {
        //        LoadEntityTypeList();
        //        GetAllEntities();
        //        ViewState["Language"] = CultureInfo.CurrentUICulture.Name;
        //    }
        //}
    }
Exemplo n.º 26
0
 private void tabPage4_Enter(object sender, EventArgs e)
 {
     PartiesJoueesStatsBindingSource.DataSource = from unePartieJouee in dataContext.PartiesJouees.Where(v => v.DatePartie.Year == DateTime.Now.Year)
                                                  select new
     {
         idAbonnement = unePartieJouee.IdAbonnement,
         nomTerrain   = recevoirTerrain(unePartieJouee.NoTerrain),
         Mois         = recevoirMoisAvecMaj(unePartieJouee.DatePartie.ToString("MMMM", CultureInfo.CreateSpecificCulture("fr")))
     };
     this.reportViewer4.RefreshReport();
 }
Exemplo n.º 27
0
        private void LocalizedContentManager_OnLanguageChange(LanguageCode code)
        {
            String cultureString = code.ToString();

            SpecificCulture = CultureInfo.CreateSpecificCulture(cultureString);
        }
Exemplo n.º 28
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            listAkun = GetListAllDataDataAkun();
            DateTime tgl_from = Convert.ToDateTime(this.tanggal_From.Value);
            DateTime tgl_to   = Convert.ToDateTime(this.tanggal_To.Value);

            if (listAkun != null && listAkun.Any())
            {
                try
                {
                    Excel.Application app = new Excel.Application();

                    Excel.Workbook book = app.Workbooks.Add();

                    Excel.Worksheet sheet = book.ActiveSheet as Excel.Worksheet;

                    app.Visible     = true;
                    app.WindowState = Excel.XlWindowState.xlMaximized;

                    int barisHeader = 3;
                    sheet.Cells[1, 1]           = "Data Laporan Periode " + tgl_from.ToString("dd/MM/yyy") + " Sampai " + tgl_to.ToString("dd/MM/yyy");
                    sheet.Cells[barisHeader, 1] = "Nomor";
                    sheet.Cells[barisHeader, 2] = "Kode";
                    sheet.Cells[barisHeader, 3] = "Tanggal";
                    sheet.Cells[barisHeader, 4] = "NamaTransaksi";
                    sheet.Cells[barisHeader, 5] = "Harga";
                    sheet.Range[$"A{barisHeader}", $"E{barisHeader}"].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                    sheet.Range[$"A{barisHeader}", $"E{barisHeader}"].Font.Bold           = true;
                    int     sum = 0;
                    decimal nominalrupiah;
                    string  harga;
                    int     baris = 4;
                    for (int i = 0; i < listAkun.Count; i++)
                    {
                        nominalrupiah         = decimal.Parse(listAkun[i].Jumlah.ToString());
                        harga                 = nominalrupiah.ToString("C", CultureInfo.CreateSpecificCulture("id-ID"));
                        sheet.Cells[baris, 1] = i + 1;
                        sheet.Cells[baris, 1].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                        sheet.Cells[baris, 2] = listAkun[i].NomorAkun + " - " + listAkun[i].NomorSubAkun;
                        sheet.Cells[baris, 3] = listAkun[i].Tanggal;
                        sheet.Cells[baris, 4] = listAkun[i].NamaTransaksi;
                        sheet.Cells[baris, 5] = harga;
                        sum += Convert.ToInt32(listAkun[i].Jumlah);
                        sheet.Cells[baris, 3].EntireColumn.Numberformat = "dd/MM/yyyy";
                        baris++;
                    }
                    harga = sum.ToString("C", CultureInfo.CreateSpecificCulture("id-ID"));
                    sheet.Cells[baris, 5] = harga;
                    sheet.Cells[baris, 1] = "TOTAL SEMUA BIAYA";
                    sheet.Range[$"A{baris}", $"E{baris}"].Font.Bold           = true;
                    sheet.Range[$"A{baris}", $"D{baris}"].MergeCells          = true;
                    sheet.Range[$"A{baris}", $"E{baris}"].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;

                    sheet.Range["A1", "E1"].Font.Bold           = true;
                    sheet.Range["A1", "E1"].MergeCells          = true;
                    sheet.Range["A1", "E1"].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                    sheet.Range[$"A{barisHeader}", $"E{5 + listAkun.Count - 1}"].Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
                    sheet.Columns.AutoFit();
                    sheet.Rows.AutoFit();
                    sheet.Name      = "Laporan";
                    app.UserControl = true;
                    book.Password   = "******";
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
Exemplo n.º 29
0
        private static CookieCollection parseResponse(string value)
        {
            var cookies = new CookieCollection();

            Cookie cookie = null;
            var    pairs  = splitCookieHeaderValue(value);

            for (var i = 0; i < pairs.Length; i++)
            {
                var pair = pairs[i].Trim();
                if (pair.Length == 0)
                {
                    continue;
                }

                if (pair.StartsWith("version", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Version = Int32.Parse(pair.GetValue('=', true));
                    }
                }
                else if (pair.StartsWith("expires", StringComparison.InvariantCultureIgnoreCase))
                {
                    var buff = new StringBuilder(pair.GetValue('='), 32);
                    if (i < pairs.Length - 1)
                    {
                        buff.AppendFormat(", {0}", pairs[++i].Trim());
                    }

                    DateTime expires;
                    if (!DateTime.TryParseExact(
                            buff.ToString(),
                            new[] { "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", "r" },
                            CultureInfo.CreateSpecificCulture("en-US"),
                            DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal,
                            out expires))
                    {
                        expires = DateTime.Now;
                    }

                    if (cookie != null && cookie.Expires == DateTime.MinValue)
                    {
                        cookie.Expires = expires.ToLocalTime();
                    }
                }
                else if (pair.StartsWith("max-age", StringComparison.InvariantCultureIgnoreCase))
                {
                    var max     = Int32.Parse(pair.GetValue('=', true));
                    var expires = DateTime.Now.AddSeconds((double)max);
                    if (cookie != null)
                    {
                        cookie.Expires = expires;
                    }
                }
                else if (pair.StartsWith("path", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Path = pair.GetValue('=');
                    }
                }
                else if (pair.StartsWith("domain", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Domain = pair.GetValue('=');
                    }
                }
                else if (pair.StartsWith("port", StringComparison.InvariantCultureIgnoreCase))
                {
                    var port = pair.Equals("port", StringComparison.InvariantCultureIgnoreCase)
                     ? "\"\""
                     : pair.GetValue('=');

                    if (cookie != null)
                    {
                        cookie.Port = port;
                    }
                }
                else if (pair.StartsWith("comment", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Comment = urlDecode(pair.GetValue('='), Encoding.UTF8);
                    }
                }
                else if (pair.StartsWith("commenturl", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.CommentUri = pair.GetValue('=', true).ToUri();
                    }
                }
                else if (pair.StartsWith("discard", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Discard = true;
                    }
                }
                else if (pair.StartsWith("secure", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.Secure = true;
                    }
                }
                else if (pair.StartsWith("httponly", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (cookie != null)
                    {
                        cookie.HttpOnly = true;
                    }
                }
                else
                {
                    if (cookie != null)
                    {
                        cookies.Add(cookie);
                    }

                    string name;
                    string val = String.Empty;

                    var pos = pair.IndexOf('=');
                    if (pos == -1)
                    {
                        name = pair;
                    }
                    else if (pos == pair.Length - 1)
                    {
                        name = pair.Substring(0, pos).TrimEnd(' ');
                    }
                    else
                    {
                        name = pair.Substring(0, pos).TrimEnd(' ');
                        val  = pair.Substring(pos + 1).TrimStart(' ');
                    }

                    cookie = new Cookie(name, val);
                }
            }

            if (cookie != null)
            {
                cookies.Add(cookie);
            }

            return(cookies);
        }
Exemplo n.º 30
0
        private static int Main(string[] args)
        {
            var isFirstInstance = true;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            // This might fix the SEHException raised sometimes. See issue:
            // https://sourceforge.net/tracker/?func=detail&aid=2335753&group_id=96589&atid=615248
            Application.DoEvents();

            // child threads should impersonate the current windows user
            AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);

            /* setup handler for unhandled exceptions in non-debug modes */
            // Allow exceptions to be unhandled so they break in the debugger
#if !DEBUG
            ApplicationExceptionHandler eh = new ApplicationExceptionHandler();

            AppDomain.CurrentDomain.UnhandledException += eh.OnAppDomainException;
#endif

#if DEBUG && TEST_I18N_THISCULTURE
            Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(new I18NTestCulture().Culture);
            Thread.CurrentThread.CurrentCulture   = Thread.CurrentThread.CurrentUICulture;
#endif

            FormWindowState initialStartupState = Win32.GetStartupWindowState();
            // if you want to debug the minimzed startup (cannot be configured in VS.IDE),
            // comment out the line above and uncomment the next one:
            //FormWindowState initialStartupState =  FormWindowState.Minimized;

            var appInstance            = new RssBanditApplication();
            Action <string[]> callback = appInstance.OnOtherInstance;
            try
            {
                GuiInvoker.Initialize();

                isFirstInstance = ApplicationActivator.LaunchOrReturn(cb => GuiInvoker.Invoke(appInstance.MainForm, () => callback(cb)), args);
            }
            catch (Exception /* ex */)
            {
                //_log.Error(ex); /* other instance is probably still running */
            }
            //_log.Info("Application v" + RssBanditApplication.VersionLong + " started, running instance is " + running);

            RssBanditApplication.StaticInit(appInstance);
            if (isFirstInstance)
            {
                // init to system default:
                RssBanditApplication.SharedCulture   = CultureInfo.CurrentCulture;
                RssBanditApplication.SharedUICulture = CultureInfo.CurrentUICulture;

                if (appInstance.HandleCommandLineArgs(args))
                {
                    if (!string.IsNullOrEmpty(appInstance.CommandLineArgs.LocalCulture))
                    {
                        try
                        {
                            RssBanditApplication.SharedUICulture =
                                CultureInfo.CreateSpecificCulture(appInstance.CommandLineArgs.LocalCulture);
                            RssBanditApplication.SharedCulture = RssBanditApplication.SharedUICulture;
                        }
                        catch (Exception ex)
                        {
                            appInstance.MessageError(String.Format(
                                                         SR.ExceptionProcessCommandlineCulture,
                                                         appInstance.CommandLineArgs.LocalCulture,
                                                         ex.Message));
                        }
                    }

                    // take over customized cultures to current main thread:
                    Thread.CurrentThread.CurrentCulture   = RssBanditApplication.SharedCulture;
                    Thread.CurrentThread.CurrentUICulture = RssBanditApplication.SharedUICulture;

                    if (!appInstance.CommandLineArgs.StartInTaskbarNotificationAreaOnly &&
                        initialStartupState != FormWindowState.Minimized)
                    {
                        // no splash, if start option is tray only or minimized
                        Splash.Show(SR.AppLoadStateLoading, RssBanditApplication.VersionLong);
                    }

                    if (appInstance.Init())
                    {
                        // does also run the windows event loop:
                        appInstance.StartMainGui(initialStartupState);
                        Splash.Close();
                    }
                    else
                    {
                        return(3); // init error
                    }
                    return(0);     // OK
                }
                return(2);         // CommandLine error
            }
            return(1);             // other running instance
        }