Exemplo n.º 1
0
    protected void Create_document(object sender, EventArgs e)
    {
        string value = Request.QueryString["Id"];

        //create word document
        //OBJECT OF MISSING "NULL VALUE"
        Object oMissing = System.Reflection.Missing.Value;

        //OBJECTS OF FALSE AND TRUE
        Object oTrue        = true;
        Object oFalse       = false;
        int    iTotalFields = 0;

        //CREATING OBJECTS OF WORD AND DOCUMENT
        Microsoft.Office.Interop.Word.Application oWord    = new Microsoft.Office.Interop.Word.Application();
        Microsoft.Office.Interop.Word.Document    oWordDoc = new Microsoft.Office.Interop.Word.Document();

        //SETTING THE VISIBILITY TO TRUE
        oWord.Visible = true;

        //THE LOCATION OF THE TEMPLATE FILE ON THE MACHINE
        //Object oTemplatePath = "C:\\YASA_PL_07_07_2014--\\dokumenty_dodatkowe\\zamowienie.doc";  //praca
        //Object oTemplatePath = "C:\\Users\\LEOTEC\\Documents\\Visual Studio 2013\\WebSites\\YASA_PL_04_07_2014--\\dokumenty_dodatkowe\\zamowienie.doc"; //dom
        Object oTemplatePath = (System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dokumenty_dodatkowe/zamowienie.doc"));

        //ADDING A NEW DOCUMENT FROM A TEMPLATE
        oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
        //   string custom_con_string = "Data Source=TECHNOLOG-DELL\\SQLEXPRESS;Integrated Security=true;Initial Catalog=YASA_PL";



        using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["custom_connection_YASA_PLContainer"].ConnectionString)) //praca
        //using (SqlConnection con = new SqlConnection("Data Source=LEOTEC-KOMPUTER\\ENOVIA_DB;Integrated Security=true;Initial Catalog=YASA_PL")) //dom
        {
            con.Open();
            SqlCommand cmd1 = new SqlCommand("SELECT Id,Title,Description, Date_created_modified, Date_required, ContractorId, UserId, Contractor_offer_name_number FROM Contractor_OrderSet where Id=@username", con);
            cmd1.Parameters.AddWithValue("@username", value);
            cmd1.CommandType = CommandType.Text;
            YASA_PL.Contractor_Order c = new YASA_PL.Contractor_Order();

            using (SqlDataReader rdr = cmd1.ExecuteReader())
            {
                if (rdr.HasRows)
                {
                    rdr.Read(); // get the first row

                    c.Id                           = rdr.GetInt32(0);
                    c.Title                        = rdr.GetString(1);
                    c.Description                  = rdr.GetString(2);
                    c.Date_created_modified        = rdr.GetDateTime(3);
                    c.Date_required                = rdr.GetDateTime(4);
                    c.ContractorId                 = rdr.GetInt32(5);
                    c.UserId                       = rdr.GetInt32(6);
                    c.Contractor_offer_name_number = rdr.GetString(7);
                }
            }

            SqlCommand cmd2 = new SqlCommand("SELECT Id,Name,Address, City, Postal_Code, Phone, Email, Www, CountryId FROM ContractorSet where Id=@ContractorId", con);
            cmd2.Parameters.AddWithValue("@ContractorId", c.ContractorId);
            cmd2.CommandType = CommandType.Text;
            YASA_PL.Contractor c2 = new YASA_PL.Contractor();

            using (SqlDataReader rdr2 = cmd2.ExecuteReader())
            {
                if (rdr2.HasRows)
                {
                    rdr2.Read(); // get the first row

                    c2.Id          = rdr2.GetInt32(0);
                    c2.Name        = rdr2.GetString(1);
                    c2.Address     = rdr2.GetString(2);
                    c2.City        = rdr2.GetString(3);
                    c2.Postal_Code = rdr2.GetString(4);
                    c2.Phone       = rdr2.GetString(5);
                    c2.Email       = rdr2.GetString(6);
                    c2.Www         = rdr2.GetString(7);
                    c2.CountryId   = rdr2.GetInt32(8);
                }
            }

            SqlCommand cmd3 = new SqlCommand("SELECT Id,F_Name,L_Name, PositionId, DepartmentId, Email, W_Phone_No, M_Phone_No FROM Users where Id=@UserId", con);
            cmd3.Parameters.AddWithValue("@UserId", c.UserId);
            cmd3.CommandType = CommandType.Text;
            YASA_PL.User c3 = new YASA_PL.User();

            using (SqlDataReader rdr3 = cmd3.ExecuteReader())
            {
                if (rdr3.HasRows)
                {
                    rdr3.Read(); // get the first row

                    c3.Id           = rdr3.GetInt32(0);
                    c3.F_Name       = rdr3.GetString(1);
                    c3.L_Name       = rdr3.GetString(2);
                    c3.PositionId   = rdr3.GetInt32(3);
                    c3.DepartmentId = rdr3.GetInt32(4);
                    c3.Email        = rdr3.GetString(5);
                    c3.W_Phone_No   = rdr3.GetString(6);
                    c3.M_Phone_No   = rdr3.GetString(7);
                }
            }

            SqlCommand cmd4 = new SqlCommand("SELECT Id, Name FROM Departments where Id=@DepartmentId", con);
            cmd4.Parameters.AddWithValue("@DepartmentId", c3.DepartmentId);
            cmd4.CommandType = CommandType.Text;
            YASA_PL.Department c4 = new YASA_PL.Department();

            using (SqlDataReader rdr4 = cmd4.ExecuteReader())
            {
                if (rdr4.HasRows)
                {
                    rdr4.Read(); // get the first row

                    c4.Id   = rdr4.GetInt32(0);
                    c4.Name = rdr4.GetString(1);
                }
            }

            SqlCommand cmd5 = new SqlCommand("SELECT Id, Name FROM Countries where Id=@CountryId", con);
            cmd5.Parameters.AddWithValue("@CountryId", c2.CountryId);
            cmd5.CommandType = CommandType.Text;
            YASA_PL.Department c5 = new YASA_PL.Department();

            using (SqlDataReader rdr5 = cmd5.ExecuteReader())
            {
                if (rdr5.HasRows)
                {
                    rdr5.Read(); // get the first row

                    c5.Id   = rdr5.GetInt32(0);
                    c5.Name = rdr5.GetString(1);
                }
            }



            foreach (Microsoft.Office.Interop.Word.Field myMergeField in oWordDoc.Fields)
            {
                iTotalFields++;
                Microsoft.Office.Interop.Word.Range rngFieldCode = myMergeField.Code;
                String fieldText = rngFieldCode.Text;

                // ONLY GETTING THE MAILMERGE FIELDS
                if (fieldText.StartsWith(" MERGEFIELD"))
                {
                    // THE TEXT COMES IN THE FORMAT OF
                    // MERGEFIELD  MyFieldName  \\* MERGEFORMAT
                    // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"
                    Int32  endMerge        = fieldText.IndexOf("\\");
                    Int32  fieldNameLength = fieldText.Length - endMerge;
                    String fieldName       = fieldText.Substring(11, endMerge - 11);

                    // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE
                    fieldName = fieldName.Trim();

                    // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//
                    // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE
                    if (fieldName == "Id")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c.Id.ToString());
                    }

                    if (fieldName == "dostawca_tresc_zam")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c.Description.ToString());
                    }

                    if (fieldName == "tytul")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c.Title.ToString());
                    }

                    if (fieldName == "data")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c.Date_created_modified.ToShortDateString().ToString());
                    }

                    if (fieldName == "datadostawy")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c.Date_required.ToShortDateString().ToString());
                    }

                    if (fieldName == "nr_oferty")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c.Contractor_offer_name_number.ToString());
                    }

                    if (fieldName == "dostawca_nazwa")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c2.Name.ToString());
                    }

                    if (fieldName == "dostawca_adres")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c2.Address.ToString());
                    }

                    if (fieldName == "dostawca_kod")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c2.Postal_Code.ToString());
                    }

                    if (fieldName == "dostawca_miasto")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c2.City.ToString());
                    }

                    if (fieldName == "dostawca_tel")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c2.Phone.ToString());
                    }

                    if (fieldName == "dostawca_email")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c2.Email.ToString());
                    }

                    if (fieldName == "zamawiajacy__imie")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c3.F_Name.ToString());
                    }

                    if (fieldName == "zamawiajacy_nazwisko")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c3.L_Name.ToString());
                    }

                    if (fieldName == "user_tel")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c3.W_Phone_No.ToString());
                    }

                    if (fieldName == "user_tel_mobile")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c3.M_Phone_No.ToString());
                    }

                    if (fieldName == "user_email")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c3.Email.ToString());
                    }

                    if (fieldName == "zamawiajacy_stanowisko")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c4.Name.ToString());
                    }

                    if (fieldName == "dostawca_panstwo")
                    {
                        myMergeField.Select(); oWord.Selection.TypeText(c5.Name.ToString());
                    }
                }
            }
        }
    }
Exemplo n.º 2
0
    /*void saveToPdf(string base64Str, string filePath, string file)
     * {
     *  byte[] bytes = Convert.FromBase64String(base64Str);
     *  //string filename = file + ".pdf";
     *  //string filename = CheckBoxList1.SelectedItem.ToString();
     *  //string filepath = CheckBoxList1.SelectedValue;
     *
     *  //System.IO.FileStream stream = new FileStream(filePath + filename, FileMode.CreateNew);
     * // System.IO.BinaryWriter writer = new BinaryWriter(stream);
     *  //writer.Write(bytes, 0, bytes.Length);
     *  //writer.Close();
     * }*/

    #region Send Message New Business/ Cover Note
    //send message button for new business
    protected void Button7_Click(object sender, EventArgs e)
    {
        MemoryStream ms1 = new MemoryStream();

        try
        {
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress("*****@*****.**", "Coverinaclick.ie", System.Text.Encoding.UTF8);
            msg.To.Add(to_email.Text);
            msg.Subject         = subject.Text;
            msg.SubjectEncoding = System.Text.Encoding.UTF8;
            //msg.Body = message_area.Value;
            msg.BodyEncoding = System.Text.Encoding.UTF8;
            msg.IsBodyHtml   = true;
            var application = new Microsoft.Office.Interop.Word.Application();
            var document    = new Microsoft.Office.Interop.Word.Document();


            document = application.Documents.Add(Template: @"c:\Projects\CoverNote.docx");
            //application.Visible = true;

            foreach (Microsoft.Office.Interop.Word.Field field in document.Fields)
            {
                if (field.Code.Text.Contains("FirstName"))
                {
                    field.Select();
                    application.Selection.TypeText(fullname_txtbox.Text);
                }
                else if (field.Code.Text.Contains("date"))
                {
                    field.Select();
                    application.Selection.TypeText(TextBox2.Text);
                }
                else if (field.Code.Text.Contains("InsuranceCoy"))
                {
                    field.Select();
                    application.Selection.TypeText("Axa");
                }
                else if (field.Code.Text.Contains("benefits"))
                {
                    field.Select();
                    List <String> CheckBoxListStr1 = new List <string>();
                    foreach (ListItem item1 in CheckBoxList3.Items)
                    {
                        if (item1.Selected)
                        {
                            CheckBoxListStr1.Add(item1.Value);
                        }
                    }

                    String checkList1 = String.Join(" ", CheckBoxListStr1.ToArray());
                    application.Selection.TypeText(checkList1);
                }
                else if (field.Code.Text.Contains("docs"))
                {
                    field.Select();
                    List <String> CheckBoxListStr = new List <string>();
                    foreach (ListItem item in CheckBoxList2.Items)
                    {
                        if (item.Selected)
                        {
                            CheckBoxListStr.Add(item.Value);
                        }
                    }

                    String checkList = String.Join(Environment.NewLine, CheckBoxListStr.ToArray());
                    application.Selection.TypeText(checkList);
                }
            }
            DateTime add_Months = Convert.ToDateTime(TextBox2.Text).AddDays(365);
            TextBox3.Text = add_Months.ToString();

            var x = double.Parse(gross_amt.Text);
            var y = double.Parse(chrg.Text);
            var z = x + y;

            List <String> checkbxlst = new List <string>();
            foreach (ListItem item in CheckBoxList3.Items)
            {
                if (item.Selected)
                {
                    checkbxlst.Add(item.Value);
                }
            }
            string theList = String.Join(",", checkbxlst.ToArray());

            List <String> checkbxlst1 = new List <string>();
            foreach (ListItem item in CheckBoxList2.Items)
            {
                if (item.Selected)
                {
                    checkbxlst1.Add(item.Value);
                }
            }
            string theList1 = String.Join(",", checkbxlst1.ToArray());

            //msg.Body = document.Content.Text;
            msg.Body = "<p>Dear " + fullname_txtbox.Text + ", </p>" + "<p> Thank you for your new business instruction, we have incepted cover from " + TextBox2.Text + ". </p>" +
                       "\n" + "<p> Find attached proposal form/statement of fact, which contains the information on which we have provided the quotation and incepted cover. Ensure that you read the proposal form/statement of fact to ensure all risk details are correct. If any of the details are not accurate to the acceptance and assessment of the risk, then please provide full details immediately. </p>"
                       + "<p> Your policy would include: </p>" + "&#8594 " + theList
                       + "<p> The proposal form/statement of fact will form part of the contract between you and your insurance company. </p>"
                       + "<p> Please forward the following documents within 7 days:  </p>" + "&#8594" + theList1
                       + "\n" + "<p>Thank you </p>" + "\n----------------" + "<br />" + "coverinaclick.ie"
                       + "<br />Insurance House"
                       + "<br />" + "62A Terenure Road North"
                       + "<br />" + "Terenure"
                       + "<br />" + "Dublin 6W"
                       + "<p><a href = www.insuremyvan.ie><img src = imv.jpg alt = IMV_LOGO></a>"
                       + "<a href = www.coverinaclick.ie><img src = ciac.jpg alt = CIAC_LOGO></a>"
                       + "<a href = www.insuremyhouse.ie><img src = imh.jpg alt = IMH_LOGO></a></p>"

                       /*+ "<p> --------------------------------------------------------------------------------------------"
                        + "<br />" + "-------------------------------------------------------------------------------------------"
                        + "<br />" + " &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp<strong> INVOICE </strong>"
                        + "<br />" + "Should you wish to make any further alterations to your policy, please advise us, and any adjustments will be dealt with when completed."
                        + "\n" + "<table border = 1 style = width:100%> <tr> <td> Period of cover: &nbsp &nbsp &nbsp" + TextBox2.Text + " " + "to" + " " + TextBox3.Text
                        + "<p> Premium:  &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp" + "€" + gross_amt.Text + "</p>"
                        + "<p>Administration charge: &nbsp &nbsp &nbsp &nbsp  " + "€" + chrg.Text + "</p>"
                        + "<p><strong> TOTAL PREMIUM: &nbsp &nbsp &nbsp &nbsp </strong>" + "€" + z + "</p></td></tr></table>"*/
                       + "<p><strong> SPECIAL NOTICE - DUTY OF DISCLOSURE</strong> </P>"
                       + "\n" + "<ol>" + "<li> Duty of Disclosure: Any facts known to you, and any changes affecting the risk since inception of the policy or last renewal date (whichever is the later) must be disclosed to us. Failure to disclose may mean that your policy may not provide you with the cover you require, or may invalidate the policy altogether.</li>"
                       + "<li> The amount shown includes a 5% Government levy and an Administration Charge (1989 Insurance Act of Practice)</li>" + "</ol>"
                       + "<p><font color = blue> City Financial Marketing Group Ltd is regulated by the Central Bank of Ireland</p>"
                       + "<p>City Financial Marketing is a memeber of the Irish Brokers Association</p>"
                       + "<p>City Financial Marketing Group Ltd is a company registered in Ireland. Registered office is situated at 70 Northumberland Road, Ballsbridge, Dublin 4, Registered Number 235088.</p>"
                       + "<p>This e-mail and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. If you have received this e-mail in error please notify the sender. Please note that any views or opinions presented in this e-mail are solely those of the author and do not necessarily represent those of the CFM Group. Finally, whilst every effort has been made to ensure this e-mail and any attachments are virus free CFM Group Ltd accepts no liability for any damage caused should any viruses be transmitted by this email.</p>"
                       + "\nPlease consider the environment before printing this email.</font>";



            using (System.IO.MemoryStream ms = new MemoryStream())
            {
                using (System.IO.StreamWriter writer = new StreamWriter(ms))
                {
                    writer.Write("Hello");
                    writer.Flush();
                    //writer.Dispose();

                    System.Net.Mime.ContentType ct        = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
                    System.Net.Mail.Attachment  attchFile = new Attachment(ms, ct);
                    //attchFile.ContentStream.
                    attchFile.ContentDisposition.FileName = "Terms of Business.pdf";
                    msg.Attachments.Add(attchFile);
                    if (FileUpload3.HasFile)
                    {
                        Attachment attachment;
                        attachment = (new Attachment(FileUpload3.PostedFile.InputStream, FileUpload3.FileName));
                        attachment.ContentDisposition.FileName = "Your Policy Booklet.pdf";
                        msg.Attachments.Add(attachment);
                    }
                    if (FileUpload4.HasFile)
                    {
                        Attachment attachment1;
                        attachment1 = (new Attachment(FileUpload4.PostedFile.InputStream, FileUpload4.FileName));
                        attachment1.ContentDisposition.FileName = "Proposal Form " + "/" + "Statement of Fact.pdf";
                        msg.Attachments.Add(attachment1);
                    }
                    if (FileUpload5.HasFile)
                    {
                        //Directory.CreateDirectory(@"");
                        Attachment attachment2;
                        attachment2 = (new Attachment(FileUpload5.PostedFile.InputStream, FileUpload5.FileName));
                        attachment2.ContentDisposition.FileName = "Direct Debit Mandate.pdf";
                        msg.Attachments.Add(attachment2);
                    }
                    if (FileUpload6.HasFile)
                    {
                        //Directory.CreateDirectory(@"");
                        Attachment attachment3;
                        attachment3 = (new Attachment(FileUpload6.PostedFile.InputStream, FileUpload6.FileName));
                        attachment3.ContentDisposition.FileName = "Gap in Cover";
                        msg.Attachments.Add(attachment3);
                    }
                    if (FileUpload7.HasFile)
                    {
                        //Directory.CreateDirectory(@"");
                        Attachment attachment4;
                        attachment4 = (new Attachment(FileUpload7.PostedFile.InputStream, FileUpload7.FileName));
                        attachment4.ContentDisposition.FileName = "Sold Car Declaration";
                        msg.Attachments.Add(attachment4);
                    }
                    if (FileUpload8.HasFile)
                    {
                        //Directory.CreateDirectory(@"");
                        Attachment attachment5;
                        attachment5 = (new Attachment(FileUpload8.PostedFile.InputStream, FileUpload8.FileName));
                        attachment5.ContentDisposition.FileName = "Surrender of NCB";
                        msg.Attachments.Add(attachment5);
                    }
                    msg.IsBodyHtml = true;

                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = "smtp.gmail.com";
                    System.Net.NetworkCredential netwrkcred = new System.Net.NetworkCredential();
                    netwrkcred.UserName        = "******";
                    netwrkcred.Password        = "******";
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials           = netwrkcred;
                    smtp.Port      = 587;
                    smtp.EnableSsl = true;
                    smtp.Send(msg);

                    //ms.Close();

                    ShowMessage("Message sent!!");

                    CheckBoxList3.ClearSelection();
                    //RadioButtonList1.ClearSelection();
                    to_email.Text = string.Empty;
                    //message_area.Value = string.Empty;
                    TextBox2.Text        = string.Empty;
                    fullname_txtbox.Text = string.Empty;
                    CheckBoxList2.ClearSelection();
                    gross_amt.Text = string.Empty;
                    chrg.Text      = string.Empty;
                }
            }

            //byte[] pdfByte = System.IO.File.ReadAllBytes(Server.MapPath("~/PDF Document/Timetable(1)"));
            //Attachment attachFile = new Attachment(new MemoryStream(CheckBoxList1.DataValueField), "pdf");
            // msg.Attachments.Add(attachFile);
        }
        catch (Exception ex)
        {
            Response.Write("Error" + ex.ToString());
        }
    }
Exemplo n.º 3
0
    //send message button for renewals
    protected void Button6_Click(object sender, EventArgs e)
    {
        MailMessage msg = new MailMessage();

        try
        {
            if (RadioButtonList3.SelectedValue == "Existing Insurer")
            {
                var application = new Microsoft.Office.Interop.Word.Application();
                var document    = new Microsoft.Office.Interop.Word.Document();

                document = application.Documents.Add(Template: @"c:\Projects\Existing.docx");
                //application.Visible = true;

                foreach (Microsoft.Office.Interop.Word.Field field in document.Fields)
                {
                    if (field.Code.Text.Contains("First Name"))
                    {
                        field.Select();
                        application.Selection.TypeText(f_name.Font.Bold.ToString());
                    }
                    else if (field.Code.Text.Contains("LastName"))
                    {
                        field.Select();
                        application.Selection.TypeText(l_name.Font.Bold.ToString());
                    }
                    else if (field.Code.Text.Contains("Date"))
                    {
                        field.Select();
                        application.Selection.TypeText(date.Font.Bold.ToString());
                    }
                    else if (field.Code.Text.Contains("Insurance Company Name"))
                    {
                        field.Select();
                        application.Selection.TypeText(insure_coy.Font.Bold.ToString());
                    }
                    else if (field.Code.Text.Contains("Amount"))
                    {
                        field.Select();
                        application.Selection.TypeText(amt.Font.Bold.ToString());
                    }
                }
                msg.Body = "<p>Dear " + f_name.Text + " " + l_name.Text + ", </p>"
                           + "<p>Firstly, may we take this oppurtunity to thank you for placing your insurance with www.coverinaclick.ie over the past year. </p>"
                           + "<p>There may be a lower premium available, based on a full review of your requirements. Please call our renewal team on 01-6606900 for a free review of your policy and benefits.</p>"
                           + "<p>We wish to advise you that your policy is due for renewal on " + date.Text + ". Having researched the market and based on the information provided by you previously, we believe that the best renewal most suited to your needs is"
                           + " " + amt.Text + " with " + insure_coy.Text + " .</p>"
                           + "<p>Please find attached your renewal notice and your No Claims bonus for "
                           + insure_coy.Text + ", with the Reason Why Statement and the Terms of Business. </p>"
                           + "<p> If you are happy to proceed with your renewal, simply:"
                           + "\n" + "<ul>" + "<li>Contact us directly on 01-6606900 to make payment by Credit/Debit card or to discuss <u>Direct Debit Options</u></li>"
                           + "\n" + "<li>Send us in a cheque/postal order/bank draft made payable to <u>www.insuremyvan.ie</u> to the address below</li>"
                           + "\n" + "<li>If you currently pay monthly through <strong>Close Premium Finance</strong>, please call us</li>" + "</ul>"
                           + "<p>Small changes could mean further savings to your renewal premium, please contact us on 01-6606900 for your policy review. Please note that if policy is not paid by renewal date"
                           + " " + date.Text + ", all covers will cease. </p>"
                           + "<p>We trust this is to your satisfaction and we look forward to hearing from you in this regard."
                           + "\n" + "<p>Thank you </p>" + "\n----------------" + "<br />" + "coverinaclick.ie";
            }
            else
            {
                var application1 = new Microsoft.Office.Interop.Word.Application();
                var document1    = new Microsoft.Office.Interop.Word.Document();

                document1 = application1.Documents.Add(Template: @"c:\Projects\Alternate.docx");
                //application.Visible = true;

                foreach (Microsoft.Office.Interop.Word.Field field in document1.Fields)
                {
                    if (field.Code.Text.Contains("First Name"))
                    {
                        field.Select();
                        application1.Selection.TypeText(f_name.Text);
                    }
                    else if (field.Code.Text.Contains("LastName"))
                    {
                        field.Select();
                        application1.Selection.TypeText(l_name.Text);
                    }
                    else if (field.Code.Text.Contains("Date"))
                    {
                        field.Select();
                        application1.Selection.TypeText(date.Text);
                    }
                    else if (field.Code.Text.Contains("Insurance Company Name"))
                    {
                        field.Select();
                        application1.Selection.TypeText(insure_coy.Text);
                    }
                    else if (field.Code.Text.Contains("Amount"))
                    {
                        field.Select();
                        application1.Selection.TypeText(amt_alt.Text);
                    }
                    else if (field.Code.Text.Contains("Amt"))
                    {
                        field.Select();
                        application1.Selection.TypeText(amt.Text);
                    }
                    else if (field.Code.Text.Contains("Alternate Insurance Company Name"))
                    {
                        field.Select();
                        application1.Selection.TypeText(alt_insur.Text);
                    }
                }
                msg.Body = "<p>Dear " + f_name.Text + " " + l_name.Text + ", </p>"
                           + "<p>Firstly, may we take this oppurtunity to thank you for placing your insurance with www.coverinaclick.ie over the past year. </p>"
                           + "<p>We wish to advise you that your policy is due for renewal on " + date.Text + ". Having researched our schemes and applying your customer discounts, the renewal most suited for your needs is"
                           + " " + amt_alt.Text + " with " + alt_insur.Text + "(the benefits of this alternate may differ to your current insurer, please call for further details) .</p>"
                           + "<p>Please find attached your renewal notice and your No Claims bonus from "
                           + insure_coy.Text + " " + "offering" + " " + amt.Text + ", with the Reason Why Statement and the Terms of Business. </p>"
                           + "<p> If you are happy to proceed with your renewal, simply:"
                           + "\n" + "<ul>" + "<li>Contact us directly on 01-6606900 to make payment by Credit/Debit card or to discuss <u>Direct Debit Options</u></li>"
                           + "\n" + "<li>Send us in a cheque/postal order/bank draft made payable to <u>www.insuremyvan.ie</u> to the address below</li>"
                           + "\n" + "<li>If you currently pay monthly through <strong>Close Premium Finance</strong>, please call us</li>" + "</ul>"
                           + "<p>Small changes could mean further savings to your renewal premium, please contact us on 01-6606900 for your policy review. Please note that if policy is not paid by renewal date"
                           + " " + date.Text + ", all covers will cease. </p>"
                           + "<p>We trust this is to your satisfaction and we look forward to hearing from you in this regard."
                           + "\n" + "<p>Thank you </p>" + "\n----------------" + "<br />" + "coverinaclick.ie";
            }

            msg.From = new MailAddress("*****@*****.**", "*****@*****.**");
            msg.To.Add(to_ren.Text);
            msg.Subject    = subj_ren.Text;
            msg.IsBodyHtml = true;

            //gmail stmp client settings and user credentials
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            System.Net.NetworkCredential netwrkcred = new System.Net.NetworkCredential();
            netwrkcred.UserName        = "******";
            netwrkcred.Password        = "******";
            smtp.UseDefaultCredentials = true;
            smtp.Credentials           = netwrkcred;
            smtp.Port      = 587;
            smtp.EnableSsl = true;
            if (FileUpload1.HasFile)
            {
                msg.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
            }
            if (FileUpload2.HasFile)
            {
                msg.Attachments.Add(new Attachment(FileUpload2.PostedFile.InputStream, FileUpload2.FileName));
            }
            smtp.Send(msg);

            ShowMessage("Message sent!!");     //pop up box to show message sent confirnmation
            RadioButtonList3.ClearSelection(); //clears the selected radiobutton

            //clears all the textboxes when message sent
            CheckBoxList2.ClearSelection();
            to_ren.Text     = string.Empty;
            f_name.Text     = string.Empty;
            l_name.Text     = string.Empty;
            insure_coy.Text = string.Empty;
            alt_insur.Text  = string.Empty;
            amt_alt.Text    = string.Empty;
            date.Text       = string.Empty;
            amt.Text        = string.Empty;
        }
        //throws an exception when error is detected in try
        catch (Exception ex)
        {
            Response.Write("Error" + ex.ToString());
        }
    }
    public void ExportToWord(string Type, string Head, DataGrid Grid, DataRowView GridRow, int RowNum)
    {
        try
        {
            DataTable dt = default(DataTable);
            if (Type == "One")
            {
                dt = DataGridRow_To_DataTable(Grid, GridRow, Head, RowNum);
            }
            else
            {
                dt = DataGrid_To_DataTable(Grid, Head);
            }

            if ((dt.Columns.Count > 0))
            {
                Microsoft.Office.Interop.Word.Application oWord;
                Microsoft.Office.Interop.Word.Document    oDoc;
                Microsoft.Office.Interop.Word.Table       oTable;
                Microsoft.Office.Interop.Word.Paragraph   oPara1;

                oWord         = new Microsoft.Office.Interop.Word.Application();
                oWord.Visible = false;
                oDoc          = (Microsoft.Office.Interop.Word.Document)(oWord.Documents.Add(System.Type.Missing));
                var _with1 = oDoc.PageSetup;
                _with1.PaperSize    = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperA4;
                _with1.Orientation  = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;
                _with1.LeftMargin   = oWord.CentimetersToPoints(1);
                _with1.BottomMargin = oWord.CentimetersToPoints(1);
                _with1.TopMargin    = oWord.CentimetersToPoints(1);

                oPara1                   = (Microsoft.Office.Interop.Word.Paragraph)(oDoc.Content.Paragraphs.Add(System.Type.Missing));
                oPara1.Range.Text        = Head;
                oPara1.Range.Font.Bold   = 0;
                oPara1.Range.Font.Size   = 8;
                oPara1.Format.SpaceAfter = 8;
                oPara1.Range.InsertParagraphAfter();

                if (Type == "One")
                {
                    oTable = oDoc.Tables.Add(oDoc.Bookmarks.get_Item("\\endofdoc").Range, dt.Rows.Count, 2);
                    oTable.Range.ParagraphFormat.SpaceAfter = 2;

                    for (int i = 0; i <= dt.Rows.Count - 1; i++)
                    {
                        oTable.Cell(i + 1, 1).Range.InsertAfter(Convert.ToString(dt.Rows[i][0]));
                        oTable.Cell(i + 1, 2).Range.Text = Convert.ToString(dt.Rows[i][1]);
                    }

                    oTable.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                    oTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;

                    oTable.AllowAutoFit = true;
                    oTable.Columns.AutoFit();
                }
                else if (Type == "Many")
                {
                    oTable = oDoc.Tables.Add(oDoc.Bookmarks.get_Item("\\endofdoc").Range, dt.Rows.Count + 1, dt.Columns.Count);
                    oTable.Range.ParagraphFormat.SpaceAfter = 2;

                    for (int i = 0; i <= dt.Columns.Count - 1; i++)
                    {
                        oTable.Cell(1, i + 1).Range.InsertAfter(Convert.ToString(dt.Columns[i].Caption));
                    }

                    for (int r = 0; r <= dt.Rows.Count - 1; r++)
                    {
                        for (int s = 0; s <= dt.Columns.Count - 1; s++)
                        {
                            oTable.Cell(r + 2, s + 1).Range.Text = Convert.ToString(dt.Rows[r][s]);
                        }
                    }

                    oTable.Rows[1].Cells.Shading.BackgroundPatternColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdGray25;

                    oTable.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                    oTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;

                    oTable.AllowAutoFit = true;
                    oTable.Columns.AutoFit();
                }
                oWord.Visible = true;
                oWord.NormalTemplate.Saved = true;
                oWord = null;
                oDoc  = null;
            }
        }
        catch
        {
        }
    }
Exemplo n.º 5
0
    public bool ExportToWord(DataSet ds, string path1, string path2, string[] obDD)//说明ds为数据集,path1为模版路径,path2为生成文档的路径,obDD为末班里面的书签
    {
        Microsoft.Office.Interop.Word.Application appWord = null;
        Microsoft.Office.Interop.Word.Document    doc     = null;
        try
        {
            appWord         = new Microsoft.Office.Interop.Word.ApplicationClass();
            appWord.Visible = false;
            object objTrue     = true;
            object objFalse    = false;
            object objTemplate = path1;//模板路径
            object objDocType  = Microsoft.Office.Interop.Word.WdDocumentType.wdTypeDocument;
            doc = appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue);
            //第一步生成word文档
            //定义书签变量
            int      length    = obDD.Length;
            object[] obDD_Name = new object[length];

            for (int i = 0; i < obDD.Length; i++)
            {
                obDD_Name[i] = obDD[i];

                doc.Bookmarks.get_Item(ref obDD_Name[i]).Range.Text = ds.Tables[0].Rows[0][i].ToString(); //姓 名
                // object obDD_Name = "t1";//姓 名
                //object obDD_Sex = "t2";//性 别
                //object obDD_Age = "t3";//年龄
                // object obDD_Birthday = "DD_Birthday"; //出生年月
                // object obDD_Nation = "DD_Nation"; //民 族
                // object obDD_Native = "DD_Native"; //籍 贯
                // ...
                //第二步 读取数据,填充数据集
                // SqlDataReader dr = XXXXX;//读取出来的数据集
                //第三步 给书签赋值
                //给书签赋值
                //   doc.Bookmarks.get_Item(ref obDD_Name).Range.Text = "nihao"; //姓 名
                // doc.Bookmarks.get_Item(ref obDD_Sex).Range.Text = "性 别";//性 别
                // doc.Bookmarks.get_Item(ref obDD_Age).Range.Text = Convert.ToString(DateTime.Now.Year);//年龄
            }
            // ds.Clear();
            // ....
            //第四步 生成word
            //object filename = Server.MapPath("file") + "\\" + "接收毕业生情况表" + ".doc";
            object filename = path2;
            object miss     = System.Reflection.Missing.Value;
            try
            {
                doc.SaveAs(ref filename, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
                //doc.Visible = true;//测试
            }
            catch
            {
                // System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件: " + DATAWORDPATH + tempFileName + WORDPOSTFIX);
                HttpContext.Current.Response.Write("<script>alert('系统找不到指定目录文件输出路径')<script>");
                return(false);
            }
            object missingValue     = Type.Missing;
            object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
            doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
            appWord.Application.Quit(ref miss, ref miss, ref miss);
            doc     = null;
            appWord = null;
            return(true);
            // HttpContext.Current.Response.Write("<script>alert('文档写入成功!')<script>");
        }
        catch (System.Exception a)
        {
            //捕捉异常,如果出现异常则清空实例,退出word,同时释放资源
            string aa               = a.ToString();
            object miss             = System.Reflection.Missing.Value;
            object missingValue     = Type.Missing;
            object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
            doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
            appWord.Application.Quit(ref miss, ref miss, ref miss);
            doc     = null;
            appWord = null;
            return(false);
            // HttpContext.Current.Response.Write("<script>alert('向word文件中写入数据出错:" + a.Message + "')<script>");
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int   count  = 0;
            int   ocount = 0;
            float per    = 0;
            float max    = 0;
            con = new SqlConnection(ConfigurationManager.AppSettings["LIS"]);
            cmd = new SqlCommand();
            con.Open();
            cmd.Connection  = con;
            cmd.CommandText = "select pname from Papers";
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                //Read file from location
                string pname = dr.GetString(0).ToString();


                //reader.Close();
                //TextBox1.Text = TextBox1.Text + " " + textPdf.ToString();


                //word File Code
                //   string file =pname;
                StringBuilder textWord = new StringBuilder();
                Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                object miss     = System.Reflection.Missing.Value;
                object path     = @Server.MapPath("~/Admin/Paper/" + pname);
                object readOnly = true;
                Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);

                for (int i = 0; i < docs.Paragraphs.Count; i++)
                {
                    textWord.Append(" \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString());
                }
                //TextBox1.Text = text.ToString();
                // text.Append(textWord.ToString());

                docs.Close();



                //Compare file

                string       newfile  = "~/Paper/AllPaper.txt";//path to text file
                StreamReader testTxt1 = new StreamReader(Server.MapPath(newfile));
                string       text1    = testTxt1.ReadToEnd();
                // Split the text block into an array of sentences.

                string[] sentences1 = text1.Split(new char[] { '.', '?', '!', ',' });
                // Response.Write(sentences1[1]);
                for (int i = 0; i < sentences1.Length; i++)
                {
                    // string oldfile = textPdf.ToString();//path to text file
                    // StreamReader testTxt = new StreamReader(Server.MapPath(oldfile));
                    string text = textWord.ToString();
                    // Split the text block into an array of sentences.

                    string[] sentences = text.Split(new char[] { '.', '?', '!' });
                    ocount = sentences.Length;
                    // Define the search terms. This list could also be dynamically populated at runtime.


                    string[] wordsToMatch;
                    wordsToMatch    = new string[1];
                    wordsToMatch[0] = sentences1[i];
                    // Find sentences that contain all the terms in the wordsToMatch array.
                    // Note that the number of terms to match is not specified at compile time.
                    var sentenceQuery = from sentence in sentences
                                        let w = sentence.Split(new char[] { '.', '?', '!', ';', ':', ',' },

                                                               StringSplitOptions.RemoveEmptyEntries)

                                                where w.Distinct().Intersect(wordsToMatch).Count() == wordsToMatch.Count()

                                                select sentence;
                    foreach (string str in sentenceQuery)
                    {
                        //  Response.Write("Hloo");
                        // Response.Write(str + ".");
                        //  txtFirstItem.Text = txtFirstItem.Text + " " + str + ".";
                        count++;
                        break;
                    }
                    //    Response.Write("Hloo");
                    // testTxt.Close();
                }
                //end for loop


                per = (count * 100) / ocount;
                if (per > max)
                {
                    max = per;
                }
            }
            //  float val = count / ocount;

            if (max > 100)
            {
                lblCount.Text = "100";
            }
            else
            {
                lblCount.Text = max.ToString();
            }

            if (max < 20)
            {
                lblStatus.Text = "Accepted";
            }
            else
            {
                lblStatus.Text = "Rejected";
            }
        }
    }