public void Fail_OnMissingModelFileParam([ValueSource(nameof(InvalidInputsMissingInformationModel))] string[] inputParams) { // Arrange var warnWrittenOut = false; var opcuaAppName = $"{inputParams.ElementAtOrDefault(1)}"; var modelsDirectory = "models"; _fileSystemMock.Setup(x => x.CombinePaths(opcuaAppName, Constants.DirectoryName.Models)).Returns(modelsDirectory); _fileSystemMock.Setup(x => x.DirectoryExists(opcuaAppName)).Returns(true); var loggerListenerMock = new Mock <ILoggerListener>(); loggerListenerMock.Setup(listener => listener.Warn(It.IsAny <string>())).Callback(delegate { warnWrittenOut = true; }); AppioLogger.RegisterListener(loggerListenerMock.Object); // Act var result = _objectUnderTest.Execute(inputParams); // Assert Assert.IsTrue(warnWrittenOut); Assert.IsFalse(result.Success); AppioLogger.RemoveListener(loggerListenerMock.Object); }
public void FailBecauseOfMissingServerFile([ValueSource(nameof(ValidInputs))] string[] inputParams) { // Arrange var clientName = inputParams.ElementAtOrDefault(1); var serverName = inputParams.ElementAtOrDefault(3); var loggerListenerMock = new Mock <ILoggerListener>(); AppioLogger.RegisterListener(loggerListenerMock.Object); // Arrange server file var appioClientProjectPath = Path.Combine(clientName, clientName + Constants.FileExtension.Appioproject); _fileSystemMock.Setup(x => x.CombinePaths(clientName, clientName + Constants.FileExtension.Appioproject)).Returns(appioClientProjectPath); _fileSystemMock.Setup(x => x.FileExists(appioClientProjectPath)).Returns(true); var appioServerProjectPath = Path.Combine(serverName, serverName + Constants.FileExtension.Appioproject); _fileSystemMock.Setup(x => x.CombinePaths(serverName, serverName + Constants.FileExtension.Appioproject)).Returns(appioServerProjectPath); _fileSystemMock.Setup(x => x.FileExists(appioServerProjectPath)).Returns(false); // Act var commandResult = _objectUnderTest.Execute(inputParams); // Assert Assert.IsFalse(commandResult.Success); Assert.IsNotNull(commandResult.OutputMessages); var firstMessageLine = commandResult.OutputMessages.FirstOrDefault(); AppioLogger.RemoveListener(loggerListenerMock.Object); loggerListenerMock.Verify(x => x.Warn(Resources.text.logging.LoggingText.ReferenceAddServerAppioprojFileNotFound), Times.Once); Assert.AreEqual(string.Format(OutputText.ReferenceAddServerAppioprojFileNotFound, appioServerProjectPath), firstMessageLine.Key); Assert.AreEqual(string.Empty, firstMessageLine.Value); _fileSystemMock.Verify(x => x.CombinePaths(serverName, serverName + Constants.FileExtension.Appioproject), Times.Once); _fileSystemMock.Verify(x => x.FileExists(appioServerProjectPath), Times.Once); }
public void BuildAllSolutionsProjects([ValueSource(nameof(ValidInputs))] string[] inputParams) { // Arrange var solutionName = inputParams.ElementAtOrDefault(1); var loggerListenerMock = new Mock <ILoggerListener>(); AppioLogger.RegisterListener(loggerListenerMock.Object); _commandMock.Setup(x => x.Execute(It.IsAny <string[]>())).Returns(new CommandResult(true, new MessageLines())); // Arrange appiosln file var appioslnPath = Path.Combine(solutionName + Constants.FileExtension.Appiosln); _fileSystemMock.Setup(x => x.CombinePaths(solutionName + Constants.FileExtension.Appiosln)).Returns(appioslnPath); _fileSystemMock.Setup(x => x.FileExists(appioslnPath)).Returns(true); var solutionFullName = Path.Combine(solutionName + Constants.FileExtension.Appiosln); using (var slnMemoryStream = new MemoryStream(Encoding.ASCII.GetBytes(_sampleAppioslnContentWithTwoProjects))) using (var clientAppioprojMemoryStream = new MemoryStream(Encoding.ASCII.GetBytes(_sampleOpcuaClientAppContent))) using (var serverAppioprojMemoryStream = new MemoryStream(Encoding.ASCII.GetBytes(_sampleOpcuaServerAppContent))) { _fileSystemMock.Setup(x => x.ReadFile(solutionFullName)).Returns(slnMemoryStream); // Act var commandResult = _objectUnderTest.Execute(inputParams); // Assert Assert.IsTrue(commandResult.Success); Assert.IsNotNull(commandResult.OutputMessages); var firstMessageLine = commandResult.OutputMessages.FirstOrDefault(); AppioLogger.RemoveListener(loggerListenerMock.Object); Assert.AreEqual(_operationData.SuccessOutputMessage, firstMessageLine.Key); Assert.AreEqual(string.Empty, firstMessageLine.Value); } }
public void FailOnAddingClientReference([ValueSource(nameof(ValidInputs))] string[] inputParams) { // Arrage var serverName = inputParams.ElementAtOrDefault(3); var clientName = inputParams.ElementAtOrDefault(1); var loggerListenerMock = new Mock <ILoggerListener>(); AppioLogger.RegisterListener(loggerListenerMock.Object); var appioClientPath = Path.Combine(clientName, clientName + Constants.FileExtension.Appioproject); _fileSystemMock.Setup(x => x.CombinePaths(clientName, clientName + Constants.FileExtension.Appioproject)).Returns(appioClientPath); _fileSystemMock.Setup(x => x.FileExists(appioClientPath)).Returns(true); var appioServerPath = Path.Combine(serverName, serverName + Constants.FileExtension.Appioproject); _fileSystemMock.Setup(x => x.CombinePaths(serverName, serverName + Constants.FileExtension.Appioproject)).Returns(appioServerPath); _fileSystemMock.Setup(x => x.FileExists(appioServerPath)).Returns(true); using (Stream serverMemoryStream = new MemoryStream(Encoding.ASCII.GetBytes(_sampleOpcuaClientAppContent))) { _fileSystemMock.Setup(x => x.ReadFile(appioServerPath)).Returns(serverMemoryStream); // Act var commandResult = _objectUnderTest.Execute(inputParams); // Assert Assert.IsFalse(commandResult.Success); Assert.IsNotNull(commandResult.OutputMessages); var firstMessageLine = commandResult.OutputMessages.FirstOrDefault(); AppioLogger.RemoveListener(loggerListenerMock.Object); loggerListenerMock.Verify(x => x.Warn(Resources.text.logging.LoggingText.ReferenceAddClientCannotBeReferred), Times.Once); Assert.AreEqual(string.Format(OutputText.ReferenceAddClientCannotBeReferred, serverName), firstMessageLine.Key); Assert.AreEqual(string.Empty, firstMessageLine.Value); } }
public void CleanNameStrategy_Should_CleanProjectOnValidProjectName([ValueSource(nameof(ValidInputs))] string[] inputParams) { // Arrange const string projectBuildDirectory = "build-dir"; var projectName = inputParams.ElementAt(0); var resultMessage = string.Format(OutputText.OpcuaappCleanSuccess, projectName); _fileSystemMock.Setup(x => x.CombinePaths(projectName, Constants.DirectoryName.MesonBuild)).Returns(projectBuildDirectory); _fileSystemMock.Setup(x => x.DeleteDirectory(projectBuildDirectory)); _fileSystemMock.Setup(x => x.DirectoryExists(projectName)).Returns(true); var loggerListenerMock = new Mock <ILoggerListener>(); AppioLogger.RegisterListener(loggerListenerMock.Object); // Act var result = _objectUnderTest.Execute(inputParams); // Assert AppioLogger.RemoveListener(loggerListenerMock.Object); loggerListenerMock.Verify(x => x.Info(Resources.text.logging.LoggingText.CleanSuccess), Times.Once); Assert.IsTrue(result.Success); Assert.AreEqual(resultMessage, result.OutputMessages.First().Key); }
public void VersionStrategy_Should_PrintVersionInformation([ValueSource(nameof(Inputs))] string[] inputParams, [ValueSource(nameof(AssemblyInfos))] AssemblyInfo[] assemblyInfos) { // Arrange var reflectionMock = new Mock <IReflection>(); reflectionMock.Setup(x => x.GetAppioAssemblyInfos()).Returns(assemblyInfos); var objectUnderTest = new VersionStrategy(reflectionMock.Object); var loggerListenerMock = new Mock <ILoggerListener>(); loggerListenerMock.Setup(x => x.Info(LoggingText.VersionCommandCalled)); AppioLogger.RegisterListener(loggerListenerMock.Object); // Act var result = objectUnderTest.Execute(inputParams); // Assert var versionRegex = new Regex(@"^\d+.\d+.\d+$"); Assert.IsTrue(result.Success); Assert.IsNotNull(result.OutputMessages); Assert.IsTrue(result.OutputMessages.All(v => versionRegex.IsMatch(v.Value))); loggerListenerMock.Verify(x => x.Info(LoggingText.VersionCommandCalled), Times.Once); AppioLogger.RemoveListener(loggerListenerMock.Object); }
public override CommandResult Execute(IEnumerable <string> inputParams) { if (!ExecuteCommon(inputParams)) { return(new CommandResult(false, _outputMessages)); } // validate server var serverFullName = _fileSystem.CombinePaths(_serverName, _serverName + Constants.FileExtension.Appioproject); if (!ValidateServer(_serverName, serverFullName)) { return(new CommandResult(false, _outputMessages)); } // deserialize server file OpcuaServerApp opcuaServer = SlnUtility.DeserializeFile <OpcuaServerApp>(serverFullName, _fileSystem); if (opcuaServer == null) { AppioLogger.Warn(LoggingText.ReferenceAddCouldntDeserliazeServer); _outputMessages.Add(string.Format(OutputText.ReferenceAddCouldntDeserliazeServer, serverFullName), string.Empty); return(new CommandResult(false, _outputMessages)); } // check if deserialized server is not a client if (opcuaServer.Type == Constants.ApplicationType.Client) { AppioLogger.Warn(LoggingText.ReferenceAddClientCannotBeReferred); _outputMessages.Add(string.Format(OutputText.ReferenceAddClientCannotBeReferred, _serverName), string.Empty); return(new CommandResult(false, _outputMessages)); } // deserialize client file OpcuaClientApp opcuaClient = null; OpcuaClientServerApp opcuaClientServer = null; RefUtility.DeserializeClient(ref opcuaClient, ref opcuaClientServer, _clientFullName, _fileSystem); if (opcuaClient == null && opcuaClientServer == null) { AppioLogger.Warn(LoggingText.ReferenceCouldntDeserliazeClient); _outputMessages.Add(string.Format(OutputText.ReferenceCouldntDeserliazeClient, _clientFullName), string.Empty); return(new CommandResult(false, _outputMessages)); } // check if deserialized client is not a server if (!ClientIsNotAServer(ref opcuaClient, ref opcuaClientServer, _clientName)) { return(new CommandResult(false, _outputMessages)); } // check if server is not already a part of client's references if (!ServerIsNotYetClientsReference(ref opcuaClient, ref opcuaClientServer, _clientName, opcuaServer.Name)) { return(new CommandResult(false, _outputMessages)); } // overwrite client appioproj file with new server reference string clientNewContent = string.Empty; if (opcuaClientServer != null) { opcuaClientServer.ServerReferences.Add(opcuaServer); clientNewContent = JsonConvert.SerializeObject(opcuaClientServer, Formatting.Indented); } else { opcuaClient.ServerReferences.Add(opcuaServer); clientNewContent = JsonConvert.SerializeObject(opcuaClient, Formatting.Indented); } _fileSystem.WriteFile(_clientFullName, new List <string> { clientNewContent }); // exit with success AppioLogger.Info(LoggingText.ReferenceAddSuccess); _outputMessages.Add(string.Format(OutputText.RefereneceAddSuccess, _serverName, _clientName), string.Empty); return(new CommandResult(true, _outputMessages)); }
public void Cleanup() { AppioLogger.RemoveListener(_loggerListenerMock.Object); }
public CommandResult Execute(IEnumerable <string> inputParams) { var projectName = inputParams.ElementAtOrDefault(0); var outputMessages = new MessageLines(); if (string.IsNullOrEmpty(projectName)) { AppioLogger.Warn(LoggingText.EmptyOpcuaappName); outputMessages.Add(OutputText.OpcuaappDeployFailure, string.Empty); return(new CommandResult(false, outputMessages)); } var projectPublishDirectory = _fileSystem.CombinePaths(projectName, Constants.DirectoryName.Publish); var appClientPublishLocation = _fileSystem.CombinePaths(projectPublishDirectory, Constants.ExecutableName.AppClient); var appServerPublishLocation = _fileSystem.CombinePaths(projectPublishDirectory, Constants.ExecutableName.AppServer); var projectDeployDirectory = _fileSystem.CombinePaths(projectName, Constants.DirectoryName.Deploy); if (!_fileSystem.FileExists(appClientPublishLocation) && !_fileSystem.FileExists(appServerPublishLocation)) { AppioLogger.Warn(LoggingText.MissingPublishedOpcuaAppFiles); outputMessages.Add(string.Format(OutputText.OpcuaappDeployWithNameFailure, projectName), string.Empty); return(new CommandResult(false, outputMessages)); } // steps // create deploy dir _fileSystem.CreateDirectory(projectDeployDirectory); // create temp dir var tempDirectory = _fileSystem.CombinePaths(projectDeployDirectory, Constants.DirectoryName.Temp); _fileSystem.CreateDirectory(tempDirectory); // create needed installer structure var zipSourceLocation = _fileSystem.CombinePaths(projectDeployDirectory, Constants.DirectoryName.Temp, Constants.DirectoryName.OpcuaappInstaller + Constants.FileExtension.ZipFile); _fileSystem.ExtractFromZip(zipSourceLocation, tempDirectory, Resources.Resources.InstallerZipResourceName); // copy all needed files to temp dir installer source if (_fileSystem.FileExists(appClientPublishLocation)) { var appClientDeployTempLocation = _fileSystem.CombinePaths(tempDirectory, Constants.DirectoryName.OpcuaappInstaller, Constants.DirectoryName.Usr, Constants.DirectoryName.Bin, Constants.ExecutableName.AppClient); _fileSystem.CopyFile(appClientPublishLocation, appClientDeployTempLocation); } if (_fileSystem.FileExists(appServerPublishLocation)) { var appServerDeployTempLocation = _fileSystem.CombinePaths(tempDirectory, Constants.DirectoryName.OpcuaappInstaller, Constants.DirectoryName.Usr, Constants.DirectoryName.Bin, Constants.ExecutableName.AppServer); _fileSystem.CopyFile(appServerPublishLocation, appServerDeployTempLocation); } // create installer var debianInstallerResult = _fileSystem.CallExecutable(Constants.ExecutableName.CreateDebianInstaller, tempDirectory, Constants.ExecutableName.CreateDebianInstallerArguments); if (!debianInstallerResult) { AppioLogger.Warn(LoggingText.CreateDebianInstallerFails); outputMessages.Add(string.Format(OutputText.OpcuaappDeployWithNameFailure, projectName), string.Empty); return(new CommandResult(false, outputMessages)); } // move installer to deploy dir var installerName = Constants.DirectoryName.OpcuaappInstaller + Constants.FileExtension.DebianInstaller; var createdInstallerPath = _fileSystem.CombinePaths(tempDirectory, installerName); var installerTargetPath = _fileSystem.CombinePaths(projectDeployDirectory, installerName); _fileSystem.CopyFile(createdInstallerPath, installerTargetPath); // remove temp dir _fileSystem.DeleteDirectory(tempDirectory); // exit with success result AppioLogger.Info(LoggingText.OpcuaappDeploySuccess); outputMessages.Add(string.Format(OutputText.OpcuaappDeploySuccess, projectName), string.Empty); return(new CommandResult(true, outputMessages)); }
public CommandResult Execute(IEnumerable <string> inputParams) { var(error, stringParams, options) = _resolver.ResolveParams(inputParams); if (error != null) { return(new CommandResult(false, new MessageLines { { error, string.Empty } })); } var project = stringParams[ParamId.Project]; var certificate = stringParams[ParamId.Certificate]; var key = stringParams[ParamId.Key]; var forServer = options[ParamId.ForServer]; var forClient = options[ParamId.ForClient]; string GetExtension(string str) => str.Substring(Math.Max(0, str.Length - 3)); var isCertPEM = GetExtension(certificate) != "der"; var isKeyPEM = GetExtension(key) != "der"; if (forClient && forServer) { return(FailureWrongClientServer()); } var appioprojContent = _fileSystem.ReadFile(_fileSystem.CombinePaths(project, project + Constants.FileExtension.Appioproject)); string appType; using (var reader = new StreamReader(appioprojContent, Encoding.ASCII)) { appType = (string)JObject.Parse(reader.ReadToEnd())["type"]; } if (appType != Constants.ApplicationType.ClientServer && (forClient || forServer)) { return(FailureWrongClientServer()); } var keyTarget = Constants.FileName.PrivateKeyDER; var certTarget = Constants.FileName.Certificate; if (appType == Constants.ApplicationType.ClientServer) { string prefix; if (forServer) { prefix = Constants.FileName.ServerCryptoPrefix; } else if (forClient) { prefix = Constants.FileName.ClientCryptoPrefix; } else { return(FailureMissingClientServer()); } certTarget = prefix + "_" + Constants.FileName.Certificate; keyTarget = prefix + "_" + Constants.FileName.PrivateKeyDER; } var certificatesFolder = _fileSystem.CombinePaths(project, Constants.DirectoryName.Certificates); _fileSystem.CreateDirectory(certificatesFolder); Import(certificatesFolder, isKeyPEM, Constants.ExternalExecutableArguments.OpenSSLConvertKeyFromPEM, key, keyTarget); Import(certificatesFolder, isCertPEM, Constants.ExternalExecutableArguments.OpenSSLConvertCertificateFromPEM, certificate, certTarget); AppioLogger.Info(string.Format(LoggingText.ImportCertificateSuccess, certificate, key)); return(new CommandResult(true, new MessageLines { { OutputText.ImportCertificateCommandSuccess, string.Empty } })); }
public CommandResult Execute(IEnumerable <string> inputParams) { var outputMessages = new MessageLines(); var(error, stringParams, _) = _resolver.ResolveParams(inputParams); if (error != null) { return(new CommandResult(false, new MessageLines { { error, string.Empty } })); } var solutionName = stringParams[ParamId.SolutionName]; var projectName = stringParams[ParamId.ProjectName]; // check if solution file is existing var solutionFullName = _fileSystem.CombinePaths(solutionName + Constants.FileExtension.Appiosln); if (string.IsNullOrEmpty(solutionName) || !_fileSystem.FileExists(solutionFullName)) { AppioLogger.Warn(LoggingText.SlnAppioslnFileNotFound); outputMessages.Add(string.Format(OutputText.SlnAppioslnNotFound, solutionFullName), string.Empty); return(new CommandResult(false, outputMessages)); } // deserialise solution file Solution appioSolution = SlnUtility.DeserializeFile <Solution>(solutionFullName, _fileSystem); if (appioSolution == null) { AppioLogger.Warn(LoggingText.SlnCouldntDeserliazeSln); outputMessages.Add(string.Format(OutputText.SlnCouldntDeserliazeSln, solutionName), string.Empty); return(new CommandResult(false, outputMessages)); } // check if the project to remove is part of the solution var appioproj = appioSolution.Projects.SingleOrDefault(x => x.Name == projectName); if (appioproj != null) { // remove opcuaapp from sln appioSolution.Projects.Remove(appioproj); // serialize and write sln var slnNewContent = JsonConvert.SerializeObject(appioSolution, Formatting.Indented); _fileSystem.WriteFile(solutionFullName, new List <string> { slnNewContent }); } else { AppioLogger.Warn(LoggingText.SlnRemoveOpcuaappIsNotInSln); outputMessages.Add(string.Format(OutputText.SlnRemoveOpcuaappIsNotInSln, projectName, solutionName), string.Empty); return(new CommandResult(false, outputMessages)); } // exit method with success AppioLogger.Info(LoggingText.SlnRemoveSuccess); outputMessages.Add(string.Format(OutputText.SlnRemoveSuccess, projectName, solutionName), string.Empty); return(new CommandResult(true, outputMessages)); }
private static void SetupAppioLogger(ILoggerListener loggerListener) { AppioLogger.RegisterListener(loggerListener); }
public void DeployStrategy_Should_SucceedOnDeployProject([ValueSource(nameof(ValidInputs))] string[] inputParams, [ValueSource(nameof(FilesExistanceFlags))] bool[] existanceFlags) { // Arrange var projectDirectoryName = inputParams.ElementAt(0); var projectPublishDirectory = Path.Combine(projectDirectoryName, Constants.DirectoryName.Publish); var publishedClientExistanceFlag = existanceFlags.ElementAtOrDefault(0); var publishedServerExistanceFlag = existanceFlags.ElementAtOrDefault(1); var fileSystemMock = new Mock <IFileSystem>(); fileSystemMock.Setup(x => x.CombinePaths(projectDirectoryName, Constants.DirectoryName.Publish)).Returns(projectPublishDirectory); fileSystemMock.Setup(x => x.CombinePaths(projectPublishDirectory, Constants.ExecutableName.AppClient)).Returns(_appClientPublishLocation); fileSystemMock.Setup(x => x.CombinePaths(projectPublishDirectory, Constants.ExecutableName.AppServer)).Returns(_appServerPublishLocation); fileSystemMock.Setup(x => x.CombinePaths(projectDirectoryName, Constants.DirectoryName.Deploy)).Returns(_deployDirectory); fileSystemMock.Setup(x => x.CombinePaths(_deployDirectory, Constants.ExecutableName.AppClient)).Returns(_appClientDeployLocation); fileSystemMock.Setup(x => x.CombinePaths(_deployDirectory, Constants.ExecutableName.AppServer)).Returns(_appServerDeployLocation); fileSystemMock.Setup(x => x.CombinePaths(projectDirectoryName, Constants.DirectoryName.Deploy)).Returns(_deployDirectory); fileSystemMock.Setup(x => x.CombinePaths(_deployDirectory, Constants.DirectoryName.Temp)).Returns(_deployTempDirectory); fileSystemMock.Setup(x => x.CombinePaths(_deployTempDirectory, Constants.DirectoryName.OpcuaappInstaller, Constants.DirectoryName.Usr, Constants.DirectoryName.Bin, Constants.ExecutableName.AppClient)).Returns(_appClientDeployTempLocation); fileSystemMock.Setup(x => x.CombinePaths(_deployTempDirectory, Constants.DirectoryName.OpcuaappInstaller, Constants.DirectoryName.Usr, Constants.DirectoryName.Bin, Constants.ExecutableName.AppServer)).Returns(_appServerDeployTempLocation); // conitue work here fileSystemMock.Setup(x => x.CallExecutable(Constants.ExecutableName.CreateDebianInstaller, It.IsAny <string>(), Constants.ExecutableName.CreateDebianInstallerArguments)).Returns(true); fileSystemMock.Setup(x => x.FileExists(_appClientPublishLocation)).Returns(publishedClientExistanceFlag); fileSystemMock.Setup(x => x.FileExists(_appServerPublishLocation)).Returns(publishedServerExistanceFlag); var deployStrategy = new DeployNameStrategy(string.Empty, fileSystemMock.Object); var loggerListenerMock = new Mock <ILoggerListener>(); loggerListenerMock.Setup(y => y.Info(It.IsAny <string>())); AppioLogger.RegisterListener(loggerListenerMock.Object); // Act var strategyResult = deployStrategy.Execute(inputParams); // Assert Assert.IsTrue(strategyResult.Success); Assert.AreEqual(string.Format(OutputText.OpcuaappDeploySuccess, projectDirectoryName), strategyResult.OutputMessages.First().Key); Assert.AreEqual(string.Empty, strategyResult.OutputMessages.First().Value); fileSystemMock.Verify(x => x.CreateDirectory(_deployDirectory), Times.Once); if (publishedClientExistanceFlag) { fileSystemMock.Verify(x => x.CopyFile(_appClientPublishLocation, _appClientDeployTempLocation), Times.Once); } else { fileSystemMock.Verify(x => x.CopyFile(_appClientPublishLocation, _appClientDeployTempLocation), Times.Never); } if (publishedServerExistanceFlag) { fileSystemMock.Verify(x => x.CopyFile(_appServerPublishLocation, _appServerDeployTempLocation), Times.Once); } else { fileSystemMock.Verify(x => x.CopyFile(_appServerPublishLocation, _appServerDeployTempLocation), Times.Never); } loggerListenerMock.Verify(x => x.Info(LoggingText.OpcuaappDeploySuccess), Times.Once); loggerListenerMock.Verify(y => y.Info(It.IsAny <string>()), Times.Once); AppioLogger.RemoveListener(loggerListenerMock.Object); }
private static void RemoveLoggerListener(ILoggerListener loggerListener) { AppioLogger.RemoveListener(loggerListener); }
public CommandResult Execute(IEnumerable <string> inputParams) { var(error, parameters, options) = _resolver.ResolveParams(inputParams); if (error != null) { return(new CommandResult(false, new MessageLines { { error, string.Empty } })); } var opcuaAppName = parameters[ParamId.AppName]; var modelPath = parameters[ParamId.ModelPath]; var typesPath = parameters[ParamId.TypesPath]; // opcuaapp name validation if (!ValidateOpcuaAppName(opcuaAppName)) { return(new CommandResult(false, _outputMessages)); } var appioprojFilePath = _fileSystem.CombinePaths(opcuaAppName, opcuaAppName + Constants.FileExtension.Appioproject); var modelData = new ModelData(); if (options[ParamId.Sample]) { var modelsDir = _fileSystem.CombinePaths(opcuaAppName, Constants.DirectoryName.Models); var nodesetContent = _fileSystem.LoadTemplateFile(Resources.Resources.SampleInformationModelFileName); var nodesetFilePath = _fileSystem.CombinePaths(modelsDir, Constants.FileName.SampleInformationModelFile); _fileSystem.CreateFile(nodesetFilePath, nodesetContent); var typesContent = _fileSystem.LoadTemplateFile(Resources.Resources.SampleInformationModelTypesFileName); var typesFilePath = _fileSystem.CombinePaths(modelsDir, Constants.FileName.SampleInformationModelTypesFile); _fileSystem.CreateFile(typesFilePath, typesContent); if (!UpdateAppioProjFile(appioprojFilePath, modelData, opcuaAppName, Constants.FileName.SampleInformationModelFile, nodesetFilePath, Constants.FileName.SampleInformationModelTypesFile)) { return(new CommandResult(false, _outputMessages)); } _outputMessages.Add(string.Format(OutputText.ImportSampleInformationModelSuccess, Constants.FileName.SampleInformationModelFile), string.Empty); AppioLogger.Info(string.Format(LoggingText.ImportInforamtionModelCommandSuccess, Constants.FileName.SampleInformationModelFile)); return(new CommandResult(true, _outputMessages)); } // nodeset validation if (!ValidateModel(modelPath)) { return(new CommandResult(false, _outputMessages)); } var modelFileName = _fileSystem.GetFileName(modelPath); // types validation var typesFileName = string.Empty; if (typesPath != string.Empty && !ValidateTypes(out typesFileName, typesPath)) { return(new CommandResult(false, _outputMessages)); } if (!UpdateAppioProjFile(appioprojFilePath, modelData, opcuaAppName, modelFileName, modelPath, typesFileName)) { return(new CommandResult(false, _outputMessages)); } // copy model file var modelsDirectory = _fileSystem.CombinePaths(opcuaAppName, Constants.DirectoryName.Models); var targetModelFilePath = _fileSystem.CombinePaths(modelsDirectory, modelFileName); _fileSystem.CopyFile(modelPath, targetModelFilePath); // copy types file if (typesPath != string.Empty) { var targetTypesFilePath = _fileSystem.CombinePaths(modelsDirectory, typesFileName); _fileSystem.CopyFile(typesPath, targetTypesFilePath); } // exit with success AppioLogger.Info(string.Format(LoggingText.ImportInforamtionModelCommandSuccess, modelPath)); _outputMessages.Add(string.Format(OutputText.ImportInformationModelCommandSuccess, modelPath), string.Empty); return(new CommandResult(true, _outputMessages)); }
private static void SetupAppioLogger() { // setups the logger AppioLogger.RegisterListener(new LoggerListenerWrapper()); }
public void NewOpcuaAppCommandStrategy_Should_CreateFilesForServerApp([ValueSource(nameof(ValidInputs_ServerAppType))] string[] inputParam) { // Arrange var projectName = inputParam.ElementAtOrDefault(1); var loggerListenerMock = new Mock <ILoggerListener>(); AppioLogger.RegisterListener(loggerListenerMock.Object); var projectDirectory = $"{projectName}"; const string sourceCodeDirectory = "source-directory"; const string clientSourceDirectory = "client-source-directory"; const string serverSourceDirectory = "server-source-directory"; _fileSystemMock.Setup(x => x.CombinePaths(projectDirectory, Constants.DirectoryName.SourceCode)).Returns(sourceCodeDirectory); _fileSystemMock.Setup(x => x.CombinePaths(sourceCodeDirectory, Constants.DirectoryName.ClientApp)).Returns(clientSourceDirectory); _fileSystemMock.Setup(x => x.CombinePaths(sourceCodeDirectory, Constants.DirectoryName.ServerApp)).Returns(serverSourceDirectory); var projectFileName = $"{projectName}{Constants.FileExtension.Appioproject}"; const string projectFilePath = "project-file-path"; const string mesonBuildFilePath = "meson-build-file-path"; const string clientMainC = "client-main-c-file"; const string clientGlobalVariablesH = "client-globalVariables-h-file"; const string serverMainC = "server-main-c-file"; const string serverMesonBuild = "server-meson-build-file"; const string serverloadInformationModelsC = "server-loadInformationModels-c-file"; const string serverconstantsH = "constants-h-file"; const string serverMainCallbacksC = "mainCallbacks-c-file"; const string modelsDirectory = "models"; _fileSystemMock.Setup(x => x.CombinePaths(projectDirectory, projectFileName)).Returns(projectFilePath); _fileSystemMock.Setup(x => x.CombinePaths(projectDirectory, Constants.FileName.SourceCode_meson_build)).Returns(mesonBuildFilePath); _fileSystemMock.Setup(x => x.CombinePaths(clientSourceDirectory, Constants.FileName.SourceCode_main_c)).Returns(clientMainC); _fileSystemMock.Setup(x => x.CombinePaths(clientSourceDirectory, Constants.FileName.SourceCode_globalVariables_h)).Returns(clientGlobalVariablesH); _fileSystemMock.Setup(x => x.CombinePaths(serverSourceDirectory, Constants.FileName.SourceCode_main_c)).Returns(serverMainC); _fileSystemMock.Setup(x => x.CombinePaths(serverSourceDirectory, Constants.FileName.SourceCode_meson_build)).Returns(serverMesonBuild); _fileSystemMock.Setup(x => x.CombinePaths(serverSourceDirectory, Constants.FileName.SourceCode_loadInformationModels_c)).Returns(serverloadInformationModelsC); _fileSystemMock.Setup(x => x.CombinePaths(serverSourceDirectory, Constants.FileName.SourceCode_constants_h)).Returns(serverconstantsH); _fileSystemMock.Setup(x => x.CombinePaths(serverSourceDirectory, Constants.FileName.SourceCode_mainCallbacks_c)).Returns(serverMainCallbacksC); _fileSystemMock.Setup(x => x.CombinePaths(projectDirectory, Constants.DirectoryName.Models)).Returns(modelsDirectory); // Act var result = _objectUnderTest.Execute(inputParam); // Assert Assert.IsTrue(result.Success); Assert.AreEqual(string.Format(OutputText.NewOpcuaappCommandSuccess, projectName), result.OutputMessages.First().Key); AppioLogger.RemoveListener(loggerListenerMock.Object); loggerListenerMock.Verify(x => x.Info(string.Format(LoggingText.NewOpcuaappCommandSuccess, projectName)), Times.Once); _fileSystemMock.Verify(x => x.CreateDirectory(projectDirectory), Times.Once); _fileSystemMock.Verify(x => x.CreateDirectory(sourceCodeDirectory), Times.Once); _fileSystemMock.Verify(x => x.CreateDirectory(clientSourceDirectory), Times.Never); _fileSystemMock.Verify(x => x.CreateDirectory(serverSourceDirectory), Times.Once); _fileSystemMock.Verify(x => x.CreateDirectory(modelsDirectory), Times.Once); _fileSystemMock.Verify(x => x.CreateFile(projectFilePath, It.IsAny <string>()), Times.Once); _fileSystemMock.Verify(x => x.CreateFile(mesonBuildFilePath, It.IsAny <string>()), Times.Once); _fileSystemMock.Verify(x => x.CreateFile(clientMainC, It.IsAny <string>()), Times.Never); _fileSystemMock.Verify(x => x.CreateFile(clientGlobalVariablesH, It.IsAny <string>()), Times.Never); _fileSystemMock.Verify(x => x.CreateFile(serverMainC, It.IsAny <string>()), Times.Once); _fileSystemMock.Verify(x => x.CreateFile(serverMesonBuild, It.IsAny <string>()), Times.Once); _fileSystemMock.Verify(x => x.CreateFile(serverloadInformationModelsC, It.IsAny <string>()), Times.Once); _fileSystemMock.Verify(x => x.CreateFile(serverconstantsH, It.IsAny <string>()), Times.Once); _fileSystemMock.Verify(x => x.CreateFile(serverMainCallbacksC, It.IsAny <string>()), Times.Once); _fileSystemMock.Verify(x => x.LoadTemplateFile(Resources.Resources.AppioOpcuaAppTemplateFileName_meson_ClientServerType_build), Times.Never); _fileSystemMock.Verify(x => x.LoadTemplateFile(Resources.Resources.AppioOpcuaAppTemplateFileName_meson_ClientType_build), Times.Never); _fileSystemMock.Verify(x => x.LoadTemplateFile(Resources.Resources.AppioOpcuaAppTemplateFileName_meson_ServerType_build), Times.Once); _fileSystemMock.Verify(x => x.LoadTemplateFile(Resources.Resources.AppioOpcuaAppTemplateFileName_main_client_c), Times.Never); _fileSystemMock.Verify(x => x.LoadTemplateFile(Resources.Resources.AppioOpcuaAppTemplateFileName_globalVariables_client_h), Times.Never); _fileSystemMock.Verify(x => x.LoadTemplateFile(Resources.Resources.AppioOpcuaAppTemplateFileName_main_server_c), Times.Once); _fileSystemMock.Verify(x => x.LoadTemplateFile(Resources.Resources.AppioOpcuaAppTemplateFileName_meson_server_build), Times.Once); _fileSystemMock.Verify(x => x.LoadTemplateFile(Resources.Resources.AppioOpcuaAppTemplateFileName_loadInformationModels_server_c), Times.Once); _fileSystemMock.Verify(x => x.LoadTemplateFile(Resources.Resources.AppioOpcuaAppTemplateFileName_constants_server_h), Times.Once); _fileSystemMock.Verify(x => x.LoadTemplateFile(Resources.Resources.AppioOpcuaAppTemplateFileName_mainCallbacks_c), Times.Once); AppioLogger.RemoveListener(loggerListenerMock.Object); }
public CommandResult Execute(IEnumerable <string> inputParams) { var outputMessages = new MessageLines(); var messages = new Messages(); var(error, stringParams, options) = _resolver.ResolveParams(inputParams); if (error != null) { return(new CommandResult(false, new MessageLines { { error, string.Empty } })); } var opcuaAppName = stringParams[ParamId.OpcuaAppName]; var applicationType = stringParams[ParamId.ApplicationType]; var url = stringParams[ParamId.Url]; var port = stringParams[ParamId.Port]; // validate opcuaapp name if (_fileSystem.GetInvalidFileNameChars().Any(opcuaAppName.Contains) || _fileSystem.GetInvalidPathChars().Any(opcuaAppName.Contains)) { AppioLogger.Warn(LoggingText.InvalidOpcuaappName); outputMessages.Add(string.Format(OutputText.NewOpcuaappCommandFailureInvalidProjectName, opcuaAppName), string.Empty); return(new CommandResult(false, outputMessages)); } // validate opcuaapp type if (!ValidateApplicationType(ref messages, applicationType, url, port)) { AppioLogger.Warn(messages.loggerMessage); outputMessages.Add(messages.outputMessage, string.Empty); return(new CommandResult(false, outputMessages)); } // combine project file paths var projectFilePath = _fileSystem.CombinePaths(opcuaAppName, $"{opcuaAppName}{Constants.FileExtension.Appioproject}"); var sourceDirectory = _fileSystem.CombinePaths(opcuaAppName, Constants.DirectoryName.SourceCode); var mesonFilePath = _fileSystem.CombinePaths(opcuaAppName, Constants.FileName.SourceCode_meson_build); // create project directories _fileSystem.CreateDirectory(opcuaAppName); _fileSystem.CreateDirectory(sourceDirectory); IOpcuaapp opcuaapp = null; // deploy files for opcuaapp Client if (applicationType == Constants.ApplicationType.Client) { opcuaapp = new OpcuaClientApp(opcuaAppName); _fileSystem.CreateFile(mesonFilePath, _fileSystem.LoadTemplateFile( Resources.Resources.AppioOpcuaAppTemplateFileName_meson_ClientType_build)); DeployTemplateOpcuaClientSourceFiles(sourceDirectory); } // deploy files for opcuaapp Server else if (applicationType == Constants.ApplicationType.Server) { opcuaapp = new OpcuaServerApp(opcuaAppName, url, port); _fileSystem.CreateFile(mesonFilePath, _fileSystem.LoadTemplateFile( Resources.Resources.AppioOpcuaAppTemplateFileName_meson_ServerType_build)); CreateModelsDirectory(opcuaAppName); DeployTemplateOpcuaServerSourceFiles(sourceDirectory); } // deploy files for opcuaapp ClientServer else if (applicationType == Constants.ApplicationType.ClientServer) { opcuaapp = new OpcuaClientServerApp(opcuaAppName, url, port); _fileSystem.CreateFile(mesonFilePath, _fileSystem.LoadTemplateFile(Resources.Resources .AppioOpcuaAppTemplateFileName_meson_ClientServerType_build)); CreateModelsDirectory(opcuaAppName); DeployTemplateOpcuaClientSourceFiles(sourceDirectory); DeployTemplateOpcuaServerSourceFiles(sourceDirectory); } if (!options[ParamId.NoCert]) { if (applicationType == Constants.ApplicationType.ClientServer) { _certificateGenerator.Generate(opcuaAppName, Constants.FileName.ClientCryptoPrefix); _certificateGenerator.Generate(opcuaAppName, Constants.FileName.ServerCryptoPrefix); } else { _certificateGenerator.Generate(opcuaAppName); } } // create *.appioproj file var opcuaappAsJson = JsonConvert.SerializeObject(opcuaapp, Formatting.Indented); _fileSystem.CreateFile(projectFilePath, opcuaappAsJson); AppioLogger.Info(string.Format(LoggingText.NewOpcuaappCommandSuccess, opcuaAppName)); outputMessages.Add(string.Format(OutputText.NewOpcuaappCommandSuccess, opcuaAppName), string.Empty); return(new CommandResult(true, outputMessages)); }
public CommandResult Execute(IEnumerable <string> inputParams) { var(error, stringParams, _) = _resolver.ResolveParams(inputParams); if (error != null) { return(new CommandResult(false, new MessageLines { { error, string.Empty } })); } var projectName = stringParams[ParamId.AppName]; var outputMessages = new MessageLines(); // deserialize appioproj file var appioprojFilePath = _fileSystem.CombinePaths(projectName, projectName + Constants.FileExtension.Appioproject); var opcuaappData = Deserialize.Opcuaapp(appioprojFilePath, _fileSystem); if (opcuaappData == null) { AppioLogger.Warn(LoggingText.GenerateInformationModelFailureCouldntDeserliazeOpcuaapp); outputMessages.Add(string.Format(OutputText.GenerateInformationModelFailureCouldntDeserliazeOpcuaapp, projectName, appioprojFilePath), string.Empty); return(new CommandResult(false, outputMessages)); } if ((opcuaappData as IOpcuaClientApp)?.Type == Constants.ApplicationType.Client) { AppioLogger.Warn(LoggingText.GenerateInformationModelFailuteOpcuaappIsAClient); outputMessages.Add(string.Format(OutputText.GenerateInformationModelFailuteOpcuaappIsAClient, projectName), string.Empty); return(new CommandResult(false, outputMessages)); } var opcuaappModels = (opcuaappData as IOpcuaServerApp)?.Models; // check if models are valid if (!ValidateModels(opcuaappModels)) { AppioLogger.Warn(LoggingText.GenerateInformationModelInvalidModelsList); outputMessages.Add(string.Format(OutputText.GenerateInformationModelInvalidModelsList, projectName), string.Empty); return(new CommandResult(false, outputMessages)); } // check if there is any circular dependency between models if (SearchForCircularDependencies(opcuaappModels)) { AppioLogger.Warn(LoggingText.GenerateInformationModelCircularDependency); outputMessages.Add(string.Format(OutputText.GenerateInformationModelCircularDependency, projectName), string.Empty); return(new CommandResult(false, outputMessages)); } // sort models SortModels(opcuaappModels); // generate models foreach (var model in opcuaappModels) { var requiredModelData = GetListOfRequiredModels(opcuaappModels, model); if (!_nodesetGenerator.GenerateNodesetSourceCodeFiles(projectName, model, requiredModelData)) { outputMessages.Add(_nodesetGenerator.GetOutputMessage(), string.Empty); return(new CommandResult(false, outputMessages)); } } // add noodeset variables CreateNamespaceVariables(projectName, opcuaappModels); // exit method with positive result AppioLogger.Info(LoggingText.GenerateInformationModelSuccess); outputMessages.Add(string.Format(OutputText.GenerateInformationModelSuccess, projectName), string.Empty); return(new CommandResult(true, outputMessages)); }
public CommandResult Execute(IEnumerable <string> inputParams) { var outputMessages = new MessageLines(); var validationMessages = new SlnUtility.ResultMessages(); var(error, stringParams, _) = _resolver.ResolveParams(inputParams); if (error != null) { return(new CommandResult(false, new MessageLines { { error, string.Empty } })); } var solutionName = stringParams[ParamId.SolutionName]; var projectName = stringParams[ParamId.ProjectName]; // validate solution name if (!SlnUtility.ValidateSolution(ref validationMessages, solutionName, _fileSystem)) { AppioLogger.Warn(validationMessages.LoggerMessage); outputMessages.Add(validationMessages.OutputMessage, string.Empty); return(new CommandResult(false, outputMessages)); } // check if *.appioproj file exists var appioprojFilePath = _fileSystem.CombinePaths(projectName, projectName + Constants.FileExtension.Appioproject); if (string.IsNullOrEmpty(projectName) || !_fileSystem.FileExists(appioprojFilePath)) { AppioLogger.Warn(LoggingText.SlnAddAppioprojFileNotFound); outputMessages.Add(string.Format(OutputText.SlnAddOpcuaappNotFound, appioprojFilePath), string.Empty); return(new CommandResult(false, outputMessages)); } // deserialize *.appiosln file var solutionFullName = solutionName + Constants.FileExtension.Appiosln; Solution appioSolution = SlnUtility.DeserializeFile <Solution>(solutionFullName, _fileSystem); if (appioSolution == null) { AppioLogger.Warn(LoggingText.SlnCouldntDeserliazeSln); outputMessages.Add(string.Format(OutputText.SlnCouldntDeserliazeSln, solutionName), string.Empty); return(new CommandResult(false, outputMessages)); } // deserialize *.appioproj file OpcuaappReference appioproj = SlnUtility.DeserializeFile <OpcuaappReference>(appioprojFilePath, _fileSystem); if (appioproj == null) { AppioLogger.Warn(LoggingText.SlnAddCouldntDeserliazeOpcuaapp); outputMessages.Add(string.Format(OutputText.SlnAddCouldntDeserliazeOpcuaapp, projectName), string.Empty); return(new CommandResult(false, outputMessages)); } // check if sln does not contain opcuaapp yet if (!appioSolution.Projects.Any(x => x.Name == appioproj.Name)) { // add opcuaapp to sln appioproj.Path = appioprojFilePath; appioSolution.Projects.Add(appioproj); // serialize and write sln var slnNewContent = JsonConvert.SerializeObject(appioSolution, Formatting.Indented); _fileSystem.WriteFile(solutionFullName, new List <string> { slnNewContent }); } else { AppioLogger.Info(LoggingText.SlnAddContainsOpcuaapp); outputMessages.Add(string.Format(OutputText.SlnAddContainsOpcuaapp, solutionName, projectName), string.Empty); return(new CommandResult(false, outputMessages)); } // exit method with success AppioLogger.Info(LoggingText.SlnAddSuccess); outputMessages.Add(string.Format(OutputText.SlnAddSuccess, projectName, solutionName), string.Empty); return(new CommandResult(true, outputMessages)); }
/// <summary> /// Needs to be cleaned-up, because static context. /// </summary> private static void CleanupAppioLogger() { AppioLogger.RemoveAllListeners(); Assert.AreEqual(AppioLogger.LoggerListeners.Count(), 0); }
public CommandResult Execute(IEnumerable <string> inputParams) { var(error, stringParams, _) = _resolver.ResolveParams(inputParams); if (error != null) { return(new CommandResult(false, new MessageLines { { error, string.Empty } })); } var appName = stringParams[ParamId.AppName]; uint keySize, days; try { keySize = uint.Parse(stringParams[ParamId.KeySize]); days = uint.Parse(stringParams[ParamId.Days]); } catch (FormatException) { AppioLogger.Warn(LoggingText.GenerateCertificateFailureNotParsable); return(new CommandResult(false, new MessageLines { { OutputText.GenerateCertificateCommandFailureNotParsable, string.Empty } })); } Stream appioprojContent; try { appioprojContent = _fileSystem.ReadFile(_fileSystem.CombinePaths(appName, appName + Constants.FileExtension.Appioproject)); } catch (Exception) { AppioLogger.Warn(string.Format(LoggingText.GenerateCertificateFailureNotFound, appName)); return(new CommandResult(false, new MessageLines { { string.Format(OutputText.GenerateCertificateCommandFailureNotFound, appName), string.Empty } })); } var reader = new StreamReader(appioprojContent, Encoding.ASCII); var appType = (string)JObject.Parse(reader.ReadToEnd())["type"]; if (appType == Constants.ApplicationType.ClientServer) { _certificateGenerator.Generate(appName, Constants.FileName.ClientCryptoPrefix, keySize, days, stringParams[ParamId.Org]); _certificateGenerator.Generate(appName, Constants.FileName.ServerCryptoPrefix, keySize, days, stringParams[ParamId.Org]); } else { _certificateGenerator.Generate(appName, string.Empty, keySize, days, stringParams[ParamId.Org]); } AppioLogger.Info(LoggingText.GenerateCertificateSuccess); return(new CommandResult(true, new MessageLines { { string.Format(OutputText.GenerateCertificateCommandSuccess, appName), string.Empty } })); }