public static string Build(string xmlpath, string xslpath, IPrincipal user, bool isFlyout, string userInfo) { var xslargs = new XsltArgumentList(); xslargs.AddParam("isFlyout", "", isFlyout); xslargs.AddParam("userInfo", "", userInfo); XElement xml = XElement.Load(xmlpath); xml.Descendants().ToList().ForEach((xe) => { if (xe.Attributes().Any(xe_ => xe_.Name == "roles")) { var roles = xe.Attributes().First(a_ => a_.Name == "roles").Value; if (roles != "*" && (user == null || !user.IsInRole(roles))) { xe.Remove(); } } }); var xsl = new XmlDocument(); xsl.Load(xslpath); var xslt = new XmlTransformer(xml.ToString(SaveOptions.DisableFormatting), xsl.OuterXml); return(xslt.Transform(xslargs)); }
private static void SaveNaesbRequestForConfirmationFile(NaesbRequestForConfirmation nrfc, string ediFileName) { //serialize with out the namespace because GENTRAN can't handle it XmlDocument xmlFile = XmlTransformer.XmlSerialize(nrfc, true); xmlFile.Save(Properties.Settings.Default.NaesbOutboundUnc + ediFileName); }
//public int Invoke(DateTime processStart, DateTime gasDay, string cycle, string fileName, NaesbQuickResponse nqr) //{ ////serialize Naesb NaesbRequestForConfirmation //XmlDocument naesbXml = XmlTransformer.XmlSerialize(nqr, true); ////create naesb event process //int eventProcessId = _naesbEventProcessCreateService.Invoke( // new NaesbEventProcess // { // Type = "QR", // GasDay = gasDay, // Cycle = cycle, // Pipeline = _naesbPipelineGetService.Invoke(nqr.PartyIndentificaton.ConfirmingPartyDuns).Pipeline, // Utility = _naesbUtilityGetService.Invoke(nqr.PartyIndentificaton.UtilityDunsNumber).Utility, // ProcessStart = processStart, // EdiFileName = fileName, // EdiData = naesbXml.InnerXml, // DomainData = null, // UserId = _settings.UserId // } //); ////TODO: maybe make this use its own class instead of generic -> NaesbEventProcessCompletion ////update ProcessEnd timestamp //_naesbEventProcessUpdateService.Invoke(eventProcessId, new KeyValuePair<string, DateTime>("ProcessEnd", DateTime.Now)); //return eventProcessId; //} public int Invoke(DateTime processStart, string fileName, Domain.ConfirmationResponse.ConfirmationResponse cr) { //transform ConfirmationResponse NaesbQuickResponse nqr = _naesbQuickResponseGetService.Invoke(cr); //serialize Naesb NaesbRequestForConfirmation XmlDocument naesbXml = XmlTransformer.XmlSerialize(nqr, true); //create naesb event process int eventProcessId = _naesbEventProcessCreateService.Invoke( new NaesbEventProcess { Type = "QR", GasDay = cr.GasDay, Cycle = cr.Cycle, Pipeline = cr.PartyIndentificaton.PipelineEntity, Utility = cr.PartyIndentificaton.UtilityEntity, ProcessStart = processStart, EdiFileName = fileName, EdiData = naesbXml.InnerXml, DomainData = null, // there is no business QuickResponse UserId = _settings.UserId } ); //TODO: maybe make this use its own class instead of generic -> NaesbEventProcessCompletion //update ProcessEnd timestamp _naesbEventProcessUpdateService.Invoke(eventProcessId, new KeyValuePair <string, DateTime>("ProcessEnd", DateTime.Now)); return(eventProcessId); }
public void ForXmlFile_should_throw_exception_if_no_paths_specified() { AssertExceptionThrown .OfType <ArgumentNullException>() .WithMessage("Value cannot be null.\r\nParameter name: possiblePaths") .WhenExecuting(() => XmlTransformer.ForXmlFile()); }
public XmlTransformerTests() { _transformer = new XmlTransformer(new Dictionary <XName, Action <XElement, XElement> > { { "x", (parent, element) => parent.AddFirst(element) } }); }
private static void SaveNaesbQuickResponseFile(NaesbQuickResponse qr, string fileName) { //serialize with out the namespace because GENTRAN can't handle it XmlDocument xmlFile = XmlTransformer.XmlSerialize(qr, true); xmlFile.Save(Properties.Settings.Default.NaesbOutboundUnc + fileName); }
public void ResolveRelativePath_should_return_expected_values() { ForTest.Scenarios ( new { Base = @"C:\SourceCode\sparky-test-helpers\.vs\SparkyTestHelpers\lut\0\t\SparkyTestHelpers.Xml.UnitTests\bin\Debug", Relative = "../../../../../../../../app.transform1.config", Expected = @"C:\SourceCode\sparky-test-helpers\app.transform1.config" }, new { Base = @"c:\folder\subfolder", Relative = @"something\web.config", Expected = @"c:\folder\subfolder\something\web.config" }, new { Base = @"c:\folder\subfolder", Relative = @"/something/web.config", Expected = @"c:\something\web.config" }, // Can use either forward or backward slashes: new { Base = @"c:\folder\subfolder", Relative = @"../../something/web.config", Expected = @"c:\something\web.config" }, new { Base = @"c:\folder\subfolder", Relative = @"..\..\something\web.config", Expected = @"c:\something\web.config" }, new { Base = @"c:\folder\subfolder", Relative = @"../something\web.config", Expected = @"c:\folder\something\web.config" }, new { Base = @"c:\folder\subfolder", Relative = @"..\something\web.config", Expected = @"c:\folder\something\web.config" }, // Full path ignores base: new { Base = @"c:\folder\subfolder", Relative = @"c:\different\subDifferent\web.config", Expected = @"c:\different\subDifferent\web.config" } ) .TestEach(scenario => Assert.AreEqual( scenario.Expected.ToLowerInvariant(), XmlTransformer.ResolveRelativePath(scenario.Base, scenario.Relative).ToLowerInvariant())); }
public DocumentFormatter(TextWriter textWriter, ICRefResolver crefResolver, string xsltAssetName, bool leaveOpen) { this.leaveOpen = leaveOpen; this.textWriter = textWriter ?? throw new ArgumentNullException(nameof(textWriter)); this.crefResolver = crefResolver ?? throw new ArgumentNullException(nameof(crefResolver)); this.xmlTransformer = XmlTransformer.Create(xsltAssetName, crefResolver); }
public void When_transforming_xml_to_html_output_is_generated() { XElement element = new XElement("ApiCheckResult"); MemoryStream sut = new MemoryStream(); Assert.DoesNotThrow(() => XmlTransformer.TransformToHtml(element.CreateReader(), sut)); Assert.Greater(sut.Length, 0); }
public void RemoveXmlNamespaces_should_remove_namespaces() { Assert.AreEqual( "<assemblyBinding><assemblyBinding>", XmlTransformer.RemoveXmlNamespaces( "<assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">" + "<assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">")); }
public void TransformedByFile_should_return_XmlTransformer_when_one_or_more_paths_specified() { ForTest.Scenarios ( new[] { "path1" }, new[] { "path1", "path2" } ) .TestEach(scenario => AssertExceptionNotThrown.WhenExecuting(() => { var transformer = XmlTransformer.ForXmlFile(scenario); Assert.AreSame(transformer, transformer.TransformedByFile(scenario)); })); }
public void Transform_should_work_with_no_transform_files() { TransformResults results = XmlTransformer .ForXmlFile("SparkyTestHelpers.Xml.UnitTests.dll.config") .Transform(); Console.WriteLine(results.Log); Assert.IsTrue(results.Successful); Assert.IsNull(results.ErrorMessage); StringAssert.Contains(results.TransformedXml, "Original Value1"); Assert.IsInstanceOfType(results.XDocument, typeof(XDocument)); }
internal XmlTransformerTest(string transformStreamContent) { _stream = new MemoryStream(Encoding.UTF8.GetBytes(transformStreamContent)); TransformStreamContent = transformStreamContent; StreamTaskFactory = () => Task.FromResult <Stream>(_stream); Transformer = new XmlTransformer(new Dictionary <XName, Action <XElement, XElement> > { { "x", (parent, element) => parent.AddFirst(element) } }); ProjectSystem = new Mock <IMSBuildProjectSystem>(MockBehavior.Strict); TestDirectory = TestDirectory.Create(); TargetFile = new FileInfo(Path.Combine(TestDirectory.Path, "target.file")); }
public void Transform_should_work_with_single_level_transformation() { TransformResults results = XmlTransformer .ForXmlFile("SparkyTestHelpers.Xml.UnitTests.dll.config") .TransformedByFile(RelativePaths("app.transform1.config")) .Transform(); Console.WriteLine(results.Log); Assert.IsTrue(results.Successful); Assert.IsNull(results.ErrorMessage); StringAssert.Contains(results.TransformedXml, "Value1 updated by transform1"); StringAssert.Contains(results.TransformedXml, "transform1 applied"); Assert.IsInstanceOfType(results.XDocument, typeof(XDocument)); }
public void Transform_should_cache_TransformResults() { var transformer = XmlTransformer.ForXmlFile("base.config") .TransformedByFile("transform1.config", "transform2.config"); TransformResults results1 = transformer.Transform(); Assert.IsFalse(transformer.GotTransformResultsFromCache); TransformResults results2 = transformer.Transform(); Assert.AreSame(results1, results2); Assert.IsTrue(transformer.GotTransformResultsFromCache); }
public int Invoke(DateTime processStart, string fileName, Domain.RequestForConfirmation.RequestForConfirmation obj) { //map domain rfc model to the Naesb rfc model. NaesbRequestForConfirmation nrfc = _naesbRequestForConfirmationGetService.Invoke(obj); //serialize to xml XmlDocument domainXml = XmlTransformer.XmlSerialize(obj, true); //serialize Naesb NaesbRequestForConfirmation XmlDocument naesbXml = XmlTransformer.XmlSerialize(nrfc, true); //create naesb event process int eventProcessId = _naesbEventProcessCreateService.Invoke( new NaesbEventProcess { Type = "RFC", GasDay = obj.GasDay, Cycle = obj.Cycle, Pipeline = obj.PartyIndentificaton.PipelineEntity, Utility = obj.PartyIndentificaton.UtilityEntity, ProcessStart = processStart, EdiFileName = fileName, EdiData = naesbXml.InnerXml, DomainData = domainXml.InnerXml, UserId = _settings.UserId } ); //get the naesb event var naesbEvent = _naesbEventGetService.Invoke("RFC", obj.PartyIndentificaton.PipelineEntity, obj.PartyIndentificaton.UtilityEntity, obj.Cycle); if (naesbEvent != null && naesbEvent.On == true) //if null then the pipeline/utility/cycle doesn't exist in Pegasys { //save the domain rfc to the repository _requestForConfirmationEventCreateService.Invoke(obj); //TODO: maybe make this use its own class instead of generic -> NaesbEventProcessCompletion //update ProcessEnd timestamp _naesbEventProcessUpdateService.Invoke(eventProcessId, new KeyValuePair <string, DateTime>("ProcessEnd", DateTime.Now)); return(eventProcessId); } throw new NaesbError { ReasonCode = "101", Value = "Pipeline/Utility/Cycle naesb event not found." }; }
public void Transform_XElement_into_XMlTester_should_work() { TransformResults results = XmlTransformer .ForXmlFile("SparkyTestHelpers.Xml.UnitTests.dll.config") .TransformedByFile(RelativePaths("app.transform1.config")) .Transform(); Assert.IsTrue(results.Successful); XmlTester xmlTester = new XmlTester(results.XDocument); Assert.IsInstanceOfType(xmlTester, typeof(XmlTester)); xmlTester.AssertAppSettingsValue("Key1", "Value1 updated by transform1"); }
public void GenerateHtmlFromXml() { using (var reader = new StreamReader(ResourceManager.GetResourceStream("Issues_v2.0.2.xml"))) { var xmlInput = XDocument.Load(reader); var transformer = new XmlTransformer(@".\TestDomain\transform.xslt", @".\XmlUtilities\Saxon\Transform.exe"); Assert.That(transformer.GenerateResultFromXml(xmlInput, @".\output.html"), Is.EqualTo(0)); using (var resultReader = new StreamReader(ResourceManager.GetResourceStream("XmlTransformerTest.html"))) { Assert.That(File.ReadAllText(@".\output.html"), Is.EqualTo(resultReader.ReadToEnd())); } } }
public Nomination.Domain.RequestForConfirmation.RequestForConfirmation Get(string pipeline, string utility, DateTime gasDay, string cycle) { //get the xml data from DB var xml = GetXmlFromDb(pipeline, utility, gasDay, cycle); if (xml != string.Empty) { //deserialize xml to DTO RequestForConfirmation var obj = XmlTransformer.XmlDeserialize <Nomination.Persistence.RequestForConfirmation.Dto.RequestForConfirmation>(xml.ToString()); //map DTO from Database to domain RequestForConfirmation Nomination.Domain.RequestForConfirmation.RequestForConfirmation rfc = new ModelFactory().Map(obj); return(rfc); } return(null); }
public void TestXmlTransform() { string sourceFile = this.WriteTextToTempFile(TestUtilities.Source01); string transformFile = this.WriteTextToTempFile(TestUtilities.Transform01); string expectedResultFile = this.WriteTextToTempFile(TestUtilities.Result01); string destFile = this.GetTempFilename(true); ITransformer transformer = new XmlTransformer(); transformer.Transform(sourceFile, transformFile, destFile); Assert.True(File.Exists(sourceFile)); Assert.True(File.Exists(transformFile)); Assert.True(File.Exists(destFile)); string actualResult = File.ReadAllText(destFile); string expectedResult = File.ReadAllText(expectedResultFile); Assert.Equal(expectedResult.Trim(), actualResult.Trim()); }
private static List <FileInfo> GetFiles(string documentElementName) { var dir = new DirectoryInfo(Properties.Settings.Default.NaesbInboundUnc); List <FileInfo> files = dir.GetFiles() .Where(x => x.Extension == ".xml") .OrderBy(x => x.CreationTime) .ToList(); if (files.Count > 0) { List <FileInfo> fis = new List <FileInfo>(); foreach (var file in files) { try { XmlDocument xml = XmlTransformer.ConvertToXmlDocument(file); if (xml.DocumentElement != null && xml.DocumentElement.Name == documentElementName) { fis.Add(file); } } catch (Exception ex) { Console.WriteLine("==Processing Error:"); Console.WriteLine(ex); CreateIncident(ex, file); File.Copy(file.FullName, Properties.Settings.Default.NaesbInboundUnc + "Archive\\" + file.Name, true); Console.WriteLine("==Processing: [" + Properties.Settings.Default.EventType + "] [File: " + file.FullName + "] has been moved to " + Properties.Settings.Default.NaesbInboundUnc + "Archive\\" + file.Name); Console.WriteLine("==Processing: [" + Properties.Settings.Default.EventType + "] <<UNSUCCESSFUL>>"); File.Delete(file.FullName); } } return(fis); } return(null); }
/// <summary> Compares the assemblies and generates the desired reports. </summary> /// <returns> The amount of errors and warnings found. </returns> public int CheckApi() { // Comparing _comparerContext.LogInfo("Comparing assemblies."); _comparerResult = _comparerContext.CreateComparer(_referenceVersion, _newVersion).Compare(); // Reporting _comparerContext.LogInfo("Generating xml result."); XElement element = XmlGenerator.GenerateXml(_comparerResult); if (_xmlOutput != null) { _comparerContext.LogInfo("Exporting xml report."); element.Save(_xmlOutput); } if (_htmlOutput != null) { _comparerContext.LogInfo("Exporting html report."); XmlTransformer.TransformToHtml(element.CreateReader(), _htmlOutput); } return(_comparerResult.GetAllCount(Severity.Error) + _comparerResult.GetAllCount(Severity.Warning)); }
public DeploymentService( DeployerConfiguration deployerConfiguration, ILogger logger, [NotNull] IKeyValueConfiguration keyValueConfiguration, IWebDeployHelper webDeployHelper, Func <DeploymentExecutionDefinition, IIisManager> iisManager, NuGetPackageInstaller nugetPackageInstaller, IFtpHandlerFactory ftpHandlerFactor) { if (logger is null) { throw new ArgumentNullException(nameof(logger)); } if (keyValueConfiguration is null) { throw new ArgumentNullException(nameof(keyValueConfiguration)); } DeployerConfiguration = deployerConfiguration ?? throw new ArgumentNullException(nameof(deployerConfiguration)); _directoryCleaner = new DirectoryCleaner(logger); _packageInstaller = new PackageInstaller(logger, deployerConfiguration, keyValueConfiguration); _fileMatcher = new FileMatcher(logger); _xmlTransformer = new XmlTransformer(logger, _fileMatcher); _logger = logger; _webDeployHelper = webDeployHelper; _iisManager = iisManager; _nugetPackageInstaller = nugetPackageInstaller; _ftpHandlerFactory = ftpHandlerFactor; }
public void GetBasePath_should_return_path() { AssertExceptionNotThrown.WhenExecuting(() => Console.WriteLine(XmlTransformer.GetBaseFolder())); }
/// <summary> /// Shows a preview of the transformation in a temporary file. /// </summary> /// <param name="hier">Current IVsHierarchy</param> /// <param name="sourceFile">Full path to the file to be trasnformed</param> /// <param name="transformFile">Full path to the transformation file</param> private void PreviewTransform(IVsHierarchy hier, string sourceFile, string transformFile) { if (string.IsNullOrWhiteSpace(sourceFile)) { throw new ArgumentNullException("sourceFile"); } if (string.IsNullOrWhiteSpace(transformFile)) { throw new ArgumentNullException("transformFile"); } if (!File.Exists(sourceFile)) { throw new FileNotFoundException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.Error_SourceFileNotFound, sourceFile), sourceFile); } if (!File.Exists(transformFile)) { throw new FileNotFoundException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.Error_TransformFileNotFound, transformFile), transformFile); } // Get our options using (OptionsDialogPage optionsPage = new OptionsDialogPage()) { optionsPage.LoadSettingsFromStorage(); this.LogMessageWriteLineFormat("SlowCheetah PreviewTransform"); FileInfo sourceFileInfo = new FileInfo(sourceFile); // dest file string destFile = PackageUtilities.GetTempFilename(true, sourceFileInfo.Extension); this.TempFilesCreated.Add(destFile); // perform the transform and then display the result into the diffmerge tool that comes with VS. // If for some reason we can't find it, we just open it in an editor window this.errorListProvider.Tasks.Clear(); ITransformationLogger logger = new TransformationPreviewLogger(this.errorListProvider, hier); ITransformer transformer = new XmlTransformer(logger, false); if (!transformer.Transform(sourceFile, transformFile, destFile)) { throw new TransformFailedException(Resources.Resources.TransformPreview_ErrorMessage); } // Does the customer want a preview? if (optionsPage.EnablePreview == false) { ProjectUtilities.GetDTE().ItemOperations.OpenFile(destFile); } else { // If the diffmerge service is available (dev11) and no diff tool is specified, or diffmerge.exe is specifed we use the service if (this.GetService(typeof(SVsDifferenceService)) is IVsDifferenceService diffService && (string.IsNullOrEmpty(optionsPage.PreviewToolExecutablePath) || optionsPage.PreviewToolExecutablePath.EndsWith(@"\diffmerge.exe", StringComparison.OrdinalIgnoreCase))) { string sourceName = Path.GetFileName(sourceFile); string leftLabel = string.Format(CultureInfo.CurrentCulture, Resources.Resources.TransformPreview_LeftLabel, sourceName); string rightLabel = string.Format(CultureInfo.CurrentCulture, Resources.Resources.TransformPreview_RightLabel, sourceName, Path.GetFileName(transformFile)); string caption = string.Format(CultureInfo.CurrentCulture, Resources.Resources.TransformPreview_Caption, sourceName); string tooltip = string.Format(CultureInfo.CurrentCulture, Resources.Resources.TransformPreview_ToolTip, sourceName); diffService.OpenComparisonWindow2(sourceFile, destFile, caption, tooltip, leftLabel, rightLabel, null, null, (uint)__VSDIFFSERVICEOPTIONS.VSDIFFOPT_RightFileIsTemporary); }
public void ToHtmlFormatTest() { XmlTransformer.ToHtmlFormat(XmlValidatorHelper.XmlPath, "result.xml"); }
/// <summary> /// Shows a preview of the transformation in a temporary file. /// </summary> /// <param name="hier">Current IVsHierarchy</param> /// <param name="sourceFile">Full path to the file to be trasnformed</param> /// <param name="transformFile">Full path to the transformation file</param> private void PreviewTransform(IVsHierarchy hier, string sourceFile, string transformFile) { if (string.IsNullOrWhiteSpace(sourceFile)) { throw new ArgumentNullException("sourceFile"); } if (string.IsNullOrWhiteSpace(transformFile)) { throw new ArgumentNullException("transformFile"); } if (!File.Exists(sourceFile)) { throw new FileNotFoundException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.Error_SourceFileNotFound, sourceFile), sourceFile); } if (!File.Exists(transformFile)) { throw new FileNotFoundException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.Error_TransformFileNotFound, transformFile), transformFile); } // Get our options using (OptionsDialogPage optionsPage = new OptionsDialogPage()) { optionsPage.LoadSettingsFromStorage(); this.LogMessageWriteLineFormat("SlowCheetah PreviewTransform"); FileInfo sourceFileInfo = new FileInfo(sourceFile); // dest file string destFile = PackageUtilities.GetTempFilename(true, sourceFileInfo.Extension); this.TempFilesCreated.Add(destFile); // perform the transform and then display the result into the diffmerge tool that comes with VS. // If for some reason we can't find it, we just open it in an editor window this.errorListProvider.Tasks.Clear(); ITransformationLogger logger = new TransformationPreviewLogger(this.errorListProvider, hier); ITransformer transformer = new XmlTransformer(logger, false); if (!transformer.Transform(sourceFile, transformFile, destFile)) { throw new TransformFailedException(Resources.Resources.TransformPreview_ErrorMessage); } // Does the customer want a preview? if (optionsPage.EnablePreview == false) { ProjectUtilities.GetDTE().ItemOperations.OpenFile(destFile); } else { // If the diffmerge service is available (dev11) and no diff tool is specified, or diffmerge.exe is specifed we use the service IVsDifferenceService diffService = this.GetService(typeof(SVsDifferenceService)) as IVsDifferenceService; if (diffService != null && (string.IsNullOrEmpty(optionsPage.PreviewToolExecutablePath) || optionsPage.PreviewToolExecutablePath.EndsWith(@"\diffmerge.exe", StringComparison.OrdinalIgnoreCase))) { string sourceName = Path.GetFileName(sourceFile); string leftLabel = string.Format(CultureInfo.CurrentCulture, Resources.Resources.TransformPreview_LeftLabel, sourceName); string rightLabel = string.Format(CultureInfo.CurrentCulture, Resources.Resources.TransformPreview_RightLabel, sourceName, Path.GetFileName(transformFile)); string caption = string.Format(CultureInfo.CurrentCulture, Resources.Resources.TransformPreview_Caption, sourceName); string tooltip = string.Format(CultureInfo.CurrentCulture, Resources.Resources.TransformPreview_ToolTip, sourceName); diffService.OpenComparisonWindow2(sourceFile, destFile, caption, tooltip, leftLabel, rightLabel, null, null, (uint)__VSDIFFSERVICEOPTIONS.VSDIFFOPT_RightFileIsTemporary); } else if (string.IsNullOrEmpty(optionsPage.PreviewToolExecutablePath)) { throw new FileNotFoundException(Resources.Resources.Error_NoPreviewToolSpecified); } else if (!File.Exists(optionsPage.PreviewToolExecutablePath)) { throw new FileNotFoundException(string.Format(Resources.Resources.Error_CantFindPreviewTool, optionsPage.PreviewToolExecutablePath), optionsPage.PreviewToolExecutablePath); } else { // Quote the filenames... ProcessStartInfo psi = new ProcessStartInfo(optionsPage.PreviewToolExecutablePath, string.Format(optionsPage.PreviewToolCommandLine, "\"" + sourceFile + "\"", "\"" + destFile + "\"")) { CreateNoWindow = true, UseShellExecute = false }; System.Diagnostics.Process.Start(psi); } } } // TODO: Instead of creating a file and then deleting it later we could instead do this // http://matthewmanela.com/blog/the-problem-with-the-envdte-itemoperations-newfile-method/ // http://social.msdn.microsoft.com/Forums/en/vsx/thread/eb032063-eb4d-42e0-84e8-dec64bf42abf }
private void ModuleToDB(ibasModule module) { try { var args = new Core.ServiceEventArgs(string.Format("开始创建模块[{0}]的数据结构", module.ModuleDescription)); this.MessageManager.OnWriteMessageLog(this, args); var dsGetter = new DataStructuresGetter(); dsGetter.WorkFolder = module.ModuleInstallPath; var dsItems = dsGetter.Get(); dsGetter.AutoSelected(this.B1Included, this.GetCurrentDBType(), dsItems); if (dsItems == null) { return; } var logPath = string.Format(@"{0}Log\data_structures_{1}.txt", System.AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyyMMddhhmmss")); if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(logPath))) { System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(logPath)); } var gpDSItems = new Dictionary <string, List <DataStructureItem> >(); foreach (var item in dsItems.Where(c => c.Selected)) { if (gpDSItems.ContainsKey(item.Group)) { gpDSItems[item.Group].Add(item); } else { gpDSItems.Add(item.Group, new List <DataStructureItem>() { item }); } } using (var logFile = System.IO.File.CreateText(logPath)) { logFile.WriteLine(string.Format("folder:{0}", this.AppSetting.InstallDiraddress)); foreach (var gpKey in gpDSItems.Keys) { List <string> files = null; logFile.WriteLine(string.Format(" group:{0}", gpKey)); #region 数据结构创建 #region ibas args = new Core.ServiceEventArgs(string.Format("正在创建模块[{0}]的ibas数据结构", module.ModuleDescription)); this.MessageManager.OnWriteMessageLog(this, args); files = new List <string>(); foreach (var item in gpDSItems[gpKey].Where(c => c.ItemType == emDSItemType.data_structure && c.Platform == emPlatform.ibas)) { logFile.WriteLine(string.Format(" file:{0}", item.FilePath)); files.Add(item.FilePath); } if (files.Count > 0) { var xmlTrans = new XmlTransformer(); var ibasModel = xmlTrans.ToDomainModel(files.ToArray()); if (xmlTrans.HasError) { throw xmlTrans.ErrorLogs.FirstOrDefault(); } var dbTrans = new DbTransformer(); dbTrans.DBTypeSign = this.AppSetting.DatabaseType; dbTrans.SetMySQLMap(new SQLMapFactory(this.AppSetting.DBServer, this.AppSetting.DBUser, this.AppSetting.DBPassword, this.AppSetting.DBName).GetSQLMap(dbTrans.DBTypeSign)); dbTrans.SetDB(new dbConnectionFactory(this.AppSetting.DBServer, this.AppSetting.DBUser, this.AppSetting.DBPassword, this.AppSetting.DBName).GetDBConnection(dbTrans.MySQLMap)); dbTrans.ToDB(ibasModel); if (dbTrans.HasError) { throw new Exception(dbTrans.Errors.ToString()); } } #endregion #region b1 args = new Core.ServiceEventArgs(string.Format("正在创建模块[{0}]的b1数据结构", module.ModuleDescription)); this.MessageManager.OnWriteMessageLog(this, args); files = new List <string>(); foreach (var item in gpDSItems[gpKey].Where(c => c.ItemType == emDSItemType.data_structure && c.Platform == emPlatform.b1)) { logFile.WriteLine(string.Format(" file:{0}", item.FilePath)); files.Add(item.FilePath); } if (files.Count > 0) { var xmlTrans = new XmlTransformer(); var b1Model = xmlTrans.ToDomainModel(files.ToArray()); if (xmlTrans.HasError) { throw xmlTrans.ErrorLogs.FirstOrDefault(); } var b1Company = this.GetNewCompany(); var b1Trans = new B1DBTransformer(); b1Trans.SetDB(b1Company); b1Trans.ToDB(b1Model); b1Company.Disconnect(); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(b1Company); if (b1Trans.HasError) { throw new Exception(b1Trans.Errors.ToString()); } } #endregion #endregion #region sql脚本 args = new Core.ServiceEventArgs(string.Format("正在执行模块[{0}]的sql脚本", module.ModuleDescription)); this.MessageManager.OnWriteMessageLog(this, args); files = new List <string>(); foreach (var item in gpDSItems[gpKey].Where(c => c.ItemType == emDSItemType.sql_script)) { logFile.WriteLine(string.Format(" file:{0}", item.FilePath)); files.Add(item.FilePath); } if (files.Count > 0) { foreach (var item in files) { try { var sqlTrans = new SqlTransformer(); sqlTrans.DBTypeSign = this.AppSetting.DatabaseType; var sqlMap = new SQLMapFactory(this.AppSetting.DBServer, this.AppSetting.DBUser, this.AppSetting.DBPassword, this.AppSetting.DBName).GetSQLMap(sqlTrans.DBTypeSign); sqlMap.DefaultDatabase = string.Empty; sqlTrans.SetDB(new dbConnectionFactory(this.AppSetting.DBServer, this.AppSetting.DBUser, this.AppSetting.DBPassword, this.AppSetting.DBName).GetDBConnection(sqlMap)); sqlTrans.AddScriptFile(item); sqlTrans.Run(); } catch (Exception error) { if (!item.Contains(string.Format(@"DataStructures\SQLs\SQL_SYS_mssql_Initialization.sql"))) { throw new Exception(string.Format("执行[{0}]脚本,错误:{1}", item, error.ToString())); } } } } #endregion logFile.WriteLine(); } logFile.Close(); } } catch (Exception ex) { throw; } }
public void CreateOutputReport() { var transformer = new XmlTransformer(); var input = Input; if (!Path.IsPathRooted(input)) input = Path.Combine(TestContext.CurrentContext.TestDirectory, input); _output = Output; if (!Path.IsPathRooted(_output)) _output = Path.Combine(REPORT_DIR, _output); string[] options = !string.IsNullOrEmpty(Options) ? Options.Split(new char[] { ' ' }) : new string[0]; string[] args = new string[options.Length + 2]; int index = 0; args[index++] = input; args[index++] = "-o=" + _output; foreach (string opt in options) args[index++] = opt; transformer.Execute(args); FileAssert.Exists(_output, "No output created - no tests can be run"); }