Exemple #1
0
        private void thesisProcess_DoWork(object sender, DoWorkEventArgs e)        //Thread start edildiğinde bu fonksiyona girer.
        {
            int failCount = 0;

            thesisProcess.ReportProgress(1);            //Yüzdeyi göstermek için kullandığımız method ReportProgres(x) x sinyalini gönderir.

            Microsoft.Office.Interop.Word.Application app = new Word.Application();
            Microsoft.Office.Interop.Word.Document    doc = app.Documents.Open(txt_thesispath.Text);         //Yukarda seçilen dosyayı Document objesinin içine yükleme işlemi.
            Word.WdStatistic stat    = Word.WdStatistic.wdStatisticPages;
            object           missing = System.Reflection.Missing.Value;
            int pageCountNumber      = doc.ComputeStatistics(stat, ref missing); //Sayfa sayısını num değişkenine atıyoruz.

            thesisProcess.ReportProgress(3);                                     //Yüzde 3

            //İlk sayfa sayısını kontrol ediyoruz.
            if (pageCountNumber < 40 || pageCountNumber > 180)
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("İdeal tez uzunluğu 40 - 180 sayfa arasında olmalıdır! Mevcut sayfa sayısı:" + pageCountNumber);
                }));
            }

            float leftmargin   = doc.PageSetup.LeftMargin;   //Sol boşluk,
            float rightmargin  = doc.PageSetup.RightMargin;  //Sağ boşluk,
            float topMargin    = doc.PageSetup.TopMargin;    //Üst boşluk,
            float bottomMargin = doc.PageSetup.BottomMargin; //Alt boşluk değerleri dokümandan okunuyor.

            if (rightmargin != 70.9f)                        //Sağ boşluğun kontrolü.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Sağ kenar boşluğu 2.5 cm olmalıdır!");
                }));
            }

            if (bottomMargin != 70.9f)            //Alt boşluğun kontrolü.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Alt kenar boşluğu 2.5 cm olmalıdır!");
                }));
            }

            if (leftmargin != 92.15f)            //Sol boşluğun kontrolü.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Sol kenar boşluğu 3.25 cm olmalıdır!");
                }));
            }

            if (topMargin != 85.05f)            //Üst boşluğun kontrolü.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Üst kenar boşluğu 3.0 cm olmalıdır!");
                }));
            }
            thesisProcess.ReportProgress(5);

            int paragraphcount = doc.Paragraphs.Count;

            int counter            = 0;
            int timesnewromancount = 0;
            int elevenpuntocounter = 0;

            bool onsozexists      = false;
            bool icindekilerexist = false;
            bool ozetexists       = false;
            bool kaynakExists     = false;
            bool beyanexists      = false;


            bool abstractExists              = false;
            bool sekilListesiexists          = false;
            bool eklerlistesiexists          = false;
            bool simgelerveKisaltmalarExists = false;

            int ShapesCount   = doc.InlineShapes.Count;
            int inShapesCount = doc.Shapes.Count;

            int tablocount = 0;

            int sekilcount = 0;

            Hashtable htSekil = new Hashtable();
            Hashtable htTablo = new Hashtable();

            double sekilCounter = 0;
            double tabloCounter = 0;

            foreach (Paragraph objParagraph in doc.Paragraphs)               //Paragrafların her biri tek tek okunup objParagraph objesinin içine atılıyor.
            {
                if (objParagraph.Range.Font.Name == "Times New Roman")       //Eğer font Times New Roman ise;
                {
                    timesnewromancount++;                                    //Times New Roman sayısı bir arttırılıyor.
                }
                if (objParagraph.Range.Font.Size == 11)                      //Font size'ı 11 ise;
                {
                    elevenpuntocounter++;                                    //Font size'ı kontrol eden değişkenimiz bir arttırılıyor.
                }
                if (objParagraph.Range.Text.Trim() == Constants.ICINDEKILER) //İçindekiler texti paragrafta bulundu mu?
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ICINDEKILER);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ICINDEKILER) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ICINDEKILER) + Constants.ICINDEKILER.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'İÇİNDEKİLER'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'İÇİNDEKİLER'");                            //Hata ekrana bastırılır..
                        }));
                    }

                    icindekilerexist = true;
                }
                if (objParagraph.Range.Text.Trim() == Constants.OZET)               //Özet texti
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.OZET);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.OZET) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.OZET) + Constants.OZET.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'Özet'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'Özet'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    ozetexists = true;
                }
                if (objParagraph.Range.Text.Trim() == Constants.ONSOZ)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ONSOZ);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ONSOZ) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ONSOZ) + Constants.ONSOZ.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'ÖNSÖZ'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'ÖNSÖZ'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    onsozexists = true;
                }
                if (objParagraph.Range.Text.Trim() == Constants.KAYNAKLAR)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.KAYNAKLAR);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.KAYNAKLAR) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.KAYNAKLAR) + Constants.KAYNAKLAR.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'KAYNAKLAR'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'KAYNAKLAR'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    kaynakExists = true;
                }
                if (objParagraph.Range.Text.Trim() == Constants.ABSTRACT)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ABSTRACT);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ABSTRACT) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ABSTRACT) + Constants.ABSTRACT.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'ABSTRACT'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'ABSTRACT'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    abstractExists = true;
                }

                if (objParagraph.Range.Text.Trim() == Constants.BEYAN)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.BEYAN);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.BEYAN) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.BEYAN) + Constants.BEYAN.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;
                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'BEYAN'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'BEYAN'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    beyanexists = true;
                }
                if (objParagraph.Range.Text.Trim() == Constants.SEKILLERLISTESI)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SEKILLERLISTESI);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SEKILLERLISTESI) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SEKILLERLISTESI) + Constants.SEKILLERLISTESI.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;
                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'ŞEKİLLER LİSTESİ'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'ŞEKİLLER LİSTESİ'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    sekilListesiexists = true;
                }

                if (objParagraph.Range.Text.Trim() == Constants.EKLERLISTESI)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.EKLERLISTESI);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.EKLERLISTESI) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.EKLERLISTESI) + Constants.EKLERLISTESI.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'EKLER LİSTESİ'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'EKLER LİSTESİ'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    eklerlistesiexists = true;
                }

                if (objParagraph.Range.Text.Trim() == Constants.SIMGELERVEKISALTMALAR)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SIMGELERVEKISALTMALAR);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SIMGELERVEKISALTMALAR) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SIMGELERVEKISALTMALAR) + Constants.SIMGELERVEKISALTMALAR.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'SİMGELER VE KISALTMALAR'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'SİMGELER VE KISALTMALAR'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    simgelerveKisaltmalarExists = true;
                }

                if (objParagraph.Range.Text.Contains(Constants.SEKIL))
                {
                    //Şekil 2.3.
                    object     start      = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SEKIL);
                    object     end        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SEKIL) + Constants.SEKIL.Length + 5;
                    Word.Range rangesekil = doc.Range(ref start, ref end);

                    bool isSekild = Helper.TextIsSekil(rangesekil.Text);

                    if (isSekild && !htSekil.ContainsKey(rangesekil.Text))                  //Eğer hashtable'da şekil yoksa kontrolü yapılıyor.
                    {
                        sekilcount++;                                                       //Yoksa şekil sayacı bir arttırılıyor.
                        htSekil[rangesekil] = rangesekil.Text;                              //Hashtable'ın içine şekil atılıyor.

                        double sekilNumber = Double.Parse(rangesekil.Text.Substring(6, 3)); // 4.3

                        if (sekilNumber < sekilCounter)                                     //sekilCounter en son şeklin numarasını tutar. Eğer yeni gelen şekil son şekilden küçükse hata vardır.
                        {
                            failCount++;
                            this.Invoke(new MethodInvoker(() =>
                            {
                                this.listResults.Items.Add("Şekil numaraları sırayla olmalıdır!");                                //Hata ekrana bastırılır..
                            }));
                        }
                        else
                        {
                            sekilCounter = sekilNumber;
                        }
                    }

                    if (isSekild && rangesekil.Font.Size < 10)                    //Eğer şekil gelmiş ve font size'ı 10'dan küçükse ekrana hata bastırılır.
                    {
                        failCount++;

                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Şekil kısımları en az 10 boyutunda olmalı!");
                        }));
                    }
                }
                //BEYAN
                if (objParagraph.Range.Text.Contains(Constants.TABLO))                //Şekil için yapılan yukardaki bloğun tamamı tablo için de yapılıyor.
                {
                    object     start      = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.TABLO);
                    object     end        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.TABLO) + Constants.TABLO.Length + 5;
                    Word.Range rangetablo = doc.Range(ref start, ref end);

                    bool istablo = Helper.TextIsTablo(rangetablo.Text);
                    if (istablo && !htTablo.ContainsKey(rangetablo.Text))
                    {
                        tablocount++;
                        htTablo[rangetablo] = rangetablo.Text;
                    }

                    if (istablo && rangetablo.Font.Size < 10)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Tablo kısımları en az 10 boyutunda olmalı!");
                        }));
                    }
                }

                thesisProcess.ReportProgress(5 + (95 * counter / doc.Paragraphs.Count));            // Progress hesaplama yüzde hesaplama Toplam paragraf sayısının mevcut paragraf indexine oranını buluyoruz. Bunu yüzde olarak gösteriyoruz.

                counter++;
            }


            if ((ShapesCount + inShapesCount) < (tablocount + sekilcount)) //Eğer dokümandaki shape countu tablo ve şekil count'ından küçükse o zaman tüm tablo ve şekillere isim verilmemiştir anlamına gelir.
            {                                                              //Bu durumda ekrana hata bastırılır.
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Tüm şekil ve tabloların altına Şekil ve Tablo numarası yazılmalıdır!");
                }));
            }

            if (!beyanexists)            //Yukarıdaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("BEYAN bölümü eksik!");
                }));
            }
            if (!onsozexists) //Önsöz değişkenine yukarıda atama yapıldı. Eğer atamalar sonucunda değişken true'ya çevrilmemişse;
            {                 //bu kod işler.
                failCount++;  //fail sayısı bir arttırılır.

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("ÖNSÖZ bölümü eksik!");                    // Önsöz bölümü eksik hatası ekrana bastırılır.
                }));
            }
            if (!icindekilerexist) //Eğer içindekiler değişkenine true atanmadıysa;
            {                      //hata ekrana bastırılır.
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("İÇİNDEKİLER bölümü eksik!");
                }));
            }
            if (!ozetexists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("ÖZET bölümü eksik!");
                }));
            }
            if (!abstractExists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("ABSTRACT bölümü eksik!");
                }));
            }


            if (!sekilListesiexists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("ŞEKİLLER LİSTESİ bölümü eksik!");
                }));
            }
            if (!eklerlistesiexists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("EKLER LİSTESİ bölümü eksik!");
                }));
            }



            if (!simgelerveKisaltmalarExists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("SIMGELER VE KISALTMALAR bölümü eksik!");
                }));
            }
            if (!kaynakExists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("KAYNAKLAR bölümü eksik!");
                }));
            }
            if (timesnewromancount * 2 < paragraphcount)            //Eğer tezin yarısından çoğu Times New Roman ile yazılmamışsa ekrana hata bastırılır.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Tezin yazım fontu Times New Roman olmalıdır! Tezdeki Times New Roman oranı = %" + 100 * timesnewromancount / paragraphcount);
                }));
            }

            if (elevenpuntocounter * 1.5 < paragraphcount)            //Tez içeriğindeki yazıların boyutu 11 punto olmalıdır.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Tezin font büyüklüğü 11 punto olmalıdır! Tezde bulunan 11 punto oranı= %" + 100 * elevenpuntocounter / paragraphcount);
                }));
            }


            if (failCount == 0)            //Eğer hata sayısı 0 ise tezinizde hata bulunamadı diye mesaj gösteriyoruz.
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Tezinizde hiçbir hata bulunamadı!");
                }));
            }
            else
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add(string.Format("Tezinizde bulunan hata başlığı sayısı:{0}", failCount));                   //Hata sayısı 0'dan farklıysa da tezde bulunan toplam hata sayısı gösteriliyor.
                }));
            }

            doc.Close();
            doc = null;
            //return num;
        }
Exemple #2
0
        //экспорт в шаблон Word
        private void button6_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("" + My.oborudovanie.ToString() );
            //if (textBox2.Text == "")
            //{
            //    MessageBox.Show("Не выбран(ы) испытатель(ли)!");
            //    return;
            //}

            //MessageBox.Show("" + My.poveritelListLength);
            //dbCon.Close();
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    doc = new Microsoft.Office.Interop.Word.Document();
            object missing = Type.Missing;

            //Объявляем новый экземпляр класса Stopwatch
            //запускаем
            Stopwatch testStopwatch = new Stopwatch();

            testStopwatch.Start();

            if (dataGridView1.Rows.Count != 0)
            {
                object fileName   = Directory.GetCurrentDirectory() + @"\ОА\tmpl.doc";
                object falseValue = false;
                object trueValue  = true;

                doc = app.Documents.Open(ref fileName, ref missing, ref falseValue,
                                         ref missing, ref missing, ref missing, ref missing, ref missing,
                                         ref missing, ref missing, ref missing, ref missing, ref missing,
                                         ref missing, ref missing, ref missing);
                //app.Visible = true;

                //exception();
                //string[] txt = { label1.Text, DateTime.Now.ToLongDateString(), label2.Text, label3.Text, /*label4.Text,*/ label5.Text, label4.Text, label6.Text, label23.Text, label7.Text, label8.Text, label9.Text, label10.Text, label11.Text, label12.Text, /*label13.Text*/ label18.Text, label19.Text, label20.Text, label21.Text, label22.Text, label14.Text, label15.Text };
                string[] txt     = { label1.Text, label26.Text, /*DateTime.Now.ToLongDateString(),*/ label2.Text, label3.Text, /*label4.Text,*/ label5.Text, label4.Text, label6.Text, label23.Text, label7.Text, label8.Text, label9.Text, label10.Text, label11.Text, label12.Text, label13.Text /*, label18.Text, label19.Text, label20.Text, label21.Text, label22.Text*/ /*, label14.Text, label15.Text*/ };
                string[] FindObj = { "$num$", "$date$", /*"$date$",*/ "$zakazchik$", "$adress_zakazchika$", /*"$postavshik$",*/ "$name_izgotov$", "$adress_izgotov$", "$product_name$", "$product_group$", "$name$", "$proba$", "$date_time_postuplenia$", "$date_exe$", "$osnovanie$", "$nd$", "$conditions$" /*, "$temperature$", "$vlazhnost$","$davlenie$", "$elmagpole$", "$magpole$"*/ /*, "$dolznost$", "$sotrudnik$"*/ };

                int n = 0;
                while (n < FindObj.Length)
                {
                    //Очищаем параметры поиска
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Replacement.ClearFormatting();

                    //Задаём параметры замены и выполняем замену.
                    object findTextNUM    = FindObj[n];
                    object replaceWithNUM = txt[n];
                    object replaceNUM     = 2;

                    app.Selection.Find.Execute(ref findTextNUM, ref missing, ref missing, ref missing,
                                               ref missing, ref missing, ref missing, ref missing, ref missing,
                                               ref replaceWithNUM, ref replaceNUM, ref missing, ref missing, ref missing, ref missing);
                    n++;
                }
                n = 0;


                //string poveritelListFind = "$poveritelList$";
                for (int nn = 0; nn < My.poveritelListLength; nn++)
                {
                    if (My.poveritelList[nn] == "")
                    {
                        nn++;
                    }
                    else
                    {
                        textBox2.AppendText(My.poveritelList[nn] + "\r\r");
                    }
                }

                //Очищаем параметры поиска
                app.Selection.Find.ClearFormatting();
                app.Selection.Find.Replacement.ClearFormatting();

                //Задаём параметры замены и выполняем замену.
                object findTextNUM2    = "$poveritelList$";
                object replaceWithNUM2 = textBox2.Text;
                object replaceNUM2     = 2;

                app.Selection.Find.Execute(ref findTextNUM2, ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing, ref missing,
                                           ref replaceWithNUM2, ref replaceNUM2, ref missing, ref missing, ref missing, ref missing);


                //string oborudovanieListFind = "$oborudovanie$";
                for (int nn = 0; nn < My.oborudovanieListLength; nn++)
                {
                    //textBox2.AppendText(My.poveritelList[nn] + "\r\r");
                    //Очищаем параметры поиска
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Replacement.ClearFormatting();

                    //Задаём параметры замены и выполняем замену.
                    object findTextNUM3    = "$oborudovanie$";
                    object replaceWithNUM3 = "- " + My.oborudovanieList[nn] + ";\r$oborudovanie$";
                    object replaceNUM3     = 2;

                    app.Selection.Find.Execute(ref findTextNUM3, ref missing, ref missing, ref missing,
                                               ref missing, ref missing, ref missing, ref missing, ref missing,
                                               ref replaceWithNUM3, ref replaceNUM3, ref missing, ref missing, ref missing, ref missing);
                }

                //Задаём параметры замены и выполняем замену.
                object findTextNUM4    = "$oborudovanie$";
                object replaceWithNUM4 = "";
                object replaceNUM4     = 2;

                app.Selection.Find.Execute(ref findTextNUM4, ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing, ref missing,
                                           ref replaceWithNUM4, ref replaceNUM4, ref missing, ref missing, ref missing, ref missing);

                Microsoft.Office.Interop.Word.Table table = doc.Tables[2];

                int i;

                for (i = 1; i < dataGridView1.Rows.Count + 1; i++)
                {
                    table.Rows.Add();
                    table.Cell(i + 2, 1).Range.Text = i.ToString();          //нумерация

                    for (int j = 1; j < dataGridView1.ColumnCount - 1; j++)  //цикл вставки dGV
                    {
                        //table.Cell(i + 2, j + 1).Range.Text = dataGridView1.Rows[i - 1].Cells[j].Value.ToString();
                        table.Cell(i + 3, j + 1).Range.Text = dataGridView1.Rows[i - 1].Cells[j].Value.ToString();
                    }
                }

                //количество страниц/листов
                Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages;
                double           x    = doc.ComputeStatistics(stat, ref missing); //страницы
                string           y    = Math.Ceiling(x / 2).ToString("G17");      //листы
                //label16.Text = x.ToString("G17");

                //поиск и вставка x&y
                string[] xy     = { x.ToString("G17"), y };
                string[] Findxy = { "$x$", "$y$" };

                while (n < Findxy.Length)
                {
                    //Очищаем параметры поиска
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Replacement.ClearFormatting();

                    //Задаём параметры замены и выполняем замену.
                    object findTextNUM    = Findxy[n];
                    object replaceWithNUM = xy[n];
                    object replaceNUM     = 2;

                    app.Selection.Find.Execute(ref findTextNUM, ref missing, ref missing, ref missing,
                                               ref missing, ref missing, ref missing, ref missing, ref missing,
                                               ref replaceWithNUM, ref replaceNUM, ref missing, ref missing, ref missing, ref missing);
                    n++;
                }
                n = 0;

                DialogResult res = MessageBox.Show("Экспорт завершен. При нажатии ДА будет открыт сгенерированный файл, при нажатии НЕТ произойдет автоматическое сохранение файла и его открытие.", "Экспорт в Excel", MessageBoxButtons.YesNoCancel);

                if (res == DialogResult.Yes)    //открытие сгенерированного файла
                {
                    try
                    {
                        //Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ОА\tmpl.doc";
                        //object newfileName = Directory.GetCurrentDirectory() + @"\ОА\протокол №" + label1.Text + ".doc";
                        app.Visible = true;

                        //doc = app.Documents.Open(ref fileName, ref missing, ref trueValue,
                        //                         ref missing, ref missing, ref missing, ref missing, ref missing,
                        //                         ref missing, ref missing, ref missing, ref missing, ref missing,
                        //                         ref missing, ref missing, ref missing);
                        //// Закрываем родительскую форму
                        //Hide();
                        MessageBox.Show("Экспорт успешно завершен, протокол открыт. При необходимости, сохраните протокол.");

                        /*
                         * string lastNumDir = Directory.GetCurrentDirectory() + @"\ОА\последний_номер.txt";
                         * string lastNumUPD = label1.Text;
                         * System.IO.File.WriteAllText(lastNumDir, lastNumUPD);
                         */
                    }
                    catch
                    {
                        MessageBox.Show("ooooops...! что-то пошло не так. Пожалуйста обратитесь в службу поддержки");
                    }
                }

                if (res == DialogResult.No)     //автоматическое сохранение файла
                {
                    try
                    {
                        object Target  = (Directory.GetCurrentDirectory() + @"\ОА\Протоколы\" + label1.Text + ".doc"); // куда сохранить
                        object format_ = Word.WdSaveFormat.wdFormatDocumentDefault;
                        //Сохранение файла
                        doc.SaveAs(ref Target, ref format_,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing);

                        //object falseValue = false;
                        //object trueValue = true;

                        doc = app.Documents.Open(ref Target, ref missing, ref falseValue,
                                                 ref missing, ref missing, ref missing, ref missing, ref missing,
                                                 ref missing, ref missing, ref missing, ref missing, ref missing,
                                                 ref missing, ref missing, ref missing);
                        ///
                        ///колонтитулы
                        ///

                        //верний колонтитул
                        //первая страница
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekFirstPageHeader;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                            doc.ActiveWindow.Selection.TypeText("");
                            doc.ActiveWindow.Selection.Fields.Add(s.Range);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        //верхний колонтитул
                        //остальные страницы
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryHeader;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                            doc.ActiveWindow.Selection.TypeText("ФБУ «Нижегородский ЦСМ» ИЦ «НИЖЕГОРОДСИСПЫТАНИЯ»          Протокол №" + label1.Text + " от " + label26.Text);
                            doc.ActiveWindow.Selection.Fields.Add(s.Range);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        //нижний колонтитул
                        //первая страница
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            //нижний колонтитул
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            // код для номеров страницы
                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekFirstPageFooter;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                            doc.ActiveWindow.Selection.TypeText("страница ");
                            object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage; //текущая страница
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref CurrentPage, ref oMissing, ref oMissing);

                            doc.ActiveWindow.Selection.TypeText(" из ");
                            object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages; //всего страниц
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref TotalPages, ref oMissing, ref oMissing);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        //нижний колонтитул
                        //первая страница
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            //нижний колонтитул
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            // код для номеров страницы
                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryFooter;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                            doc.ActiveWindow.Selection.TypeText("страница ");
                            object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage; //текущая страница
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref CurrentPage, ref oMissing, ref oMissing);

                            doc.ActiveWindow.Selection.TypeText(" из ");
                            object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages; //всего страниц
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref TotalPages, ref oMissing, ref oMissing);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        app.Visible = true;

                        MessageBox.Show("Экспорт успешно завершен, протокол сохранен под номером " + label1.Text);
                    }
                    catch
                    {
                        MessageBox.Show("ooooops...! что-то пошло не так. Пожалуйста обратитесь в службу поддержки");
                    }
                }

                if (res == DialogResult.Cancel) //отмена
                {
                    MessageBox.Show("Сохранение результатов экспорта отменено");
                    ((Microsoft.Office.Interop.Word._Application)app).Quit(false, ref missing, ref missing);
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
                }
                //Останавливаем
                testStopwatch.Stop();

                //Теперь можем смотреть время выполнения операции
                TimeSpan tSpan; tSpan = testStopwatch.Elapsed;
                //MessageBox.Show("Время выполнения операции - " + tSpan.ToString()); //время выполнения операции
            }
            else
            {
                MessageBox.Show("Не открыта таблица для запроса");
            }
            exit = false;



            Hide();
            Form3 form3 = new Form3();

            form3.Show();
        }