public ImageSource Extract(File file) { try { if (new List<string> {".ico", ".png", ".jpg", ".gif"}.Contains(file.Extension.ToLower())) { if (!file.Exists()) return new BitmapImage(); return new BitmapImage(new Uri(file.FullName)); } Icon icon = ExtractIcon(ActualFile(file)); Bitmap bmp = icon.ToBitmap(); DestroyIcon(icon.Handle); var strm = new MemoryStream(); bmp.Save(strm, ImageFormat.Png); return Extract(strm); } catch (ExternalException exception) { LogManager.WriteLog(exception); return new BitmapImage(); } catch (DirectoryNotFoundException exception) { LogManager.WriteLog("Requested file: {0}", file); LogManager.WriteLog(exception); return new BitmapImage(); } catch (ArgumentException exception) { LogManager.WriteLog("Requested file: {0}", file); LogManager.WriteLog(exception); return new BitmapImage(); } }
public TemporaryLocalFile(File backingFile) { _backingFile = backingFile; if (!backingFile.Exists()) backingFile.Create(); }
/// <summary> /// SORRY :( I didn't have time to put this in a service somewhere - the old packager did this all manually too /// </summary> /// <param name="pack"></param> protected void PerformUninstall(InstalledPackage pack) { if (pack == null) { throw new ArgumentNullException("pack"); } var removedTemplates = new List <ITemplate>(); var removedMacros = new List <IMacro>(); var removedContentTypes = new List <IContentType>(); var removedDictionaryItems = new List <IDictionaryItem>(); var removedDataTypes = new List <IDataType>(); var removedFiles = new List <string>(); //Uninstall templates foreach (var item in pack.Data.Templates.ToArray()) { int nId; if (int.TryParse(item, out nId) == false) { continue; } var found = Services.FileService.GetTemplate(nId); if (found != null) { removedTemplates.Add(found); Services.FileService.DeleteTemplate(found.Alias, Security.GetUserId().ResultOr(0)); } pack.Data.Templates.Remove(nId.ToString()); } //Uninstall macros foreach (var item in pack.Data.Macros.ToArray()) { int nId; if (int.TryParse(item, out nId) == false) { continue; } var macro = Services.MacroService.GetById(nId); if (macro != null) { removedMacros.Add(macro); Services.MacroService.Delete(macro); } pack.Data.Macros.Remove(nId.ToString()); } //Remove Document Types var contentTypes = new List <IContentType>(); var contentTypeService = Services.ContentTypeService; foreach (var item in pack.Data.Documenttypes.ToArray()) { int nId; if (int.TryParse(item, out nId) == false) { continue; } var contentType = contentTypeService.Get(nId); if (contentType == null) { continue; } contentTypes.Add(contentType); pack.Data.Documenttypes.Remove(nId.ToString(CultureInfo.InvariantCulture)); } //Order the DocumentTypes before removing them if (contentTypes.Any()) { //TODO: I don't think this ordering is necessary var orderedTypes = from contentType in contentTypes orderby contentType.ParentId descending, contentType.Id descending select contentType; removedContentTypes.AddRange(orderedTypes); contentTypeService.Delete(orderedTypes); } //Remove Dictionary items foreach (var item in pack.Data.DictionaryItems.ToArray()) { int nId; if (int.TryParse(item, out nId) == false) { continue; } var di = Services.LocalizationService.GetDictionaryItemById(nId); if (di != null) { removedDictionaryItems.Add(di); Services.LocalizationService.Delete(di); } pack.Data.DictionaryItems.Remove(nId.ToString()); } //Remove Data types foreach (var item in pack.Data.DataTypes.ToArray()) { int nId; if (int.TryParse(item, out nId) == false) { continue; } var dtd = Services.DataTypeService.GetDataType(nId); if (dtd != null) { removedDataTypes.Add(dtd); Services.DataTypeService.Delete(dtd); } pack.Data.DataTypes.Remove(nId.ToString()); } pack.Save(); // uninstall actions //TODO: We should probably report errors to the UI!! // This never happened before though, but we should do something now if (pack.Data.Actions.IsNullOrWhiteSpace() == false) { try { var actionsXml = new XmlDocument(); actionsXml.LoadXml("<Actions>" + pack.Data.Actions + "</Actions>"); Logger.Debug <PackageInstallController>("Executing undo actions: {UndoActionsXml}", actionsXml.OuterXml); foreach (XmlNode n in actionsXml.DocumentElement.SelectNodes("//Action")) { try { global::Umbraco.Web._Legacy.Packager.PackageInstance.PackageAction .UndoPackageAction(pack.Data.Name, n.Attributes["alias"].Value, n); } catch (Exception ex) { Logger.Error <PackageInstallController>(ex, "An error occurred running undo actions"); } } } catch (Exception ex) { Logger.Error <PackageInstallController>(ex, "An error occurred running undo actions"); } } //moved remove of files here so custom package actions can still undo //Remove files foreach (var item in pack.Data.Files.ToArray()) { removedFiles.Add(item.GetRelativePath()); //here we need to try to find the file in question as most packages does not support the tilde char var file = IOHelper.FindFile(item); if (file != null) { if (file.StartsWith("/") == false) { file = string.Format("/{0}", file); } var filePath = IOHelper.MapPath(file); if (File.Exists(filePath)) { File.Delete(filePath); } } pack.Data.Files.Remove(file); } pack.Save(); pack.Delete(Security.GetUserId().ResultOr(0)); // create a summary of what was actually removed, for PackagingService.UninstalledPackage var summary = new UninstallationSummary { MetaData = pack.GetMetaData(), TemplatesUninstalled = removedTemplates, MacrosUninstalled = removedMacros, ContentTypesUninstalled = removedContentTypes, DictionaryItemsUninstalled = removedDictionaryItems, DataTypesUninstalled = removedDataTypes, FilesUninstalled = removedFiles, PackageUninstalled = true }; // trigger the UninstalledPackage event PackagingService.OnUninstalledPackage(new UninstallPackageEventArgs <UninstallationSummary>(summary, false)); }
public async Task <bool> ProcessTrack(string id, AlbumInfo albumInfo = null, TrackInfo trackInfo = null) { var trackProgress = new ProgressBar(100, 100); if (trackInfo == null) { trackInfo = await GetTrackInfo(id); if (trackInfo == null) { trackProgress.Refresh(0, $"{id} | Failed to get track info"); return(false); } } if (albumInfo == null) { string albumId = trackInfo.TrackTags.AlbumId; albumInfo = await GetAlbumInfo(albumId) ?? new AlbumInfo { AlbumTags = new AlbumTags { Artists = new [] { new Artists { Name = "Unknown Artist" } }, Type = "Unknown", Title = albumId ?? "Unknown Collection " + Helpers.GetRandomChars(5), NumberOfDiscs = "0", NumberOfTracks = "0" } }; } AudioQuality qualityToUse = FindAvailableAudioQuality(trackInfo); if (qualityToUse == AudioQuality.None) { Helpers.RedMessage("Failed to find any available audio quality"); return(false); } string trackProgressTitle = $"\nDownloading {albumInfo.AlbumTags.Artists[0].Name} - {trackInfo.TrackTags.Title} | Quality: {DeezerHelpers.AudioQualityToOutputString[qualityToUse]}"; trackProgress.Next($"{trackProgressTitle} | Getting save location"); string saveLocation = DeezerHelpers.BuildSaveLocation(trackInfo, albumInfo, qualityToUse); string saveLocationDirectory = Path.GetDirectoryName(saveLocation); string tempTrackPath = DeezerHelpers.GetTempTrackPath(saveLocationDirectory, trackInfo.TrackTags.Id); if (File.Exists(saveLocation)) { trackProgress.Refresh(100, $"{trackProgressTitle} | file already exists"); return(true); } byte[] decryptedBytes = await GetDecryptedBytes(trackInfo, qualityToUse, trackProgress, trackProgressTitle); trackProgress.Next($"{trackProgressTitle} | Writing to disk"); if (!DeezerHelpers.WriteTrackBytes(decryptedBytes, tempTrackPath)) { trackProgress.Refresh(0, $"{trackProgressTitle} | Failed to write file to disk"); return(false); } byte[] albumCover = await GetAndSaveAlbumArt(albumInfo.AlbumTags.PictureId, saveLocationDirectory); trackProgress.Next($"{trackProgressTitle} | Writing metadata"); var metadataWriter = new MetadataWriter(trackInfo, albumInfo, tempTrackPath, albumCover); if (!metadataWriter.WriteMetaData(qualityToUse == AudioQuality.Flac)) { trackProgress.Refresh(0, $"{trackProgressTitle} | Failed to write tags"); } DeezerHelpers.RenameFiles(tempTrackPath, saveLocation, saveLocationDirectory); trackProgress.Next($"{trackProgressTitle} | Complete"); return(true); }
private KeyValuePair <string, string>[] FindFilesToBeReplaced(IEnumerable <KeyValuePair <string, string> > sourceDestination) { return(sourceDestination.Where(sd => File.Exists(Path.Combine(FullPathToRoot, sd.Value))).ToArray()); }
internal static string DownloadFile(string queryUrl, string destination, PackageSourceListRequest request, ProgressTracker progressTracker) { try { request.Debug(Resources.Messages.DebugInfoCallMethod, Constants.ProviderName, string.Format(System.Globalization.CultureInfo.InvariantCulture, "DownloadFile - url='{0}', destination='{1}'", queryUrl, destination)); if (string.IsNullOrWhiteSpace(destination)) { throw new ArgumentNullException("destination"); } // make sure that the parent folder is created first. var folder = Path.GetDirectoryName(destination); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } if (File.Exists(destination)) { destination.TryHardToDelete(); } if (progressTracker == null) { progressTracker = new ProgressTracker(request.StartProgress(0, Resources.Messages.DownloadingPackage, queryUrl)); } Uri uri; if (!Uri.TryCreate(queryUrl, UriKind.Absolute, out uri)) { request.WriteError(Internal.ErrorCategory.InvalidOperation, "", Resources.Messages.UnsuportedUriFormat, Constants.ProviderName, queryUrl); return(null); } if (uri.IsFile) { // downloading from a file share using (var input = File.OpenRead(queryUrl)) { using (var output = new FileStream(destination, FileMode.Create, FileAccess.Write, FileShare.Read)) { request.Progress(progressTracker.ProgressID, progressTracker.StartPercent, Resources.Messages.Downloading); input.CopyTo(output); } } request.CompleteProgress(progressTracker.ProgressID, true); } else { //Downloading from url var result = DownloadDataToFileAsync(destination, queryUrl, request, PathUtility.GetNetworkCredential(request.CredentialUsername, request.CredentialPassword), progressTracker).Result; } if (File.Exists(destination)) { request.Verbose(Resources.Messages.CompletedDownload, queryUrl); return(destination); } else { request.WriteError(ErrorCategory.InvalidOperation, queryUrl, Resources.Messages.FailedToDownload, Constants.ProviderName, queryUrl); return(null); } } catch (Exception ex) { ex.Dump(request); request.Warning(ex.Message); return(null); } }
public void StandaloneTest() { IFactory factory = null; // clear foreach (var file in Directory.GetFiles(Path.Combine(IOHelper.MapPath("~/App_Data")), "NuCache.*")) { File.Delete(file); } // settings // reset the current version to 0.0.0, clear connection strings ConfigurationManager.AppSettings[Constants.AppSettings.ConfigurationStatus] = ""; // FIXME: we need a better management of settings here (and, true config files?) // create the very basic and essential things we need var logger = new ConsoleLogger(); var profiler = new LogProfiler(logger); var profilingLogger = new ProfilingLogger(logger, profiler); var appCaches = new AppCaches(); // FIXME: has HttpRuntime stuff? var databaseFactory = new UmbracoDatabaseFactory(logger, new Lazy <IMapperCollection>(() => factory.GetInstance <IMapperCollection>())); var typeLoader = new TypeLoader(appCaches.RuntimeCache, IOHelper.MapPath("~/App_Data/TEMP"), profilingLogger); var mainDom = new SimpleMainDom(); var runtimeState = new RuntimeState(logger, null, null, new Lazy <IMainDom>(() => mainDom), new Lazy <IServerRegistrar>(() => factory.GetInstance <IServerRegistrar>())); // create the register and the composition var register = RegisterFactory.Create(); var composition = new Composition(register, typeLoader, profilingLogger, runtimeState); composition.RegisterEssentials(logger, profiler, profilingLogger, mainDom, appCaches, databaseFactory, typeLoader, runtimeState); // create the core runtime and have it compose itself var coreRuntime = new CoreRuntime(); coreRuntime.Compose(composition); // determine actual runtime level runtimeState.DetermineRuntimeLevel(databaseFactory, logger); Console.WriteLine(runtimeState.Level); // going to be Install BUT we want to force components to be there (nucache etc) runtimeState.Level = RuntimeLevel.Run; var composerTypes = typeLoader.GetTypes <IComposer>() // all of them .Where(x => !x.FullName.StartsWith("Umbraco.Tests.")) // exclude test components .Where(x => x != typeof(WebInitialComposer) && x != typeof(WebFinalComposer)); // exclude web runtime var composers = new Composers(composition, composerTypes, profilingLogger); composers.Compose(); // must registers stuff that WebRuntimeComponent would register otherwise // FIXME: UmbracoContext creates a snapshot that it does not register with the accessor // and so, we have to use the UmbracoContextPublishedSnapshotAccessor // the UmbracoContext does not know about the accessor // else that would be a catch-22 where they both know about each other? //composition.Register<IPublishedSnapshotAccessor, TestPublishedSnapshotAccessor>(Lifetime.Singleton); composition.Register <IPublishedSnapshotAccessor, UmbracoContextPublishedSnapshotAccessor>(Lifetime.Singleton); composition.Register <IUmbracoContextAccessor, TestUmbracoContextAccessor>(Lifetime.Singleton); composition.Register <IVariationContextAccessor, TestVariationContextAccessor>(Lifetime.Singleton); composition.Register <IDefaultCultureAccessor, TestDefaultCultureAccessor>(Lifetime.Singleton); composition.Register <ISiteDomainHelper>(_ => Mock.Of <ISiteDomainHelper>(), Lifetime.Singleton); composition.RegisterUnique(f => new DistributedCache()); composition.WithCollectionBuilder <UrlProviderCollectionBuilder>().Append <DefaultUrlProvider>(); composition.RegisterUnique <IDistributedCacheBinder, DistributedCacheBinder>(); composition.RegisterUnique <IExamineManager>(f => ExamineManager.Instance); composition.RegisterUnique <IUmbracoContextFactory, UmbracoContextFactory>(); composition.RegisterUnique <IMacroRenderer, MacroRenderer>(); composition.RegisterUnique <MediaUrlProviderCollection>(_ => new MediaUrlProviderCollection(Enumerable.Empty <IMediaUrlProvider>())); // initialize some components only/individually composition.WithCollectionBuilder <ComponentCollectionBuilder>() .Clear() .Append <DistributedCacheBinderComponent>(); // configure composition.Configs.Add(SettingsForTests.GetDefaultGlobalSettings); composition.Configs.Add(SettingsForTests.GetDefaultUmbracoSettings); // create and register the factory Current.Factory = factory = composition.CreateFactory(); // instantiate and initialize components var components = factory.GetInstance <ComponentCollection>(); // do stuff Console.WriteLine(runtimeState.Level); // install if (true || runtimeState.Level == RuntimeLevel.Install) { var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var file = databaseFactory.Configured ? Path.Combine(path, "UmbracoNPocoTests.sdf") : Path.Combine(path, "Umbraco.sdf"); if (File.Exists(file)) { File.Delete(file); } // create the database file // databaseBuilder.ConfigureEmbeddedDatabaseConnection() can do it too, // but then it wants to write the connection string to web.config = bad var connectionString = databaseFactory.Configured ? databaseFactory.ConnectionString : "Data Source=|DataDirectory|\\Umbraco.sdf;Flush Interval=1;"; using (var engine = new SqlCeEngine(connectionString)) { engine.CreateDatabase(); } //var databaseBuilder = factory.GetInstance<DatabaseBuilder>(); //databaseFactory.Configure(DatabaseBuilder.EmbeddedDatabaseConnectionString, Constants.DbProviderNames.SqlCe); //databaseBuilder.CreateDatabaseSchemaAndData(); if (!databaseFactory.Configured) { databaseFactory.Configure(DatabaseBuilder.EmbeddedDatabaseConnectionString, Constants.DbProviderNames.SqlCe); } var scopeProvider = factory.GetInstance <IScopeProvider>(); using (var scope = scopeProvider.CreateScope()) { var creator = new DatabaseSchemaCreator(scope.Database, logger); creator.InitializeDatabaseSchema(); scope.Complete(); } } // done installing runtimeState.Level = RuntimeLevel.Run; components.Initialize(); // instantiate to register events // should be done by Initialize? // should we invoke Initialize? _ = factory.GetInstance <IPublishedSnapshotService>(); // at that point, Umbraco can run! // though, we probably still need to figure out what depends on HttpContext... var contentService = factory.GetInstance <IContentService>(); var content = contentService.GetById(1234); Assert.IsNull(content); // create a document type and a document var contentType = new ContentType(-1) { Alias = "ctype", Name = "ctype" }; factory.GetInstance <IContentTypeService>().Save(contentType); content = new Content("test", -1, contentType); contentService.Save(content); // assert that it is possible to get the document back content = contentService.GetById(content.Id); Assert.IsNotNull(content); Assert.AreEqual("test", content.Name); // need an UmbracoCOntext to access the cache // FIXME: not exactly pretty, should not depend on HttpContext var httpContext = Mock.Of <HttpContextBase>(); var umbracoContextFactory = factory.GetInstance <IUmbracoContextFactory>(); var umbracoContextReference = umbracoContextFactory.EnsureUmbracoContext(httpContext); var umbracoContext = umbracoContextReference.UmbracoContext; // assert that there is no published document var pcontent = umbracoContext.ContentCache.GetById(content.Id); Assert.IsNull(pcontent); // but a draft document pcontent = umbracoContext.ContentCache.GetById(true, content.Id); Assert.IsNotNull(pcontent); Assert.AreEqual("test", pcontent.Name); Assert.IsTrue(pcontent.IsDraft()); // no published url Assert.AreEqual("#", pcontent.GetUrl()); // now publish the document + make some unpublished changes contentService.SaveAndPublish(content); content.Name = "testx"; contentService.Save(content); // assert that snapshot has been updated and there is now a published document pcontent = umbracoContext.ContentCache.GetById(content.Id); Assert.IsNotNull(pcontent); Assert.AreEqual("test", pcontent.Name); Assert.IsFalse(pcontent.IsDraft()); // but the url is the published one - no draft url Assert.AreEqual("/test/", pcontent.GetUrl()); // and also an updated draft document pcontent = umbracoContext.ContentCache.GetById(true, content.Id); Assert.IsNotNull(pcontent); Assert.AreEqual("testx", pcontent.Name); Assert.IsTrue(pcontent.IsDraft()); // and the published document has a url Assert.AreEqual("/test/", pcontent.GetUrl()); umbracoContextReference.Dispose(); mainDom.Stop(); components.Terminate(); // exit! }
public void RunJob() { SmtpClient smtpClient = null; try { CoreContext.TenantManager.SetCurrentTenant(_tenantID); SecurityContext.CurrentUser = _currUser; smtpClient = GetSmtpClient(); using (var scope = DIHelper.Resolve()) { var _daoFactory = scope.Resolve <DaoFactory>(); var userCulture = CoreContext.UserManager.GetUsers(_currUser).GetCulture(); Thread.CurrentThread.CurrentCulture = userCulture; Thread.CurrentThread.CurrentUICulture = userCulture; var contactCount = _contactID.Count; if (contactCount == 0) { Complete(); return; } MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone()); var from = new MailboxAddress(_smtpSetting.SenderDisplayName, _smtpSetting.SenderEmailAddress); var filePaths = new List <string>(); using (var fileDao = FilesIntegration.GetFileDao()) { foreach (var fileID in _fileID) { var fileObj = fileDao.GetFile(fileID); if (fileObj == null) { continue; } using (var fileStream = fileDao.GetFileStream(fileObj)) { var directoryPath = Path.Combine(TempPath.GetTempPath(), "teamlab", _tenantID.ToString(), "crm/files/mailsender/"); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } var filePath = Path.Combine(directoryPath, fileObj.Title); using (var newFileStream = File.Create(filePath)) { fileStream.CopyTo(newFileStream); } filePaths.Add(filePath); } } } var templateManager = new MailTemplateManager(_daoFactory); var deliveryCount = 0; try { Error = string.Empty; foreach (var contactID in _contactID) { _exactPercentageValue += 100.0 / contactCount; Percentage = Math.Round(_exactPercentageValue); if (IsCompleted) { break; // User selected cancel } var contactInfoDao = _daoFactory.ContactInfoDao; var startDate = DateTime.Now; var contactEmails = contactInfoDao.GetList(contactID, ContactInfoType.Email, null, true); if (contactEmails.Count == 0) { continue; } var recipientEmail = contactEmails[0].Data; if (!recipientEmail.TestEmailRegex()) { Error += string.Format(CRMCommonResource.MailSender_InvalidEmail, recipientEmail) + "<br/>"; continue; } var to = MailboxAddress.Parse(recipientEmail); var mimeMessage = new MimeMessage { Subject = _subject }; mimeMessage.From.Add(from); mimeMessage.To.Add(to); var bodyBuilder = new BodyBuilder { HtmlBody = templateManager.Apply(_bodyTempate, contactID) }; foreach (var filePath in filePaths) { bodyBuilder.Attachments.Add(filePath); } mimeMessage.Body = bodyBuilder.ToMessageBody(); mimeMessage.Headers.Add("Auto-Submitted", "auto-generated"); _log.Debug(GetLoggerRow(mimeMessage)); var success = false; try { smtpClient.Send(mimeMessage); success = true; } catch (SmtpCommandException ex) { _log.Error(Error, ex); Error += string.Format(CRMCommonResource.MailSender_FailedDeliverException, recipientEmail) + "<br/>"; } if (success) { if (_storeInHistory) { AddToHistory(contactID, string.Format(CRMCommonResource.MailHistoryEventTemplate, mimeMessage.Subject), _daoFactory); } var endDate = DateTime.Now; var waitInterval = endDate.Subtract(startDate); deliveryCount++; var estimatedTime = TimeSpan.FromTicks(waitInterval.Ticks * (_contactID.Count - deliveryCount)); Status = new { RecipientCount = _contactID.Count, EstimatedTime = estimatedTime.ToString(), DeliveryCount = deliveryCount }; } if (MailSenderDataCache.CheckCancelFlag()) { MailSenderDataCache.ResetAll(); throw new OperationCanceledException(); } MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone()); if (Percentage > 100) { Percentage = 100; if (MailSenderDataCache.CheckCancelFlag()) { MailSenderDataCache.ResetAll(); throw new OperationCanceledException(); } MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone()); } } } catch (OperationCanceledException) { _log.Debug("cancel mail sender"); } finally { foreach (var filePath in filePaths) { if (File.Exists(filePath)) { File.Delete(filePath); } } } Status = new { RecipientCount = _contactID.Count, EstimatedTime = TimeSpan.Zero.ToString(), DeliveryCount = deliveryCount }; } } catch (Exception e) { Error = e.Message; _log.Error(Error); } finally { if (smtpClient != null) { smtpClient.Dispose(); } Complete(); } }
// This is NOT thread safe but it is only called from within a lock private Assembly GetModelsAssembly(bool forceRebuild) { if (!Directory.Exists(_pureLiveDirectory.Value)) { Directory.CreateDirectory(_pureLiveDirectory.Value); } IList <TypeModel> typeModels = UmbracoServices.GetAllTypes(); var currentHash = TypeModelHasher.Hash(typeModels); var modelsHashFile = Path.Combine(_pureLiveDirectory.Value, "models.hash"); var modelsSrcFile = Path.Combine(_pureLiveDirectory.Value, "models.generated.cs"); var projFile = Path.Combine(_pureLiveDirectory.Value, "all.generated.cs"); var dllPathFile = Path.Combine(_pureLiveDirectory.Value, "all.dll.path"); // caching the generated models speeds up booting // currentHash hashes both the types & the user's partials if (!forceRebuild) { _logger.LogDebug("Looking for cached models."); if (File.Exists(modelsHashFile) && File.Exists(projFile)) { var cachedHash = File.ReadAllText(modelsHashFile); if (currentHash != cachedHash) { _logger.LogDebug("Found obsolete cached models."); forceRebuild = true; } // else cachedHash matches currentHash, we can try to load an existing dll } else { _logger.LogDebug("Could not find cached models."); forceRebuild = true; } } Assembly assembly; if (!forceRebuild) { // try to load the dll directly (avoid rebuilding) // // ensure that the .dll file does not have a corresponding .dll.delete file // as that would mean the the .dll file is going to be deleted and should not // be re-used - that should not happen in theory, but better be safe if (File.Exists(dllPathFile)) { var dllPath = File.ReadAllText(dllPathFile); _logger.LogDebug($"Cached models dll at {dllPath}."); if (File.Exists(dllPath) && !File.Exists(dllPath + ".delete")) { assembly = ReloadAssembly(dllPath); ModelsBuilderAssemblyAttribute attr = assembly.GetCustomAttribute <ModelsBuilderAssemblyAttribute>(); if (attr != null && attr.IsInMemory && attr.SourceHash == currentHash) { // if we were to resume at that revision, then _ver would keep increasing // and that is probably a bad idea - so, we'll always rebuild starting at // ver 1, but we remember we want to skip that one - so we never end up // with the "same but different" version of the assembly in memory _skipver = assembly.GetName().Version.Revision; _logger.LogDebug("Loading cached models (dll)."); return(assembly); } _logger.LogDebug("Cached models dll cannot be loaded (invalid assembly)."); } else if (!File.Exists(dllPath)) { _logger.LogDebug("Cached models dll does not exist."); } else if (File.Exists(dllPath + ".delete")) { _logger.LogDebug("Cached models dll is marked for deletion."); } else { _logger.LogDebug("Cached models dll cannot be loaded (why?)."); } } // must reset the version in the file else it would keep growing // loading cached modules only happens when the app restarts var text = File.ReadAllText(projFile); Match match = s_assemblyVersionRegex.Match(text); if (match.Success) { text = text.Replace(match.Value, "AssemblyVersion(\"0.0.0." + _ver + "\")"); File.WriteAllText(projFile, text); } _ver++; try { var assemblyPath = GetOutputAssemblyPath(currentHash); RoslynCompiler.CompileToFile(projFile, assemblyPath); assembly = ReloadAssembly(assemblyPath); File.WriteAllText(dllPathFile, assembly.Location); File.WriteAllText(modelsHashFile, currentHash); TryDeleteUnusedAssemblies(dllPathFile); } catch { ClearOnFailingToCompile(dllPathFile, modelsHashFile, projFile); throw; } _logger.LogDebug("Loading cached models (source)."); return(assembly); } // need to rebuild _logger.LogDebug("Rebuilding models."); // generate code, save var code = GenerateModelsCode(typeModels); // add extra attributes, // IsLive=true helps identifying Assemblies that contain live models // AssemblyVersion is so that we have a different version for each rebuild var ver = _ver == _skipver ? ++_ver : _ver; _ver++; string mbAssemblyDirective = $@"[assembly:ModelsBuilderAssembly(IsInMemory = true, SourceHash = ""{currentHash}"")] [assembly:System.Reflection.AssemblyVersion(""0.0.0.{ver}"")]"; code = code.Replace("//ASSATTR", mbAssemblyDirective); File.WriteAllText(modelsSrcFile, code); // generate proj, save var projFiles = new Dictionary <string, string> { { "models.generated.cs", code } }; var proj = GenerateModelsProj(projFiles); File.WriteAllText(projFile, proj); // compile and register try { var assemblyPath = GetOutputAssemblyPath(currentHash); RoslynCompiler.CompileToFile(projFile, assemblyPath); assembly = ReloadAssembly(assemblyPath); File.WriteAllText(dllPathFile, assemblyPath); File.WriteAllText(modelsHashFile, currentHash); TryDeleteUnusedAssemblies(dllPathFile); } catch { ClearOnFailingToCompile(dllPathFile, modelsHashFile, projFile); throw; } _logger.LogDebug("Done rebuilding."); return(assembly); }
public async Task <List <UpdateChannel> > DownloadReleaseHistoryCabAsync() { var guid = Guid.NewGuid().ToString(); var cabPath = Environment.ExpandEnvironmentVariables(@"%temp%\" + guid); Directory.CreateDirectory(cabPath); var savePath = Environment.ExpandEnvironmentVariables(@"%temp%\ReleaseHistory.xml"); var releaseHistoryPath = ""; var localCabPath = Environment.ExpandEnvironmentVariables(@"%temp%\" + guid + @"\" + guid + ".cab"); try { var now = DateTime.Now; var tmpReleaseHistory = Environment.ExpandEnvironmentVariables(@"%temp%\" + now.Year + now.Month + now.Day + now.Hour + "_ReleaseHistory.xml"); using (var releaser = await myLock.LockAsync()) { if (File.Exists(localCabPath)) { File.Delete(localCabPath); } if (!File.Exists(tmpReleaseHistory)) { if (!File.Exists(localCabPath)) { var fd = new FileDownloader(); await fd.DownloadAsync(OfficeVersionHistoryUrl, localCabPath); } var cabExtractor = new CabExtractor(localCabPath); cabExtractor.ExtractCabFiles(); } var dirInfo = new DirectoryInfo(Environment.ExpandEnvironmentVariables(@"%temp%")); foreach (var file in dirInfo.GetFiles("*_ReleaseHistory.xml")) { try { if (!file.FullName.Equals(tmpReleaseHistory, StringComparison.InvariantCultureIgnoreCase)) { File.Delete(file.FullName); } } catch (Exception ex) { } } releaseHistoryPath = Environment.ExpandEnvironmentVariables(@"%temp%\" + guid + @"\ExtractedFiles\ReleaseHistory.xml"); if (File.Exists(tmpReleaseHistory)) { releaseHistoryPath = tmpReleaseHistory; } else { Retry.Block(10, 1, () => File.Copy(releaseHistoryPath, tmpReleaseHistory, true)); } } } catch (Exception ex) { releaseHistoryPath = savePath; } var releaseHistory = GenerateReleaseHistory(releaseHistoryPath); try { using (var releaser = await myLock.LockAsync()) { if (!string.IsNullOrEmpty(releaseHistoryPath)) { if (File.Exists(releaseHistoryPath)) { if (releaseHistoryPath != savePath) { File.Copy(releaseHistoryPath, savePath, true); } } } if (File.Exists(localCabPath)) { File.Delete(localCabPath); } if (Directory.Exists(cabPath)) { Directory.Delete(cabPath, true); } } } catch { } return(releaseHistory); }
public async Task <List <UpdateFiles> > DownloadCabAsync() { var guid = Guid.NewGuid().ToString(); var cabPath = Environment.ExpandEnvironmentVariables(@"%temp%\" + guid); Directory.CreateDirectory(cabPath); var localCabPath = Environment.ExpandEnvironmentVariables(@"%temp%\" + guid + @"\" + guid + ".cab"); if (File.Exists(localCabPath)) { File.Delete(localCabPath); } var now = DateTime.Now; var tmpFile32 = Environment.ExpandEnvironmentVariables(@"%temp%\" + now.Year + now.Month + now.Day + now.Hour + "_32.xml"); var tmpFile64 = Environment.ExpandEnvironmentVariables(@"%temp%\" + now.Year + now.Month + now.Day + now.Hour + "_64.xml"); if (!File.Exists(tmpFile32) || !File.Exists(tmpFile64)) { using (var releaser = await myLock.LockAsync()) { var tmpFile = Environment.ExpandEnvironmentVariables(@"%temp%\" + now.Year + now.Month + now.Day + now.Hour + ".cab"); if (File.Exists(tmpFile)) { Retry.Block(10, 1, () => File.Copy(tmpFile, localCabPath, true)); } if (!File.Exists(localCabPath)) { var fd = new FileDownloader(); await fd.DownloadAsync(OfficeVersionUrl, localCabPath); try { File.Copy(localCabPath, tmpFile); } catch { } } var cabExtractor = new CabExtractor(localCabPath); cabExtractor.ExtractCabFiles(); } } var xml32Path = Environment.ExpandEnvironmentVariables(@"%temp%\" + guid + @"\ExtractedFiles\o365client_32bit.xml"); var xml64Path = Environment.ExpandEnvironmentVariables(@"%temp%\" + guid + @"\ExtractedFiles\o365client_64bit.xml"); if (File.Exists(tmpFile32)) { xml32Path = tmpFile32; } else { Retry.Block(10, 1, () => File.Copy(xml32Path, tmpFile32, true)); } if (File.Exists(tmpFile64)) { xml64Path = tmpFile64; } else { Retry.Block(10, 1, () => File.Copy(xml64Path, tmpFile64, true)); } var updateFiles32 = GenerateUpdateFiles(xml32Path); var updateFiles64 = GenerateUpdateFiles(xml64Path); try { if (File.Exists(localCabPath)) { File.Delete(localCabPath); } if (Directory.Exists(cabPath)) { Directory.Delete(cabPath, true); } } catch { } return(new List <UpdateFiles>() { updateFiles32, updateFiles64 }); }
public async Task <bool> ValidateSourceFiles(DownloadBranchProperties properties, CancellationToken token = new CancellationToken()) { var fd = new FileDownloader(); if (properties.Languages == null) { properties.Languages = new List <string>() { "en-us" } } ; if (_updateFiles == null) { for (var t = 1; t <= 20; t++) { try { _updateFiles = await DownloadCabAsync(); break; } catch (Exception ex) { } await Task.Delay(1000, token); } } var selectUpdateFile = new UpdateFiles(); if (properties.OfficeEdition == OfficeEdition.Office32Bit) { selectUpdateFile = _updateFiles.FirstOrDefault(u => u.OfficeEdition == OfficeEdition.Office32Bit); } else if (properties.OfficeEdition == OfficeEdition.Office64Bit) { selectUpdateFile = _updateFiles.FirstOrDefault(u => u.OfficeEdition == OfficeEdition.Office64Bit); } else if (properties.OfficeEdition == OfficeEdition.Both) { var selectUpdateFile32 = _updateFiles.FirstOrDefault(u => u.OfficeEdition == OfficeEdition.Office32Bit); var selectUpdateFile64 = _updateFiles.FirstOrDefault(u => u.OfficeEdition == OfficeEdition.Office64Bit); selectUpdateFile32.Files.AddRange(selectUpdateFile64.Files); selectUpdateFile = selectUpdateFile32; } if (selectUpdateFile == null) { throw (new Exception("Cannot Find Office Files")); } var branch = selectUpdateFile.BaseURL.FirstOrDefault(b => b.Branch.ToLower() == properties.BranchName.ToLower()); var version = properties.Version; if (string.IsNullOrEmpty(properties.Version)) { version = await GetLatestVersionAsync(branch, properties.OfficeEdition); } var allFiles = new List <Model.File>(); foreach (var language in properties.Languages) { var langCode = language.GetLanguageNumber(); var langfiles = selectUpdateFile.Files.Where(f => f.Language == 0 || f.Language == langCode); foreach (var file in langfiles) { file.Name = Regex.Replace(file.Name, "%version%", version, RegexOptions.IgnoreCase); file.RelativePath = Regex.Replace(file.RelativePath, "%version%", version, RegexOptions.IgnoreCase); file.RemoteUrl = branch.URL + @"/" + file.RelativePath + file.Name; file.FileSize = await fd.GetFileSizeAsync(file.RemoteUrl); allFiles.Add(file); } } allFiles = allFiles.Distinct().ToList(); foreach (var file in allFiles) { file.LocalFilePath = properties.TargetDirectory + file.RelativePath.Replace("/", "\\") + file.Name; } foreach (var file in allFiles) { var localFilePath = properties.TargetDirectory + file.RelativePath.Replace("/", "\\") + file.Name; if (!File.Exists(localFilePath)) { return(false); } } return(true); }
private async Task DownloadRemotelyAgent(string serverUrl) { var targetFile = Path.Combine(Path.GetTempPath(), $"Remotely-Agent.zip"); if (CommandLineParser.CommandLineArgs.TryGetValue("path", out var result) && FileIO.Exists(result)) { targetFile = result; } else { ProgressMessageChanged.Invoke(this, "Downloading Remotely agent."); var client = new WebClient(); client.DownloadProgressChanged += (sender, args) => { ProgressValueChanged?.Invoke(this, args.ProgressPercentage); }; await client.DownloadFileTaskAsync($"{serverUrl}/Downloads/Remotely-Win10-{Platform}.zip", targetFile); } ProgressMessageChanged.Invoke(this, "Extracting Remotely files."); ProgressValueChanged?.Invoke(this, 0); var tempDir = Path.Combine(Path.GetTempPath(), "RemotelyUpdate"); if (Directory.Exists(tempDir)) { Directory.Delete(tempDir, true); } Directory.CreateDirectory(InstallPath); while (!Directory.Exists(InstallPath)) { await Task.Delay(10); } var wr = WebRequest.CreateHttp($"{serverUrl}/Downloads/Remotely-Win10-{Platform}.zip"); wr.Method = "Head"; using (var response = (HttpWebResponse)await wr.GetResponseAsync()) { FileIO.WriteAllText(Path.Combine(InstallPath, "etag.txt"), response.Headers["ETag"]); } ZipFile.ExtractToDirectory(targetFile, tempDir); var fileSystemEntries = Directory.GetFileSystemEntries(tempDir); for (var i = 0; i < fileSystemEntries.Length; i++) { try { ProgressValueChanged?.Invoke(this, (int)((double)i / (double)fileSystemEntries.Length * 100d)); var entry = fileSystemEntries[i]; if (FileIO.Exists(entry)) { FileIO.Copy(entry, Path.Combine(InstallPath, Path.GetFileName(entry)), true); } else if (Directory.Exists(entry)) { FileSystem.CopyDirectory(entry, Path.Combine(InstallPath, new DirectoryInfo(entry).Name), true); } await Task.Delay(1); } catch (Exception ex) { Logger.Write(ex); } } ProgressValueChanged?.Invoke(this, 0); }
private async void MainForm_Load(object sender, EventArgs e) { await Task.Delay(10); // Load online data var data = await FetchOnlineDataAsync(); lblAbout.Text = data.AboutText; // Order the list to get the featured servers to the top, putting bancho back at index 0 m_servers.Add(Server.BanchoServer); m_servers.AddRange(data.Servers.Where(x => x.IsFeatured)); m_servers.AddRange(data.Servers.Where(x => !x.IsFeatured)); m_servers.Add(Server.LocalhostServer); lblCurrentServer.Text = "Updating icon cache..."; Application.DoEvents(); // Check if servers which icon is in cache no longer exist foreach (string icon in Directory.GetFiles(m_iconCacheFolder, "*.png", SearchOption.TopDirectoryOnly)) { string name = Path.GetFileNameWithoutExtension(icon); if (!m_servers.Any(x => x.ServerName == name)) { File.Delete(icon); } } // Check for servers which icons arent in cache yet foreach (Server server in m_servers) { if (!File.Exists(m_iconCacheFolder + $@"\{server.ServerName}.png") && !string.IsNullOrEmpty(server.IconUrl)) { lblCurrentServer.Text = $"Downloading icon of {server.ServerName}..."; Application.DoEvents(); Image icon = await DownloadImageAsync(server.IconUrl); icon.Save(m_iconCacheFolder + $@"\{server.ServerName}.png"); icon.Dispose(); } } // Load icons from cache foreach (Server server in m_servers) { if (File.Exists(m_iconCacheFolder + $@"\{server.ServerName}.png")) { using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(m_iconCacheFolder + $@"\{server.ServerName}.png"))) server.Icon = Image.FromStream(ms); } } // Create .ico files for shortcuts foreach (Server server in m_servers) { if (server.Icon != null) { using (FileStream fs = File.OpenWrite(m_iconCacheFolder + $@"\{server.ServerName}.ico")) using (MemoryStream ms = new MemoryStream((byte[])new ImageConverter().ConvertTo(server.Icon, typeof(byte[])))) ImagingHelper.ConvertToIcon(ms, fs, 48, true); } } //Adds all servers to combo box foreach (Server server in m_servers) { string name = server.ServerName; if (server.IsFeatured) { name = "⭐" + name + "⭐"; } cmbbxServer.Items.Add(name); } bool newVersionAvailable = await VersionChecker.NewVersionAvailable(); btnUpdateAvailable.Visible = newVersionAvailable; lblClearIconCache.Enabled = true; lblCreateShortcut.Show(); UpdateServerUI(); osuWatcher.Start(); }
/// <inheritdoc /> /// <returns> /// False if: /// Invalid OpenSauce binaries directory path. /// - or - /// Important OpenSauce binaries don't exist. /// - or - /// Kornner Studios or its contents do not exist. /// - or - /// Direct3D9 Extensions DXSetup is not present. /// </returns> public Verification Verify() { var dxrDir = Path.Combine(Paths.KStudios, OpenSauceDirectory, "dxredist"); var dxrFiles = new List <string> { "dsetup.dll", "dsetup32.dll", "dxdllreg_x86.cab", "dxredist.zip", "dxsetup.exe", "dxupdate.cab", "Jun2010_d3dx9_43_x86.cab" }; var osMainClientBinaries = new List <string> { /* variants of client dll */ "dinput8.dll", "opensauce.dll", // another app will need to move or rename this Path.Combine("mods", "opensauce.dll") // needs a mod loader }; var osMainBinaries = new List <string> { "CheApe.map", "CheApeDLLG.dll", "CheApeDLLS.dll", "CheApeDLLT.dll", "crashrpt_lang.ini", "CrashRpt1401.dll", "CrashSender1401.exe", "dbghelp.dll", "Halo1_CE_Readme.txt", "Halo1_CheApe_Readme.txt", "msvcp100.dll", "msvcp120.dll", "msvcr100.dll", "msvcr120.dll", "OpenSauceDedi.dll", "OS_Guerilla.exe", "OS_haloceded.exe", "OS_Sapien.exe", "OS_Settings.Editor.xml", "OS_Tool.exe" }; if (!Directory.Exists(_binariesPath)) { return(new Verification(false, "Selected directory for OpenSauce binaries doesn't exist.")); } if (!osMainClientBinaries.Any(bin => File.Exists(Path.Combine(_binariesPath, bin)))) { return(new Verification(false, "OpenSauce client binary not found.")); } foreach (var bin in osMainBinaries) { if (!File.Exists(Path.Combine(_binariesPath, bin))) { return(new Verification(false, $"OpenSauce main binary not found: {bin}")); } } if (!Directory.Exists(Paths.KStudios)) { return(new Verification(false, $"Kornner Studios not found in \"{Paths.ProgData}\"")); } if (!Directory.Exists(dxrDir)) { return(new Verification(false, $"Direct3D9 Extensions not found in {dxrDir}")); } foreach (var dxredist in dxrFiles) { if (!File.Exists(Path.Combine(dxrDir, dxredist))) { return(new Verification(false, $"DirectX Redist file not found: {dxredist}")); } } if (!Directory.Exists(Path.Combine(Paths.KStudios, OpenSauceDirectory, OpenSauceIDE))) { return(new Verification(false, "OpenSauceIDE not found in '/Kornner Studios/OpenSauce/'" + NewLine + "Deleted by Install procedure?")); } return(new Verification(true)); }
private void ReadExcel(string pathFile) { _excel = new AccessExcel(); _excel.DoAccess(pathFile); emailsListView.Items.Clear(); int count = _excel.MaxRows(); for (int i = 2; i < count; i++) { int j = 2; #region PersonReadExcel Person p = new Person(); p.email = _excel.ReadCellString(i, j++); if (!Persons.Exists(person => person.email == p.email)) { p.URLPhoto = _excel.ReadCellString(i, j++); p.SurName = _excel.ReadCellString(i, j++); p.Name = _excel.ReadCellString(i, j++); p.Patronomyc = _excel.ReadCellString(i, j++); p.Telefon = _excel.ReadCellString(i, j++); p.Birthday = _excel.ReadDate(i, j++); p.BirthdayMesto = _excel.ReadCellString(i, j++); p.Country = _excel.ReadCellString(i, j++); p.Addres = _excel.ReadCellString(i, j++); p.AddresRegistry = _excel.ReadCellString(i, j++); p.SubjectRF = _excel.ReadCellString(i, j++); p.VK = _excel.ReadCellString(i, j++); p.Health = _excel.ReadCellString(i, j++); p.HealtHron = _excel.ReadCellString(i, j++); p.VUZ = _excel.ReadCellString(i, j++); p.VUZKor = _excel.ReadCellString(i, j++); p.Specialnost = _excel.ReadCellString(i, j++); p.Diplom = _excel.ReadCellString(i, j++); p.SrBall = _excel.ReadCellDouble(i, j++); p.VKR = _excel.ReadCellString(i, j++); p.Soiskatelstvo = _excel.ReadCellString(i, j++) == "Да" ? 5 : 0; p.Exams = _excel.ReadCellString(i, j++); p.Statiy[0] = _excel.ReadCellString(i, j++) == "Есть" ? 5 : 0; p.Statiy[1] = _excel.ReadCellString(i, j++) == "Есть" ? 4 : 0; p.Statiy[2] = _excel.ReadCellString(i, j++) == "Есть" ? 3 : 0; p.Statiy[3] = _excel.ReadCellString(i, j++) == "Есть" ? 1 : 0; p.Statiy[4] = _excel.ReadCellString(i, j++) == "Есть" ? 1 : 0; p.Statiy[5] = _excel.ReadCellString(i, j++) == "Есть" ? 0.5 : 0; p.Sience[0] = _excel.ReadCellString(i, j++) == "Есть" ? 4 : 0; p.Sience[1] = _excel.ReadCellString(i, j++) == "Есть" ? 4 : 0; p.Sience[2] = _excel.ReadCellString(i, j++) == "Есть" ? 3 : 0; p.Sience[3] = _excel.ReadCellString(i, j++) == "Есть" ? 3 : 0; p.Sience[4] = _excel.ReadCellString(i, j++) == "Есть" ? 3 : 0; p.Sience[5] = _excel.ReadCellString(i, j++) == "Есть" ? 2 : 0; p.Sience[6] = _excel.ReadCellString(i, j++) == "Есть" ? 1 : 0; p.SienceName = _excel.ReadCellString(i, j++); p.SienceStepen[0] = _excel.ReadCellString(i, j++) == "Есть" ? 3 : 0; p.SienceStepen[1] = _excel.ReadCellString(i, j++) == "Есть" ? 6 : 0; p.SienceStepen[2] = _excel.ReadCellString(i, j++) == "Есть" ? 8 : 0; p.Work[0] = _excel.ReadCellString(i, j++) == "Есть" ? 2 : 0; p.Work[1] = _excel.ReadCellString(i, j++) == "Есть" ? 4 : 0; p.Work[2] = _excel.ReadCellString(i, j++) == "Есть" ? 6 : 0; p.Sport[0] = _excel.ReadCellString(i, j++) == "Есть" ? 4 : 0; p.Sport[1] = _excel.ReadCellString(i, j++) == "Есть" ? 2 : 0; p.Language = _excel.ReadCellString(i, j++); p.Products = _excel.ReadCellString(i, j++); p.Napravlenie = _excel.ReadCellString(i, j++); p.Dopusk = _excel.ReadCellString(i, j++); p.TattooAndPirsing = _excel.ReadCellString(i, j++); p.Rost = _excel.ReadCellDouble(i, j++); p.Ves = _excel.ReadCellDouble(i, j++); p.Family = _excel.ReadCellString(i, j++); p.Child = _excel.ReadCellString(i, j++); p.Info = _excel.ReadCellString(i, j++); p.Prioritet[0] = _excel.ReadCellString(i, 100) == "Есть" ? 3 : 0; p.Prioritet[1] = _excel.ReadCellString(i, 101) == "Есть" ? 1 : 0; p.Reserv = _excel.ReadCellString(i, 102) == "Резерв"; p.Magistr = _excel.ReadCellString(i, 103) == "Магистр"; p.Bakalavr = _excel.ReadCellString(i, 103) == "Бакаларв"; p.Zachetka = _excel.ReadCellString(i, 103) == "Зачетка"; p.Ball = p.ExecuteBall(); #endregion emailsListView.Items.Add(p.email, p.ToString(), p.Status); Persons.Add(p); } } emailsListView.Items.Clear(); foreach (var person in Persons) { AddPersonInList(emailsListView, person); if (string.IsNullOrEmpty(person.PDFPath) && !File.Exists(person.PDFPath)) { person.PDFPath = word.ListStart(person); } word.Close(); } _excel.FinishAccess(); }
//specify packagefile to create a new package //specify -u oldpackage newpackage to create an update from oldpackage to newpackage static int Main(string[] args) { FileSystem.Current = new FileSystem(); TimeService.Current = new TimeService(); ArchiveFactory.Current = new ArchiveFactory(); if (args.Length == 3 && args[1] == "-o") { try { Console.WriteLine("Creating installer package"); if (!Directory.Exists(args[0])) { Console.WriteLine("Error: Directory " + args[0] + " not found"); return(1); } CreateInstaller(args[0], args[2], file => file.StartsWith(".svn", StringComparison.OrdinalIgnoreCase)); PackageMetadata metadata = new PackageMetadata(); if (!ValidateInstaller(args[2], metadata)) { return(1); } Console.WriteLine("Installer package created"); Console.WriteLine(" Version: " + metadata.Version); Console.WriteLine(" MD5: " + metadata.MD5); } catch (Exception ex) { Console.WriteLine("Error: " + ex); Console.WriteLine("Installer package creation failed"); } } else if (args.Length == 5 && args[0] == "-u" && args[3] == "-o") { try { Console.WriteLine("Creating update installer package"); if (!File.Exists(args[1])) { Console.WriteLine("Error: File " + args[1] + " not found"); return(1); } GameInstall oldInstall; if (!ValidateNonUpdateInstaller(args[1], out oldInstall)) { return(1); } if (!File.Exists(args[2])) { Console.WriteLine("Error: File " + args[2] + " not found"); return(1); } GameInstall newInstall; if (!ValidateNonUpdateInstaller(args[2], out newInstall)) { return(1); } var details = new UpdateDetails { UpdateVersion = oldInstall.Game.Version }; oldInstall.Dispose(); newInstall.Dispose(); CreateUpdateInstaller(details, args[1], args[2], args[4]); PackageMetadata metadata = new PackageMetadata(); if (!ValidateInstaller(args[4], metadata)) { return(1); } Console.WriteLine("Installer update package created"); Console.WriteLine(" Version: " + metadata.Version); Console.WriteLine(" MD5: " + metadata.MD5); } catch (Exception ex) { Console.WriteLine("Error: " + ex); Console.WriteLine("Installer update package creation failed"); } } else if (args.Length == 0) { Console.WriteLine("Usage"); Console.WriteLine(); Console.WriteLine("GamesManager.PackageGen <installer package folder> -o <installer package>"); Console.WriteLine(" Creates a new installer package from a directory."); Console.WriteLine("GamesManager.PackageGen -u <old installer package> <new installer package> -o <installer package>"); Console.WriteLine(" Creates a new installer package that updates the old game to the new one."); } return(0); }
public static bool Create(string shortcutPath, string targetPath, string arguments = "") { #if !__MonoCS__ if (!string.IsNullOrEmpty(shortcutPath) && !string.IsNullOrEmpty(targetPath) && File.Exists(targetPath)) { try { IWshShell wsh = new WshShellClass(); IWshShortcut shortcut = (IWshShortcut)wsh.CreateShortcut(shortcutPath); shortcut.TargetPath = targetPath; shortcut.Arguments = arguments; shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath); shortcut.Save(); return(true); } catch (Exception e) { DebugHelper.WriteException(e); } } #endif return(false); }
private void ChangeTagsInFile(string path, string pattern) { var tagPlaceholdersMatches = Regex.Matches(pattern, "(%([^%]*)%)"); if (!File.Exists(path)) { throw new Exception($"File '{path}' doesn't exist!"); } if (tagPlaceholdersMatches.Count == 0) { throw new Exception($"Invalid pattern '{pattern}'!"); } TagLibFile tagLibFile; try { tagLibFile = TagLibFile.Create(path); if (tagLibFile.Properties.MediaTypes != MediaTypes.Audio) { throw new Exception($"'{path}' is not audio! Skipping it..."); } } catch (Exception exception) { throw new Exception($"{nameof(TagLib.File)} for '{path}' doesn't created!", exception); } RemoveAllTags(path); using (tagLibFile) { var fileName = Path.GetFileNameWithoutExtension(path); if (fileName == null) { throw new NullReferenceException(); } var tagPattern = pattern; tagPattern = Regex.Escape(tagPattern); foreach (Match placeholderMatch in tagPlaceholdersMatches) { tagPattern = tagPattern.Replace(placeholderMatch.Groups[1].Value, $"(?<{placeholderMatch.Groups[2].Value}>.+)"); } var tagMatch = Regex.Match(fileName, tagPattern); foreach (Match placeholderMatch in tagPlaceholdersMatches) { var tagName = placeholderMatch.Groups[2].Value; tagPropertyEditor.AssignTag( tagLibFile: tagLibFile, name: tagName, value: tagMatch.Groups[tagName].Value); } tagLibFile.Save(); } }
public static bool CheckShortcut(Environment.SpecialFolder specialFolder) { string shortcutPath = GetShortcutPath(specialFolder); return(File.Exists(shortcutPath)); }
static void Main(string[] args) { Log("--------------------"); Log("* Start : Samples directory: " + Samples); Log(""); // Override command arguments args = new[] { "sample.wav" }; foreach (var fname in args) { var fpath = Samples + fname; var tpath = Samples + "tmpwrite" + Path.GetExtension(fname); Log("+ File : " + fpath); if (!File.Exists(fpath)) { Log(" # File not found: " + fpath); continue; } Log(" read : " + fpath); var rfile = TagLib.File.Create(fpath); Log(" Type : " + rfile.MimeType); File.Copy(fpath, tpath, true); var file = TagLib.File.Create(tpath); Log(" Type : " + file.MimeType); Log(" rboy1 test start : " + file.MimeType); var MKVTag = (TagLib.Matroska.Tag)file.GetTag(TagTypes.Matroska); MKVTag.Title = "my Title"; MKVTag.Set("SUBTITLE", null, "my SubTitle"); MKVTag.Set("DESCRIPTION", null, "my Description"); MKVTag.Set("TVCHANNEL", null, "my Network"); MKVTag.Set("LAW_RATING", null, "my Rating"); MKVTag.Set("ACTOR", null, "my MediaCredits"); MKVTag.Set("GENRE", null, "my Genres"); MKVTag.Set("SEASON", null, "my Season"); MKVTag.Set("EPISODE", null, "my Episode"); var bannerFile = Samples + "sample_invalidifdoffset.jpg"; var videoPicture = new Picture(bannerFile); MKVTag.Pictures = new IPicture[] { videoPicture }; Log(" rboy1 test save : " + file.MimeType); file.Save(); Log(" rboy1 test read : " + file.MimeType); var tagFile = TagLib.File.Create(tpath); Log(" rboy1 test end : " + file.MimeType); var tag = file.Tag; var pics = file.Tag.Pictures; var mtag = (TagLib.Matroska.Tag)file.GetTag(TagTypes.Matroska); mtag.PerformersRole = new[] { "TEST role 1", "TEST role 2" }; Log(" Picture : " + pics[0].Description); var tracks = mtag.Tags.Tracks; var audiotag = mtag.Tags.Get(tracks[1]); if (audiotag != null) { audiotag.Clear(); audiotag.Title = "The Noise"; audiotag.Set("DESCRIPTION", null, "Useless background noise"); } Log(" Erase : " + tag.Title); file.RemoveTags(TagTypes.Matroska); file.Save(); Log(" Write : " + tag.Title); tag.TitleSort = "title, TEST"; tag.AlbumSort = "album, TEST"; tag.PerformersSort = new[] { "performer 1, TEST", "performer 2, TEST" }; tag.ComposersSort = new[] { "composer 1, TEST", "composer 2, TEST" }; tag.AlbumArtistsSort = new[] { "album artist 1, TEST", "album artist 2, TEST" }; tag.Album = "TEST album"; tag.AlbumArtists = new[] { "TEST album artist 1", "TEST album artist 2" }; tag.BeatsPerMinute = 120; tag.Comment = "TEST comment"; tag.Composers = new[] { "TEST composer 1", "TEST composer 2" }; tag.Conductor = "TEST conductor"; tag.Copyright = "TEST copyright"; tag.Disc = 1; tag.DiscCount = 2; tag.Genres = new[] { "TEST genre 1", "TEST genre 2" }; tag.Grouping = "TEST grouping"; tag.Lyrics = "TEST lyrics 1\r\nTEST lyrics 2"; tag.Performers = new[] { "TEST performer 1", "TEST performer 2" }; tag.Title = "TEST title"; tag.Track = 5; tag.TrackCount = 10; tag.Year = 1999; // Insert new picture Array.Resize(ref pics, 2); pics[1] = new Picture(Samples + "sample_sony2.jpg"); file.Tag.Pictures = pics; file.Save(); Log(" Done : " + tag.Title); // Now read it again file = TagLib.File.Create(tpath); tag = file.Tag; mtag = (TagLib.Matroska.Tag)file.GetTag(TagTypes.Matroska); Log(" Read : " + tag.Title); Log(" Album : " + tag.Album); Log(" JoinedAlbumArtists : " + tag.JoinedAlbumArtists); Log(" BeatsPerMinute : " + tag.BeatsPerMinute); Log(" Comment : " + tag.Comment); Log(" JoinedComposers : " + tag.JoinedComposers); Log(" Conductor : " + tag.Conductor); Log(" Copyright : " + tag.Copyright); Log(" Disc : " + tag.Disc); Log(" DiscCount : " + tag.DiscCount); Log(" JoinedGenres : " + tag.JoinedGenres); Log(" Grouping : " + tag.Grouping); Log(" Lyrics : " + tag.Lyrics); Log(" JoinedPerformers : " + tag.JoinedPerformers); Log(" Title : " + tag.Title); Log(" Track : " + tag.Track); Log(" TrackCount : " + tag.TrackCount); Log(" Year : " + tag.Year); Log(" TitleSort : " + tag.TitleSort); Log(" AlbumSort : " + tag.AlbumSort); Log(" PerformersSort : " + tag.JoinedPerformersSort); Log(" ComposersSort : " + string.Join("; ", tag.ComposersSort)); Log(" AlbumArtistsSort : " + string.Join("; ", tag.AlbumArtistsSort)); Log(" PerformersRole : " + string.Join("; ", mtag.PerformersRole)); Log(" Done : " + tag.Title); } Log("* End"); }
private void InstallScripts(string path) { Logger.Info($"Installing Scripts to {path}"); _progressBarDialog.UpdateProgress(false, $"Creating Script folders @ {path}"); //Scripts Path CreateDirectory(path + "\\Scripts"); CreateDirectory(path + "\\Scripts\\Hooks"); //Make Tech Path CreateDirectory(path + "\\Mods"); CreateDirectory(path + "\\Mods\\Services"); CreateDirectory(path + "\\Mods\\Services\\DCS-SRS"); Task.Delay(TimeSpan.FromMilliseconds(100)).Wait(); _progressBarDialog.UpdateProgress(false, $"Updating / Creating Export.lua @ {path}"); Logger.Info($"Handling Export.lua"); //does it contain an export.lua? if (File.Exists(path + "\\Scripts\\Export.lua")) { var contents = File.ReadAllText(path + "\\Scripts\\Export.lua"); contents.Split('\n'); if (contents.Contains("SimpleRadioStandalone.lua")) { Logger.Info($"Updating existing Export.lua with existing SRS install"); var lines = contents.Split('\n'); StringBuilder sb = new StringBuilder(); foreach (var line in lines) { if (line.Contains("SimpleRadioStandalone.lua")) { sb.Append("\n"); sb.Append(EXPORT_SRS_LUA); sb.Append("\n"); } else if (line.Trim().Length > 0) { sb.Append(line); sb.Append("\n"); } } File.WriteAllText(path + "\\Scripts\\Export.lua", sb.ToString()); } else { Logger.Info($"Appending to existing Export.lua"); var writer = File.AppendText(path + "\\Scripts\\Export.lua"); writer.WriteLine("\n" + EXPORT_SRS_LUA + "\n"); writer.Close(); } } else { Logger.Info($"Creating new Export.lua"); var writer = File.CreateText(path + "\\Scripts\\Export.lua"); writer.WriteLine("\n" + EXPORT_SRS_LUA + "\n"); writer.Close(); } //Now sort out Scripts//Hooks folder contents Logger.Info($"Creating / installing Hooks & Mods / Services"); _progressBarDialog.UpdateProgress(false, $"Creating / installing Hooks & Mods/Services @ {path}"); try { File.Copy(_currentDirectory + "\\Scripts\\Hooks\\DCS-SRS-hook.lua", path + "\\Scripts\\Hooks\\DCS-SRS-hook.lua", true); DirectoryCopy(_currentDirectory + "\\Scripts\\DCS-SRS", path + "\\Mods\\Services\\DCS-SRS"); } catch (FileNotFoundException ex) { MessageBox.Show( "Install files not found - Unable to install! \n\nMake sure you extract all the files in the zip then run the Installer", "Not Unzipped", MessageBoxButton.OK, MessageBoxImage.Error); Environment.Exit(0); } Logger.Info($"Scripts installed to {path}"); _progressBarDialog.UpdateProgress(false, $"Installed Hooks & Mods/Services @ {path}"); }
async Task OnTick() { LogEventLevel?minimumAcceptedLevel = LogEventLevel.Debug; try { // Locking the bookmark ensures that though there may be multiple instances of this // class running, only one will ship logs at a time. using (var bookmark = IOFile.Open(_bookmarkFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read)) { using (var bookmarkStreamReader = new StreamReader(bookmark, _encoding, false, 128)) { using (var bookmarkStreamWriter = new StreamWriter(bookmark)) { int count; do { count = 0; long nextLineBeginsAtOffset; string currentFile; TryReadBookmark(bookmark, bookmarkStreamReader, out nextLineBeginsAtOffset, out currentFile); var fileSet = GetFileSet(); if (currentFile == null || !IOFile.Exists(currentFile)) { nextLineBeginsAtOffset = 0; currentFile = fileSet.FirstOrDefault(); } if (currentFile == null) { continue; } //grab the list of pending LogglyEvents from the file var payload = GetListOfEvents(currentFile, ref nextLineBeginsAtOffset, ref count); if (count > 0) { //send the loggly events through the bulk API var result = await _logglyClient.Log(payload).ConfigureAwait(false); if (result.Code == ResponseCode.Success) { _connectionSchedule.MarkSuccess(); WriteBookmark(bookmarkStreamWriter, nextLineBeginsAtOffset, currentFile); } else if (result.Code == ResponseCode.Error) { // The connection attempt was successful - the payload we sent was the problem. _connectionSchedule.MarkSuccess(); DumpInvalidPayload(result, payload); WriteBookmark(bookmarkStreamWriter, nextLineBeginsAtOffset, currentFile); } else { _connectionSchedule.MarkFailure(); SelfLog.WriteLine("Received failed HTTP shipping result {0}: {1}", result.Code, result.Message); break; } } else { // For whatever reason, there's nothing waiting to send. This means we should try connecting again at the // regular interval, so mark the attempt as successful. _connectionSchedule.MarkSuccess(); // Only advance the bookmark if no other process has the // current file locked, and its length is as we found it. if (fileSet.Length == 2 && fileSet.First() == currentFile && IsUnlockedAtLength(currentFile, nextLineBeginsAtOffset)) { WriteBookmark(bookmarkStreamWriter, 0, fileSet[1]); } if (fileSet.Length > 2) { // Once there's a third file waiting to ship, we do our // best to move on, though a lock on the current file // will delay this. IOFile.Delete(fileSet[0]); } } } while (count == _batchPostingLimit); } } } } catch (Exception ex) { SelfLog.WriteLine("Exception while emitting periodic batch from {0}: {1}", this, ex); _connectionSchedule.MarkFailure(); } finally { lock (_stateLock) { _controlledSwitch.Update(minimumAcceptedLevel); if (!_unloading) { SetTimer(); } } } }
private bool CheckForVsCode(string frcHomePath) { var codeBatFile = Path.Combine(frcHomePath, "vscode", "bin", "code.cmd"); return(File.Exists(codeBatFile)); }
/// <summary> /// Download data from remote via uri query. /// </summary> /// <param name="fileName">A file to store the downloaded data.</param> /// <param name="query">Uri query</param> /// <param name="request">An object passed in from the PackageManagement platform that contains APIs that can be used to interact with it </param> /// <param name="networkCredential">Credential to pass along to get httpclient</param> /// <param name="progressTracker">Utility class to help track progress</param> /// <returns></returns> internal static async Task <long> DownloadDataToFileAsync(string fileName, string query, PackageSourceListRequest request, NetworkCredential networkCredential, ProgressTracker progressTracker) { request.Verbose(Resources.Messages.DownloadingPackage, query); // try downloading for 3 times int remainingTry = 3; long totalDownloaded = 0; CancellationTokenSource cts; Stream input = null; FileStream output = null; while (remainingTry > 0) { // if user cancel the request, no need to do anything if (request.IsCanceled) { break; } input = null; output = null; cts = new CancellationTokenSource(); totalDownloaded = 0; try { // decrease try by 1 remainingTry -= 1; var httpClient = request.Client; httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "text/html; charset=iso-8859-1"); input = await httpClient.GetStreamAsync(query); // buffer size of 64 KB, this seems to be preferable buffer size, not too small and not too big byte[] bytes = new byte[1024 * 64]; output = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read); int current = 0; // here we read content that we got from the http response stream into the bytes array current = await input.ReadAsync(bytes, 0, bytes.Length, cts.Token); int progressPercentage = progressTracker.StartPercent; // report initial progress request.Progress(progressTracker.ProgressID, progressPercentage, Resources.Messages.BytesRead, current); int i = progressTracker.StartPercent; while (current > 0) { totalDownloaded += current; // here we write out the bytes array into the file await output.WriteAsync(bytes, 0, current, cts.Token); // report the progress request.Progress(progressTracker.ProgressID, progressPercentage < progressTracker.EndPercent?progressPercentage++:progressTracker.EndPercent, Resources.Messages.BytesRead, totalDownloaded); // continue reading from the stream current = await input.ReadAsync(bytes, 0, bytes.Length, cts.Token); } if (totalDownloaded > 0) { // report that we finished the download request.Progress(progressTracker.ProgressID, progressTracker.EndPercent, Resources.Messages.BytesRead, totalDownloaded); request.CompleteProgress(progressTracker.ProgressID, true); return(totalDownloaded); } // if request is canceled, don't retry if (request.IsCanceled) { return(0); } } catch (Exception ex) { request.CompleteProgress(progressTracker.ProgressID, true); request.Verbose(ex.Message); request.Debug(ex.StackTrace); } finally { // dispose input and output stream if (input != null) { input.Dispose(); } // dispose it if (output != null) { output.Dispose(); } // delete the file if created and nothing has downloaded if (totalDownloaded == 0 && File.Exists(fileName)) { fileName.TryHardToDelete(); } if (cts != null) { cts.Dispose(); } } // we have to retry again request.Verbose(Resources.Messages.RetryingDownload, query, remainingTry); } return(totalDownloaded); }
private void SetVsCodeSettings(string frcHomePath) { //data\user-data\User var vsCodePath = Path.Combine(frcHomePath, "vscode"); var settingsDir = Path.Combine(vsCodePath, "data", "user-data", "User"); var settingsFile = Path.Combine(settingsDir, "settings.json"); try { Directory.CreateDirectory(settingsDir); } catch (IOException) { } dynamic settingsJson = new JObject(); if (File.Exists(settingsFile)) { settingsJson = (JObject)JsonConvert.DeserializeObject(File.ReadAllText(settingsFile)); } setIfNotSet("java.home", Path.Combine(frcHomePath, "jdk"), settingsJson); setIfNotSet("extensions.autoUpdate", false, settingsJson); setIfNotSet("extensions.autoCheckUpdates", false, settingsJson); setIfNotSet("extensions.ignoreRecommendations", true, settingsJson); setIfNotSet("extensions.showRecommendationsOnlyOnDemand", false, settingsJson); setIfNotSet("update.channel", "none", settingsJson); setIfNotSet("update.showReleaseNotes", false, settingsJson); if (!settingsJson.ContainsKey("terminal.integrated.env.windows")) { dynamic terminalProps = new JObject(); terminalProps["JAVA_HOME"] = Path.Combine(frcHomePath, "jdk"); terminalProps["PATH"] = Path.Combine(frcHomePath, "jdk", "bin") + ":${env:PATH}"; settingsJson["terminal.integrated.env.windows"] = terminalProps; } else { dynamic terminalEnv = settingsJson["terminal.integrated.env.windows"]; terminalEnv["JAVA_HOME"] = Path.Combine(frcHomePath, "jdk"); string path = terminalEnv["PATH"]; if (path == null) { terminalEnv["PATH"] = Path.Combine(frcHomePath, "jdk", "bin") + ";${env:PATH}"; } else { var binPath = Path.Combine(frcHomePath, "jdk", "bin"); if (!path.Contains(binPath)) { path = binPath + ";" + path; terminalEnv["PATH"] = path; } } } var serialized = JsonConvert.SerializeObject(settingsJson, Formatting.Indented); File.WriteAllText(settingsFile, serialized); }
protected override void ExecuteCmdlet() { // var template = new ProvisioningTemplate(); var templateCi = new ProvisioningTemplateCreationInformation(ClientContext.Web) { IncludeAllTermGroups = true }; templateCi.HandlersToProcess = Handlers.TermGroups; var template = ClientContext.Web.GetProvisioningTemplate(templateCi); if (ParameterSpecified(nameof(Identity))) { if (Identity.Id != Guid.Empty) { template.TermGroups.RemoveAll(t => t.Id != Identity.Id); } else if (Identity.Name != string.Empty) { template.TermGroups.RemoveAll(t => t.Name != Identity.Name); } } var outputStream = XMLPnPSchemaFormatter.LatestFormatter.ToFormattedTemplate(template); var reader = new StreamReader(outputStream); var fullxml = reader.ReadToEnd(); var xml = string.Empty; if (!FullTemplate) { var document = XDocument.Parse(fullxml); XNamespace pnp = document.Root.GetNamespaceOfPrefix("pnp"); var termGroupsElement = document.Root.Descendants(pnp + "TermGroups").FirstOrDefault(); if (termGroupsElement != null) { xml = termGroupsElement.ToString(); } } else { xml = fullxml; } if (!string.IsNullOrEmpty(Out)) { if (!Path.IsPathRooted(Out)) { Out = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Out); } if (File.Exists(Out)) { if (Force || ShouldContinue(string.Format(Resources.File0ExistsOverwrite, Out), Resources.Confirm)) { File.WriteAllText(Out, xml, Encoding); } } else { File.WriteAllText(Out, xml, Encoding); } } else { WriteObject(xml); } }
private void WebClientOnOpenReadCompleted(object sender, OpenReadCompletedEventArgs openReadCompletedEventArgs) { _webClient.Dispose(); if (openReadCompletedEventArgs.Cancelled) { OnDownloadItemDownloadCompleted(new DownloadCompletedEventArgs(true, openReadCompletedEventArgs.Error)); return; } if (!Overwrite && File.Exists(SavePath)) { return; } var totalLength = 0; try { totalLength = int.Parse(((WebClient)sender).ResponseHeaders["Content-Length"]); } catch (Exception) { // ignored } try { long processed = 0; var tmpPath = Path.GetTempFileName(); using (var stream = openReadCompletedEventArgs.Result) using (var fs = File.Create(tmpPath)) { var buffer = new byte[32 * 1024]; int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { fs.Write(buffer, 0, read); processed += read; OnDownloadItemDownloadProgressChanged(new DownloadProgressChangedEventArgs(processed, totalLength)); } } switch (DownloadFormat) { case DownloadFormat.M4A: { File.Move(tmpPath, SavePath); } break; case DownloadFormat.MP3: { OnDownloadItemConvertionStarted(null); using (var reader = new MediaFoundationReader(tmpPath)) { MediaFoundationEncoder.EncodeToMp3(reader, SavePath); } File.Delete(tmpPath); } break; } var information = TrackInformationFetcher.GetTrackInformation(Item); using (var file = TagLib.File.Create(SavePath)) { file.Tag.Title = information.Name; file.Tag.AlbumArtists = new[] { information.Artist }; file.Tag.Album = information.Album; if (!string.IsNullOrEmpty(information.CoverUrl)) { byte[] result; using (var client = new WebClient()) { client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); result = client.DownloadData(information.CoverUrl); } file.Tag.Pictures = new IPicture[] { new Picture(new ByteVector(result)) { Type = PictureType.FrontCover, Description = "Cover" } }; } file.Save(); } GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); OnDownloadItemDownloadCompleted(new DownloadCompletedEventArgs(false)); } catch (Exception ex) { OnDownloadItemDownloadCompleted(new DownloadCompletedEventArgs(true, ex)); } }
public string ExportPackage(PackageDefinition definition) { if (definition.Id == default) { throw new ArgumentException("The package definition does not have an ID, it must be saved before being exported"); } if (definition.PackageId == default) { throw new ArgumentException("the package definition does not have a GUID, it must be saved before being exported"); } //ensure it's valid ValidatePackage(definition); //Create a folder for building this package var temporaryPath = _hostingEnvironment.MapPathContentRoot(_tempFolderPath.EnsureEndsWith('/') + Guid.NewGuid()); if (Directory.Exists(temporaryPath) == false) { Directory.CreateDirectory(temporaryPath); } try { //Init package file XDocument compiledPackageXml = CreateCompiledPackageXml(out XElement root); //Info section root.Add(GetPackageInfoXml(definition)); PackageDocumentsAndTags(definition, root); PackageDocumentTypes(definition, root); PackageMediaTypes(definition, root); PackageTemplates(definition, root); PackageStylesheets(definition, root); PackageStaticFiles(definition.Scripts, root, "Scripts", "Script", _fileSystems.ScriptsFileSystem); PackageStaticFiles(definition.PartialViews, root, "PartialViews", "View", _fileSystems.PartialViewsFileSystem); PackageMacros(definition, root); PackageDictionaryItems(definition, root); PackageLanguages(definition, root); PackageDataTypes(definition, root); Dictionary <string, Stream> mediaFiles = PackageMedia(definition, root); string fileName; string tempPackagePath; if (mediaFiles.Count > 0) { fileName = "package.zip"; tempPackagePath = Path.Combine(temporaryPath, fileName); using (FileStream fileStream = File.OpenWrite(tempPackagePath)) using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true)) { ZipArchiveEntry packageXmlEntry = archive.CreateEntry("package.xml"); using (Stream entryStream = packageXmlEntry.Open()) { compiledPackageXml.Save(entryStream); } foreach (KeyValuePair <string, Stream> mediaFile in mediaFiles) { var entryPath = $"media{mediaFile.Key.EnsureStartsWith('/')}"; ZipArchiveEntry mediaEntry = archive.CreateEntry(entryPath); using (Stream entryStream = mediaEntry.Open()) using (mediaFile.Value) { mediaFile.Value.Seek(0, SeekOrigin.Begin); mediaFile.Value.CopyTo(entryStream); } } } } else { fileName = "package.xml"; tempPackagePath = Path.Combine(temporaryPath, fileName); using (FileStream fileStream = File.OpenWrite(tempPackagePath)) { compiledPackageXml.Save(fileStream); } } var directoryName = _hostingEnvironment.MapPathContentRoot(Path.Combine(_createdPackagesFolderPath, definition.Name.Replace(' ', '_'))); Directory.CreateDirectory(directoryName); var finalPackagePath = Path.Combine(directoryName, fileName); if (File.Exists(finalPackagePath)) { File.Delete(finalPackagePath); } File.Move(tempPackagePath, finalPackagePath); definition.PackagePath = finalPackagePath; SavePackage(definition); return(finalPackagePath); } finally { // Clean up Directory.Delete(temporaryPath, true); } }
private FileInfo LookForFile(string folder, string imageName) { var path = Path.Combine(_installFolder, folder, String.Format("{0}.jpg", imageName)); return(File.Exists(path) ? new FileInfo(path) : null); }
public static bool Exists(string path) { return(File.Exists(path)); }
private static bool ParseCommandLine(string[] args, out CommandLineParser parser) { try { parser = new CommandLineParser(args); } catch (Exception) { throw new InvalidOperationException( "An error occurred whilst parsing the command line; try -? for command line arguments."); } try { parser.ExtractAndValidateArguments(); if (parser.PrintUsage) { System.Console.WriteLine(parser.Usage()); return(false); } if (parser.PrintVersion) { var entryAssembly = System.Reflection.Assembly.GetEntryAssembly(); if (entryAssembly == null) { Logger.Warn("No entry assembly, running from unmanaged application"); } else { var version = entryAssembly.GetName().Version; System.Console.WriteLine("OpenCover version {0}", version); return(false); } } if (!string.IsNullOrWhiteSpace(parser.TargetDir) && !Directory.Exists(parser.TargetDir)) { System.Console.WriteLine("TargetDir '{0}' cannot be found - have you specified your arguments correctly?", parser.TargetDir); return(false); } if (parser.Service) { try { using (var service = new ServiceController(parser.Target)) { var name = service.DisplayName; System.Console.WriteLine("Service '{0}' found", name); } } catch (Exception) { System.Console.WriteLine("Service '{0}' cannot be found - have you specified your arguments correctly?", parser.Target); return(false); } } else if (!File.Exists(ResolveTargetPathname(parser))) { System.Console.WriteLine("Target '{0}' cannot be found - have you specified your arguments correctly?", parser.Target); return(false); } } catch (Exception ex) { System.Console.WriteLine(""); System.Console.WriteLine("Incorrect Arguments: {0}", ex.Message); System.Console.WriteLine(""); System.Console.WriteLine(parser.Usage()); return(false); } return(true); }