// TODO: this should use inputstreams from the loader, not File! //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public void inform(org.apache.lucene.analysis.util.ResourceLoader loader) throws java.io.IOException public virtual void inform(ResourceLoader loader) { if (mapping != null) { IList<string> wlist = null; File mappingFile = new File(mapping); if (mappingFile.exists()) { wlist = getLines(loader, mapping); } else { IList<string> files = splitFileNames(mapping); wlist = new List<>(); foreach (string file in files) { IList<string> lines = getLines(loader, file.Trim()); wlist.AddRange(lines); } } NormalizeCharMap.Builder builder = new NormalizeCharMap.Builder(); parseRules(wlist, builder); normMap = builder.build(); if (normMap.map == null) { // if the inner FST is null, it means it accepts nothing (e.g. the file is empty) // so just set the whole map to null normMap = null; } } }
private void ReadDirectoryStructure(Directory rootDirectory) { List<File> files = new List<File>(); foreach (var f in rootDirectory.infos.EnumerateFiles()) { File file = new File(f); try { file.file = TagLib.File.Create(file.infos.FullName); if (file.file is TagLib.Image.File) file.file = null; } catch (TagLib.UnsupportedFormatException) { file.file = null; } files.Add(file); } List<Directory> directories = new List<Directory>(); foreach (var f in rootDirectory.infos.EnumerateDirectories()) directories.Add(new Directory(f)); rootDirectory.files = files; rootDirectory.directories = directories; foreach (var directory in directories) { ReadDirectoryStructure(directory); } }
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 MetadataPartition(UdfContext context, LogicalVolumeDescriptor volumeDescriptor, MetadataPartitionMap partitionMap) : base(context, volumeDescriptor) { _partitionMap = partitionMap; PhysicalPartition physical = context.PhysicalPartitions[partitionMap.PartitionNumber]; long fileEntryPos = partitionMap.MetadataFileLocation * (long)volumeDescriptor.LogicalBlockSize; byte[] entryData = Utilities.ReadFully(physical.Content, fileEntryPos, _context.PhysicalSectorSize); if (!DescriptorTag.IsValid(entryData, 0)) { throw new IOException("Invalid descriptor tag looking for Metadata file entry"); } DescriptorTag dt = Utilities.ToStruct<DescriptorTag>(entryData, 0); if (dt.TagIdentifier == TagIdentifier.ExtendedFileEntry) { ExtendedFileEntry efe = Utilities.ToStruct<ExtendedFileEntry>(entryData, 0); _metadataFile = new File(context, physical, efe, _volumeDescriptor.LogicalBlockSize); } else { throw new NotImplementedException("Only EFE implemented for Metadata file entry"); } }
public static void Save(File file) { using (var istorage = IsolatedStorageFile.GetUserStoreForApplication()) { WriteFileToFile(file, istorage, GetFilePath(file)); } }
public CopyFileAction(File source, Storage destinationStorage, string destinationPath, string destinationName) { Source = source; DestinationStorage = destinationStorage; DestinationPath = destinationPath; DestinationName = destinationName; }
public File SaveFile(File file, Stream fileStream) { if (fileStream == null) throw new ArgumentNullException("fileStream"); ICloudFileSystemEntry entry = null; if(file.ID != null) { entry = SharpBoxProviderInfo.Storage.GetFile(MakePath(file.ID), null); } else if (file.FolderID != null) { var folder = GetFolderById(file.FolderID); try { //Check existense if (SharpBoxProviderInfo.Storage.GetFileSystemObject(file.Title, folder) != null) throw new ArgumentException(string.Format(Web.Files.Resources.FilesCommonResource.Error_FileAlreadyExists, file.Title)); } catch(ArgumentException) { throw; } catch (Exception) { } entry = SharpBoxProviderInfo.Storage.CreateFile(folder, file.Title); } if (entry != null) { entry.GetDataTransferAccessor().Transfer(fileStream, nTransferDirection.nUpload); return ToFile(entry); } return null; }
private static void GetAllFilesAndFoldersInGivenDirectory(DirectoryInfo directory, Folder folder) { try { var files = directory.GetFiles(); foreach (var file in files) { var myFile = new File(); myFile.Name = file.Name; myFile.Size = file.Length; folder.Files.Add(myFile); } var directories = directory.GetDirectories(); foreach (var dir in directories) { var newFolder = new Folder(dir.Name); GetAllFilesAndFoldersInGivenDirectory(dir, newFolder); folder.ChildFolder.Add(newFolder); } } catch (UnauthorizedAccessException) { return; } }
/** * * @param file * File object. * @param chunkList * Chunk list, maybe with duplicates. * @return Number of new chunks, that were not in the list before. Duplicates within the file are considered only * once. */ public int addFile(File file, List<long> chunkList) { // Sanity check if (file == null || chunkList == null || (chunkList.Count == 0)) return 0; int result = 0; long offset = 0; // Walk through the chunks foreach (long curChunk in chunkList) { HashSet<FileAndOffset> files; files = null; chunksFiles.TryGetValue(curChunk, out files); if (files == null) { // Create a new file list for the current chunk files = new HashSet<FileAndOffset>(); chunksFiles.Add(curChunk, files); // Indicate that the current chunk is new to this list result++; } // Add the file to the file list for the current chunk files.Add(new FileAndOffset(file, offset)); offset += StreamChunckingLib.PackChunking.chunkToLen(curChunk); } return result; }
public TemporaryLocalFile(File backingFile) { _backingFile = backingFile; if (!backingFile.Exists()) backingFile.Create(); }
public File SaveFile(File file, Stream fileStream) { if (file == null) throw new ArgumentNullException("file"); var fileId = file.ID; var folderId = file.FolderID; IDaoSelector selector; File fileSaved = null; //Convert if (fileId != null) { selector = GetSelector(fileId); file.ID = selector.ConvertId(fileId); if (folderId != null) file.FolderID = selector.ConvertId(folderId); fileSaved = selector.GetFileDao(fileId).SaveFile(file, fileStream); } else if (folderId != null) { selector = GetSelector(folderId); file.FolderID = selector.ConvertId(folderId); fileSaved = selector.GetFileDao(folderId).SaveFile(file, fileStream); } if (fileSaved != null) { return fileSaved; } throw new ArgumentException("No file id or folder id toFolderId determine provider"); }
public Reader(File file) { _file = file; _totalSize = file.GetSize(); _ofs = 0; FillBuffer(); }
public static void Delete(File file) { using (var istorage = IsolatedStorageFile.GetUserStoreForApplication()) { if (istorage.FileExists(file.FileName)) istorage.DeleteFile(file.FileName); } }
public void FileCheck_LetterFile_ThrowsException() { var mockSocket = Substitute.For<ISymSocket>(); var file = new File("symitar", "10", "FILE.TO.CHECK", FileType.Letter, DateTime.Now, 110); var session = new SymSession(mockSocket, 10); Assert.Throws<Exception>(() => session.FileCheck(file)); }
public Reader(File owner) { _owner = owner; _valueSize = _owner.GetSize(); _ofs = 0; Buf = new byte[32768]; FillBuffer(); }
private static File ActualFile(File file) { if (!file.FullName.EndsWith(".lnk")) return file; string linkPathName = file.FullName; var link = (IWshShortcut) new WshShell().CreateShortcut(linkPathName); if (string.IsNullOrEmpty(link.TargetPath) || !File.Exists(link.TargetPath)) return file; return new File(link.TargetPath); }
public Keywords(File file) { this.List = new WeightedGuessList<FuzzyString>(); var cleanPath = RemoveNoise(file.Path.ToLower()); ExtractKeywordsFromPath(Path.GetDirectoryName(cleanPath)); ExtractInfoFromName(Path.GetFileNameWithoutExtension(cleanPath)); }
void WritePage(string filename, File.Font f) { string nfilename = Path.ChangeExtension(filename, ".png"); // we just have one f.Frame.Image.Save(nfilename); // just in case -png was not set sw.Write("page "); sw.Write("id", 0); sw.Write("file", nfilename); sw.WriteLine(); }
public void NotifySpeeder(int cameralocation, double speed, File image) { //Send to database dman.submitToDatabase(cameralocation, speed); //Send to car Car c = cars.OrderBy(x => x.Location - cameralocation).First(); c.speeder(cameralocation, speed, image); }
public Stream GetFileStream(File file) { if (file == null) throw new ArgumentNullException("file"); var fileId = file.ID; var selector = GetSelector(fileId); file.ID = selector.ConvertId(fileId); var stream = selector.GetFileDao(fileId).GetFileStream(file); file.ID = fileId; //Restore id return stream; }
public void FileCheck_CommandHasWarning_ThrowsFileNotFoundException() { var mockSocket = Substitute.For<ISymSocket>(); mockSocket.ReadCommand() .Returns(new SymCommand("Check", new Dictionary<string, string> {{"Warning", ""}})); var file = new File("symitar", "10", "FILE.TO.CHECK", FileType.RepGen, DateTime.Now, 110); var session = new SymSession(mockSocket, 10); Assert.Throws<FileNotFoundException>(() => session.FileCheck(file)); }
private void TestSameCore(File memTempFile, File localTempFile, FileMode mode, FileAccess access, FileShare share) { Stream memStream = null, localStream = null; Exception memException = null, localException = null; try { memStream = memTempFile.Open(mode, access, share); } catch (Exception e) { memException = e; } try { localStream = localTempFile.Open(mode, access, share); } catch (Exception e) { localException = e; } if (memException != null || localException != null) { if (memStream != null) memStream.Dispose(); if (localStream != null) localStream.Dispose(); var anyException = (memException ?? localException).GetType(); Assert.That(memException, Is.InstanceOf(anyException), string.Format("In-Memory ex was {0}, but file was: {1}", memException != null ? memException.ToString() : "NULL", localException != null ? localException.ToString() : "NULL")); Assert.That(localException, Is.InstanceOf(anyException), string.Format("Local file ex was {0}, but in mem was: {1}.", localException != null ? localException.ToString() : "NULL", memException != null ? memException.ToString() : "NULL")); if (!(memException.GetType() == anyException && localException.GetType() == anyException)) Console.WriteLine("Memory exception: " + (memException != null ? memException.GetType().Name : null) + " Local exception: " + (localException != null ? localException.GetType().Name : null)); return; } if (memStream.CanWrite) memStream.WriteByte(99); if (localStream.CanWrite) localStream.WriteByte(99); memStream.Dispose(); localStream.Dispose(); using (memStream = memTempFile.OpenRead()) using (localStream = localTempFile.OpenRead()) { memStream.ReadToEnd().ShouldBe(localStream.ReadToEnd()); localStream.Close(); memStream.Close(); } }
public void Should_Return_Bodies_That_Respond_To_ToPath() { var env = new MockRequest().EnvironmentFor("/cgi/test"); var response = new File(_docRoot).Call(env); var path = Path.Combine(_docRoot, "cgi/test"); Assert.AreEqual(200, response[0]); Assert.IsTrue(response[2] is IPathConvertible); Assert.AreEqual(path, response[2].ToPath()); }
public static void SaveAsBMFont(string filename, File.Font f) { BMFontWriter writer = new BMFontWriter(); writer.sw = new StreamWriter(filename); writer.WriteInfoTag(f); writer.WriteCommon(f); writer.WritePage(filename, f); writer.WriteChars(f); writer.sw.Flush(); writer.sw.Close(); }
/// <summary> /// ctor, copys all the properties from the file object into the new object. /// </summary> public Image(File obj) { if (obj != null) { var qry = typeof(File).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.CanRead && p.CanWrite); foreach (var pi in qry) this.GetType().GetProperty(pi.Name).SetValue(this, pi.GetValue(obj, null), null); } if (!this.IsImage) throw new Exception("File not of an image type"); }
private async Task<File> TryCreateApplicationDirectoryAsync() { DriveService driveService = await TryGetAuthorizer(); File applicationDirectory = new File(); applicationDirectory.Title = ApplicationFolderName; applicationDirectory.MimeType = FolderContentType; FilesResource.InsertRequest fileInsertRequest = driveService.Files.Insert(applicationDirectory); return fileInsertRequest.Execute(); }
public static IEnumerable<File> Decode(System.Windows.IDataObject data) { IntPtr fileGroupDescriptorWPointer = IntPtr.Zero; try { //use the underlying IDataObject to get the FileGroupDescriptorW as a MemoryStream MemoryStream fileGroupDescriptorStream = (MemoryStream)data.GetData("FileGroupDescriptorW"); byte[] fileGroupDescriptorBytes = new byte[fileGroupDescriptorStream.Length]; fileGroupDescriptorStream.Read(fileGroupDescriptorBytes, 0, fileGroupDescriptorBytes.Length); fileGroupDescriptorStream.Close(); //copy the file group descriptor into unmanaged memory fileGroupDescriptorWPointer = Marshal.AllocHGlobal(fileGroupDescriptorBytes.Length); Marshal.Copy(fileGroupDescriptorBytes, 0, fileGroupDescriptorWPointer, fileGroupDescriptorBytes.Length); //marshal the unmanaged memory to to FILEGROUPDESCRIPTORW struct object fileGroupDescriptorObject = Marshal.PtrToStructure(fileGroupDescriptorWPointer, typeof(NativeMethods.FILEGROUPDESCRIPTORW)); NativeMethods.FILEGROUPDESCRIPTORW fileGroupDescriptor = (NativeMethods.FILEGROUPDESCRIPTORW)fileGroupDescriptorObject; //create a new array to store file names in of the number of items in the file group descriptor List<File> files = new List<File>(); //get the pointer to the first file descriptor IntPtr fileDescriptorPointer = (IntPtr)((int)fileGroupDescriptorWPointer + Marshal.SizeOf(fileGroupDescriptorWPointer)); //loop for the number of files acording to the file group descriptor for (int fileDescriptorIndex = 0; fileDescriptorIndex < fileGroupDescriptor.cItems; fileDescriptorIndex++) { //marshal the pointer top the file descriptor as a FILEDESCRIPTORW struct and get the file name NativeMethods.FILEDESCRIPTORW fileDescriptor = (NativeMethods.FILEDESCRIPTORW)Marshal.PtrToStructure(fileDescriptorPointer, typeof(NativeMethods.FILEDESCRIPTORW)); File file = new File(); file.Name = fileDescriptor.cFileName; file.Size = (long)fileDescriptor.nFileSizeLow + ((long)fileDescriptor.nFileSizeHigh << 32); files.Add(file); //move the file descriptor pointer to the next file descriptor fileDescriptorPointer = (IntPtr)((int)fileDescriptorPointer + Marshal.SizeOf(fileDescriptor)); } int index = 0; foreach (File f in files) { f.Content = GetData(data, FileContents, index++); } //return the array of files return files; } finally { //free unmanaged memory pointer Marshal.FreeHGlobal(fileGroupDescriptorWPointer); } }
public static List<File> GetLFilesList(this DirectoryInfo dir) { List<File> files = new List<File>(); foreach (FileInfo f in dir.GetFiles()) { File file = new File(); file.Name = f.Name; files.Add(file); } return files; }
public void FileCheck_ActionNoError_PassesCheck() { var mockSocket = Substitute.For<ISymSocket>(); mockSocket.ReadCommand() .Returns(new SymCommand("Check", new Dictionary<string, string> {{"Action", "NoError"}})); var file = new File("symitar", "10", "FILE.TO.CHECK", FileType.RepGen, DateTime.Now, 110); var session = new SymSession(mockSocket, 10); SpecfileResult result = session.FileCheck(file); result.PassedCheck.Should().BeTrue(); }
public void AddFile(string fileName, long fileSize, DateTime? exifDateTimeOriginal = null) { string[] x = ConvertPathToParentAndTargetPaths(fileName); string parentPath = x[0]; string childPath = x[1]; if (!DirectoryExists(parentPath)) { CreateDirectory(parentPath); } var newFile = new File(childPath, fileSize) {ExifDateTimeOriginal = exifDateTimeOriginal}; ConvertPathToNodeReference(parentPath).AddFile(newFile); }
public override void Execute() { if (!File.Exists(_packagePath)) { throw new PackageInstallationException(Labels.InvalidPackagePath, 5); } // Get the context root. var fileSystemRoot = GetFileSystemRoot(); if (fileSystemRoot == null) { throw new PackageInstallationException(Labels.CannotDetermineInstallationPath, 10); } PackageMetadata metadata; using (var zipFile = new ZipFile(_packagePath)) { metadata = ExtractMetadata(zipFile); if (metadata == null) { throw new PackageInstallationException(Labels.InvalidPackage, 6); } if (!IsValidPackageId(Context, metadata.Id)) { throw new PackageInstallationException(Labels.InvalidPackageId, 9); } // Temporarily store a few parameters we want to add back later. using (var contextKey = OpenContextRegistry(false)) using (var packageKey = contextKey.OpenSubKey("InstalledProducts\\" + metadata.Id)) { if (packageKey != null) { metadata.NuGetSite = (string)packageKey.GetValue("NuGetSite"); metadata.GalleryDetailsUrl = (string)packageKey.GetValue("GalleryDetailsUrl"); } } } string target = RemovePackage(metadata.Id, fileSystemRoot); ExtractPackage(_packagePath, target); var manifest = GetPackageManifest(target); if (manifest == null) { throw new PackageInstallationException(Labels.InvalidPackage, 8); } _packagePath = target; try { INiPackage package; using (CreateAppDomain(_packagePath, manifest.EntryPoint, out package)) { PerformRegistration(metadata.Id, fileSystemRoot, package); } // Restore some variables that were removed as part of the update. using (var contextKey = OpenContextRegistry(true)) using (var packageKey = contextKey.CreateSubKey("InstalledProducts\\" + metadata.Id)) { if (metadata.NuGetSite != null) { packageKey.SetValue("NuGetSite", metadata.NuGetSite); } if (metadata.GalleryDetailsUrl != null) { packageKey.SetValue("GalleryDetailsUrl", metadata.GalleryDetailsUrl); } } } catch { try { RemovePackage(metadata.Id, fileSystemRoot); } catch (Exception ex) { throw new PackageInstallationException(String.Format(Labels.RollbackFailed, ex.Message), 4, ex); } throw; } }
private void tsbExportSelected_Click(object sender, EventArgs e) { if (_fs == null) { return; } if (lvFiles.SelectedItems.Count == 1) { File file = lvFiles.SelectedItems[0].Tag as File; SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = "Export..."; if (_lastImportExportPath != null) { sfd.InitialDirectory = _lastImportExportPath; sfd.FileName = Path.Combine(_lastImportExportPath, file.Name); } else { sfd.FileName = file.Name; } sfd.OverwritePrompt = true; if (sfd.ShowDialog() == DialogResult.OK) { _lastImportExportPath = IODirectory.GetParent(sfd.FileName).FullName; using (new WaitCursor(this)) { byte[] data = file.GetData(); IOFile.WriteAllBytes(sfd.FileName, data); } } } else if (lvFiles.SelectedItems.Count > 1) { FolderBrowserDialog fbd = new FolderBrowserDialog(); fbd.Description = "Export Selected..."; fbd.ShowNewFolderButton = true; fbd.SelectedPath = _lastImportExportPath; if (fbd.ShowDialog() == DialogResult.OK) { _lastImportExportPath = fbd.SelectedPath; string path = fbd.SelectedPath; using (new WaitCursor(this)) { foreach (ListViewItem item in lvFiles.SelectedItems) { File file = item.Tag as File; byte[] data = file.GetData(); IOFile.WriteAllBytes(Path.Combine(path, file.Name), data); } } MessageBox.Show("All selected files exported.", "Export Selected", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
/// <summary> /// Prepare this controller to import from a dictionary configuration zip file. /// /// TODO Validate the XML first and/or handle failure to create DictionaryConfigurationModel object. /// TODO Handle if zip has no .fwdictconfig file. /// TODO Handle if file is not a zip, or a corrupted zip file. /// </summary> internal void PrepareImport(string configurationZipPath) { if (string.IsNullOrEmpty(configurationZipPath)) { ImportHappened = false; NewConfigToImport = null; _originalConfigLabel = null; _temporaryImportConfigLocation = null; _newPublications = null; return; } try { using (var zip = new ZipFile(configurationZipPath)) { var tmpPath = Path.GetTempPath(); var configInZip = zip.SelectEntries("*" + DictionaryConfigurationModel.FileExtension).First(); configInZip.Extract(tmpPath, ExtractExistingFileAction.OverwriteSilently); _temporaryImportConfigLocation = tmpPath + configInZip.FileName; if (!FileUtils.IsFileReadableAndWritable(_temporaryImportConfigLocation)) { File.SetAttributes(_temporaryImportConfigLocation, FileAttributes.Normal); } var customFieldLiftFile = zip.SelectEntries("*.lift").First(); customFieldLiftFile.Extract(tmpPath, ExtractExistingFileAction.OverwriteSilently); var liftRangesFile = zip.SelectEntries("*.lift-ranges").First(); liftRangesFile.Extract(tmpPath, ExtractExistingFileAction.OverwriteSilently); _importLiftLocation = tmpPath + customFieldLiftFile.FileName; var stylesFile = zip.SelectEntries("*.xml").First(); stylesFile.Extract(tmpPath, ExtractExistingFileAction.OverwriteSilently); _importStylesLocation = tmpPath + stylesFile.FileName; } } catch (Exception) { ClearValuesOnError(); return; } NewConfigToImport = new DictionaryConfigurationModel(_temporaryImportConfigLocation, _cache); //Validating the user is not trying to import a Dictionary into a Reversal area or a Reversal into a Dictionary area var configDirectory = Path.GetFileName(_projectConfigDir); if (DictionaryConfigurationListener.DictionaryConfigurationDirectoryName.Equals(configDirectory) && NewConfigToImport.IsReversal || !DictionaryConfigurationListener.DictionaryConfigurationDirectoryName.Equals(configDirectory) && !NewConfigToImport.IsReversal) { _isInvalidConfigFile = true; ClearValuesOnError(); return; } _isInvalidConfigFile = false; // Reset flag ImportHappened = false; _newPublications = DictionaryConfigurationModel.PublicationsInXml(_temporaryImportConfigLocation).Except(NewConfigToImport.Publications); _customFieldsToImport = CustomFieldsInLiftFile(_importLiftLocation); // Use the full list of publications in the XML file, even ones that don't exist in the project. NewConfigToImport.Publications = DictionaryConfigurationModel.PublicationsInXml(_temporaryImportConfigLocation).ToList(); // Make a new, unique label for the imported configuration, if needed. var newConfigLabel = NewConfigToImport.Label; _originalConfigLabel = NewConfigToImport.Label; var i = 1; while (_configurations.Any(config => config.Label == newConfigLabel)) { newConfigLabel = string.Format(xWorksStrings.kstidImportedSuffix, NewConfigToImport.Label, i++); } NewConfigToImport.Label = newConfigLabel; _proposedNewConfigLabel = newConfigLabel; // Not purporting to use any particular file location yet. NewConfigToImport.FilePath = null; }
/// <summary> /// Connect using the parameter set APPONLYAAD /// </summary> /// <returns>PnPConnection based on the parameters provided in the parameter set</returns> private PnPConnection ConnectAppOnlyWithCertificate() { if (ParameterSpecified(nameof(CertificatePath))) { if (!Path.IsPathRooted(CertificatePath)) { CertificatePath = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, CertificatePath); } if (!File.Exists(CertificatePath)) { throw new FileNotFoundException("Certificate not found"); } X509Certificate2 certificate = CertificateHelper.GetCertificateFromPath(CertificatePath, CertificatePassword); if (PnPConnection.Current?.ClientId == ClientId && PnPConnection.Current?.Tenant == Tenant && PnPConnection.Current?.Certificate.Thumbprint == certificate.Thumbprint) { ReuseAuthenticationManager(); } return(PnPConnection.CreateWithCert(new Uri(Url), ClientId, Tenant, TenantAdminUrl, AzureEnvironment, certificate, true)); } else if (ParameterSpecified(nameof(CertificateBase64Encoded))) { var certificateBytes = Convert.FromBase64String(CertificateBase64Encoded); var certificate = new X509Certificate2(certificateBytes, CertificatePassword); if (PnPConnection.Current?.ClientId == ClientId && PnPConnection.Current?.Tenant == Tenant && PnPConnection.Current?.Certificate.Thumbprint == certificate.Thumbprint) { ReuseAuthenticationManager(); } return(PnPConnection.CreateWithCert(new Uri(Url), ClientId, Tenant, TenantAdminUrl, AzureEnvironment, certificate)); } else if (ParameterSpecified(nameof(Thumbprint))) { X509Certificate2 certificate = CertificateHelper.GetCertificateFromStore(Thumbprint); if (certificate == null) { throw new PSArgumentException("Cannot find certificate with this thumbprint in the certificate store.", nameof(Thumbprint)); } // Ensure the private key of the certificate is available if (!certificate.HasPrivateKey) { throw new PSArgumentException("The certificate specified does not have a private key.", nameof(Thumbprint)); } if (PnPConnection.Current?.ClientId == ClientId && PnPConnection.Current?.Tenant == Tenant && PnPConnection.Current?.Certificate.Thumbprint == certificate.Thumbprint) { ReuseAuthenticationManager(); } return(PnPConnection.CreateWithCert(new Uri(Url), ClientId, Tenant, TenantAdminUrl, AzureEnvironment, certificate)); } else { throw new ArgumentException("You must either provide CertificatePath, Certificate or CertificateBase64Encoded when connecting using an Azure Active Directory registered application"); } }
public bool Execute(string packageName, XmlNode xmlData) { IMediaService mediaService = ApplicationContext.Current.Services.MediaService; IContentService contentService = UmbracoContext.Current.Application.Services.ContentService; IContentTypeService contentTypeService = ApplicationContext.Current.Services.ContentTypeService; IFileService fileService = ApplicationContext.Current.Services.FileService; //ApplicationContext.Current.Services.DataTypeService. IDataTypeService dataTypeService = UmbracoContext.Current.Application.Services.DataTypeService; #region Create media List <int> productImageIds = new List <int>(); List <IMedia> productImages = new List <IMedia>(); try { //Create image files const string productImagesFolderName = "Product images"; string[] mediaInstallImages = Directory.GetFiles(HostingEnvironment.MapPath("~/installMedia")); IMedia productImagesFolder = mediaService.GetByLevel(1).FirstOrDefault(m => m.Name == productImagesFolderName); if (productImagesFolder == null) { productImagesFolder = mediaService.CreateMedia(productImagesFolderName, -1, "Folder"); mediaService.Save(productImagesFolder); } if (!productImagesFolder.Children().Any()) { foreach (string mediaInstallImage in mediaInstallImages) { string fileName = Path.GetFileName(mediaInstallImage); IMedia productImage = mediaService.CreateMedia(fileName, productImagesFolder.Id, "Image"); byte[] buffer = File.ReadAllBytes(Path.GetFullPath(mediaInstallImage)); using (MemoryStream strm = new MemoryStream(buffer)) { productImage.SetValue("umbracoFile", fileName, strm); mediaService.Save(productImage); productImages.Add(productImage); productImageIds.Add(productImage.Id); } } } else { productImageIds = productImagesFolder.Children().Select(c => c.Id).ToList(); } Directory.Delete(HostingEnvironment.MapPath("~/installMedia"), true); } catch (Exception ex) { LogHelper.Error <TeaCommerceStarterKitInstall>("Create media failed", ex); } #endregion #region Set up Tea Commerce Store store = null; try { //Get store or create it IReadOnlyList <Store> stores = StoreService.Instance.GetAll().ToList(); store = stores.FirstOrDefault(); if (store == null) { store = new Store("Starter Kit Store"); } store.ProductSettings.ProductVariantPropertyAlias = "variants"; store.Save(); foreach (PaymentMethod paymentMethod in PaymentMethodService.Instance.GetAll(store.Id).Where(p => p.Alias == "invoicing")) { PaymentMethodSetting setting = paymentMethod.Settings.FirstOrDefault(s => s.Key == "acceptUrl"); if (setting != null) { setting.Value = "/cart-content/confirmation/"; } paymentMethod.Save(); } } catch (Exception ex) { LogHelper.Error <TeaCommerceStarterKitInstall>("Setting up Tea Commerce failed", ex); } #endregion #region Create Templates List <ITemplate> templates = new List <ITemplate>(); try { string[] templateFiles = Directory.GetFiles(HostingEnvironment.MapPath("~/views")); foreach (string templateFile in templateFiles) { string fileName = Path.GetFileNameWithoutExtension(templateFile); string fileContent = File.ReadAllText(templateFile); templates.Add(fileService.CreateTemplateWithIdentity(fileName, fileContent)); } } catch (Exception ex) { LogHelper.Error <TeaCommerceStarterKitInstall>("Create templates failed", ex); } #endregion #region Set up content types IEnumerable <IDataTypeDefinition> allDataTypeDefinitions = dataTypeService.GetAllDataTypeDefinitions(); try { IDataTypeDefinition variantEditorDataTypeDefinition = allDataTypeDefinitions.FirstOrDefault(d => d.Name.ToLowerInvariant().Contains("variant editor")); variantEditorDataTypeDefinition.DatabaseType = DataTypeDatabaseType.Ntext; var preValDictionary = new Dictionary <string, object> { { "xpathOrNode", "{\"showXPath\": true,\"query\": \"$current/ancestor-or-self::frontpage/attributes\"}" }, { "variantDocumentType", "variant" }, { "extraListInformation", "sku,priceJMD" }, { "hideLabel", "1" }, }; var currVal = dataTypeService.GetPreValuesCollectionByDataTypeId(variantEditorDataTypeDefinition.Id); //we need to allow for the property editor to deserialize the prevalues PropertyEditor pe = PropertyEditorResolver.Current.PropertyEditors.SingleOrDefault(x => x.Alias == "TeaCommerce.VariantEditor"); var formattedVal = pe.PreValueEditor.ConvertEditorToDb(preValDictionary, currVal); dataTypeService.SaveDataTypeAndPreValues(variantEditorDataTypeDefinition, formattedVal); //dataTypeService.Save( variantEditorDataTypeDefinition ); variantEditorDataTypeDefinition = dataTypeService.GetDataTypeDefinitionById(variantEditorDataTypeDefinition.Id); } catch (Exception ex) { LogHelper.Error <TeaCommerceStarterKitInstall>("Set up content types failed", ex); } #endregion #region Create Document types ContentType attributeContentType = null, attributeGroupContentType = null, attributesContentType = null, cartStepContentType = null, cartContentType = null, variantContentType = null, productContentType = null, productListContentType = null, frontpageContentType = null; try { attributeContentType = new ContentType(-1); attributeContentType.Alias = "attribute"; attributeContentType.Name = "Attribute"; attributeContentType.Icon = "icon-t-shirt"; contentTypeService.Save(attributeContentType); attributeGroupContentType = new ContentType(-1); attributeGroupContentType.Alias = "attributeGroup"; attributeGroupContentType.Name = "Attribute group"; attributeGroupContentType.Icon = "icon-t-shirt color-orange"; attributeGroupContentType.AllowedContentTypes = new List <ContentTypeSort>() { new ContentTypeSort(attributeContentType.Id, 0) }; contentTypeService.Save(attributeGroupContentType); attributesContentType = new ContentType(-1); attributesContentType.Alias = "attributes"; attributesContentType.Name = "Attributes"; attributesContentType.Icon = "icon-t-shirt"; attributesContentType.AllowedContentTypes = new List <ContentTypeSort>() { new ContentTypeSort(attributeGroupContentType.Id, 0) }; contentTypeService.Save(attributesContentType); cartStepContentType = new ContentType(-1); cartStepContentType.Alias = "cartStep"; cartStepContentType.Name = "Cart step"; cartStepContentType.Icon = "icon-shopping-basket-alt-2 color-orange"; cartStepContentType.AllowedTemplates = templates.Where(t => t.Alias.ToLowerInvariant().Contains("cartstep") && !t.Alias.ToLowerInvariant().Contains("master")); contentTypeService.Save(cartStepContentType); cartContentType = new ContentType(-1); cartContentType.Alias = "cart"; cartContentType.Name = "Cart"; cartContentType.Icon = "icon-shopping-basket-alt-2"; cartContentType.AllowedContentTypes = new List <ContentTypeSort>() { new ContentTypeSort(cartStepContentType.Id, 0) }; cartContentType.AllowedTemplates = templates.Where(t => t.Alias.ToLowerInvariant().Contains("cartstep1")); contentTypeService.Save(cartContentType); variantContentType = CreateVariantContentType(allDataTypeDefinitions, contentTypeService); productContentType = CreateProductContentType(allDataTypeDefinitions, contentTypeService, templates); productListContentType = new ContentType(-1); productListContentType.Alias = "productList"; productListContentType.Name = "Product list"; productListContentType.Icon = "icon-tags"; productListContentType.AllowedContentTypes = new List <ContentTypeSort>() { new ContentTypeSort(productContentType.Id, 0) }; productListContentType.AllowedTemplates = templates.Where(t => t.Alias.ToLowerInvariant().Contains("productlist")); contentTypeService.Save(productListContentType); frontpageContentType = CreateFrontpageContentType(allDataTypeDefinitions, contentTypeService, templates); } catch (Exception ex) { LogHelper.Error <TeaCommerceStarterKitInstall>("Create templates failed", ex); } #endregion #region Create content try { Content frontPageContent = new Content("Home", -1, frontpageContentType); frontPageContent.Template = frontpageContentType.AllowedTemplates.First(); frontPageContent.SetValue("slider", string.Join(",", productImages.Select(p => "umb://media/" + p.Key.ToString().Replace("-", "")))); frontPageContent.SetValue("store", store.Id); contentService.SaveAndPublishWithStatus(frontPageContent, raiseEvents: false); #region Create Cart Content cartContent = new Content("Cart content", frontPageContent.Id, cartContentType); cartContent.Template = cartContentType.AllowedTemplates.First(); contentService.SaveAndPublishWithStatus(cartContent, raiseEvents: false); Content informationContent = new Content("Information", cartContent.Id, cartStepContentType); informationContent.Template = templates.First(t => t.Alias.ToLowerInvariant() == "cartstep2"); contentService.SaveAndPublishWithStatus(informationContent, raiseEvents: false); Content shippingPaymentContent = new Content("Shipping/Payment", cartContent.Id, cartStepContentType); shippingPaymentContent.Template = templates.First(t => t.Alias.ToLowerInvariant() == "cartstep3"); contentService.SaveAndPublishWithStatus(shippingPaymentContent, raiseEvents: false); Content acceptContent = new Content("Accept", cartContent.Id, cartStepContentType); acceptContent.Template = templates.First(t => t.Alias.ToLowerInvariant() == "cartstep4"); contentService.SaveAndPublishWithStatus(acceptContent, raiseEvents: false); Content paymentContent = new Content("Payment", cartContent.Id, cartStepContentType); contentService.SaveAndPublishWithStatus(paymentContent); Content confirmationContent = new Content("Confirmation", cartContent.Id, cartStepContentType); confirmationContent.Template = templates.First(t => t.Alias.ToLowerInvariant() == "cartstep6"); contentService.SaveAndPublishWithStatus(confirmationContent, raiseEvents: false); #endregion #region Create Attributes Content variantAttributesContent = new Content("Variant attributes", frontPageContent.Id, attributesContentType); contentService.SaveAndPublishWithStatus(variantAttributesContent, raiseEvents: false); Content colorContent = new Content("Color", variantAttributesContent.Id, attributeGroupContentType); contentService.SaveAndPublishWithStatus(colorContent, raiseEvents: false); Content sizeContent = new Content("Size", variantAttributesContent.Id, attributeGroupContentType); contentService.SaveAndPublishWithStatus(sizeContent, raiseEvents: false); Content blackContent = new Content("Black", colorContent.Id, attributeContentType); contentService.SaveAndPublishWithStatus(blackContent, raiseEvents: false); Content whiteContent = new Content("White", colorContent.Id, attributeContentType); contentService.SaveAndPublishWithStatus(whiteContent, raiseEvents: false); Content blueContent = new Content("Blue", colorContent.Id, attributeContentType); contentService.SaveAndPublishWithStatus(blueContent, raiseEvents: false); Content largeContent = new Content("Large", sizeContent.Id, attributeContentType); contentService.SaveAndPublishWithStatus(largeContent, raiseEvents: false); Content mediumContent = new Content("Medium", sizeContent.Id, attributeContentType); contentService.SaveAndPublishWithStatus(mediumContent, raiseEvents: false); Content smallContent = new Content("Small", sizeContent.Id, attributeContentType); contentService.SaveAndPublishWithStatus(smallContent, raiseEvents: false); #endregion #region Create Products Content expensiveYachtsContent = new Content("Expensive Yachts", frontPageContent.Id, productListContentType); expensiveYachtsContent.Template = productListContentType.AllowedTemplates.First(); contentService.SaveAndPublishWithStatus(expensiveYachtsContent, raiseEvents: false); Content veryAxpensiveYachtsContent = new Content("Very expensive Yachts", frontPageContent.Id, productListContentType); veryAxpensiveYachtsContent.Template = productListContentType.AllowedTemplates.First(); contentService.SaveAndPublishWithStatus(veryAxpensiveYachtsContent, raiseEvents: false); Content summerYachtContent = new Content("Summer Yacht", expensiveYachtsContent, productContentType); summerYachtContent.Template = productContentType.AllowedTemplates.First(); summerYachtContent.SetValue("image", "umb://media/" + productImages[0].Key.ToString().Replace("-", "")); summerYachtContent.SetValue("productName", "Summer Yacht"); summerYachtContent.SetValue("sku", "p0001"); summerYachtContent.SetValue("priceJMD", "500"); summerYachtContent.SetValue("description", "<p>This is the product description.</p>"); summerYachtContent.SetValue("variants", "{\"variants\": [],\"variantGroupsOpen\":{}}"); contentService.SaveAndPublishWithStatus(summerYachtContent, raiseEvents: false); Content yachtWithSailsContent = new Content("Yacht with sails", expensiveYachtsContent, productContentType); yachtWithSailsContent.Template = productContentType.AllowedTemplates.First(); yachtWithSailsContent.SetValue("image", "umb://media/" + productImages[1].Key.ToString().Replace("-", "")); yachtWithSailsContent.SetValue("productName", "Yacht with sails"); yachtWithSailsContent.SetValue("sku", "p0002"); yachtWithSailsContent.SetValue("priceJMD", "1000"); yachtWithSailsContent.SetValue("description", "<p>This is the product description.</p>"); yachtWithSailsContent.SetValue("variants", "{\"variants\": [],\"variantGroupsOpen\":{}}"); contentService.SaveAndPublishWithStatus(yachtWithSailsContent, raiseEvents: false); Content motorDrivenYachtContent = new Content("Motor driven Yacht", veryAxpensiveYachtsContent, productContentType); motorDrivenYachtContent.Template = productContentType.AllowedTemplates.First(); motorDrivenYachtContent.SetValue("image", "umb://media/" + productImages[2].Key.ToString().Replace("-", "")); motorDrivenYachtContent.SetValue("productName", "Motor driven Yacht"); motorDrivenYachtContent.SetValue("sku", "p0003"); motorDrivenYachtContent.SetValue("priceJMD", "1500"); motorDrivenYachtContent.SetValue("description", "<p>This is the product description.</p>"); motorDrivenYachtContent.SetValue("variants", "{\"variants\": [],\"variantGroupsOpen\":{}}"); contentService.SaveAndPublishWithStatus(motorDrivenYachtContent, raiseEvents: false); Content oneMastedYachtContent = new Content("One masted yacht", veryAxpensiveYachtsContent, productContentType); oneMastedYachtContent.Template = productContentType.AllowedTemplates.First(); oneMastedYachtContent.SetValue("image", "umb://media/" + productImages[3].Key.ToString().Replace("-", "")); oneMastedYachtContent.SetValue("productName", "One masted yacht"); oneMastedYachtContent.SetValue("sku", "p0004"); oneMastedYachtContent.SetValue("priceJMD", "2000"); oneMastedYachtContent.SetValue("description", "<p>This is the product description.</p>"); oneMastedYachtContent.SetValue("variants", "{\"variants\": [],\"variantGroupsOpen\":{}}"); contentService.SaveAndPublishWithStatus(oneMastedYachtContent, raiseEvents: false); #endregion frontPageContent.SetValue("featuredProducts", string.Join(",", new List <string> { "umb://document/" + summerYachtContent.Key.ToString().Replace("-", ""), "umb://document/" + yachtWithSailsContent.Key.ToString().Replace("-", ""), "umb://document/" + motorDrivenYachtContent.Key.ToString().Replace("-", ""), "umb://document/" + oneMastedYachtContent.Key.ToString().Replace("-", ""), })); contentService.SaveAndPublishWithStatus(frontPageContent, raiseEvents: false); } catch (Exception ex) { LogHelper.Error <TeaCommerceStarterKitInstall>("Create content failed", ex); } #endregion return(true); }
public void ProcessDirectory(FolderSearch dir, HashSet <RunItem> theBag) { try { if (Directory.Exists(dir.Path)) { if (dir.IncludeFoldersInSearch) { var folder = new RunItem() { Name = new DirectoryInfo(dir.Path).Name, URI = new StringBuilder(dir.Path).Replace("/", "\\").Replace("//", "\\").ToString(), Type = ItemType.Directory }; theBag.Add(folder); } } else { Log.Error($"{dir.Path} does not exist..."); return; } //ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Product"); //foreach (ManagementObject mgmtObjectin in searcher.Get()) //{ // Console.WriteLine(mgmtObjectin["Name"]); // Console.WriteLine(mgmtObjectin.Path); //} //var t = theBag.ContainsKey(dir.URI); // Process the list of files found in the directory. string[] fileEntries = Directory.GetFiles(dir.Path, dir.SearchPattern); foreach (string fileName in fileEntries) { try { if (Path.GetExtension(fileName) == ".lnk") { Directory.CreateDirectory(Common.LinksPath); File.Copy(fileName, Common.LinksPath + Path.GetFileName(fileName), true); var item = new RunItem(); item.Type = ItemType.Link; item.Command = Common.LinksPath + Path.GetFileName(fileName); WshShell shell = new WshShell(); //Create a new WshShell Interface IWshShortcut link = (IWshShortcut)shell.CreateShortcut(item.Command); //Link the interface to our shortcut var uri = link.TargetPath; item.URI = uri; item.Arguments = link.Arguments; //var t = link.FullName; //var t2 = link.Description; //var t3 = link.WorkingDirectory; //var t4 = link.FullName; var split = link.IconLocation.Split(','); var iconName = split[0]; item.IconNr = Convert.ToInt32(split[1]); if (File.Exists(iconName)) { try { Stream iconStream = new FileStream(iconName, FileMode.Open, FileAccess.Read); IconBitmapDecoder decoder = new IconBitmapDecoder(iconStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); BitmapFrame frame = decoder.Frames[item.IconNr]; item.IconName = iconName; } catch { if (S.Settings.DebugMode) { Log.Error($"Could not add icon for {iconName} nr: {item.IconNr}"); } } } item.Name = Path.GetFileNameWithoutExtension(item.Command).Replace(" - Shortcut", ""); //get the name of the icon and removing the shortcut ending that sometimes are there, because nice-ness if (uri != "") { item.KeyWords.Add(Path.GetFileName(uri)); } theBag.Add(item); } else { var item = new RunItem { Type = ItemType.File, URI = new StringBuilder(fileName).Replace("/", "\\").Replace("//", "\\").ToString() }; item.Name = item.FileName; theBag.Add(item); } } catch (Exception e) { if (S.Settings.DebugMode) { Log.Error(e, $"Could not index {fileName}"); } } } } catch (Exception) { if (S.Settings.DebugMode) { Log.Debug($"Could not search {dir.Path}"); } } if (dir.SearchSubFolders) { try { // Recurse into subdirectories of this directory. string[] subdirectoryEntries = Directory.GetDirectories(dir.Path); foreach (string subdirectory in subdirectoryEntries) { try { ProcessDirectory( new FolderSearch() { Path = subdirectory, IncludeFoldersInSearch = dir.IncludeFoldersInSearch, SearchPattern = dir.SearchPattern, SearchSubFolders = dir.SearchSubFolders }, theBag); } catch (Exception e) { Log.Debug(e.Message); } } } catch (Exception e) { Log.Error(e.Message); } } }
private void AddReleaseCompareFeature() { var migrationName = MethodBase.GetCurrentMethod().Name; try { var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt"); if (File.Exists(path)) { return; } var contentTypeService = ApplicationContext.Current.Services.ContentTypeService; var releaseCompareAlias = "ReleaseCompare"; var compareContentType = contentTypeService.GetContentType(releaseCompareAlias); if (compareContentType == null) { var contentType = new ContentType(-1) { Name = "Release Compare", Alias = releaseCompareAlias }; contentTypeService.Save(contentType); } compareContentType = contentTypeService.GetContentType(releaseCompareAlias); var releaseLandingContentType = contentTypeService.GetContentType("ReleaseLanding"); var allowedContentTypes = new List <ContentTypeSort> { new ContentTypeSort(compareContentType.Id, 0) }; releaseLandingContentType.AllowedContentTypes = allowedContentTypes; contentTypeService.Save(releaseLandingContentType); var templatePathRelative = "~/masterpages/ReleaseCompare.master"; var templatePath = HostingEnvironment.MapPath(templatePathRelative); var templateContent = File.ReadAllText(templatePath); var releaseCompareTemplate = new Template("Release Compare", releaseCompareAlias) { MasterTemplateAlias = "Master", Content = templateContent }; var fileService = ApplicationContext.Current.Services.FileService; var masterTemplate = fileService.GetTemplate("Master"); releaseCompareTemplate.SetMasterTemplate(masterTemplate); fileService.SaveTemplate(releaseCompareTemplate); contentTypeService.Save(compareContentType); compareContentType.AllowedTemplates = new List <ITemplate> { releaseCompareTemplate }; compareContentType.SetDefaultTemplate(releaseCompareTemplate); contentTypeService.Save(compareContentType); var contentService = ApplicationContext.Current.Services.ContentService; var rootNode = contentService.GetRootContent().OrderBy(x => x.SortOrder).First(x => x.ContentType.Alias == "Community"); if (rootNode == null) { return; } var contributeNode = rootNode.Children().FirstOrDefault(x => x.Name == "Contribute"); if (contributeNode == null) { return; } var releasesNode = contributeNode.Children().FirstOrDefault(x => x.Name == "Releases"); if (releasesNode == null) { return; } var compareContent = contentService.CreateContent("Compare", releasesNode.Id, "ReleaseCompare"); compareContent.Template = releaseCompareTemplate; contentService.SaveAndPublishWithStatus(compareContent); var macroService = ApplicationContext.Current.Services.MacroService; const string macroAlias = "ReleasesDropdown"; if (macroService.GetByAlias(macroAlias) == null) { var macro = new Macro { Name = "ReleasesDropdown", Alias = macroAlias, ScriptingFile = "~/Views/MacroPartials/Releases/ReleasesDropdown.cshtml", UseInEditor = true }; macro.Save(); } string[] lines = { "" }; File.WriteAllLines(path, lines); } catch (Exception ex) { LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex); } }
/// <summary> /// Creates a new post on disk and returns the filename /// </summary> /// <param name="post"></param> /// <param name="weblogName"></param> /// <returns></returns> public string CreateDownloadedPostOnDisk(Post post, string weblogName = null) { if (post == null) { return(null); } string filename = GetSafeFilename(post.Title); if (string.IsNullOrEmpty(weblogName)) { weblogName = WeblogInfo.Name; } var mmPostFolder = Path.Combine(WeblogAddinConfiguration.Current.PostsFolder, "Downloaded", weblogName, filename); if (!Directory.Exists(mmPostFolder)) { Directory.CreateDirectory(mmPostFolder); } var outputFile = Path.Combine(mmPostFolder, StringUtils.ToCamelCase(filename) + ".md"); string body = post.Body; string featuredImage = null; string categories = null; if (post.Categories != null && post.Categories.Length > 0) { categories = string.Join(",", post.Categories); } // Create the new post by creating a file with title preset var meta = new WeblogPostMetadata() { Title = post.Title, RawMarkdownBody = body, Categories = categories, Keywords = post.mt_keywords, Abstract = post.mt_excerpt, PostId = post.PostId?.ToString(), WeblogName = weblogName, FeaturedImageUrl = featuredImage, PostDate = post.DateCreated, PostStatus = post.PostStatus, Permalink = post.Permalink }; var postMarkdown = meta.SetPostYamlFromMetaData(); var jekyllPostFolder = Path.Combine(WeblogInfo.ApiUrl, "assets", meta.PostId); postMarkdown = CopyImagesToLocal(postMarkdown, jekyllPostFolder, mmPostFolder); try { File.WriteAllText(outputFile, postMarkdown); } catch (Exception ex) { this.SetError($@"Couldn't write new file at: {outputFile} {ex.Message}"); return(null); } mmApp.Configuration.LastFolder = Path.GetDirectoryName(outputFile); return(outputFile); }
/// <summary> /// Watermarks a PDF file. /// </summary> /// <paramref name="fileName"/> private void WatermarkPdf(string fileName) { var watermarkText = _operation.WatermarkText; var sourceFile = $"{_operation.SourcePath}\\{fileName}"; var destinationPath = $"{_operation.DestinationPath}\\{PathWatermarked}"; var destinationFile = $"{destinationPath}\\{fileName}"; ValidatePath(destinationPath); const float watermarkTrimmingRectangleWidth = 600; const float watermarkTrimmingRectangleHeight = 600; const float formWidth = 300; const float formHeight = 300; const float formXOffset = 0; const float formYOffset = 0; const float xTranslation = 50; const float yTranslation = 25; const double rotationInRads = Math.PI / 3; try { FontCache.ClearSavedFonts(); } catch (Exception exception) { Log.Error(exception.Message); } var font = PdfFontFactory.CreateFont(StandardFonts.COURIER); const float fontSize = 119; using var reader = new PdfReader(new MemoryStream(File.ReadAllBytes(sourceFile))); using var pdfDoc = new PdfDocument(reader, new PdfWriter(destinationFile)); var numberOfPages = pdfDoc.GetNumberOfPages(); PdfPage page = null; for (var i = 1; i <= numberOfPages; i++) { page = pdfDoc.GetPage(i); var ps = page.GetPageSize(); //Center the annotation var bottomLeftX = ps.GetWidth() / 2 - watermarkTrimmingRectangleWidth / 2; var bottomLeftY = ps.GetHeight() / 2 - watermarkTrimmingRectangleHeight / 2; var watermarkTrimmingRectangle = new Rectangle(bottomLeftX, bottomLeftY, watermarkTrimmingRectangleWidth, watermarkTrimmingRectangleHeight); var watermark = new PdfWatermarkAnnotation(watermarkTrimmingRectangle); //Apply linear algebra rotation math //Create identity matrix var transform = new AffineTransform(); //No-args constructor creates the identity transform //Apply translation transform.Translate(xTranslation, yTranslation); //Apply rotation transform.Rotate(rotationInRads); var fixedPrint = new PdfFixedPrint(); watermark.SetFixedPrint(fixedPrint); //Create appearance var formRectangle = new Rectangle(formXOffset, formYOffset, formWidth, formHeight); //Observation: font XObject will be resized to fit inside the watermark rectangle var form = new PdfFormXObject(formRectangle); var gs1 = new PdfExtGState().SetFillOpacity(0.6f); var canvas = new PdfCanvas(form, pdfDoc); var transformValues = new float[6]; transform.GetMatrix(transformValues); canvas.SaveState() .BeginText().SetColor(ColorConstants.GRAY, true).SetExtGState(gs1) .SetTextMatrix(transformValues[0], transformValues[1], transformValues[2], transformValues[3], transformValues[4], transformValues[5]) .SetFontAndSize(font, fontSize) .ShowText(watermarkText) .EndText() .RestoreState(); canvas.Release(); watermark.SetAppearance(PdfName.N, new PdfAnnotationAppearance(form.GetPdfObject())); watermark.SetFlags(PdfAnnotation.PRINT); page.AddAnnotation(watermark); } page?.Flush(); pdfDoc.Close(); }
public void RunJob() { SmtpClient smtpClient = null; try { CoreContext.TenantManager.SetCurrentTenant(_tenantID); SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(_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(); } }
private void launch_Click(object sender, EventArgs e) { var lp = GetLaunchParams(); var engine = (EngineItem)lp[ItemType.ENGINE]; var mod = (ModItem)lp[ItemType.MOD]; string argsstr = cmdline.GetCommandLine(); // Some sanity checks bool reloadengines = false; bool reloadmods = false; List <string> reasons = new List <string>(); if (!File.Exists(engine.FileName)) { reasons.Add("- Selected game engine does not exist!"); reloadengines = true; } if (mod != null && !Directory.Exists(mod.ModPath)) { reasons.Add("- Selected mod folder not exist!"); reloadmods = true; } if (reasons.Count > 0) { MessageBox.Show(this, "Unable to launch:\n" + string.Join("\n", reasons.ToArray()) + "\n\nAffected data will be updated.", App.ErrorMessageTitle); if (reloadengines) { UpdateEngines(); } if (reloadmods) { UpdateAll(); } return; } // Don't mess with window position when launching in windowed mode var res = (ResolutionItem)lp[ItemType.RESOLUTION]; windowx = (res.IsDefault ? (int)this.Left : int.MaxValue); windowy = (res.IsDefault ? (int)this.Top : int.MaxValue); // Proceed with launch enginelaunched = true; #if DEBUG string result = engine.FileName + " " + argsstr; if (MessageBox.Show(this, "Launch parameters:\n" + result + "\n\nProceed?", "Launch Preview", MessageBoxButton.YesNo) == MessageBoxResult.No) { return; } #endif // Setup process info ProcessStartInfo processinfo = new ProcessStartInfo { Arguments = argsstr, FileName = engine.FileName, CreateNoWindow = false, ErrorDialog = false, UseShellExecute = true, WindowStyle = ProcessWindowStyle.Normal, }; processinfo.WorkingDirectory = Path.GetDirectoryName(processinfo.FileName); try { // Start the program var process = Process.Start(processinfo); if (process != null) { process.EnableRaisingEvents = true; process.Exited += ProcessOnExited; } } catch (Exception ex) { // Unable to start the program MessageBox.Show(this, "Unable to start game engine, " + ex.GetType().Name + ": " + ex.Message, App.ErrorMessageTitle); } }
// Doesn't handle random items! private void CreateShortcut(string shortcutpath) { var lp = GetLaunchParams(); // Determine shortcut name string shortcutname; if (lp[ItemType.DEMO] != null && !lp[ItemType.DEMO].IsDefault) { var demo = (DemoItem)lp[ItemType.DEMO]; string map = RemoveInvalidFilenameChars(demo.MapTitle); if (string.IsNullOrEmpty(map)) { map = Path.GetFileName(demo.MapFilePath); } shortcutname = "Watch '" + map.UppercaseFirst() + "' Demo"; } else { // Determine game/map title string map; if (lp[ItemType.MAP] != null && !lp[ItemType.MAP].IsDefault) { var mi = (MapItem)lp[ItemType.MAP]; map = RemoveInvalidFilenameChars(mi.MapTitle); if (string.IsNullOrEmpty(map)) { map = mi.Value; } } else if (lp[ItemType.MOD] != null && !lp[ItemType.MOD].IsDefault) { map = Path.GetFileName(lp[ItemType.MOD].Title); } else if (lp[ItemType.GAME] != null && !lp[ItemType.GAME].IsDefault) { map = RemoveInvalidFilenameChars(lp[ItemType.GAME].Title); } else { map = GameHandler.Current.GameTitle; } shortcutname = "Play '" + map.UppercaseFirst() + "'"; // Add class/skill if available/non-default var extrainfo = new List <string>(); if (lp[ItemType.CLASS] != null && !lp[ItemType.CLASS].IsDefault) { extrainfo.Add(lp[ItemType.CLASS].Title); } if (lp[ItemType.SKILL] != null && !lp[ItemType.SKILL].IsDefault) { extrainfo.Add(lp[ItemType.SKILL].Title); } if (extrainfo.Count > 0) { shortcutname += " (" + string.Join(", ", extrainfo) + ")"; } } // Assemble shortcut path shortcutpath = Path.Combine(shortcutpath, shortcutname + ".lnk"); // Check if we already have a shortcut with that name... if (File.Exists(shortcutpath) && MessageBox.Show("Shortcut '" + shortcutname + "' already exists." + Environment.NewLine + "Do you want to replace it?", "Serious Question", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel) { return; } // Create shortcut string enginepath = ((EngineItem)lp[ItemType.ENGINE]).FileName; var shell = new WshShell(); var shortcut = (IWshShortcut)shell.CreateShortcut(shortcutpath); shortcut.TargetPath = enginepath; shortcut.WorkingDirectory = Path.GetDirectoryName(enginepath); shortcut.Arguments = cmdline.GetCommandLine(); shortcut.Save(); }
public static void UseNewLanguageFile(string fileName, long id, int msgId) { var msg = "Moving file to production..\n"; msg += "Checking paths for duplicate language file...\n"; Bot.Api.EditMessageTextAsync(id, msgId, msg).Wait(); fileName += ".xml"; var tempPath = Bot.TempLanguageDirectory; var langPath = Bot.LanguageDirectory; var newFilePath = Path.Combine(tempPath, fileName); var copyToPath = Path.Combine(langPath, fileName); //get the new files language var doc = XDocument.Load(newFilePath); var newFileLang = new { Name = doc.Descendants("language").First().Attribute("name").Value, Base = doc.Descendants("language").First().Attribute("base").Value, Variant = doc.Descendants("language").First().Attribute("variant").Value }; //check for existing file var langs = Directory.GetFiles(langPath, "*.xml").Select(x => new LangFile(x)).ToList(); var lang = langs.FirstOrDefault(x => x.Name == newFileLang.Name && x.FilePath != copyToPath); if (lang != null) { msg += $"Found duplicate language (name attribute) with filename {Path.GetFileNameWithoutExtension(lang.FilePath)}\n"; copyToPath = lang.FilePath; } else { lang = langs.FirstOrDefault(x => x.Base == newFileLang.Base && x.Variant == newFileLang.Variant && x.Name != newFileLang.Name); if (lang != null) { msg += $"Found duplicate language (matching base and variant) with filename {Path.GetFileNameWithoutExtension(lang.FilePath)}\n"; msg += "Aborting!"; Bot.Api.EditMessageTextAsync(id, msgId, msg); return; } } System.IO.File.Copy(newFilePath, copyToPath, true); msg += "File copied to bot\n"; //#if RELEASE // msg += $"File copied to bot 1\n"; //#elif RELEASE2 // msg += $"File copied to bot 2\n"; //#endif //Bot.Api.EditMessageTextAsync(id, msgId, msg); //#if RELEASE // copyToPath = copyToPath.Replace("Werewolf 3.0", "Werewolf 3.0 Clone"); // System.IO.File.Copy(newFilePath, copyToPath, true); // msg += $"File copied to bot 2\n"; // Bot.Api.EditMessageTextAsync(id, msgId, msg); //#endif #if !DEBUG var gitPath = Path.Combine(@"C:\Werewolf Source\Werewolf\Werewolf for Telegram\Languages", Path.GetFileName(copyToPath)); File.Copy(newFilePath, gitPath, true); System.IO.File.Delete(newFilePath); msg += $"File copied to git directory\n"; if (Path.GetFileName(newFilePath) == Program.MasterLanguage) { var p = new Process { StartInfo = { FileName = @"C:\Werewolf Source\Werewolf\Werewolf for Telegram\Languages\commit.bat", Arguments = $"\"Syncing langfiles from Telegram (English.xml update)\"", WorkingDirectory = @"C:\Werewolf Source\Werewolf\Werewolf for Telegram\Languages", UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true } }; p.Start(); msg += "Started the committing process. Reading output from git..."; Bot.Edit(id, msgId, msg).Wait(); var output = ""; while (!p.StandardOutput.EndOfStream) { output += p.StandardOutput.ReadLine() + Environment.NewLine; } while (!p.StandardError.EndOfStream) { output += p.StandardError.ReadLine() + Environment.NewLine; } msg += "\nValidating the output..."; Bot.Edit(id, msgId, msg).Wait(); //validate the output if (output.Contains("failed")) { msg += "\n<b>Failed</b> to commit files. See control output for information"; Console.WriteLine(output); } else if (output.Contains("nothing to commit")) { msg += "\nNothing to commit."; } else { //try to grab the commit var regex = new Regex("(\\[master .*])"); var match = regex.Match(output); var commit = ""; if (match.Success) { commit = match.Value.Replace("[master ", "").Replace("]", ""); } msg += $"\n<b>Files committed successfully.</b> {(String.IsNullOrEmpty(commit) ? "" : $"<a href=\"https://github.com/GreyWolfDev/Werewolf/commit/" + commit + $"\">{commit}</a>")}"; } } #endif using (var db = new WWContext()) { var newFile = new LangFile(copyToPath); // search for language file entry and update it or add it if it's not present yet Language language = db.Language.FirstOrDefault(x => x.FileName == newFile.FileName); if (language == null) { language = db.Language.Add(new Language { FileName = newFile.FileName }); } language.Base = newFile.Base; language.IsDefault = newFile.IsDefault; language.LangCode = newFile.LangCode; language.Name = newFile.Name; language.Variant = newFile.Variant; db.SaveChanges(); } var info = new ReloadLangInfo { LangName = Path.GetFileNameWithoutExtension(copyToPath) }; var json = JsonConvert.SerializeObject(info); foreach (var n in Bot.Nodes) { n.Broadcast(json); } msg += "\n<b>Operation complete.</b>"; Bot.Edit(id, msgId, msg, parsemode: ParseMode.Html); }
async Task OnTick() { LogEventLevel?minimumAcceptedLevel = null; try { int count; do { count = 0; // 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)) { long nextLineBeginsAtOffset; string currentFile; TryReadBookmark(bookmark, out nextLineBeginsAtOffset, out currentFile); var fileSet = GetFileSet(); if (currentFile == null || !IOFile.Exists(currentFile)) { nextLineBeginsAtOffset = 0; currentFile = fileSet.FirstOrDefault(); } if (currentFile == null) { continue; } var payload = ReadPayload(currentFile, ref nextLineBeginsAtOffset, ref count); if (count > 0 || _controlledSwitch.IsActive && _nextRequiredLevelCheckUtc < DateTime.UtcNow) { lock (_stateLock) { _nextRequiredLevelCheckUtc = DateTime.UtcNow.Add(RequiredLevelCheckInterval); } var content = new StringContent(payload, Encoding.UTF8, "application/json"); if (!string.IsNullOrWhiteSpace(_apiKey)) { content.Headers.Add(SeqApi.ApiKeyHeaderName, _apiKey); } var result = await _httpClient.PostAsync(SeqApi.BulkUploadResource, content); if (result.IsSuccessStatusCode) { _connectionSchedule.MarkSuccess(); WriteBookmark(bookmark, nextLineBeginsAtOffset, currentFile); var returned = await result.Content.ReadAsStringAsync(); minimumAcceptedLevel = SeqApi.ReadEventInputResult(returned); } else if (result.StatusCode == HttpStatusCode.BadRequest || result.StatusCode == HttpStatusCode.RequestEntityTooLarge) { // The connection attempt was successful - the payload we sent was the problem. _connectionSchedule.MarkSuccess(); await DumpInvalidPayload(result, payload); WriteBookmark(bookmark, nextLineBeginsAtOffset, currentFile); } else { _connectionSchedule.MarkFailure(); SelfLog.WriteLine("Received failed HTTP shipping result {0}: {1}", result.StatusCode, await result.Content.ReadAsStringAsync()); 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(bookmark, 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(); } } } }
public HttpResponseMessage PutSaveView([FromBody] ViewFile view) { var ct = JsonConvert.DeserializeObject <string>(view.Value); if (view.IsNew) { view.FileName = view.NewFileName; } var filenameChanged = view.FileName.ToLowerInvariant() != view.NewFileName.ToLowerInvariant(); if (filenameChanged && File.Exists(HttpContext.Current.Request.MapPath("~/Views/" + view.NewFileName))) { return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } if (filenameChanged && view.FileName.IsValidViewFile() && view.NewFileName.IsValidViewFile()) { using (var streamWriter = new StreamWriter(HttpContext.Current.Request.MapPath("~/Views/" + view.NewFileName), false)) { streamWriter.WriteLine(ct); // Write the text } // If new file was successfully written, delete the old one // TODO: sync tree here? if (view.FileName.StartsWith("-1") == false && view.FileName.IsValidViewFile() && File.Exists(HttpContext.Current.Request.MapPath("~/Views/" + view.NewFileName))) { File.Delete(HttpContext.Current.Request.MapPath("~/Views/" + view.FileName)); } } if (view.FileName.IsValidViewFile()) { var file = filenameChanged ? view.NewFileName : view.FileName; using (var streamWriter = new StreamWriter(HttpContext.Current.Request.MapPath("~/Views/" + file), false)) { streamWriter.WriteLine(ct); // Write the text } } return(new HttpResponseMessage(HttpStatusCode.OK)); }
private void AddSearchDocumentTypeAndPage() { var migrationName = MethodBase.GetCurrentMethod().Name; try { var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt"); if (File.Exists(path)) { return; } var contentTypeService = ApplicationContext.Current.Services.ContentTypeService; var searchContentType = contentTypeService.GetContentType("search"); if (searchContentType == null) { var contentType = new ContentType(-1) { Name = "Search", Alias = "search", Icon = "icon-search" }; contentType.PropertyGroups.Add(new PropertyGroup { Name = "Content" }); var checkbox = new DataTypeDefinition("Umbraco.TrueFalse"); var checkboxPropertyType = new PropertyType(checkbox, "umbracoNaviHide") { Name = "Hide in navigation?" }; contentType.AddPropertyType(checkboxPropertyType, "Content"); contentTypeService.Save(contentType); searchContentType = contentTypeService.GetContentType("search"); var templateCreateResult = ApplicationContext.Current.Services.FileService.CreateTemplateForContentType("search", "Search"); if (templateCreateResult.Success) { var template = ApplicationContext.Current.Services.FileService.GetTemplate("search"); var masterTemplate = ApplicationContext.Current.Services.FileService.GetTemplate("master"); template.SetMasterTemplate(masterTemplate); ApplicationContext.Current.Services.FileService.SaveTemplate(template); searchContentType.AllowedTemplates = new List <ITemplate> { template }; searchContentType.SetDefaultTemplate(template); contentTypeService.Save(searchContentType); var contentService = ApplicationContext.Current.Services.ContentService; var rootContent = contentService.GetRootContent().FirstOrDefault(); if (rootContent != null) { var searchPage = rootContent.Children().FirstOrDefault(x => x.Name == "Search"); contentService.Delete(searchPage); searchPage = contentService.CreateContent("Search", rootContent.Id, "search"); var saveResult = contentService.SaveAndPublishWithStatus(searchPage); } } } } catch (Exception ex) { LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex); } }
public async Task <IActionResult> Publish(IFormFile package) { // Copy the package to a temporary file, and read package info try { PackageIdentity packageIdentity; string packageHash; string nuspecContent; var tmpPackagePath = Path.GetTempFileName(); using (var tmpFile = IOFile.Open(tmpPackagePath, FileMode.Create, FileAccess.ReadWrite)) { await package.CopyToAsync(tmpFile); tmpFile.Seek(0, SeekOrigin.Begin); var reader = new PackageArchiveReader(tmpFile, true); packageIdentity = reader.GetIdentity(); var nuspecReader = new StreamReader(reader.GetNuspec()); nuspecContent = await nuspecReader.ReadToEndAsync(); tmpFile.Seek(0, SeekOrigin.Begin); packageHash = Convert.ToBase64String(new CryptoHashProvider("SHA512").CalculateHash(tmpFile)); } // Repository var localRepDir = Directory.GetCurrentDirectory() + "/packages/"; var pathResolver = new VersionFolderPathResolver(localRepDir, true); // Check if package already exists if (IOFile.Exists(pathResolver.GetPackageFilePath(packageIdentity.Id, packageIdentity.Version))) { Console.WriteLine($"[WARNING] Package already exists"); return(Conflict()); } // Create the package/version folder, and write files Directory.CreateDirectory(pathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version)); IOFile.Move(tmpPackagePath, pathResolver.GetPackageFilePath(packageIdentity.Id, packageIdentity.Version)); using (var hashFile = IOFile.CreateText(pathResolver.GetHashPath(packageIdentity.Id, packageIdentity.Version))) { await hashFile.WriteAsync(packageHash); } using (var nuspecFile = IOFile.CreateText(pathResolver.GetManifestFilePath(packageIdentity.Id, packageIdentity.Version))) { await nuspecFile.WriteAsync(nuspecContent); } return(Ok()); } catch (Exception ex) { Console.WriteLine($"[ERROR] Processing package. {ex.Message}"); return(BadRequest()); } }
private void UseNewRssFeedsOverview() { var migrationName = MethodBase.GetCurrentMethod().Name; try { var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt"); if (File.Exists(path)) { return; } var contentService = ApplicationContext.Current.Services.ContentService; var rootContent = contentService.GetRootContent().FirstOrDefault(); if (rootContent != null) { var rssPage = rootContent.Children().FirstOrDefault(x => string.Equals(x.Name, "Rss", StringComparison.InvariantCultureIgnoreCase)); foreach (var page in rssPage.Children()) { if (string.Equals(page.Name, "Wiki", StringComparison.InvariantCultureIgnoreCase)) { contentService.UnPublish(page); } if (string.Equals(page.Name, "CommunityBlogs", StringComparison.InvariantCultureIgnoreCase)) { contentService.UnPublish(page); } if (string.Equals(page.Name, "Help", StringComparison.InvariantCultureIgnoreCase)) { contentService.UnPublish(page); } if (string.Equals(page.Name, "Forum", StringComparison.InvariantCultureIgnoreCase)) { page.SetValue("macro", "RSSForum"); contentService.SaveAndPublishWithStatus(page); } if (string.Equals(page.Name, "ActiveTopics", StringComparison.InvariantCultureIgnoreCase)) { page.SetValue("macro", "RssLatestTopics"); contentService.SaveAndPublishWithStatus(page); } if (string.Equals(page.Name, "Projects", StringComparison.InvariantCultureIgnoreCase)) { page.SetValue("macro", "RSSPackages"); contentService.SaveAndPublishWithStatus(page); } if (string.Equals(page.Name, "Karma", StringComparison.InvariantCultureIgnoreCase)) { contentService.UnPublish(page); } if (string.Equals(page.Name, "YourTopics", StringComparison.InvariantCultureIgnoreCase)) { page.SetValue("macro", "RSSParticipated"); contentService.SaveAndPublishWithStatus(page); } if (string.Equals(page.Name, "ProjectsUpdate", StringComparison.InvariantCultureIgnoreCase)) { page.SetValue("macro", "RssPackages"); contentService.SaveAndPublishWithStatus(page); } if (string.Equals(page.Name, "Topic", StringComparison.InvariantCultureIgnoreCase)) { page.SetValue("macro", "RSSTopic"); contentService.SaveAndPublishWithStatus(page); } } var htmlPage = rootContent.Children().FirstOrDefault(x => string.Equals(x.Name, "html", StringComparison.InvariantCultureIgnoreCase)); foreach (var page in htmlPage.Children()) { if (string.Equals(page.Name, "GithubPullTrigger", StringComparison.InvariantCultureIgnoreCase)) { page.SetValue("macro", "Documentation-GithubSync"); contentService.SaveAndPublishWithStatus(page); } else { contentService.UnPublish(page); } } } string[] lines = { "" }; File.WriteAllLines(path, lines); } catch (Exception ex) { LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex); } }
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); if (args.Length == 1) { 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); }
/// <summary> /// ZIP変換する。 /// </summary> /// <returns></returns> private bool convertZip() { // Todo: ファイルからまとめてZIP圧縮をサポートする。 bool result = false; try { TagEditFileInfo fileInfo = _fileInfoList[0]; string oldArchiveFilePath = fileInfo.ArchiveFilePath; string newArchiveFilePath = oldArchiveFilePath.Replace(Path.GetExtension(oldArchiveFilePath), ".zip"); if (File.Exists(fileInfo.ArchiveFilePath)) { // アーカイブファイル内一覧取得 IList <string> targetPathList = SevenZipManager.Instance.getFileNames(oldArchiveFilePath); // アーカイブを解凍する SevenZipManager.Instance.extract(oldArchiveFilePath, Path.Combine(LinearGlobal.TempDirectory, "conv")); // ZIPで再圧縮 SevenZipManager.Instance.compress(newArchiveFilePath, targetPathList, Path.Combine(LinearGlobal.TempDirectory, "conv")); // DB更新 updateDB(oldArchiveFilePath, newArchiveFilePath); // フォーム内変数更新 foreach (TagEditFileInfo tefi in _fileInfoList) { tefi.ArchiveFilePath = newArchiveFilePath; } // グリッド更新 int i = 1; while (i <= LinearAudioPlayer.GridController.Grid.Rows.Count - 1) { if (oldArchiveFilePath.Equals(LinearAudioPlayer.GridController.getValue(i, (int)GridController.EnuGrid.FILEPATH))) { LinearAudioPlayer.GridController .Grid[i, (int)GridController.EnuGrid.FILEPATH].Value = newArchiveFilePath; } i++; } // ファイルを削除 FileUtils.moveRecycleBin(oldArchiveFilePath); } txtArchivePath.Text = newArchiveFilePath; result = true; } catch (Exception ex) { MessageUtils.showMessage(MessageBoxIcon.Error, MessageResource.E0003 + "\n" + ex.Message); } return(result); }
public MainWindow() { _webClient = new WebClient(); InitializeComponent(); try { if (!IsElevated) { var p = new Process { StartInfo = { FileName = Assembly.GetEntryAssembly().Location, Verb = "runas", Arguments = string.Join(" ", Environment.GetCommandLineArgs().Skip(1)) } }; p.Start(); Environment.Exit(-1); } var useCurrentPath = Array.Exists(Environment.GetCommandLineArgs(), x => x.Contains("--useCurrentPath")); _forceUpdate = Array.Exists(Environment.GetCommandLineArgs(), x => x.Contains("--forceUpdate")); if (useCurrentPath) { Console.WriteLine("Skipping Registry Checks & Installation."); } Console.WriteLine("Downloading Manifest..."); XmlSerializer serializer = new XmlSerializer(typeof(UpdateManifest)); _updateManifest = (UpdateManifest)serializer.Deserialize(new StringReader(new WebClient().DownloadString(UPDATE_URL))); var installationPath = Environment.GetEnvironmentVariable("ProgramFiles") + "\\HomeState\\"; var subKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\HomeState", true); Console.WriteLine(_updateManifest.UpdaterVersion); _installDir = installationPath; var _updateUpdater = Array.Exists(Environment.GetCommandLineArgs(), x => x.Contains("--update")); if ((_updateManifest.UpdaterVersion != FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).FileVersion) && subKey != null && !_updateUpdater) { //Needs to update. if (File.Exists(Path.GetTempPath() + "\\Launcher.exe")) { File.Delete(Path.GetTempPath() + "\\Launcher.exe"); } File.Copy(Assembly.GetEntryAssembly().Location, Path.GetTempPath() + "\\Launcher.exe"); var p = new Process { StartInfo = { FileName = Path.GetTempPath() + "\\Launcher.exe", Verb = "runas", Arguments = "--update" } }; p.Start(); Environment.Exit(-1); } if (_updateUpdater) { if (subKey == null) { Environment.Exit(0); } if (File.Exists(installationPath + "Launcher.exe")) { File.Delete(installationPath + "Launcher.exe"); } new WebClient().DownloadFile(_updateManifest.UpdaterFile, installationPath + "Launcher.exe"); var p = new Process { StartInfo = { FileName = installationPath + "Launcher.exe", Verb = "runas" } }; p.Start(); Environment.Exit(0); } if (!useCurrentPath) { if (subKey != null) { var installPathRegistry = (string)subKey.GetValue("InstallationPath", installationPath); _installDir = installPathRegistry; Console.WriteLine(Assembly.GetEntryAssembly().Location); Console.WriteLine(_installDir + "Launcher.exe"); Console.WriteLine(Assembly.GetEntryAssembly().Location == _installDir); if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu) + @"\Programme\HomeState\")) { Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu) + @"\Programme\HomeState\"); appShortcutToStartmenu("HomeState Launcher"); } if (!string.Equals(Assembly.GetEntryAssembly().Location, _installDir + "Launcher.exe")) { if (!File.Exists(_installDir + "Launcher.exe")) { File.Copy(Process.GetCurrentProcess().MainModule.FileName, _installDir + "Launcher.exe"); } Process.Start(_installDir + "Launcher.exe"); Environment.Exit(0); } } else { Console.WriteLine(@"RegKey not found. HomeState Launcher is not installed"); Console.WriteLine(_installDir); if (Directory.Exists(_installDir)) { Directory.Delete(_installDir, true); } Directory.CreateDirectory(_installDir); Console.WriteLine(Process.GetCurrentProcess().MainModule.FileName); File.Copy(Process.GetCurrentProcess().MainModule.FileName, _installDir + "Launcher.exe"); subKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\HomeState"); subKey?.SetValue("InstallationPath", _installDir, RegistryValueKind.String); if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu) + @"\Programme\HomeState\")) { Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu) + @"\Programme\HomeState\"); appShortcutToStartmenu("HomeState Launcher"); } Process.Start(_installDir + "\\Launcher.exe"); Environment.Exit(0); } } Console.WriteLine("Initialized. Ready to check Launcher Version."); if (useCurrentPath) { _installDir = Environment.CurrentDirectory + "\\"; } } catch (Exception eex) { Console.WriteLine(eex); Console.Read(); } }
public void CreateDownloadedPostOnDisk(Post post, string weblogName) { string filename = FileUtils.SafeFilename(post.Title); var folder = Path.Combine(WeblogAddinConfiguration.Current.PostsFolder, "Downloaded", weblogName, filename); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } var outputFile = Path.Combine(folder, StringUtils.ToCamelCase(filename) + ".md"); bool isMarkdown = false; string body = post.Body; string featuredImage = null; if (post.CustomFields != null) { var cf = post.CustomFields.FirstOrDefault(custf => custf.Id == "mt_markdown"); if (cf != null) { body = cf.Value; isMarkdown = true; } cf = post.CustomFields.FirstOrDefault(custf => custf.Id == "wp_post_thumbnail"); if (cf != null) { featuredImage = cf.Value; } } if (!isMarkdown) { if (!string.IsNullOrEmpty(post.mt_text_more)) { // Wordpress ReadMore syntax - SERIOUSLY??? if (string.IsNullOrEmpty(post.mt_excerpt)) { post.mt_excerpt = HtmlUtils.StripHtml(post.Body); } body = MarkdownUtilities.HtmlToMarkdown(body) + $"{mmApp.NewLine}{mmApp.NewLine}<!--more-->{mmApp.NewLine}{mmApp.NewLine}" + MarkdownUtilities.HtmlToMarkdown(post.mt_text_more); } else { body = MarkdownUtilities.HtmlToMarkdown(body); } } string categories = null; if (post.Categories != null && post.Categories.Length > 0) { categories = string.Join(",", post.Categories); } // Create the new post by creating a file with title preset var meta = new WeblogPostMetadata() { Title = post.Title, MarkdownBody = body, Categories = categories, Keywords = post.mt_keywords, Abstract = post.mt_excerpt, PostId = post.PostId.ToString(), WeblogName = weblogName, FeaturedImageUrl = featuredImage, PostDate = post.DateCreated, PostStatus = post.PostStatus, Permalink = post.Permalink }; string newPostMarkdown = NewWeblogPost(meta); try { File.WriteAllText(outputFile, newPostMarkdown); } catch (Exception ex) { MessageBox.Show($@"Couldn't write new file at: {outputFile} {ex.Message} ", "Weblog Entry File not created", MessageBoxButton.OK, MessageBoxImage.Warning); return; } mmApp.Configuration.LastFolder = Path.GetDirectoryName(outputFile); if (isMarkdown) { string html = post.Body; string path = mmApp.Configuration.LastFolder; // do this synchronously so images show up :-< ShowStatus("Downloading post images...", mmApp.Configuration.StatusMessageTimeout); SaveMarkdownImages(html, path); ShowStatus("Post download complete.", mmApp.Configuration.StatusMessageTimeout); //new Action<string,string>(SaveImages).BeginInvoke(html,path,null, null); } Model.Window.OpenTab(outputFile); Model.Window.ShowFolderBrowser(folder: Path.GetDirectoryName(outputFile)); }
public void OpenFile(string filename, FileSystem fs) { if (fs == null) { if (filename.EndsWith(".rpf")) { fs = new RPFFileSystem(); } else if (filename.EndsWith(".img")) { fs = new IMGFileSystem(); } else if (IODirectory.Exists(filename)) { fs = new RealFileSystem(); filename = (new DirectoryInfo(filename)).FullName; } } if (fs != null) { if (IOFile.Exists(filename)) { FileInfo fi = new FileInfo(filename); if ((fi.Attributes & FileAttributes.ReadOnly) != 0) { DialogResult result = MessageBox.Show("The file you are trying to open appears to be read-only. " + "Would you like to make it writable before opening this file?", "Open", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { fi.Attributes = fi.Attributes & ~FileAttributes.ReadOnly; } } } try { using (new WaitCursor(this)) { fs.Open(filename); if (_fs != null) { _fs.Close(); } _fs = fs; Text = Application.ProductName + " - " + new FileInfo(filename).Name; } PopulateUI(); } catch (Exception ex) { fs.Close(); MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
/// <summary> /// Perform the configuration import that the controller has prepared to do. /// </summary> internal void DoImport() { Debug.Assert(NewConfigToImport != null); ImportCustomFields(_importLiftLocation); // If the configuration to import has the same label as an existing configuration in the project folder // then overwrite the existing configuration. var existingConfigurationInTheWay = _configurations.FirstOrDefault(config => config.Label == NewConfigToImport.Label && Path.GetDirectoryName(config.FilePath) == _projectConfigDir); NewConfigToImport.Publications.ForEach( publication => { AddPublicationTypeIfNotPresent(publication, _cache); }); try { ImportStyles(_importStylesLocation); ImportHappened = true; } catch (InstallationException e) // This is the exception thrown if the dtd guid in the style file doesn't match our program { #if DEBUG if (_view == null) // _view is sometimes null in unit tests, and it's helpful to know what exactly went wrong. { throw new Exception(xWorksStrings.kstidCannotImport, e); } #endif _view.explanationLabel.Text = xWorksStrings.kstidCannotImport; } // We have re-loaded the model from disk to preserve custom field state so the Label must be set here NewConfigToImport.FilePath = _temporaryImportConfigLocation; NewConfigToImport.Load(_cache); if (existingConfigurationInTheWay != null) { _configurations.Remove(existingConfigurationInTheWay); if (existingConfigurationInTheWay.FilePath != null) { FileUtils.Delete(existingConfigurationInTheWay.FilePath); } } else { NewConfigToImport.Label = _proposedNewConfigLabel; } // Set a filename for the new configuration. Use a unique filename that isn't either registered with another configuration, or existing on disk. Note that in this way, we ignore what the original filename was of the configuration file in the .zip file. DictionaryConfigurationManagerController.GenerateFilePath(_projectConfigDir, _configurations, NewConfigToImport); var outputConfigPath = existingConfigurationInTheWay != null ? existingConfigurationInTheWay.FilePath : NewConfigToImport.FilePath; File.Move(_temporaryImportConfigLocation, outputConfigPath); NewConfigToImport.FilePath = outputConfigPath; _configurations.Add(NewConfigToImport); // phone home (analytics) var configType = NewConfigToImport.Type; var configDir = DictionaryConfigurationListener.GetDefaultConfigurationDirectory( configType == DictionaryConfigurationModel.ConfigType.Reversal ? DictionaryConfigurationListener.ReversalIndexConfigurationDirectoryName : DictionaryConfigurationListener.DictionaryConfigurationDirectoryName); var isCustomizedOriginal = DictionaryConfigurationManagerController.IsConfigurationACustomizedOriginal(NewConfigToImport, configDir, _cache); UsageReporter.SendEvent("DictionaryConfigurationImport", "Import", "Import Config", string.Format("Import of [{0}{1}]:{2}", configType, isCustomizedOriginal ? string.Empty : "-Custom", ImportHappened ? "succeeded" : "failed"), 0); }
private bool CheckExtracted() { return(File.Exists(_currentDirectory + "\\opus.dll") && File.Exists(_currentDirectory + "\\awacs-radios.json") && File.Exists(_currentDirectory + "\\SR-ClientRadio.exe") && File.Exists(_currentDirectory + "\\Scripts\\DCS-SRS\\Scripts\\DCS-SimpleRadioStandalone.lua")); }
public override bool Execute() { if (!Overwrite && IOFile.Exists(File)) { Log.LogError($"Zip file {File} already exists. Set Overwrite=true to replace it."); return(false); } var workDir = FileHelpers.EnsureTrailingSlash(WorkingDirectory).Replace('\\', '/'); foreach (var file in SourceFiles) { if (!string.IsNullOrEmpty(file.GetMetadata("Link"))) { continue; } var filePath = file.ItemSpec.Replace('\\', '/'); if (!filePath.StartsWith(workDir)) { Log.LogError("Item {0} is not inside the working directory {1}. Set the metadata 'Link' to file path that should be used within the zip archive", filePath, workDir); return(false); } file.SetMetadata("Link", filePath.Substring(workDir.Length)); } Directory.CreateDirectory(Path.GetDirectoryName(File)); using (var stream = IOFile.Create(File)) using (var zip = new ZipArchiveStream(stream, ZipArchiveMode.Create)) { foreach (var file in SourceFiles) { var entryName = file.GetMetadata("Link").Replace('\\', '/'); if (string.IsNullOrEmpty(Path.GetFileName(entryName))) { Log.LogError("Empty file names not allowed. The effective entry path for item '{0}' is '{1}'", file.ItemSpec, entryName); return(false); } var entry = zip.CreateEntryFromFile(file.ItemSpec, entryName); #if NET46 #elif NETCOREAPP2_0 if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // This isn't required when creating a zip on Windows. unzip will check which // platform was used to create the zip file. If the zip was created on Windows, // unzip will use a default set of permissions. However, if the zip was created // on a Unix-y system, it will set the permissions as defined in the external_attr // field. // Set the file permissions on each entry so they are extracted correctly on Unix. // Picking -rw-rw-r-- by default because we don't yet have a good way to access existing // Unix permissions. If we don't set this, files may be extracted as ---------- (0000), // which means the files are completely unusable. // FYI - this may not be necessary in future versions of .NET Core. See https://github.com/dotnet/corefx/issues/17342. const int rw_rw_r = (0x8000 + 0x0100 + 0x0080 + 0x0020 + 0x0010 + 0x0004) << 16; entry.ExternalAttributes = rw_rw_r; } #else #error Update target frameworks #endif Log.LogMessage("Added '{0}' to archive", entry.FullName); } } var fileInfo = new FileInfo(File); Log.LogMessage(MessageImportance.High, $"Added {SourceFiles.Length} file(s) to '{File}' ({fileInfo.Length / 1024:n0} KB)"); return(true); }
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\\Tech"); CreateDirectory(path + "\\Mods\\Tech\\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") && !contents.Contains("Mods\\Tech\\DCS-SRS\\Scripts\\DCS-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"); _progressBarDialog.UpdateProgress(false, $"Creating / installing Hooks & Mods @ {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\\Tech\\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 @ {path}"); }
private void WorkerThread() { bool file = false; try { if (File.Exists(Source)) { file = true; } } catch { // ignored } if (_mFactory == null) { var args = new List <string> { "-I", "dumy", "--ignore-config", "--no-osd", "--disable-screensaver", "--plugin-path=./plugins" }; if (file) { args.Add("--file-caching=3000"); } try { var l2 = args.ToList(); l2.AddRange(_arguments); l2 = l2.Distinct().ToList(); _mFactory = new MediaPlayerFactory(l2.ToArray()); } catch (Exception ex) { Logger.LogException(ex, "VLC Stream"); Logger.LogMessage("VLC arguments are: " + string.Join(",", args.ToArray()), "VLC Stream"); Logger.LogMessage("Using default VLC configuration.", "VLC Stream"); return; } GC.KeepAlive(_mFactory); } var vss = Source; if (!_modeAudio) { vss = Tokenise(vss); } _mMedia = file ? _mFactory.CreateMedia <IMediaFromFile>(vss) : _mFactory.CreateMedia <IMedia>(vss); _mMedia.Events.DurationChanged += EventsDurationChanged; _mMedia.Events.StateChanged += EventsStateChanged; if (_mPlayer != null) { try { _mPlayer?.Dispose(); } catch { // ignored } _mPlayer = null; } _mPlayer = _mFactory.CreatePlayer <IVideoPlayer>(); _mPlayer.Events.TimeChanged += EventsTimeChanged; var fc = new Func <SoundFormat, SoundFormat>(SoundFormatCallback); _mPlayer.CustomAudioRenderer.SetFormatCallback(fc); var ac = new AudioCallbacks { SoundCallback = SoundCallback }; _mPlayer.CustomAudioRenderer.SetCallbacks(ac); _mPlayer.CustomAudioRenderer.SetExceptionHandler(Handler); if (!_modeAudio) { _mPlayer.CustomRenderer.SetCallback(FrameCallback); _mPlayer.CustomRenderer.SetExceptionHandler(Handler); } GC.KeepAlive(_mPlayer); _needsSetup = true; if (!_modeAudio) { _mPlayer.CustomRenderer.SetFormat(new BitmapFormat(_source.settings.vlcWidth, _source.settings.vlcHeight, ChromaType.RV24)); } _mPlayer.Open(_mMedia); _mMedia.Parse(true); _mPlayer.Delay = 0; Duration = Time = 0; LastFrame = DateTime.MinValue; //check if file source (isseekable in _mPlayer is not reliable) Seekable = false; try { var p = Path.GetFullPath(_mMedia.Input); Seekable = !string.IsNullOrEmpty(p); } catch (Exception) { Seekable = false; } _videoQueue = new ConcurrentQueue <Bitmap>(); _audioQueue = new ConcurrentQueue <byte[]>(); _mPlayer.Play(); _abort = new ManualResetEvent(false); EventManager(); if (Seekable) { PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.StoppedByUser)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.StoppedByUser)); } else { PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); } DisposePlayer(); _abort.Close(); }
public void Update([NotNull] string code, [NotNull] string gold) { IOFile.WriteAllText(TestPath, code); IOFile.WriteAllText(Path.ChangeExtension(TestPath, ".gold"), gold); }
public bool FileExists(string name) { return(FLE.Exists(PTH.Combine(_path, name))); }