//making export from database to csv file
        private async void ExportToCSVFile(object sender, RoutedEventArgs e)
        {
            string dictionary = StringOperation.LanguagesToTable(ChosenDictionary.Text);
            string path       = Path.Combine(ChosenPathText.Text, dictionary + ".csv");

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("Word, Translation");

            DatabaseConnection dbCon = new DatabaseConnection();
            List <string>      words = dbCon.GettingRows(dictionary);

            foreach (string word in words)
            {
                sb.AppendLine(word.Replace(" ➤", ","));
            }

            try
            {
                await folder.GetFileAsync(dictionary + ".csv");
            }
            catch
            {
                await folder.CreateFileAsync(dictionary + ".csv");
            }

            StorageFile csvFile = await folder.GetFileAsync(dictionary + ".csv");

            await FileIO.WriteTextAsync(csvFile, sb.ToString(), Windows.Storage.Streams.UnicodeEncoding.Utf8);
        }
        public void ItShouldPossibleToInvokeStringCompare()
        {
            const string expected =
                @"public System.Int32 Call(System.String par1, System.String par2)
{
  System.Int32 result;
  result = System.String.Compare(par1, par2, CurrentCulture);
  return result;
}";

            var newExpression = Function.Create()
                                .WithParameter <string>("par1")
                                .WithParameter <string>("par2")
                                .WithBody(
                CodeLine.CreateVariable <int>("result"),
                CodeLine.Assign(Operation.Variable("result"), StringOperation.Compare("par1", "par2"))
                )
                                .Returns("result");

            AssertString.AreEqual(expected, newExpression.ToString());

            var lambda = newExpression.ToLambda <Func <string, string, int> >();

            Assert.IsNotNull(lambda);
            var result = lambda("a", "a");

            Assert.AreEqual(0, result);
            result = lambda("a", "b");
            Assert.AreEqual(-1, result);
        }
        public void ItShouldPossibleToInvokeStringFormat()
        {
            const string expected =
                @"public System.String Call(System.String par1, System.String par2)
{
  System.String result;
  result = System.String.Format(""{0}-{1}"", par1, par2);
  return result;
}";

            var newExpression = Function.Create()
                                .WithParameter <string>("par1")
                                .WithParameter <string>("par2")
                                .WithBody(
                CodeLine.CreateVariable <string>("result"),
                CodeLine.Assign(Operation.Variable("result"),
                                StringOperation.Format(
                                    "{0}-{1}",
                                    Operation.Variable("par1"),
                                    Operation.Variable("par2")))
                )
                                .Returns("result");

            AssertString.AreEqual(expected, newExpression.ToString());

            var lambda = newExpression.ToLambda <Func <string, string, string> >();

            Assert.IsNotNull(lambda);
            var result = lambda("a", "b");

            Assert.AreEqual("a-b", result);
        }
        public async Task <IActionResult> ForgotPasswordViaSMS(ForgotPasswordViaEmailViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user == null)
                {
                    model.ModelStateValid = false;
                    ModelState.AddModelError("", $"We can't find an account with email:`{model.Email}`!");
                    return(View(model));
                }
                if (user.PhoneNumberConfirmed == false)
                {
                    model.ModelStateValid = false;
                    ModelState.AddModelError("", "Your account did not bind a valid phone number!");
                    return(View(model));
                }
                var code = StringOperation.RandomString(6);
                user.SMSPasswordResetToken = code;
                await _userManager.UpdateAsync(user);

                await _smsSender.SendAsync(user.PhoneNumber, code + " is your Aiursoft password reset code.");

                return(RedirectToAction(nameof(EnterSMSCode), new { model.Email }));
            }
            return(View(model));
        }
        public void ItShouldPossibleToInvokeToString()
        {
            const string expected =
                @"public System.String Call(System.Int32 par)
{
  System.String result;
  result = par.ToString();
  return result;
}";

            var newExpression = Function.Create()
                                .WithParameter <int>("par")
                                .WithBody(
                CodeLine.CreateVariable <string>("result"),
                CodeLine.Assign(Operation.Variable("result"), StringOperation.ToString("par"))
                )
                                .Returns("result");

            AssertString.AreEqual(expected, newExpression.ToString());

            var lambda = newExpression.ToLambda <Func <int, string> >();

            Assert.IsNotNull(lambda);
            var result = lambda(1);

            Assert.AreEqual("1", result);
        }
Example #6
0
        //translate two string with translate google app
        public async void GTranslateText()
        {
            if (!String.IsNullOrEmpty(ToTranslateText.Text))
            {
                try
                {
                    //erasing white spaces from string thats appear more then one time
                    Regex  regex           = new Regex("[ ]{2,}");
                    string toTranslateText = regex.Replace(ToTranslateText.Text.Trim(), " ");

                    //creating language pair to translation
                    string languagePair = StringOperation.CreatingLangugePair(fromLanguageButton.Content.ToString(), toLanguageButton.Content.ToString());

                    //translation
                    GTranslator translator = new GTranslator(toTranslateText, languagePair);

                    //added translation to textblock
                    TranslatedText.Text  = translator.translation;
                    ToTranslateText.Text = toTranslateText;
                }
                catch
                {
                    //if no internet connection
                    MessageDialog msg = new MessageDialog("You don't have an internet connection!");
                    await msg.ShowAsync();

                    ToTranslateText.Text = "";
                    TranslatedText.Text  = "";
                }
            }
        }
Example #7
0
        //adding words to database
        private async void AddToDatabase(object sender, RoutedEventArgs e)
        {
            if (!String.IsNullOrEmpty(TranslatedText.Text))
            {
                string [] words = { ToTranslateText.Text.ToLower(), TranslatedText.Text.ToLower() };

                string languagePair = StringOperation.CreatingLangugePair(fromLanguageButton.Content.ToString(), toLanguageButton.Content.ToString());
                languagePair = languagePair.Replace("|", "");

                DatabaseConnection dbCon = new DatabaseConnection(languagePair);
                dbCon.InsertingValue(words[0], words[1]);

                if (dbCon.SearchingForWord(languagePair, words[0]))
                {
                    dbCon.IncreasingValue(languagePair, words[0]);
                }

                MessageDialog msg = new MessageDialog(String.Format("Added '{0} ➤ {1}' to {2} database!", words[0], words[1], languagePair));
                await msg.ShowAsync();

                ToTranslateText.Text = "";
                TranslatedText.Text  = "";
            }
            else
            {
                MessageDialog msg = new MessageDialog("You can't add empty translation to database!");
                await msg.ShowAsync();
            }
        }
Example #8
0
        static void Main(string[] args)
        {
            Technique     technique     = new Technique(100);
            SemiTechnique semiTechnique = new SemiTechnique(30, 100);

            Boss.Upgrade(technique.AddVoltage100);

            technique.TurnOn(500);

            Boss.Upgrading += semiTechnique.AddVoltage100;
            semiTechnique.TurnOn(100, 350);

            semiTechnique.TurnOn(100, 350);

            String str = "Лабораторная,.,   ,,,номер:! 9;...?";

            StringOperation stringOperation = null;

            stringOperation += DeletePunctuationMark;
            stringOperation += FerstToApperCase;
            stringOperation += AddDote;
            stringOperation += AddAuthor;

            Action_ColorPrint(ref str, CorrectString);

            Console.ReadLine();
        }
        public async Task <IActionResult> ForgotPasswordViaSms(ForgotPasswordViaEmailViewModel model)
        {
            var mail = await _dbContext.UserEmails.SingleOrDefaultAsync(t => t.EmailAddress == model.Email.ToLower());

            if (mail == null)
            {
                return(NotFound());
            }
            var user = await _dbContext
                       .Users
                       .Include(t => t.Emails)
                       .SingleOrDefaultAsync(t => t.Id == mail.OwnerId);

            if (user.PhoneNumberConfirmed == false)
            {
                return(NotFound());
            }
            var code = StringOperation.RandomString(6);

            user.SMSPasswordResetToken = code;
            await _userManager.UpdateAsync(user);

            _cannonService.FireAsync <APISMSSender>(async(sender) =>
            {
                await sender.SendAsync(user.PhoneNumber, code + " is your Aiursoft password reset code.");
            });
            return(RedirectToAction(nameof(EnterSmsCode), new { model.Email }));
        }
Example #10
0
        public async Task <IActionResult> Generate(GenerateAddressModel model)
        {
            var app = await _coreApiService.ValidateAccessTokenAsync(model.AccessToken);

            var appLocal = await _dbContext.Apps.SingleOrDefaultAsync(t => t.AppId == app.AppId);

            var file = await _dbContext.OSSFile.Include(t => t.BelongingBucket).SingleOrDefaultAsync(t => t.FileKey == model.Id);

            if (file == null || file.BelongingBucket.BelongingAppId != appLocal.AppId)
            {
                return(NotFound());
            }
            // Generate secret
            var newSecret = new Secret
            {
                Value  = StringOperation.RandomString(15),
                FileId = file.FileKey
            };

            _dbContext.Secrets.Add(newSecret);
            await _dbContext.SaveChangesAsync();

            return(Json(new AiurValue <string>(newSecret.Value)
            {
                Code = ErrorType.Success,
                Message = "Successfully created your onetime secret!"
            }));
        }
Example #11
0
    static void Main(string[] args)
    {
        List <string>          ptr             = new List <string>();
        AlphaNumbericCollector alphaCollector  = new AlphaNumbericCollector();
        StringCollector        stringCollector = new StringCollector();

        while (true)
        {
            ptr.Add(Console.ReadLine());
            if (ptr[ptr.Count - 1] != null)
            {
                for (int i = 0; i < ptr[ptr.Count - 1].Length; i++)
                {
                    if (ptr[ptr.Count - 1][i] >= 0x30 && ptr[ptr.Count - 1][i] <= 0x39)
                    {
                        AlphaOperation alpha_operation = alphaCollector.CollectingMethod;
                        alpha_operation(ptr[ptr.Count - 1]);
                        alphaCollector.Show();
                        break;
                    }
                    else if (i == ptr[ptr.Count - 1].Length - 1)
                    {
                        StringOperation string_operation = stringCollector.CollectingMethod;
                        string_operation(ptr[ptr.Count - 1]);
                        stringCollector.Show();
                        break;
                    }
                }
            }
            else
            {
                ptr.Remove(ptr[ptr.Count - 1]);
            }
        }
    }
Example #12
0
        public async Task <IActionResult> CreateChannel([FromForm] CreateChannelAddressModel model)
        {
            var token = await _dbContext.AccessTokens.Include(t => t.ApplyApp).SingleOrDefaultAsync(t => t.Value == model.AccessToken);

            if (token == null || token.ApplyApp == null)
            {
                return(Protocal(ErrorType.Unauthorized, "Invalid accesstoken!"));
            }
            //Create and save to database
            var newChannel = new Channel
            {
                Description = model.Description,
                ConnectKey  = StringOperation.RandomString(20),
                AppId       = token.ApplyAppId
            };

            _dbContext.Channels.Add(newChannel);
            await _dbContext.SaveChangesAsync();

            //return model
            var viewModel = new CreateChannelViewModel
            {
                ChannelId  = newChannel.Id,
                ConnectKey = newChannel.ConnectKey,
                code       = ErrorType.Success,
                message    = "Successfully created your channel!"
            };

            return(Json(viewModel));
        }
Example #13
0
 void QueryPolicy(Pagination pagination)
 {
     try
     {
         var paramer    = GetCondition(pagination);
         var list_query = ChinaPay.B3B.Service.PolicyMatch.PolicyMatchServcie.GetSpecialPolicies(this.CurrentCompany.CompanyId, paramer, item => item.Rebate, OrderMode.Descending);
         var list       = from item in list_query
                          let item_special = item.OriginalPolicy as SpecialPolicyInfo
                                             select new
         {
             //政策编号
             id = item_special.Id,
             //航空公司
             Airline = item_special.Airline,
             //出发城市
             Departure = paramer.Departure,
             //到达城市
             Arrival = paramer.Arrival,
             //排除日期
             DepartureDateFilter = item_special.DepartureDateFilter,
             //适用班期
             DepartureWeekFilter = StringOperation.TransferToChinese(item_special.DepartureWeekFilter),
             //航班限制
             Include = item_special.DepartureFlightsFilterType == LimitType.None ? "不限" : (item_special.DepartureFlightsFilterType == LimitType.Include ? ("适用:" + item_special.DepartureFlightsFilter) : "不适用:" + item_special.DepartureFlightsFilter),
             //发布价格
             Price = item_special.Price == -1 ? "" : item_special.Price.TrimInvaidZero(),
             //提前天数
             BeforehandDays = item_special.BeforehandDays == -1 ? "" : item_special.BeforehandDays + "",
             //去程日期
             DepartureDates  = item_special.DepartureDateStart.ToString("yyyy-MM-dd") + "<br />" + item_special.DepartureDateEnd.ToString("yyyy-MM-dd"),
             Commission_link = item_special.Owner == this.CurrentCompany.CompanyId ? "<a href=\"javascript:ModifyCommission('" + item_special.Id + "','" + item_special.Price.TrimInvaidZero() + "','" + item_special.PriceType + "','" + item_special.Type + "','" + item_special.IsInternal + "','" + item_special.IsPeer + "','" + item_special.InternalCommission.TrimInvaidZero() + "','" + (CurrentCompany.CompanyType == CompanyType.Provider || (CurrentCompany.CompanyType == CompanyType.Supplier && OEM != null) ? item_special.SubordinateCommission.TrimInvaidZero() : "-1") + "','" + item_special.ProfessionCommission.TrimInvaidZero() + "','" + item_special.IsBargainBerths + "');\">修改返佣</a>" : "同行政策",
             Policy_link     = item_special.Owner == this.CurrentCompany.CompanyId ? "<a href='special_policy_edit.aspx?Id=" + item_special.Id + "&Type=Update&Check=view'>修改详细</a>" : "&nbsp",
             //操作人
             Opearor = item_special.Owner == this.CurrentCompany.CompanyId ? item_special.Creator : "&nbsp",
             Sudit   = item_special.Audited == true ? "已审" : "未审",
             Hang    = item_special.Suspended == true ? "挂起" : "未挂"
         };
         this.grv_specical.DataSource = list;
         this.grv_specical.DataBind();
         if (list.Count() > 0)
         {
             this.pager.Visible = true;
             if (pagination.GetRowCount)
             {
                 this.pager.RowCount = list_query.RowCount;
             }
             showempty.Visible = false;
         }
         else
         {
             this.pager.Visible = false;
             showempty.Visible  = true;
         }
     }
     catch (Exception ex)
     {
         ShowExceptionMessage(ex, "查询");
     }
 }
        private void onClickBankChange(object sender, RoutedEventArgs e)
        {
            Error = "";

            if (string.IsNullOrEmpty(field_CardNumber.Text))
            {
                Error = "Ви не заповнили поле 'Номер карти'";
                return;
            }

            if (string.IsNullOrEmpty(field_ExpireDate.Text))
            {
                Error = "Ви не заповнили поле 'Термін придатності'";
                return;
            }

            if (string.IsNullOrEmpty(field_CVV.Text))
            {
                Error = "Ви не заповнили поле 'CVV-код'";
                return;
            }

            if (field_CardNumber.Text.Length != 16)
            {
                Error = "Допущена помилка в полі 'Номер карти'";
                return;
            }

            if (!StringOperation.IsOnlyDigit(field_CardNumber.Text))
            {
                Error = "Допущена помилка в полі 'CVV-код'";
                return;
            }

            if (field_ExpireDate.Text.Length != 5)
            {
                Error = "Допущена помилка в полі 'Термін придатності'";
                return;
            }

            if (field_CVV.Text.Length != 3)
            {
                Error = "Допущена помилка в полі 'CVV-код'";
                return;
            }

            if (!StringOperation.IsOnlyDigit(field_CVV.Text))
            {
                Error = "Допущена помилка в полі 'CVV-код'";
                return;
            }

            Client.User.CardNumber = field_CardNumber.Text;
            Client.User.ExpireDate = field_ExpireDate.Text;
            Client.User.CVV        = Convert.ToInt32(field_CVV.Text);

            Client.Server.ConnectProvider.SaveUser(Client.User);
        }
Example #15
0
 public void AddFriend(string userId1, string userId2)
 {
     this.PrivateConversations.Add(new PrivateConversation
     {
         RequesterId = userId1,
         TargetId    = userId2,
         AESKey      = StringOperation.RandomString(30)
     });
 }
        private void AddSuggestion(string str)
        {
            if (string.IsNullOrWhiteSpace(str))
            {
                return;
            }

            Buffer = StringOperation.ReplaceLastOccurrence(Buffer, StringOperation.LastWord(Buffer), str);
        }
Example #17
0
 public App(string seed, string name, string description, Category category, Platform platform)
 {
     this.AppId          = (seed + DateTime.Now.ToString()).GetMD5();
     this.AppSecret      = (seed + this.AppId + DateTime.Now.ToString() + StringOperation.RandomString(15)).GetMD5();
     this.AppName        = name;
     this.AppDescription = description;
     this.AppCategory    = category;
     this.AppPlatform    = platform;
 }
        public static void Run()
        {
            StringOperation invert = delegate(string s){
                char[] charArray = s.ToCharArray();
                Array.Reverse(charArray);
                return(new string(charArray));
            };

            System.Console.WriteLine(invert("C# is amazing!"));
        }
        public void SettingRows()
        {
            DatabaseConnection conDB = new DatabaseConnection();
            List <string>      rows  = conDB.GettingRows(StringOperation.LanguagesToTable(Tables.SelectedItem.ToString()));

            foreach (string item in rows)
            {
                CreatingListItems(Words, item);
            }
        }
        //setting dictionary names in menuflyoutitem
        private void SettingDictionaries()
        {
            DatabaseConnection conDB        = new DatabaseConnection();
            List <string>      dictionaries = conDB.GettingTables();

            foreach (string dictionary in dictionaries)
            {
                CreatingMenuFlyoutItem(DictionariesMenu, StringOperation.TableToLanguages(dictionary));
            }
        }
Example #21
0
        public void Should_RaiseException_When_SingleWord_IsPassed()
        {
            //arrange
            IStringOperation opertaion = new StringOperation();

            //act
            IEnumerable <WordDataDto> data = (opertaion.CountFrequentWords("AlphaFX"));

            //assert
            Assert.Single(data);
        }
Example #22
0
        public void Should_RaiseException_When_Whitespace_IsPassed()
        {
            //arrange
            IStringOperation opertaion = new StringOperation();

            //act
            void act() => opertaion.CountFrequentWords("         ");

            //assert
            Assert.Throws <ArgumentException>(act);
        }
Example #23
0
        public void Should_ReturnAllWordWithAlphaCount2_When_StringWithLessThan10Word_And_1RepeatingWord_IsPassed()
        {
            //arrange
            IStringOperation opertaion = new StringOperation();

            //act
            IEnumerable <WordDataDto> data = opertaion.CountFrequentWords("Alpha Alpha FX - Count of Word");

            //assert
            Assert.Equal(6, data.Count());
            Assert.Equal(2, data.Single(b => b.Word.Equals("Alpha")).Count);
        }
Example #24
0
        public void Should_ReturnAllWordWithSingleAppearance_When_StringWithLessThan10Word_And_AllUniqueWord_IsPassed()
        {
            //arrange
            IStringOperation opertaion = new StringOperation();

            //act
            IEnumerable <WordDataDto> data = (opertaion.CountFrequentWords("Alpha FX - Count of Word"));

            //assert
            Assert.Equal(6, data.Count());
            Assert.True(data.All(a => a.Count == 1));
        }
Example #25
0
        public async Task <IActionResult> SendConfirmationEmail(SendConfirmationEmailAddressModel model)//User Id
        {
            var accessToken = await _dbContext
                              .AccessToken
                              .SingleOrDefaultAsync(t => t.Value == model.AccessToken);

            var app = await _developerApiService.AppInfoAsync(accessToken.ApplyAppId);

            var user = await _userManager.FindByIdAsync(model.Id);

            var useremail = await _dbContext.UserEmails.SingleOrDefaultAsync(t => t.EmailAddress == model.Email.ToLower());

            if (useremail == null)
            {
                return(this.Protocal(ErrorType.NotFound, $"Can not find your email:{model.Email}"));
            }
            if (useremail.OwnerId != user.Id)
            {
                return(this.Protocal(ErrorType.Unauthorized, $"The account you tried to authorize is not an account with id: {model.Id}"));
            }
            if (useremail.Validated)
            {
                return(this.Protocal(ErrorType.HasDoneAlready, $"The email :{model.Email} was already validated!"));
            }
            if (!_dbContext.LocalAppGrant.Exists(t => t.AppID == accessToken.ApplyAppId && t.APIUserId == user.Id))
            {
                return(Json(new AiurProtocal {
                    Code = ErrorType.Unauthorized, Message = "This user did not grant your app!"
                }));
            }
            if (!app.App.ConfirmEmail)
            {
                return(this.Protocal(ErrorType.Unauthorized, "You app is not allowed to send confirmation email!"));
            }
            //limit the sending frenquency to 3 minutes.
            if (DateTime.Now > useremail.LastSendTime + new TimeSpan(0, 3, 0))
            {
                var token = StringOperation.RandomString(30);
                useremail.ValidateToken = token;
                useremail.LastSendTime  = DateTime.Now;
                await _dbContext.SaveChangesAsync();

                var callbackUrl = new AiurUrl(_serviceLocation.API, "User", nameof(EmailConfirm), new
                {
                    userId = user.Id,
                    code   = token
                });
                await _emailSender.SendEmail(useremail.EmailAddress, $"{Values.ProjectName} Account Email Confirmation",
                                             $"Please confirm your email by clicking <a href='{callbackUrl}'>here</a>");
            }
            return(this.Protocal(ErrorType.Success, "Successfully sent the validation email."));
        }
Example #26
0
        static void CorrectString(string str)
        {
            StringOperation stringOperation = null;

            stringOperation += DeletePunctuationMark;
            stringOperation += FerstToApperCase;
            stringOperation += AddDote;
            stringOperation += AddAuthor;

            stringOperation(ref str);

            Console.WriteLine(str);
        }
Example #27
0
        static void Main(string[] args)
        {
            int strLen = int.Parse(Console.ReadLine());

            string[] names = Console.ReadLine()
                             .Split(" ", StringSplitOptions.RemoveEmptyEntries);

            StringOperation          getCharSum = str => str.Select(ch => (int)ch).Sum();
            Func <string, int, bool> isValid    = (str, len) => getCharSum(str) >= len;

            string result = FindFirstValid(names, strLen, isValid);

            Console.WriteLine(result);
        }
Example #28
0
 private void buttonSend_Click(object sender, EventArgs e)
 {
     try
     {
         string sendstring = this.textBoxSend.Text;
         sendstring = sendstring.Replace(" ", "");
         byte[] bs = StringOperation.HexstringToHexBytes(sendstring);
         socketControl.Send(bs, bs.Length, 0);
         SendCnt += bs.Length;
         this.labelSendCnt.Text = SendCnt.ToString();
     }
     catch (Exception ex)
     { MessageBox.Show(ex.ToString()); }
 }
        public async Task TestGetOutter()
        {
            var http   = _serviceProvider.GetRequiredService <APIProxyService>();
            var random = StringOperation.RandomString(100);
            var result = await http.Get(new AiurUrl("https://postman-echo.com/get", new
            {
                a = random
            }));

            dynamic resultObject = JObject.Parse(result);

            Assert.AreEqual(resultObject.args.a.ToString(), random);
            Assert.IsTrue(resultObject.url.ToString().StartsWith("https://"));
        }
Example #30
0
        public void Should_ReturnTop10Words_When_String_IsPassed()
        {
            //arrange
            IStringOperation opertaion = new StringOperation();

            //act
            string             fileData = File.ReadAllText("Lord of the Ring.txt");
            List <WordDataDto> data     = new List <WordDataDto>(
                opertaion.CountFrequentWords(fileData));

            //assert
            int count = data.Count();

            Assert.Equal(10, count);
        }