public void AddNewCacheWorkerRoleSuccessful() { using (FileSystemHelper files = new FileSystemHelper(this)) { string rootPath = Path.Combine(files.RootPath, "AzureService"); string roleName = "WorkerRole"; int expectedInstanceCount = 10; newServiceCmdlet.NewAzureServiceProcess(files.RootPath, "AzureService"); WorkerRole cacheWorkerRole = addCacheRoleCmdlet.AddAzureCacheWorkerRoleProcess(roleName, expectedInstanceCount, rootPath); AzureAssert.ScaffoldingExists(Path.Combine(files.RootPath, "AzureService", "WorkerRole"), Path.Combine(Resources.GeneralScaffolding, Resources.WorkerRole)); AzureAssert.WorkerRoleImportsExists(new Import { moduleName = Resources.CachingModuleName }, cacheWorkerRole); AzureAssert.LocalResourcesLocalStoreExists(new LocalStore { name = Resources.CacheDiagnosticStoreName, cleanOnRoleRecycle = false }, cacheWorkerRole.LocalResources); Assert.IsNull(cacheWorkerRole.Endpoints.InputEndpoint); AssertConfigExists(AzureAssert.GetCloudRole(rootPath, roleName)); AssertConfigExists(AzureAssert.GetLocalRole(rootPath, roleName), Resources.EmulatorConnectionString); PSObject actualOutput = mockCommandRuntime.OutputPipeline[1] as PSObject; Assert.AreEqual<string>(roleName, actualOutput.Members[Parameters.CacheWorkerRoleName].Value.ToString()); Assert.AreEqual<int>(expectedInstanceCount, int.Parse(actualOutput.Members[Parameters.Instances].Value.ToString())); } }
public void AddNewCacheWorkerRoleSuccessful() { using (FileSystemHelper files = new FileSystemHelper(this)) { string servicePath = Path.Combine(files.RootPath, "AzureService"); string roleName = "WorkerRole"; int expectedInstanceCount = 10; new NewAzureServiceProjectCommand().NewAzureServiceProcess(files.RootPath, "AzureService"); WorkerRole cacheWorkerRole = cmdlet.AddAzureCacheWorkerRoleProcess(roleName, expectedInstanceCount, servicePath); RoleSettings cacheRoleSettings = Testing.GetRole(servicePath, roleName); AzureAssert.ScaffoldingExists(Path.Combine(files.RootPath, "AzureService", "WorkerRole"), Path.Combine(Resources.NodeScaffolding, Resources.WorkerRole)); AzureAssert.WorkerRoleImportsExists(new Import { moduleName = Resources.CachingModuleName }, cacheWorkerRole); AzureAssert.LocalResourcesLocalStoreExists(new LocalStore { name = Resources.CacheDiagnosticStoreName, cleanOnRoleRecycle = false }, cacheWorkerRole.LocalResources); Assert.IsNull(cacheWorkerRole.Endpoints.InputEndpoint); AzureAssert.ConfigurationSettingExist(new ConfigConfigurationSetting { name = Resources.NamedCacheSettingName, value = Resources.NamedCacheSettingValue }, cacheRoleSettings.ConfigurationSettings); AzureAssert.ConfigurationSettingExist(new ConfigConfigurationSetting { name = Resources.DiagnosticLevelName, value = Resources.DiagnosticLevelValue }, cacheRoleSettings.ConfigurationSettings); AzureAssert.ConfigurationSettingExist(new ConfigConfigurationSetting { name = Resources.CachingCacheSizePercentageSettingName, value = string.Empty }, cacheRoleSettings.ConfigurationSettings); AzureAssert.ConfigurationSettingExist(new ConfigConfigurationSetting { name = Resources.CachingConfigStoreConnectionStringSettingName, value = string.Empty }, cacheRoleSettings.ConfigurationSettings); PSObject actualOutput = writer.OutputChannel[0] as PSObject; Assert.AreEqual<string>(roleName, actualOutput.Members[Parameters.CacheWorkerRoleName].Value.ToString()); Assert.AreEqual<int>(expectedInstanceCount, int.Parse(actualOutput.Members[Parameters.Instances].Value.ToString())); } }
public void SetDeploymentStatusProcessDeploymentDoesNotExistTest() { SimpleServiceManagement channel = new SimpleServiceManagement(); string newStatus = DeploymentStatus.Running; string resultMessage; string expectedMessage = string.Format(Resources.ServiceSlotDoesNotExist, slot, serviceName); bool statusUpdated = false; channel.UpdateDeploymentStatusBySlotThunk = ar => { statusUpdated = true; channel.GetDeploymentBySlotThunk = ar2 => new Deployment{Name = serviceName, DeploymentSlot = slot, Status = newStatus}; }; channel.GetDeploymentBySlotThunk = ar => { throw new ServiceManagementClientException(HttpStatusCode.NotFound, new ServiceManagementError(), string.Empty); }; using (FileSystemHelper files = new FileSystemHelper(this)) { files.CreateAzureSdkDirectoryAndImportPublishSettings(); AzureService service = new AzureService(files.RootPath, serviceName, null); var deploymentManager = new DeploymentStatusManager(channel); deploymentManager.ShareChannel = true; deploymentManager.CommandRuntime = new MockCommandRuntime(); deploymentManager.SetDeploymentStatusProcess(service.Paths.RootPath, newStatus, slot, Data.ValidSubscriptionNames[0], serviceName); resultMessage = ((MockCommandRuntime)deploymentManager.CommandRuntime).WarningStream[0]; Assert.IsFalse(statusUpdated); Assert.IsTrue(resultMessage.Contains(expectedMessage)); Assert.IsTrue(((MockCommandRuntime)deploymentManager.CommandRuntime).OutputPipeline.Count.Equals(0)); } }
public void SetDeploymentStatusProcessDeploymentDoesNotExistTest() { SimpleServiceManagement channel = new SimpleServiceManagement(); string newStatus = DeploymentStatus.Running; string resultMessage; string expectedMessage = string.Format(Resources.ServiceSlotDoesNotExist, serviceName, slot); bool statusUpdated = false; channel.UpdateDeploymentStatusBySlotThunk = ar => { statusUpdated = true; channel.GetDeploymentBySlotThunk = ar2 => new Deployment(serviceName, slot, newStatus); }; channel.GetDeploymentBySlotThunk = ar => { throw new EndpointNotFoundException(); }; using (FileSystemHelper files = new FileSystemHelper(this)) { files.CreateAzureSdkDirectoryAndImportPublishSettings(); AzureService service = new AzureService(files.RootPath, serviceName, null); var deploymentManager = new DeploymentStatusManager(channel); deploymentManager.ShareChannel = true; resultMessage = deploymentManager.SetDeploymentStatusProcess(service.Paths.RootPath, newStatus, slot, Data.ValidSubscriptionName[0], serviceName); Assert.IsFalse(statusUpdated); Assert.AreEqual<string>(expectedMessage, resultMessage); } }
public void SetAzureServiceProjectTestsLocationValid() { string[] locations = { "West US", "East US", "East Asia", "North Europe" }; foreach (string item in locations) { using (FileSystemHelper files = new FileSystemHelper(this)) { // Create new empty settings file // PowerShellProjectPathInfo paths = new PowerShellProjectPathInfo(files.RootPath); ServiceSettings settings = new ServiceSettings(); mockCommandRuntime = new MockCommandRuntime(); setServiceProjectCmdlet.CommandRuntime = mockCommandRuntime; settings.Save(paths.Settings); settings = setServiceProjectCmdlet.SetAzureServiceProjectProcess(item, null, null, paths.Settings); // Assert location is changed // Assert.AreEqual<string>(item, settings.Location); ServiceSettings actualOutput = mockCommandRuntime.OutputPipeline[0] as ServiceSettings; Assert.AreEqual<string>(item, settings.Location); } } }
public void RemoveAzureServiceProcessTest() { bool serviceDeleted = false; bool deploymentDeleted = false; channel.GetDeploymentBySlotThunk = ar => { if (deploymentDeleted) throw new EndpointNotFoundException(); return new Deployment(serviceName, ArgumentConstants.Slots[Slot.Production], DeploymentStatus.Suspended); }; channel.DeleteHostedServiceThunk = ar => serviceDeleted = true; channel.DeleteDeploymentBySlotThunk = ar => { deploymentDeleted = true; }; channel.IsDNSAvailableThunk = ida => new AvailabilityResponse { Result = false }; using (FileSystemHelper files = new FileSystemHelper(this)) { files.CreateAzureSdkDirectoryAndImportPublishSettings(); AzureService service = new AzureService(files.RootPath, serviceName, null); removeServiceCmdlet.PassThru = true; removeServiceCmdlet.RemoveAzureServiceProcess(service.Paths.RootPath, string.Empty, serviceName); Assert.IsTrue(deploymentDeleted); Assert.IsTrue(serviceDeleted); Assert.IsTrue((bool)mockCommandRuntime.OutputPipeline[0]); } }
public void RemoveAzureServiceProcessTest() { SimpleServiceManagement channel = new SimpleServiceManagement(); bool serviceDeleted = false; bool deploymentDeleted = false; channel.GetDeploymentBySlotThunk = ar => { if (deploymentDeleted) throw new EndpointNotFoundException(); return new Deployment(serviceName, ArgumentConstants.Slots[Slot.Production], DeploymentStatus.Suspended); }; channel.DeleteHostedServiceThunk = ar => serviceDeleted = true; channel.DeleteDeploymentBySlotThunk = ar => { deploymentDeleted = true; }; using (FileSystemHelper files = new FileSystemHelper(this)) { files.CreateAzureSdkDirectoryAndImportPublishSettings(); AzureService service = new AzureService(files.RootPath, serviceName, null); new RemoveAzureServiceCommand(channel).RemoveAzureServiceProcess(service.Paths.RootPath, string.Empty); Assert.IsTrue(deploymentDeleted); Assert.IsTrue(serviceDeleted); } }
public void AddAzureWebRoleWillRecreateDeploymentSettings() { using (FileSystemHelper files = new FileSystemHelper(this)) { string roleName = "WebRole1"; string serviceName = "AzureService"; string rootPath = files.CreateNewService(serviceName); string expectedVerboseMessage = string.Format(Resources.AddRoleMessageCreate, rootPath, roleName); string settingsFilePath = Path.Combine(rootPath, Resources.SettingsFileName); string originalDirectory = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(rootPath); File.Delete(settingsFilePath); Assert.IsFalse(File.Exists(settingsFilePath)); addWebCmdlet = new AddAzureWebRoleCommand() { RootPath = rootPath, CommandRuntime = mockCommandRuntime, Name = roleName }; addWebCmdlet.ExecuteCmdlet(); AzureAssert.ScaffoldingExists(Path.Combine(files.RootPath, "AzureService", roleName), Path.Combine(Resources.GeneralScaffolding, Resources.WebRole)); Assert.AreEqual<string>(roleName, ((PSObject)mockCommandRuntime.OutputPipeline[0]).GetVariableValue<string>(Parameters.RoleName)); Assert.AreEqual<string>(expectedVerboseMessage, mockCommandRuntime.VerboseStream[0]); Assert.IsTrue(File.Exists(settingsFilePath)); Directory.SetCurrentDirectory(originalDirectory); } }
public void AzureServiceAddNewWorkerRoleWithWhiteCharFail() { using (FileSystemHelper files = new FileSystemHelper(this)) { Testing.AssertThrows<ArgumentException>(() => new AzureService(files.RootPath, serviceName, null).AddWebRole("\tRole"), string.Format(Resources.InvalidRoleNameMessage, "\tRole")); } }
public void SetDeploymentStatusProcessSetStatusToActualStatusTest() { SimpleServiceManagement channel = new SimpleServiceManagement(); string newStatus = DeploymentStatus.Suspended; string currentStatus = DeploymentStatus.Suspended; string resultMessage; string expectedMessage = string.Format(Resources.DeploymentAlreadyInState, slot, serviceName, currentStatus); bool statusUpdated = false; channel.UpdateDeploymentStatusBySlotThunk = ar => { statusUpdated = true; channel.GetDeploymentBySlotThunk = ar2 => new Deployment(serviceName, slot, newStatus); }; channel.GetDeploymentBySlotThunk = ar => new Deployment(serviceName, slot, currentStatus); using (FileSystemHelper files = new FileSystemHelper(this)) { files.CreateAzureSdkDirectoryAndImportPublishSettings(); AzureService service = new AzureService(files.RootPath, serviceName, null); resultMessage = new DeploymentStatusManager(channel).SetDeploymentStatusProcess(service.Paths.RootPath, newStatus, slot, Data.ValidSubscriptionName[0], serviceName); Assert.IsFalse(statusUpdated); Assert.AreEqual<string>(expectedMessage, resultMessage); } }
public void SetAzureInstancesProcessTestsEmptyRoleNameFail() { using (FileSystemHelper files = new FileSystemHelper(this)) { AzureService service = new AzureService(files.RootPath, serviceName, null); Testing.AssertThrows<ArgumentException>(() => service.SetRoleInstances(service.Paths, string.Empty, 10), string.Format(Resources.InvalidOrEmptyArgumentMessage, Resources.RoleName)); } }
public void AzureServiceAddExistingRoleFail() { using (FileSystemHelper files = new FileSystemHelper(this)) { AzureService service = new AzureService(files.RootPath, serviceName, null); service.AddWebRole("WebRole"); Testing.AssertThrows<ArgumentException>(() => service.AddWebRole("WebRole"), string.Format(Resources.AddRoleMessageRoleExists, "WebRole")); } }
public void DisableRemoteDesktopForEmptyService() { using (FileSystemHelper files = new FileSystemHelper(this)) { files.CreateAzureSdkDirectoryAndImportPublishSettings(); files.CreateNewService("NEW_SERVICE"); disableRDCmdlet.DisableRemoteDesktop(); } }
public void NewAzureServiceProcessTest() { string serviceName = "AzureService"; using (FileSystemHelper files = new FileSystemHelper(this)) { new NewAzureServiceProjectCommand().NewAzureServiceProcess(files.RootPath, serviceName); AzureAssert.AzureServiceExists(files.RootPath, Resources.GeneralScaffolding, serviceName); } }
public void GetNextPortAllNull() { using (FileSystemHelper files = new FileSystemHelper(this)) { int expectedPort = int.Parse(Resources.DefaultWebPort); AzureService service = new AzureService(files.RootPath, serviceName, null); int nextPort = service.Components.GetNextPort(); Assert.AreEqual<int>(expectedPort, nextPort); } }
public void DisableRemoteDesktopForWebRole() { using (FileSystemHelper files = new FileSystemHelper(this)) { files.CreateAzureSdkDirectoryAndImportPublishSettings(); string root = files.CreateNewService("NEW_SERVICE"); new AddAzureNodeWebRoleCommand().AddAzureNodeWebRoleProcess("WebRole", 1, root); new DisableAzureServiceProjectRemoteDesktopCommand().DisableRemoteDesktop(); } }
public void AddAzureNodeWorkerRoleProcess() { using (FileSystemHelper files = new FileSystemHelper(this)) { new NewAzureServiceProjectCommand().NewAzureServiceProcess(files.RootPath, "AzureService"); new AddAzureNodeWorkerRoleCommand().AddAzureNodeWorkerRoleProcess("WorkerRole", 1, Path.Combine(files.RootPath, "AzureService")); AzureAssert.ScaffoldingExists(Path.Combine(files.RootPath, "AzureService", "WorkerRole"), Path.Combine(Resources.NodeScaffolding, Resources.WorkerRole)); } }
public void SetAzureInstancesProcessNegativeRoleInstanceFail() { string roleName = "WebRole1"; using (FileSystemHelper files = new FileSystemHelper(this)) { AzureService service = new AzureService(files.RootPath, serviceName, null); Testing.AssertThrows<ArgumentException>(() => service.SetRoleInstances(service.Paths, roleName, -1), string.Format(Resources.InvalidInstancesCount, roleName)); } }
public void AzureServiceAddNewWorkerRoleTest() { using (FileSystemHelper files = new FileSystemHelper(this)) { AzureService service = new AzureService(files.RootPath, serviceName, null); RoleInfo workerRole = service.AddWorkerRole("MyWorkerRole", 10); AzureAssert.AzureServiceExists(Path.Combine(files.RootPath, serviceName), Resources.GeneralScaffolding, serviceName, workerRoles: new WorkerRoleInfo[] { (WorkerRoleInfo)workerRole }, workerScaff: Path.Combine(Resources.NodeScaffolding, Resources.WorkerRole), roles: new RoleInfo[] { workerRole }); } }
public void NewAzureServiceWithInvalidNames() { using (FileSystemHelper files = new FileSystemHelper(this)) { foreach (string name in Data.InvalidServiceNames) { cmdlet.ServiceName = name; Testing.AssertThrows<ArgumentException>(() => cmdlet.ExecuteCmdlet()); } } }
public void CreateLocalPackageWithPHPWorkerRoleTest() { using (FileSystemHelper files = new FileSystemHelper(this)) { CloudServiceProject service = new CloudServiceProject(files.RootPath, serviceName, null); service.AddWorkerRole(Data.PHPWorkerRoleScaffoldingPath); service.CreatePackage(DevEnv.Local); AzureAssert.ScaffoldingExists(Path.Combine(service.Paths.LocalPackage, @"roles\WorkerRole1\approot"), Path.Combine(Resources.PHPScaffolding, Resources.WorkerRole)); } }
public void TestGetRuntimes() { using (FileSystemHelper files = new FileSystemHelper(this)) { AzureService service = new AzureService(files.RootPath, serviceName, null); service.AddWebRole(Resources.NodeScaffolding); string manifest = RuntimePackageHelper.GetTestManifest(files); CloudRuntimeCollection collection = service.GetCloudRuntimes(service.Paths, manifest); RuntimePackageHelper.ValidateRuntimesMatchManifest(manifest, collection); } }
public NodeModuleSystemDependency(string name, NodeModulesHelper nodeModulesHelper, FileSystemHelper fileSystemHelper) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } Name = name; _nodeModulesHelper = nodeModulesHelper; _fileSystemHelper = fileSystemHelper; }
public void TestSetAzureRuntimeInvalidRuntimeVersion() { using (FileSystemHelper files = new FileSystemHelper(this)) { AzureService service = new AzureService(files.RootPath, serviceName, null); service.AddWebRole(Resources.NodeScaffolding); new SetAzureServiceProjectRoleCommand().SetAzureRuntimesProcess("WebRole1", "node", "0.8.99", service.Paths.RootPath, RuntimePackageHelper.GetTestManifest(files)); new SetAzureServiceProjectRoleCommand().SetAzureRuntimesProcess("WebRole1", "iisnode", "0.9.99", service.Paths.RootPath, RuntimePackageHelper.GetTestManifest(files)); VerifyInvalidPackageJsonVersion(service.Paths.RootPath, "WebRole1", "node", "*"); VerifyInvalidPackageJsonVersion(service.Paths.RootPath, "WebRole1", "iisnode", "*"); } }
public void GetNextPortNodeWebRoleNull() { using (FileSystemHelper files = new FileSystemHelper(this)) { int expectedPort = int.Parse(Resources.DefaultPort); AzureService service = new AzureService(files.RootPath, serviceName, null); service.AddWorkerRole(Data.NodeWorkerRoleScaffoldingPath); service = new AzureService(service.Paths.RootPath, null); int nextPort = service.Components.GetNextPort(); Assert.AreEqual<int>(expectedPort, nextPort); } }
public void Map_Path_Virtual_Path() { var url = "~/Js/Test1.js"; var helper = new FileSystemHelper( Mock.Of<IApplicationEnvironment>(), Mock.Of<IHostingEnvironment>(x => x.WebRootPath == "C:\\MySolution\\MyProject"), Mock.Of<ISmidgeConfig>()); var result = helper.MapPath(url); Assert.Equal("C:\\MySolution\\MyProject\\Js\\Test1.js", result); }
public void Normalize_Web_Path_External_Schemaless() { var url = "//test.com/hello.js"; var helper = new FileSystemHelper( Mock.Of<IApplicationEnvironment>(), Mock.Of<IHostingEnvironment>(x => x.WebRootPath == "C:\\MySolution\\MyProject"), Mock.Of<ISmidgeConfig>()); var result = helper.NormalizeWebPath(url, Mock.Of<HttpRequest>(x => x.Scheme == "http")); Assert.Equal("http://test.com/hello.js", result); }
public void CreateLocalPackageWithNodeWorkerRoleTest() { using (FileSystemHelper files = new FileSystemHelper(this)) { string standardOutput; string standardError; AzureService service = new AzureService(files.RootPath, serviceName, null); service.AddWorkerRole(Resources.NodeScaffolding); service.CreatePackage(DevEnv.Local, out standardOutput, out standardError); AzureAssert.ScaffoldingExists(Path.Combine(service.Paths.LocalPackage, @"roles\WorkerRole1\approot"), Path.Combine(Resources.NodeScaffolding, Resources.WorkerRole)); } }
public void AzureSetDeploymentSlotProcessTestsInvalidFail() { using (FileSystemHelper files = new FileSystemHelper(this)) { // Create new empty settings file // ServicePathInfo paths = new ServicePathInfo(files.RootPath); ServiceSettings settings = new ServiceSettings(); settings.Save(paths.Settings); Testing.AssertThrows<ArgumentException>(() => new SetAzureDeploymentSlotCommand().SetAzureDeploymentSlotProcess("MyHome", paths.Settings), string.Format(Resources.InvalidServiceSettingElement, "Slot")); } }
public void AzureSetDeploymentLocationProcessTestsEmptyFail() { using (FileSystemHelper files = new FileSystemHelper(this)) { // Create new empty settings file // ServicePathInfo paths = new ServicePathInfo(files.RootPath); ServiceSettings settings = new ServiceSettings(); settings.Save(paths.Settings); Testing.AssertThrows<ArgumentException>(() => new SetAzureDeploymentLocationCommand().SetAzureDeploymentLocationProcess(string.Empty, paths.Settings), string.Format(Resources.InvalidOrEmptyArgumentMessage, "Location")); } }
internal static async Task Run() { TimeTaken.Start(); foreach (FileInfo inFile in SourceFiles) { FileInfo outFile = new FileInfo(inFile.FullName.Replace(inFile.DirectoryName, Program.Settings.DestinationDirectory.FullName) .Replace(inFile.Extension, "." + Program.Settings.ConvertToNonAlphaValue.ToString().ToLower())); if (!inFile.Extension.ContainsAny(".png", ".jpg", ".bmp", ".gif")) { if (Program.Settings.CopySkippedFiles) { await FileSystemHelper.Copy(inFile, new FileInfo(outFile.FullName.Replace(outFile.Extension, inFile.Extension)), true); } IncompatibleFilesCopiedOver++; if (!Program.CommandMode) { Program.Form.IncrementOverallProgress(); } continue; } if (!Program.CommandMode) { Program.Form.Invoke((MethodInvoker) delegate() { Program.Form.CurrentFileLabel.Text = "File: " + inFile.Name; }); } using (FileStream inStream = await FileIOHelper.OpenStream(inFile)) { byte[] imgData = new byte[inStream.Length]; await inStream.ReadAsync(imgData); using MemoryStream memStr = new MemoryStream(imgData); using Bitmap map = new Bitmap(memStr); bool isAlphaPresent = map.PixelFormat == PixelFormat.Format16bppArgb1555 || map.PixelFormat == PixelFormat.Format32bppArgb || map.PixelFormat == PixelFormat.Format32bppPArgb || map.PixelFormat == PixelFormat.Format64bppArgb || map.PixelFormat == PixelFormat.Format64bppPArgb; if (Program.Settings.DownsizeLargerResolutionImages && (map.Width <= Program.Settings.TargetImageWidth || map.Height <= Program.Settings.TargetImageHeight)) { if (Program.Settings.CopySkippedFiles) { await FileSystemHelper.Copy(inFile, new FileInfo(outFile.FullName.Replace(outFile.Extension, inFile.Extension)), true); } if (!Program.CommandMode) { Program.Form.IncrementOverallProgress(); } continue; } if (map.Width != map.Height && Program.Settings.OnlyPassSquareImages) { if (!Program.CommandMode) { Program.Form.IncrementOverallProgress(); } continue; } if (Program.Settings.UseAlphaFormatOnly || isAlphaPresent) { outFile = new FileInfo(inFile.FullName.Replace(inFile.DirectoryName, Program.Settings.DestinationDirectory.FullName) .Replace(inFile.Extension, "." + Program.Settings.ConvertToAlphaValue.ToString().ToLower())); } using FileStream outStream = outFile.Create(); using (Image image = Image.Load(imgData, out IImageFormat format)) { string ConvertToAlphaString = Program.Settings.ConvertToAlphaValue.ToString(); string ConvertToNonAlphaString = Program.Settings.ConvertToNonAlphaValue.ToString(); image.Mutate(c => { c.Resize(Program.Settings.TargetImageWidth != 0 ? Program.Settings.TargetImageWidth : map.Width, Program.Settings.TargetImageHeight != 0 ? Program.Settings.TargetImageHeight : map.Height); }); if (Program.Settings.UseAlphaFormatOnly || isAlphaPresent) { ConvertTransparentFormat(); } else { ConvertNonTransparentFormat(); } ProcessedImageCount++; void ConvertNonTransparentFormat() { if (ConvertToNonAlphaString == "JPG") { image.SaveAsJpeg(outStream, new JpegEncoder { Quality = 100 - Program.Settings.CompressionLevel }); LogConversionState(); } else if (ConvertToNonAlphaString == "BMP") { image.SaveAsBmp(outStream); LogConversionState(); } } void ConvertTransparentFormat() { if (ConvertToAlphaString == "PNG") { image.SaveAsPng(outStream, new PngEncoder { CompressionLevel = Program.Settings.CompressionLevel == 0 ? PngCompressionLevel.Level0 : Program.Settings.CompressionLevel == 10 ? PngCompressionLevel.Level1 : Program.Settings.CompressionLevel == 20 ? PngCompressionLevel.Level2 : Program.Settings.CompressionLevel == 30 ? PngCompressionLevel.Level3 : Program.Settings.CompressionLevel == 40 ? PngCompressionLevel.Level4 : Program.Settings.CompressionLevel == 50 ? PngCompressionLevel.Level5 : Program.Settings.CompressionLevel == 60 ? PngCompressionLevel.Level6 : Program.Settings.CompressionLevel == 70 ? PngCompressionLevel.Level7 : Program.Settings.CompressionLevel == 80 ? PngCompressionLevel.Level8 : Program.Settings.CompressionLevel == 90 ? PngCompressionLevel.Level9 : PngCompressionLevel.Level9 }); LogConversionState(); } else if (ConvertToAlphaString == "GIF") { image.SaveAsGif(outStream); LogConversionState(); } } void LogConversionState() { if (Program.Settings.TargetImageWidth != 0 || Program.Settings.TargetImageHeight != 0 && outFile.Extension != inFile.Extension) { AddLog("Resized " + inFile.Name + " to " + Program.Settings.TargetImageWidth + "x" + Program.Settings.TargetImageHeight + " & converted to " + outFile.Extension.ToUpper()[1..] + " | Reduction " + GetPercentageReduction().ToString("0.00") + "%."); }
public void SendEmailNotification( string subject, string body, List <string> fileAttachments, List <string> emailRecipients, bool sendAsync, bool sendLater) { if (!_enabled) { return; } MailMessage email = GetMailMessage(subject, body); if (emailRecipients != null) { emailRecipients.ForEach(p => email.To.Add(new MailAddress(p))); } List <MemoryStream> streams = null; try { if (fileAttachments != null) { streams = new List <MemoryStream>(); foreach (string filePath in fileAttachments) { FileSystemHelper.ValidateFileExists(filePath); byte[] fileBytes = File.ReadAllBytes(filePath); MemoryStream ms = new MemoryStream(fileBytes); streams.Add(ms); string fileName = Path.GetFileName(filePath); email.Attachments.Add(new Attachment(ms, fileName, MediaTypeNames.Text.Plain)); } } if (sendLater) { SaveToDB(email, fileAttachments); return; } StringBuilder logMessage = new StringBuilder(); logMessage.AppendLine("Sending Notification Email"); logMessage.AppendLine(string.Format("Subject: {0}", subject)); email.To.ToList().ForEach(p => logMessage.AppendLine(p.Address)); GOC.Instance.Logger.LogMessage(new LogMessage(logMessage.ToString(), LogMessageType.Information, LoggingLevel.Maximum)); if (sendAsync) { _smtpClient.SendAsync(email, email); } else { _smtpClient.Send(email); } } finally { if (streams != null) { foreach (MemoryStream ms in streams) { ms.Close(); ms.Dispose(); } } } }
public void SetupTest() { CmdletSubscriptionExtensions.SessionManager = new InMemorySessionManager(); files = new FileSystemHelper(this); //files.CreateAzureSdkDirectoryAndImportPublishSettings(); }
public void ValidateSite(ref Site site) { string[] bindingsUserInputs = Request.Form.BindingsUserInput.ToString().Split(','); string[] bindingsCertificateThumbprint = Request.Form.BindingsCertificateThumbprint.ToString().Split(','); string[] bindingsIpAddresses = Request.Form.BindingsIpAddress.ToString().Split(','); site.Bindings = new List <Binding>(); var certificates = SiteManager.GetCertificates(); for (var i = 0; i < bindingsUserInputs.Length; i++) { if (string.IsNullOrWhiteSpace(bindingsUserInputs[i])) { continue; } var isValid = true; var userinput = bindingsUserInputs[i]; var finalizedHost = BindingHelper.SafeFinializeBinding(userinput); var ip = bindingsIpAddresses[i]; if (string.IsNullOrWhiteSpace(ip)) { ip = "*"; } if (finalizedHost == null) { AddPropertyError("bindingsuserinput[" + i + "]", "The binding is invalid."); isValid = false; } else if (!BindingHelper.IsIpValid(ip)) { AddPropertyError("bindingsipaddress[" + i + "]", string.Format("The IP {0} is not valid.", ip)); isValid = false; } else if (SiteManager.IsBindingInUse(finalizedHost, bindingsIpAddresses[i], site.IisId)) { AddPropertyError("bindingsuserinput[" + i + "]", string.Format("The binding {0} is already in use.", finalizedHost)); isValid = false; } Binding binding; if (isValid) { var certificate = certificates.SingleOrDefault(x => x.Thumbprint == bindingsCertificateThumbprint[i]); binding = BindingHelper.ConvertToBinding(finalizedHost, ip, certificate); } else { binding = new Binding() { CertificateName = bindingsCertificateThumbprint[i], UserInput = bindingsUserInputs[i], IpAddress = ip }; } site.Bindings.Add(binding); } if (!site.Bindings.Any()) { AddPropertyError("bindingsipaddress[0]", "Minimum one binding is required."); site.Bindings.Add(new Binding() { UserInput = "" }); } if (string.IsNullOrWhiteSpace(site.Name)) { AddPropertyError("name", "Name is required."); } var existingSite = SiteManager.GetSiteByName(site.Name); if (site.Name != null && existingSite != null && existingSite.IisId != site.IisId) { AddPropertyError("name", "There's already a site with this name."); } if (string.IsNullOrWhiteSpace(site.SitePath)) { AddPropertyError("sitepath", "Site path is required."); } else { if (!FileSystemHelper.IsPathValid(site.SitePath)) { AddPropertyError("sitepath", "Path cannot contain the following characters: ?, ;, :, @, &, =, +, $, ,, |, \", <, >, *."); } else { if (!FileSystemHelper.DirectoryExists(site.SitePath)) { FileSystemHelper.CreateDirectory(site.SitePath); } } } }
public JsonResult FileUpload(int id) { var success = false; string error = null; string tempFile = ""; if (Services.Permissions.Authorize(StandardPermissionProvider.ManageImports)) { var postedFile = Request.ToPostedFileResult(); if (postedFile != null) { if (id == 0) { var path = Path.Combine(FileSystemHelper.TempDirTenant(), postedFile.FileName); FileSystemHelper.Delete(path); success = postedFile.Stream.ToFile(path); if (success) { success = IsValidImportFile(path, out error); if (success) { tempFile = postedFile.FileName; } } } else { var profile = _importProfileService.GetImportProfileById(id); if (profile != null) { var files = profile.GetImportFiles(); if (files.Any()) { var extension = Path.GetExtension(files.First()); if (!postedFile.FileExtension.IsCaseInsensitiveEqual(extension)) { error = T("Admin.Common.FileTypeMustEqual", extension.Substring(1).ToUpper()); } } if (!error.HasValue()) { var folder = profile.GetImportFolder(true, true); var fileName = Path.GetFileName(postedFile.FileName); var path = Path.Combine(folder, fileName); success = postedFile.Stream.ToFile(path); if (success) { success = IsValidImportFile(path, out error); if (success) { var fileType = (Path.GetExtension(fileName).IsCaseInsensitiveEqual(".xlsx") ? ImportFileType.XLSX : ImportFileType.CSV); if (fileType != profile.FileType) { profile.FileType = fileType; _importProfileService.UpdateImportProfile(profile); } } } } } } } } else { error = T("Admin.AccessDenied.Description"); } if (!success && error.IsEmpty()) { error = T("Admin.Common.UploadFileFailed"); } if (error.HasValue()) { NotifyError(error); } return(Json(new { success = success, tempFile = tempFile, error = error })); }
//classes injected using dependancy injection public VoiceRecognitionHandler(FileSystemHelper fileSystemHelper, VoiceRecognitionHelper voiceRecognitionHelper, CPUHelper cpuHelper) { _fileSystemHelper = fileSystemHelper; _voiceRecognitionHelper = voiceRecognitionHelper; _cpuHelper = cpuHelper; }
public void Execute(TaskExecutionContext ctx) { FileSystemHelper.TempCleanup(); }
private void AddPHPRoleTest(int webRole, int workerRole, int order = 0) { using (FileSystemHelper files = new FileSystemHelper(this)) { AzureServiceWrapper wrappedService = new AzureServiceWrapper(files.RootPath, serviceName, null); CloudServiceProject service = new CloudServiceProject(Path.Combine(files.RootPath, serviceName), null); WebRoleInfo[] webRoles = null; if (webRole > 0) { webRoles = new WebRoleInfo[webRole]; for (int i = 0; i < webRoles.Length; i++) { webRoles[i] = new WebRoleInfo(string.Format("{0}{1}", Resources.WebRole, i + 1), 1); } } WorkerRoleInfo[] workerRoles = null; if (workerRole > 0) { workerRoles = new WorkerRoleInfo[workerRole]; for (int i = 0; i < workerRoles.Length; i++) { workerRoles[i] = new WorkerRoleInfo(string.Format("{0}{1}", Resources.WorkerRole, i + 1), 1); } } RoleInfo[] roles = (webRole + workerRole > 0) ? new RoleInfo[webRole + workerRole] : null; if (order == 0) { for (int i = 0, w = 0, wo = 0; i < webRole + workerRole;) { if (w++ < webRole) { roles[i++] = wrappedService.AddWebRole(Data.PHPWebRoleScaffoldingPath); } if (wo++ < workerRole) { roles[i++] = wrappedService.AddWorkerRole(Data.PHPWorkerRoleScaffoldingPath); } } } else if (order == 1) { for (int i = 0, w = 0, wo = 0; i < webRole + workerRole;) { if (wo++ < workerRole) { roles[i++] = wrappedService.AddWorkerRole(Data.PHPWorkerRoleScaffoldingPath); } if (w++ < webRole) { roles[i++] = wrappedService.AddWebRole(Data.PHPWebRoleScaffoldingPath); } } } else if (order == 2) { wrappedService.AddRole(Data.PHPWebRoleScaffoldingPath, Data.PHPWorkerRoleScaffoldingPath, webRole, workerRole); webRoles.CopyTo(roles, 0); Array.Copy(workerRoles, 0, roles, webRole, workerRoles.Length); } else if (order == 3) { wrappedService.AddRole(Data.PHPWebRoleScaffoldingPath, Data.PHPWorkerRoleScaffoldingPath, 0, workerRole); workerRoles.CopyTo(roles, 0); wrappedService.AddRole(Data.PHPWebRoleScaffoldingPath, Data.PHPWorkerRoleScaffoldingPath, webRole, 0); Array.Copy(webRoles, 0, roles, workerRole, webRoles.Length); } else { throw new ArgumentException("value for order parameter is unknown"); } AzureAssert.AzureServiceExists(Path.Combine(files.RootPath, serviceName), Resources.GeneralScaffolding, serviceName, webRoles: webRoles, workerRoles: workerRoles, webScaff: Data.PHPWebRoleScaffoldingPath, workerScaff: Data.PHPWorkerRoleScaffoldingPath, roles: roles); } }
private void ImportCoreOuter(DataImporterContext ctx) { if (ctx.Request.Profile == null || !ctx.Request.Profile.Enabled) { return; } var logPath = ctx.Request.Profile.GetImportLogPath(); FileSystemHelper.Delete(logPath); using (var logger = new TraceLogger(logPath)) { var scopes = new List <IDisposable>(); try { _dbCache.Enabled = false; scopes.Add(_localizedEntityService.BeginScope()); scopes.Add(_urlRecordService.BeginScope()); ctx.Log = logger; ctx.ExecuteContext.Request = ctx.Request; ctx.ExecuteContext.DataExchangeSettings = _dataExchangeSettings.Value; ctx.ExecuteContext.Services = _services; ctx.ExecuteContext.Log = logger; ctx.ExecuteContext.Languages = _languageService.GetAllLanguages(true); ctx.ExecuteContext.UpdateOnly = ctx.Request.Profile.UpdateOnly; ctx.ExecuteContext.KeyFieldNames = ctx.Request.Profile.KeyFieldNames.SplitSafe(","); ctx.ExecuteContext.ImportFolder = ctx.Request.Profile.GetImportFolder(); ctx.ExecuteContext.ExtraData = XmlHelper.Deserialize <ImportExtraData>(ctx.Request.Profile.ExtraData); { var mapConverter = new ColumnMapConverter(); ctx.ExecuteContext.ColumnMap = mapConverter.ConvertFrom <ColumnMap>(ctx.Request.Profile.ColumnMapping) ?? new ColumnMap(); } var files = ctx.Request.Profile.GetImportFiles(); if (files.Count == 0) { throw new SmartException("No files to import."); } if (!HasPermission(ctx)) { throw new SmartException("You do not have permission to perform the selected import."); } ctx.Importer = _importerFactory(ctx.Request.Profile.EntityType); _services.EventPublisher.Publish(new ImportExecutingEvent(ctx.ExecuteContext)); files.ForEach(x => ImportCoreInner(ctx, x)); } catch (Exception exception) { ctx.ExecuteContext.Result.AddError(exception); } finally { try { _dbCache.Enabled = true; scopes.Each(x => x.Dispose()); _services.EventPublisher.Publish(new ImportExecutedEvent(ctx.ExecuteContext)); } catch (Exception exception) { ctx.ExecuteContext.Result.AddError(exception); } try { // database context sharing problem: if there are entities in modified state left by the provider due to SaveChanges failure, // then all subsequent SaveChanges would fail too (e.g. IImportProfileService.UpdateImportProfile, IScheduledTaskService.UpdateTask...). // so whatever it is, detach\dispose all what the tracker still has tracked. _services.DbContext.DetachAll(false); } catch (Exception exception) { ctx.ExecuteContext.Result.AddError(exception); } try { SendCompletionEmail(ctx); } catch (Exception exception) { ctx.ExecuteContext.Result.AddError(exception); } try { ctx.ExecuteContext.Result.EndDateUtc = DateTime.UtcNow; LogResult(ctx); } catch (Exception exception) { logger.ErrorsAll(exception); } try { ctx.Request.Profile.ResultInfo = XmlHelper.Serialize(ctx.ExecuteContext.Result.Clone()); _importProfileService.UpdateImportProfile(ctx.Request.Profile); } catch (Exception exception) { logger.ErrorsAll(exception); } try { ctx.Request.CustomData.Clear(); ctx.Log = null; } catch (Exception exception) { logger.ErrorsAll(exception); } } } }
public override Task Load() { return(Task.Run(() => { string path = UOFileManager.GetUOFilePath("texmaps.mul"); string pathidx = UOFileManager.GetUOFilePath("texidx.mul"); FileSystemHelper.EnsureFileExists(path); FileSystemHelper.EnsureFileExists(pathidx); _file = new UOFileMul(path, pathidx, Constants.MAX_LAND_TEXTURES_DATA_INDEX_COUNT, 10); _file.FillEntries(ref Entries); string pathdef = UOFileManager.GetUOFilePath("TexTerr.def"); if (!File.Exists(pathdef)) { return; } using (DefReader defReader = new DefReader(pathdef)) { while (defReader.Next()) { int index = defReader.ReadInt(); if (index < 0 || index >= Constants.MAX_LAND_TEXTURES_DATA_INDEX_COUNT) { continue; } int[] group = defReader.ReadGroup(); if (group == null) { continue; } for (int i = 0; i < group.Length; i++) { int checkindex = group[i]; if (checkindex < 0 || checkindex >= Constants.MAX_LAND_TEXTURES_DATA_INDEX_COUNT) { continue; } Entries[index] = Entries[checkindex]; } } } //using (StreamReader reader = new StreamReader(File.OpenRead(pathdef))) //{ // string line; // while ((line = reader.ReadLine()) != null) // { // line = line.Trim(); // if (line.Length <= 0 || line[0] == '#') // continue; // string[] defs = line.Split(new[] // { // '\t', ' ', '#' // }, StringSplitOptions.RemoveEmptyEntries); // if (defs.Length < 2) // continue; // int index = int.Parse(defs[0]); // if (index < 0 || index >= TEXTMAP_COUNT) // continue; // int first = defs[1].IndexOf("{"); // int last = defs[1].IndexOf("}"); // string[] newdef = defs[1].Substring(first + 1, last - 1).Split(new[] // { // ' ', ',' // }, StringSplitOptions.RemoveEmptyEntries); // foreach (string s in newdef) // { // int checkindex = int.Parse(s); // if (checkindex < 0 || checkindex >= TEXTMAP_COUNT) // continue; // _file.Entries[index] = _file.Entries[checkindex]; // } // } //} })); }
internal static void RunIsolated(string application = null, string target = null, IsolatedPackageAction isolatedAction = null) { using (var tpmClient = new ExecutorClient()) { var packages = new Installation(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)).GetPackages(); PackageDef findPackageWithFile(string file) { foreach (var package in packages) { foreach (var pkgfile in package.Files) { var filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), pkgfile.FileName); if (string.Equals(NormalizePath(filePath), NormalizePath(file), StringComparison.OrdinalIgnoreCase)) { return(package); } } } return(null); } var exec = application ?? Assembly.GetEntryAssembly().Location; PackageDef pkg = findPackageWithFile(Path.GetFullPath(exec)); if (pkg == null) { throw new InvalidOperationException($"{Path.GetFileName(exec)} was not installed through a package."); } var dependencies = pkg.Dependencies.ToList(); if (isolatedAction != null) { // If the executing IsolatedPackageAction does not origin from OpenTAP package, we need to include it when we copy and run isolated var actionAsm = isolatedAction.GetType().Assembly.Location; PackageDef isolatedActionPackage = findPackageWithFile(Path.GetFullPath(actionAsm)); if (isolatedActionPackage == null) { throw new InvalidOperationException($"{Path.GetFileName(actionAsm)} was not installed through a package."); } if (pkg.Name != isolatedActionPackage.Name) { if (!dependencies.Any(p => p.Name == isolatedActionPackage.Name)) { dependencies.Add(new PackageDependency(isolatedActionPackage.Name, new VersionSpecifier(isolatedActionPackage.Version, VersionMatchBehavior.Compatible))); } } } // when installing/uninstalling packages we might need to use custom package actions as well. var extraDependencies = PluginManager.GetPlugins <ICustomPackageAction>().Select(t => t.Assembly.Location).Distinct().ToList(); foreach (var exDep in extraDependencies) { var package = findPackageWithFile(exDep); if (package != null && !dependencies.Any(p => p.Name == package.Name)) { dependencies.Add(new PackageDependency(package.Name, new VersionSpecifier(package.Version, VersionMatchBehavior.Compatible))); } } var deps = OpenTap.Utils.FlattenHeirarchy(dependencies, dep => (IEnumerable <PackageDependency>)packages.FirstOrDefault(x => x.Name == dep.Name)?.Dependencies ?? Array.Empty <PackageDependency>(), distinct: true); if (false == deps.Any(x => x.Name == pkg.Name)) { deps.Add(new PackageDependency(pkg.Name, new VersionSpecifier(pkg.Version, VersionMatchBehavior.Compatible))); } bool force = isolatedAction?.Force ?? false; List <string> allFiles = new List <string>(); foreach (var d in deps) { var availPackages = packages.Where(p => p.Name == d.Name); var package = availPackages.FirstOrDefault(p => d.Version.IsCompatible(p.Version)); if (package == null) { package = availPackages.FirstOrDefault(); if (!force) { if (package != null) { throw new Exception($"Cannot find compatible dependency '{d.Name}' {d.Version}. Version {package.Version} is installed."); } throw new Exception($"Cannot find needed dependency '{d.Name}'."); } log.Warning("Unable to find compatible package, using {0} v{1} instead.", package.Name, package.Version); } var defPath = String.Join("/", PackageDef.PackageDefDirectory, package.Name, PackageDef.PackageDefFileName); if (File.Exists(defPath)) { allFiles.Add(defPath); } var fs = package.Files; var brokenPackages = new HashSet <string>(); foreach (var file in fs) { string loc = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), file.FileName); if (!File.Exists(loc)) { brokenPackages.Add(package.Name); log.Debug($"Could not find file '{loc}' part of package '{package.Name}'."); continue; } allFiles.Add(file.FileName); } foreach (var name in brokenPackages) { log.Warning($"Package '{name}' has missing files and is broken."); } } string tempFolder = Path.GetFullPath(FileSystemHelper.CreateTempDirectory()); foreach (var _loc in allFiles.Distinct()) { string loc = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), _loc); var newloc = Path.Combine(tempFolder, _loc); OpenTap.FileSystemHelper.EnsureDirectory(newloc); if (File.Exists(newloc)) { continue; } File.Copy(loc, newloc); } { // tell TPM Server to start new app. var loc = application ?? Assembly.GetEntryAssembly().Location; if (string.Equals(".dll", Path.GetExtension(loc), StringComparison.OrdinalIgnoreCase)) { //.netcore wierdness. loc = Path.ChangeExtension(loc, "exe"); if (File.Exists(loc) == false) { loc = loc.Substring(0, loc.Length - ".exe".Length); } } var newname = Path.Combine(tempFolder, Path.GetFileName(loc)); newname = $"\"{newname}\""; // there could be whitespace in the name. // now that we start from a different dir, we need to supply a --target argument if (target != null) { newname = $"{newname} --target \"{target}\""; } tpmClient.MessageServer("run " + newname); tpmClient.Dispose(); } } }
public void PublishAzureServiceRemovesNodeLogs() { // Create a temp directory that we'll use to "publish" our service using (FileSystemHelper files = new FileSystemHelper(this) { EnableMonitoring = true }) { // Import our default publish settings files.CreateAzureSdkDirectoryAndImportPublishSettings(); // Create a new channel to mock the calls to Azure and // determine all of the results that we'll need. SimpleServiceManagement channel = new SimpleServiceManagement(); // Create a new service that we're going to publish string serviceName = "TEST_SERVICE_NAME"; NewAzureServiceProjectCommand newService = new NewAzureServiceProjectCommand(); newService.NewAzureServiceProcess(files.RootPath, serviceName); string servicePath = files.CreateDirectory(serviceName); // Add a web role AddAzureNodeWebRoleCommand newWebRole = new AddAzureNodeWebRoleCommand(); string webRoleName = "NODE_WEB_ROLE"; newWebRole.AddAzureNodeWebRoleProcess(webRoleName, 2, servicePath); string webRolePath = Path.Combine(servicePath, webRoleName); // Add a worker role AddAzureNodeWorkerRoleCommand newWorkerRole = new AddAzureNodeWorkerRoleCommand(); string workerRoleName = "NODE_WORKER_ROLE"; newWorkerRole.AddAzureNodeWorkerRoleProcess(workerRoleName, 2, servicePath); string workerRolePath = Path.Combine(servicePath, workerRoleName); // Add second web and worker roles that we won't add log // entries to new AddAzureNodeWebRoleCommand() .AddAzureNodeWebRoleProcess("SECOND_WEB_ROLE", 2, servicePath); new AddAzureNodeWorkerRoleCommand() .AddAzureNodeWorkerRoleProcess("SECOND_WORKER_ROLE", 2, servicePath); // Add fake logs directories for server.js string logName = "server.js.logs"; string logPath = Path.Combine(webRolePath, logName); Directory.CreateDirectory(logPath); File.WriteAllText(Path.Combine(logPath, "0.txt"), "secret web role debug details were logged here"); logPath = Path.Combine(Path.Combine(workerRolePath, "NestedDirectory"), logName); Directory.CreateDirectory(logPath); File.WriteAllText(Path.Combine(logPath, "0.txt"), "secret worker role debug details were logged here"); // Get the publishing process started by creating the package PublishAzureServiceProjectCommand publishService = new PublishAzureServiceProjectCommand(channel); publishService.InitializeSettingsAndCreatePackage(servicePath); // Rip open the package and make sure we can't find the log string packagePath = Path.Combine(servicePath, "cloud_package.cspkg"); using (Package package = Package.Open(packagePath)) { // Make sure the web role and worker role packages don't // have any files with server.js.logs in the name Action <string> validateRole = roleName => { PackagePart rolePart = package.GetParts().Where(p => p.Uri.ToString().Contains(roleName)).First(); using (Package rolePackage = Package.Open(rolePart.GetStream())) { Assert.IsFalse( rolePackage.GetParts().Any(p => p.Uri.ToString().Contains(logName)), "Found {0} part in {1} package!", logName, roleName); } }; validateRole(webRoleName); validateRole(workerRoleName); } } }
public void TestResolveRuntimePackageUrls() { // Create a temp directory that we'll use to "publish" our service using (FileSystemHelper files = new FileSystemHelper(this) { EnableMonitoring = true }) { // Import our default publish settings files.CreateAzureSdkDirectoryAndImportPublishSettings(); // Create a new service that we're going to publish string serviceName = "TEST_SERVICE_NAME"; string rootPath = files.CreateNewService(serviceName); // Add web and worker roles string defaultWebRoleName = "WebRoleDefault"; addNodeWebCmdlet = new AddAzureNodeWebRoleCommand() { RootPath = rootPath, CommandRuntime = mockCommandRuntime, Name = defaultWebRoleName, Instances = 2 }; addNodeWebCmdlet.ExecuteCmdlet(); string defaultWorkerRoleName = "WorkerRoleDefault"; addNodeWorkerCmdlet = new AddAzureNodeWorkerRoleCommand() { RootPath = rootPath, CommandRuntime = mockCommandRuntime, Name = defaultWorkerRoleName, Instances = 2 }; addNodeWorkerCmdlet.ExecuteCmdlet(); AddAzureNodeWebRoleCommand matchWebRole = addNodeWebCmdlet; string matchWebRoleName = "WebRoleExactMatch"; addNodeWebCmdlet = new AddAzureNodeWebRoleCommand() { RootPath = rootPath, CommandRuntime = mockCommandRuntime, Name = matchWebRoleName, Instances = 2 }; addNodeWebCmdlet.ExecuteCmdlet(); AddAzureNodeWorkerRoleCommand matchWorkerRole = addNodeWorkerCmdlet; string matchWorkerRoleName = "WorkerRoleExactMatch"; addNodeWorkerCmdlet = new AddAzureNodeWorkerRoleCommand() { RootPath = rootPath, CommandRuntime = mockCommandRuntime, Name = matchWorkerRoleName, Instances = 2 }; addNodeWorkerCmdlet.ExecuteCmdlet(); AddAzureNodeWebRoleCommand overrideWebRole = addNodeWebCmdlet; string overrideWebRoleName = "WebRoleOverride"; addNodeWebCmdlet = new AddAzureNodeWebRoleCommand() { RootPath = rootPath, CommandRuntime = mockCommandRuntime, Name = overrideWebRoleName, Instances = 2 }; addNodeWebCmdlet.ExecuteCmdlet(); AddAzureNodeWorkerRoleCommand overrideWorkerRole = addNodeWorkerCmdlet; string overrideWorkerRoleName = "WorkerRoleOverride"; addNodeWorkerCmdlet = new AddAzureNodeWorkerRoleCommand() { RootPath = rootPath, CommandRuntime = mockCommandRuntime, Name = overrideWorkerRoleName, Instances = 2 }; addNodeWorkerCmdlet.ExecuteCmdlet(); string webRole2Name = "WebRole2"; AddAzureNodeWebRoleCommand addAzureWebRole = new AddAzureNodeWebRoleCommand() { RootPath = rootPath, CommandRuntime = mockCommandRuntime, Name = webRole2Name }; addAzureWebRole.ExecuteCmdlet(); CloudServiceProject testService = new CloudServiceProject(rootPath, FileUtilities.GetContentFilePath("Services")); RuntimePackageHelper.SetRoleRuntime(testService.Components.Definition, matchWebRoleName, testService.Paths, version: "0.8.2"); RuntimePackageHelper.SetRoleRuntime(testService.Components.Definition, matchWorkerRoleName, testService.Paths, version: "0.8.2"); RuntimePackageHelper.SetRoleRuntime(testService.Components.Definition, overrideWebRoleName, testService.Paths, overrideUrl: "http://OVERRIDE"); RuntimePackageHelper.SetRoleRuntime(testService.Components.Definition, overrideWorkerRoleName, testService.Paths, overrideUrl: "http://OVERRIDE"); bool exceptionWasThrownOnSettingCacheRole = false; try { string cacheRuntimeVersion = "1.7.0"; testService.AddRoleRuntime(testService.Paths, webRole2Name, Resources.CacheRuntimeValue, cacheRuntimeVersion, RuntimePackageHelper.GetTestManifest(files)); } catch (NotSupportedException) { exceptionWasThrownOnSettingCacheRole = true; } Assert.True(exceptionWasThrownOnSettingCacheRole); testService.Components.Save(testService.Paths); // Get the publishing process started by creating the package testService.ResolveRuntimePackageUrls(RuntimePackageHelper.GetTestManifest(files)); CloudServiceProject updatedService = new CloudServiceProject(testService.Paths.RootPath, null); RuntimePackageHelper.ValidateRoleRuntime(updatedService.Components.Definition, defaultWebRoleName, "http://cdn/node/default.exe;http://cdn/iisnode/default.exe", null); RuntimePackageHelper.ValidateRoleRuntime(updatedService.Components.Definition, defaultWorkerRoleName, "http://cdn/node/default.exe", null); RuntimePackageHelper.ValidateRoleRuntime(updatedService.Components.Definition, matchWorkerRoleName, "http://cdn/node/foo.exe", null); RuntimePackageHelper.ValidateRoleRuntime(updatedService.Components.Definition, matchWebRoleName, "http://cdn/node/foo.exe;http://cdn/iisnode/default.exe", null); RuntimePackageHelper.ValidateRoleRuntime(updatedService.Components.Definition, overrideWebRoleName, null, "http://OVERRIDE"); RuntimePackageHelper.ValidateRoleRuntime(updatedService.Components.Definition, overrideWorkerRoleName, null, "http://OVERRIDE"); } }
static void Main(string[] args) { string login = "******"; string password = "******"; do { Console.WriteLine("Enter the login"); string enterLogin = Console.ReadLine(); Console.WriteLine("Enter the password"); string enterPassword = Console.ReadLine(); } while (!Login.Auth(login, password)); if (Login.Auth(login, password)) { User user = new User(); user.Login = login; user.CreationDate = DateTime.Now; Console.WriteLine($"Hello {login}"); Console.WriteLine($"You added at {user.CreationDate.ToString("yyyy-MM-dd")}"); } else { Console.WriteLine("Wrong login and(or) password"); } do { Console.WriteLine(new string('-', 38)); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Please select command "); Console.WriteLine("\t1 - Add file" + Environment.NewLine + "\t2 - Info file" + Environment.NewLine + "\t3 - Show directories and files" + Environment.NewLine + "\t5 - Copy file" + Environment.NewLine + "\t6 - Move file" + Environment.NewLine + "\t7 - Create folder" + Environment.NewLine + "\t8 - Delete file" + Environment.NewLine + "\t0 - Exit"); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(new string('-', 38)); string enteringValue = Console.ReadLine(); if (!int.TryParse(enteringValue, out int command)) { Console.WriteLine("Invalid command"); continue; } switch (command) { case 1: Console.WriteLine("Enter filename"); string filenameAdd = Console.ReadLine(); FileSystemHelper.CreateFileIfNotExist(filenameAdd); continue; case 2: Console.WriteLine("Enter filename"); string filenameInfo = Console.ReadLine(); FileSystemHelper.ShowFileInfo(filenameInfo); continue; case 3: Console.WriteLine("Directories and files"); FileSystemHelper.ShowDirectoryStructure(); continue; case 5: Console.WriteLine("Enter filename"); string filenameCopy = Console.ReadLine(); Console.WriteLine("Enter puth"); string endPuthCopy = Console.ReadLine(); FileSystemHelper.RemoveFileIfExist(filenameCopy, endPuthCopy); continue; case 6: Console.WriteLine("Enter filename"); string filename = Console.ReadLine(); Console.WriteLine("Enter puth"); string endPuth = Console.ReadLine(); FileSystemHelper.RemoveFileIfExist(filename, endPuth); continue; case 7: Console.WriteLine("Enter foldername"); string folderAdd = Console.ReadLine(); FileSystemHelper.CreateFolderIfNotExist(folderAdd); continue; case 9: Console.WriteLine("Enter filename"); string filenameDel = Console.ReadLine(); FileSystemHelper.DeleteFileIfExist(filenameDel); continue; case 0: Console.WriteLine("Do you want to exit y/n?"); string switch_on = Console.ReadLine(); switch (switch_on) { case "y": Environment.Exit(0); break; case "n": continue; default: Console.WriteLine("Repeat answer."); continue; } break; default: Console.WriteLine("Unknown command"); continue; } } while (Login.Auth(login, password)); Console.ReadLine(); }
public virtual ImportProfile InsertImportProfile(string fileName, string name, ImportEntityType entityType) { Guard.ArgumentNotEmpty(() => fileName); if (name.IsEmpty()) { name = GetNewProfileName(entityType); } var task = new ScheduleTask { CronExpression = "0 */24 * * *", Type = typeof(DataImportTask).AssemblyQualifiedNameWithoutVersion(), Enabled = false, StopOnError = false, IsHidden = true }; task.Name = string.Concat(name, " Task"); _scheduleTaskService.InsertTask(task); var profile = new ImportProfile { Name = name, EntityType = entityType, Enabled = true, SchedulingTaskId = task.Id }; if (Path.GetExtension(fileName).IsCaseInsensitiveEqual(".xlsx")) { profile.FileType = ImportFileType.XLSX; } else { profile.FileType = ImportFileType.CSV; } string[] keyFieldNames = null; switch (entityType) { case ImportEntityType.Product: keyFieldNames = ProductImporter.DefaultKeyFields; break; case ImportEntityType.Category: keyFieldNames = CategoryImporter.DefaultKeyFields; break; case ImportEntityType.Customer: keyFieldNames = CustomerImporter.DefaultKeyFields; break; case ImportEntityType.NewsLetterSubscription: keyFieldNames = NewsLetterSubscriptionImporter.DefaultKeyFields; break; } profile.KeyFieldNames = string.Join(",", keyFieldNames); profile.FolderName = SeoHelper.GetSeName(name, true, false) .ToValidPath() .Truncate(_dataExchangeSettings.MaxFileNameLength); profile.FolderName = FileSystemHelper.CreateNonExistingDirectoryName(CommonHelper.MapPath("~/App_Data/ImportProfiles"), profile.FolderName); _importProfileRepository.Insert(profile); task.Alias = profile.Id.ToString(); _scheduleTaskService.UpdateTask(task); _eventPublisher.EntityInserted(profile); return(profile); }
private static void Main(string[] args) { string directoryPath = null; // If path is not provided in startup args // trying to get them from console itself if (args.Length == 0) { Console.WriteLine("No directory path to work with is being provided\r\n" + "Enter it in console then."); directoryPath = Console.ReadLine(); } else { directoryPath = args[0]; } var mtxDir = FileSystemHelper.WorkWithFolder(directoryPath); // Check if Directory is exists and contains needed files CheckDirectoryValidity(mtxDir); var anyErrorsFlag = false; var problematicFiles = new List <string>(); // Process files and gather errors, if occurred foreach (var matrixFile in mtxDir.EnumerateFiles("*.txt")) { var fileProcessingResult = matrixFile.ProcessMatrixFile(); if (!fileProcessingResult.Success) { if (!anyErrorsFlag) { anyErrorsFlag = true; } problematicFiles.Add(matrixFile.PathItemName); Console.WriteLine(fileProcessingResult.ErrorMessage); try { // Try to write same message in *_result.txt file if can fileProcessingResult.ResultFile.WriteToFile(fileProcessingResult.ErrorMessage); } catch { } } Console.WriteLine($"Calculation process for file {matrixFile.PathItemName} is completed successfully!"); } // Move result files to the same folder // NOTE: this done because of performance reasons. At this time we are enumerating files in folder, // not just gather them all in memory and process. This can be optimized in future by multithreading var resultsDir = FileSystemHelper.WorkWithFolder(Path.Combine(directoryPath, "Results")); resultsDir.MoveAllFiles(mtxDir); resultsDir.Delete(); // Show filenames with problems if (anyErrorsFlag) { Console.WriteLine( "Program completed calculations with errors for some files. List of these files:\r\n"); if (problematicFiles.Count > 1) { var fileNamesBuilder = new StringBuilder(); for (var i = 0; i < problematicFiles.Count; i++) { fileNamesBuilder.Append($"{problematicFiles[i]}"); // 5 file names on each line if (i % 5 == 0) { fileNamesBuilder.Append("\r\n"); } } Console.WriteLine(fileNamesBuilder.ToString()); } else { Console.WriteLine(problematicFiles.First()); } } else { Console.WriteLine( "Program completed calculations without errors, result can be found in the same folder " + "were original matrices was (with _result.txt postfix)"); } Console.ReadLine(); }
public List <Gump> ReadGumps() { string path = FileSystemHelper.CreateFolderIfNotExists(Engine.ExePath, "Data", "Profiles", Username, ServerName, CharacterName); string binpath = Path.Combine(path, "gumps.bin"); if (!File.Exists(binpath)) { return(null); } List <Gump> gumps = new List <Gump>(); using (BinaryReader reader = new BinaryReader(File.OpenRead(binpath))) { if (reader.BaseStream.Position + 12 < reader.BaseStream.Length) { uint version = reader.ReadUInt32(); uint empty = reader.ReadUInt32(); int count = reader.ReadInt32(); for (int i = 0; i < count; i++) { try { int typeLen = reader.ReadUInt16(); string typeName = reader.ReadUTF8String(typeLen); int x = reader.ReadInt32(); int y = reader.ReadInt32(); Type type = Type.GetType(typeName, true); Gump gump = (Gump)Activator.CreateInstance(type); gump.Initialize(); gump.Restore(reader); gump.X = x; gump.Y = y; if (gump.LocalSerial != 0) { Engine.UI.SavePosition(gump.LocalSerial, new Point(x, y)); } if (!gump.IsDisposed) { gumps.Add(gump); } } catch (Exception e) { Log.Message(LogTypes.Error, e.Message); } } } } string anchorsPath = Path.Combine(path, "anchors.bin"); if (File.Exists(anchorsPath)) { using (BinaryReader reader = new BinaryReader(File.OpenRead(anchorsPath))) { Engine.AnchorManager.Restore(reader, gumps); } } return(gumps); }
static bool HandleCommandLine(string[] args) { var upperArgList = args.Select(arg => arg.ToUpper()).ToList(); var argList = args.Select(arg => arg).ToList(); if (upperArgList.Contains("-?") || upperArgList.Contains("/?") || upperArgList.Contains("-H") || upperArgList.Contains("/H") || upperArgList.Contains("HELP")) { OutputUsage(); return(true); } enableVSTS = upperArgList.IndexOf("-VSTS") > -1 || upperArgList.IndexOf("-V") > -1; var warnOnUnprocessed = upperArgList.IndexOf("-WARN") > -1 || upperArgList.IndexOf("-W") > -1; var errorOnDaxErr = upperArgList.IndexOf("-ERR") > -1 || upperArgList.IndexOf("-E") > -1; TabularModelHandler h; if (args.Length == 2 || args[2].StartsWith("-")) { // File argument provided (either alone or with switches), i.e.: // TabularEditor.exe myfile.bim // TabularEditor.exe myfile.bim -... if (!File.Exists(args[1]) && !File.Exists(args[1] + "\\database.json")) { Error("File not found: {0}", args[1]); return(true); } else { // If nothing else was specified on the command-line, open the UI: if (args.Length == 2) { return(false); } } try { h = new TOMWrapper.TabularModelHandler(args[1]); } catch (Exception e) { Error("Error loading file: " + e.Message); return(true); } } else if (args.Length == 3 || args[3].StartsWith("-")) { // Server + Database argument provided (either alone or with switches), i.e.: // TabularEditor.exe localhost AdventureWorks // TabularEditor.exe localhost AdventureWorks -... // If nothing else was specified on the command-line, open the UI: if (args.Length == 3) { return(false); } try { h = new TOMWrapper.TabularModelHandler(args[1], args[2]); } catch (Exception e) { Error("Error loading model: " + e.Message); return(true); } } else { // Otherwise, it's nonsensical return(false); } string script = null; string scriptFile = null; var doTestRun = upperArgList.IndexOf("-T"); string testRunFile = null; if (doTestRun == -1) { doTestRun = upperArgList.IndexOf("-TRX"); } if (doTestRun > -1) { if (upperArgList.Count <= doTestRun || upperArgList[doTestRun + 1].StartsWith("-")) { Error("Invalid argument syntax.\n"); OutputUsage(); return(true); } testRun = new TestRun(h.Database?.Name ?? h.Source); testRunFile = argList[doTestRun + 1]; } var doScript = upperArgList.IndexOf("-SCRIPT"); if (doScript == -1) { doScript = upperArgList.IndexOf("-S"); } if (doScript > -1) { if (upperArgList.Count <= doScript) { Error("Invalid argument syntax.\n"); OutputUsage(); return(true); } scriptFile = argList[doScript + 1]; script = File.Exists(scriptFile) ? File.ReadAllText(scriptFile) : scriptFile; } var doCheckDs = upperArgList.IndexOf("-SCHEMACHECK"); if (doCheckDs == -1) { doCheckDs = upperArgList.IndexOf("-SC"); } string saveToFolderOutputPath = null; string saveToFolderReplaceId = null; var doSaveToFolder = upperArgList.IndexOf("-FOLDER"); if (doSaveToFolder == -1) { doSaveToFolder = upperArgList.IndexOf("-F"); } if (doSaveToFolder > -1) { if (upperArgList.Count <= doSaveToFolder) { Error("Invalid argument syntax.\n"); OutputUsage(); return(true); } saveToFolderOutputPath = argList[doSaveToFolder + 1]; if (doSaveToFolder + 2 < argList.Count && !argList[doSaveToFolder + 2].StartsWith("-")) { saveToFolderReplaceId = argList[doSaveToFolder + 2]; } var directoryName = new FileInfo(saveToFolderOutputPath).Directory.FullName; Directory.CreateDirectory(saveToFolderOutputPath); } string buildOutputPath = null; string buildReplaceId = null; var doSave = upperArgList.IndexOf("-BUILD"); if (doSave == -1) { doSave = upperArgList.IndexOf("-B"); } if (doSave == -1) { doSave = upperArgList.IndexOf("-BIM"); } if (doSave > -1) { if (upperArgList.Count <= doSave) { Error("Invalid argument syntax.\n"); OutputUsage(); return(true); } buildOutputPath = argList[doSave + 1]; if (doSave + 2 < argList.Count && !argList[doSave + 2].StartsWith("-")) { buildReplaceId = argList[doSave + 2]; } var directoryName = new FileInfo(buildOutputPath).Directory.FullName; Directory.CreateDirectory(directoryName); } if (doSaveToFolder > -1 && doSave > -1) { Error("-FOLDER and -BUILD arguments are mutually exclusive.\n"); OutputUsage(); return(true); } // Load model: Console.WriteLine("Loading model..."); if (!string.IsNullOrEmpty(script)) { Console.WriteLine("Executing script..."); System.CodeDom.Compiler.CompilerResults result; Scripting.ScriptOutputForm.Reset(false); var dyn = ScriptEngine.CompileScript(script, out result); //nUnit.StartSuite("Script Compilation"); if (result.Errors.Count > 0) { Error("Script compilation errors:"); var errIndex = 0; foreach (System.CodeDom.Compiler.CompilerError err in result.Errors) { errIndex++; ErrorX(err.ErrorText, scriptFile, err.Line, err.Column, err.ErrorNumber); //nUnit.Failure("Script Compilation", $"Compilation Error #{errIndex}", err.ErrorText, $"{scriptFile} line {err.Line}, column {err.Column}"); } return(true); } try { h.BeginUpdate("script"); dyn.Invoke(h.Model, null); h.EndUpdateAll(); } catch (Exception ex) { Error("Script execution error: " + ex.Message); return(true); } finally { h.Model.Database.CloseReader(); } } if (doCheckDs > -1) { Console.WriteLine("Checking source schema..."); ScriptHelper.SchemaCheck(h.Model); } if (!string.IsNullOrEmpty(buildOutputPath)) { Console.WriteLine("Building Model.bim file..."); if (buildReplaceId != null) { h.Database.Name = buildReplaceId; h.Database.ID = buildReplaceId; } h.Save(buildOutputPath, SaveFormat.ModelSchemaOnly, SerializeOptions.Default); } else if (!string.IsNullOrEmpty(saveToFolderOutputPath)) { Console.WriteLine("Saving Model.bim file to Folder Output Path ..."); if (buildReplaceId != null) { h.Database.Name = buildReplaceId; h.Database.ID = buildReplaceId; } //Note the last parameter, we use whatever SerializeOptions are already in the file h.Save(saveToFolderOutputPath, SaveFormat.TabularEditorFolder, null, true); } var replaceMap = new Dictionary <string, string>(); var analyze = upperArgList.IndexOf("-ANALYZE"); if (analyze == -1) { analyze = upperArgList.IndexOf("-A"); } if (analyze > -1) { var rulefile = analyze + 1 < argList.Count ? argList[analyze + 1] : ""; if (rulefile.StartsWith("-") || string.IsNullOrEmpty(rulefile)) { rulefile = null; } Console.WriteLine("Running Best Practice Analyzer..."); Console.WriteLine("================================="); var analyzer = new BPA.Analyzer(); analyzer.SetModel(h.Model, h.SourceType == ModelSourceType.Database ? null : FileSystemHelper.DirectoryFromPath(h.Source)); BPA.BestPracticeCollection suppliedRules = null; if (!string.IsNullOrEmpty(rulefile)) { if (!File.Exists(rulefile)) { Error("Rulefile not found: {0}", rulefile); return(true); } try { suppliedRules = BPA.BestPracticeCollection.GetCollectionFromFile(Environment.CurrentDirectory, rulefile); } catch { Error("Invalid rulefile: {0}", rulefile); return(true); } } IEnumerable <BPA.AnalyzerResult> bpaResults; if (suppliedRules == null) { bpaResults = analyzer.AnalyzeAll(); } else { var effectiveRules = analyzer.GetEffectiveRules(false, false, true, true, suppliedRules); bpaResults = analyzer.Analyze(effectiveRules); } bool none = true; foreach (var res in bpaResults.Where(r => !r.Ignored)) { if (res.InvalidCompatibilityLevel) { Console.WriteLine("Skipping rule '{0}' as it does not apply to Compatibility Level {1}.", res.RuleName, h.CompatibilityLevel); } else if (res.RuleHasError) { none = false; Error("Error on rule '{0}': {1}", res.RuleName, res.RuleError); } else { none = false; if (res.Object != null) { var text = string.Format("{0} {1} violates rule \"{2}\"", res.Object.GetTypeName(), (res.Object as IDaxObject)?.DaxObjectFullName ?? res.ObjectName, res.RuleName ); if (res.Rule.Severity <= 1) { Console.WriteLine(text); } else if (res.Rule.Severity == 2) { Warning(text); } else if (res.Rule.Severity >= 3) { Error(text); } } } } if (none) { Console.WriteLine("No objects in violation of Best Practices."); } Console.WriteLine("================================="); } var deploy = upperArgList.IndexOf("-DEPLOY"); if (deploy == -1) { deploy = upperArgList.IndexOf("-D"); } if (deploy > -1) { var serverName = argList.Skip(deploy + 1).FirstOrDefault(); if (serverName == null || serverName.StartsWith("-")) { serverName = null; } var databaseID = argList.Skip(deploy + 2).FirstOrDefault(); if (databaseID != null && databaseID.StartsWith("-")) { databaseID = null; } // Perform direct save: if (serverName == null) { var nextSwitch = upperArgList.Skip(deploy + 1).FirstOrDefault(); var deploySwitches = new[] { "-L", "-LOGIN", "-O", "-OVERWRITE", "-C", "-CONNECTIONS", "-P", "-PARTITIONS", "-R", "-ROLES", "-M", "-MEMBERS", "-X", "-XMLA" }; if (deploySwitches.Contains(nextSwitch)) { Error("Invalid argument syntax.\n"); OutputUsage(); return(true); } Console.WriteLine("Saving model metadata back to source..."); if (h.SourceType == ModelSourceType.Database) { try { h.SaveDB(); Console.WriteLine("Model metadata saved."); var deploymentResult = h.GetLastDeploymentResults(); foreach (var err in deploymentResult.Issues) { if (errorOnDaxErr) { Error(err); } else { Warning(err); } } foreach (var err in deploymentResult.Warnings) { Warning(err); } foreach (var err in deploymentResult.Unprocessed) { if (warnOnUnprocessed) { Warning(err); } else { Console.WriteLine(err); } } } catch (Exception ex) { Error("Save failed: " + ex.Message); } } else { try { h.Save(h.Source, h.SourceType == ModelSourceType.Folder ? SaveFormat.TabularEditorFolder : h.SourceType == ModelSourceType.Pbit ? SaveFormat.PowerBiTemplate : SaveFormat.ModelSchemaOnly, h.SerializeOptions, true); Console.WriteLine("Model metadata saved."); } catch (Exception ex) { Error("Save failed: " + ex.Message); } } return(true); } var conn = upperArgList.IndexOf("-CONNECTIONS"); if (conn == -1) { conn = upperArgList.IndexOf("-C"); } if (conn > -1) { var replaces = argList.Skip(conn + 1).TakeWhile(s => s[0] != '-').ToList(); if (replaces.Count > 0 && replaces.Count % 2 == 0) { // Placeholder replacing: for (var index = 0; index < replaces.Count; index = index + 2) { replaceMap.Add(replaces[index], replaces[index + 1]); } } } string userName = null; string password = null; var options = DeploymentOptions.StructureOnly; var switches = args.Skip(deploy + 1).Where(arg => arg.StartsWith("-")).Select(arg => arg.ToUpper()).ToList(); if (string.IsNullOrEmpty(serverName) || string.IsNullOrEmpty(databaseID)) { Error("Invalid argument syntax.\n"); OutputUsage(); return(true); } if (switches.Contains("-L") || switches.Contains("-LOGIN")) { var switchPos = upperArgList.IndexOf("-LOGIN"); if (switchPos == -1) { switchPos = upperArgList.IndexOf("-L"); } userName = argList.Skip(switchPos + 1).FirstOrDefault(); if (userName != null && userName.StartsWith("-")) { userName = null; } password = argList.Skip(switchPos + 2).FirstOrDefault(); if (password != null && password.StartsWith("-")) { password = null; } if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password)) { Error("Missing username or password.\n"); OutputUsage(); return(true); } switches.Remove("-L"); switches.Remove("-LOGIN"); } if (switches.Contains("-O") || switches.Contains("-OVERWRITE")) { options.DeployMode = DeploymentMode.CreateOrAlter; switches.Remove("-O"); switches.Remove("-OVERWRITE"); } else { options.DeployMode = DeploymentMode.CreateDatabase; } if (switches.Contains("-P") || switches.Contains("-PARTITIONS")) { options.DeployPartitions = true; switches.Remove("-P"); switches.Remove("-PARTITIONS"); } if (switches.Contains("-C") || switches.Contains("-CONNECTIONS")) { options.DeployConnections = true; switches.Remove("-C"); switches.Remove("-CONNECTIONS"); } if (switches.Contains("-R") || switches.Contains("-ROLES")) { options.DeployRoles = true; switches.Remove("-R"); switches.Remove("-ROLES"); if (switches.Contains("-M") || switches.Contains("-MEMBERS")) { options.DeployRoleMembers = true; switches.Remove("-M"); switches.Remove("-MEMBERS"); } } var xmla_scripting_only = switches.Contains("-X") || switches.Contains("-XMLA"); string xmla_script_file = null; if (xmla_scripting_only) { var switchPos = upperArgList.IndexOf("-XMLA"); if (switchPos == -1) { switchPos = upperArgList.IndexOf("-X"); } xmla_script_file = argList.Skip(switchPos + 1).FirstOrDefault(); if (String.IsNullOrWhiteSpace(xmla_script_file) || xmla_script_file.StartsWith("-")) { xmla_script_file = null; } if (string.IsNullOrEmpty(xmla_script_file)) { Error("Missing xmla_script_file.\n"); OutputUsage(); return(true); } switches.Remove("-X"); switches.Remove("-XMLA"); } /*if(switches.Count > 0) * { * Error("Unknown switch {0}\n", switches[0]); * OutputUsage(); * return true; * }*/ try { if (replaceMap.Count > 0) { Console.WriteLine("Switching connection string placeholders..."); foreach (var map in replaceMap) { h.Model.DataSources.SetPlaceholder(map.Key, map.Value); } } var cs = string.IsNullOrEmpty(userName) ? TabularConnection.GetConnectionString(serverName) : TabularConnection.GetConnectionString(serverName, userName, password); if (xmla_scripting_only) { Console.WriteLine("Generating XMLA/TMSL script..."); var s = new TOM.Server(); s.Connect(cs); var xmla = TabularDeployer.GetTMSL(h.Database, s, databaseID, options); using (var sw = new StreamWriter(xmla_script_file)) { sw.Write(xmla); } Console.WriteLine("XMLA/TMSL script generated."); } else { Console.WriteLine("Deploying..."); UpdateDeploymentMetadata(h.Model, DeploymentModeMetadata.CLI); var deploymentResult = TabularDeployer.Deploy(h, cs, databaseID, options); Console.WriteLine("Deployment succeeded."); foreach (var err in deploymentResult.Issues) { if (errorOnDaxErr) { Error(err); } else { Warning(err); } } foreach (var err in deploymentResult.Warnings) { Warning(err); } foreach (var err in deploymentResult.Unprocessed) { if (warnOnUnprocessed) { Warning(err); } else { Console.WriteLine(err); } } } } catch (Exception ex) { Error($"{(xmla_scripting_only ? "Script generation" : "Deployment")} failed! {ex.Message}"); } } if (testRun != null) { testRun.SerializeAsVSTest(testRunFile); Console.WriteLine("VSTest XML file saved: " + testRunFile); } return(true); }
public bool NewFile() { var sfd = new CommonSaveFileDialog("New Rule File"); sfd.EnsurePathExists = true; sfd.InitialDirectory = analyzer.BasePath; sfd.DefaultFileName = "BPARules.json"; sfd.DefaultExtension = "json"; sfd.Filters.Add(new CommonFileDialogFilter("JSON file", "*.json")); sfd.Filters.Add(new CommonFileDialogFilter("All files", "*.*")); var localPathCheckBox = new CommonFileDialogCheckBox("Use relative path", true) { Visible = false }; if (UIController.Current.File_Current != null) { sfd.Controls.Add(localPathCheckBox); localPathCheckBox.Visible = true; sfd.FolderChanging += (s, e) => { var relativePath = FileSystemHelper.GetRelativePath(analyzer.BasePath, e.Folder); if (relativePath.Length >= 2 && relativePath[1] == ':') { localPathCheckBox.Visible = false; } else { localPathCheckBox.Visible = true; } }; } parent.Enabled = false; if (sfd.ShowDialog() == CommonFileDialogResult.Ok) { parent.Enabled = true; try { File.WriteAllText(sfd.FileName, "[]"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Unable to create rule file", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } var fileName = localPathCheckBox.Visible && localPathCheckBox.IsChecked ? FileSystemHelper.GetRelativePath(analyzer.BasePath, sfd.FileName) : sfd.FileName; if (!analyzer.ExternalRuleCollections.Any( rc => rc.FilePath != null && FileSystemHelper.GetAbsolutePath(analyzer.BasePath, rc.FilePath).EqualsI(sfd.FileName) )) { analyzer.ExternalRuleCollections.Add(BestPracticeCollection.GetCollectionFromFile(analyzer.BasePath, fileName)); } return(true); } parent.Enabled = true; return(false); }
/// <summary> /// Check if current step is valid. /// </summary> public override Task <bool> IsValid() { var result = false; if (chkCreateLog.Checked) { if (txtLogFile.Text == string.Empty) { SetError("Error_PathRequired"); } else { try { string validationResult = FileSystemHelper.ValidatePath(txtLogFile.Text); if (!string.IsNullOrEmpty(validationResult)) { SetError(validationResult); } else { FileInfo fi = FileInfo.New(txtLogFile.Text); // If filename is not specified or filename is already a directory if (string.IsNullOrEmpty(fi.Name)) { SetError("Error_NoFilename"); } else { if (((fi.Attributes & FileAttributes.Directory) == FileAttributes.Directory) && (Convert.ToInt32(fi.Attributes) != -1)) { SetError("Error_PathIsOccupied"); } else { // If directory doesn't exist if (fi.Directory != null) { if (!fi.Directory.Exists) { SetError("Error_PathNotExist"); } else { // Check write permissions FileIOPermission fileIoPermission = new FileIOPermission(FileIOPermissionAccess.Write, fi.FullName); PermissionSet permSet = new PermissionSet(PermissionState.None); permSet.AddPermission(fileIoPermission); bool isGranted = permSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet); if (!isGranted) { SetError("Error_NoWritePermissions"); } else { result = true; } } } else { SetError("Error_PathMissingDirectory"); } } } } } catch (Exception) { SetError("Error_PathNotValid"); result = false; } } } else { result = true; } lblMessage.Visible = !result; ImportProfile.LogPath = txtLogFile.Text; return(Task.FromResult(result)); }
public virtual ExportProfile InsertExportProfile( string providerSystemName, string name, string fileExtension, ExportFeatures features, bool isSystemProfile = false, string profileSystemName = null, int cloneFromProfileId = 0) { Guard.NotEmpty(providerSystemName, nameof(providerSystemName)); if (name.IsEmpty()) { name = providerSystemName; } if (!isSystemProfile) { var profileCount = _exportProfileRepository.Table.Count(x => x.ProviderSystemName == providerSystemName); name = string.Concat(_localizationService.GetResource("Common.My"), " ", name, " ", profileCount + 1); } var cloneProfile = GetExportProfileById(cloneFromProfileId); ScheduleTask task = null; ExportProfile profile = null; if (cloneProfile == null) { task = new ScheduleTask { CronExpression = "0 */6 * * *", // every six hours Type = typeof(DataExportTask).AssemblyQualifiedNameWithoutVersion(), Enabled = false, StopOnError = false, IsHidden = true }; } else { task = cloneProfile.ScheduleTask.Clone(); task.LastEndUtc = task.LastStartUtc = task.LastSuccessUtc = null; } task.Name = string.Concat(name, " Task"); _scheduleTaskService.InsertTask(task); if (cloneProfile == null) { profile = new ExportProfile { FileNamePattern = _defaultFileNamePattern }; if (isSystemProfile) { profile.Enabled = true; profile.PerStore = false; profile.CreateZipArchive = false; profile.Cleanup = false; } else { // what we do here is to preset typical settings for feed creation // but on the other hand they may be untypical for generic data export\exchange var projection = new ExportProjection { RemoveCriticalCharacters = true, CriticalCharacters = "¼,½,¾", PriceType = PriceDisplayType.PreSelectedPrice, NoGroupedProducts = (features.HasFlag(ExportFeatures.CanOmitGroupedProducts) ? true : false), OnlyIndividuallyVisibleAssociated = true, DescriptionMerging = ExportDescriptionMerging.Description }; var filter = new ExportFilter { IsPublished = true, ShoppingCartTypeId = (int)ShoppingCartType.ShoppingCart }; profile.Projection = XmlHelper.Serialize <ExportProjection>(projection); profile.Filtering = XmlHelper.Serialize <ExportFilter>(filter); } } else { profile = cloneProfile.Clone(); } profile.IsSystemProfile = isSystemProfile; profile.Name = name; profile.ProviderSystemName = providerSystemName; profile.SchedulingTaskId = task.Id; var cleanedSystemName = providerSystemName .Replace("Exports.", "") .Replace("Feeds.", "") .Replace("/", "") .Replace("-", ""); var folderName = SeoHelper.GetSeName(cleanedSystemName, true, false) .ToValidPath() .Truncate(_dataExchangeSettings.MaxFileNameLength); var path = DataSettings.Current.TenantPath + "/ExportProfiles"; profile.FolderName = path + "/" + FileSystemHelper.CreateNonExistingDirectoryName(CommonHelper.MapPath(path), folderName); profile.SystemName = profileSystemName.IsEmpty() && isSystemProfile ? cleanedSystemName : profileSystemName; _exportProfileRepository.Insert(profile); task.Alias = profile.Id.ToString(); _scheduleTaskService.UpdateTask(task); if (fileExtension.HasValue() && !isSystemProfile) { if (cloneProfile == null) { if (features.HasFlag(ExportFeatures.CreatesInitialPublicDeployment)) { var subFolder = FileSystemHelper.CreateNonExistingDirectoryName(CommonHelper.MapPath("~/" + DataExporter.PublicFolder), folderName); profile.Deployments.Add(new ExportDeployment { ProfileId = profile.Id, Enabled = true, DeploymentType = ExportDeploymentType.PublicFolder, Name = profile.Name, SubFolder = subFolder }); UpdateExportProfile(profile); } } else { foreach (var deployment in cloneProfile.Deployments) { profile.Deployments.Add(deployment.Clone()); } UpdateExportProfile(profile); } } return(profile); }
public void LoadTexture() { if (mTexture != null) { return; } if (mPackFrame != null) { ((MonoTexture)mPackFrame.PackTexture)?.LoadTexture(); return; } mLoadError = true; if (string.IsNullOrWhiteSpace(mRealPath)) { Log.Error("Invalid texture path (empty/null)."); return; } var relativePath = FileSystemHelper.RelativePath(Directory.GetCurrentDirectory(), mPath); if (!File.Exists(mRealPath)) { Log.Error($"Texture does not exist: {relativePath}"); return; } using (var fileStream = File.Open(mRealPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { try { mTexture = Texture2D.FromStream(mGraphicsDevice, fileStream); if (mTexture == null) { Log.Error($"Failed to load texture due to unknown error: {relativePath}"); ChatboxMsg.AddMessage( new ChatboxMsg( Strings.Errors.LoadFile.ToString(Strings.Words.lcase_sprite) + " [" + mName + "]", new Color(0xBF, 0x0, 0x0) ) ); return; } mWidth = mTexture.Width; mHeight = mTexture.Height; mLoadError = false; } catch (Exception exception) { Log.Error( exception, $"Failed to load texture ({FileSystemHelper.FormatSize(fileStream.Length)}): {relativePath}" ); ChatboxMsg.AddMessage( new ChatboxMsg( Strings.Errors.LoadFile.ToString(Strings.Words.lcase_sprite) + " [" + mName + "]", new Color(0xBF, 0x0, 0x0) ) ); } } }
public void Setup() { FileSystemHelper.KillDirectory(dirname); }
public string GetStagingDirectory(params string[] extraPaths) => FileSystemHelper.GetPath(config, extraPaths, getStagingName(Path.GetFileName(GetRealLiveDirectory())));
private static void LogPacket(Span <byte> buffer, int length, bool toServer) { if (_logFile == null) { _logFile = new LogFile(FileSystemHelper.CreateFolderIfNotExists(CUOEnviroment.ExecutablePath, "Logs", "Network"), "packets.log"); } Span <char> span = stackalloc char[256]; ValueStringBuilder output = new ValueStringBuilder(span); { int off = sizeof(ulong) + 2; output.Append(' ', off); output.Append(string.Format("Ticks: {0} | {1} | ID: {2:X2} Length: {3}\n", Time.Ticks, (toServer ? "Client -> Server" : "Server -> Client"), buffer[0], length)); if (buffer[0] == 0x80 || buffer[0] == 0x91) { output.Append(' ', off); output.Append("[ACCOUNT CREDENTIALS HIDDEN]\n"); } else { output.Append(' ', off); output.Append("0 1 2 3 4 5 6 7 8 9 A B C D E F\n"); output.Append(' ', off); output.Append("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n"); ulong address = 0; for (int i = 0; i < length; i += 16, address += 16) { output.Append($"{address:X8}"); for (int j = 0; j < 16; ++j) { if ((j % 8) == 0) { output.Append(" "); } if (i + j < length) { output.Append($" {buffer[i + j]:X2}"); } else { output.Append(" "); } } output.Append(" "); for (int j = 0; j < 16 && i + j < length; ++j) { byte c = buffer[i + j]; if (c >= 0x20 && c < 0x80) { output.Append((char)c); } else { output.Append('.'); } } output.Append('\n'); } } output.Append('\n'); output.Append('\n'); _logFile.Write(output.ToString()); output.Dispose(); } }
public string GetLiveDirectory(params string[] extraPaths) => FileSystemHelper.GetPath(config, extraPaths, "Live");
public static IEnumerator <FileHandleInfo> GetCurrentProcessOpenFilesEnumerator(int processId, SmartPtr systemHandleInformationPointer, int handleCount) { return(FileSystemHelper.GetOpenFilesEnumerator(processId, systemHandleInformationPointer, handleCount)); }
public string GetRpositoryDirectory(params string[] extraPaths) => FileSystemHelper.GetPath(config, extraPaths, "Repo");
public override unsafe Task Load() { return(Task.Run ( () => { string path = UOFileManager.GetUOFilePath("tiledata.mul"); FileSystemHelper.EnsureFileExists(path); UOFileMul tileData = new UOFileMul(path); bool isold = Client.Version < ClientVersion.CV_7090; const int LAND_SIZE = 512; int land_group = isold ? Marshal.SizeOf <LandGroupOld>() : Marshal.SizeOf <LandGroupNew>(); int static_group = isold ? Marshal.SizeOf <StaticGroupOld>() : Marshal.SizeOf <StaticGroupNew>(); int staticscount = (int)((tileData.Length - LAND_SIZE * land_group) / static_group); if (staticscount > 2048) { staticscount = 2048; } tileData.Seek(0); _landData = new LandTiles[Constants.MAX_LAND_DATA_INDEX_COUNT]; _staticData = new StaticTiles[staticscount * 32]; byte *bufferString = stackalloc byte[20]; for (int i = 0; i < 512; i++) { tileData.Skip(4); for (int j = 0; j < 32; j++) { if (tileData.Position + (isold ? 4 : 8) + 2 + 20 > tileData.Length) { goto END; } int idx = i * 32 + j; ulong flags = isold ? tileData.ReadUInt() : tileData.ReadULong(); ushort textId = tileData.ReadUShort(); for (int k = 0; k < 20; ++k) { bufferString[k] = tileData.ReadByte(); } string name = string.Intern(Encoding.UTF8.GetString(bufferString, 20).TrimEnd('\0')); LandData[idx] = new LandTiles(flags, textId, name); } } END: for (int i = 0; i < staticscount; i++) { if (tileData.Position >= tileData.Length) { break; } tileData.Skip(4); for (int j = 0; j < 32; j++) { if (tileData.Position + (isold ? 4 : 8) + 13 + 20 > tileData.Length) { goto END_2; } int idx = i * 32 + j; ulong flags = isold ? tileData.ReadUInt() : tileData.ReadULong(); byte weight = tileData.ReadByte(); byte layer = tileData.ReadByte(); int count = tileData.ReadInt(); ushort animId = tileData.ReadUShort(); ushort hue = tileData.ReadUShort(); ushort lightIndex = tileData.ReadUShort(); byte height = tileData.ReadByte(); for (int k = 0; k < 20; ++k) { bufferString[k] = tileData.ReadByte(); } string name = string.Intern(Encoding.UTF8.GetString(bufferString, 20).TrimEnd('\0')); StaticData[idx] = new StaticTiles ( flags, weight, layer, count, animId, hue, lightIndex, height, name ); } } //path = Path.Combine(FileManager.UoFolderPath, "tileart.uop"); //if (File.Exists(path)) //{ // UOFileUop uop = new UOFileUop(path, ".bin"); // DataReader reader = new DataReader(); // for (int i = 0; i < uop.Entries.Length; i++) // { // long offset = uop.Entries[i].Offset; // int csize = uop.Entries[i].Length; // int dsize = uop.Entries[i].DecompressedLength; // if (offset == 0) // continue; // uop.Seek(offset); // byte[] cdata = uop.ReadArray<byte>(csize); // byte[] ddata = new byte[dsize]; // ZLib.Decompress(cdata, 0, ddata, dsize); // reader.SetData(ddata, dsize); // ushort version = reader.ReadUShort(); // uint stringDicOffset = reader.ReadUInt(); // uint tileID = reader.ReadUInt(); // reader.Skip(1 + // bool unk // 1 + // unk // 4 + // float unk // 4 + // float unk // 4 + // fixed zero ? // 4 + // old id ? // 4 + // unk // 4 + // unk // 1 + // unk // 4 + // 3F800000 // 4 + // unk // 4 + // float light // 4 + // float light // 4 // unk // ); // ulong flags = reader.ReadULong(); // ulong flags2 = reader.ReadULong(); // reader.Skip(4); // unk // reader.Skip(24); // EC IMAGE OFFSET // byte[] imageOffset = reader.ReadArray(24); // 2D IMAGE OFFSET // if (tileID + 0x4000 == 0xa28d) // { // TileFlag f = (TileFlag) flags; // } // int count = reader.ReadByte(); // for (int j = 0; j < count; j++) // { // byte prop = reader.ReadByte(); // uint value = reader.ReadUInt(); // } // count = reader.ReadByte(); // for (int j = 0; j < count; j++) // { // byte prop = reader.ReadByte(); // uint value = reader.ReadUInt(); // } // count = reader.ReadInt(); // Gold Silver // for (int j = 0; j < count; j++) // { // uint amount = reader.ReadUInt(); // uint id = reader.ReadUInt(); // } // count = reader.ReadInt(); // for (int j = 0; j < count; j++) // { // byte val = reader.ReadByte(); // if (val != 0) // { // if (val == 1) // { // byte unk = reader.ReadByte(); // uint unk1 = reader.ReadUInt(); // } // } // else // { // int subCount = reader.ReadInt(); // for (int k = 0; k < subCount; k++) // { // uint unk = reader.ReadUInt(); // uint unk1 = reader.ReadUInt(); // } // } // } // count = reader.ReadByte(); // if (count != 0) // { // uint unk = reader.ReadUInt(); // uint unk1 = reader.ReadUInt(); // uint unk2 = reader.ReadUInt(); // uint unk3 = reader.ReadUInt(); // } // if (StaticData[tileID].AnimID == 0) // { // //StaticData[tileID] = new StaticTiles(flags, 0, 0, 0, ); // } // } // uop.Dispose(); // reader.ReleaseData(); //} END_2: tileData.Dispose(); } )); }
private void Upload(string path) { path = GetRelativePath(path); string message = null; var hasError = false; var width = 0; var height = 0; int.TryParse(GetSetting("MAX_IMAGE_WIDTH"), out width); int.TryParse(GetSetting("MAX_IMAGE_HEIGHT"), out height); var tempDir = FileSystemHelper.TempDirTenant("roxy " + CommonHelper.GenerateRandomInteger().ToString()); try { // copy uploaded files to temp folder and resize them for (var i = 0; i < Request.Files.Count; ++i) { var file = Request.Files[i]; var extension = Path.GetExtension(file.FileName); if (IsAllowedFileType(extension)) { var dest = Path.Combine(tempDir, file.FileName); file.SaveAs(dest); if (GetFileContentType(extension).IsCaseInsensitiveEqual("image")) { ImageResize(dest, dest, width, height); } } else { message = LangRes("E_UploadNotAll"); } } // copy files to file storage foreach (var tempPath in Directory.EnumerateFiles(tempDir, "*", SearchOption.TopDirectoryOnly)) { using (var stream = new FileStream(tempPath, FileMode.Open, FileAccess.Read)) { var name = GetUniqueFileName(path, Path.GetFileName(tempPath)); var newPath = _fileSystem.Combine(path, name); _fileSystem.SaveStream(newPath, stream); } } } catch (Exception exception) { hasError = true; message = exception.Message; } finally { FileSystemHelper.ClearDirectory(tempDir, true); } if (IsAjaxUpload()) { if (message.HasValue()) { Response.Write(GetResultString(message, hasError ? "error" : "ok")); } } else { Response.Write("<script>"); Response.Write("parent.fileUploaded(" + GetResultString(message, hasError ? "error" : "ok") + ");"); Response.Write("</script>"); } }