Exemple #1
0
        private static string CreateDocument(string path, QuoteInformation satisBilgileri, string folderName)
        {
            string path1 = string.Empty;

            {
                byte[]  bytes    = (byte[])null;
                DataSet dataSet1 = new DataSet();
                DataSet dataSet2 = satisBilgileri.DataSet;

                if (satisBilgileri.Fields.ContainsKey("accountname") && projectNameGlobal != "827 Inistanbul Topkapı")//Satış Yapan Firma Var ise ve Topkapı projesi değil ise
                {
                    bytes = DocumentMerge.WordDokumanOlustur(path + "DocumentMerge\\Templates\\presalesform2.docx", dataSet2, satisBilgileri.Fields);
                    path1 = path + "DocumentMerge\\Document\\" + folderName + "\\presalesform2.docx";
                }
                else if (!satisBilgileri.Fields.ContainsKey("accountname") && projectNameGlobal != "827 Inistanbul Topkapı")//Satış Yapan Firma yok ise ve Topkapı projesi değil ise
                {
                    bytes = DocumentMerge.WordDokumanOlustur(path + "DocumentMerge\\Templates\\presalesform.docx", dataSet2, satisBilgileri.Fields);
                    path1 = path + "DocumentMerge\\Document\\" + folderName + "\\presalesform.docx";
                }
                else
                {
                    bytes = DocumentMerge.WordDokumanOlustur(path + "DocumentMerge\\Templates\\Topkapipresalesform.docx", dataSet2, satisBilgileri.Fields);
                    path1 = path + "DocumentMerge\\Document\\" + folderName + "\\Topkapipresalesform.docx";
                }



                if (path1 != string.Empty)
                {
                    System.IO.File.WriteAllBytes(path1, bytes);
                }
            }

            return(path1);
        }
Exemple #2
0
        internal static string ToTitleCaseHelper(string toConvert, string alreadyConverted)
        {
            if (string.IsNullOrEmpty(toConvert))
            {
                return(alreadyConverted);
            }
            int    num = toConvert.IndexOf(' ');
            string str;
            string toConvert1;

            if (num != -1)
            {
                str        = toConvert.Substring(0, num);
                toConvert1 = toConvert.Substring(num).Trim();
            }
            else
            {
                str        = toConvert.Substring(0);
                toConvert1 = string.Empty;
            }
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append(alreadyConverted);
            stringBuilder.Append(" ");
            stringBuilder.Append(str.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture));
            if (str.Length > 1)
            {
                stringBuilder.Append(str.Substring(1).ToLower(CultureInfo.CurrentCulture));
            }
            return(DocumentMerge.ToTitleCaseHelper(toConvert1, ((object)stringBuilder).ToString()));
        }
Exemple #3
0
 internal static string[] ApplyFormatting(string format, string fieldValue, string preText, string postText)
 {
     string[] strArray = new string[3];
     if ("UPPER".Equals(format))
     {
         strArray[0] = fieldValue.ToUpper(CultureInfo.CurrentCulture);
         strArray[1] = preText.ToUpper(CultureInfo.CurrentCulture);
         strArray[2] = postText.ToUpper(CultureInfo.CurrentCulture);
     }
     else if ("LOWER".Equals(format))
     {
         strArray[0] = fieldValue.ToLower(CultureInfo.CurrentCulture);
         strArray[1] = preText.ToLower(CultureInfo.CurrentCulture);
         strArray[2] = postText.ToLower(CultureInfo.CurrentCulture);
     }
     else if ("FirstCap".Equals(format))
     {
         if (!string.IsNullOrEmpty(fieldValue))
         {
             strArray[0] = fieldValue.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture);
             if (fieldValue.Length > 1)
             {
                 strArray[0] = strArray[0] + fieldValue.Substring(1).ToLower(CultureInfo.CurrentCulture);
             }
         }
         if (!string.IsNullOrEmpty(preText))
         {
             strArray[1] = preText.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture);
             if (fieldValue.Length > 1)
             {
                 strArray[1] = strArray[1] + preText.Substring(1).ToLower(CultureInfo.CurrentCulture);
             }
         }
         if (!string.IsNullOrEmpty(postText))
         {
             strArray[2] = postText.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture);
             if (fieldValue.Length > 1)
             {
                 strArray[2] = strArray[2] + postText.Substring(1).ToLower(CultureInfo.CurrentCulture);
             }
         }
     }
     else if ("Caps".Equals(format))
     {
         strArray[0] = DocumentMerge.ToTitleCase(fieldValue);
         strArray[1] = DocumentMerge.ToTitleCase(preText);
         strArray[2] = DocumentMerge.ToTitleCase(postText);
     }
     else
     {
         strArray[0] = fieldValue;
         strArray[1] = preText;
         strArray[2] = postText;
     }
     return(strArray);
 }
Exemple #4
0
        internal static Paragraph GetPreOrPostParagraphToInsert(string text, SimpleField fieldToMimic)
        {
            Run       runElementForText = DocumentMerge.GetRunElementForText(text, fieldToMimic);
            Paragraph paragraph         = new Paragraph();

            paragraph.Append(new OpenXmlElement[1]
            {
                (OpenXmlElement)runElementForText
            });
            return(paragraph);
        }
Exemple #5
0
 internal static T GetFirstParent <T>(OpenXmlElement element) where T : OpenXmlElement
 {
     if (element.Parent == null)
     {
         return(default(T));
     }
     if (element.Parent.GetType() == typeof(T))
     {
         return(element.Parent as T);
     }
     else
     {
         return(DocumentMerge.GetFirstParent <T>(element.Parent));
     }
 }
Exemple #6
0
 internal static void ExecuteSwitches(OpenXmlElement element, string[] switches)
 {
     if (switches == null || Enumerable.Count <string>((IEnumerable <string>)switches) == 0)
     {
         return;
     }
     if (Enumerable.Contains <string>((IEnumerable <string>)switches, "dp"))
     {
         Paragraph firstParent = DocumentMerge.GetFirstParent <Paragraph>(element);
         if (firstParent == null)
         {
             return;
         }
         firstParent.Remove();
     }
     else if (Enumerable.Contains <string>((IEnumerable <string>)switches, "dr"))
     {
         TableRow firstParent = DocumentMerge.GetFirstParent <TableRow>(element);
         if (firstParent == null)
         {
             return;
         }
         firstParent.Remove();
     }
     else
     {
         if (!Enumerable.Contains <string>((IEnumerable <string>)switches, "dt"))
         {
             return;
         }
         Table firstParent = DocumentMerge.GetFirstParent <Table>(element);
         if (firstParent != null)
         {
             firstParent.Remove();
         }
     }
 }
Exemple #7
0
        internal static void FillWordFieldsInElement(WordprocessingDocument docx, Dictionary <string, string> values, OpenXmlElement element)
        {
            Dictionary <SimpleField, string[]> dictionary = new Dictionary <SimpleField, string[]>();

            foreach (SimpleField index in element.Descendants <SimpleField>())
            {
                string[] switches;
                string[] options;
                string   fieldNameWithOptions = DocumentMerge.GetFieldNameWithOptions(index, out switches, out options);
                if (!string.IsNullOrEmpty(fieldNameWithOptions) && values.ContainsKey(fieldNameWithOptions))
                {
                    if (values.ContainsKey(fieldNameWithOptions) && !string.IsNullOrEmpty(values[fieldNameWithOptions]))
                    {
                        string[] strArray = DocumentMerge.ApplyFormatting(options[0], ((object)values[fieldNameWithOptions]).ToString(), options[1], options[2]);
                        if (!string.IsNullOrEmpty(options[1]))
                        {
                            index.Parent.InsertBeforeSelf <Paragraph>(DocumentMerge.GetPreOrPostParagraphToInsert(strArray[1], index));
                        }
                        if (!string.IsNullOrEmpty(options[2]))
                        {
                            index.Parent.InsertAfterSelf <Paragraph>(DocumentMerge.GetPreOrPostParagraphToInsert(strArray[2], index));
                        }
                        index.Parent.ReplaceChild <SimpleField>((OpenXmlElement)DocumentMerge.GetRunElementForText(strArray[0], index), index);
                    }
                    else
                    {
                        dictionary[index] = switches;
                    }
                }
            }
            foreach (KeyValuePair <SimpleField, string[]> keyValuePair in dictionary)
            {
                DocumentMerge.ExecuteSwitches((OpenXmlElement)keyValuePair.Key, keyValuePair.Value);
                keyValuePair.Key.Remove();
            }
        }
        internal string ExecutePrePaymentForm(Guid QuoteId, string Path)
        {
            string  folder                  = prePaymentFormHelper.CreateFolder(QuoteId, Path);
            string  projectName             = string.Empty;
            string  referans                = string.Empty;
            string  blok                    = string.Empty;
            string  floor                   = string.Empty;
            string  apartmentNo             = string.Empty;
            decimal m2                      = 0;
            decimal grossm2                 = 0;
            string  currencySymbol          = string.Empty;
            Guid    projectId               = Guid.Empty;
            string  city                    = string.Empty;
            string  address                 = string.Empty;
            string  passportNumber          = string.Empty;
            string  foreignAddress          = string.Empty;
            string  secondaryPersonLastName = string.Empty;
            string  secondaryPersonName     = string.Empty;
            string  secondaryPersonPhone    = string.Empty;
            string  blocktype               = string.Empty;

            Entity contact = null;
            Entity account = null;

            service = MSCRM.AdminOrgService;
            Entity quote          = service.Retrieve("quote", QuoteId, new ColumnSet(true));
            Entity currencyDetail = this.GetCurrencyDetail(((EntityReference)quote["transactioncurrencyid"]).Id, new string[1] {
                "currencysymbol"
            });

            if (currencyDetail != null && currencyDetail.Attributes.Contains("currencysymbol"))
            {
                currencySymbol = currencyDetail["currencysymbol"].ToString();
            }
            string secondCustomerName = string.Empty;
            string secondCustomerTc   = string.Empty;

            if (quote.Contains("new_secondcontactid"))
            {
                Entity secondContact = service.Retrieve("contact", ((EntityReference)quote.Attributes["new_secondcontactid"]).Id, new ColumnSet(true));
                secondCustomerName = secondContact.Contains("fullname") ? (string)secondContact.Attributes["fullname"] : string.Empty;
                secondCustomerTc   = secondContact.Contains("new_tcidentitynumber") ? (string)secondContact.Attributes["new_tcidentitynumber"] : string.Empty;
                if (secondContact.Contains("new_passportnumber"))
                {
                    secondCustomerTc = secondCustomerTc + " / " + (string)secondContact.Attributes["new_passportnumber"];
                }
            }
            if (((EntityReference)quote.Attributes["customerid"]).LogicalName.ToLower() == "contact")
            {
                contact        = service.Retrieve("contact", ((EntityReference)quote.Attributes["customerid"]).Id, new ColumnSet(true));
                city           = contact.Contains("new_addresscityid") ? ((EntityReference)contact.Attributes["new_addresscityid"]).Name + "/" : string.Empty + "/";
                city          += contact.Contains("new_addresstownid") ? ((EntityReference)contact.Attributes["new_addresstownid"]).Name + "/" : string.Empty + "/";
                city          += contact.Contains("new_addressdistrictid") ? ((EntityReference)contact.Attributes["new_addressdistrictid"]).Name : string.Empty;
                address        = contact.Contains("new_addressdetail") ? contact.Attributes["new_addressdetail"].ToString() : string.Empty;
                address       += " " + city;
                passportNumber = contact.Contains("new_passportnumber") ? (string)contact.Attributes["new_passportnumber"] : string.Empty;
                if (contact.Contains("new_address3countryid"))
                {
                    foreignAddress  = contact.Contains("new_nontcidentityaddress") ? contact.Attributes["new_nontcidentityaddress"].ToString() : string.Empty;
                    foreignAddress += " " + ((EntityReference)contact.Attributes["new_address3cityid"]).Name + "/" + ((EntityReference)contact.Attributes["new_address3countryid"]).Name;
                }
                referans                = contact.Contains("new_referencecontactid") ? ((EntityReference)contact.Attributes["new_referencecontactid"]).Name : string.Empty;
                secondaryPersonName     = contact.Contains("new_secondrypersonname") ? contact.Attributes["new_secondrypersonname"].ToString() : string.Empty;
                secondaryPersonLastName = contact.Contains("new_secondrypersonlastname") ? contact.Attributes["new_secondrypersonlastname"].ToString() : string.Empty;
                secondaryPersonPhone    = contact.Contains("new_secondrypersonphone") ? contact.Attributes["new_secondrypersonphone"].ToString() : string.Empty;
            }
            else if (((EntityReference)quote.Attributes["customerid"]).LogicalName.ToLower() == "account")
            {
                account  = service.Retrieve("account", ((EntityReference)quote.Attributes["customerid"]).Id, new ColumnSet(true));
                city     = account.Contains("new_addresscityid") ? ((EntityReference)account.Attributes["new_addresscityid"]).Name + "/" : string.Empty + "/";
                city    += account.Contains("new_addresstownid") ? ((EntityReference)account.Attributes["new_addresstownid"]).Name + "/" : string.Empty + "/";
                city    += account.Contains("new_addressdistrictid") ? ((EntityReference)account.Attributes["new_addressdistrictid"]).Name : string.Empty;
                address  = account.Contains("new_addressdetail") ? account.Attributes["new_addressdetail"].ToString() : string.Empty;
                address += " " + city;
                referans = account.Contains("primarycontactid") ? ((EntityReference)account.Attributes["primarycontactid"]).Name : string.Empty;
            }


            ConditionExpression con1 = new ConditionExpression();

            con1.AttributeName = "quoteid";
            con1.Operator      = ConditionOperator.Equal;
            con1.Values.Add(QuoteId);

            FilterExpression filter = new FilterExpression();

            filter.FilterOperator = LogicalOperator.And;
            filter.Conditions.Add(con1);

            QueryExpression Query = new QueryExpression("quotedetail");

            Query.ColumnSet = new ColumnSet("productid");
            Query.Criteria.FilterOperator = LogicalOperator.And;
            Query.Criteria.Filters.Add(filter);

            EntityCollection Result = service.RetrieveMultiple(Query);

            if (Result.Entities.Count > 0)
            {
                Entity product = service.Retrieve("product", ((EntityReference)Result.Entities[0].Attributes["productid"]).Id, new ColumnSet(true));
                projectId   = product.Contains("new_projectid") ? ((EntityReference)product.Attributes["new_projectid"]).Id : Guid.Empty;
                projectName = product.Contains("new_projectid") ? ((EntityReference)product.Attributes["new_projectid"]).Name : string.Empty;
                blok        = product.Contains("new_blockid") ? ((EntityReference)product.Attributes["new_blockid"]).Name : string.Empty;
                floor       = product.Contains("new_floornumber") ? product.Attributes["new_floornumber"].ToString() : string.Empty;
                apartmentNo = product.Contains("new_homenumber") ? (string)product.Attributes["new_homenumber"] : string.Empty;
                m2          = product.Contains("new_netm2") ? (decimal)product.Attributes["new_netm2"] : 0;
                grossm2     = product.Contains("new_grossm2") ? (decimal)product.Attributes["new_grossm2"] : 0;
                blocktype   = product.Contains("new_blocktypeid") ? ((EntityReference)product.Attributes["new_blocktypeid"]).Name : string.Empty;
            }
            Entity project = service.Retrieve("new_project", projectId, new ColumnSet(true));

            Dictionary <string, string> dictionary1 = new Dictionary <string, string>();

            if (projectName == "853 NEF 03 Kağıthane")
            {
                dictionary1.Add("Proje", "NEF KAĞITHANE 03");
            }
            else
            {
                dictionary1.Add("proje", projectName);
            }

            dictionary1.Add("satisdanismani", ((EntityReference)quote.Attributes["ownerid"]).Name);
            if (quote.Contains("new_salesprocessdate"))
            {
                dictionary1.Add("satistarihi", ((DateTime)quote.Attributes["new_salesprocessdate"]).ToLocalTime().ToString("dd/MM/yyyy"));
            }
            else
            {
                dictionary1.Add("satistarihi", string.Empty);
            }
            dictionary1.Add("referans", referans);
            dictionary1.Add("blok", blok);
            dictionary1.Add("daireno", apartmentNo);
            dictionary1.Add("kat", floor);
            dictionary1.Add("brutnet", grossm2.ToString("N2") + "/" + m2.ToString("N2"));
            dictionary1.Add("satisaesasbrutm2", grossm2.ToString("N2"));
            dictionary1.Add("adres1", address);

            if (foreignAddress != string.Empty)
            {
                dictionary1.Add("adres2", foreignAddress);
            }
            else
            {
                dictionary1.Add("adres2", string.Empty);
            }

            if (contact != null)
            {
                if (contact.Contains("fullname"))
                {
                    if (secondCustomerName != string.Empty)
                    {
                        dictionary1.Add("musterifirmaadsoyad", contact.Attributes["fullname"].ToString() + " - " + secondCustomerName);
                    }
                    else
                    {
                        dictionary1.Add("musterifirmaadsoyad", contact.Attributes["fullname"].ToString());
                    }
                }
                else
                {
                    dictionary1.Add("musterifirmaadsoyad", string.Empty);
                }
                if (contact.Contains("new_tcidentitynumber"))
                {
                    if (secondCustomerTc != string.Empty)
                    {
                        if (passportNumber != string.Empty)
                        {
                            dictionary1.Add("tcnovergino", contact.Attributes["new_tcidentitynumber"].ToString() + "/" + passportNumber + " - " + secondCustomerTc);
                        }
                        else
                        {
                            dictionary1.Add("tcnovergino", contact.Attributes["new_tcidentitynumber"].ToString() + " - " + secondCustomerTc);
                        }
                    }
                    else
                    {
                        if (passportNumber != string.Empty)
                        {
                            dictionary1.Add("tcnovergino", contact.Attributes["new_tcidentitynumber"].ToString() + "/" + passportNumber);
                        }
                        else
                        {
                            dictionary1.Add("tcnovergino", contact.Attributes["new_tcidentitynumber"].ToString());
                        }
                    }
                }
                else
                {
                    dictionary1.Add("tcnovergino", passportNumber);
                }
                if (contact.Contains("mobilephone"))
                {
                    dictionary1.Add("telefon", contact.Attributes["mobilephone"].ToString());
                }
                else
                {
                    dictionary1.Add("telefon", string.Empty);
                }
                if (contact.Contains("emailaddress1"))
                {
                    dictionary1.Add("eposta", contact.Attributes["emailaddress1"].ToString());
                }
                else
                {
                    dictionary1.Add("eposta", string.Empty);
                }

                if (!string.IsNullOrEmpty(secondaryPersonName) && !string.IsNullOrEmpty(secondaryPersonLastName))
                {
                    dictionary1.Add("ikincilkisiadsoyad", string.Format(" {0} {1}", secondaryPersonName, secondaryPersonLastName));
                }
                else
                {
                    dictionary1.Add("ikincilkisiadsoyad", string.Empty);
                }

                if (!string.IsNullOrEmpty(secondaryPersonPhone))
                {
                    dictionary1.Add("ikincilkisitelefon", secondaryPersonPhone);
                }
                else
                {
                    dictionary1.Add("ikincilkisitelefon", string.Empty);
                }
            }
            else if (account != null)
            {
                if (account.Contains("name"))
                {
                    dictionary1.Add("musterifirmaadsoyad", account.Attributes["name"].ToString());
                }
                else
                {
                    dictionary1.Add("musterifirmaadsoyad", string.Empty);
                }
                if (account.Contains("new_taxnumber"))
                {
                    dictionary1.Add("tcnovergino", account.Attributes["new_taxnumber"].ToString());
                }
                if (account.Contains("telephone1"))
                {
                    dictionary1.Add("telefon", account.Attributes["telephone1"].ToString());
                }
                else
                {
                    dictionary1.Add("telefon", string.Empty);
                }
                if (account.Contains("emailaddress1"))
                {
                    dictionary1.Add("eposta", account.Attributes["emailaddress1"].ToString());
                }
                else
                {
                    dictionary1.Add("eposta", string.Empty);
                }
            }
            if (quote.Contains("totalamount"))
            {
                dictionary1.Add("dairesatisfiyati", ((Money)quote.Attributes["totalamount"]).Value.ToString("N2") + " " + currencySymbol);
            }
            else
            {
                dictionary1.Add("dairesatisfiyati", string.Empty);
            }

            if (quote.Contains("totallineitemamount"))
            {
                dictionary1.Add("listefiyati", ((Money)quote.Attributes["totallineitemamount"]).Value.ToString("N2") + " " + currencySymbol);
            }
            else
            {
                dictionary1.Add("listefiyati", string.Empty);
            }



            if (quote.Contains("new_prepaymentamount"))
            {
                dictionary1.Add("kaporatutar", ((Money)quote.Attributes["new_prepaymentamount"]).Value.ToString("N2") + " " + currencySymbol);
            }
            else
            {
                dictionary1.Add("kaporatutar", string.Empty);
            }
            if (quote.Contains("new_prepaymentdate"))
            {
                dictionary1.Add("kaporatarih", ((DateTime)quote.Attributes["new_prepaymentdate"]).ToLocalTime().ToString("dd/MM/yyyy"));
            }
            else
            {
                dictionary1.Add("kaporatarih", string.Empty);
            }
            if (quote.Contains("new_taxamount"))
            {
                dictionary1.Add("kdvtutari", ((Money)quote.Attributes["new_taxamount"]).Value.ToString("N2") + " " + currencySymbol);
            }
            else
            {
                dictionary1.Add("kdvtutari", string.Empty);
            }
            if (quote.Contains("new_taxofstampamount"))
            {
                dictionary1.Add("damgavergisitutari", ((Money)quote.Attributes["new_taxofstampamount"]).Value.ToString("N2") + " " + currencySymbol);
            }
            else
            {
                dictionary1.Add("damgavergisitutari", string.Empty);
            }

            if (!string.IsNullOrEmpty(blocktype))
            {
                dictionary1.Add("blocktype", blocktype);
            }
            else
            {
                dictionary1.Add("blocktype", string.Empty);
            }


            if (projectName == "895 NEF Yalıkavak")
            {
                byte[] bytes = DocumentMerge.WordDokumanOlustur(Path + "DocumentMerge\\Templates\\YalikavakOnSatisFormu.docx", (DataSet)null, dictionary1);
                string path1 = Path + "DocumentMerge\\Document\\" + folder + "\\YalikavakOnSatisFormu.docx";
                if (path1 != string.Empty)
                {
                    System.IO.File.WriteAllBytes(path1, bytes);
                }
                return(path1);
            }
            else if (projectId == Globals.TopkapiProjectId)
            {
                byte[] bytes = DocumentMerge.WordDokumanOlustur(Path + "DocumentMerge\\Templates\\TopkapiOnSatisFormu.docx", (DataSet)null, dictionary1);
                string path1 = Path + "DocumentMerge\\Document\\" + folder + "\\TopkapiOnSatisFormu.docx";
                if (path1 != string.Empty)
                {
                    System.IO.File.WriteAllBytes(path1, bytes);
                }
                return(path1);
            }
            else
            {
                byte[] bytes = DocumentMerge.WordDokumanOlustur(Path + "DocumentMerge\\Templates\\PrePayment.docx", (DataSet)null, dictionary1);
                string path1 = Path + "DocumentMerge\\Document\\" + folder + "\\PrePayment.docx";
                if (path1 != string.Empty)
                {
                    System.IO.File.WriteAllBytes(path1, bytes);
                }
                return(path1);
            }
        }
Exemple #9
0
 internal static string ToTitleCase(string toConvert)
 {
     return(DocumentMerge.ToTitleCaseHelper(toConvert, string.Empty));
 }
Exemple #10
0
 public static byte[] WordDokumanOlustur(string sablon, DataSet dataset, Dictionary <string, string> degerler)
 {
     byte[]   buffer   = File.ReadAllBytes(sablon);
     string[] switches = (string[])null;
     using (MemoryStream memoryStream = new MemoryStream())
     {
         memoryStream.Write(buffer, 0, buffer.Length);
         using (WordprocessingDocument docx = WordprocessingDocument.Open((Stream)memoryStream, true))
         {
             DocumentMerge.ConvertFieldCodes((OpenXmlElement)docx.MainDocumentPart.Document);
             foreach (SimpleField field in docx.MainDocumentPart.Document.Descendants <SimpleField>())
             {
                 string fieldName = DocumentMerge.GetFieldName(field, out switches);
                 if (!string.IsNullOrEmpty(fieldName) && fieldName.StartsWith("TBL_"))
                 {
                     TableRow firstParent1 = DocumentMerge.GetFirstParent <TableRow>((OpenXmlElement)field);
                     if (firstParent1 != null)
                     {
                         Table firstParent2 = DocumentMerge.GetFirstParent <Table>((OpenXmlElement)firstParent1);
                         if (firstParent2 != null)
                         {
                             string nameFromFieldName = DocumentMerge.GetTableNameFromFieldName(fieldName);
                             if (dataset != null && dataset.Tables.Contains(nameFromFieldName) && dataset.Tables[nameFromFieldName].Rows.Count != 0)
                             {
                                 DataTable dataTable = dataset.Tables[nameFromFieldName];
                                 List <TableCellProperties> list1 = new List <TableCellProperties>();
                                 List <string>      list2         = new List <string>();
                                 List <string>      list3         = new List <string>();
                                 List <SimpleField> list4         = new List <SimpleField>();
                                 foreach (TableCell tableCell in firstParent1.Descendants <TableCell>())
                                 {
                                     list1.Add(tableCell.GetFirstChild <TableCellProperties>());
                                     Paragraph firstChild1 = tableCell.GetFirstChild <Paragraph>();
                                     if (firstChild1 != null)
                                     {
                                         ParagraphProperties firstChild2 = firstChild1.GetFirstChild <ParagraphProperties>();
                                         if (firstChild2 != null)
                                         {
                                             list3.Add(firstChild2.OuterXml);
                                         }
                                         else
                                         {
                                             list3.Add((string)null);
                                         }
                                     }
                                     else
                                     {
                                         list3.Add((string)null);
                                     }
                                     string      str         = string.Empty;
                                     SimpleField simpleField = (SimpleField)null;
                                     using (IEnumerator <SimpleField> enumerator = tableCell.Descendants <SimpleField>().GetEnumerator())
                                     {
                                         if (enumerator.MoveNext())
                                         {
                                             SimpleField current = enumerator.Current;
                                             simpleField = current;
                                             str         = DocumentMerge.GetColumnNameFromFieldName(DocumentMerge.GetFieldName(current, out switches));
                                         }
                                     }
                                     list2.Add(str);
                                     if (str != "")
                                     {
                                         list4.Add(simpleField);
                                     }
                                 }
                                 TableRowProperties firstChild = firstParent1.GetFirstChild <TableRowProperties>();
                                 foreach (DataRow dataRow in (InternalDataCollectionBase)dataTable.Rows)
                                 {
                                     TableRow tableRow = new TableRow();
                                     if (firstChild != null)
                                     {
                                         tableRow.Append(new OpenXmlElement[1]
                                         {
                                             (OpenXmlElement) new TableRowProperties(firstChild.OuterXml)
                                         });
                                     }
                                     for (int index = 0; index < list1.Count; ++index)
                                     {
                                         TableCellProperties tableCellProperties = new TableCellProperties(list1[index].OuterXml);
                                         TableCell           tableCell           = new TableCell();
                                         tableCell.Append(new OpenXmlElement[1]
                                         {
                                             (OpenXmlElement)tableCellProperties
                                         });
                                         Paragraph paragraph = new Paragraph(new OpenXmlElement[1]
                                         {
                                             (OpenXmlElement) new ParagraphProperties(list3[index])
                                         });
                                         tableCell.Append(new OpenXmlElement[1]
                                         {
                                             (OpenXmlElement)paragraph
                                         });
                                         try
                                         {
                                             if (!string.IsNullOrEmpty(list2[index]))
                                             {
                                                 if (!dataTable.Columns.Contains(list2[index]))
                                                 {
                                                     throw new Exception(string.Format("Unable to complete template: column name '{0}' is unknown in parameter tables !", (object)list2[index]));
                                                 }
                                                 if (!dataRow.IsNull(list2[index]))
                                                 {
                                                     string text = dataRow[list2[index]].ToString();
                                                     paragraph.Append(new OpenXmlElement[1]
                                                     {
                                                         (OpenXmlElement)DocumentMerge.GetRunElementForText(text, list4[index])
                                                     });
                                                 }
                                             }
                                         }
                                         catch
                                         {
                                         }
                                         tableRow.Append(new OpenXmlElement[1]
                                         {
                                             (OpenXmlElement)tableCell
                                         });
                                     }
                                     firstParent2.Append(new OpenXmlElement[1]
                                     {
                                         (OpenXmlElement)tableRow
                                     });
                                 }
                                 firstParent1.Remove();
                             }
                         }
                     }
                 }
             }
             foreach (SimpleField field in docx.MainDocumentPart.Document.Descendants <SimpleField>())
             {
                 string fieldName = DocumentMerge.GetFieldName(field, out switches);
                 if (!string.IsNullOrEmpty(fieldName) && fieldName.StartsWith("TBL_"))
                 {
                     TableRow firstParent1 = DocumentMerge.GetFirstParent <TableRow>((OpenXmlElement)field);
                     if (firstParent1 != null)
                     {
                         Table firstParent2 = DocumentMerge.GetFirstParent <Table>((OpenXmlElement)firstParent1);
                         if (firstParent2 != null)
                         {
                             string nameFromFieldName = DocumentMerge.GetTableNameFromFieldName(fieldName);
                             if ((dataset == null || !dataset.Tables.Contains(nameFromFieldName) || dataset.Tables[nameFromFieldName].Rows.Count == 0) && Enumerable.Contains <string>((IEnumerable <string>)switches, "dt"))
                             {
                                 firstParent2.Remove();
                             }
                         }
                     }
                 }
             }
             DocumentMerge.FillWordFieldsInElement(docx, degerler, (OpenXmlElement)docx.MainDocumentPart.Document);
             ((OpenXmlPartRootElement)docx.MainDocumentPart.Document).Save();
             foreach (HeaderPart headerPart in docx.MainDocumentPart.HeaderParts)
             {
                 DocumentMerge.ConvertFieldCodes((OpenXmlElement)headerPart.Header);
                 DocumentMerge.FillWordFieldsInElement(docx, degerler, (OpenXmlElement)headerPart.Header);
                 ((OpenXmlPartRootElement)headerPart.Header).Save();
             }
             foreach (FooterPart footerPart in docx.MainDocumentPart.FooterParts)
             {
                 DocumentMerge.ConvertFieldCodes((OpenXmlElement)footerPart.Footer);
                 DocumentMerge.FillWordFieldsInElement(docx, degerler, (OpenXmlElement)footerPart.Footer);
                 ((OpenXmlPartRootElement)footerPart.Footer).Save();
             }
         }
         memoryStream.Seek(0L, SeekOrigin.Begin);
         return(memoryStream.ToArray());
     }
 }