public void AddSpecialCharacter(SpecialCharacter character, char?header = null) { AddSpecialCharacters(new List <SpecialCharacter>() { character }, header); }
public StringPatternAnalyzerResult Run() { SpecialCharacter.ResetMiddleSpecialCharacterCount(); SequentialCharacter.ResetSequentialCharacterCount(); RepeatedCharacters repeatedCharacters = new RepeatedCharacters { Count = 0, Deduction = 0 }; for (int index = 0; index < password.Length; index++) { CheckCharacter(index); CheckRepeatedCharacters(index, ref repeatedCharacters); } sequentialLetters = CheckSequentialLetters(); sequentialNumbers = CheckSequentialNumbers(); sequentialSymbols = CheckSequentialSymbols(); int score = 0; ApplyPositiveMultipliers(ref score); ApplyNagativeMultipliers(ref score, repeatedCharacters); return(StringPatternAnalyzerResult.FromScore(score)); }
private void ApplyPositiveMultipliers(ref int score) { // positive multipliers const int lengthMultipier = 6, numberMultiplier = 4, symbolMultiplier = 8, middleSpecialCharacterMultiplier = 2, unicodeMultiplier = 30; const int minimumPasswordLength = 12; /* Modify overall score value based on usage vs requirements */ score += password.Length * lengthMultipier; if (upperCase.Count > 0 && upperCase.Count < password.Length) { score += (password.Length - upperCase.Count) * 2; } if (lowerCase.Count > 0 && lowerCase.Count < password.Length) { score += (password.Length - lowerCase.Count) * 2; } if (number.Count < password.Length) { score += number.Count * numberMultiplier; } score += symbol.Count * symbolMultiplier; score += SpecialCharacter.GetMiddleSpecialCharacterCount() * middleSpecialCharacterMultiplier; score += unicode.Count * unicodeMultiplier; /* Determine if mandatory requirements have been met and set image indicators accordingly */ int fulfilledRequirementsCount = password.Length >= minimumPasswordLength ? 2 : 0; fulfilledRequirementsCount += new int[] { upperCase.Count, lowerCase.Count, number.Count, symbol.Count }.Count(i => i > 0); if (fulfilledRequirementsCount > 4) { score += fulfilledRequirementsCount * 3; } }
public static void CreateHtml() { // Set a path to our HTML document. string htmlPath = @"Result.html"; // Let's create a simple HTML document. DocumentCore dc = new DocumentCore(); //DocumentCore.Serial = "put your serial here"; // Add new section. Section section = new Section(dc); dc.Sections.Add(section); // Add two paragraphs using different ways: // Way 1: Add 1st paragraph. Paragraph par1 = new Paragraph(dc); par1.ParagraphFormat.Alignment = HorizontalAlignment.Center; section.Blocks.Add(par1); // Let's create a characterformat for text in the 1st paragraph. CharacterFormat cf = new CharacterFormat() { FontName = "Verdana", Size = 16, FontColor = Color.Orange }; Run text1 = new Run(dc, "This is a first line in 1st paragraph!"); text1.CharacterFormat = cf; par1.Inlines.Add(text1); // Let's add a line break into our paragraph. par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); Run text2 = text1.Clone(); text2.Text = "Let's type a second line."; par1.Inlines.Add(text2); // Way 2 (easy): Add 2nd paragraph using ContentRange. dc.Content.End.Insert("\nThis is a first line in 2nd paragraph.", new CharacterFormat() { Size = 25, FontColor = Color.Blue, Bold = true }); SpecialCharacter lBr = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr.Content); dc.Content.End.Insert("This is a second line.", new CharacterFormat() { Size = 20, FontColor = Color.DarkGreen, UnderlineStyle = UnderlineType.Single }); // Save HTML document to a file. dc.Save(htmlPath, new HtmlFixedSaveOptions()); ShowResult(htmlPath); }
public StringPatternAnalyzer(IProtectedString password) { this.password = password; upperCase = new Character(this); lowerCase = new Character(this); number = new NumericalCharacter(this); symbol = new SpecialCharacter(this); unicode = new SpecialCharacter(this); }
// How to create a plain table in a document. public static void AddText() { string documentPath = @"Text.docx"; // Let's create a new document. DocumentCore dc = new DocumentCore(); // Create a new section and add into the document. Section section = new Section(dc); dc.Sections.Add(section); // Create a new paragraph and add into the section. Paragraph par = new Paragraph(dc); section.Blocks.Add(par); // Create Inline-derived objects with text. Run run1 = new Run(dc, "This is a rich"); run1.CharacterFormat = new CharacterFormat() { FontName = "Times New Roman", Size = 18.0, FontColor = new Color(112, 173, 71) }; Run run2 = new Run(dc, " formatted text"); run2.CharacterFormat = new CharacterFormat() { FontName = "Arial", Size = 10.0, FontColor = new Color("#0070C0") }; SpecialCharacter spch3 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); Run run4 = new Run(dc, "with a line break."); run4.CharacterFormat = new CharacterFormat() { FontName = "Times New Roman", Size = 10.0, FontColor = Color.Black }; // Add our inlines into the paragraph. par.Inlines.Add(run1); par.Inlines.Add(run2); par.Inlines.Add(spch3); par.Inlines.Add(run4); // Save our document into the DOCX format. dc.Save(documentPath, new DocxSaveOptions()); // Open the result for demonstation purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(documentPath) { UseShellExecute = true }); }
public void AppendSpecialCharacter(SpecialCharacter specialCharacter) { if (Enum.IsDefined(typeof(SpecialCharacter), specialCharacter)) { _data.Add((byte)specialCharacter); } else { throw new ArgumentException(nameof(specialCharacter)); } }
private void CreateDocument() { _document = new DocumentModel { DefaultCharacterFormat = { Size = 12, FontColor = new Color(0, 54, 107) } }; _lineBreak = new SpecialCharacter(_document, SpecialCharacterType.LineBreak); }
public IActionResult Index(LetterModel letterModel) { //return Content(string.Join('\n', letterModel.SelectedIds)); var docx = new DocumentCore(); if (letterModel.SelectedIds is null) { return(RedirectToAction("Index")); } foreach (var id in letterModel.SelectedIds) { var section = GetSectionForUser(docx, _context.Users.Single(x => x.Id == int.Parse(id))); var par = new Paragraph(docx); section.Blocks.Add(par); var separators = new List <char>(); for (var i = 0; i < 32; i++) { separators.Add((char)i); } for (var i = 0; i < 4; i++) { var run = new SpecialCharacter(docx, SpecialCharacterType.LineBreak); par.Inlines.Add(run); } letterModel.Text = letterModel.Text ?? ""; var text = letterModel.Text.Split(separators.ToArray(), StringSplitOptions.RemoveEmptyEntries); foreach (var str in text) { var run = new Run(docx, str); par.Inlines.Add(run); var @break = new SpecialCharacter(docx, SpecialCharacterType.LineBreak); par.Inlines.Add(@break); } par.ParagraphFormat.Alignment = HorizontalAlignment.Center; docx.Sections.Add(section); } var filename = Path.GetTempFileName(); docx.Save(filename, SaveOptions.DocxDefault); return(File(System.IO.File.ReadAllBytes(filename), "application/msword", "letter.docx")); }
/// <summary>Generates a random password.</summary> /// <param name="length">The length.</param> /// <param name="specialCharacter">The special character.</param> /// <param name="digitCharacter">The digit character.</param> /// <param name="upperCaseCharacter">The upper case character.</param> /// <param name="lowerCaseCharacter">The lower case character.</param> /// <param name="passwordAllowedSpecialCharacters">The password allowed special characters.</param> /// <returns>String containing a randomly generated password.</returns> /// <exception cref="ArgumentOutOfRangeException">Thrown when length is not greater than zero.</exception> /// <exception cref="InvalidOperationException">Thrown when all password characteristics are <c>No</c>.</exception> /// <exception cref="ArgumentNullEmptyWhiteSpaceException">Thrown when passwordAllowedSpecialCharacters is null, empty, or white space.</exception> public static String Generate(Int32 length, SpecialCharacter specialCharacter, DigitCharacter digitCharacter, UpperCaseCharacter upperCaseCharacter, LowerCaseCharacter lowerCaseCharacter, String passwordAllowedSpecialCharacters = PasswordAllowedSpecialCharacters) { if (length <= Zero) { throw new ArgumentOutOfRangeException(nameof(length), Strings.MustBeGreaterThanZero); } if (specialCharacter == SpecialCharacter.No && digitCharacter == DigitCharacter.No && specialCharacter == SpecialCharacter.No && upperCaseCharacter == UpperCaseCharacter.No && lowerCaseCharacter == LowerCaseCharacter.No) { throw new InvalidOperationException(Strings.AtLeastOnePasswordCharacteristicMustBeYes); } if (String.IsNullOrWhiteSpace(passwordAllowedSpecialCharacters)) { throw new ArgumentNullEmptyWhiteSpaceException(nameof(passwordAllowedSpecialCharacters)); } return(Generate(length, length, specialCharacter, digitCharacter, upperCaseCharacter, lowerCaseCharacter, passwordAllowedSpecialCharacters)); }
internal StringPatternAnalyzerResult Run() { SpecialCharacter.ResetMiddleSpecialCharacterCount(); SequentialCharacter.ResetSequentialCharacterCount(); RepeatedCharacters repeatedCharacters = new RepeatedCharacters { Count = 0, Deduction = 0 }; for (int index = 0; index < password.Length; index++) { CheckCharacter(index); CheckRepeatedCharacters(index, ref repeatedCharacters); } throw new NotImplementedException(); }
public void SetCharacter(SpecialCharacter specialCharacter) { Character = new Character(specialCharacter); }
//Формирование документа protected void CreateDocx() { DBConnection connection = new DBConnection(); string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"Contract № " + tbNumber.Text + ".pdf"; DocumentCore dc = new DocumentCore(); Section section = new Section(dc); dc.Sections.Add(section); section.PageSetup.PaperType = PaperType.A4; dc.Content.End.Insert("\nОрганизация 'Мобильный магазин'", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black }); SpecialCharacter lBr = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr.Content); dc.Content.End.Insert("\nДоговор №" + tbNumber.Text + "", new CharacterFormat() { FontName = "Times New Roman", Size = 18, FontColor = SautinSoft.Document.Color.Black }); SpecialCharacter lBr2 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr2.Content); dc.Content.End.Insert("Дата заключения " + tbDate.Text + "г.", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black, }); SpecialCharacter lBr3 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr3.Content); dc.Content.End.Insert("Организация заключает трудовой договор с гражданином " + tbSurname.Text.ToString() + " " + tbName.Text + " " + tbMiddleName.Text + ", на должность " + ddlPost.SelectedItem.Text + " " + "с ежемесячной выплатой в размере " + Convert.ToString(tbPay.Text) + " руб. Настоящий Трудовой договор является договором по основной работе. Настоящий Трудовой договор заключен на неопределенный срок. " + "Дата начала работы " + tbDate.Text + "года. Продолжительность испытания при приеме на работу – 3 месяца.", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black, }); SpecialCharacter lBr4 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr4.Content); dc.Content.End.Insert("Паспортные данные: " + tbPassportNumber.Text + "" + tbPassportSeries.Text + "", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black }); SpecialCharacter lBr5 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr5.Content); dc.Content.End.Insert("Подпись работодателя ________________", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black }); SpecialCharacter lBr7 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr7.Content); dc.Content.End.Insert("Подпись работника ________________", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black }); dc.Save(docPath, new PdfSaveOptions() { Compliance = PdfCompliance.PDF_A, PreserveFormFields = true }); Process.Start(new ProcessStartInfo(docPath) { UseShellExecute = true }); }
//Формирование документа protected void CreateDocx() { string Number, contractNumber; DBConnection connection = new DBConnection(); SqlCommand command = new SqlCommand("", DBConnection.connection); command.CommandType = System.Data.CommandType.Text; command.CommandText = "SELECT [Fired_Order_Number] from [Fired_Order] where [ID_Fired_Order] = '" + DBConnection.selectedRow + "'"; DBConnection.connection.Open(); Number = command.ExecuteScalar().ToString(); command.ExecuteNonQuery(); DBConnection.connection.Close(); command.CommandText = "select [Contract_Number] from [Employee] inner join [Contract] on [ID_Contract] = [Contract_ID] where [ID_Employee] = " + Convert.ToInt32(ddlEmployee.SelectedValue.ToString()) + ""; DBConnection.connection.Open(); contractNumber = command.ExecuteScalar().ToString(); command.ExecuteNonQuery(); string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"Order № " + Number + ".pdf"; DocumentCore dc = new DocumentCore(); Section section = new Section(dc); dc.Sections.Add(section); section.PageSetup.PaperType = PaperType.A4; dc.Content.End.Insert("\nОрганизация 'Мобильный магазин'", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black }); SpecialCharacter lBr = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr.Content); dc.Content.End.Insert("\nПриказ о прекращении (расторжении) трудового договора с работником (увольнении) №" + Convert.ToString(Number) + "", new CharacterFormat() { FontName = "Times New Roman", Size = 18, FontColor = SautinSoft.Document.Color.Black }); SpecialCharacter lBr2 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr2.Content); dc.Content.End.Insert("Дата офрмления увольнения сотрудника " + tbDate.Text + "г.", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black, }); SpecialCharacter lBr3 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr3.Content); dc.Content.End.Insert("Приказ о прекращении трудового договора № " + contractNumber + " с сотрудником " + ddlEmployee.SelectedItem.Text + ". Причина увольнения сотрудника : " + tbReason.Text + "", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black, }); SpecialCharacter lBr4 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr4.Content); dc.Content.End.Insert("Подпись работодателя ________________", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black }); SpecialCharacter lBr7 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr7.Content); dc.Content.End.Insert("Подпись сотрудника ________________", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black }); dc.Save(docPath, new PdfSaveOptions() { Compliance = PdfCompliance.PDF_A, PreserveFormFields = true }); Process.Start(new ProcessStartInfo(docPath) { UseShellExecute = true }); }
public void gerarRelatório(string option, DateTime data) { DocumentModel doc = new DocumentModel(); Section s = new Section(doc); doc.Sections.Add(s); Paragraph intro = new Paragraph(doc); s.Blocks.Add(intro); Run introRun = new Run(doc, "Relatório de Veículos, com manutenções e locações, cada uma com suas respectivas datas."); intro.Inlines.Add(introRun); SpecialCharacter newline = new SpecialCharacter(doc, SpecialCharacterType.LineBreak); intro.Inlines.Add(newline); newline = newline.Clone(); introRun = new Run(doc, "Relatório da opção " + option + option == "período" ? "no período dado por " + data.ToString() : ""); intro.Inlines.Add(introRun); using (var ctx = new DadosContainer()) { ctx.Attach(this); foreach (Histórico h in getHistóricos()) { Paragraph p = new Paragraph(doc); s.Blocks.Add(p); List <Locação> locs = h.getLocações().FindAll(l => comparaDatas(option, data, l.getInicio()) || (l.acabou() && comparaDatas(option, data, l.getFim()))); List <Manutenção> mans = h.getManutenções().FindAll(m => comparaDatas(option, data, m.getInicio()) || (m.acabou() && comparaDatas(option, data, m.getFim()))); Run run = new Run(doc, "Veículo " + h.Veículo.Id); p.Inlines.Add(run); p.Inlines.Add(newline); newline = newline.Clone(); run = new Run(doc, "Manutenções no período dado"); p.Inlines.Add(run); p.Inlines.Add(newline); newline = newline.Clone(); List <string> linhas; foreach (Manutenção m in mans) { linhas = m.ToString().Split('\n').ToList(); foreach (string linha in linhas) { run = new Run(doc, linha); p.Inlines.Add(run); p.Inlines.Add(newline); newline = newline.Clone(); } } run = new Run(doc, "Locações no período dado"); p.Inlines.Add(run); p.Inlines.Add(newline); newline = newline.Clone(); foreach (Locação l in locs) { linhas = l.ToString().Split('\n').ToList(); foreach (string linha in linhas) { run = new Run(doc, linha); p.Inlines.Add(run); p.Inlines.Add(newline); newline = newline.Clone(); } } } } doc.Save("relatorio.pdf"); }
/// <summary> /// Создание нового документа /// </summary> /// <param name="Format">Формат файла</param> protected void CreateDocx(string Format) { DBConnection connection = new DBConnection(); string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"Contract № " + tbContractNumber.Text + Format; DocumentCore dc = new DocumentCore(); Section section = new Section(dc); dc.Sections.Add(section); section.PageSetup.PaperType = PaperType.A4; //Добавление строк dc.Content.End.Insert("\nТРУДОВОЙ ДОГОВОР № " + tbContractNumber.Text + "", new CharacterFormat() { FontName = "Times New Roman", Size = 18, FontColor = SautinSoft.Document.Color.Black, Bold = true }); SpecialCharacter lBr = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr.Content); dc.Content.End.Insert("" + tbContractDate.Text + "г.", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black, }); SpecialCharacter lBr2 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr2.Content); dc.Content.End.Insert("Организация библиотека, именуемое в дальнейшем «Работодатель», в лице генерального директора Иванова Ивана Ивановича, " + "и гражданин(ка) " + tbSurname.Text.ToString() + " " + tbName.Text + " " + tbMiddleName.Text + ", заключают трудовой договор. Гражданин вступает в должность " + ddlPosition.SelectedItem.Text + " " + "с заработной платой в размере " + Convert.ToString(DBConnection.Pay) + " рублей.", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black, }); SpecialCharacter lBr3 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr2.Content); dc.Content.End.Insert("Паспорт: серия " + tbPassportNumber.Text + " № " + tbPassportSeries.Text + "", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black }); //Документ в формате .docx if (Format == ".docx") { // Сохраняем документ в формате .docx dc.Save(docPath, new DocxSaveOptions()); // Открываем документ Process.Start(new ProcessStartInfo(docPath) { UseShellExecute = true }); } //Документ в другом формате (тут .pdf) else { dc.Save(docPath, new PdfSaveOptions() { Compliance = PdfCompliance.PDF_A, PreserveFormFields = true }); // Open the result for demonstration purposes. Process.Start(new ProcessStartInfo(docPath) { UseShellExecute = true }); } }
private async void button2_Click(object sender, EventArgs e) { FirebaseResponse response = client.Get("hoadon"); dynamic EInvoices1 = JsonConvert.DeserializeObject(response.Body); // Trả về object hóa đơn dưới dạng JSON foreach (var EInvoice in EInvoices1) // Duyệt từng hóa đơn { string a = EInvoice.Name; //Lấy key of Hóa đơn dưới dạng JSON if (listKeyTempt1.Contains(a) == false) { // listKeyTempt.Add(a); listKey1.Add(a); } listKeyTempt1.Add(a); } foreach (var key in listKey1) // Duyệt từng hóa đơn { FirebaseResponse responseInfor = await client.GetTaskAsync("hoadon/" + key); //Lấy value của hóa đơn EInvoicing temp = new EInvoicing(); //Tạo một Class Einvoice tạm temp = responseInfor.ResultAs <EInvoicing>(); //Kéo dữ liệu hóa đơn từ server đổ về class tạm này if (einvoiceArray1.Count == 0) { einvoiceArray1.Add(temp);//Thêm dữ liệu vào List Einvoice } else { if (einvoiceArray1.Count < listKey1.Count) { einvoiceArray1.Add(temp);//Thêm dữ liệu vào List Einvoice } else { if (einvoiceArray1.Contains(temp) == true) { einvoiceArray1.Add(temp);//Thêm dữ liệu vào List Einvoice } } } } foreach (var einvoice in einvoiceArray1) { if (einvoice.ComName == ComName && einvoice.CusName == CusName && einvoice.InvoiceSerialNo == EName) { string pdfPath = "Result.pdf"; CharacterFormat textFormat = new CharacterFormat() { Size = 15, FontColor = SautinSoft.Document.Color.Black }; DocumentCore dc = new DocumentCore(); Section section = new Section(dc); dc.Sections.Add(section); section.PageSetup.PaperType = PaperType.A4; section.PageSetup.Orientation = SautinSoft.Document.Orientation.Landscape; Paragraph par1 = new Paragraph(dc); par1.ParagraphFormat.Alignment = SautinSoft.Document.HorizontalAlignment.Center; section.Blocks.Add(par1); CharacterFormat cf = new CharacterFormat() { FontName = "Verdana", Size = 20, FontColor = SautinSoft.Document.Color.Red, Bold = true }; Run text1 = new Run(dc, einvoice.InvoiceName); text1.CharacterFormat = cf; par1.Inlines.Add(text1); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); dc.Content.End.Insert("Ngày lập hóa đơn : " + einvoice.InvoiceArisingDate, textFormat); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); dc.Content.End.Insert("Số hóa đơn : " + einvoice.InvoiceNo, textFormat); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); dc.Content.End.Insert("Số hiệu hóa đơn : " + einvoice.InvoiceSerialNo, textFormat); // Let's add a line break into our paragraph. par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); // Way 2 (easy): Add 2nd paragraph using ContentRange. dc.Content.End.Insert("Tên khách hàng : " + einvoice.CusName, textFormat); SpecialCharacter lBr = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr.Content); dc.Content.End.Insert("Địa chỉ khách hàng : " + einvoice.CusAddress, textFormat); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); dc.Content.End.Insert("Email khách hàng : " + einvoice.CusEmail, textFormat); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); dc.Content.End.Insert("Số điện thoại khách hàng : " + einvoice.CusPhone, textFormat); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); dc.Content.End.Insert("Số tài khoản : " + einvoice.CusBankNo, textFormat); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); dc.Content.End.Insert("Tên ngân hàng : " + einvoice.CusBankName, textFormat); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); dc.Content.End.Insert("Tên công ty : " + einvoice.ComName, textFormat); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); dc.Content.End.Insert("Địa chỉ công ty : " + einvoice.ComAddress, textFormat); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); dc.Content.End.Insert("Số điện thoại công ty : " + einvoice.ComPhone, textFormat); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); foreach (var items in einvoice.itemsData) { dc.Content.End.Insert("Món hàng : " + items.ItemsName, textFormat); dc.Content.End.Insert("\t\t", textFormat); dc.Content.End.Insert("Số lượng : " + items.ItemsNum, textFormat); dc.Content.End.Insert("\t\t", textFormat); dc.Content.End.Insert("Đơn giá : " + items.ItemsPrice + " đồng", textFormat); dc.Content.End.Insert("\t\t", textFormat); // dc.Content.End.Insert("------------------------------------", textFormat); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); } par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); dc.Content.End.Insert("Hình thức thanh toán : " + einvoice.Payment, textFormat); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); dc.Content.End.Insert("Tổng tiền : " + einvoice.TotalPrice + " đồng", new CharacterFormat() { Size = 30, FontColor = SautinSoft.Document.Color.Red }); Paragraph par2 = new Paragraph(dc); par2.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); par2.ParagraphFormat.Alignment = SautinSoft.Document.HorizontalAlignment.Justify; section.Blocks.Add(par2); par2.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); dc.Content.End.Insert("Chữ ký của khách hàng \t\t\t\t\t Chữ ký của nhà bán hàng ", new CharacterFormat() { Size = 20, FontColor = SautinSoft.Document.Color.Red }); //Add a signature String picPath = System.AppDomain.CurrentDomain.BaseDirectory + "signature.png"; // File located in Resources SDD::Picture signaturePic = new SDD::Picture(dc, picPath); signaturePic.Layout = SDD::Layout.Floating( new HorizontalPosition(16.5, LengthUnit.Centimeter, HorizontalPositionAnchor.Page), new VerticalPosition(10.5, LengthUnit.Centimeter, VerticalPositionAnchor.Page), new SDD::Size(20 * 3, 10 * 3, LengthUnit.Millimeter)); dc.Content.End.Insert(signaturePic.Content); // Save PDF to a file dc.Save(pdfPath, new PdfSaveOptions()); // Open the result for demonstation purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(pdfPath) { UseShellExecute = true }); break; } } listKey1.Clear(); einvoiceArray1.Clear(); }
/// <summary> /// Создание нового документа /// </summary> /// <param name="Format">Формат файла</param> protected void CreateDocx(string Format) { DBConnection connection = new DBConnection(); string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\Reservation information № " + Convert.ToString(DBConnection.idRecord) + Format; // Путь для скачивания документа DocumentCore dc = new DocumentCore(); Section section = new Section(dc); dc.Sections.Add(section); section.PageSetup.PaperType = PaperType.A4; //Добавление строк dc.Content.End.Insert("\nИНФОРМАЦИЯ О БРОНИРОВАНИИ", new CharacterFormat() { FontName = "Times New Roman", Size = 18, FontColor = Color.Black, Bold = true }); SpecialCharacter lBr = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr.Content); dc.Content.End.Insert("Вы забронировали стол №" + ddlNumber.SelectedItem.Text + ". Стол забронирован на " + tbDate.Text + " " + "в " + Convert.ToString(ddlTime.SelectedItem.Text) + ". Количество гостей " + tbQuantity.Text + ".", new CharacterFormat() { FontName = "Times New Roman", Size = 16, FontColor = Color.Black, }); SpecialCharacter lBr2 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr2.Content); dc.Content.End.Insert("Ваш номер бронирования " + Convert.ToString(DBConnection.idRecord) + ".", new CharacterFormat() { FontName = "Times New Roman", Size = 16, FontColor = Color.Black, }); SpecialCharacter lBr3 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr2.Content); dc.Content.End.Insert("Кому, " + connection.KlientData(DBConnection.idKlient) + ".", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = Color.Black }); //Документ в формате .docx if (Format == ".docx") { // Сохраняем документ в формате .docx dc.Save(docPath, new DocxSaveOptions()); // Открываем документ Process.Start(new ProcessStartInfo(docPath) { UseShellExecute = true }); } //Документ в другом формате (тут .pdf) else { dc.Save(docPath, new PdfSaveOptions() { Compliance = PdfCompliance.PDF_A, PreserveFormFields = true }); // Open the result for demonstration purposes. Process.Start(new ProcessStartInfo(docPath) { UseShellExecute = true }); } }
/// <summary> /// Creates a new document and saves it into PDF format. Print PDF using your default printer. /// </summary> /// <remarks> /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/print-document-net-csharp-vb.php /// </remarks> public static void CreateAndPrintPdf() { // Set the path to create pdf document. string pdfPath = @"Result.pdf"; // Let's create a simple PDF document. DocumentCore dc = new DocumentCore(); // Add new section. Section section = new Section(dc); dc.Sections.Add(section); // Let's set page size A4. section.PageSetup.PaperType = PaperType.A4; // Add a paragraph using ContentRange: dc.Content.End.Insert("\nHi Dear Friends.", new CharacterFormat() { Size = 25, FontColor = Color.Blue, Bold = true }); SpecialCharacter lBr = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr.Content); dc.Content.End.Insert("I'm happy to see you!", new CharacterFormat() { Size = 20, FontColor = Color.DarkGreen, UnderlineStyle = UnderlineType.Single }); // Save PDF to a file dc.Save(pdfPath, new PdfSaveOptions()); // Create a new process: Acrobat Reader. You may change in on Foxit Reader. string processFilename = Microsoft.Win32.Registry.LocalMachine .OpenSubKey("Software") .OpenSubKey("Microsoft") .OpenSubKey("Windows") .OpenSubKey("CurrentVersion") .OpenSubKey("App Paths") .OpenSubKey("AcroRd32.exe") .GetValue(String.Empty).ToString(); // Let's transfer our PDF file to the process Adobe Reader ProcessStartInfo info = new ProcessStartInfo(); info.Verb = "print"; info.FileName = processFilename; info.Arguments = String.Format("/p /h {0}", pdfPath); info.CreateNoWindow = true; //(It won't be hidden anyway... thanks Adobe!) info.WindowStyle = ProcessWindowStyle.Hidden; info.UseShellExecute = false; Process p = Process.Start(info); p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; // Print our PDF int counter = 0; while (!p.HasExited) { System.Threading.Thread.Sleep(1000); counter += 1; if (counter == 5) { break; } } if (!p.HasExited) { p.CloseMainWindow(); p.Kill(); } // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(pdfPath) { UseShellExecute = true }); }
/// <summary>Initializes a new instance of the <see cref="PasswordValidatorAttribute"/> class.</summary> /// <param name="lowerCaseCharacter">Is a lower case character required.</param> /// <param name="upperCaseCharacter">Is an upper case character required.</param> /// <param name="digitCharacter">Is a digit character required.</param> /// <param name="specialCharacter">Is a special character required.</param> /// <param name="allowedPasswordSpecialCharacters">The allowed password special characters. Change value to limit or increase the number of special characters.</param> /// <exception cref="ArgumentOutOfRangeException">Thrown when minimumLength is less than one.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when maximumLength is less than one.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when maximumLength less than or equal to Minimum Length.</exception> /// <exception cref="InvalidEnumArgumentException">Thrown when enum value lowerCaseCharacter is not defined.</exception> /// <exception cref="InvalidEnumArgumentException">Thrown when enum value upperCaseCharacter is not defined.</exception> /// <exception cref="InvalidEnumArgumentException">Thrown when enum value digitCharacter is not defined.</exception> /// <exception cref="InvalidEnumArgumentException">Thrown when enum value specialCharacter is not defined.</exception> /// <exception cref="InvalidEnumArgumentException">Thrown when enum value requiredEntry is not defined.</exception> /// <exception cref="ArgumentNullEmptyWhiteSpaceException">Thrown when allowedPasswordSpecialCharacters is null, empty, or white space.</exception> public PasswordValidatorAttribute(Int32 minimumLength, Int32 maximumLength, LowerCaseCharacter lowerCaseCharacter, UpperCaseCharacter upperCaseCharacter, DigitCharacter digitCharacter, SpecialCharacter specialCharacter, String allowedPasswordSpecialCharacters = "!@#$*^%&()-_+|") : this(minimumLength, maximumLength, lowerCaseCharacter, upperCaseCharacter, digitCharacter, specialCharacter, RequiredEntry.Yes, allowedPasswordSpecialCharacters) { }
/// <summary> /// Creates a new PDF document using DOM directly. /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/create-pdf-document-net-csharp-vb.php /// </remarks> public static void CreatePdfUsingDOM() { // Set a path to our document. string docPath = @"Result-DocumentCore.pdf"; // Create a new document. DocumentCore dc = new DocumentCore(); // Add new section. Section section = new Section(dc); dc.Sections.Add(section); // Let's set page size A4. section.PageSetup.PaperType = PaperType.A4; // Add two paragraphs Paragraph par1 = new Paragraph(dc); par1.ParagraphFormat.Alignment = HorizontalAlignment.Center; section.Blocks.Add(par1); // Let's create a characterformat for text in the 1st paragraph. CharacterFormat cf = new CharacterFormat() { FontName = "Verdana", Size = 16, FontColor = Color.Orange }; Run run1 = new Run(dc, "This is a first line in 1st paragraph!"); run1.CharacterFormat = cf; par1.Inlines.Add(run1); // Let's add a line break into the 1st paragraph. par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); // Copy the formatting. Run run2 = run1.Clone(); run2.Text = "Let's type a second line."; par1.Inlines.Add(run2); // Add 2nd paragraph. Paragraph par2 = new Paragraph(dc, new Run(dc, "This is a first line in 2nd paragraph.", new CharacterFormat() { Size = 25, FontColor = Color.Blue, Bold = true })); section.Blocks.Add(par2); SpecialCharacter lBr = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); par2.Inlines.Add(lBr); Run run3 = new Run(dc, "This is a second line.", new CharacterFormat() { Size = 20, FontColor = Color.DarkGreen, UnderlineStyle = UnderlineType.Single }); par2.Inlines.Add(run3); // Add a graphics figure into the paragraph. Shape shape = new Shape(dc, new InlineLayout(new SautinSoft.Document.Drawing.Size(50, 50, LengthUnit.Millimeter))); // Specify outline and fill. shape.Outline.Fill.SetSolid(new SautinSoft.Document.Color("#358CCB")); shape.Outline.Width = 3; shape.Fill.SetSolid(SautinSoft.Document.Color.Orange); shape.Geometry.SetPreset(Figure.SmileyFace); par2.Inlines.Add(shape); // Save the document to the file in PDF format. dc.Save(docPath, new PdfSaveOptions() { Compliance = PdfCompliance.PDF_A1a }); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(docPath) { UseShellExecute = true }); }
/// <summary> /// pageAllFile /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnWrite_Click(object sender, EventArgs e) { if (rbtnTxt.Checked == true) { #region System: using System.IO save.Filter = "File TXT| *.txt"; if (save.ShowDialog() == DialogResult.OK) { try { // save.FileName: Tên File vs định dạng đuôi do save.Filter quy định // true or false: Cho phép ghi tiếp File đã tồn tại (true) hay là ghi đè (false) // Encoding.UTF8: Các ký tự đặc biết như có dấu hoặc ê, â... StreamWriter write = new /*System.IO.*/ StreamWriter(save.FileName, true, Encoding.UTF8); foreach (var item in lbxExample.Items) { string line = item.ToString(); write.WriteLine(line); } write.WriteLine(rtxtExample.Text); write.WriteLine(txtExample.Text); write.WriteLine(dtExample.Value); write.Close(); MessageBox.Show("Done"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } #endregion } else if (rbtnRtf.Checked == true) { #region Sautinsoft: using Sautinsoft.Document save.Filter = "File RTF| *.rtf"; if (save.ShowDialog() == DialogResult.OK) { try { DocumentCore document = new DocumentCore(); // Tao 1 char dac biet LineBreak == '\n'; // Ngoai ra con co nhiu char khac nhu tab... SpecialCharacter spec = new SpecialCharacter(document, SpecialCharacterType.LineBreak); // Cach 1: document.Content.End.Insert(rtxtExample.Text + spec.Content); foreach (var item in lbxExample.Items) { document.Content.End.Insert(item + "\n"); } document.Content.End.Insert(txtExample.Text + "\n" + dtExample.Value); document.Save(save.FileName); MessageBox.Show("Done"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } #endregion } else if (rbtnDocx.Checked == true) { save.Filter = "File DOCX| *.docx"; if (save.ShowDialog() == DialogResult.OK) { try { #region Microsoft Word 16.0 Object Library: using Microsoft.Office.Interop.Word; Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document document = new Microsoft.Office.Interop.Word.Document(); application.Visible = true; object obj = System.Reflection.Missing.Value; document = application.Documents.Add(ref obj); application.Selection.TypeText(rtxtExample.Text); foreach (var item in lbxExample.Items) { application.Selection.TypeText(item.ToString() + "\n"); } application.Selection.TypeText(txtExample.Text + "\n" + dtExample.Value); application = null; #endregion #region Sautinsoft: using Sautinsoft.Document //DocumentCore document = new DocumentCore(); //// Tao 1 char dac biet LineBreak == '\n'; //// Ngoai ra con co nhiu char khac nhu tab... //SpecialCharacter spec = new SpecialCharacter(document, SpecialCharacterType.LineBreak); //// Cach 1: //document.Content.End.Insert(rtxtExample.Text + spec.Content); //foreach (var item in lbxExample.Items) //{ // document.Content.End.Insert(item + "\n"); //} //document.Content.End.Insert(txtExample.Text + "\n" + dtExample.Value); //document.Save(save.FileName); #endregion #region DocX: using Xceed.Words.NET //var doc = DocX.Create(save.FileName); //doc.InsertParagraph(rtxtExample.Text + "\n"); //foreach (var item in lbxExample.Items) //{ // doc.InsertParagraph(item + "\n"); //} //doc.InsertParagraph(txtExample.Text + "\n" + dtExample.Value); //doc.Save(); #endregion MessageBox.Show("Done"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } else if (rbtnPdf.Checked == true) { save.Filter = "File PDF| *.pdf"; if (save.ShowDialog() == DialogResult.OK) { try { #region iTextSharp: using iTextSharp.text.pdf iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate()); PdfWriter.GetInstance(document, new FileStream(save.FileName, FileMode.Create)); document.Open(); document.Add(new iTextSharp.text.Paragraph(rtxtExample.Text)); foreach (var item in lbxExample.Items) { document.Add(new iTextSharp.text.Paragraph(item.ToString())); } document.Add(new iTextSharp.text.Paragraph(txtExample.Text + "\n" + dtExample.Value)); document.Close(); #endregion MessageBox.Show("Done"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } else if (rbtnExcel.Checked == true) { } }
/// <summary>Generates a random password.</summary> /// <param name="length">The length.</param> /// <param name="specialCharacter">The special character.</param> /// <param name="digitCharacter">The digit character.</param> /// <param name="upperCaseCharacter">The upper case character.</param> /// <param name="lowerCaseCharacter">The lower case character.</param> /// <param name="passwordAllowedSpecialCharacters">The password allowed special characters.</param> /// <returns>String containing a randomly generated password.</returns> /// <exception cref="ArgumentOutOfRangeException">Thrown when minimumLength is not greater than zero.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when maximumLength is not greater than zero.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when maximumLength is less than minimum length.</exception> /// <exception cref="InvalidOperationException">Thrown when all password characteristics are <c>No</c>.</exception> /// <exception cref="ArgumentNullEmptyWhiteSpaceException">Thrown when passwordAllowedSpecialCharacters is null, empty, or white space.</exception> public static String Generate(Int32 minimumLength, Int32 maximumLength, SpecialCharacter specialCharacter, DigitCharacter digitCharacter, UpperCaseCharacter upperCaseCharacter, LowerCaseCharacter lowerCaseCharacter, String passwordAllowedSpecialCharacters = PasswordAllowedSpecialCharacters) { if (minimumLength <= Zero) { throw new ArgumentOutOfRangeException(nameof(minimumLength), Strings.MustBeGreaterThanZero); } if (maximumLength <= Zero) { throw new ArgumentOutOfRangeException(nameof(maximumLength), Strings.MustBeGreaterThanZero); } if (maximumLength < minimumLength) { throw new ArgumentOutOfRangeException(nameof(maximumLength), Strings.MustBeGreaterThanOrEqualToMinimumLength); } if (specialCharacter == SpecialCharacter.No && digitCharacter == DigitCharacter.No && specialCharacter == SpecialCharacter.No && upperCaseCharacter == UpperCaseCharacter.No && lowerCaseCharacter == LowerCaseCharacter.No) { throw new InvalidOperationException(Strings.AtLeastOnePasswordCharacteristicMustBeYes); } var characterGroupsList = new List <Char[]>(); if (specialCharacter == SpecialCharacter.Yes) { characterGroupsList.Add(passwordAllowedSpecialCharacters.ToCharArray()); } if (digitCharacter == DigitCharacter.Yes) { characterGroupsList.Add(PasswordCharactersNumeric.ToCharArray()); } if (upperCaseCharacter == UpperCaseCharacter.Yes) { characterGroupsList.Add(PasswordCharactersUpperCase.ToCharArray()); } if (lowerCaseCharacter == LowerCaseCharacter.Yes) { characterGroupsList.Add(PasswordCharactersLowerCase.ToCharArray()); } var characterGroups = characterGroupsList.ToArray(); //Use this array to track the number of unused characters in each character group. var charsRemainingInGroup = new Int32[characterGroups.Length]; //Initially, all characters in each group are not used. Int32 i; for (i = 0; i < charsRemainingInGroup.Length; i++) { charsRemainingInGroup[i] = characterGroups[i].Length; } //Use this array to track (iterate through) unused character groups. var remainingGroupsOrder = new Int32[characterGroups.Length]; //Initially, all character groups are not used. for (i = 0; i < remainingGroupsOrder.Length; i++) { remainingGroupsOrder[i] = i; } var randomBytes = new Byte[4]; using (var rng = new RNGCryptoServiceProvider()) { rng.GetBytes(randomBytes); } //Convert 4 bytes into a 32-bit integer value. Int32 seed = (randomBytes[0] & 0X7F) << 24 | randomBytes[1] << 16 | randomBytes[2] << 8 | randomBytes[3]; var random = new Random(seed); Char[] password = minimumLength < maximumLength ? new Char[random.Next(minimumLength - 1, maximumLength) + 1] : new Char[minimumLength]; Int32 nextCharacterIndex; Int32 nextGroupIndex; Int32 nextRemainingGroupsOrderIndex; Int32 lastCharacterIndex; Int32 lastRemainingGroupsOrderIndex = remainingGroupsOrder.Length - 1; //Generate password characters one at a time. for (i = 0; i < password.Length; i++) { //If only one character group remained unprocessed, process it; //otherwise, pick a random character group from the unprocessed //group list. To allow a special character to appear in the //first position, increment the second parameter of the Next //function call by one, i.e. lastLeftGroupsOrderIdx + 1. nextRemainingGroupsOrderIndex = lastRemainingGroupsOrderIndex == 0 ? 0 : random.Next(0, lastRemainingGroupsOrderIndex); //Get the actual index of the character group, from which we will //pick the next character. nextGroupIndex = remainingGroupsOrder[nextRemainingGroupsOrderIndex]; //Get the index of the last unprocessed characters in this group. lastCharacterIndex = charsRemainingInGroup[nextGroupIndex] - 1; //If only one unprocessed character is left, pick it; otherwise, //get a random character from the unused character list. nextCharacterIndex = lastCharacterIndex == 0 ? 0 : random.Next(0, lastCharacterIndex + 1); //Add this character to the password. password[i] = characterGroups[nextGroupIndex][nextCharacterIndex]; //If we processed the last character in this group, start over. if (lastCharacterIndex == 0) { charsRemainingInGroup[nextGroupIndex] = characterGroups[nextGroupIndex].Length; //There are more unprocessed characters left. } else { //Swap processed character with the last unprocessed character //so that we don't pick it until we process all characters in //this group. if (lastCharacterIndex != nextCharacterIndex) { Char temp = characterGroups[nextGroupIndex][lastCharacterIndex]; characterGroups[nextGroupIndex][lastCharacterIndex] = characterGroups[nextGroupIndex][nextCharacterIndex]; characterGroups[nextGroupIndex][nextCharacterIndex] = temp; } //Decrement the number of unprocessed characters in //this group. charsRemainingInGroup[nextGroupIndex] = charsRemainingInGroup[nextGroupIndex] - 1; } //If we processed the last group, start all over. if (lastRemainingGroupsOrderIndex == 0) { lastRemainingGroupsOrderIndex = remainingGroupsOrder.Length - 1; //There are more unprocessed groups left. } else { //Swap processed group with the last unprocessed group //so that we don't pick it until we process all groups. if (lastRemainingGroupsOrderIndex != nextRemainingGroupsOrderIndex) { Int32 temp = remainingGroupsOrder[lastRemainingGroupsOrderIndex]; remainingGroupsOrder[lastRemainingGroupsOrderIndex] = remainingGroupsOrder[nextRemainingGroupsOrderIndex]; remainingGroupsOrder[nextRemainingGroupsOrderIndex] = temp; } //Decrement the number of unprocessed groups. lastRemainingGroupsOrderIndex -= 1; } } //Convert password characters into a String and return the result. return(new String(password)); }
public Character(SpecialCharacter character) { IsCode = true; Code = (int)character; }
/// <summary> /// Создание нового документа /// </summary> /// <param name="Format">Формат файла</param> protected void CreateDocx(string Format) { DBConnection connection = new DBConnection(); string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"Termination contract № " + tbNumber.Text + Format; DocumentCore dc = new DocumentCore(); Section section = new Section(dc); dc.Sections.Add(section); section.PageSetup.PaperType = PaperType.A4; //Добавление строк dc.Content.End.Insert("\nПРИКАЗ О РАСТОРЖЕНИИ ТРУДОВОГО ДОГОВОРА № " + tbNumber.Text + "", new CharacterFormat() { FontName = "Times New Roman", Size = 18, FontColor = SautinSoft.Document.Color.Black, Bold = true }); SpecialCharacter lBr = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr.Content); dc.Content.End.Insert("" + tbData.Text + "г.", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black, }); SpecialCharacter lBr2 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr2.Content); dc.Content.End.Insert("Прекращение трудового договора с сотрудником " + ddlContract.SelectedItem.Text + ".", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black, }); SpecialCharacter lBr3 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr2.Content); dc.Content.End.Insert("Причина увольнения: " + tbReason.Text + ".", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black }); //Документ в формате .docx if (Format == ".docx") { // Сохраняем документ в формате .docx dc.Save(docPath, new DocxSaveOptions()); // Открываем документ Process.Start(new ProcessStartInfo(docPath) { UseShellExecute = true }); } //Документ в другом формате (тут .pdf) else { dc.Save(docPath, new PdfSaveOptions() { Compliance = PdfCompliance.PDF_A, PreserveFormFields = true }); // Open the result for demonstration purposes. Process.Start(new ProcessStartInfo(docPath) { UseShellExecute = true }); } }
/// <summary> /// Creates a simple Docx document. /// </summary> public static void CreateDocx() { // Set a path to our docx file. string docxPath = @"..\..\..\..\..\Testing Files\Result.docx"; // Let's create a simple DOCX document. DocumentCore docx = new DocumentCore(); //DocumentCore.Serial = "put your serial here"; // Add new section. Section section = new Section(docx); docx.Sections.Add(section); // Let's set page size A4. section.PageSetup.PaperType = PaperType.A4; // Add two paragraphs using different ways: // Way 1: Add 1st paragraph. section.Blocks.Add(new Paragraph(docx, "This is a first line in 1st paragraph!")); Paragraph par1 = section.Blocks[0] as Paragraph; par1.ParagraphFormat.Alignment = HorizontalAlignment.Center; // Let's add a second line. par1.Inlines.Add(new SpecialCharacter(docx, SpecialCharacterType.LineBreak)); par1.Inlines.Add(new Run(docx, "Let's type a second line.")); // Let's change font name, size and color. CharacterFormat cf = new CharacterFormat() { FontName = "Verdana", Size = 16, FontColor = Color.Orange }; foreach (Inline inline in par1.Inlines) { if (inline is Run) { (inline as Run).CharacterFormat = cf.Clone(); } } // Way 2 (easy): Add 2nd paragarph using another way. docx.Content.End.Insert("\nThis is a first line in 2nd paragraph.", new CharacterFormat() { Size = 25, FontColor = Color.Blue, Bold = true }); SpecialCharacter lBr = new SpecialCharacter(docx, SpecialCharacterType.LineBreak); docx.Content.End.Insert(lBr.Content); docx.Content.End.Insert("This is a second line.", new CharacterFormat() { Size = 20, FontColor = Color.DarkGreen, UnderlineStyle = UnderlineType.Single }); // Save DOCX to a file docx.Save(docxPath); // Open the result for demonstation purposes. System.Diagnostics.Process.Start(docxPath); }
/// <summary>Initializes a new instance of the <see cref="PasswordValidatorAttribute"/> class.</summary> /// <param name="lowerCaseCharacter">Is a lower case character required.</param> /// <param name="upperCaseCharacter">Is an upper case character required.</param> /// <param name="digitCharacter">Is a digit character required.</param> /// <param name="specialCharacter">Is a special character required.</param> /// <param name="requiredEntry">Is the entry required.</param> /// <param name="allowedPasswordSpecialCharacters">The allowed password special characters. Change value to limit or increase the number of special characters.</param> /// <exception cref="ArgumentOutOfRangeException">Thrown when minimumLength is less than one.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when maximumLength is less than one.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when maximumLength less than or equal to Minimum Length.</exception> /// <exception cref="InvalidEnumArgumentException">Thrown when enum value lowerCaseCharacter is not defined.</exception> /// <exception cref="InvalidEnumArgumentException">Thrown when enum value upperCaseCharacter is not defined.</exception> /// <exception cref="InvalidEnumArgumentException">Thrown when enum value digitCharacter is not defined.</exception> /// <exception cref="InvalidEnumArgumentException">Thrown when enum value specialCharacter is not defined.</exception> /// <exception cref="InvalidEnumArgumentException">Thrown when enum value requiredEntry is not defined.</exception> /// <exception cref="ArgumentNullEmptyWhiteSpaceException">Thrown when allowedPasswordSpecialCharacters is null, empty, or white space.</exception> public PasswordValidatorAttribute(Int32 minimumLength, Int32 maximumLength, LowerCaseCharacter lowerCaseCharacter, UpperCaseCharacter upperCaseCharacter, DigitCharacter digitCharacter, SpecialCharacter specialCharacter, RequiredEntry requiredEntry, String allowedPasswordSpecialCharacters = "!@#$*&^%()-_+|") { if (minimumLength < One) { throw new ArgumentOutOfRangeException(nameof(minimumLength), Strings.MustBeGreaterThanZero); } if (maximumLength < One) { throw new ArgumentOutOfRangeException(nameof(maximumLength), Strings.MustBeGreaterThanZero); } if (maximumLength < minimumLength) { throw new ArgumentOutOfRangeException(nameof(maximumLength), Strings.MustBeGreaterThanOrEqualToMinimumLength); } if (!Enum.IsDefined(typeof(LowerCaseCharacter), lowerCaseCharacter)) { throw new InvalidEnumArgumentException(nameof(lowerCaseCharacter), (Int32)lowerCaseCharacter, typeof(LowerCaseCharacter)); } if (!Enum.IsDefined(typeof(UpperCaseCharacter), upperCaseCharacter)) { throw new InvalidEnumArgumentException(nameof(upperCaseCharacter), (Int32)upperCaseCharacter, typeof(UpperCaseCharacter)); } if (!Enum.IsDefined(typeof(DigitCharacter), digitCharacter)) { throw new InvalidEnumArgumentException(nameof(digitCharacter), (Int32)digitCharacter, typeof(DigitCharacter)); } if (!Enum.IsDefined(typeof(SpecialCharacter), specialCharacter)) { throw new InvalidEnumArgumentException(nameof(specialCharacter), (Int32)specialCharacter, typeof(SpecialCharacter)); } if (!Enum.IsDefined(typeof(RequiredEntry), requiredEntry)) { throw new InvalidEnumArgumentException(nameof(requiredEntry), (Int32)requiredEntry, typeof(RequiredEntry)); } if (specialCharacter == SpecialCharacter.Yes && String.IsNullOrWhiteSpace(allowedPasswordSpecialCharacters)) { throw new ArgumentNullEmptyWhiteSpaceException(nameof(allowedPasswordSpecialCharacters)); } this.MinimumLength = minimumLength; this.MaximumLength = maximumLength; this.LowerCaseCharacter = lowerCaseCharacter; this.UpperCaseCharacter = upperCaseCharacter; this.DigitCharacter = digitCharacter; this.SpecialCharacter = specialCharacter; this.AllowedPasswordSpecialCharacters = allowedPasswordSpecialCharacters; this.RequiredEntry = requiredEntry; }
/// <summary> /// Creates a simple RTF document. /// </summary> public static void CreateRtf() { // Working directory string workingDir = Path.GetFullPath(Directory.GetCurrentDirectory() + @"..\..\..\..\..\..\Testing Files"); string rtfFilePath = Path.Combine(workingDir, "Result.rtf"); // Let's create a simple RTF document. DocumentCore rtf = new DocumentCore(); //DocumentCore.Serial = "put your serial here"; // Add new section. Section section = new Section(rtf); rtf.Sections.Add(section); // Let's set page size A4. section.PageSetup.PaperType = PaperType.A4; // Add two paragraphs using different ways: // Way 1: Add 1st paragraph. section.Blocks.Add(new Paragraph(rtf, "This is a first line in 1st paragraph!")); Paragraph par1 = section.Blocks[0] as Paragraph; par1.ParagraphFormat.Alignment = HorizontalAlignment.Center; // Let's add a second line. par1.Inlines.Add(new SpecialCharacter(rtf, SpecialCharacterType.LineBreak)); par1.Inlines.Add(new Run(rtf, "Let's type a second line.")); // Let's change font name, size and color. CharacterFormat cf = new CharacterFormat() { FontName = "Verdana", Size = 16, FontColor = Color.Orange }; foreach (Inline inline in par1.Inlines) { if (inline is Run) { (inline as Run).CharacterFormat = cf.Clone(); } } // Way 2 (easy): Add 2nd paragarph using another way. rtf.Content.End.Insert("\nThis is a first line in 2nd paragraph.", new CharacterFormat() { Size = 25, FontColor = Color.Blue, Bold = true }); SpecialCharacter lBr = new SpecialCharacter(rtf, SpecialCharacterType.LineBreak); rtf.Content.End.Insert(lBr.Content); rtf.Content.End.Insert("This is a second line.", new CharacterFormat() { Size = 20, FontColor = Color.DarkGreen, UnderlineStyle = UnderlineType.Single }); // Save RTF to a file rtf.Save(rtfFilePath, SaveOptions.RtfDefault); // Open the result for demonstation purposes. System.Diagnostics.Process.Start(rtfFilePath); }
//Формирование документа protected void CreateDocx() { SqlCommand command = new SqlCommand("", DBConnection.connection); //Получение времени command.CommandType = System.Data.CommandType.Text; command.CommandText = "SELECT [Time] FROM [Check] where [Order_ID] = " + DBConnection.selectedRow + ""; DBConnection.connection.Open(); string Time = command.ExecuteScalar().ToString(); command.ExecuteNonQuery(); DBConnection.connection.Close(); //Получение даты command.CommandType = System.Data.CommandType.Text; command.CommandText = "SELECT [Date] FROM [Check] where [Order_ID] = " + DBConnection.selectedRow + ""; DBConnection.connection.Open(); string Date = command.ExecuteScalar().ToString(); command.ExecuteNonQuery(); DBConnection.connection.Close(); //Получение фамилии сотрудника command.CommandType = System.Data.CommandType.Text; command.CommandText = "SELECT [Employee_Surname] FROM [Check] inner join [Employee] on [ID_Employee] = [Employee_ID] where [Check_Number] = " + tbCheckNumber.Text + ""; DBConnection.connection.Open(); string Employee = command.ExecuteScalar().ToString(); command.ExecuteNonQuery(); DBConnection.connection.Close(); //Получение цены command.CommandType = System.Data.CommandType.Text; command.CommandText = "select [Price] from [Order] inner join [Product] on [ID_Product] = [Product_ID] where [ID_Order] = " + DBConnection.selectedRow + ""; DBConnection.connection.Open(); string Cost = command.ExecuteScalar().ToString(); command.ExecuteNonQuery(); DBConnection.connection.Close(); DBConnection connection = new DBConnection(); string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"Check № " + tbCheckNumber.Text + ".pdf"; DocumentCore dc = new DocumentCore(); Section section = new Section(dc); dc.Sections.Add(section); section.PageSetup.PaperType = PaperType.A4; dc.Content.End.Insert("\nОрганизация 'Мобильный магазин'", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black }); SpecialCharacter lBr = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr.Content); dc.Content.End.Insert("\nЧек № " + tbCheckNumber.Text + ".", new CharacterFormat() { FontName = "Times New Roman", Size = 18, FontColor = SautinSoft.Document.Color.Black, Bold = true }); (dc.Sections[0].Blocks[1] as Paragraph).ParagraphFormat.Alignment = HorizontalAlignment.Center; SpecialCharacter lBr4 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr4.Content); dc.Content.End.Insert("" + Date + " " + Time + " ", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black, }); SpecialCharacter lBr5 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr5.Content); dc.Content.End.Insert("Наименование товара: " + ddlProduct.SelectedItem.Text + ". Цена за 1 штуку: " + Cost + ". Кол-во: " + tbQuantity.Text + ". Сумма: " + tbSum.Text + "", new CharacterFormat() { FontName = "Times New Roman", Size = 18, FontColor = SautinSoft.Document.Color.Black, }); SpecialCharacter lBr6 = new SpecialCharacter(dc, SpecialCharacterType.LineBreak); dc.Content.End.Insert(lBr6.Content); dc.Content.End.Insert("Кассир: " + Employee + "", new CharacterFormat() { FontName = "Times New Roman", Size = 14, FontColor = SautinSoft.Document.Color.Black }); dc.Save(docPath, new PdfSaveOptions() { Compliance = PdfCompliance.PDF_A, PreserveFormFields = true }); Process.Start(new ProcessStartInfo(docPath) { UseShellExecute = true }); }
public static string EscapeSpecialCharacterForGrep(this string grep) => new string( grep .SelectMany(c => SpecialCharacter.Contains(c) ? new[] { '\\', c } : new[] { c }) .ToArray());