//// It seems like we don’t need this function anymore.
        //// /// <summary>
        //// /// ?abc?
        //// /// </summary>
        //// /// <param name="xmlNode">?abc?</param>
        //// /// <param name="xmlNamespaceMgt">?abc?</param>
        //// public static void CleanProperties(XmlNode xmlNode, XmlNamespaceManager xmlNamespaceMgt)
        //// {
        /////*   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:Caption", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:DataCaptionExpr", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:DataCaptionFields", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:BorderStyle", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:CaptionBar", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:Minimizable", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:Maximizable", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:Sizeable", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:LogWidth", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:LogHeight", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:Width", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:Height", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:XPos", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:YPos", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:BackColor", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:Visible", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:ActiveControlOnOpen", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:MinimizedOnOpen", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:MaximizedOnOpen", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:AutoPosition", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:TableBoxId", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:LookupMode", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:CalcFields", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:SourceTablePlacement", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:SourceTableRecord", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:SaveControlInfo", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:SaveColumnWidths", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:SavePosAndSize", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:UpdateOnActivate", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:DelayedInsert", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:PopulateAllFields", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:Horzgrid", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:VertGrid", xmlNamespaceMgt);
        ////   XmlUtility.DeleteElements(xmlNode.SelectSingleNode(@"./a:Properties", xmlNamespaceMgt), "./a:TimerInterval", xmlNamespaceMgt);*/
        //// }

        /// <summary>
        /// ?abc?
        /// </summary>
        public static void AddDefaultProperties()
        {
            MetadataDocumentManagement metaDataDocMgt = MetadataDocumentManagement.Instance;

            // Add PageType=Card
            const string PageType        = "PageType";
            string       defaultPageType = "Card";

            XmlNode properties = metaDataDocMgt.XmlCurrentFormNode.SelectSingleNode("./a:Properties", metaDataDocMgt.XmlNamespaceMgt);

            if (properties != null)
            {
                if (properties.SelectSingleNode("./a:" + PageType, metaDataDocMgt.XmlNamespaceMgt) == null)
                {
                    // Only assign default Pagetype for Page objects
                    if (metaDataDocMgt.GetCurrentPageId > 0)
                    {
                        XmlElement element = XmlUtility.CreateXmlElement(PageType, defaultPageType);
                        properties.AppendChild(element);
                    }
                }
            }
            else
            {
                string logStr = string.Format(
                    System.Globalization.CultureInfo.InvariantCulture,
                    Resources.CanNotFindNode,
                    "Properties",
                    PageType);
                TransformationLog.GenericLogEntry(logStr, LogCategory.Error, metaDataDocMgt.GetCurrentPageId);
            }
        }
        public static Boolean SaveXmlToFile(XmlDocument xmlDocument, String fileName)
        {
            if (xmlDocument == null)
            {
                throw new ArgumentNullException("xmlDocument");
            }

            try
            {
                xmlDocument.Save(fileName);
            }
            catch (XmlException ex)
            {
                string logStr = String.Format(System.Globalization.CultureInfo.InvariantCulture, Resources.CouldNotSave, fileName);
                TransformationLog.GenericLogEntry(logStr, LogCategory.Error, (int)LogEntryObjectId.None, ex.Message);
                return(false);
            }
            catch (IOException ex)
            {
                string logStr = String.Format(System.Globalization.CultureInfo.InvariantCulture, Resources.CouldNotSave, fileName);
                TransformationLog.GenericLogEntry(logStr, LogCategory.Error, (int)LogEntryObjectId.None, ex.Message);
                return(false);
            }

            return(true);
        }
Exemple #3
0
        private static void CheckIfFileExists(String fileName, ref bool fileNotFound)
        {
            if (!File.Exists(fileName.Substring(1)))
            {
                fileNotFound = true;
                TransformationLog.GenericLogEntry(String.Format(System.Globalization.CultureInfo.InvariantCulture, Resources.FileLoadError, fileName), LogCategory.Error);
            }

            RemoveTempFile(fileName);
        }
 /// <summary>
 /// Log error with all inner exceptions to log file
 /// </summary>
 /// <param name="exceptionToLog">System.Exception</param>
 /// <param name="objectId">Form or Page ID related to this log entry. If it's n/a, use LogEntryObjectId</param>
 /// <param name="logCategory">LogCategory if not Error</param>
 public static void WriteErrorToLogFile(Exception exceptionToLog, int objectId, LogCategory logCategory)
 {
     if (exceptionToLog != null)
     {
         GenericLogEntry(exceptionToLog.Message, logCategory, objectId);
         while (exceptionToLog.InnerException != null)
         {
             exceptionToLog = exceptionToLog.InnerException;
             TransformationLog.GenericLogEntry(exceptionToLog.Message, logCategory, objectId);
         }
     }
 }
        /// <summary>
        /// This delivers the input to form transformation
        /// </summary>
        /// <returns>XmlDocument compliant with form transformation</returns>
        public XmlDocument ReturnSourceForms()
        {
            XmlNamespaceManager xmlNamespace = new XmlNamespaceManager(document.NameTable);

            xmlNamespace.AddNamespace("a", "urn:schemas-microsoft-com:dynamics:NAV:ApplicationObjects");

            foreach (XmlElement report in document.SelectNodes(@"./a:Objects/a:Report", xmlNamespace))
            {
                XmlElement rawPage = (XmlElement)report.SelectSingleNode("./a:RequestPage", xmlNamespace);
                if (rawPage != null)
                {
                    String logStr = String.Format(CultureInfo.InvariantCulture,
                                                  Resources.RequestPageIsAlreadyExists, report.Attributes["ID"].InnerText);
                    TransformationLog.GenericLogEntry(logStr, LogCategory.Warning, report.Attributes["ID"].InnerText, null);
                    report.ParentNode.RemoveChild(report);
                    continue;
                }
                reportElements.Add(report.Attributes["ID"].InnerText, report);

                XmlElement code    = (XmlElement)report.SelectSingleNode("./a:Code", xmlNamespace).Clone();
                XmlElement rawForm = (XmlElement)report.SelectSingleNode("./a:RequestForm", xmlNamespace);

                XmlElement form = document.CreateElement("Form", "urn:schemas-microsoft-com:dynamics:NAV:ApplicationObjects");
                form.InnerXml = rawForm.InnerXml;
                form.AppendChild(code);

                XmlAttribute attribute = document.CreateAttribute("ID");
                attribute.InnerText = "-" + report.Attributes["ID"].InnerText;
                form.Attributes.Append(attribute);

                attribute           = document.CreateAttribute("Name");
                attribute.InnerText = report.Attributes["Name"].InnerText;
                form.Attributes.Append(attribute);

                if (report.Attributes["Date"] != null)
                {
                    attribute           = document.CreateAttribute("Date");
                    attribute.InnerText = report.Attributes["Date"].InnerText;
                    form.Attributes.Append(attribute);
                }
                if (report.Attributes["Time"] != null)
                {
                    attribute           = document.CreateAttribute("Time");
                    attribute.InnerText = report.Attributes["Time"].InnerText;
                    form.Attributes.Append(attribute);
                }
                document.DocumentElement.ReplaceChild(form, report);
            }

            return(document);
        }
        private void RunCodeTransfromation()
        {
            CodeTransformationRules.SetRules();

            // select forms nodes
            XmlNodeList nodeList      = metaDataDocMgt.XmlDocument.SelectNodes(@"./a:Objects/a:Page", metaDataDocMgt.XmlNamespaceMgt);
            Double      numberOfPages = nodeList.Count;
            Double      pageCounter   = 0;

            Console.WriteLine("Code Transformation started.");
            const String Indentation = "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b   ";

            // for each form

            foreach (XmlNode formNode in nodeList)
            {
                metaDataDocMgt.XmlCurrentFormNode = formNode;
                string s = Indentation +
                           Convert.ToInt32(((pageCounter + 1) / numberOfPages) * 100) +
                           "%  #" +
                           metaDataDocMgt.GetCurrentPageId.ToString(CultureInfo.InvariantCulture);
                Console.Write(s);

                pageCounter++;

                // select all trigger node[unsupported]

                try
                {
                    CodeTransformationRules.TransformFormTriggers(formNode);
                }
                catch (Exception e)
                {
                    if (SuppressErrors)
                    {
                        TransformationLog.GenericLogEntry(e.Message, LogCategory.Error, metaDataDocMgt.GetCurrentPageId);
                    }
                    else
                    {
                        throw new TransformationException(Resources.StepCodeTransformation + metaDataDocMgt.GetCurrentPageId, e);
                    }
                }
            }

            Console.WriteLine("");
            CodeTransformationRules.SummarizeActions();
        }
        private void PreRenameNodes()
        {
            XmlNodeList formNodeList = metaDataDocMgt.XmlDocument.SelectNodes(@"./a:Objects/a:Form", metaDataDocMgt.XmlNamespaceMgt);

            XmlUtility.RenameNode(formNodeList, "Page");

            XmlNodeList subFormIDNodeList = metaDataDocMgt.XmlDocument.SelectNodes(@"./a:Objects/a:Page//a:SubFormID", metaDataDocMgt.XmlNamespaceMgt);

            XmlUtility.RenameNode(subFormIDNodeList, "PagePartID");

            XmlNodeList timerIntervalNodeList = metaDataDocMgt.XmlDocument.SelectNodes(@"./a:Objects/a:Page/a:Properties/a:TimerInterval", metaDataDocMgt.XmlNamespaceMgt);

            XmlUtility.RenameNode(timerIntervalNodeList, "TimerUpdate");

            XmlNodeList updateOnActivateNodeList = metaDataDocMgt.XmlDocument.SelectNodes(@"./a:Objects/a:Page/a:Properties/a:UpdateOnActivate", metaDataDocMgt.XmlNamespaceMgt);

            XmlUtility.RenameNode(updateOnActivateNodeList, "RefreshOnActivate");

            XmlNodeList passwordTextList = metaDataDocMgt.XmlDocument.SelectNodes(@"./a:Objects//a:Control/a:Properties/a:PasswordText", metaDataDocMgt.XmlNamespaceMgt);

            foreach (XmlNode passwordText in passwordTextList)
            {
                XmlNode page   = passwordText.ParentNode.ParentNode.ParentNode.ParentNode; // Node parent to Controls node
                int     pageId = (int)LogEntryObjectId.NotSpecified;

                while (page != null)
                {
                    if (page.Name == "Page")
                    {
                        pageId = Convert.ToInt32(page.Attributes["ID"].Value, CultureInfo.InvariantCulture);
                        page   = null;
                    }
                    else
                    {
                        page = page.ParentNode;
                    }
                }

                TransformationLog.GenericLogEntry(Resources.PasswordText, LogCategory.Warning, pageId, null);

                passwordText.ParentNode.AppendChild(XmlUtility.CreateXmlElement("ExtendedDataType", "Masked"));
                passwordText.ParentNode.RemoveChild(passwordText);
            }
        }
        private static string PrepareCaptionValue(int pageId, int langId, string captionValue, TranslationType translationType)
        {
            if (langId == 0)
            {
                return(string.Empty);
            }

            try
            {
                string lang;
                if (langId == 1034)
                {
                    lang = "ESP"; // Otherwise it will be ESN
                }
                else
                {
                    CultureInfo myCItrad = new CultureInfo(langId, false);
                    lang = myCItrad.ThreeLetterWindowsLanguageName;
                }

                if (translationType == TranslationType.TextVariable)
                {
                    Regex textConstWithDoubleQuotesExp = new System.Text.RegularExpressions.Regex(@"\%\d*\s*=\s*\%", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    if (textConstWithDoubleQuotesExp.Match(captionValue).Success)
                    {
                        captionValue = @"""" + captionValue + @"""";
                    }
                }

                return(String.Format(CultureInfo.InvariantCulture, "{0}={1}", lang, captionValue));
            }
            catch
            {
                string logStr = String.Format(CultureInfo.InvariantCulture, Resources.IncorrectLanguageId, langId);
                TransformationLog.GenericLogEntry(logStr, LogCategory.Warning, pageId, "Check translation file");
                return(string.Empty);
            }
        }
        private void RunTransformation()
        {
            XmlNodeList nodeList      = metaDataDocMgt.XmlDocument.SelectNodes(@"./a:Objects/a:Page", metaDataDocMgt.XmlNamespaceMgt);
            Decimal     numberOfPages = nodeList.Count;
            Decimal     pageCounter   = 0;

            Console.WriteLine("Control and Property Transformation started.");
            const string Indentation = "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b   ";

            Stack postponedPages = PostponedPagesList(nodeList);

            foreach (XmlNode formNode in nodeList)
            {
                metaDataDocMgt.XmlCurrentFormNode = formNode;

                if (!postponedPages.Contains(metaDataDocMgt.GetCurrentPageId))
                {
                    string currentPage = metaDataDocMgt.GetCurrentPageId.ToString(CultureInfo.InvariantCulture);
                    string s           = Indentation +
                                         Convert.ToInt32(((pageCounter + 1) / numberOfPages) * 100) +
                                         "%  #" +
                                         currentPage;

                    Console.Write(s);
                    pageCounter++;

                    try
                    {
                        TransformPage();
                    }
                    catch (TransformationException ex)
                    {
                        if (SuppressErrors)
                        {
                            TransformationLog.WriteErrorToLogFile(ex, metaDataDocMgt.GetCurrentPageId);
                        }
                        else
                        {
                            throw new TransformationException(string.Format(CultureInfo.InvariantCulture, Resources.RunTransformationError, currentPage), ex);
                        }
                    }
                }
            }

            if (postponedPages.Count > 0)
            {
                Console.WriteLine();
                Console.WriteLine("   Subforms tranformation started.");
            }

            int ilen = 0;

            foreach (int i in postponedPages)
            {
                XmlNode formNode = metaDataDocMgt.XmlDocument.SelectSingleNode(
                    "./a:Objects/a:Page[@ID='" + i.ToString(CultureInfo.InvariantCulture) + "']",
                    metaDataDocMgt.XmlNamespaceMgt);
                if (formNode != null)
                {
                    metaDataDocMgt.XmlCurrentFormNode = formNode;

                    if (postponedPages.Contains(metaDataDocMgt.GetCurrentPageId))
                    {
                        StringBuilder tmp = new StringBuilder();
                        if (ilen > 0)
                        {
                            int length = ilen - i.ToString(CultureInfo.InvariantCulture).Length;
                            if (length < 0)
                            {
                                length = 0;
                            }

                            tmp.Insert(0, " ", length);
                        }

                        string currentPage = i.ToString(CultureInfo.InvariantCulture);
                        string s           = Indentation +
                                             Convert.ToInt32(((pageCounter + 1) / numberOfPages) * 100) +
                                             "%  #" +
                                             currentPage + tmp.ToString();
                        Console.Write(s);
                        ilen = i.ToString(CultureInfo.InvariantCulture).Length;
                        pageCounter++;

                        try
                        {
                            TransformPage();
                        }
                        catch (TransformationException ex)
                        {
                            TransformationLog.WriteErrorToLogFile(ex, metaDataDocMgt.GetCurrentPageId);
                        }
                    }
                }
            }

            Console.WriteLine(String.Empty);
        }
        private bool TestSchema(XmlDocument doc, String schema)
        {
            string fileName = "tmp.xml";

            try
            {
                if (doc != null)
                {
                    Console.Write("-> Validate " + schema);
                    XmlReaderSettings pageSchemaSetting = new XmlReaderSettings();
                    pageSchemaSetting.Schemas.Add("urn:schemas-microsoft-com:dynamics:NAV:ApplicationObjects", userMgt.SchemasPathLocation + schema);
                    pageSchemaSetting.ValidationType          = ValidationType.Schema;
                    pageSchemaSetting.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

                    //XmlReader rdr = XmlReader.Create(new XmlNodeReader(doc), pageSchemaSetting);
                    //doc.Save(FileName);

                    FileInfo fi = new FileInfo(schema);
                    fileName = fi.Name + "." + fileName;
                    doc.Save(fileName);
                    XmlReader rdr = XmlReader.Create(fileName, pageSchemaSetting);

                    StringBuilder sb = new StringBuilder();
                    while (rdr.Read())
                    {
                        sb.Append(rdr.Value);
                    }

                    rdr.Close();
                    Console.WriteLine("...Done. ");

                    try
                    {
                        System.IO.File.Delete(fileName);
                    }
                    catch (IOException ex)
                    {
                        string logStr = string.Format(CultureInfo.InvariantCulture, Resources.CanNotDeleteTmpFile, ex.Message);
                        TransformationLog.GenericLogEntry(logStr, LogCategory.Warning, (int)LogEntryObjectId.NotSpecified, null);
                    }
                }

                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine("...FAILED. ");
                Console.WriteLine(e.Message);
                TransformationLog.GenericLogEntry("Schema: " + schema, LogCategory.Error);
                TransformationLog.WriteErrorToLogFile(e, (int)LogEntryObjectId.Error);
                //TransformationLog.GenericLogEntry(e.Message, LogCategory.Error);

                //try
                //{
                //  FileInfo fi = new FileInfo(schema);
                //  File.Move(FileName, fi.Name + "." + FileName);
                //}
                //finally
                //{
                //  TransformationLog.GenericLogEntry(FileName, LogCategory.IgnoreWarning);
                //}

                return(false);
            }
        }
        private static void MergeComplexStructure(XmlNode sectionNode, XmlNode destinationNode)
        {
            MetadataDocumentManagement metaDataDocMgt = MetadataDocumentManagement.Instance;
            Int32 GroupCount = 0;

            foreach (XmlNode childNode in sectionNode.ChildNodes)
            {
                switch (childNode.Name)
                {
                case "Properties":
                    XmlNode destinationPropertiesNode = destinationNode.SelectSingleNode("./a:" + childNode.Name, metaDataDocMgt.XmlNamespaceMgt);
                    if (destinationPropertiesNode == null)
                    {
                        destinationPropertiesNode = metaDataDocMgt.XmlDocument.CreateNode(XmlNodeType.Element, childNode.Name, metaDataDocMgt.XmlNamespace);
                        destinationNode.AppendChild(destinationPropertiesNode);
                    }

                    MergeSimpleSection(childNode, destinationPropertiesNode);
                    break;

                case "Action":
                {
                    MergeComplexStructure_Action(childNode, destinationNode);
                    break;
                }

                /*
                 * case "ID":
                 * {
                 *  XmlNode destinationActionNode = destinationNode.ParentNode.SelectSingleNode(".//a:Action[./a:ID = " + childNode.InnerText + "]", metaDataDocMgt.XmlNamespaceMgt);
                 *  if (destinationActionNode != null)
                 *  {
                 *    MergeSimpleSection(childNode.ParentNode, destinationActionNode);
                 *  }
                 *  else
                 *  {
                 *    string logStr = string.Format(
                 *      CultureInfo.InvariantCulture,
                 *      Resources.IDNotFound,
                 *      childNode.InnerText);
                 *    TransformationLog.GenericLogEntry(logStr, LogCategory.CheckInputFile, metaDataDocMgt.GetCurrentPageID);
                 *  }
                 *
                 *  break;
                 * }
                 */

                case "ActionGroup":
                case "Control":
                case "Group":
                case "Part":
                case "Field":
                    XmlNode complexIDNode = childNode.SelectSingleNode("./a:Properties/a:ID", metaDataDocMgt.XmlNamespaceMgt);

                    if ((complexIDNode == null) || (String.IsNullOrEmpty(complexIDNode.InnerText)))
                    {
                        complexIDNode = null;
                        XmlNode newNode = metaDataDocMgt.XmlDocument.ImportNode(childNode, true);
                        InsertIDAsChildInNodeList(newNode.SelectNodes(@".//a:Properties", metaDataDocMgt.XmlNamespaceMgt), sectionNode.Name);
                        InsertIDAsChildInNodeList(newNode.SelectNodes(@".//a:Action", metaDataDocMgt.XmlNamespaceMgt), sectionNode.Name);
                        if ((newNode.Name == "Group") || (newNode.Name == "Control") || (newNode.Name == "Field") || (newNode.Name == "Part") || (newNode.Name == "ActionGroup"))
                        {
                            if (newNode.SelectSingleNode("./a:Properties", metaDataDocMgt.XmlNamespaceMgt) == null)
                            {
                                XmlNode propertiesNode = metaDataDocMgt.XmlDocument.CreateNode(XmlNodeType.Element, "Properties", metaDataDocMgt.XmlNamespace);
                                XmlNode idNode         = metaDataDocMgt.XmlDocument.CreateNode(XmlNodeType.Element, "ID", metaDataDocMgt.XmlNamespace);
                                //idNode.InnerText = metaDataDocMgt.CalcID(null, null, sectionNode.Name);
                                //idNode.InnerText = metaDataDocMgt.GetNewId.ToString(CultureInfo.InvariantCulture); // not possible to generate id using content
                                idNode.InnerText = metaDataDocMgt.CalcId(null, (GroupCount++).ToString(CultureInfo.InvariantCulture), sectionNode.Name).ToString(CultureInfo.InvariantCulture);
                                propertiesNode.AppendChild(idNode);
                                newNode.PrependChild(propertiesNode);
                            }
                        }

                        destinationNode.AppendChild(newNode);
                    }
                    else
                    {
                        XmlNode destinationActionGroupNode = destinationNode.SelectSingleNode("./a:" + childNode.Name + "[./a:Properties/a:ID = '" + complexIDNode.InnerText + "']", metaDataDocMgt.XmlNamespaceMgt);
                        if (destinationActionGroupNode != null)
                        {
                            MergeComplexStructure(childNode, destinationActionGroupNode);
                        }
                        else
                        {
                            /* Something is wrong in the transformation input file... */
                            string logStr = string.Format(
                                CultureInfo.InvariantCulture,
                                Resources.IDNotFound,
                                complexIDNode.InnerText);
                            TransformationLog.GenericLogEntry(logStr, LogCategory.CheckInputFile, metaDataDocMgt.GetCurrentPageId);
                        }
                    }

                    break;

                case "Triggers":
                    XmlNode triggerNode = metaDataDocMgt.XmlDocument.ImportNode(childNode, true);
                    destinationNode.AppendChild(triggerNode);
                    break;
                }
            }
        }
        private static void MergeComplexStructure_Action(XmlNode childNode, XmlNode destinationNode)
        {
            if (childNode == null)
            {
                return;
            }

            MetadataDocumentManagement metaDataDocMgt = MetadataDocumentManagement.Instance;
            XmlNode actionIDNode = childNode.SelectSingleNode("./a:ID", metaDataDocMgt.XmlNamespaceMgt);

            if ((actionIDNode == null) || (String.IsNullOrEmpty(actionIDNode.InnerText)))
            {
                XmlNode captionMlNode = childNode.SelectSingleNode("./a:CaptionML", metaDataDocMgt.XmlNamespaceMgt);
                if (captionMlNode == null)
                {
                    captionMlNode = childNode.FirstChild;
                    string log = string.Format(CultureInfo.InvariantCulture, Resources.AddCaptionMl, childNode.InnerXml);
                    TransformationLog.GenericLogEntry(log, LogCategory.Warning, metaDataDocMgt.GetCurrentPageId);
                }

                String newID =
                    metaDataDocMgt.CalcId(GetProperty(captionMlNode.ParentNode, "NewID"),
                                          XmlUtility.GetCaption(captionMlNode.InnerText), captionMlNode.ParentNode.ParentNode.Name).ToString(CultureInfo.InvariantCulture);

                actionIDNode           = metaDataDocMgt.XmlDocument.CreateNode(XmlNodeType.Element, "ID", metaDataDocMgt.XmlNamespace);
                actionIDNode.InnerText = newID;

                XmlNode newNode = metaDataDocMgt.XmlDocument.ImportNode(childNode, true);
                newNode.PrependChild(actionIDNode);
                destinationNode.AppendChild(newNode);
            }
            else
            {
                XmlNode destinationActionNode = destinationNode.SelectSingleNode("./a:" + childNode.Name + "[./a:ID = " + actionIDNode.InnerText + "]", metaDataDocMgt.XmlNamespaceMgt);
                if (destinationActionNode != null)
                {
                    MergeSimpleSection(childNode, destinationActionNode);
                }
                else
                {
                    /* TODO  !!! TEMPORARY !!!  we should change TransformPages.xml instead! */
                    // Lets try to find it by ID:
                    XmlNodeList actionListById = childNode.SelectNodes(@".//a:ID", metaDataDocMgt.XmlNamespaceMgt);
                    if (actionListById.Count == 0)
                    {
                        /* Something is wrong in the transformation input file... */
                        string logStr = string.Format(
                            CultureInfo.InvariantCulture,
                            Resources.IDNotFound,
                            actionIDNode.InnerText);
                        TransformationLog.GenericLogEntry(logStr, LogCategory.CheckInputFile, metaDataDocMgt.GetCurrentPageId);

                        // break;
                        return;
                    }

                    foreach (XmlNode actionById in actionListById)
                    {
                        string  query = ".//a:Action[./a:ID = " + actionById.InnerText + "]";
                        XmlNode destinationActionNodeById = destinationNode.ParentNode.SelectSingleNode(query, metaDataDocMgt.XmlNamespaceMgt);
                        if (destinationActionNodeById != null)
                        {
                            MergeSimpleSection(actionById.ParentNode, destinationActionNodeById);
                        }
                        else
                        {
                            /* Something is wrong in the transformation input file... */
                            string logStr = string.Format(
                                CultureInfo.InvariantCulture,
                                Resources.IDNotFound,
                                actionById.InnerText);
                            string  tmpAddStr = string.Empty;
                            XmlNode tmp       = metaDataDocMgt.XmlCurrentFormNode.SelectSingleNode(".//a:ID[../a:ID = " + actionById.InnerText + "]", metaDataDocMgt.XmlNamespaceMgt);
                            if (tmp != null)
                            {
                                tmpAddStr = tmp.ParentNode.ParentNode.InnerXml;
                            }
                            TransformationLog.GenericLogEntry(logStr, LogCategory.CheckInputFile, metaDataDocMgt.GetCurrentPageId, tmpAddStr);
                        }
                    }
                }
            }
        }
        private static void AddMlCaptions(XmlNode page)
        {
            MetadataDocumentManagement metaDataDocMgt = MetadataDocumentManagement.Instance;
            XmlNodeList idList        = page.SelectNodes(@".//a:ID", metaDataDocMgt.XmlNamespaceMgt);
            int         destinationID = Convert.ToInt32(page.Attributes["ID"].Value, CultureInfo.InvariantCulture);

            foreach (XmlNode id in idList)
            {
                if (!string.IsNullOrEmpty(id.InnerText))
                {
                    try
                    {
                        AddMultiLanguageSupport.PopulateMlStrings(id.ParentNode, destinationID, Convert.ToInt32(id.InnerText, CultureInfo.InvariantCulture));
                    }
                    catch (Exception ex)
                    {
                        string log = String.Format(CultureInfo.InvariantCulture, Resources.CannotGetMlCaption, "control ", id.InnerText);
                        TransformationLog.GenericLogEntry(log, LogCategory.Warning, destinationID, "Ignore");
                        TransformationLog.WriteErrorToLogFile(ex, destinationID, LogCategory.Warning);
                    }
                }
            }

            XmlNode pageCaption = page.SelectSingleNode(@"./a:Properties", metaDataDocMgt.XmlNamespaceMgt);

            if (pageCaption != null)
            {
                try
                {
                    AddMultiLanguageSupport.PopulateMlStrings(pageCaption, destinationID, 0);
                }
                catch (Exception ex)
                {
                    string log = String.Format(CultureInfo.InvariantCulture, Resources.CannotGetMlCaption, "page", string.Empty);
                    TransformationLog.GenericLogEntry(log, LogCategory.Warning, destinationID, "Ignore");
                    TransformationLog.WriteErrorToLogFile(ex, destinationID, LogCategory.Warning);
                }
            }

            XmlNode code = page.SelectSingleNode(@"./a:Code", metaDataDocMgt.XmlNamespaceMgt);

            if (code == null)
            {
                return;
            }

            try
            {
                System.Text.RegularExpressions.Regex textVariableExp = new System.Text.RegularExpressions.Regex(@"\@(?<varId>\d+)\s*\:\s*TextConst\s*\'", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                if (!textVariableExp.Match(code.InnerText).Success)
                {
                    return;
                }

                string[] codeArr = code.InnerText.Split(new char[] { '\r' });
                System.Text.RegularExpressions.Match textVariableMatch;
                int    textVarId;
                string textVarNewCaption;
                for (int i = 0; i < codeArr.Length; i++)
                {
                    textVariableMatch = textVariableExp.Match(codeArr[i]);
                    if (textVariableMatch.Success)
                    {
                        textVarId         = Convert.ToInt32(textVariableMatch.Result("${varId}"), CultureInfo.InvariantCulture);
                        textVarNewCaption = AddMultiLanguageSupport.GetCaptionML(destinationID, textVarId, AddMultiLanguageSupport.TranslationType.TextVariable);
                        if (!string.IsNullOrEmpty(textVarNewCaption))
                        {
                            textVarNewCaption = textVarNewCaption.Replace("'", "''");
                            codeArr[i]        = codeArr[i].Remove(textVariableMatch.Length + textVariableMatch.Index) + textVarNewCaption + "';";
                        }
                    }
                }

                XmlNode codeNode = XmlUtility.CreateXmlElement("Code");
                codeNode.AppendChild(XmlUtility.CreateCDataSection(string.Join("\r", codeArr)));
                code.ParentNode.AppendChild(codeNode);
                code.ParentNode.RemoveChild(code);
            }
            catch (Exception ex)
            {
                string log = String.Format(CultureInfo.InvariantCulture, Resources.CannotGetMlCaption, "code", string.Empty);
                TransformationLog.GenericLogEntry(log, LogCategory.Warning, destinationID, "Ignore");
                TransformationLog.WriteErrorToLogFile(ex, destinationID, LogCategory.Warning);
            }
        }
        private static void ReadTranslationFile()
        {
            if (fileState == TranslationFileStates.NotRead)
            {
                int pageId = 0;
                if (string.IsNullOrEmpty(UserSetupManagement.Instance.TranslationFile))
                {
                    fileState = TranslationFileStates.NotRead;
                    return;
                }

                try
                {
                    System.Text.Encoding encoding;
                    string encodingPage = System.Configuration.ConfigurationManager.AppSettings["EncodingPage"];
                    int    encodingPageCode;
                    try
                    {
                        encodingPageCode = Convert.ToInt32(encodingPage, CultureInfo.InvariantCulture);
                        try
                        {
                            encoding = System.Text.Encoding.GetEncoding(encodingPageCode);
                        }
                        catch (Exception ex2)
                        {
                            string log = string.Format(CultureInfo.InvariantCulture, Resources.IncorrectEncodingPage, ex2.Message);
                            TransformationLog.GenericLogEntry(log, LogCategory.Error, (int)LogEntryObjectId.None);
                            encoding = System.Text.Encoding.GetEncoding(850);
                        }
                    }
                    catch (FormatException)
                    {
                        try
                        {
                            encoding = System.Text.Encoding.GetEncoding(encodingPage);
                        }
                        catch (Exception ex3)
                        {
                            string log = string.Format(CultureInfo.InvariantCulture, Resources.IncorrectEncodingPage, ex3.Message);
                            TransformationLog.GenericLogEntry(log, LogCategory.Error, (int)LogEntryObjectId.None);
                            encoding = System.Text.Encoding.GetEncoding(850);
                        }
                    }

                    string[] readFile = File.ReadAllLines(UserSetupManagement.Instance.TranslationFile, encoding);

                    Regex pageIdExp          = new Regex(@"N(?<pagelId>\d+)-", RegexOptions.IgnoreCase);
                    Regex controlIdExp       = new Regex(@"-(?<controlType>[CGQ])(?<controlId>\d+)-", RegexOptions.IgnoreCase);
                    Regex languageIdExp      = new Regex(@"-A(?<languageId>\d+)-", RegexOptions.IgnoreCase);
                    Regex captionExp         = new Regex(@"-L999:(?<caption>[\W\w\s]*)", RegexOptions.IgnoreCase);
                    Regex translationTypeExp = new Regex(@"-P(?<translationType>\d+)-", RegexOptions.IgnoreCase);
                    Regex actionIdExp        = new Regex(@"-G(?<actionId>\d+)-", RegexOptions.IgnoreCase);
                    Match translationTypeMatche;

                    foreach (string s in readFile)
                    {
                        pageId = 0;
                        int             controlId            = 0;
                        int             languageId           = 0;
                        string          caption              = string.Empty;
                        int             translationTypeValue = 0;
                        TranslationType translationType      = TranslationType.CaptionMl;
                        bool            goNext = false;

                        if (translationTypeExp.Match(s).Success)
                        {
                            translationTypeMatche = translationTypeExp.Matches(s)[translationTypeExp.Matches(s).Count - 1];

                            translationTypeValue = Convert.ToInt32(translationTypeMatche.Result("${translationType}"), CultureInfo.InvariantCulture);

                            switch (translationTypeValue)
                            {
                            case 8629:
                            case 55242:
                                translationType = TranslationType.CaptionMl;
                                break;

                            case 8631:
                                translationType = TranslationType.ToolTip;
                                break;

                            case 8632:
                                translationType = TranslationType.OptionCaptionMl;
                                break;

                            case 26171:
                                translationType = TranslationType.TextVariable;
                                break;

                            default:
                                goNext = true;
                                break;
                            }

                            if (!goNext)
                            {
                                if (captionExp.Match(s).Success)
                                {
                                    caption = captionExp.Match(s).Result("${caption}");

                                    if (languageIdExp.Match(s).Success)
                                    {
                                        languageId = Convert.ToInt32(languageIdExp.Match(s).Result("${languageId}"), CultureInfo.InvariantCulture);

                                        if (pageIdExp.Match(s).Success)
                                        {
                                            pageId = Convert.ToInt32(pageIdExp.Match(s).Result("${pagelId}"), CultureInfo.InvariantCulture);

                                            controlId = GetControlIdFromTranslation(controlIdExp, actionIdExp, s, controlId);

                                            Dictionary <TranslationType, Dictionary <int, string> > pageWithTranslationType;
                                            if (translations.TryGetValue(pageId, out pageWithTranslationType))
                                            {
                                                Dictionary <int, string> controlsWithCaptions = new Dictionary <int, string>();
                                                if (pageWithTranslationType.TryGetValue(translationType, out controlsWithCaptions))
                                                {
                                                    string captionValue = string.Empty;
                                                    if (controlsWithCaptions.TryGetValue(controlId, out captionValue))
                                                    {
                                                        if (translationType == TranslationType.TextVariable)
                                                        {
                                                            captionValue = String.Format(CultureInfo.InvariantCulture, "{0};{1}", captionValue, PrepareCaptionValue(pageId, languageId, caption, translationType));
                                                        }
                                                        else
                                                        {
                                                            captionValue = String.Format(CultureInfo.InvariantCulture, "{0};\r\n{1}", captionValue, PrepareCaptionValue(pageId, languageId, caption, translationType));
                                                        }

                                                        controlsWithCaptions[controlId] = captionValue;
                                                    }
                                                    else
                                                    {
                                                        captionValue = PrepareCaptionValue(pageId, languageId, caption, translationType);
                                                        controlsWithCaptions.Add(controlId, captionValue);
                                                    }
                                                }
                                                else
                                                {
                                                    controlsWithCaptions = new Dictionary <int, string>();
                                                    string captionValue = PrepareCaptionValue(pageId, languageId, caption, translationType);
                                                    controlsWithCaptions.Add(controlId, captionValue);

                                                    pageWithTranslationType.Add(translationType, controlsWithCaptions);
                                                }
                                            }
                                            else
                                            {
                                                Dictionary <int, string> controlsWithCaptions = new Dictionary <int, string>();
                                                string captionValue = PrepareCaptionValue(pageId, languageId, caption, translationType);
                                                controlsWithCaptions.Add(controlId, captionValue);

                                                pageWithTranslationType = new Dictionary <TranslationType, Dictionary <int, string> >();
                                                pageWithTranslationType.Add(translationType, controlsWithCaptions);

                                                translations.Add(pageId, pageWithTranslationType);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    fileState = TranslationFileStates.Read;
                }
                catch (Exception ex)
                {
                    fileState = TranslationFileStates.NotReady;
                    TransformationLog.GenericLogEntry(Resources.ImportingLocalizedStrings, LogCategory.Warning, pageId, "Check translation file");
                    TransformationLog.WriteErrorToLogFile(ex, pageId, LogCategory.Warning);
                }
            }
        }
        private static void RemoveIgnoredForm(String pageID)
        {
            MetadataDocumentManagement metaDataDocMgt = MetadataDocumentManagement.Instance;
            XmlNode formToBeIgnored = metaDataDocMgt.XmlDocument.SelectSingleNode("./a:Objects/a:Form[@ID =" + pageID + "]", metaDataDocMgt.XmlNamespaceMgt);

            if (formToBeIgnored == null)
            {
                return;
            }

            XmlNode codeTriggerNode = formToBeIgnored.SelectSingleNode(@".//a:Code", metaDataDocMgt.XmlNamespaceMgt);
            Boolean restart         = true;
            Int32   startAfter      = 0;

            while (restart)
            {
                restart = false;
                Boolean inProcedure   = false;
                Boolean inCodeBody    = false;
                Int32   beginPosition = 0;

                SimpleNAVCodeParser sNAVCodeParser = new SimpleNAVCodeParser();
                foreach (NormalizedCode normNAVCode in sNAVCodeParser.GenerateNormalisedCode(codeTriggerNode.InnerText))
                {
                    if (inProcedure)
                    {
                        if (inCodeBody)
                        {
                            if ((normNAVCode.xPos == 2) && (normNAVCode.Token == "END"))
                            {
                                inProcedure = false;
                                inCodeBody  = false;

                                String beginningPart = codeTriggerNode.InnerText.Substring(0, beginPosition + 6);
                                String endPart       = codeTriggerNode.InnerText.Substring(normNAVCode.position - 1);
                                codeTriggerNode.RemoveAll();

                                XmlCDataSection data = metaDataDocMgt.XmlDocument.CreateCDataSection(
                                    String.Format(CultureInfo.InvariantCulture, "{0}{1}", beginningPart, endPart));
                                codeTriggerNode.AppendChild(data);

                                startAfter    = beginPosition;
                                beginPosition = 0;
                                inProcedure   = false;
                                inCodeBody    = false;
                                restart       = true;
                                break;
                            }
                        }
                        else
                        {
                            if ((normNAVCode.xPos == 2) && (normNAVCode.Token == "BEGIN"))
                            {
                                inCodeBody    = true;
                                beginPosition = normNAVCode.position;
                            }
                        }
                    }
                    else
                    {
                        if ((normNAVCode.position >= startAfter) && (normNAVCode.xPos == 2) && ((normNAVCode.Token == "LOCAL") ||
                                                                                                (normNAVCode.Token == "PROCEDURE") ||
                                                                                                (normNAVCode.Token == "EVENT")))
                        {
                            inProcedure = true;
                        }
                    }
                }
            }

            XmlNode controlNode = formToBeIgnored.SelectSingleNode(@".//a:Controls", metaDataDocMgt.XmlNamespaceMgt);

            controlNode.ParentNode.ReplaceChild(XmlUtility.CreateXmlElement("Controls", null), controlNode);

            XmlNode triggerNode = formToBeIgnored.SelectSingleNode(@".//a:Triggers", metaDataDocMgt.XmlNamespaceMgt);

            triggerNode.ParentNode.ReplaceChild(XmlUtility.CreateXmlElement("Triggers", null), triggerNode);

            // TransformationLog.IgnoreFormsLog(Convert.ToInt32(pageID.Value, CultureInfo.InvariantCulture));
            String logStr = Resources.FormIgnored;

            TransformationLog.GenericLogEntry(logStr, LogCategory.IgnoreForms, pageID, null);
        }