public void P_SetPassword() { string userPath = NewUser(); string password = "******"; try { SetProperty(userPath, "Password", password); DirectoryEntryInfo info = GetItem <DirectoryEntryInfo>(userPath); Assert.IsNotNull(info); string samName = GetProperty <String>(userPath, "SamAccountName"); Assert.AreEqual(info.Name, samName); using (DirectoryEntry entry = new DirectoryEntry(ForeignServerPath, samName, password)) { Assert.AreEqual("CN=" + info.Name, entry.Name); } } finally { RemoveItem(userPath); } }
internal static EntryInfoBase Parse(string info, string parentPath) { EntryInfoBase entry = null; //parse line Match match = EntryInfoBase.GetMatch(info); if (match == null)//failed { throw new ArgumentException(string.Format("Parsing error:{0}", info)); } else { //Parsing attribute string name = match.Groups["name"].Value; string permission = match.Groups["permission"].Value; //Parsing time DateTime time; try { time = DateTime.Parse(match.Groups["timestamp"].Value); } catch (Exception) { time = new DateTime(); } //Check is file or directory string dir = match.Groups["dir"].Value; if (!string.IsNullOrEmpty(dir) && dir != "-") { entry = new DirectoryEntryInfo(name, time, permission, parentPath); } else { long size = 0; try { size = Convert.ToInt64(match.Groups["size"].Value); } catch (Exception) { } //Parsing extension string extension = null; int i = name.LastIndexOf("."); if (i >= 0 && i < name.Length - 1) { extension = name.Substring(i + 1); } entry = new FileEntryInfo(name, time, size, extension, permission, parentPath); } } return(entry); }
/// <summary> /// Internal method that is used to generate the next Active file name. May delete the oldest file in order to reuse the name when appropriate. /// </summary> protected void GenerateNextActiveFile() { string formatStr = string.Empty; string dateTreeStr = string.Empty; string middleStr = string.Empty; DateTime dtNow = DateTime.Now; try { dateTreeStr = dtNow.ToString(config.DateTreeFormat).AddSuffixIfNeeded(@"\"); } catch { dateTreeStr = @"BadDateTreeFmt\"; } middleStr = Utils.Dates.CvtToString(ref dtNow, Utils.Dates.DateTimeFormat.ShortWithMSec); string name = "{0}{1}{2}".CheckedFormat(config.FileNamePrefix, middleStr, config.FileNameExtension.AddPrefixIfNeeded(".")); // generate the file's full path string fullDirPath = System.IO.Path.Combine(config.DirPath, dateTreeStr); string fullFilePath = System.IO.Path.Combine(fullDirPath, name); // check if the file is already known and if so attempt to delete it DirectoryEntryInfo fileEntryInfo = new DirectoryEntryInfo(fullFilePath); FileSystemInfo fileEntryFSI = fileEntryInfo.FileSystemInfo; if (fileEntryInfo.Exists) { // delete the file (failure means we cannot use this name...) double fileAgeInHours = fileEntryInfo.CreationAge.TotalHours; Int64 fileSize = fileEntryInfo.Length; logger.Trace.Emit("{0}: Attempting to delete prior file:'{1}' size:{2} age:{3} hours", Fcns.CurrentMethodName, fileEntryInfo.Name, fileSize, fileAgeInHours.ToString("f3")); try { fileEntryFSI.Delete(); logger.Debug.Emit("{0}: Deleted prior file:'{1}' size:{2} age:{3} hours", Fcns.CurrentMethodName, fileEntryInfo.Name, fileSize, fileAgeInHours.ToString("f3")); } catch (System.Exception ex) { logger.Error.Emit("{0}: failed to delete prior file:'{1}', error:'{2}'", Fcns.CurrentMethodName, fileEntryInfo.Name, ex.Message); return; } } // the name has been generated and if it existed, it has been deleted // create the entry, add it to the maps and set the active entry to refer to the new entry ActiveFileDirEntryInfo = fileEntryInfo; logger.Debug.Emit("GenerateNextActiveFile active file is now:'{0}'", ActiveFileDirEntryInfo.Name); }
public FtpClient(string host, string username, string password) { this._host = host; this._username = username; this._password = password; this.EnableSsl = false; this.KeepAlive = true; this._currentDirectory = new DirectoryEntryInfo("", new DateTime(), null, this._host); }
protected string NewGroup(string parent) { string path; using (DirectoryEntryInfo container = NewItem(parent, "group", out path)) { return(path); } }
protected string NewOrgUnit(string parent) { string path; using (DirectoryEntryInfo orgUnit = NewItem(parent, "organizationalUnit", out path)) { return(path); } }
protected string NewUser(string parent) { string path; using (DirectoryEntryInfo user = NewItem(parent, "user", out path)) { return(path); } }
protected DirectoryEntryInfo[] NewUsers(int count) { DirectoryEntryInfo[] users = new DirectoryEntryInfo[count]; for (int i = 0; i < count; i++) { users[i] = GetItem <DirectoryEntryInfo>(NewUser()); } return(users); }
/// <summary> /// Internal method used to track changes in the state of the active file. /// The forceUpdate parameter may be used to cause the information to be immediately refreshed rather than waiting for the config.advanceRules.TestPeriodInSec to elapse between refreshes (default behavior). /// </summary> protected void RefreshActiveFileDirIfNeeded(bool forceUpdate) { if (ActiveFileDirEntryInfo == null) { return; } DirectoryEntryInfo activeFileInfo = ActiveFileDirEntryInfo; bool wasExistingFile = activeFileInfo.IsExistingFile; Int64 oldSize = wasExistingFile ? activeFileInfo.Length : 0; double stateAge = activeFileInfo.QpcTimeStamp.Age.TotalSeconds; if (forceUpdate || !wasExistingFile || stateAge < 0.0 || stateAge >= config.AdvanceRules.testPeriodInSec) { activeFileInfo.Refresh(); } }
/// <summary>Returns true if the client should stop using the current file and should start using a new file in the directory</summary> public bool IsFileAdvanceNeeded(bool recheckActiveFileSizeNow) { if (!IsDirectoryUsable) { return(false); // if the directory is not usable then we do not need to advance (since we cannot ever advance) } DirectoryEntryInfo activeFileEntry = ActiveFileDirEntryInfo; FileSystemInfo activeFSI = activeFileEntry.FileSystemInfo; FileInfo activeFileInfo = activeFSI as FileInfo; RefreshActiveFileDirIfNeeded(recheckActiveFileSizeNow); if (activeFSI == null || activeFileEntry.IsDirectory) { return(true); // advance needed if entry's file system info is null or if it is a directory. } if (!activeFSI.Exists) { return(false); // advance is not needed if the entry represents a file that does not exist (yet). } return(config.AdvanceRules.IsFileAdvanceNeeded(activeFileInfo)); }
public void DeleteDirectory(DirectoryEntryInfo remoteDirectory) { this.DeleteDirectory(remoteDirectory.FullName); }
public void RenameDirectory(DirectoryEntryInfo remoteDirectory, string newName) { this.RenameDirectory(remoteDirectory.FullName, newName); }
public void Upload(string localFile, DirectoryEntryInfo remoteDirectory, Encoding encoding) { this.Upload(localFile, remoteDirectory.FullName, encoding); }
public void Upload(string[] localFiles, DirectoryEntryInfo remoteDirectory) { this.Upload(localFiles, remoteDirectory.FullName); }
private void TransferFiles(IFileOperationsExecuter sourceAgentHelper, char srcSeparator, string srcPath, DirectoryEntryInfo sourceDir, int targetServerId) { using (var targetAgent = BuildMasterAgent.Create(targetServerId)) { var fileOps = targetAgent.GetService <IFileOperationsExecuter>(); char targetSeparator = fileOps.DirectorySeparator; var tarPath = fileOps.GetLegacyWorkingDirectory( (IGenericBuildMasterContext)this.Context, this.TargetDirectory ); this.LogDebug("Full target directory: {0}", tarPath); fileOps.CreateDirectory(tarPath); this.LogDebug("Loading target file list..."); var targetDir = fileOps.GetDirectoryEntry( new GetDirectoryEntryCommand { Path = tarPath, IncludeRootPath = true, Recurse = true } ).Entry; this.LogDebug("Performing directory comparison..."); List <string> filesToCopy = new List <string>(), foldersToCopy = new List <string>(), filesToDelete = new List <string>(), foldersToDelete = new List <string>(); Util.Files.Comparison.CompareDirectories( sourceDir, targetDir, filesToCopy, foldersToCopy, filesToDelete, foldersToDelete); // Make sure target files and folders to delete are canonical paths for (int i = 0; i < filesToDelete.Count; i++) { filesToDelete[i] = filesToDelete[i].Replace(srcSeparator, targetSeparator); } for (int i = 0; i < foldersToDelete.Count; i++) { foldersToDelete[i] = foldersToDelete[i].Replace(srcSeparator, targetSeparator); } // Run Filters if (this.IncludeFileMasks.Length != 0 && !(this.IncludeFileMasks.Length == 1 && string.IsNullOrEmpty(this.IncludeFileMasks[0]))) { filesToCopy = new List <string>(Util.Files.Comparison .GetMatches(srcPath, filesToCopy.ToArray(), IncludeFileMasks)); foldersToCopy = new List <string>(Util.Files.Comparison .GetMatches(srcPath, foldersToCopy.ToArray(), IncludeFileMasks)); filesToDelete = new List <string>(Util.Files.Comparison .GetMatches(tarPath, filesToDelete.ToArray(), IncludeFileMasks)); foldersToDelete = new List <string>(Util.Files.Comparison .GetMatches(tarPath, foldersToDelete.ToArray(), IncludeFileMasks)); } if (this.DeleteTarget) { this.LogInformation("Deleting files and directories that are not present in the source directory..."); if (filesToDelete.Count == 0) { this.LogDebug("No files to delete in target directory."); } else { this.LogDebug("Deleting {0} files from target directory...", filesToDelete.Count); } foreach (string path in filesToDelete) { this.LogDebug("\t" + path.Substring(tarPath.Length)); } fileOps.DeleteFiles(filesToDelete.ToArray()); if (foldersToDelete.Count == 0) { this.LogDebug("No directories to delete in target directory."); } else { this.LogDebug("Deleting {0} directories from target directory...", foldersToDelete.Count); } foreach (string path in foldersToDelete) { this.LogDebug("\t" + path.Substring(tarPath.Length)); } fileOps.DeleteDirectories(foldersToDelete.ToArray()); } else { this.LogDebug("Files and directories not present in source directory will not be deleted from target directory."); } this.LogInformation("Creating missing directories in target directory..."); if (foldersToCopy.Count == 0) { this.LogDebug("No directories missing in target directory."); } else { this.LogDebug("Creating {0} directories in target directory...", foldersToCopy.Count); } foreach (string directoryToCopy in foldersToCopy) { string relativeTargetPath = directoryToCopy.Substring(srcPath.Length) .Replace(srcSeparator, targetSeparator); if (relativeTargetPath.StartsWith(targetSeparator.ToString())) { relativeTargetPath = relativeTargetPath.Substring(1); } this.LogDebug("\t" + relativeTargetPath); fileOps.CreateDirectory(fileOps.CombinePath(tarPath, relativeTargetPath)); } this.LogInformation("Copying or transferring modified files from source directory to target directory..."); if (filesToCopy.Count == 0) { this.LogDebug("No files to copy to the target directory."); } else { this.LogDebug("Copying {0} files to the target directory...", filesToCopy.Count); } // Build list of source and target files to copy. var sourceFilesToCopy = new List <string>(filesToCopy.Count); var destFilesToCreate = new List <string>(filesToCopy.Count); foreach (var fileToCopy in filesToCopy) { var relativeSourcePath = fileToCopy.Substring(srcPath.Length) .TrimStart(srcSeparator); sourceFilesToCopy.Add(relativeSourcePath); var relativeDestPath = relativeSourcePath.Replace(srcSeparator, targetSeparator); destFilesToCreate.Add(relativeDestPath); // These are copied in a batch, so can't get logged all at once. if (this.Context.SourceServerId == targetServerId) { this.LogDebug("Copying all files from: {0}", relativeDestPath); } } if (this.Context.SourceServerId == targetServerId) { this.LogDebug("Both source and target servers are the same, performing batch copy of files..."); fileOps.FileCopyBatch(srcPath, sourceFilesToCopy.ToArray(), tarPath, destFilesToCreate.ToArray(), true, true); } else { this.LogDebug("Transferring files from source server to target server..."); for (int i = 0; i < sourceFilesToCopy.Count; i++) { this.LogDebug("\t" + destFilesToCreate[i]); var fullSourcePath = CombinePath(srcPath, sourceFilesToCopy[i], srcSeparator); var fullTargetPath = CombinePath(tarPath, destFilesToCreate[i], targetSeparator); string targetDirectory = PathEx.GetDirectoryName(fullTargetPath); if (!string.IsNullOrEmpty(targetDirectory)) { try { fileOps.CreateDirectory(targetDirectory); } catch (Exception ex) { this.LogDebug("Could not create directory at \"{0}\"; error was: {1}", targetDirectory, ex.Message); } } Util.Files.TransferFile(sourceAgentHelper, fullSourcePath, fileOps, fullTargetPath); var lastModified = sourceAgentHelper.GetFileInfo(fullSourcePath).LastWriteTimeUtc; fileOps.SetLastWriteTime(fullTargetPath, lastModified); } } } }