private void VerifyStorage() { var os = ObjectFactory.GetProvider<IStorageProvider>(); var fs = new FileSystemUtils(); try { fs.Verify(); os.Verify(); fs.SaveAppConfiguration(); } catch (DataFolderDoesNotExistException e) { ObjectFactory.GetProvider<IAppConfigProvider>().AppConfig.FirstTimeRunning = true; } }
/// <summary> /// Handles file system exceptions and rethrows PHP exceptions. /// </summary> /// <typeparam name="T">The return value type.</typeparam> /// <param name="invalid">Invalid value.</param> /// <param name="path">Path to the resource passed to the <paramref name="action"/>. Also used for error control.</param> /// <param name="action">Action to try. The first argument is the path.</param> /// <returns>The value of <paramref name="action"/>() or <paramref name="invalid"/>.</returns> internal static T HandleFileSystemInfo <T>(T invalid, string path, Func <string, T> /*!*/ action) { try { return(action(path)); } catch (ArgumentException) { PhpException.Throw(PhpError.Warning, ErrResources.stream_stat_invalid_path, FileSystemUtils.StripPassword(path)); } catch (PathTooLongException) { PhpException.Throw(PhpError.Warning, ErrResources.stream_stat_invalid_path, FileSystemUtils.StripPassword(path)); } catch (System.Exception e) { PhpException.Throw(PhpError.Warning, ErrResources.stream_error, FileSystemUtils.StripPassword(path), e.Message); } return(invalid); }
private bool ProcessCleanupFile() { Log.AddInfo(string.Format(Util.CLEANUP_Processing, Version.ToString(3))); bool bSuccess = true; try { string strListFile = Path.Combine(this.Package.InstallerInfo.TempInstallFolder, _FileName); if (File.Exists(strListFile)) { FileSystemUtils.DeleteFiles(System.Text.RegularExpressions.Regex.Split(FileSystemUtils.ReadFile(strListFile), Environment.NewLine)); } Log.AddInfo(string.Format(Util.CLEANUP_ProcessComplete, Version.ToString(3))); } catch (Exception ex) { Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); bSuccess = false; } return(bSuccess); }
protected void Save_OnClick(object sender, EventArgs e) { try { if (FolderList.Items.Count == 0) { return; } DotNetNuke.Entities.Portals.PortalSettings portalSettings = DotNetNuke.Entities.Portals.PortalSettings.Current; string fileContents = htmlText2.Text.Trim(); string newFileName = FileName.Text; if (!(newFileName.EndsWith(".html"))) { newFileName = newFileName + ".html"; } string rootFolder = portalSettings.HomeDirectoryMapPath; string dbFolderPath = FolderList.SelectedValue; string virtualFolder = (string)(string)FileSystemValidation.ToVirtualPath(dbFolderPath); rootFolder = rootFolder + FolderList.SelectedValue; rootFolder = rootFolder.Replace("/", "\\"); string errorMessage = string.Empty; FolderController folderCtrl = new FolderController(); FolderInfo folder = folderCtrl.GetFolder(portalSettings.PortalId, dbFolderPath, false); if ((folder == null)) { ShowSaveTemplateMessage(GetString("msgFolderDoesNotExist.Text")); return; } // Check file name is valid FileSystemValidation dnnValidator = new FileSystemValidation(); errorMessage = dnnValidator.OnCreateFile(virtualFolder + newFileName, fileContents.Length); if (!(string.IsNullOrEmpty(errorMessage))) { ShowSaveTemplateMessage(errorMessage); return; } FileController fileCtrl = new FileController(); DotNetNuke.Services.FileSystem.FileInfo existingFile = fileCtrl.GetFile(newFileName, portalSettings.PortalId, folder.FolderID); // error if file exists if (!Overwrite.Checked && existingFile != null) { ShowSaveTemplateMessage(GetString("msgFileExists.Text")); return; } FileInfo newFile = existingFile; if ((newFile == null)) { newFile = new FileInfo(); } newFile.FileName = newFileName; newFile.ContentType = "text/plain"; newFile.Extension = "html"; newFile.Size = fileContents.Length; newFile.FolderId = folder.FolderID; errorMessage = FileSystemUtils.CreateFileFromString(rootFolder, newFile.FileName, fileContents, newFile.ContentType, string.Empty, false); if (!(string.IsNullOrEmpty(errorMessage))) { ShowSaveTemplateMessage(errorMessage); return; } existingFile = fileCtrl.GetFile(newFileName, portalSettings.PortalId, folder.FolderID); if (newFile.FileId != existingFile.FileId) { newFile.FileId = existingFile.FileId; } if (newFile.FileId != Null.NullInteger) { fileCtrl.UpdateFile(newFile.FileId, newFile.FileName, newFile.Extension, newFile.Size, newFile.Width, newFile.Height, newFile.ContentType, folder.FolderPath, folder.FolderID); } else { fileCtrl.AddFile(portalSettings.PortalId, newFile.FileName, newFile.Extension, newFile.Size, newFile.Width, newFile.Height, newFile.ContentType, folder.FolderPath, folder.FolderID, true); } ShowSaveTemplateMessage(string.Empty); } catch (Exception ex) { DotNetNuke.Services.Exceptions.Exceptions.LogException(ex); throw ex; } }
/// <include file='Doc/Wrappers.xml' path='docs/method[@name="Open"]/*'/> public override PhpStream Open(ref string path, string mode, StreamOpenOptions options, StreamContext context) { Debug.Assert(path != null); //Debug.Assert(PhpPath.IsLocalFile(path)); // Get the File.Open modes from the mode string FileMode fileMode; FileAccess fileAccess; StreamAccessOptions ao; if (!ParseMode(mode, options, out fileMode, out fileAccess, out ao)) { return(null); } // Open the native stream FileStream stream = null; try { // stream = File.Open(path, fileMode, fileAccess, FileShare.ReadWrite); stream = new FileStream(path, fileMode, fileAccess, FileShare.ReadWrite | FileShare.Delete); } catch (FileNotFoundException) { // Note: There may still be an URL in the path here. PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_not_exists", FileSystemUtils.StripPassword(path))); return(null); } catch (IOException e) { if ((ao & StreamAccessOptions.Exclusive) > 0) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_exists", FileSystemUtils.StripPassword(path))); } else { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_io_error", FileSystemUtils.StripPassword(path), PhpException.ToErrorMessage(e.Message))); } return(null); } catch (UnauthorizedAccessException) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_access_denied", FileSystemUtils.StripPassword(path))); return(null); } catch (Exception) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_invalid", FileSystemUtils.StripPassword(path))); return(null); } if ((ao & StreamAccessOptions.SeekEnd) > 0) { // Read/Write Append is not supported. Seek to the end of file manually. stream.Seek(0, SeekOrigin.End); } if ((ao & StreamAccessOptions.Temporary) > 0) { // Set the file attributes to Temporary too. File.SetAttributes(path, FileAttributes.Temporary); } return(new NativeStream(stream, this, ao, path, context)); }
public void Init() { FileSystemUtils.FileDelete(fileName); FileSystemUtils.FileDelete(fileName + ".bak"); }
/// <summary> /// Performs all checks on a path passed to a PHP function. /// </summary> /// <remarks> /// <para> /// This method performs a check similar to <c>safe_mode.c: php_checkuid_ex()</c> /// together with <c>open_basedir</c> check. /// </para> /// <para> /// The <paramref name="filename"/> may be one of the following: /// <list type="bullet"> /// <item>A relative path. The path is resolved regarding the <c>include_path</c> too if required /// and checking continues as in the next case.</item> /// <item>An absolute path. The file or directory is checked for existence and for access permissions<sup>1</sup> /// according to the given <paramref name="mode"/>.</item> /// </list> /// <sup>1</sup> Regarding the <c>open_basedir</c> configuration option. /// File access permissions are checked at the time of file manipulation /// (opening, copying etc.). /// </para> /// </remarks> /// <param name="filename">A resolved path. Must be an absolute path to a local file.</param> /// <param name="mode">One of the <see cref="CheckAccessMode"/>.</param> /// <param name="options"><c>true</c> to suppress error messages.</param> /// <returns><c>true</c> if the function may continue with file access, /// <c>false</c>to fail.</returns> /// <exception cref="PhpException">If the file can not be accessed /// and the <see cref="CheckAccessOptions.Quiet"/> is not set.</exception> public static bool CheckAccess(string filename, CheckAccessMode mode, CheckAccessOptions options) { Debug.Assert(Path.IsPathRooted(filename)); string url = FileSystemUtils.StripPassword(filename); bool quiet = (options & CheckAccessOptions.Quiet) > 0; switch (mode) { case CheckAccessMode.FileMayExist: break; case CheckAccessMode.FileExists: if (!File.Exists(filename)) { if (!quiet) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_not_exists", url)); } return(false); } break; case CheckAccessMode.FileNotExists: if (File.Exists(filename)) { if (!quiet) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_exists", url)); } return(false); } break; case CheckAccessMode.FileOrDirectory: if ((!Directory.Exists(filename)) && (!File.Exists(filename))) { if (!quiet) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_path_not_exists", url)); } return(false); } break; case CheckAccessMode.Directory: if (!Directory.Exists(filename)) { if (!quiet) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_directory_not_exists", url)); } return(false); } break; default: Debug.Assert(false); return(false); } return(true); }
public void SplitPathSeparator_PathGiven_PathSplit(string path) { string[] splitPath = FileSystemUtils.SplitPathSeparator(path); Assert.Equal(new[] { "some", "test", "path" }, splitPath); }
private string ExportModule(int moduleID, string fileName, string folder) { var strMessage = ""; if (Module != null) { if (!String.IsNullOrEmpty(Module.DesktopModule.BusinessControllerClass) && Module.DesktopModule.IsPortable) { try { var objObject = Reflection.CreateObject(Module.DesktopModule.BusinessControllerClass, Module.DesktopModule.BusinessControllerClass); //Double-check if (objObject is IPortable) { var content = Convert.ToString(((IPortable)objObject).ExportModule(moduleID)); if (!String.IsNullOrEmpty(content)) { //add attributes to XML document content = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<content type=\"" + CleanName(Module.DesktopModule.ModuleName) + "\" version=\"" + Module.DesktopModule.Version + "\">" + content + "</content>"; //First check the Portal limits will not be exceeded (this is approximate) var objPortalController = new PortalController(); var strFile = PortalSettings.HomeDirectoryMapPath + folder + fileName; if (objPortalController.HasSpaceAvailable(PortalId, content.Length)) { //save the file var objStream = File.CreateText(strFile); objStream.WriteLine(content); objStream.Close(); //add file to Files table #pragma warning disable 612,618 FileSystemUtils.AddFile(fileName, PortalId, folder, PortalSettings.HomeDirectoryMapPath, "application/octet-stream"); #pragma warning restore 612,618 } else { strMessage += "<br>" + string.Format(Localization.GetString("DiskSpaceExceeded"), strFile); } } else { strMessage = Localization.GetString("NoContent", LocalResourceFile); } } else { strMessage = Localization.GetString("ExportNotSupported", LocalResourceFile); } } catch { strMessage = Localization.GetString("Error", LocalResourceFile); } } else { strMessage = Localization.GetString("ExportNotSupported", LocalResourceFile); } } return(strMessage); }
private async void Window_Loaded(object sender, RoutedEventArgs e) { if ((bool)SettingsInstance["ShowPlaylistEditorOnStartup"].Value) { InstanceManager.Instance.PlaylistEditorInstance.Show(); } // Set the initial scrolling animation SetTextScrollingAnimation(MainLabel.Text); // Init PluginWidget PlWidget = new PluginsWidget(this, PluginsButton, Widget.WidgetRelativePosition.Above, Widget.WidgetAlignment.Center, false, true); // Load plugin GUIs: foreach (var p in InstanceManager.Instance.LoadedExtensions) { p.Instance.InitGui(); } // Debug //MessageBox.Show("Actual size: " + playButtonImage.ActualHeight + "*" + playButtonImage.ActualWidth); // Open the file specified in CLArgs. If failed, open the autoload playlist if enabled if (!FileSystemUtils.LoadFileFromClArgs() && (bool)SettingsInstance["LoadPlaylistOnStartup"].Value) { var f = (string)SettingsInstance["PlaylistToAutoLoad"].Value; if (File.Exists(f)) { PlaybackManagerInstance.Playlist.AddRange(f, FileSystemUtils.DefaultLoadErrorCallback); } else { MessageBox.Show("File not found: " + f, "Non-critical error, everything is ok!", MessageBoxButton.OK, MessageBoxImage.Asterisk); } } try { // Update Checking if (!(bool)SettingsInstance["CheckForUpdates"].Value) { return; } var upd = await UpdateCheck.CheckForUpdate(); if (upd == "") { return; } var result = MessageBox.Show("A new version of Sky Jukebox is available! Download the update now?", "Update Checker", MessageBoxButton.YesNo, MessageBoxImage.Information); if (result == MessageBoxResult.Yes) { Process.Start("https://github.com/OronDF343/Sky-Jukebox/releases"); } } catch (Exception ex) { Console.WriteLine(ex); } }
public void ProcessRequest(HttpContext context) { context.Response.Clear(); context.Response.ContentType = "text/html"; context.Response.Write(FileSystemUtils.ReadFile(context.Request.PhysicalPath)); }
/// <summary> /// Open a ZIP file archive. /// </summary> /// <param name="ctx">Current runtime context.</param> /// <param name="filename">The file name of the ZIP archive to open.</param> /// <param name="flags">The mode to use to open the archive.</param> /// <returns>TRUE on success or the error code.</returns> public PhpValue open(Context ctx, string filename, int flags = 0) { if ((flags & CHECKCONS) != 0) { PhpException.ArgumentValueNotSupported(nameof(flags), nameof(CHECKCONS)); } if (_archive != null) { // Save the changes to the current archive before opening another one _archive.Dispose(); _archive = null; } try { string fullPath = FileSystemUtils.AbsolutePath(ctx, filename); FileMode mode; if (File.Exists(fullPath)) { if ((flags & EXCL) != 0) { PhpException.Throw(PhpError.Warning, Resources.Resources.file_exists, fullPath); return(ER_EXISTS); } else if ((flags & OVERWRITE) != 0) { mode = FileMode.Truncate; } else { mode = FileMode.Open; } } else { if ((flags & CREATE) != 0) { mode = FileMode.Create; } else { PhpException.Throw(PhpError.Warning, Resources.Resources.file_not_exists, fullPath); return(ER_NOENT); } } var fileStream = File.Open(fullPath, mode); _archive = new System.IO.Compression.ZipArchive(fileStream, ZipArchiveMode.Update); this.filename = fullPath; return(true); } catch (IOException e) { PhpException.Throw(PhpError.Warning, e.Message); return(ER_OPEN); } catch (InvalidDataException e) { PhpException.Throw(PhpError.Warning, e.Message); return(ER_INCONS); } catch (System.Exception e) { PhpException.Throw(PhpError.Warning, e.Message); return(ER_INTERNAL); } }
public void CanExpandPathVariablesConstantPath() { const string path = @"c:\x\y\z.txt"; Assert.AreEqual(path, FileSystemUtils.ExpandPathVariables(path)); }
public void CanExpandPathVariablesEmptyPath() { Assert.AreEqual(string.Empty, FileSystemUtils.ExpandPathVariables(string.Empty)); }
public void Initialize(Cockpit cockpit, float fCockpitRadius) { activeCockpit = cockpit; activeCockpit.PositionMode = Cockpit.MovementMode.Static; activeCockpit.GrabFocus = true; activeHUDRadius = fCockpitRadius; string[] files, folders; try { files = Source.GetFiles(FolderPath); folders = Source.GetFolders(FolderPath); } catch (Exception e) { Debug.Log("[CurrentFolderList.Initialize] exception! " + e.Message); return; } float fMinHorz = -45.0f, fMaxHorz = 45.0f; float fStartVert = 15.0f; float fTop = HUDUtil.GetSphereFrame(fCockpitRadius, 0.0f, fStartVert).Origin.y; int folderi = 0, filei = 0; Mesh folderMesh = Resources.Load <Mesh>("icon_meshes/folder_v1"); Color folderColor = ColorUtil.make(241, 213, 146); Color inaccessibleFolderColor = ColorUtil.make(100, 100, 100); Mesh fileMesh = Resources.Load <Mesh>("icon_meshes/file_v1"); Color fileColor = ColorUtil.make(250, 250, 250); // [TODO] something wrong here, icons are loading backwards...?? Quaternion meshRotation = Quaternion.AngleAxis(270.0f, Vector3.right) * Quaternion.AngleAxis(180.0f + 25.0f, Vector3.forward); float meshScale = IconSize * 0.9f; HUDCylinder hudSurf = new HUDCylinder() { Radius = fCockpitRadius, VerticalCoordIsAngle = false }; float fStepH = VRUtil.HorizontalStepAngle(fCockpitRadius, 0, IconSize + IconPadding); int nStepsHorz = (int)((fMaxHorz - fMinHorz) / fStepH); fMinHorz = -(nStepsHorz * fStepH * 0.5f); fMaxHorz = (nStepsHorz * fStepH * 0.5f); float fStepV = IconSize + IconPadding; IconCollection = new HUDCollection(); IconCollection.Create(); bool bDone = false; int yi = 0; while (!bDone) { float fCurV = fTop - yi * fStepV; yi++; for (int xi = 0; xi < nStepsHorz && bDone == false; ++xi) { float fCurH = fMinHorz + ((float)xi + 0.5f) * fStepH; string name = "x"; fMesh useMesh = null; Color useColor = Color.white; bool bAccessible = true; bool bIsFile = false; if (folderi < folders.Length) { name = folders[folderi++]; useMesh = new fMesh(UnityEngine.Object.Instantiate <Mesh>(folderMesh)); useColor = folderColor; if (Source.FilterInaccessibleFolders == false && FileSystemUtils.CanAccessFolder(Path.Combine(FolderPath, name)) == false) { bAccessible = false; useColor = inaccessibleFolderColor; } } else if (filei < files.Length) { name = files[filei++]; useMesh = new fMesh(UnityEngine.Object.Instantiate <Mesh>(fileMesh)); useColor = fileColor; bIsFile = true; } else { bDone = true; break; } //useColor.a = 0.999f; // [RMS] can use this to force into alpha pass string displayName = name; if (displayName.Length > 12) { displayName = name.Substring(0, 12) + "..."; } //float TextScale = 0.01f, ShiftX = -IconSize * 0.5f; float TextScale = 0.005f, ShiftX = -IconSize * 0.5f; HUDButton iconButton = HUDBuilder.CreateMeshClickButton( useMesh, useColor, meshScale, meshRotation, hudSurf, fCurH, fCurV, new TextLabelGenerator() { Text = displayName, Scale = TextScale, Translate = new Vector3(ShiftX, 0.0f, 0.0f) }); iconButton.Name = name; //cockpit.AddUIElement(iconButton, true); IconCollection.AddChild(iconButton); if (bIsFile) { iconButton.OnClicked += (o, e) => { if (this.OnFileClicked != null) { this.OnFileClicked(name); } }; } if (bAccessible) { iconButton.OnDoubleClicked += IconButton_DoubleClick; } } } cockpit.AddUIElement(IconCollection, true); fCurMaxScroll = Mathf.Max(0, (yi - 4) * fStepV); }
public void DirectoryExists() { Assert.IsTrue(FileSystemUtils.DirectoryExists(m_Folder2)); }
private void CopyDriverToSetupDriverDirectoryAndRegisterIt(PNPDriverINFFile pnpDriverInf) { Console.WriteLine(); Console.WriteLine("Making the driver available to GUI mode setup."); // build list of source files: var driverFiles = new List <string>(); foreach (var fileToCopy in DriverFilesToCopy) { DisableInBoxDeviceDriverFile(_installation.SetupDirectory, fileToCopy.DestinationFileName); driverFiles.Add(fileToCopy.RelativeSourceFilePath); } // make sure the .inf file will be copied too driverFiles.Add(pnpDriverInf.FileName); if (pnpDriverInf.CatalogFile != string.Empty) { if (File.Exists(DriverDirectory.Path + pnpDriverInf.CatalogFile)) { // add the catalog file too (to suppress unsigned driver warning message if the .inf has not been modified) // the catalog file is in the same location as the INF file ( http://msdn.microsoft.com/en-us/library/windows/hardware/ff547502%28v=vs.85%29.aspx ) driverFiles.Add(pnpDriverInf.CatalogFile); } } // Note that we may perform some operations on the same directory more than once, // the allocate / register methods are supposed to return the previously allocated IDs on subsequent calls, // and skip registration of previously registered directories foreach (var relativeFilePath in driverFiles) { var fileName = FileSystemUtils.GetNameFromPath(relativeFilePath); var relativeDirectoryPath = relativeFilePath.Substring(0, relativeFilePath.Length - fileName.Length); // we need to copy the files to the proper sub-directories var sourceDir = DriverDirectory.Path + relativeDirectoryPath; var pathParts = sourceDir.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); var destinationDir = pnpDriverInf.ClassName + '\\' + pathParts[pathParts.Length - 1] + relativeDirectoryPath + Path.DirectorySeparatorChar; _installation.CopyFileToSetupDriverDirectory(sourceDir + fileName, destinationDir, fileName); var sourceDirectoryInMediaRootForm = _installation.GetSourceDriverDirectoryInMediaRootForm(HardwareID + @"\" + relativeDirectoryPath); // note that we may violate ISO9660 - & is not allowed var sourceDiskID = _installation.TextSetupInf.AllocateSourceDiskID(_installation.ArchitectureIdentifier, sourceDirectoryInMediaRootForm); var destinationWinntDirectory = _installation.GetDriverDestinationWinntDirectory(HardwareID + @"\" + relativeDirectoryPath); var destinationWinntDirectoryID = _installation.TextSetupInf.AllocateWinntDirectoryID(destinationWinntDirectory); _installation.TextSetupInf.SetSourceDisksFileEntry(_installation.ArchitectureIdentifier, sourceDiskID, destinationWinntDirectoryID, fileName, FileCopyDisposition.AlwaysCopy); // dosnet.inf: we add the file to the list of files to be copied to local source directory if (!_installation.IsTargetContainsTemporaryInstallation) { _installation.DOSNetInf.InstructSetupToCopyFileFromSetupDirectoryToLocalSourceDriverDirectory( sourceDirectoryInMediaRootForm, fileName); } _installation.HiveSoftwareInf.RegisterDriverDirectory(destinationWinntDirectory); if (_installation.Is64Bit) { // hivsft32.inf _installation.HiveSoftware32Inf.RegisterDriverDirectory(destinationWinntDirectory); } } // set inf to boot start: { var sourceDir = DriverDirectory.Path; var pathParts = sourceDir.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); var destinationDir = pnpDriverInf.ClassName + '\\' + pathParts[pathParts.Length - 1]; var setupDriverDirectoryPath = _installation.GetSetupDriverDirectoryPath(destinationDir + Path.DirectorySeparatorChar); var installSectionName = pnpDriverInf.GetDeviceInstallSectionName(HardwareID, _installation.ArchitectureIdentifier, _installation.MinorOSVersion, _installation.ProductType); pnpDriverInf.SetServiceToBootStart(installSectionName, _installation.ArchitectureIdentifier, _installation.MinorOSVersion); pnpDriverInf.SaveToDirectory(setupDriverDirectoryPath); // finished setting inf to boot start } }
public void GetAbsolutePath() { Assert.AreEqual(m_FileName2, FileSystemUtils.GetAbsolutePath(m_FileName2, null)); }
public void GetPathDiff_Test(string pathFrom, string pathTo, string expectedResult) { string actualResult = FileSystemUtils.GetPathDiff(pathFrom, pathTo); Assert.Equal(expectedResult, actualResult); }
public void GetDirectoryName() { Assert.AreEqual(m_Folder1, FileSystemUtils.GetDirectoryName(m_FileName1)); Assert.AreEqual(m_Folder2, FileSystemUtils.GetDirectoryName(m_FileName2)); }
/// <summary> /// Merges the path with the current working directory /// to get a canonicalized absolute pathname representing the same file. /// </summary> /// <remarks> /// This method is an analogy of <c>main/safe_mode.c: php_checkuid</c>. /// Looks for the file in the <c>include_path</c> and checks for <c>open_basedir</c> restrictions. /// </remarks> /// <param name="path">An absolute or relative path to a file.</param> /// <param name="wrapper">The wrapper found for the specified file or <c>null</c> if the path resolution fails.</param> /// <param name="mode">The checking mode of the <see cref="CheckAccess"/> method (file, directory etc.).</param> /// <param name="options">Additional options for the <see cref="CheckAccess"/> method.</param> /// <returns><c>true</c> if all the resolution and checking passed without an error, <b>false</b> otherwise.</returns> /// <exception cref="PhpException">Security violation - when the target file /// lays outside the tree defined by <c>open_basedir</c> configuration option.</exception> public static bool ResolvePath(ref string path, out StreamWrapper wrapper, CheckAccessMode mode, CheckAccessOptions options) { // Path will contain the absolute path without file:// or the complete URL; filename is the relative path. string filename, scheme = GetSchemeInternal(path, out filename); wrapper = StreamWrapper.GetWrapper(scheme, (StreamOptions)options); if (wrapper == null) { return(false); } if (wrapper.IsUrl) { // Note: path contains the whole URL, filename the same without the scheme:// portion. // What to check more? } else if (scheme != "php") { try { // Filename contains the original path without the scheme:// portion, check for include path. bool isInclude = false; if ((options & CheckAccessOptions.UseIncludePath) > 0) { isInclude = CheckIncludePath(filename, ref path); } // Path will now contain an absolute path (either to an include or actual directory). if (!isInclude) { path = Path.GetFullPath(Path.Combine(ScriptContext.CurrentContext.WorkingDirectory, filename)); } } catch (Exception) { if ((options & CheckAccessOptions.Quiet) == 0) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_filename_invalid", FileSystemUtils.StripPassword(path))); } return(false); } GlobalConfiguration global_config = Configuration.Global; // Note: extensions check open_basedir too -> double check.. if (!global_config.SafeMode.IsPathAllowed(path)) { if ((options & CheckAccessOptions.Quiet) == 0) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("open_basedir_effect", path, global_config.SafeMode.GetAllowedPathPrefixesJoin())); } return(false); } // Replace all '/' with '\'. // path = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); Debug.Assert( path.IndexOf(Path.AltDirectorySeparatorChar) == -1 || (Path.AltDirectorySeparatorChar == Path.DirectorySeparatorChar), // on Mono, so ignore it string.Format("'{0}' should not contain '{1}' char.", path, Path.AltDirectorySeparatorChar)); // The file wrapper expects an absolute path w/o the scheme, others expect the scheme://url. if (scheme != "file") { path = String.Format("{0}://{1}", scheme, path); } } return(true); }
/// <summary> /// Opens a new SocketStream /// </summary> internal static SocketStream Connect(Context ctx, string remoteSocket, int port, out int errno, out string errstr, double timeout, SocketOptions flags, StreamContext /*!*/ context) { errno = 0; errstr = null; if (remoteSocket == null) { PhpException.ArgumentNull(nameof(remoteSocket)); return(null); } bool isSsl = false; // TODO: extract schema (tcp://, udp://) and port from remoteSocket // Uri uri = Uri.TryCreate(remoteSocket); const string protoSeparator = "://"; var protocol = ProtocolType.Tcp; var protoIdx = remoteSocket.IndexOf(protoSeparator, StringComparison.Ordinal); if (protoIdx >= 0) { var protoStr = remoteSocket.AsSpan(0, protoIdx); if (protoStr.Equals("udp".AsSpan(), StringComparison.Ordinal)) { protocol = ProtocolType.Udp; } else if (protoStr.Equals("ssl".AsSpan(), StringComparison.Ordinal)) { // use SSL encryption isSsl = true; } remoteSocket = remoteSocket.Substring(protoIdx + protoSeparator.Length); } var colonIdx = remoteSocket.IndexOf(':'); if (colonIdx >= 0) { var portStr = remoteSocket.AsSpan(colonIdx + 1); if (portStr.Length != 0 && int.TryParse(portStr.ToString(), out var n) && // TODO: (perf) ReadOnlySpan<char> n > 0 && n <= 0xffff) { port = n; } remoteSocket = remoteSocket.Remove(colonIdx); } if (double.IsNaN(timeout)) { timeout = ctx.Configuration.Core.DefaultSocketTimeout; } // TODO: if (flags != SocketOptions.None && flags != SocketOptions.Asynchronous) { PhpException.ArgumentValueNotSupported("flags", (int)flags); } var connect_async = (flags & SocketOptions.Asynchronous) != 0; try { // workitem 299181; for remoteSocket as IPv4 address it results in IPv6 address //IPAddress address = System.Net.Dns.GetHostEntry(remoteSocket).AddressList[0]; if (!IPAddress.TryParse(remoteSocket, out var address)) // if remoteSocket is not a valid IP address then lookup the DNS { var addresses = System.Net.Dns.GetHostAddressesAsync(remoteSocket).Result; if (addresses != null && addresses.Length != 0) { address = addresses[0]; } else { throw new ArgumentException(nameof(remoteSocket)); } } var socket = new Socket(address.AddressFamily, SocketType.Stream, protocol); // socket.Connect(new IPEndPoint(address, port)); if (socket.ConnectAsync(address, port).Wait((int)(timeout * 1000))) { SslStream sslstream; if (isSsl) { var crypto_method = default(CryptoMethod); var options = context.GetOptions("ssl"); if (options != null) { // TODO: provide parameters based on context[ssl][verify_peer|verify_peer_name|allow_self_signed|cafile] options.TryGetValue("verify_peer", out var vpvalue); options.TryGetValue("verify_peer_name", out var vpnvalue); options.TryGetValue("allow_self_signed", out var assvalue); options.TryGetValue("cafile", out var cafilevalue); options.TryGetValue("crypto_method", out var crypto_method_value); Debug.WriteLineIf(Operators.IsSet(vpvalue) && !vpvalue, "ssl: verify_peer not supported"); Debug.WriteLineIf(Operators.IsSet(vpnvalue) && (bool)vpnvalue, "ssl: verify_peer_name not supported"); Debug.WriteLineIf(Operators.IsSet(assvalue) && !assvalue, "ssl: allow_self_signed not supported"); Debug.WriteLineIf(Operators.IsSet(cafilevalue), "ssl: cafile not supported"); crypto_method = (CryptoMethod)crypto_method_value.ToLong(); } sslstream = OpenSslStream(socket, remoteSocket, crypto_method); // stream_socket_* functions work with "SocketStream" object //return new NativeStream(ctx, sslstream, null, StreamAccessOptions.Read | StreamAccessOptions.Write, remoteSocket, context) //{ // IsWriteBuffered = false, // IsReadBuffered = false, //}; } else { sslstream = null; } // return(new SocketStream(ctx, socket, remoteSocket, context) { SslStream = sslstream, }); } else { Debug.Assert(!socket.Connected); PhpException.Throw(PhpError.Warning, string.Format(Resources.LibResources.socket_open_timeout, FileSystemUtils.StripPassword(remoteSocket))); return(null); } } catch (SocketException e) { errno = (int)e.SocketErrorCode; errstr = e.Message; } catch (System.Exception e) { errno = -1; errstr = e.Message; } PhpException.Throw(PhpError.Warning, string.Format(Resources.LibResources.socket_open_error, FileSystemUtils.StripPassword(remoteSocket), errstr)); return(null); }
/// <include file='Doc/Wrappers.xml' path='docs/method[@name="Rename"]/*'/> public override bool Rename(string fromPath, string toPath, StreamRenameOptions options, StreamContext context) { try { File.Move(fromPath, toPath); return(true); } catch (UnauthorizedAccessException) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_access_denied", FileSystemUtils.StripPassword(fromPath))); } catch (IOException) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_rename_file_exists", FileSystemUtils.StripPassword(fromPath), FileSystemUtils.StripPassword(toPath))); } catch (Exception e) { PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_error", FileSystemUtils.StripPassword(fromPath), e.Message)); } return(false); }
private void TrainNetwork() //when training dataset created we start the training by, again, calling DeepLabCut's function { Console.WriteLine("TRAIN NETWROK"); bool errorDuringTraining = false; string errorMessage = "No Error"; string filePath = EnvDirectory + "\\vdlc_train_network.py"; FileSystemUtils.MurderPython(); FileSystemUtils.RenewScript(filePath, AllScripts.TrainNetwork); FileSystemUtils.ReplaceStringInFile(filePath, "config_path_identifier", CurrentProject.ConfigPath); Process p = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = "cmd.exe"; info.RedirectStandardInput = true; info.RedirectStandardOutput = !ReadShowDebugConsole(); //when we want to show debug console, we don't want to redirect output info.UseShellExecute = false; info.Verb = "runas"; info.CreateNoWindow = !ReadShowDebugConsole(); //if show debug console = true, then create no window has to be false this.Dispatcher.Invoke(() => { LoadingWindow = new LoadingWindow(); //show a loading window during training that takes cmd's output (DeepLabCut's train_network function generated output) so the user knows how far along they are LoadingWindow.Title = "Training"; LoadingWindow.Show(); LoadingWindow.Closed += LoadingClosed; LoadingWindow.ProgressBar.Maximum = int.Parse(CurrentProject.EndIters); }); //NONDEBUG ----------------------------------------------------------------------------------------------- if (info.CreateNoWindow) //if not in debug mode { int currentIter = 0; StringBuilder output = new StringBuilder(); p.OutputDataReceived += new DataReceivedEventHandler((sender, e) => { if (!String.IsNullOrEmpty(e.Data)) { string line = e.Data; //Console.WriteLine(line); if (line.Contains("OOM")) { errorMessage = "Training failed due to insufficient GPU memory. Try setting \"Global Scale\" to a lower value, and/or reducing training videos' resolution during import."; errorDuringTraining = true; FileSystemUtils.MurderPython(); } if (line.Contains("iteration:") && line.Contains("loss:")) //extracting the current iterations information from cmd's output { currentIter = currentIter + int.Parse(CurrentProject.DisplayIters); this.Dispatcher.Invoke(() => { string currentIters = line.Substring(line.IndexOf("n:") + 3, line.IndexOf("lo") - line.IndexOf("n:") - 4); string progressInfo = currentIters + " / " + CurrentProject.EndIters + " iterations"; LoadingWindow.ProgressLabel.Content = progressInfo; LoadingWindow.ProgressBar.Value = currentIter; }); } } }); } //NONDEBUG ----------------------------------------------------------------------------------------------- p.EnableRaisingEvents = true; p.Exited += (sender1, e1) => { if (errorDuringTraining) { this.Dispatcher.Invoke(() => { LoadingWindow.Close(); EnableInteraction(); }); UpdateVGLConfig(); //update VDLC's config file MessageBox.Show(errorMessage, "Error Occurred", MessageBoxButton.OK, MessageBoxImage.Error); } else { globalStopWatch.Stop(); TimeSpan ts = globalStopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); this.Dispatcher.Invoke(() => { LoadingWindow.Close(); }); CurrentProject.TrainedWith = new List <string>(); foreach (TrainingVideo current in TrainingListBox.ItemsSource) { CurrentProject.TrainedWith.Add(current.Path); } UpdateVGLConfig(); //update VDLC's config file DeleteEvalFiles(); //overwrite eval files EvalNetwork(elapsedTime); } }; p.StartInfo = info; p.Start(); globalStopWatch = new Stopwatch(); globalStopWatch.Start(); //time the training period using ( StreamWriter sw = p.StandardInput) { if (sw.BaseStream.CanWrite) { sw.WriteLine(Drive); sw.WriteLine("cd " + EnvDirectory); sw.WriteLine(FileSystemUtils.CONDA_ACTIVATE_PATH); sw.WriteLine("conda activate " + EnvName); sw.WriteLine("ipython vdlc_train_network.py"); if (info.CreateNoWindow == false) //for debug purposes { sw.WriteLine("ECHO WHEN YOU'RE DONE, CLOSE THIS WINDOW"); p.WaitForExit(); sw.WriteLine("Done, exiting."); } } } if (info.CreateNoWindow) { p.BeginOutputReadLine(); } }
public override void ImportData(ExportImportJob importJob, ImportDto importDto) { if (CheckCancelled(importJob)) { return; } //Skip the export if all the templates have been processed already. if (CheckPoint.Stage >= 1 || CheckPoint.Completed) { return; } _exportImportJob = importJob; var packageZipFile = $"{Globals.ApplicationMapPath}{Constants.ExportFolder}{_exportImportJob.Directory.TrimEnd('\\', '/')}\\{Constants.ExportZipThemes}"; var tempFolder = $"{Path.GetDirectoryName(packageZipFile)}\\{DateTime.Now.Ticks}"; if (File.Exists(packageZipFile)) { CompressionUtil.UnZipArchive(packageZipFile, tempFolder); var exporeFiles = Directory.Exists(tempFolder) ? Directory.GetFiles(tempFolder, "*.*", SearchOption.AllDirectories) : new string[0]; var portalSettings = new PortalSettings(importDto.PortalId); _importCount = exporeFiles.Length; CheckPoint.TotalItems = CheckPoint.TotalItems <= 0 ? exporeFiles.Length : CheckPoint.TotalItems; if (CheckPointStageCallback(this)) { return; } if (CheckPoint.Stage == 0) { try { foreach (var file in exporeFiles) { try { var checkFolder = file.Replace(tempFolder + "\\", string.Empty).Split('\\')[0]; var relativePath = file.Substring((tempFolder + "\\" + checkFolder + "\\").Length); string targetPath; if (checkFolder == "_default") { targetPath = Path.Combine(Globals.HostMapPath, relativePath); } else if (checkFolder.EndsWith("-System")) { targetPath = Path.Combine(portalSettings.HomeSystemDirectoryMapPath, relativePath); } else { targetPath = Path.Combine(portalSettings.HomeDirectoryMapPath, relativePath); } if (!File.Exists(targetPath) || importDto.CollisionResolution == CollisionResolution.Overwrite) { var directory = Path.GetDirectoryName(targetPath); if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) { Directory.CreateDirectory(directory); } File.Copy(file, targetPath, true); } Result.AddLogEntry("Import Theme File completed", targetPath); CheckPoint.ProcessedItems++; CheckPoint.Progress = CheckPoint.ProcessedItems * 100.0 / exporeFiles.Length; CheckPointStageCallback(this); // just to update the counts without exit logic } catch (Exception ex) { Result.AddLogEntry("Import Theme error", file); Logger.Error(ex); } } CheckPoint.Stage++; CheckPoint.Completed = true; } finally { CheckPointStageCallback(this); FileSystemUtils.DeleteFolderRecursive(tempFolder); } } } else { CheckPoint.Completed = true; CheckPointStageCallback(this); Result.AddLogEntry("ThemesFileNotFound", "Themes file not found. Skipping themes import", ReportLevel.Warn); } }
//MARK: Evaluation Methods private void EvalNetwork(string elapsedTime) //evaluate the newly trained network using DeepLabCut's evaluate_network function { BarInteraction(); string filePath = EnvDirectory + "\\vdlc_eval_network.py"; FileSystemUtils.MurderPython(); FileSystemUtils.RenewScript(filePath, AllScripts.EvalNetwork); FileSystemUtils.ReplaceStringInFile(filePath, "config_path_identifier", CurrentProject.ConfigPath); Process p = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = "cmd.exe"; info.RedirectStandardInput = true; info.UseShellExecute = false; info.Verb = "runas"; info.CreateNoWindow = !ReadShowDebugConsole(); //if show debug console = true, then create no window has to be false this.Dispatcher.Invoke(() => { LoadingWindow = new LoadingWindow(); LoadingWindow.Title = "Evaluating"; LoadingWindow.Show(); LoadingWindow.Closed += LoadingClosed; LoadingWindow.ProgressBar.Maximum = 100; LoadingWindow.ProgressBar.Value = 100; LoadingWindow.ProgressLabel.Content = "Just a sec..."; }); p.EnableRaisingEvents = true; p.Exited += (sender1, e1) => { CurrentProject.TrainTime = elapsedTime; GetEvalResultsSaveTime(ref CurrentProject); this.Dispatcher.Invoke(() => { LoadingWindow.Close(); EvalWindow evalWindow = new EvalWindow(CurrentProject.TrainTime, CurrentProject.TrainError, CurrentProject.TestError, CurrentProject.PCutoff); //once done evaluating, show a window with evaluation stats evalWindow.Show(); }); SyncUI(); EnableInteraction(); }; p.StartInfo = info; p.Start(); globalStopWatch = new Stopwatch(); globalStopWatch.Start(); using ( StreamWriter sw = p.StandardInput) { //run the evaluation script if (sw.BaseStream.CanWrite) { sw.WriteLine(Drive); sw.WriteLine("cd " + EnvDirectory); sw.WriteLine(FileSystemUtils.CONDA_ACTIVATE_PATH); sw.WriteLine("conda activate " + EnvName); sw.WriteLine("ipython vdlc_eval_network.py"); if (info.CreateNoWindow == false) //for debug purposes { sw.WriteLine("ECHO WHEN YOU'RE DONE, CLOSE THIS WINDOW"); p.WaitForExit(); sw.WriteLine("Done, exiting."); } } } }
public virtual void __construct(Context ctx, string file_name) { _fullpath = FileSystemUtils.AbsolutePath(ctx, file_name); }
//public static PhpArray stream_socket_pair(ProtocolFamily protocolFamily, SocketType type, ProtocolType protocol) //{ // PhpException.FunctionNotSupported(); // return null; //} #endregion #region Connect /// <summary> /// Opens a new SocketStream /// </summary> internal static SocketStream Connect(Context ctx, string remoteSocket, int port, out int errno, out string errstr, double timeout, SocketOptions flags, StreamContext /*!*/ context) { errno = 0; errstr = null; if (remoteSocket == null) { PhpException.ArgumentNull("remoteSocket"); return(null); } // TODO: extract schema (tcp://, udp://) and port from remoteSocket // Uri uri = Uri.TryCreate(remoteSocket); ProtocolType protocol = ProtocolType.Tcp; if (remoteSocket.Contains("://")) { String[] separator = { "://" }; String[] socketParts = remoteSocket.Split(separator, 2, StringSplitOptions.None); switch (socketParts[0]) { case "udp": protocol = ProtocolType.Udp; break; case "tcp": default: protocol = ProtocolType.Tcp; break; } remoteSocket = socketParts[1]; } if (remoteSocket.Contains(":")) { Char[] separator = { ':' }; String[] socketParts = remoteSocket.Split(separator, 2, StringSplitOptions.None); remoteSocket = socketParts[0]; int result = 0; if (socketParts[1] != "" && int.TryParse(socketParts[1], out result) && (0 < result && result < 65536)) { port = result; } } if (double.IsNaN(timeout)) { timeout = ctx.Configuration.Core.DefaultSocketTimeout; } // TODO: if (flags != SocketOptions.None && flags != SocketOptions.Asynchronous) { PhpException.ArgumentValueNotSupported("flags", (int)flags); } try { // workitem 299181; for remoteSocket as IPv4 address it results in IPv6 address //IPAddress address = System.Net.Dns.GetHostEntry(remoteSocket).AddressList[0]; IPAddress address; if (!IPAddress.TryParse(remoteSocket, out address)) // if remoteSocket is not a valid IP address then lookup the DNS { var addresses = System.Net.Dns.GetHostAddressesAsync(remoteSocket).Result; if (addresses != null && addresses.Length != 0) { address = addresses[0]; } else { throw new ArgumentException(nameof(remoteSocket)); } } var socket = new Socket(address.AddressFamily, SocketType.Stream, protocol); if (!socket.ConnectAsync(address, port).Wait((int)(timeout * 1000))) { Debug.Assert(!socket.Connected); PhpException.Throw(PhpError.Warning, string.Format(Resources.LibResources.socket_open_timeout, FileSystemUtils.StripPassword(remoteSocket))); return(null); } // socket.Connect(new IPEndPoint(address, port)); return(new SocketStream(ctx, socket, remoteSocket, context, (flags & SocketOptions.Asynchronous) == SocketOptions.Asynchronous)); } catch (SocketException e) { errno = (int)e.SocketErrorCode; errstr = e.Message; } catch (System.Exception e) { errno = -1; errstr = e.Message; } PhpException.Throw(PhpError.Warning, string.Format(Resources.LibResources.socket_open_error, FileSystemUtils.StripPassword(remoteSocket), errstr)); return(null); }
/// <Summary> /// This handler handles requests for LinkClick.aspx, but only those specifc /// to file serving /// </Summary> /// <Param name="context">System.Web.HttpContext)</Param> public virtual void ProcessRequest(HttpContext context) { PortalSettings portalSettings = PortalController.GetCurrentPortalSettings(); // get TabId int tabId = -1; if (context.Request.QueryString["tabid"] != null) { tabId = int.Parse(context.Request.QueryString["tabid"]); } // get ModuleId int moduleId = -1; if (context.Request.QueryString["mid"] != null) { moduleId = int.Parse(context.Request.QueryString["mid"]); } // get the URL string URL = ""; bool blnClientCache = true; bool blnForceDownload = false; if (context.Request.QueryString["fileticket"] != null) { URL = "FileID=" + UrlUtils.DecryptParameter(context.Request.QueryString["fileticket"]); } if (context.Request.QueryString["userticket"] != null) { URL = "UserId=" + UrlUtils.DecryptParameter(context.Request.QueryString["userticket"]); } if (context.Request.QueryString["link"] != null) { URL = context.Request.QueryString["link"]; if (URL.ToLower().StartsWith("fileid=")) { URL = ""; // restrict direct access by FileID } } if (!String.IsNullOrEmpty(URL)) { TabType UrlType = Globals.GetURLType(URL); if (UrlType != TabType.File) { URL = Globals.LinkClick(URL, tabId, moduleId, false); } if (UrlType == TabType.File && URL.ToLower().StartsWith("fileid=") == false) { // to handle legacy scenarios before the introduction of the FileServerHandler FileController objFiles = new FileController(); URL = "FileID=" + objFiles.ConvertFilePathToFileId(URL, portalSettings.PortalId); } // get optional parameters if (context.Request.QueryString["clientcache"] != null) { blnClientCache = bool.Parse(context.Request.QueryString["clientcache"]); } if ((context.Request.QueryString["forcedownload"] != null) || (context.Request.QueryString["contenttype"] != null)) { blnForceDownload = bool.Parse(context.Request.QueryString["forcedownload"]); } // update clicks UrlController objUrls = new UrlController(); objUrls.UpdateUrlTracking(portalSettings.PortalId, URL, moduleId, -1); // clear the current response context.Response.Clear(); if (UrlType == TabType.File) { // serve the file if (tabId == Null.NullInteger) { if (!(FileSystemUtils.DownloadFile(portalSettings.PortalId, int.Parse(UrlUtils.GetParameterValue(URL)), blnClientCache, blnForceDownload))) { context.Response.Write(Services.Localization.Localization.GetString("FilePermission.Error")); } } else { if (!(FileSystemUtils.DownloadFile(portalSettings, int.Parse(UrlUtils.GetParameterValue(URL)), blnClientCache, blnForceDownload))) { context.Response.Write(Services.Localization.Localization.GetString("FilePermission.Error")); } } } else { // redirect to URL context.Response.Redirect(URL, true); } } }
public void CopyFileFromSetupDirectoryToBootDirectory(string fileName) { FileSystemUtils.ClearReadOnlyAttribute(BootDirectory + fileName); File.Copy(SetupDirectory + fileName, BootDirectory + fileName, true); }
/// <summary> /// Sets access and modification time of file. /// </summary> /// <remarks> /// Attempts to set the access and modification time of the file named by /// path to the value given by time. If the option time is not given, /// uses the present time. If the third option atime is present, the access /// time of the given path is set to the value of atime. Note that /// the access time is always modified, regardless of the number of parameters. /// If the file does not exist, it is created. /// </remarks> /// <param name="ctx">Runtime context.</param> /// <param name="path">The file to touch.</param> /// <param name="mtime">The new modification time.</param> /// <param name="atime">The desired access time.</param> /// <returns><c>true</c> on success, <c>false</c> on failure.</returns> public static bool touch(Context ctx, string path, int mtime = 0, int atime = 0) { // Create the file if it does not already exist (performs all checks). //PhpStream file = (PhpStream)Open(path, "ab"); //if (file == null) return false; StreamWrapper wrapper; if (!PhpStream.ResolvePath(ctx, ref path, out wrapper, CheckAccessMode.FileMayExist, CheckAccessOptions.Quiet)) { return(false); } if (!file_exists(ctx, path)) { // Open and close => create new. wrapper.Open(ctx, ref path, "wb", StreamOpenOptions.Empty, StreamContext.Default) ?.Dispose(); } var access_time = (atime > 0) ? DateTimeUtils.UnixTimeStampToUtc(atime) : System.DateTime.UtcNow; var modification_time = (mtime > 0) ? DateTimeUtils.UnixTimeStampToUtc(mtime) : System.DateTime.UtcNow; //access_time -= DateTimeUtils.GetDaylightTimeDifference(access_time, System.DateTime.UtcNow); //modification_time -= DateTimeUtils.GetDaylightTimeDifference(modification_time, System.DateTime.UtcNow); try { File.SetLastWriteTimeUtc(path, modification_time); File.SetLastAccessTimeUtc(path, access_time); // Clear the cached stat values clearstatcache(); return(true); } catch (UnauthorizedAccessException) { PhpException.Throw(PhpError.Warning, ErrResources.stream_file_access_denied, FileSystemUtils.StripPassword(path)); } catch (System.Exception e) { PhpException.Throw(PhpError.Warning, ErrResources.stream_error, FileSystemUtils.StripPassword(path), e.Message); } return(false); }
private void LoadAppConfig() { ObjectFactory.GetProvider<ILoggingProvider>().Debug("Loading App Config"); var fs = new FileSystemUtils(); var acp = ObjectFactory.GetProvider<IAppConfigProvider>(); var config = fs.LoadAppConfiguration(); acp.AppConfig = config ?? new AppConfig(); appConfig = acp.AppConfig; }