/// <summary> /// add a folder to the list /// </summary> public void AddFolder(XmlNode AFolderNode, string AUserId, CheckAccessPermissionDelegate AHasAccessPermission) { TRbtNavigationButton rbt = new TRbtNavigationButton(FolderCheckChanging); this.sptNavigation.Panel2.Controls.Add(rbt); rbt.Dock = System.Windows.Forms.DockStyle.Bottom; rbt.Tag = AFolderNode; rbt.Name = "rbt" + AFolderNode.Name; rbt.Text = GetLabel(AFolderNode); // TODO: pick up icon from within the resx file, if it is available? if (TYml2Xml.HasAttribute(AFolderNode, "Icon") && System.IO.File.Exists(ResourceDirectory + System.IO.Path.DirectorySeparatorChar + TYml2Xml.GetAttribute(AFolderNode, "Icon"))) { rbt.Icon = ResourceDirectory + System.IO.Path.DirectorySeparatorChar + TYml2Xml.GetAttribute(AFolderNode, "Icon"); } rbt.CheckedChanged += new System.EventHandler(this.FolderCheckedChanged); if ((TYml2Xml.HasAttribute(AFolderNode, "Enabled")) && (TYml2Xml.GetAttribute(AFolderNode, "Enabled").ToLower() == "false")) { rbt.Enabled = false; } else { rbt.Enabled = AHasAccessPermission(AFolderNode, AUserId, false); } }
/// <summary>check if the generator fits the given control by checking the prefix and perhaps some of the attributes</summary> public override bool ControlFitsNode(XmlNode curNode) { if (base.ControlFitsNode(curNode)) { string typeAttribute = TYml2Xml.GetAttribute(curNode, "Type"); if (typeAttribute.ToLower() == "winforms") { return(false); } if (typeAttribute.Length == 0) { this.FControlType = TYPE_DATA_GRID_NON_PAGED; } else { this.FControlType = typeAttribute; } return(true); } return(false); }
/// <summary> /// process a tab page /// </summary> /// <param name="curNode"></param> /// <returns></returns> public Boolean AddTabPage(XmlNode curNode) { // name of tabpage TControlDef tabPage = FCodeStorage.AddControl(curNode); tabPage.parentName = FCodeStorage.GetRootControl("tab").controlName; curNode = TXMLParser.NextNotBlank(curNode.FirstChild); if (curNode != null) { if (curNode.Name == "Controls") { // one control per row, align labels StringCollection controls = TYml2Xml.GetElements(curNode); foreach (string ctrlName in controls) { TControlDef ctrl = FCodeStorage.GetControl(ctrlName); if (ctrl != null) { ctrl.parentName = tabPage.controlName; } } } } return(true); }
/// <summary>write the code for the designer file where the properties of the control are written</summary> public override ProcessTemplate SetControlProperties(TFormWriter writer, TControlDef ctrl) { // Support NoLabel=true FGenerateLabel = true; if (GenerateLabel(ctrl)) { writer.SetControlProperty(ctrl, "Text", "\"" + ctrl.Label + "\""); ctrl.SetAttribute("Width", (PanelLayoutGenerator.MeasureTextWidth(ctrl.Label) + 30).ToString()); } else { ctrl.SetAttribute("Width", "15"); } base.SetControlProperties(writer, ctrl); FGenerateLabel = false; if (TYml2Xml.HasAttribute(ctrl.xmlNode, "RadioChecked")) { writer.SetControlProperty(ctrl, "Checked", TYml2Xml.GetAttribute(ctrl.xmlNode, "RadioChecked")); } return(writer.FTemplate); }
/// <summary> /// get the controls that belong to the toolstrip /// </summary> public override void ProcessChildren(TFormWriter writer, TControlDef container) { // add all the children // TODO add Container elements in statusbar if (container.controlName.StartsWith("stb")) { return; } List <XmlNode> childrenlist; if (TYml2Xml.GetChild(container.xmlNode, "Controls") != null) { // this is for generated toolbar, eg. for the PrintPreviewControl StringCollection childrenNames = TYml2Xml.GetElements(container.xmlNode, "Controls"); childrenlist = new List <XmlNode>(); foreach (string name in childrenNames) { childrenlist.Add(container.xmlNode.OwnerDocument.CreateElement(name)); } } else { // usually, the toolbar buttons are direct children of the toolbar control childrenlist = TYml2Xml.GetChildren(container.xmlNode, true); } //Console.WriteLine("Container: " + container.controlName); foreach (XmlNode child in childrenlist) { // Console.WriteLine("Child: " + child.Name); /* Get unique name if we need it * at the moment we need it only for menu separators */ String UniqueChildName = child.Name; TControlDef ControlDefChild = container.FCodeStorage.GetControl(child.Name); if (ControlDefChild == null) { UniqueChildName = TYml2Xml.GetAttribute(child, "UniqueName"); ControlDefChild = container.FCodeStorage.GetControl(UniqueChildName); } container.Children.Add(ControlDefChild); if (ControlDefChild != null) { IControlGenerator ctrlGenerator = writer.FindControlGenerator(ControlDefChild); // add control itself if (ctrlGenerator != null) { ctrlGenerator.GenerateControl(writer, ControlDefChild); } } } }
/// <summary>check if the generator fits the given control by checking the prefix and perhaps some of the attributes</summary> public override bool ControlFitsNode(XmlNode curNode) { if (base.ControlFitsNode(curNode)) { if ((TYml2Xml.GetAttribute(curNode, "Format") != String.Empty)) { return(false); } if (TYml2Xml.GetAttribute(curNode, "ReadOnly").ToLower() == "true") { if ((TYml2Xml.GetAttribute(curNode, "Type") != "PartnerKey")) { return(true); } } if ((TYml2Xml.GetAttribute(curNode, "Type") == "PartnerKey") || (TYml2Xml.GetAttribute(curNode, "Type") == "Extract") || (TYml2Xml.GetAttribute(curNode, "Type") == "Occupation") || (TYml2Xml.GetAttribute(curNode, "Type") == "Conference") || (TYml2Xml.GetAttribute(curNode, "Type") == "Event") || (TYml2Xml.GetAttribute(curNode, "Type") == "Hyperlink") || (TYml2Xml.GetAttribute(curNode, "Type") == "Bank")) { return(false); } return(true); } return(false); }
/// <summary>add GeneratedReadSetControls</summary> public override void ApplyDerivedFunctionality(TFormWriter writer, TControlDef control) { string paramName = ReportControls.GetParameterName(control.xmlNode); if (paramName == null) { return; } StringCollection optionalValues = TYml2Xml.GetElements(TXMLParser.GetChild(control.xmlNode, "OptionalValues")); foreach (string rbtValueText in optionalValues) { string rbtValue = StringHelper.UpperCamelCase(rbtValueText.Replace("'", "").Replace(" ", "_"), false, false); string rbtName = "rbt" + rbtValue; writer.Template.AddToCodelet("READCONTROLS", "if (" + rbtName + ".Checked) " + Environment.NewLine + "{" + Environment.NewLine + " ACalc.AddParameter(\"" + paramName + "\", \"" + rbtValue + "\");" + Environment.NewLine + "}" + Environment.NewLine); writer.Template.AddToCodelet("SETCONTROLS", rbtName + ".Checked = " + "AParameters.Get(\"" + paramName + "\").ToString() == \"" + rbtValue + "\";" + Environment.NewLine); } }
private void PopulateStartupModuleList() { DataTable moduleTable = new DataTable(); moduleTable.Columns.Add("Value", typeof(System.String)); moduleTable.Columns.Add("Display", typeof(System.String)); TYml2Xml parser = new TYml2Xml(TAppSettingsManager.GetValue("UINavigation.File")); XmlDocument UINavigation = parser.ParseYML2XML(); XmlNode OpenPetraNode = UINavigation.FirstChild.NextSibling.FirstChild; XmlNode SearchBoxesNode = OpenPetraNode.FirstChild; XmlNode MainMenuNode = SearchBoxesNode.NextSibling; XmlNodeList modules = MainMenuNode.ChildNodes; foreach (XmlNode n in modules) { string moduleName = n.Name; if ((moduleName != "Settings") && (moduleName != "CrossLedgerSetup")) { bool hasLabelAttribute = n.Attributes["Label"] != null; DataRow row = moduleTable.NewRow(); row["Value"] = n.Name; row["Display"] = hasLabelAttribute ? n.Attributes["Label"].Value.Replace("&", "") : n.Name; moduleTable.Rows.Add(row); } } cmbInitialSelectedModule.ValueMember = "Value"; cmbInitialSelectedModule.DisplayMember = "Display"; cmbInitialSelectedModule.DataSource = moduleTable.DefaultView; }
/// <summary> /// check if the control has an attribute with the property name in the xml definition /// if such an attribute exists, then set it /// </summary> /// <param name="ACtrl"></param> /// <param name="APropertyName"></param> public virtual void SetControlProperty(TControlDef ACtrl, string APropertyName) { if (TYml2Xml.HasAttribute(ACtrl.xmlNode, APropertyName)) { SetControlProperty(ACtrl, APropertyName, TYml2Xml.GetAttribute(ACtrl.xmlNode, APropertyName)); } }
/// <summary> /// declare the control /// </summary> public override void GenerateDeclaration(TFormWriter writer, TControlDef ctrl) { string hostedControlName = TYml2Xml.GetAttribute(ctrl.xmlNode, "HostedControl"); TControlDef hostedCtrl = FCodeStorage.FindOrCreateControl(hostedControlName, ctrl.controlName); IControlGenerator ctrlGenerator = writer.FindControlGenerator(hostedCtrl); // add control itself if ((hostedCtrl != null) && (ctrlGenerator != null)) { ctrlGenerator.GenerateDeclaration(writer, hostedCtrl); } string localControlType = ControlType; if (ctrl.controlType.Length > 0) { localControlType = ctrl.controlType; } writer.Template.AddToCodelet("CONTROLDECLARATION", "private " + localControlType + " " + ctrl.controlName + ";" + Environment.NewLine); writer.Template.AddToCodelet("CONTROLCREATION", "this." + ctrl.controlName + " = new " + localControlType + "(" + TYml2Xml.GetAttribute(ctrl.xmlNode, "HostedControl") + ");" + Environment.NewLine); }
/// <summary> /// add using namespaces, defined in the yml file in the interface directory /// </summary> public static string AddNamespacesFromYmlFile(String AOutputPath, string AModuleName) { string result = string.Empty; if (AOutputPath.Contains("ICT/Petra/Plugins")) { // for plugins string pluginWithNamespace = TAppSettingsManager.GetValue("plugin"); result += "using " + pluginWithNamespace + ".Data;" + Environment.NewLine; } if (File.Exists(AOutputPath + Path.DirectorySeparatorChar + "InterfacesUsingNamespaces.yml")) { TYml2Xml reader = new TYml2Xml(AOutputPath + Path.DirectorySeparatorChar + "InterfacesUsingNamespaces.yml"); XmlDocument doc = reader.ParseYML2XML(); XmlNode RootNode = doc.DocumentElement.FirstChild; StringCollection usingNamespaces = TYml2Xml.GetElements(RootNode, AModuleName); foreach (string s in usingNamespaces) { result += "using " + s.Trim() + ";" + Environment.NewLine; } } return(result); }
/// <summary> /// build an XML document which includes all ledgers etc. /// </summary> public static XmlNode BuildNavigationXml(bool ADontUseDefaultLedger = false) { TYml2Xml parser = new TYml2Xml(TAppSettingsManager.GetValue("UINavigation.File")); XmlDocument UINavigation = parser.ParseYML2XML(); ALedgerTable AvailableLedgers = new ALedgerTable(); if (UserInfo.GUserInfo.IsInModule(SharedConstants.PETRAMODULE_FINANCE1)) { AvailableLedgers = TRemote.MFinance.Setup.WebConnectors.GetAvailableLedgers(); } XmlNode OpenPetraNode = UINavigation.FirstChild.NextSibling.FirstChild; XmlNode SearchBoxesNode = OpenPetraNode.FirstChild; XmlNode MainMenuNode = SearchBoxesNode.NextSibling; if (TFormsList.GSingletonForms.Count == 0) // There is no need to re-record all Singleton screens if this was already done once { RecordAllSingletonScreens(MainMenuNode); } AddNavigationForEachLedger(MainMenuNode, AvailableLedgers, ADontUseDefaultLedger); if (UserInfo.GUserInfo.IsInModule("PTNRUSER") && UserInfo.GUserInfo.IsInModule("CONFERENCE")) { AddConferenceInformation(MainMenuNode); } return(MainMenuNode); }
/// <summary> /// create the radio buttons and the controls that depend on them /// </summary> /// <param name="writer"></param> /// <param name="curNode"></param> /// <returns></returns> public override StringCollection FindContainedControls(TFormWriter writer, XmlNode curNode) { StringCollection Controls = TYml2Xml.GetElements(TXMLParser.GetChild(curNode, "Controls")); string DefaultValue = Controls[0]; if (TXMLParser.HasAttribute(curNode, "DefaultValue")) { DefaultValue = TXMLParser.GetAttribute(curNode, "DefaultValue"); } foreach (string controlName in Controls) { TControlDef radioButton = writer.CodeStorage.GetControl(controlName); if (radioButton == null) { throw new Exception("cannot find control " + controlName + " used in RadioGroup " + curNode.Name); } if (StringHelper.IsSame(DefaultValue, controlName)) { radioButton.SetAttribute("RadioChecked", "true"); } } return(Controls); }
private void ChangeTaskListNode(object sender, EventArgs e) { TYml2Xml parser = new TYml2Xml(rtbChangeTaskListNode.Lines); XmlDocument xmldoc = parser.ParseYML2XML(); this.FPnl.TaskListNode = xmldoc.FirstChild.NextSibling.FirstChild; }
/// <summary>write the code for the designer file where the properties of the control are written</summary> public override ProcessTemplate SetControlProperties(TFormWriter writer, TControlDef ACtrl) { ProcessTemplate ctrlSnippet = base.SetControlProperties(writer, ACtrl); ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "URL", ACtrl, TYml2Xml.GetAttribute(ACtrl.xmlNode, "url")); ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "BROWSERMISSINGIFRAMESUPPORT", null, "Your browser is not able to display embedded documents. Please click on the following link to read the text: "); ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "IFRAMEINBIGGERWINDOW", null, "Open this document in a bigger window"); ctrlSnippet.SetCodelet("HEIGHT", "250"); if (ACtrl.HasAttribute("Height")) { ctrlSnippet.SetCodelet("HEIGHT", ACtrl.GetAttribute("Height")); } return(ctrlSnippet); }
/// <summary>write the code for the designer file where the properties of the control are written</summary> public override ProcessTemplate SetControlProperties(TFormWriter writer, TControlDef ctrl) { ProcessTemplate ctrlSnippet = base.SetControlProperties(writer, ctrl); if (ctrlSnippet.FTemplateCode.Contains("{#REDIRECTONSUCCESS}")) { ProcessTemplate redirectSnippet = writer.FTemplate.GetSnippet("REDIRECTONSUCCESS"); ctrlSnippet.SetCodelet("REDIRECTONSUCCESS", redirectSnippet.FTemplateCode.ToString()); } if (ctrl.HasAttribute("AjaxRequestUrl")) { ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "VALIDATIONERRORTITLE", ctrl, ctrl.GetAttribute("ValidationErrorTitle")); ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "VALIDATIONERRORMESSAGE", ctrl, ctrl.GetAttribute("ValidationErrorMessage")); ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "SENDINGDATATITLE", ctrl, ctrl.GetAttribute("SendingMessageTitle")); ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "SENDINGDATAMESSAGE", ctrl, ctrl.GetAttribute("SendingMessage")); if (ctrl.HasAttribute("SuccessMessage")) { ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "REQUESTSUCCESSTITLE", ctrl, ctrl.GetAttribute("SuccessMessageTitle")); ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "REQUESTSUCCESSMESSAGE", ctrl, ctrl.GetAttribute("SuccessMessage")); } ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "REQUESTFAILURETITLE", ctrl, ctrl.GetAttribute("FailureMessageTitle")); ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "REQUESTFAILUREMESSAGE", ctrl, ctrl.GetAttribute("FailureMessage")); } ctrlSnippet.SetCodelet("REQUESTURL", ctrl.GetAttribute("AjaxRequestUrl")); ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "REDIRECTURLONSUCCESS", ctrl, ctrl.GetAttribute("RedirectURLOnSuccess")); if (ctrl.GetAttribute("DownloadOnSuccess").StartsWith("jsonData")) { ctrlSnippet.SetCodelet("REDIRECTDOWNLOAD", ctrl.GetAttribute("DownloadOnSuccess")); } ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "REDIRECTURLONCANCEL", ctrl, ctrl.GetAttribute("RedirectURLOnCancel")); ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "CANCELQUESTIONTITLE", ctrl, ctrl.GetAttribute("CancelQuestionTitle")); ((TExtJsFormsWriter)writer).AddResourceString(ctrlSnippet, "CANCELQUESTIONMESSAGE", ctrl, ctrl.GetAttribute("CancelQuestionMessage")); XmlNode AjaxParametersNode = TYml2Xml.GetChild(ctrl.xmlNode, "AjaxRequestParameters"); if (AjaxParametersNode != null) { string ParameterString = String.Empty; foreach (XmlAttribute attr in AjaxParametersNode.Attributes) { if (!attr.Name.Equals("depth")) { ParameterString += attr.Name + ": '" + attr.Value + "', "; } } ctrlSnippet.SetCodelet("REQUESTPARAMETERS", ParameterString); writer.FTemplate.SetCodelet("REQUESTPARAMETERS", "true"); } return(ctrlSnippet); }
/// <summary>write the code for the designer file where the properties of the control are written</summary> public override ProcessTemplate SetControlProperties(TFormWriter writer, TControlDef ctrl) { base.SetControlProperties(writer, ctrl); if (TYml2Xml.HasAttribute(ctrl.xmlNode, "DefaultValue")) { writer.SetControlProperty(ctrl, "Text", "\"" + TYml2Xml.GetAttribute(ctrl.xmlNode, "DefaultValue") + "\""); } if ((TYml2Xml.HasAttribute(ctrl.xmlNode, "Multiline")) && (TYml2Xml.GetAttribute(ctrl.xmlNode, "Multiline") == "true")) { writer.SetControlProperty(ctrl, "Multiline", "true"); if ((TYml2Xml.HasAttribute(ctrl.xmlNode, "WordWrap")) && (TYml2Xml.GetAttribute(ctrl.xmlNode, "WordWrap") == "false")) { writer.SetControlProperty(ctrl, "WordWrap", "false"); } if (TYml2Xml.HasAttribute(ctrl.xmlNode, "ScrollBars")) { writer.SetControlProperty(ctrl, "ScrollBars", "ScrollBars." + TYml2Xml.GetAttribute(ctrl.xmlNode, "ScrollBars")); } } writer.Template.AddToCodelet("ASSIGNFONTATTRIBUTES", "this." + ctrl.controlName + ".Font = TAppSettingsManager.GetDefaultBoldFont();" + Environment.NewLine); return(writer.FTemplate); }
/// <summary> /// build an XML document which includes all ledgers etc. /// </summary> public static XmlNode BuildNavigationXml(bool ADontUseDefaultLedger = false) { string UINavigationFile = TAppSettingsManager.GetValue("UINavigation.File"); if (!File.Exists(UINavigationFile)) { throw new Exception("cannot find file " + UINavigationFile); } TYml2Xml parser = new TYml2Xml(UINavigationFile); XmlDocument UINavigation = parser.ParseYML2XML(); ALedgerTable AvailableLedgers = new ALedgerTable(); if (UserInfo.GUserInfo.IsInModule(SharedConstants.PETRAMODULE_FINANCE1)) { AvailableLedgers = TGLSetupWebConnector.GetAvailableLedgers(); } XmlNode OpenPetraNode = UINavigation.FirstChild.NextSibling.FirstChild; XmlNode MainMenuNode = OpenPetraNode.FirstChild; AddNavigationForEachLedger(MainMenuNode, AvailableLedgers, ADontUseDefaultLedger); return(MainMenuNode); }
void Button3Click(object sender, EventArgs e) { String yamlFile = txtYaml.Text.ToString(); TYml2Xml parser = new TYml2Xml(yamlFile); XmlDocument UINavigation = parser.ParseYML2XML(); new ShepherdTest(UINavigation.FirstChild.NextSibling.FirstChild).Show(); }
/// <summary>write the code for the designer file where the properties of the control are written</summary> public override ProcessTemplate SetControlProperties(TFormWriter writer, TControlDef ctrl) { // TODO this does not work yet. see EventRole Maintain screen if ((!ctrl.HasAttribute("Align")) && (!ctrl.HasAttribute("Width"))) { ctrl.SetAttribute("Stretch", "horizontally"); } base.SetControlProperties(writer, ctrl); TControlDef parentCtrl = writer.FCodeStorage.GetControl(ctrl.parentName); // We need to over-ride any Anchor requests in the YAML to anchor an attached label to anything other than top-left // But pure label controls can be anchored to, say, left-top-right if ((ctrl.controlName.Substring(ctrl.controlTypePrefix.Length) == parentCtrl.controlName.Substring(parentCtrl.controlTypePrefix.Length)) || ((ctrl.HasAttribute("Dock") == false) && (ctrl.HasAttribute("Align") == false))) { // stretch at design time, but do not align to the right writer.SetControlProperty(ctrl, "Anchor", "((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)))"); } string labelText = ""; if (TYml2Xml.HasAttribute(ctrl.xmlNode, "Text")) { labelText = TYml2Xml.GetAttribute(ctrl.xmlNode, "Text"); } else { labelText = ctrl.Label + ":"; } if (ctrl.HasAttribute("Width")) { ctrl.SetAttribute("Width", ctrl.GetAttribute("Width")); } else { ctrl.SetAttribute("Width", (PanelLayoutGenerator.MeasureTextWidth(labelText) + 5).ToString()); } if (ctrl.HasAttribute("Height")) { ctrl.SetAttribute("Height", ctrl.GetAttribute("Height")); } writer.SetControlProperty(ctrl, "Text", "\"" + labelText + "\""); writer.SetControlProperty(ctrl, "Padding", "new System.Windows.Forms.Padding(0, 5, 0, 0)"); if (FRightAlign) { writer.SetControlProperty(ctrl, "TextAlign", "System.Drawing.ContentAlignment.TopRight"); } return(writer.FTemplate); }
/// <summary>check if the generator fits the given control by checking the prefix and perhaps some of the attributes</summary> public override bool ControlFitsNode(XmlNode curNode) { if (base.ControlFitsNode(curNode)) { return((curNode.Name != "tbbSeparator") && (TYml2Xml.GetAttribute(curNode, "Label") != "-")); } return(false); }
/// <summary>check if the generator fits the given control by checking the prefix and perhaps some of the attributes</summary> public override bool ControlFitsNode(XmlNode curNode) { if (SimplePrefixMatch(curNode)) { return(TYml2Xml.HasAttribute(curNode, "List")); } return(false); }
/// <summary> /// get value of attribute from yaml /// </summary> public string GetAttribute(string name, string ADefaultValue) { if (!TYml2Xml.HasAttribute(xmlNode, name)) { return(ADefaultValue); } return(TYml2Xml.GetAttribute(xmlNode, name)); }
/// <summary>write the code for the designer file where the properties of the control are written</summary> public override ProcessTemplate SetControlProperties(TFormWriter writer, TControlDef ctrl) { Int32 buttonWidth = 40; Int32 textBoxWidth = 80; // seems to be hardcoded in csharp\ICT\Petra\Client\CommonControls\Gui\txtAutoPopulatedButtonLabel.Designer.cs Int32 controlWidth = 390; base.SetControlProperties(writer, ctrl); if ((ctrl.HasAttribute("ShowLabel") && (ctrl.GetAttribute("ShowLabel").ToLower() == "false"))) { writer.SetControlProperty(ctrl, "ShowLabel", "false"); controlWidth = 120; } // Note: the control defaults to 'ShowLabel' true, so this doesn't need to be set to 'true' in code. writer.SetControlProperty(ctrl, "ASpecialSetting", "true"); writer.SetControlProperty(ctrl, "ButtonTextAlign", "System.Drawing.ContentAlignment.MiddleCenter"); writer.SetControlProperty(ctrl, "ListTable", "TtxtAutoPopulatedButtonLabel.TListTableEnum." + FButtonLabelType); writer.SetControlProperty(ctrl, "PartnerClass", "\"" + ctrl.GetAttribute("PartnerClass") + "\""); writer.SetControlProperty(ctrl, "MaxLength", "32767"); writer.SetControlProperty(ctrl, "Tag", "\"CustomDisableAlthoughInvisible\""); writer.SetControlProperty(ctrl, "TextBoxWidth", textBoxWidth.ToString()); if (!(ctrl.HasAttribute("ReadOnly") && (ctrl.GetAttribute("ReadOnly").ToLower() == "true"))) { writer.SetControlProperty(ctrl, "ButtonWidth", buttonWidth.ToString()); writer.SetControlProperty(ctrl, "ReadOnly", "false"); writer.SetControlProperty(ctrl, "Font", "new System.Drawing.Font(\"Verdana\", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, (byte)0)"); writer.SetControlProperty(ctrl, "ButtonText", "\"Find\""); } else { writer.SetControlProperty(ctrl, "ButtonWidth", "0"); writer.SetControlProperty(ctrl, "BorderStyle", "System.Windows.Forms.BorderStyle.None"); writer.SetControlProperty(ctrl, "Padding", "new System.Windows.Forms.Padding(0, 4, 0, 0)"); } if (!ctrl.HasAttribute("Width")) { ctrl.SetAttribute("Width", controlWidth.ToString()); } if (TYml2Xml.HasAttribute(ctrl.xmlNode, "DefaultValue")) { writer.SetControlProperty(ctrl, "Text", "\"" + TYml2Xml.GetAttribute(ctrl.xmlNode, "DefaultValue") + "\""); } return(writer.FTemplate); }
/// <summary> /// add Catalog.GetString for each label and description in the UINavigation file to the dummy file to prepare the translation files /// </summary> /// <param name="UINavigationFilename">yml file</param> /// <param name="ATranslationWriter">dummy cs file that is used to provide the strings to gettext</param> public static void AddTranslationUINavigation(string UINavigationFilename, StreamWriter ATranslationWriter) { TYml2Xml parser = new TYml2Xml(UINavigationFilename); XmlDocument doc = parser.ParseYML2XML(); XmlNode OpenPetraNode = doc.FirstChild.NextSibling.FirstChild; XmlNode SearchBoxesNode = OpenPetraNode.FirstChild; XmlNode MainMenuNode = SearchBoxesNode.NextSibling; XmlNode DepartmentNode = MainMenuNode.FirstChild; while (DepartmentNode != null) { ATranslationWriter.WriteLine("Catalog.GetString(\"" + GetLabelOrName(DepartmentNode) + "\");"); XmlNode ModuleNode = DepartmentNode.FirstChild; while (ModuleNode != null) { ATranslationWriter.WriteLine("Catalog.GetString(\"" + GetLabelOrName(ModuleNode) + "\");"); XmlNode SubModuleNode = ModuleNode.FirstChild; while (SubModuleNode != null) { ATranslationWriter.WriteLine("Catalog.GetString(\"" + GetLabelOrName(SubModuleNode) + "\");"); XmlNode TaskGroupNode = SubModuleNode.FirstChild; while (TaskGroupNode != null) { ATranslationWriter.WriteLine("Catalog.GetString(\"" + GetLabelOrName(TaskGroupNode) + "\");"); XmlNode TaskNode = TaskGroupNode.FirstChild; while (TaskNode != null) { ATranslationWriter.WriteLine("Catalog.GetString(\"" + GetLabelOrName(TaskNode) + "\");"); if (TYml2Xml.HasAttribute(TaskNode, "Description")) { ATranslationWriter.WriteLine("Catalog.GetString(\"" + TYml2Xml.GetAttribute(TaskNode, "Description") + "\");"); } TaskNode = TaskNode.NextSibling; } TaskGroupNode = TaskGroupNode.NextSibling; } SubModuleNode = SubModuleNode.NextSibling; } ModuleNode = ModuleNode.NextSibling; } DepartmentNode = DepartmentNode.NextSibling; } }
/// <summary> /// set the orientation based on the attribute: ControlsOrientation; /// the default is vertical /// </summary> /// <param name="ACtrl"></param> public void SetOrientation(TControlDef ACtrl) { FOrientation = eOrientation.Vertical; if (TYml2Xml.HasAttribute(ACtrl.xmlNode, "ControlsOrientation") && (TYml2Xml.GetAttribute(ACtrl.xmlNode, "ControlsOrientation").ToLower() == "horizontal")) { FOrientation = eOrientation.Horizontal; } }
private string ExecuteAction(XmlNode ActionNode, out bool GotServerAccessDeniedException) { string ReturnValue = string.Empty; Exception TheException = null; GotServerAccessDeniedException = false; string actionClick = TYml2Xml.GetAttribute(ActionNode, "ActionClick"); string actionOpenScreen = TYml2Xml.GetAttribute(ActionNode, "ActionOpenScreen"); string className = string.Empty; if (actionClick.Contains(".")) { className = actionClick.Substring(0, actionClick.IndexOf(".")); } else if (actionOpenScreen.Length > 0) { className = actionOpenScreen; } TLogging.Log("Opening " + className); try { // Execute the action by calling the TLstTasks static method // If the call goes through to the server we may get an exception. // It really ought to be one of our Ict.Common.Exceptions.EAccessDeniedExceptions // but Remoting turns that into a TargetInvocationException (sadly). Microsoft may change this in the future. ReturnValue = TLstTasks.ExecuteAction(ActionNode, null); GotServerAccessDeniedException = false; } catch (System.Reflection.TargetInvocationException ex) { // Get the InnerException, if we can TheException = (ex.InnerException == null) ? ex : ex.InnerException; } catch (Exception ex) { // This would include a real Ict.Common.Exceptions.EAccessDeniedException if we ever got one TheException = ex; } if (TheException != null) { if (TheException is ESecurityAccessDeniedException) { GotServerAccessDeniedException = true; } ReturnValue = TheException.Message; } return(ReturnValue); }
XmlDocument LoadYAMLTestFile() { String yamlFile = txtYaml.Text.ToString(); new TAppSettingsManager("../../csharp/ICT/Testing/exe/Controls/ControlTestBench/ControlTestBench.exe.config"); TYml2Xml parser = new TYml2Xml(TAppSettingsManager.GetValue("YAMLDemodataPath") + '/' + yamlFile); XmlDocument UINavigation = parser.ParseYML2XML(); return UINavigation; }
/// <summary>check if the generator fits the given control by checking the prefix and perhaps some of the attributes</summary> public override bool ControlFitsNode(XmlNode curNode) { if (base.ControlFitsNode(curNode)) { return(!TYml2Xml.HasAttribute(curNode, "List") && !TYml2Xml.HasAttribute(curNode, "AutoComplete") && !TYml2Xml.HasAttribute(curNode, "MultiColumn")); } return(false); }
void Button1Click(object sender, EventArgs e) { String yamlFile = txtYaml.Text.ToString(); // TAppSettingsManager opts = new TAppSettingsManager(); //opts.GetValue(yamlFile) TYml2Xml parser = new TYml2Xml(yamlFile); XmlDocument UINavigation = parser.ParseYML2XML(); String VisualStyle = cmbVisualStyle.Text.ToString(); TVisualStylesEnum EnumStyle; switch (VisualStyle) { case "AccordionPanel": EnumStyle = Ict.Common.Controls.TVisualStylesEnum.vsAccordionPanel; break; case "TaskPanel": EnumStyle = Ict.Common.Controls.TVisualStylesEnum.vsTaskPanel; break; case "Dashboard": EnumStyle = Ict.Common.Controls.TVisualStylesEnum.vsDashboard; break; case "Shepherd": EnumStyle = Ict.Common.Controls.TVisualStylesEnum.vsShepherd; break; case "HorizontalCollapse": default: EnumStyle = Ict.Common.Controls.TVisualStylesEnum.vsHorizontalCollapse; break; } // // taskList1 // this.Controls.Remove(taskList1); // if(this.taskList1 == null){ this.taskList1 = new Ict.Common.Controls.TTaskList(UINavigation.FirstChild.NextSibling.FirstChild, EnumStyle); // } // else{ // this.taskList1 = new Ict.Common.Controls.TTaskList(this.taskList1.MasterXmlNode,EnumStyle); // } // this.taskList1.AutomaticNumbering = false; this.taskList1.Location = new System.Drawing.Point(333, 29); // this.taskList1.MasterXmlNode = null; this.taskList1.Name = "taskList1"; this.taskList1.Size = new System.Drawing.Size(322, 213); this.taskList1.TabIndex = 6; this.Controls.Add(taskList1); // this.taskList1.VisualStyle = null; // using ( TaskListCheck newForm = new TaskListCheck(UINavigation.FirstChild.NextSibling.FirstChild,EnumStyle) ) newForm.ShowDialog(); //newForm.Controls.Add( }
private static void MergePluginUINavigation(string APluginsPath, ref XmlDocument AUINavigation) { string[] UINavigationFiles = Directory.GetFiles(APluginsPath, "*UINavigation.yml", SearchOption.AllDirectories); foreach (string UINavFile in UINavigationFiles) { TYml2Xml parser = new TYml2Xml(UINavFile); XmlDocument UINavigation = parser.ParseYML2XML(); TYml2Xml.Merge(ref AUINavigation, UINavigation, 1); } }
XmlDocument LoadYAMLTestFile() { String yamlFile = txtYaml.Text.ToString(); new TAppSettingsManager("../../csharp/ICT/Testing/exe/Controls/ControlTestBench/ControlTestBench.exe.config"); TYml2Xml parser = new TYml2Xml(TAppSettingsManager.GetValue("YAMLDemodataPath") + '/' + yamlFile); XmlDocument UINavigation = parser.ParseYML2XML(); return(UINavigation); }
/// import records for fees payable or receivable into an empty new ledger private static void ImportDefaultAdminGrantsPayableReceivable(ref GLSetupTDS AMainDS, Int32 ALedgerNumber) { AFeesPayableRow newFeesPayableRow = null; AFeesReceivableRow newFeesReceivableRow = null; bool newRow; DataRow existingRow; bool IsFeesPayable; string FeeCode; XmlDocument doc; TYml2Xml ymlFile; string Filename = TAppSettingsManager.GetValue("SqlFiles.Path", ".") + Path.DirectorySeparatorChar + "DefaultAdminGrantsPayableReceivable.yml"; try { ymlFile = new TYml2Xml(Filename); doc = ymlFile.ParseYML2XML(); } catch (XmlException exp) { throw new Exception( Catalog.GetString("There was a problem with the syntax of the file.") + Environment.NewLine + exp.Message + Environment.NewLine + Filename); } XmlNode root = doc.FirstChild.NextSibling; foreach (XmlNode child in root) { FeeCode = TYml2Xml.GetElementName(child).ToUpper(); IsFeesPayable = (TYml2Xml.GetAttribute(child, "feespayable") == "yes" || TYml2Xml.GetAttribute(child, "feespayable") == "true"); if (IsFeesPayable) { // does this fee already exist? newRow = false; existingRow = AMainDS.AFeesPayable.Rows.Find(new object[] { ALedgerNumber, FeeCode }); if (existingRow != null) { newFeesPayableRow = (AFeesPayableRow)existingRow; } else { newRow = true; newFeesPayableRow = AMainDS.AFeesPayable.NewRowTyped(); } newFeesPayableRow.LedgerNumber = ALedgerNumber; newFeesPayableRow.FeeCode = FeeCode; newFeesPayableRow.ChargeOption = TYml2Xml.GetAttribute(child, "chargeoption"); if (TYml2Xml.HasAttribute(child, "percentage")) { newFeesPayableRow.ChargePercentage = Convert.ToInt32(TYml2Xml.GetAttribute(child, "percentage")); } newFeesPayableRow.CostCentreCode = TYml2Xml.GetAttribute(child, "costcentrecode"); newFeesPayableRow.AccountCode = TYml2Xml.GetAttribute(child, "accountcode"); newFeesPayableRow.DrAccountCode = TYml2Xml.GetAttribute(child, "draccountcode"); if (TYml2Xml.HasAttribute(child, "description")) { newFeesPayableRow.FeeDescription = TYml2Xml.GetAttribute(child, "description"); } if (newRow) { AMainDS.AFeesPayable.Rows.Add(newFeesPayableRow); } } else { // does this fee already exist? newRow = false; existingRow = AMainDS.AFeesReceivable.Rows.Find(new object[] { ALedgerNumber, FeeCode }); if (existingRow != null) { newFeesReceivableRow = (AFeesReceivableRow)existingRow; } else { newRow = true; newFeesReceivableRow = AMainDS.AFeesReceivable.NewRowTyped(); } newFeesReceivableRow.LedgerNumber = ALedgerNumber; newFeesReceivableRow.FeeCode = FeeCode; newFeesReceivableRow.ChargeOption = TYml2Xml.GetAttribute(child, "chargeoption"); if (TYml2Xml.HasAttribute(child, "percentage")) { newFeesReceivableRow.ChargePercentage = Convert.ToInt32(TYml2Xml.GetAttribute(child, "percentage")); } newFeesReceivableRow.CostCentreCode = TYml2Xml.GetAttribute(child, "costcentrecode"); newFeesReceivableRow.AccountCode = TYml2Xml.GetAttribute(child, "accountcode"); newFeesReceivableRow.DrAccountCode = TYml2Xml.GetAttribute(child, "draccountcode"); if (TYml2Xml.HasAttribute(child, "description")) { newFeesReceivableRow.FeeDescription = TYml2Xml.GetAttribute(child, "description"); } if (newRow) { AMainDS.AFeesReceivable.Rows.Add(newFeesReceivableRow); } } } }
/// <summary> /// Display File open dialog box and read file into memory /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OpenFile(System.Object sender, EventArgs e) { if (!btnStartImport.Enabled && btnCancelImport.Enabled) { MessageBox.Show(Catalog.GetString("Please stop the current import before selecting a different file")); return; } txtPartnerInfo.Text = ""; OpenFileDialog DialogOpen = new OpenFileDialog(); DialogOpen.Filter = Catalog.GetString( "All supported formats|*.yml;*.csv;*.ext|Text file (*.yml)|*.yml|Partner Extract (*.ext)|*.ext|Partner List (*.csv)|.csv"); DialogOpen.FilterIndex = 1; DialogOpen.RestoreDirectory = true; DialogOpen.Title = Catalog.GetString("Select the file for importing partners"); if (DialogOpen.ShowDialog() == DialogResult.OK) { try { this.Cursor = Cursors.WaitCursor; TVerificationResultCollection VerificationResult = null; FFileName = DialogOpen.FileName; AddStatus(String.Format("Reading {0}\r\n", Path.GetFileName(FFileName))); if (Path.GetExtension(FFileName) == ".yml") { TYml2Xml yml = new TYml2Xml(FFileName); AddStatus(Catalog.GetString("Parsing file. Please wait...\r\n")); FFileContent = TXMLParser.XmlToString(yml.ParseYML2XML()); LoadDataSet(ref VerificationResult); } if (Path.GetExtension(FFileName) == ".csv") { // select separator, make sure there is a header line with the column captions/names TDlgSelectCSVSeparator dlgSeparator = new TDlgSelectCSVSeparator(true); Boolean fileCanOpen = dlgSeparator.OpenCsvFile(FFileName); if (!fileCanOpen) { MessageBox.Show(Catalog.GetString("Unable to open file."), Catalog.GetString("Import Partners"), MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } if (dlgSeparator.ShowDialog() == DialogResult.OK) { try { XmlDocument doc = TCsv2Xml.ParseCSV2Xml(FFileName, dlgSeparator.SelectedSeparator); FFileContent = TXMLParser.XmlToString(doc); LoadDataSet(ref VerificationResult); } catch (Exception ex) { MessageBox.Show(ex.Message, Catalog.GetString("Import Partners")); AddStatus("\r\n" + ex.Message + "\r\n\r\n" + String.Format("Import of file {0} cancelled!", Path.GetFileName(FFileName)) + "\r\n"); return; } } else { AddStatus(String.Format("\r\nImport of file {0} cancelled!\r\n", Path.GetFileName(FFileName))); return; } } else if (Path.GetExtension(FFileName) == ".ext") { StreamReader sr = new StreamReader(FFileName, true); FFileContent = sr.ReadToEnd().Replace("\r", ""); sr.Close(); AddStatus(String.Format("{0} lines.\r\n", FFileContent.Length)); AddStatus(Catalog.GetString("Parsing file. Please wait...\r\n")); LoadDataSet(ref VerificationResult); } AddStatus(FormatVerificationResult("Imported file verification: ", VerificationResult)); if (!TVerificationHelper.IsNullOrOnlyNonCritical(VerificationResult)) { string ErrorMessages = String.Empty; foreach (TVerificationResult verif in VerificationResult) { ErrorMessages += "[" + verif.ResultContext + "] " + verif.ResultTextCaption + ": " + verif.ResultText + Environment.NewLine; } MessageBox.Show(ErrorMessages, Catalog.GetString("Import of partners failed!")); FMainDS = null; return; } txtFilename.Text = FFileName; grpStepTwo.Enabled = true; btnStartImport.Enabled = true; // Determine the 'Primary E-Mail Address' of all Partners that are contained in the import file FPartnersOverallContactSettings = Calculations.DeterminePrimaryOrWithinOrgSettings(FMainDS.PPartnerAttribute, Calculations.TOverallContSettingKind.ocskPrimaryEmailAddress); AddStatus(String.Format(Catalog.GetString("File read OK ({0} partners) - press Start to import.\r\n"), FMainDS.PPartner.Rows.Count)); } finally { if (FMainDS == null) { FMainDSBackup = new PartnerImportExportTDS(); } else { FMainDSBackup.Merge(FMainDS.Copy()); } this.Cursor = Cursors.Default; } } }
public void TestReadAndWriteYaml() { // parse a winforms yaml file, write it again, check if the same string filename = PathToTestData + "testReadWrite.yml"; TYml2Xml converterYml = new TYml2Xml(filename); XmlDocument docFromYML = converterYml.ParseYML2XML(); TYml2Xml.Xml2Yml(docFromYML, filename + ".new"); Assert.AreEqual(true, TTextFile.SameContent(filename, filename + ".new"), "the files should be the same: " + filename); System.IO.File.Delete(filename + ".new"); }
private static void CreateLocalisedYamlFile(string ALanguageCode, string AYamlfile) { TLogging.Log(AYamlfile); string localisedYamlFile = AYamlfile.Replace(".yaml", "." + ALanguageCode + ".yaml"); TYml2Xml parser; XmlDocument localisedYamlFileDoc = new XmlDocument(); if (File.Exists(localisedYamlFile)) { // TODO parse the localised yaml file and add translations to the po file parser = new TYml2Xml(localisedYamlFile); localisedYamlFileDoc = parser.ParseYML2XML(); } // parse the yaml file parser = new TYml2Xml(AYamlfile); XmlDocument yamlFile = parser.ParseYML2XML(); SortedList xmlNodes = new SortedList(); TCodeStorage CodeStorage = new TCodeStorage(yamlFile, xmlNodes); XmlNode RootNode = TXMLParser.FindNodeRecursive(yamlFile.DocumentElement, "RootNode"); RootNode.Attributes.RemoveAll(); TXMLParser.SetAttribute(RootNode, "BaseYaml", Path.GetFileName(AYamlfile)); // get controls node XmlNode Controls = TXMLParser.FindNodeRecursive(yamlFile.DocumentElement, "Controls"); if (Controls != null) { foreach (XmlNode control in Controls) { AdjustLabel(control, CodeStorage, localisedYamlFileDoc); } } // get actions node XmlNode Actions = TXMLParser.FindNodeRecursive(yamlFile.DocumentElement, "Actions"); if (Actions != null) { foreach (XmlNode action in Actions) { AdjustLabel(action, CodeStorage, localisedYamlFileDoc); } } // menu items XmlNode menuitems = TXMLParser.FindNodeRecursive(yamlFile.DocumentElement, "Menu"); if (menuitems != null) { foreach (XmlNode menu in menuitems) { if (menu.Name.Contains("Separator")) { continue; } AdjustLabel(menu, CodeStorage, localisedYamlFileDoc); } } // toolbar buttons XmlNode tbbuttons = TXMLParser.FindNodeRecursive(yamlFile.DocumentElement, "Toolbar"); if (tbbuttons != null) { foreach (XmlNode tbb in tbbuttons) { if (tbb.Name.Contains("Separator")) { continue; } AdjustLabel(tbb, CodeStorage, localisedYamlFileDoc); } } // TODO parse the cs file for string constants // TODO warn about Catalog.GetString calls in manualcode file // TODO add constants to localised yaml file TYml2Xml.Xml2Yml(yamlFile, localisedYamlFile); }
/// <summary> /// convert from all sorts of formats into xml document; /// shows a dialog to the user to select the file to import /// </summary> /// <returns></returns> public static XmlDocument ImportWithDialog(string ADialogTitle, out string AFilename) { // TODO support import from Excel and OpenOffice files // See also http://sourceforge.net/apps/mediawiki/openpetraorg/index.php?title=Data_liberation OpenFileDialog DialogOpen = new OpenFileDialog(); AFilename = ""; DialogOpen.Filter = Catalog.GetString( "Text file (*.yml)|*.yml|XML file (*.xml)|*.xml|Spreadsheet file (*.csv)|All supported file formats (*.yml, *.xml, *.csv)|*.csv;*.yml;*.xml|"); DialogOpen.FilterIndex = 4; DialogOpen.RestoreDirectory = true; DialogOpen.Title = ADialogTitle; if (DialogOpen.ShowDialog() == DialogResult.OK) { AFilename = DialogOpen.FileName; if (DialogOpen.FileName.ToLower().EndsWith("csv")) { // select separator, make sure there is a header line with the column captions/names TDlgSelectCSVSeparator dlgSeparator = new TDlgSelectCSVSeparator(true); Boolean fileCanOpen = dlgSeparator.OpenCsvFile(DialogOpen.FileName); if (!fileCanOpen) { throw new Exception(String.Format(Catalog.GetString("File {0} Cannot be opened."), DialogOpen.FileName)); } if (dlgSeparator.ShowDialog() == DialogResult.OK) { XmlDocument doc = TCsv2Xml.ParseCSV2Xml(DialogOpen.FileName, dlgSeparator.SelectedSeparator); return doc; } } else if (DialogOpen.FileName.ToLower().EndsWith("xml")) { XmlDocument doc = new XmlDocument(); doc.Load(DialogOpen.FileName); return doc; } else if (DialogOpen.FileName.ToLower().EndsWith("yml")) { TYml2Xml yml = new TYml2Xml(DialogOpen.FileName); return yml.ParseYML2XML(); } } return null; }
public static bool ImportAccountHierarchy(Int32 ALedgerNumber, string AHierarchyName, string AYmlAccountHierarchy, out TVerificationResultCollection AVerificationResult) { AVerificationResult = new TVerificationResultCollection(); #region Validate Arguments if (ALedgerNumber <= 0) { throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString( "Function:{0} - The Ledger number must be greater than 0!"), Utilities.GetMethodName(true)), ALedgerNumber); } else if (AHierarchyName.Length == 0) { throw new ArgumentException(String.Format(Catalog.GetString("Function:{0} - The Hierarchy name is empty!"), Utilities.GetMethodName(true))); } else if (AYmlAccountHierarchy.Length == 0) { throw new ArgumentException(String.Format(Catalog.GetString("Function:{0} - The Account Hierarchy YML is empty!"), Utilities.GetMethodName(true))); } #endregion Validate Arguments XmlDocument XMLDoc = new XmlDocument(); if (AYmlAccountHierarchy.StartsWith("<?xml version=")) { XMLDoc.LoadXml(AYmlAccountHierarchy); } else { try { TYml2Xml ymlParser = new TYml2Xml(AYmlAccountHierarchy.Split(new char[] { '\n' })); XMLDoc = ymlParser.ParseYML2XML(); } catch (XmlException exp) { TLogging.Log(exp.ToString()); throw new Exception( Catalog.GetString("There was a problem with the syntax of the file.") + Environment.NewLine + exp.Message + Environment.NewLine + AYmlAccountHierarchy); } } GLSetupTDS MainDS = LoadAccountHierarchies(ALedgerNumber); XmlNode Root = XMLDoc.FirstChild.NextSibling.FirstChild; StringCollection ImportedAccountNames = new StringCollection(); ImportedAccountNames.Add(ALedgerNumber.ToString()); // delete all account hierarchy details of this hierarchy foreach (AAccountHierarchyDetailRow accounthdetail in MainDS.AAccountHierarchyDetail.Rows) { if (accounthdetail.AccountHierarchyCode == AHierarchyName) { accounthdetail.Delete(); } } CreateAccountHierarchyRecursively(ref MainDS, ALedgerNumber, ref ImportedAccountNames, Root, ALedgerNumber.ToString(), ref AVerificationResult); foreach (AAccountRow accountRow in MainDS.AAccount.Rows) { if ((accountRow.RowState != DataRowState.Deleted) && !ImportedAccountNames.Contains(accountRow.AccountCode)) { // if there are any existing posted transactions that reference this account, it can't be deleted. ATransactionTable transTbl = null; TDBTransaction transaction = null; DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, ref transaction, delegate { // if there are any existing posted transactions that reference this account, it can't be deleted. transTbl = ATransactionAccess.LoadViaAAccount(ALedgerNumber, accountRow.AccountCode, transaction); }); if (transTbl.Rows.Count == 0) // No-one's used this account, so I can delete it. { // // If the deleted account included Analysis types I need to unlink them from the Account first. foreach (AAnalysisAttributeRow Row in MainDS.AAnalysisAttribute.Rows) { if ((Row.LedgerNumber == ALedgerNumber) && (Row.AccountCode == accountRow.AccountCode)) { Row.Delete(); } } // remove fees receivable if they reference the account foreach (AFeesReceivableRow Row in MainDS.AFeesReceivable.Rows) { if ((Row.RowState != DataRowState.Deleted) && (Row.LedgerNumber == ALedgerNumber) && (Row.AccountCode == accountRow.AccountCode)) { Row.Delete(); } } // remove fees payable if they reference the account foreach (AFeesPayableRow Row in MainDS.AFeesPayable.Rows) { if ((Row.RowState != DataRowState.Deleted) && (Row.LedgerNumber == ALedgerNumber) && (Row.AccountCode == accountRow.AccountCode)) { Row.Delete(); } } accountRow.Delete(); } else { string ErrorMsg = String.Format(Catalog.GetString("There is a balance on account {0}"), accountRow.AccountCode); AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Import hierarchy"), ErrorMsg, TResultSeverity.Resv_Critical)); } } } if (AVerificationResult.HasCriticalErrors) { return false; } return SaveGLSetupTDS(ALedgerNumber, ref MainDS, out AVerificationResult) == TSubmitChangesResult.scrOK; }
/// <summary> /// Display File open dialog box and read file into memory /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OpenFile(System.Object sender, EventArgs e) { if (!FPetraUtilsObject.IsEnabled("actStartImport")) { MessageBox.Show(Catalog.GetString("Please cancel the current import before selecting a different file")); return; } txtPartnerInfo.Text = ""; OpenFileDialog DialogOpen = new OpenFileDialog(); DialogOpen.Filter = Catalog.GetString( "All supported formats|*.yml;*.csv;*.ext|Text file (*.yml)|*.yml|Partner Extract (*.ext)|*.ext|Partner List (*.csv)|.csv"); DialogOpen.FilterIndex = 1; DialogOpen.RestoreDirectory = true; DialogOpen.Title = Catalog.GetString("Select the file for importing partners"); if (DialogOpen.ShowDialog() == DialogResult.OK) { txtFilename.Text = DialogOpen.FileName; TVerificationResultCollection VerificationResult = null; AddStatus(String.Format("Reading {0}\r\n", Path.GetFileName(DialogOpen.FileName))); if (Path.GetExtension(DialogOpen.FileName) == ".yml") { TYml2Xml yml = new TYml2Xml(DialogOpen.FileName); AddStatus(Catalog.GetString("Parsing file. Please wait..\r\n")); FMainDS = TRemote.MPartner.ImportExport.WebConnectors.ImportPartnersFromYml(TXMLParser.XmlToString( yml.ParseYML2XML()), out VerificationResult); } if (Path.GetExtension(DialogOpen.FileName) == ".csv") { // select separator, make sure there is a header line with the column captions/names TDlgSelectCSVSeparator dlgSeparator = new TDlgSelectCSVSeparator(true); Boolean fileCanOpen = dlgSeparator.OpenCsvFile(DialogOpen.FileName); if (!fileCanOpen) { MessageBox.Show(Catalog.GetString("Unable to open file."), Catalog.GetString("Import Partners"), MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } if (dlgSeparator.ShowDialog() == DialogResult.OK) { XmlDocument doc = TCsv2Xml.ParseCSV2Xml(DialogOpen.FileName, dlgSeparator.SelectedSeparator); FMainDS = TRemote.MPartner.ImportExport.WebConnectors.ImportFromCSVFile(TXMLParser.XmlToString(doc), out VerificationResult); } } else if (Path.GetExtension(DialogOpen.FileName) == ".ext") { StreamReader sr = new StreamReader(DialogOpen.FileName, true); string[] FileContent = sr.ReadToEnd().Replace("\r", "").Split(new char[] { '\n' }); sr.Close(); AddStatus(String.Format("{0} lines.\r\n", FileContent.Length)); AddStatus(Catalog.GetString("Parsing file. Please wait..\r\n")); FMainDS = TRemote.MPartner.ImportExport.WebConnectors.ImportFromPartnerExtract(FileContent, out VerificationResult); } AddStatus(FormatVerificationResult("Imported file verification: ", VerificationResult)); if (!TVerificationHelper.IsNullOrOnlyNonCritical(VerificationResult)) { string ErrorMessages = String.Empty; foreach (TVerificationResult verif in VerificationResult) { ErrorMessages += "[" + verif.ResultContext + "] " + verif.ResultTextCaption + ": " + verif.ResultText + Environment.NewLine; } MessageBox.Show(ErrorMessages, Catalog.GetString("Import of partners failed!")); FMainDS = null; return; } AddStatus(String.Format(Catalog.GetString("File read OK ({0} partners) - press Start to import.\r\n"), FMainDS.PPartner.Rows.Count)); } }
/// <summary> /// Returns an XML node that defines a number of the properties of each Shepherd. Including size and title. /// </summary> /// <param name="AYamlFile">Full path to the Shepherd's YAML Definition file.</param> /// <returns></returns> protected XmlNode ParseYAMLFileElements(string AYamlFile) { TLogging.Log("ParseYAMLFileElements method starting."); TYml2Xml parser = new TYml2Xml(AYamlFile); XmlDocument XmlPages = parser.ParseYML2XML(); TLogging.Log("ParseYAMLFileElements currently has this many attributes: " + XmlPages.LastChild.LastChild.Attributes.Count); XmlNode FileElementData = XmlPages.DocumentElement; FileElementData = XmlPages.LastChild.LastChild; string ShepherdHeight = ""; string ShepherdWidth = ""; string ShepherdTitle = ""; string TestElement = ""; string FinishPageNote = ""; #region YAML Attributes Input if (FileElementData.Attributes["FinishPageNote"] != null) { FinishPageNote = FileElementData.Attributes["FinishPageNote"].Value; } else { TLogging.Log("DID NOT FIND FINISH PAGE"); } if (FileElementData.Attributes["Testelement"] != null) { TLogging.Log("FOUND TEST ELEMENT"); TLogging.Log("Printing the value of test: " + FileElementData.Attributes["Testelement"].Value); TestElement = FileElementData.Attributes["Testelement"].Value; } else { TLogging.Log("Did not find a test element for this shepherd."); } if (FileElementData.Attributes["Width"] != null) { TLogging.Log("Printing the width of shepherd: " + FileElementData.Attributes["Width"].Value); ShepherdWidth = FileElementData.Attributes["Width"].Value; } else { TLogging.Log("Did not find a width for this shepherd."); } if (FileElementData.Attributes["Height"] != null) { TLogging.Log("Printing the height of shepherd: " + FileElementData.Attributes["Height"].Value); ShepherdHeight = FileElementData.Attributes["Height"].Value; } else { TLogging.Log("Did not find a height for this shepherd."); } if (FileElementData.Attributes["Title"] != null) { TLogging.Log("Printing the title of shepherd: " + FileElementData.Attributes["Title"].Value); ShepherdTitle = FileElementData.Attributes["Title"].Value; } else { TLogging.Log("Did not find a title for this shepherd."); } #endregion try { FForm.UpdateShepherdFormProperties(ShepherdTitle, Convert.ToInt32(ShepherdWidth), Convert.ToInt32(ShepherdHeight)); } catch (FormatException) { TLogging.Log("An element (height or width) cannot be converted to integer. Check the datatype and try again."); } return FileElementData; }
/// <summary> /// </summary> private XmlNode GetHardCodedXmlNodes() { string[] lines = new string[7]; lines[0] = "TaskGroup:\n"; lines[1] = " Task1:\n"; lines[2] = " Label: First Item"; lines[3] = " Task2:\n"; lines[4] = " Label: Second Item"; lines[5] = " Task3:\n"; lines[6] = " Label: Third Item"; TYml2Xml parser = new TYml2Xml(lines); XmlNode xmlnode = parser.ParseYML2TaskListRoot(); return xmlnode; }
/// <summary> /// add using namespaces, defined in the yml file in the interface directory /// </summary> public static string AddNamespacesFromYmlFile(String AOutputPath, string AModuleName) { string result = string.Empty; if (AOutputPath.Contains("ICT/Petra/Plugins")) { // for plugins string pluginWithNamespace = TAppSettingsManager.GetValue("plugin"); result += "using " + pluginWithNamespace + ".Data;" + Environment.NewLine; } if (File.Exists(AOutputPath + Path.DirectorySeparatorChar + "InterfacesUsingNamespaces.yml")) { TYml2Xml reader = new TYml2Xml(AOutputPath + Path.DirectorySeparatorChar + "InterfacesUsingNamespaces.yml"); XmlDocument doc = reader.ParseYML2XML(); XmlNode RootNode = doc.DocumentElement.FirstChild; StringCollection usingNamespaces = TYml2Xml.GetElements(RootNode, AModuleName); foreach (string s in usingNamespaces) { result += "using " + s.Trim() + ";" + Environment.NewLine; } } return result; }
/// <summary> /// this loads the contents of the yaml file. /// it supports inheritance, base elements are overwritten /// </summary> /// <param name="AYamlFilename"></param> /// <param name="ASelectedLocalisation"></param> /// <param name="AAlreadyGotLocalisation"></param> /// <param name="depth">0 is the last file that is derived from all base files</param> /// <returns></returns> protected Boolean LoadRecursively(string AYamlFilename, string ASelectedLocalisation, bool AAlreadyGotLocalisation, Int32 depth) { // check if file exists for localisation string localisedFile = null; if ((ASelectedLocalisation != null) && !AAlreadyGotLocalisation) { localisedFile = Path.GetDirectoryName(AYamlFilename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(AYamlFilename) + "." + ASelectedLocalisation + ".yaml"; // first check if there is such a file if (!File.Exists(localisedFile)) { localisedFile = null; } } if (localisedFile == null) { localisedFile = AYamlFilename; } string baseyaml; if (!TYml2Xml.ReadHeader(localisedFile, out baseyaml)) { throw new Exception("This is not an OpenPetra Yaml file"); } if ((baseyaml.Length > 0) && baseyaml.EndsWith(".yaml")) { LoadRecursively(System.IO.Path.GetDirectoryName(AYamlFilename) + System.IO.Path.DirectorySeparatorChar + baseyaml, ASelectedLocalisation, localisedFile != AYamlFilename, depth - 1); } if ((depth == 0) && (FCodeStorage.FXmlNodes != null)) { // apply the tag, so that we know which things have been changed by the last yml file TYml2Xml.Tag((XmlNode)FCodeStorage.FXmlNodes[TParseYAMLFormsDefinition.ROOTNODEYML]); } XmlDocument newDoc = null; localisedFile = Path.GetFullPath(localisedFile); if (CachedYamlFiles.ContainsKey(localisedFile)) { newDoc = CachedYamlFiles[localisedFile]; } else { Console.WriteLine("Loading " + localisedFile + "..."); TYml2Xml yml2xml = new TYml2Xml(localisedFile); newDoc = yml2xml.ParseYML2XML(); CachedYamlFiles.Add(localisedFile, newDoc); } TYml2Xml.Merge(ref FCodeStorage.FXmlDocument, newDoc, depth); if (TLogging.DebugLevel > 0) { // for debugging: FCodeStorage.FXmlDocument.Save(localisedFile + ".xml"); } FCodeStorage.FXmlNodes = TYml2Xml.ReferenceNodes(FCodeStorage.FXmlDocument); FCodeStorage.FRootNode = (XmlNode)FCodeStorage.FXmlNodes[TParseYAMLFormsDefinition.ROOTNODEYML]; if (baseyaml.Length == 0) { if (FCodeStorage.FXmlNodes[TYml2Xml.ROOTNODEINTERNAL] == null) { throw new Exception("TParseYAMLFormsDefinition.LoadRecursively: YML Document could not be properly parsed"); } if (TXMLParser.GetAttribute((XmlNode)FCodeStorage.FXmlNodes[TParseYAMLFormsDefinition.ROOTNODEYML], "BaseYaml").Length > 0) { throw new Exception("The BaseYaml attribute must come first!"); } } if (depth == 0) { FCodeStorage.FFilename = AYamlFilename; LoadData(FCodeStorage.FXmlNodes); } return true; }
/// <summary> /// build an XML document which includes all ledgers etc. /// </summary> public static XmlNode BuildNavigationXml(bool ADontUseDefaultLedger = false) { TYml2Xml parser = new TYml2Xml(TAppSettingsManager.GetValue("UINavigation.File")); XmlDocument UINavigation = parser.ParseYML2XML(); ALedgerTable AvailableLedgers = new ALedgerTable(); if (UserInfo.GUserInfo.IsInModule(SharedConstants.PETRAMODULE_FINANCE1)) { AvailableLedgers = TRemote.MFinance.Setup.WebConnectors.GetAvailableLedgers(); } XmlNode OpenPetraNode = UINavigation.FirstChild.NextSibling.FirstChild; XmlNode SearchBoxesNode = OpenPetraNode.FirstChild; XmlNode MainMenuNode = SearchBoxesNode.NextSibling; if (TFormsList.GSingletonForms.Count == 0) // There is no need to re-record all Singleton screens if this was already done once { RecordAllSingletonScreens(MainMenuNode); } AddNavigationForEachLedger(MainMenuNode, AvailableLedgers, ADontUseDefaultLedger); if (UserInfo.GUserInfo.IsInModule("PTNRUSER") && UserInfo.GUserInfo.IsInModule("CONFERENCE")) { AddConferenceInformation(MainMenuNode); } return MainMenuNode; }
/// import motivation groups, details into an empty new ledger private static void ImportDefaultMotivations(ref GLSetupTDS AMainDS, Int32 ALedgerNumber) { XmlDocument doc; TYml2Xml ymlFile; string Filename = TAppSettingsManager.GetValue("SqlFiles.Path", ".") + Path.DirectorySeparatorChar + "DefaultMotivations.yml"; try { ymlFile = new TYml2Xml(Filename); doc = ymlFile.ParseYML2XML(); } catch (XmlException exp) { throw new Exception( Catalog.GetString("There was a problem with the syntax of the file.") + Environment.NewLine + exp.Message + Environment.NewLine + Filename); } XmlNode root = doc.FirstChild.NextSibling; foreach (XmlNode child in root) { CreateMotivationGroup(ref AMainDS, ALedgerNumber, child); } }
/// <summary> /// add using namespaces, defined in the yml file in the interface directory /// </summary> public static string AddNamespacesFromYmlFile(String AOutputPath, string AModuleName) { TYml2Xml reader = new TYml2Xml(AOutputPath + Path.DirectorySeparatorChar + "InterfacesUsingNamespaces.yml"); XmlDocument doc = reader.ParseYML2XML(); XmlNode RootNode = doc.DocumentElement.FirstChild; StringCollection usingNamespaces = TYml2Xml.GetElements(RootNode, AModuleName); string result = string.Empty; foreach (string s in usingNamespaces) { result += "using " + s.Trim() + ";" + Environment.NewLine; } return result; }
private static void ImportDefaultCostCentreHierarchy(ref GLSetupTDS AMainDS, Int32 ALedgerNumber, string ALedgerName) { if (ALedgerName.Length == 0) { throw new Exception("We need a name for the ledger, otherwise the yml will be invalid"); } // load XmlCostCentreHierarchy from a default file string Filename = TAppSettingsManager.GetValue("SqlFiles.Path", ".") + Path.DirectorySeparatorChar + "DefaultCostCentreHierarchy.yml"; TextReader reader = new StreamReader(Filename, TTextFile.GetFileEncoding(Filename), false); string XmlCostCentreHierarchy = reader.ReadToEnd(); reader.Close(); XmlCostCentreHierarchy = XmlCostCentreHierarchy.Replace("{#LEDGERNUMBER}", ALedgerNumber.ToString()); XmlCostCentreHierarchy = XmlCostCentreHierarchy.Replace("{#LEDGERNUMBERWITHLEADINGZEROS}", ALedgerNumber.ToString("00")); XmlCostCentreHierarchy = XmlCostCentreHierarchy.Replace("{#LEDGERNAME}", ALedgerName); string[] lines = XmlCostCentreHierarchy.Replace("\r", "").Split(new char[] { '\n' }); TYml2Xml ymlFile = new TYml2Xml(lines); XmlDocument doc = ymlFile.ParseYML2XML(); XmlNode root = doc.FirstChild.NextSibling.FirstChild; StringCollection ImportedCostCentreNames = new StringCollection(); CreateCostCentresRecursively(ref AMainDS, ALedgerNumber, ref ImportedCostCentreNames, root, null); }
/// creates a file with enums in Shared and one file per submodule in Server for cached tables public static void WriteCachedTables(TDataDefinitionStore AStore, string ACacheYamlFilename, string ASharedPath, string ATemplateDir) { // Load yaml file with list of tables that should be cached TYml2Xml ymlParser = new TYml2Xml(ACacheYamlFilename); XmlDocument xmlDoc = ymlParser.ParseYML2XML(); XmlNode module = xmlDoc.DocumentElement.FirstChild.FirstChild; while (module != null) { XmlNode subModule = module.FirstChild; bool severalSubModules = (subModule != null && subModule.NextSibling != null); // write the shared file with the enum definitions ProcessTemplate SharedTemplate = new ProcessTemplate(ATemplateDir + Path.DirectorySeparatorChar + "ORM" + Path.DirectorySeparatorChar + "Cacheable.Shared.cs"); SharedTemplate.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(ATemplateDir)); // SharedTemplate.SetCodelet("NAMESPACE", "Ict.Petra.Shared.M" + module.Name); SharedTemplate.SetCodelet("NAMESPACE", "Ict.Petra.Shared"); while (subModule != null) { List <string>UsingNamespaces = new List <string>(); // write the server file for each submodule ProcessTemplate ServerTemplate = new ProcessTemplate(ATemplateDir + Path.DirectorySeparatorChar + "ORM" + Path.DirectorySeparatorChar + "Cacheable.Server.cs"); ServerTemplate.SetCodelet("GPLFILEHEADER", ProcessTemplate.LoadEmptyFileComment(ATemplateDir)); ServerTemplate.SetCodelet("NAMESPACE", "Ict.Petra.Server.M" + module.Name + "." + subModule.Name + ".Cacheable"); ServerTemplate.SetCodelet("SUBNAMESPACE", "M" + module.Name + "." + subModule.Name); ServerTemplate.SetCodelet("CACHEABLECLASS", "T" + module.Name + "Cacheable"); ServerTemplate.SetCodelet("SUBMODULE", subModule.Name); ServerTemplate.SetCodelet("GETCALCULATEDLISTFROMDB", ""); ServerTemplate.SetCodelet("LEDGERGETCACHEABLE", ""); ServerTemplate.SetCodelet("LEDGERSAVECACHEABLE", ""); if (!severalSubModules) { // for MCommon ServerTemplate.SetCodelet("NAMESPACE", "Ict.Petra.Server.M" + module.Name + ".Cacheable"); ServerTemplate.SetCodelet("SUBNAMESPACE", "M" + module.Name); ServerTemplate.SetCodelet("CACHEABLECLASS", "TCacheable"); } ProcessTemplate snippetSubmodule = SharedTemplate.GetSnippet("SUBMODULEENUM"); snippetSubmodule.SetCodelet("SUBMODULE", subModule.Name); snippetSubmodule.SetCodelet("MODULE", module.Name); ProcessTemplate snippetLedgerGetTable = null; ProcessTemplate snippetLedgerSaveTable = null; XmlNode TableOrListElement = subModule.FirstChild; while (TableOrListElement != null) { XmlNode enumElement = TableOrListElement.FirstChild; while (enumElement != null) { bool DependsOnLedger = false; if (TYml2Xml.GetAttributeRecursive(enumElement, "DependsOnLedger") == "true") { if (snippetLedgerGetTable == null) { snippetLedgerGetTable = ServerTemplate.GetSnippet("LEDGERGETCACHEABLE"); snippetLedgerGetTable.SetCodelet("SUBMODULE", subModule.Name); } if ((snippetLedgerSaveTable == null) && (TableOrListElement.Name == "DatabaseTables")) { snippetLedgerSaveTable = ServerTemplate.GetSnippet("LEDGERSAVECACHEABLE"); snippetLedgerSaveTable.SetCodelet("SUBMODULE", subModule.Name); } DependsOnLedger = true; ServerTemplate.SetCodelet("WITHLEDGER", "true"); } ProcessTemplate snippetElement = SharedTemplate.GetSnippet("ENUMELEMENT"); if ((enumElement.NextSibling == null) && ((TableOrListElement.NextSibling == null) || (TableOrListElement.NextSibling.FirstChild == null))) { snippetElement = SharedTemplate.GetSnippet("ENUMELEMENTLAST"); } string Comment = TXMLParser.GetAttribute(enumElement, "Comment"); if (TableOrListElement.Name == "DatabaseTables") { TTable Table = AStore.GetTable(enumElement.Name); string Namespace = "Ict.Petra.Shared." + TTable.GetNamespace(Table.strGroup) + ".Data"; if (!UsingNamespaces.Contains(Namespace)) { UsingNamespaces.Add(Namespace); } Namespace = "Ict.Petra.Shared." + TTable.GetNamespace(Table.strGroup) + ".Validation"; if (!UsingNamespaces.Contains(Namespace)) { UsingNamespaces.Add(Namespace); } Namespace = "Ict.Petra.Server." + TTable.GetNamespace(Table.strGroup) + ".Data.Access"; if (!UsingNamespaces.Contains(Namespace)) { UsingNamespaces.Add(Namespace); } if (Table == null) { throw new Exception("Error: cannot find table " + enumElement.Name + " for caching in module " + module.Name); } if (Comment.Length == 0) { Comment = Table.strDescription; } } if (Comment.Length == 0) { Comment = "todoComment"; } snippetElement.SetCodelet("ENUMCOMMENT", Comment); string enumName = enumElement.Name; if (TXMLParser.HasAttribute(enumElement, "Enum")) { enumName = TXMLParser.GetAttribute(enumElement, "Enum"); } else if (TableOrListElement.Name == "DatabaseTables") { string character2 = enumElement.Name.Substring(1, 1); if (character2.ToLower() == character2) { // this is a table name that has a 2 digit prefix enumName = enumElement.Name.Substring(2) + "List"; } else { enumName = enumElement.Name.Substring(1) + "List"; } } snippetElement.SetCodelet("ENUMNAME", enumName); snippetElement.SetCodelet("DATATABLENAME", enumElement.Name); snippetSubmodule.InsertSnippet("ENUMELEMENTS", snippetElement); if (TableOrListElement.Name == "DatabaseTables") { ProcessTemplate snippetLoadTable = ServerTemplate.GetSnippet("LOADTABLE"); if (DependsOnLedger) { snippetLoadTable = ServerTemplate.GetSnippet("LOADTABLEVIALEDGER"); } snippetLoadTable.SetCodelet("ENUMNAME", enumName); snippetLoadTable.SetCodelet("DATATABLENAME", enumElement.Name); if (DependsOnLedger) { snippetLedgerGetTable.InsertSnippet("LOADTABLESANDLISTS", snippetLoadTable); } else { ServerTemplate.InsertSnippet("LOADTABLESANDLISTS", snippetLoadTable); } ProcessTemplate snippetSaveTable = ServerTemplate.GetSnippet("SAVETABLE"); snippetSaveTable.SetCodelet("ENUMNAME", enumName); snippetSaveTable.SetCodelet("SUBMODULE", subModule.Name); snippetSaveTable.SetCodelet("DATATABLENAME", enumElement.Name); if (DependsOnLedger) { snippetLedgerSaveTable.InsertSnippet("SAVETABLE", snippetSaveTable); } else { ServerTemplate.InsertSnippet("SAVETABLE", snippetSaveTable); } ProcessTemplate snippetDataValidation = ServerTemplate.GetSnippet("DATAVALIDATION"); snippetDataValidation.SetCodelet("ENUMNAME", enumName); snippetDataValidation.SetCodelet("DATATABLENAME", enumElement.Name); if (DependsOnLedger) { snippetLedgerSaveTable.InsertSnippet("DATAVALIDATION", snippetDataValidation); } else { ServerTemplate.InsertSnippet("DATAVALIDATION", snippetDataValidation); } } else { ProcessTemplate snippetLoadList = ServerTemplate.GetSnippet("LOADCALCULATEDLIST"); if (DependsOnLedger) { snippetLoadList = ServerTemplate.GetSnippet("LOADCALCULATEDLISTFORLEDGER"); } snippetLoadList.SetCodelet("ENUMNAME", enumName); snippetLoadList.SetCodelet("CALCULATEDLISTNAME", enumName); if (DependsOnLedger) { snippetLedgerGetTable.InsertSnippet("LOADTABLESANDLISTS", snippetLoadList); } else { ServerTemplate.InsertSnippet("LOADTABLESANDLISTS", snippetLoadList); } if (TYml2Xml.GetAttributeRecursive(enumElement, "IsStorableToDBTable") != String.Empty) { ProcessTemplate snippetSaveTable = ServerTemplate.GetSnippet("SAVETABLE"); snippetSaveTable.SetCodelet("ENUMNAME", enumName); snippetSaveTable.SetCodelet("SUBMODULE", subModule.Name); snippetSaveTable.SetCodelet("DATATABLENAME", TYml2Xml.GetAttributeRecursive(enumElement, "IsStorableToDBTable")); if (DependsOnLedger) { snippetLedgerSaveTable.InsertSnippet("SAVETABLE", snippetSaveTable); } else { ServerTemplate.InsertSnippet("SAVETABLE", snippetSaveTable); } ProcessTemplate snippetDataValidation = ServerTemplate.GetSnippet("DATAVALIDATION"); snippetDataValidation.SetCodelet("ENUMNAME", enumName); snippetDataValidation.SetCodelet("DATATABLENAME", TYml2Xml.GetAttributeRecursive(enumElement, "IsStorableToDBTable")); if (DependsOnLedger) { snippetLedgerSaveTable.InsertSnippet("DATAVALIDATION", snippetDataValidation); } else { ServerTemplate.InsertSnippet("DATAVALIDATION", snippetDataValidation); } } } enumElement = enumElement.NextSibling; if (enumElement != null) { snippetSubmodule.AddToCodelet("ENUMELEMENTS", Environment.NewLine); } } TableOrListElement = TableOrListElement.NextSibling; } SharedTemplate.InsertSnippet("ENUMS", snippetSubmodule); if (snippetLedgerGetTable != null) { ServerTemplate.InsertSnippet("LEDGERGETCACHEABLE", snippetLedgerGetTable); } if (snippetLedgerSaveTable != null) { ServerTemplate.InsertSnippet("LEDGERSAVECACHEABLE", snippetLedgerSaveTable); } ServerTemplate.SetCodelet("USINGNAMESPACES", string.Empty); foreach (string UsingNamespace in UsingNamespaces) { ServerTemplate.AddToCodelet("USINGNAMESPACES", "using " + UsingNamespace + ";" + Environment.NewLine); } string path = ASharedPath + Path.DirectorySeparatorChar + ".." + Path.DirectorySeparatorChar + "Server" + Path.DirectorySeparatorChar + "lib" + Path.DirectorySeparatorChar + "M" + module.Name + Path.DirectorySeparatorChar; if (File.Exists(path + "Cacheable.ManualCode.cs")) { path += "Cacheable-generated.cs"; } else { if (File.Exists(path + "data" + Path.DirectorySeparatorChar + subModule.Name + "." + "Cacheable.ManualCode.cs")) { path += "data" + Path.DirectorySeparatorChar + subModule.Name + "." + "Cacheable-generated.cs"; } else if (File.Exists(path + "data" + Path.DirectorySeparatorChar + "Cacheable.ManualCode.cs")) { path += "data" + Path.DirectorySeparatorChar + "Cacheable-generated.cs"; } else { path += subModule.Name + "." + "Cacheable-generated.cs"; } } ServerTemplate.FinishWriting(path, ".cs", true); subModule = subModule.NextSibling; } SharedTemplate.FinishWriting(ASharedPath + Path.DirectorySeparatorChar + "M" + module.Name + ".Cacheable-generated.cs", ".cs", true); module = module.NextSibling; } }
/// import a new Account hierarchy into an empty new ledger private static void ImportDefaultAccountHierarchy(ref GLSetupTDS AMainDS, Int32 ALedgerNumber, ref TVerificationResultCollection AVerificationResult) { XmlDocument doc; TYml2Xml ymlFile; string Filename = TAppSettingsManager.GetValue("SqlFiles.Path", ".") + Path.DirectorySeparatorChar + "DefaultAccountHierarchy.yml"; try { ymlFile = new TYml2Xml(Filename); doc = ymlFile.ParseYML2XML(); } catch (XmlException exp) { throw new Exception( Catalog.GetString("There was a problem with the syntax of the file.") + Environment.NewLine + exp.Message + Environment.NewLine + Filename); } // create the root account AAccountHierarchyRow accountHierarchyRow = AMainDS.AAccountHierarchy.NewRowTyped(); accountHierarchyRow.LedgerNumber = ALedgerNumber; accountHierarchyRow.AccountHierarchyCode = "STANDARD"; accountHierarchyRow.RootAccountCode = ALedgerNumber.ToString(); AMainDS.AAccountHierarchy.Rows.Add(accountHierarchyRow); AAccountRow accountRow = AMainDS.AAccount.NewRowTyped(); accountRow.LedgerNumber = ALedgerNumber; accountRow.AccountCode = ALedgerNumber.ToString(); accountRow.PostingStatus = false; AMainDS.AAccount.Rows.Add(accountRow); XmlNode root = doc.FirstChild.NextSibling.FirstChild; StringCollection ImportedAccountNames = new StringCollection(); CreateAccountHierarchyRecursively(ref AMainDS, ALedgerNumber, ref ImportedAccountNames, root, ALedgerNumber.ToString(), ref AVerificationResult); }
/// <summary> /// build an XML document which includes all ledgers etc. /// </summary> public static XmlNode BuildNavigationXml(bool ADontUseDefaultLedger = false) { TYml2Xml parser = new TYml2Xml(TAppSettingsManager.GetValue("UINavigation.File")); XmlDocument UINavigation = parser.ParseYML2XML(); ALedgerTable AvailableLedgers = new ALedgerTable(); if (UserInfo.GUserInfo.IsInModule(SharedConstants.PETRAMODULE_FINANCE1)) { AvailableLedgers = TGLSetupWebConnector.GetAvailableLedgers(); } XmlNode OpenPetraNode = UINavigation.FirstChild.NextSibling.FirstChild; XmlNode SearchBoxesNode = OpenPetraNode.FirstChild; XmlNode MainMenuNode = SearchBoxesNode.NextSibling; AddNavigationForEachLedger(MainMenuNode, AvailableLedgers, ADontUseDefaultLedger); return MainMenuNode; }
/// <summary> /// Constructor for TPetraShepherdPagesList. This function reads in a yaml file from the appropriate /// namespace, parses it into xmlNodes, and adds them to the list of pages so that they can be read /// by the individual ShepherdPage constructor, which it calls. /// </summary> /// <param name="AYamlFile">Full path to the Shepherd's YAML Definition file.</param> public TPetraShepherdPagesList(string AYamlFile) { TLogging.Log("Entering TPetraShepherdPagesList Constructor. AYamlFile = " + AYamlFile + "..."); TYml2Xml parser = new TYml2Xml(AYamlFile); XmlDocument XmlPages = parser.ParseYML2XML(); TLogging.Log("TPetraShepherdPagesList currently has this many nodes: " + XmlPages.LastChild.LastChild.LastChild.ChildNodes.Count); XmlNode temporaryXmlNode = XmlPages.LastChild.LastChild.LastChild.FirstChild; //...LastChild.LastChild.LastChild.FirstChild is required because of the structure of the XML File after parsing. int counter = 0; XmlNodeList nodeList; XmlNode root = XmlPages.DocumentElement; nodeList = XmlPages.LastChild.LastChild.LastChild.ChildNodes; TLogging.Log("The amount of nodes in the nodeList in the TPetraShepherdPagesList constructor is as follows: " + nodeList.Count); foreach (XmlNode node in nodeList) { if (node.Name.Contains("SubShepherd.")) { TLogging.Log("TPetraSHepherdPagesList Constructor loop: Found a sub shepherd.. Skipping.. "); } else { TPetraShepherdPage temporaryPetraShepherdPage = new TPetraShepherdPage(node); // Constructor call for each page built off an XML node. TLogging.Log("TPetraShepherdPagesList Constructor loop: THE TITLE OF THE CURRENT PAGE IS: " + temporaryPetraShepherdPage.Title); FPagesList.Add(temporaryPetraShepherdPage.ID, temporaryPetraShepherdPage); } counter++; } TPetraShepherdFinishPage shepherdFinishPage = new TPetraShepherdFinishPage(XmlPages); TLogging.Log("Adding a shepherd finish page: " + shepherdFinishPage.ID); FPagesList.Add(shepherdFinishPage.ID, shepherdFinishPage); //// //Temporary Statement to add a subshepherd finish page in addition to the Finish page above //// TPetraShepherdFinishPage shepherdSubFinishPage = new TPetraShepherdFinishPage(XmlPages, "SubShepherd"); //// TLogging.Log("Adding a shepherd sub-finish page: " + shepherdSubFinishPage.ID); //// FPagesList.Add(shepherdSubFinishPage.ID, shepherdSubFinishPage); TLogging.Log("TPetraShepherdPagesList Constructor ran successfully."); }
public void TestYMLBackSlashValue() { string filename = PathToTestData + "testBackslash.yml"; string backslashValue = "data\\Kontoauszuege\\test.csv"; TYml2Xml converterYml = new TYml2Xml(filename); XmlDocument docFromYML = converterYml.ParseYML2XML(); XmlNode node = TXMLParser.FindNodeRecursive(docFromYML.DocumentElement, "testname"); Assert.AreEqual(backslashValue, TXMLParser.GetAttribute(node, "Filename")); // does writing of the backslash value work as well? TXMLParser.SetAttribute(node, "Filename", backslashValue); TYml2Xml.Xml2Yml(docFromYML, filename + ".new"); Assert.AreEqual(true, TTextFile.SameContent(filename, filename + ".new"), "the files should be the same: " + filename); System.IO.File.Delete(filename + ".new"); }
public void TestYMLParser() { CreateTestDoc(); // load from yml, is it the same xml code? string filename = PathToTestData + "test.yml"; TYml2Xml converterYml = new TYml2Xml(filename); XmlDocument docFromYML = converterYml.ParseYML2XML(); filename = PathToTestData + "testWithInheritedAttributes.xml"; StreamWriter sw = new StreamWriter(filename + ".new"); sw.Write(TXMLParser.XmlToString2(docFromYML)); sw.Close(); Assert.AreEqual(true, TTextFile.SameContent(filename, filename + ".new"), "after importing from yml: the files should be the same: " + filename); System.IO.File.Delete(filename + ".new"); }
/// <summary> /// Import a batch from a spreadsheet /// </summary> /// <param name="ACSVDataFileName"></param> /// <param name="ALatestTransactionDate"></param> /// <returns></returns> public bool ImportFromSpreadsheet(out string ACSVDataFileName, out DateTime ALatestTransactionDate) { ALatestTransactionDate = DateTime.MinValue; ACSVDataFileName = String.Empty; OpenFileDialog dialog = new OpenFileDialog(); dialog.Title = Catalog.GetString("Import transactions from spreadsheet file"); dialog.Filter = Catalog.GetString("Spreadsheet files (*.csv)|*.csv"); if (dialog.ShowDialog() == DialogResult.OK) { string directory = Path.GetDirectoryName(dialog.FileName); string[] ymlFiles = Directory.GetFiles(directory, "*.yml"); string definitionFileName = String.Empty; if (ymlFiles.Length == 1) { definitionFileName = ymlFiles[0]; } else { // show another open file dialog for the description file OpenFileDialog dialogDefinitionFile = new OpenFileDialog(); dialogDefinitionFile.Title = Catalog.GetString("Please select a yml file that describes the content of the spreadsheet"); dialogDefinitionFile.Filter = Catalog.GetString("Data description files (*.yml)|*.yml"); if (dialogDefinitionFile.ShowDialog() == DialogResult.OK) { definitionFileName = dialogDefinitionFile.FileName; } } if (File.Exists(definitionFileName)) { TYml2Xml parser = new TYml2Xml(definitionFileName); XmlDocument dataDescription = parser.ParseYML2XML(); XmlNode RootNode = TXMLParser.FindNodeRecursive(dataDescription.DocumentElement, "RootNode"); Int32 FirstTransactionRow = TXMLParser.GetIntAttribute(RootNode, "FirstTransactionRow"); string DefaultCostCentre = TXMLParser.GetAttribute(RootNode, "CostCentre"); FMyUserControl.CreateNewABatch(); GLBatchTDSAJournalRow NewJournal = FMainDS.AJournal.NewRowTyped(true); FMyForm.GetJournalsControl().NewRowManual(ref NewJournal); FMainDS.AJournal.Rows.Add(NewJournal); NewJournal.TransactionCurrency = TXMLParser.GetAttribute(RootNode, "Currency"); if (Path.GetExtension(dialog.FileName).ToLower() == ".csv") { ACSVDataFileName = dialog.FileName; CreateBatchFromCSVFile(dialog.FileName, RootNode, NewJournal, FirstTransactionRow, DefaultCostCentre, out ALatestTransactionDate); return true; } } } return false; }
/// <summary> /// build an XML document which includes all ledgers etc. /// </summary> public static XmlNode BuildNavigationXml(bool ADontUseDefaultLedger = false) { TYml2Xml parser = new TYml2Xml(TAppSettingsManager.GetValue("UINavigation.File")); XmlDocument UINavigation = parser.ParseYML2XML(); // look for plugin UINavigation files, for development mode in the OpenPetra source code working tree string PluginsPath = "../../csharp/ICT/Petra/Plugins"; if (!Directory.Exists(PluginsPath)) { // in Production, we can have extension yml UINavigation files for the plugins too PluginsPath = "Plugins"; } if (Directory.Exists(PluginsPath)) { MergePluginUINavigation(PluginsPath, ref UINavigation); } ALedgerTable AvailableLedgers = new ALedgerTable(); if (UserInfo.GUserInfo.IsInModule(SharedConstants.PETRAMODULE_FINANCE1)) { AvailableLedgers = TRemote.MFinance.Setup.WebConnectors.GetAvailableLedgers(); } XmlNode OpenPetraNode = UINavigation.FirstChild.NextSibling.FirstChild; XmlNode SearchBoxesNode = OpenPetraNode.FirstChild; XmlNode MainMenuNode = SearchBoxesNode.NextSibling; if (TFormsList.GSingletonForms.Count == 0) // There is no need to re-record all Singleton screens if this was already done once { RecordAllSingletonScreens(MainMenuNode); } AddNavigationForEachLedger(MainMenuNode, AvailableLedgers, ADontUseDefaultLedger); if (UserInfo.GUserInfo.IsInModule("PTNRUSER") && UserInfo.GUserInfo.IsInModule("CONFERENCE")) { AddConferenceInformation(MainMenuNode); } return MainMenuNode; }
void Button2Click(object sender, EventArgs e) { String yamlFile = txtYaml.Text.ToString(); TYml2Xml parser = new TYml2Xml(yamlFile); XmlDocument UINavigation = parser.ParseYML2XML(); TVisualStylesEnum EnumStyle = Helper.GetVisualStylesEnumFromString(cmbVisualStyle.Text.ToString()); new MainForm2(UINavigation.FirstChild.NextSibling.FirstChild, EnumStyle).Show(); }