/// <summary> /// Rename an entry in the cache. /// Entry must already be in the cache. /// </summary> internal void RenameEntry(string oldFullPath, ProjectRootElement projectRootElement) { lock (_locker) { ErrorUtilities.VerifyThrowArgumentLength(oldFullPath, "oldFullPath"); RenameEntryInternal(oldFullPath, projectRootElement); } }
/// <summary> /// Verifies that a name is valid for the name of an item, property, or piece of metadata. /// If it isn't, throws an ArgumentException indicating the invalid character. /// </summary> /// <remarks> /// Note that our restrictions are more stringent than the XML Standard's restrictions. /// </remarks> /// <throws>ArgumentException</throws> /// <param name="name">name to validate</param> internal static void VerifyThrowArgumentValidElementName(string name) { ErrorUtilities.VerifyThrowArgumentLength(name, nameof(name)); int firstInvalidCharLocation = LocateFirstInvalidElementNameCharacter(name); if (-1 != firstInvalidCharLocation) { ErrorUtilities.ThrowArgument("OM_NameInvalid", name, name[firstInvalidCharLocation]); } }
private static Uri CreateUriFromPath(string path) { ErrorUtilities.VerifyThrowArgumentLength(path, "path"); Uri result = null; if (!Uri.TryCreate(path, UriKind.Absolute, out result)) { result = new Uri(path, UriKind.Relative); } return(result); }
internal static string NormalizePath(string path) { ErrorUtilities.VerifyThrowArgumentLength(path, "path"); int errorCode = 0; int num2 = NativeMethodsShared.MAX_PATH; StringBuilder buffer = new StringBuilder(num2 + 1); int num3 = NativeMethodsShared.GetFullPathName(path, buffer.Capacity, buffer, IntPtr.Zero); errorCode = Marshal.GetLastWin32Error(); if (num3 > num2) { num2 = num3; buffer = new StringBuilder(num2 + 1); num3 = NativeMethodsShared.GetFullPathName(path, buffer.Capacity, buffer, IntPtr.Zero); errorCode = Marshal.GetLastWin32Error(); ErrorUtilities.VerifyThrow((num3 + 1) < buffer.Capacity, "Final buffer capacity should be sufficient for full path name and null terminator."); } if (num3 <= 0) { errorCode = -2147024896 | errorCode; Marshal.ThrowExceptionForHR(errorCode); return(null); } string message = buffer.ToString(); if (message.Length >= 260) { throw new PathTooLongException(message); } message = Path.Combine(message, string.Empty); if (message.StartsWith(@"\\", StringComparison.OrdinalIgnoreCase)) { int num4 = 2; while (num4 < message.Length) { char ch = message[num4]; if (ch.Equals('\\')) { num4++; break; } num4++; } if ((num4 == message.Length) || (message.IndexOf(@"\\?\globalroot", StringComparison.OrdinalIgnoreCase) != -1)) { message = Path.GetFullPath(message); } } if (string.Equals(message, path, StringComparison.Ordinal)) { message = path; } return(message); }
/// <summary> /// Creates a new property /// </summary> /// <param name="name">The property name</param> /// <param name="value">The property value</param> /// <param name="source">The property source</param> public ToolsetPropertyDefinition(string name, string value, IElementLocation source) { ErrorUtilities.VerifyThrowArgumentLength(name, "name"); ErrorUtilities.VerifyThrowArgumentNull(source, "source"); // value can be the empty string but not null ErrorUtilities.VerifyThrowArgumentNull(value, "value"); _name = name; _value = value; _source = source; }
/// <summary> /// Helper function to create an Uri object from path. /// </summary> /// <param name="path">path string</param> /// <returns>uri object</returns> private static Uri CreateUriFromPath(string path) { ErrorUtilities.VerifyThrowArgumentLength(path, "path"); Uri pathUri = null; // Try absolute first, then fall back on relative, otherwise it // makes some absolute UNC paths like (\\foo\bar) relative ... if (!Uri.TryCreate(path, UriKind.Absolute, out pathUri)) { pathUri = new Uri(path, UriKind.Relative); } return(pathUri); }
internal static string MakeRelative(string basePath, string path) { ErrorUtilities.VerifyThrowArgumentNull(basePath, "basePath"); ErrorUtilities.VerifyThrowArgumentLength(path, "path"); if (basePath.Length == 0) { return(path); } Uri baseUri = new Uri(EnsureTrailingSlash(basePath), UriKind.Absolute); Uri relativeUri = CreateUriFromPath(path); if (!relativeUri.IsAbsoluteUri) { relativeUri = new Uri(baseUri, relativeUri); } Uri uri3 = baseUri.MakeRelativeUri(relativeUri); return(Uri.UnescapeDataString(uri3.IsAbsoluteUri ? uri3.LocalPath : uri3.ToString()).Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)); }
/// <summary> /// Creates a file with unique temporary file name with a given extension in the specified folder. /// File is guaranteed to be unique. /// Extension may have an initial period. /// If folder is null, the temporary folder will be used. /// Caller must delete it when finished. /// May throw IOException. /// </summary> internal static string GetTemporaryFile(string directory, string extension) { ErrorUtilities.VerifyThrowArgumentLengthIfNotNull(directory, "directory"); ErrorUtilities.VerifyThrowArgumentLength(extension, "extension"); if (extension[0] != '.') { extension = '.' + extension; } string file = null; try { directory = directory ?? Path.GetTempPath(); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } file = Path.Combine(directory, "tmp" + Guid.NewGuid().ToString("N") + extension); ErrorUtilities.VerifyThrow(!File.Exists(file), "Guid should be unique"); File.WriteAllText(file, String.Empty); } catch (Exception ex) { if (ExceptionHandling.NotExpectedException(ex)) { throw; } throw new IOException(ResourceUtilities.FormatResourceString("Shared.FailedCreatingTempFile", ex.Message), ex); } return(file); }
public static string Replace(this string aString, string oldValue, string newValue, StringComparison stringComparison) { ErrorUtilities.VerifyThrowArgumentNull(aString, nameof(aString)); ErrorUtilities.VerifyThrowArgumentNull(oldValue, nameof(oldValue)); ErrorUtilities.VerifyThrowArgumentLength(oldValue, nameof(oldValue)); if (newValue == null) { newValue = string.Empty; } var currentOccurrence = aString.IndexOf(oldValue, stringComparison); if (currentOccurrence == -1) { return(aString); } var endOfPreviousOccurrence = 0; // Assumes one match. Optimizes for replacing fallback property values (e.g. MSBuildExtensionsPath), where an import usually references the fallback property once. // Reduces memory usage by half. var builder = new StringBuilder(aString.Length - oldValue.Length + newValue.Length); while (currentOccurrence != -1) { var nonMatchLength = currentOccurrence - endOfPreviousOccurrence; builder.Append(aString, endOfPreviousOccurrence, nonMatchLength); builder.Append(newValue); endOfPreviousOccurrence = currentOccurrence + oldValue.Length; currentOccurrence = aString.IndexOf(oldValue, endOfPreviousOccurrence, stringComparison); } builder.Append(aString, endOfPreviousOccurrence, aString.Length - endOfPreviousOccurrence); return(builder.ToString()); }
/// <summary> /// Gets an identifier for a property based on its name, its containing object's name and/or type. This is intended to /// help the user zero in on the offending line/element in a xaml file, when we don't have access to a parser to /// report line numbers. /// </summary> /// <param name="propertyName"> The name of the property. </param> /// <param name="containingObjectName"> The name of the containing object. </param> /// <param name="containingObject"> The object which contains this property. </param> /// <returns> Returns "(containingObject's type name)containingObjectName.PropertyName". </returns> internal static string GetPropertyId(string propertyName, string containingObjectName, object containingObject) { ErrorUtilities.VerifyThrowArgumentLength(propertyName, "propertyName"); ErrorUtilities.VerifyThrowArgumentLength(containingObjectName, "containingObjectName"); ErrorUtilities.VerifyThrowArgumentNull(containingObject, "containingObject"); StringBuilder propertyId = new StringBuilder(); propertyId.Append("("); propertyId.Append(containingObject.GetType().Name); propertyId.Append(")"); if (!string.IsNullOrEmpty(containingObjectName)) { propertyId.Append(containingObjectName); } propertyId.Append("."); propertyId.Append(propertyName); return(propertyId.ToString()); }
/// <summary> /// Changes the unique name of the project. /// </summary> internal void UpdateUniqueProjectName(string newUniqueName) { ErrorUtilities.VerifyThrowArgumentLength(newUniqueName, nameof(newUniqueName)); _uniqueProjectName = newUniqueName; }
/// <summary> /// Gets the canonicalized full path of the provided path. /// Path.GetFullPath The pre .Net 4.6.2 implementation of Path.GetFullPath is slow and creates strings in its work. /// Therefore MSBuild has its own implementation on full framework. /// Guidance for use: call this on all paths accepted through public entry /// points that need normalization. After that point, only verify the path /// is rooted, using ErrorUtilities.VerifyThrowPathRooted. /// ASSUMES INPUT IS ALREADY UNESCAPED. /// </summary> internal static string NormalizePath(string path) { ErrorUtilities.VerifyThrowArgumentLength(path, "path"); #if FEATURE_LEGACY_GETFULLPATH if (NativeMethodsShared.IsWindows) { int errorCode = 0; // 0 == success in Win32 #if _DEBUG // Just to make sure and exercise the code that sets the correct buffer size // we'll start out with it deliberately too small int lenDir = 1; #else int lenDir = MaxPath; #endif unsafe { char *finalBuffer = stackalloc char[lenDir + 1]; // One extra for the null terminator int length = NativeMethodsShared.GetFullPathName(path, lenDir + 1, finalBuffer, IntPtr.Zero); errorCode = Marshal.GetLastWin32Error(); // If the length returned from GetFullPathName is greater than the length of the buffer we've // allocated, then reallocate the buffer with the correct size, and repeat the call if (length > lenDir) { lenDir = length; char *tempBuffer = stackalloc char[lenDir]; finalBuffer = tempBuffer; length = NativeMethodsShared.GetFullPathName(path, lenDir, finalBuffer, IntPtr.Zero); errorCode = Marshal.GetLastWin32Error(); // If we find that the length returned from GetFullPathName is longer than the buffer capacity, then // something very strange is going on! ErrorUtilities.VerifyThrow( length <= lenDir, "Final buffer capacity should be sufficient for full path name and null terminator."); } if (length > 0) { // In order to prevent people from taking advantage of our ability to extend beyond MaxPath // since it is unlikely that the CLR fix will be a complete removal of maxpath madness // we reluctantly have to restrict things here. if (length >= MaxPath) { throw new PathTooLongException(); } // Avoid creating new strings unnecessarily string finalFullPath = AreStringsEqual(finalBuffer, length, path) ? path : new string( finalBuffer, startIndex : 0, length : length); // We really don't care about extensions here, but Path.HasExtension provides a great way to // invoke the CLR's invalid path checks (these are independent of path length) Path.HasExtension(finalFullPath); if (finalFullPath.StartsWith(@"\\", StringComparison.Ordinal)) { // If we detect we are a UNC path then we need to use the regular get full path in order to do the correct checks for UNC formatting // and security checks for strings like \\?\GlobalRoot int startIndex = 2; while (startIndex < finalFullPath.Length) { if (finalFullPath[startIndex] == '\\') { startIndex++; break; } else { startIndex++; } } /* * From Path.cs in the CLR * * Throw an ArgumentException for paths like \\, \\server, \\server\ * This check can only be properly done after normalizing, so \\foo\.. will be properly rejected. Also, reject \\?\GLOBALROOT\ * (an internal kernel path) because it provides aliases for drives. * * throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegalUNC")); * * // Check for \\?\Globalroot, an internal mechanism to the kernel * // that provides aliases for drives and other undocumented stuff. * // The kernel team won't even describe the full set of what * // is available here - we don't want managed apps mucking * // with this for security reasons. */ if (startIndex == finalFullPath.Length || finalFullPath.IndexOf(@"\\?\globalroot", PathComparison) != -1) { finalFullPath = Path.GetFullPath(finalFullPath); } } return(finalFullPath); } } NativeMethodsShared.ThrowExceptionForErrorCode(errorCode); return(null); } #endif return(FixFilePath(Path.GetFullPath(path))); }
/// <summary> /// Validates the properties of this object. This method should be called /// after initialization is complete. /// </summary> internal void Validate(this DynamicEnumProperty type) { (type as BaseProperty).Validate(); ErrorUtilities.VerifyThrowArgumentLength(type.EnumProvider, "EnumProvider"); }