dotnet / dotnet-api-docs Goto Github PK
View Code? Open in Web Editor NEW.NET API reference documentation (.NET 5+, .NET Core, .NET Framework)
Home Page: https://docs.microsoft.com/dotnet/api/
License: Other
.NET API reference documentation (.NET 5+, .NET Core, .NET Framework)
Home Page: https://docs.microsoft.com/dotnet/api/
License: Other
For types that have .Net Standard packages, but are not part of NETStandard.Library
, it seems the new API reference behaves as if those types did not have .Net Standard versions at all (i.e. it hides all their members).
For example, this happens for XmlNode
(the URL says netstandard-1.6
, but it seems it changes to netframework-4.7
on its own, so you have to use the dropdown to see it), which exists in the System.Xml.XmlDocument
package, which has a version for .Net Standard 1.3.
I think for such types, their .Net Standard version should be shown.
https://apisof.net/ has a very similar issue (https://github.com/terrajobst/apisof.net/issues/2), which could be related.
MONO .NET APIs might be decorated with the System.MonoTODO attribute. In some cases, it could be useful to add the information from that attribute into some sort of "platform availability notes" section to call out differences between .NET implementations.
Related to PR dotnet/docs#2612
I have a headless machine which I want to report its Windows version so I know if the machine is up to date, and Environment.OSVersion has been very frustrating. After learning about everything I've learned, it still doesn't do what I need, because I need the full revision number. (i.e. 10.0.16299.192) and OSVersion insists on a .0 at the end. I'm using a WMI call instead. But anyways, Docs bug:
https://docs.microsoft.com/en-us/dotnet/api/system.environment.osversion?view=netframework-4.7.1
Both the "Important" and "Note" sections here simply state that from now on, OSVersion reports Windows 8 and above as Windows 6.2, with no qualifying details. This is wrong. I realized this due to reading the High DPI for Windows Forms documentation here: https://docs.microsoft.com/en-us/dotnet/framework/winforms/high-dpi-support-in-windows-forms
The correct information can only be found by digging into the "Operating System Version" link, which is an old MSDN page, and then noticing the link about "Targeting your application for Windows" at the bottom of that page. Nothing on System.Environment.OSVersion's Docs page would lead me to realize this.
Ideally, the Important/Note segments, which are somewhat redundant, should be collapsed into a single box which summarizes the default behavior as well as links directly to details on how to specify the supportedOS: https://msdn.microsoft.com/en-us/library/windows/desktop/dn481241.aspx
When implementing exceptions with state, it's necessary to implement serialization in order to allow such exceptions to pass AppDomain boundaries. Up to .NET 4, this was done simply by overriding GetObjectData
and providing a deserialization constructor.
Starting with .NET 4 and its security model, this is no longer possible with assemblies that have the AllowPartiallyTrustedCallersAttribute
. As these are loaded to be security-transparent, they cannot override GetObjectData
. .NET 4 therefore added Exception.SerializeObjectState
(https://docs.microsoft.com/de-de/dotnet/api/system.exception.serializeobjectstate?view=netframework-4.7.1), thus defining a new pattern for serializable exceptions.
This new pattern is however insufficiently documented. It should be explained in the "Remarks" sections of both the System.Exception
class (https://docs.microsoft.com/de-de/dotnet/api/system.exception?view=netframework-4.7.1) and the Exception.GetObjectData
method (https://docs.microsoft.com/de-de/dotnet/api/system.exception.getobjectdata?view=netframework-4.7.1#System_Exception_GetObjectData_System_Runtime_Serialization_SerializationInfo_System_Runtime_Serialization_StreamingContext_).
This issue is created in reference to my corefx issue here and SO issue here, which did not receive an answer in days. I then decided to experiment on my own. A copy is given below.
I'm not sure if the dotnet team has access to the docs here, but since it applies to .NET Core as well, it could be updated to clarify my use case below and potentially mention the 64k buffer size.
QUESTION
I am writing an application to manage processes and handle failovers. This program is written in C# for .NET Core and will run on Ubuntu Server 16.04 x64.
I have this code to create processes and track them, with exit events and such
ProcessStartInfo psi = new ProcessStartInfo
{
WorkingDirectory = "/home/xyzserver/someprocess",
FileName = "mono",
Arguments = "someprocess.exe",
RedirectStandardOutput = true
};
_proc = Process.Start(psi);
_proc.EnableRaisingEvents = true;
_proc.Exited += ProcOnExited;
I understand from the docs here that calls to Console.WriteLine will block if the _proc.StandardOutput stream is full. I want to prevent this behavior and dispose all the output from the managed application, since it will also write to a physical log on its own.
In addition, I would like to avoid storing any of the output in any unused stream buffers since they will never be used. A preferred solution will not UseShellExecute.
I have considered adding these 2 lines in the hope that any received data will be disposed, but am unsure about correctness.
_proc.OutputDataReceived += (sender, eventArgs) => {};
_proc.BeginOutputReadLine();
SOLUTION
I manually ran the test on .NET Core using 3 programs:
1. An HTTP server to track the *TextOutputter* program.
2. A TextOutputter program that prints 1000 characters and makes an HTTP request every second.
3. a ProgramRunner that runs one instance of TextOutputter.
Without the 2 lines, the buffer fills upto 64k and stalls. With the 2 lines, there is no stalling.
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
Intellisense warns me XmlNode.SelectNodes()
may return null. I was interested in what circumstances that happens in - but there doesn't seem to be any mention of this method returning null in the docs.
Google seems to suggest it can happen in various unusual situations, but the information seems to be sparse. (link).
Could this be documented? (If it's not instead an Intellisense error instead, of course!)
Hi,
The third constructor of MailAddress, MailAddress(String, String, Encoding.
The third parameter is, displayNameEncoding Encoding
The Encoding that defines the character set used for displayName.
But when I have a instance of MailAddress, how can I get the encoding of the displayname?
I am not sure if there is the correct place for me to give the feedback,but I can not leave a comment in document
The API reference does not in all cases provide a complete list of exceptions of methods that call into GetFullPath. A complete list is provided in the Directory.GetParent method. The same exception information should be incorporated into the documentation of the other methods that call into GetFullPath.
Note, incidentally, that SecurityException is a .NET Framework-only exception. The documentation should be revised to reflect that as part of this work.
For a discussion of the issue, see PR dotnet/docs#3971.
On the Application.ThreadException
page - there is the below notice:
Caution
Because this is a static event, you must detach your event handlers when your application is disposed, or memory leaks will result.
That confused me - surely the event will be disposed when the application ends anyway? Or is this suggesting that some resources may be kept hold of, once my application has already terminated?
I looked at the code example on that page, which seems to do no special handling regarding this notice. I then Googled it - and seems I wasn't the only person confused:
https://stackoverflow.com/q/7812627/1768779
https://www.pcreview.co.uk/threads/detach-application-threadexception-event-really.3084009/
Is the explanation on StackOverflow correct? If so - that seems a niche case to pull out in a big red Caution box - could the situation be clarified?
This sample code snippet currently uses C++ for all languages (C#, VB), so copy and paste does not work.
The lines in XML files in API reference are way too long. This causes several fairly minor, but noticeable annoyances to contributors like me:
My questions (similar to those in dotnet/docs#1951):
I have a work-in-progress code that would fix this here. In case this is deemed worth doing, I would finish it and submit a PR.
The documentation for the Socket
constructor says:
The
addressFamily
parameter specifies the addressing scheme that theSocket
class uses, thesocketType
parameter specifies the type of theSocket
class, and theprotocolType
parameter specifies the protocol used bySocket
. The three parameters are not independent. Some address families restrict which protocols can be used with them, and often theSocket
type is implicit in the protocol. If the combination of address family,Socket
type, and protocol type results in an invalidSocket
, this constructor throws aSocketException
.
It doesn't explain how to find out which combination of the three parameters work together, except for "try it and see if it throws". I think this is not sufficient and that valid combinations for the three parameters should be documented.
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
The remarks for MethodBase.Invoke(Object, Object[])
contain an xref
link to the other overload (MethodBase.Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)
), but it renders as:
[Invoke(Object, BindingFlags, Binder, Object<xref:System.Reflection.MethodBase.Invoke%28System.Object%2CSystem.Reflection.BindingFlags%2CSystem.Reflection.Binder%2CSystem.Object%5B%5D%2CSystem.Globalization.CultureInfo%29>
The source seems to be fine, so my guess is that this is some issue with converting xref
links to markdown, likely caused by the presence of encoded square brackets in the link.
When reading a ZipArchive from a non-seekable stream, the library loads the entire archive into memory before processing individual members. It looks like this is expected behavior - zip files store entry metadata at the end of the archive, and it's necessary to read the metadata before extracting files.
Though valid, this should be noted in the documentation for ZipArchive so people aren't surprised by the significant memory usage.
See PR dotnet/docs#4548
The documentation for all System.ComponentModel.BackgroundWorker types is lacking in detail and in need of revision. This includes the following types:
See dotnet/docs#4548.
System.IO.WindowsRuntimeStorageExtensions
(from the System.Runtime.WindowsRuntime
library) had APIs added for converting from Windows.Storage.IStorageFile
and Windows.Storage.IStorageFolder
to Microsoft.Win32.SafeHandles.SafeFileHandle
. These don't appear to be documented anywhere.
The key usage scenario is taking a WinRT IStorageFile and constructing a System.IO.FileStream
around it. This allows synchronous access to IStorageFile/IStorageFolder objects.
The reference definitions:
/runtime/src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.cs#L41-L46 [edited to point to dotnet/runtime]:
public static SafeFileHandle CreateSafeFileHandle(
this IStorageFile windowsRuntimeFile,
FileAccess access = FileAccess.ReadWrite,
FileShare share = FileShare.Read,
FileOptions options = FileOptions.None)
public static SafeFileHandle CreateSafeFileHandle(
this IStorageFolder rootDirectory,
string relativePath,
FileMode mode)
public static SafeFileHandle CreateSafeFileHandle(
this IStorageFolder rootDirectory,
string relativePath,
FileMode mode,
FileAccess access,
FileShare share = FileShare.Read,
FileOptions options = FileOptions.None)
Arguments work the same as FileStream constructor arguments, with the obvious exception that you can provide a root directory and a relative path.
The API is present in 2.0 releases of System.IO.WindowsRuntime` for .NET 4.6.1, .NET Core 2.0, and Universal Windows Platform 10.0.16299.
The API reference for various constructors of FileStream
contain these two paragraphs:
The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\.\PHYSICALDRIVE0 ".
Note
path
is not required to be a file stored on disk; it can be any part of a system that supports access through streams. For example, depending on the system, this class can access a physical device.
On first reading, I thought the two paragraphs are contradicting each other: the first says I can't access physical disks, the second says I can.
On second reading, I realized the paragraphs don't contradict each other: I can access physical devices, just not physical disks.
Is this interpretation correct?
In any case, I think this is confusing. Considering that I think device access is not a common requirement, should the two paragraphs just be deleted? If device access is actually possible this way, maybe it should be explained in a separate article?
Current document for Environment.SpecialFolder
only lists the meaning of each field on Windows. There're several problems since .NET Core targets multiple platform:
ProgramFilesX86
indicates nothing for Linux and Mac. We need to let user know what platforms are supported for each field.Environment.SpecialFolder
field to make it more intuitive. It'll save a lot of time for developers.Hey all, I'm trying to dive into the sources for async sockets on Posix/Linux.. And I just want to make sure that I'm not imagining...
In posix based systems the async sockets actually queue work items into the ThreadPool, and the actual IO is performed in a synchronous (maybe non-blocking) manner?
Is this right?
I assume that this is a very big split from how things are done on a native win32 system...
I would appreciate any sort of clarification on this matter from someone well aware of the actual implementation
I also think the documentation could benefit from a more detailed explanation of how async I/O works in different scenarios (OS)... I would be more than happy to submit a PR for the documentation, but I just want to make sure I'm reading the situation the right way
Basically people doing async IO need to be aware of how the .NET idioms map to the actual OS...
Better documentation for Windows/Linux/OSX should be very useful
In member documentation, almost all descriptions of the condition under which PathTooLongException is thrown mention the 260 character limit in the .NET Framework 4.6.1 and earlier versions. This needs to be changed, since the .NET Framework supports long paths. For Directory.GetParent, it was changed to "The specified path, file name, or both exceed the system-defined maximum length. For more information, see the topic." in PR dotnet/docs#4283.
In addition, the PathTooLongException topic itself is too .NET Framework-centric. It fails to mention the size of supported paths on Linux and MacOS.
//cc @mairaw @JeremyKuhne @pjanotti
Moved from dotnet/AspNetCore.Docs#5641
cc @rpetrusha
See XmlDsigXPathTransform Class
test sample. Copy from this bug
Description: After MS16-035 security update this code from MSDN doesn't work:
[Edit: here is the dotnet link]
See XmlDsigXPathTransform Class
[Edit - not needed to repo]
Repro Steps:- Install MS16-035
Impact:Unable to verify XML signed document
Run sample and you get the following output:
New XML file created.
XML file signed.
Verifying signature...
The XML signature is not valid.
Every time I use the Sin/Cosin functions (with GPS coordinates) I wonder what should be the unit the input.
Even if it seems logical, in some contexts it is not, therefore it would be nice to have "in radians" in the IntelliSense documentation.
I couldn't find where the comments are located in the repository (or in another).
The line below needs to be updated to reflect the fix for dotnet/coreclr#15780 and implemented by dotnet/coreclr#16464. This change is expected to be included in .NET Core 2.1 - https://github.com/dotnet/coreclr/issues/15780#issuecomment-368585175.
This is the new behavior for rethrown exceptions:
Exception rethrown in a method different than the method where it was originally thrown: the stack trace contains both the location in the method where the exception was originally thrown, and the location where the method that threw the exception was called.
Exception is thrown and later rethrown in the same method: the stack trace only contains the location where the exception was originally thrown and does not include the location where the exception was rethrown.
https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.ciphermode?view=netcore-2.0
The current documentation does not show which cipher modes are supported by a certain algorithm on different platforms. One question I have is that "on which platforms is AES CFB mode fully supported?", that no existing documentation can tell.
Library authors and users are forced to rely on CryptographicException
as stated, which is clearly inconvenient.
I know it is not easy to build a matrix in documentation, as there are multiple platforms, multiple algorithms and cipher modes to check. But I guess your test suite should cover the same things, so the information is already somewhere.
Only if you provide it, library authors and end users can then save tons of hours testing on their own.
public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source);
has the doc for all exceptions.
public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
looks like it's missing the invalid operation one.
// .....
// Exceptions:
// T:System.ArgumentNullException:
// source is null.
//
// T:System.InvalidOperationException:
// The input sequence contains more than one element.
public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source);
// .....
// Exceptions:
// T:System.ArgumentNullException:
// source or predicate is null.
public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
The Task.Wait methods which accept timeout as a parameter, can complete before the Task itself completes. The docs don't tell explicitly what happens to the Task itself in such scenario, which I observed to lead to some confusion.
Would it be ok to add an information that "the Task itself is not stopped" at the end of the remark about timeout elpapsing?
@tannergooding commented on Wed Jun 28 2017
The documentation currently makes no mention that this method will return errno
on Unix/Mac (or the conditions, if any, under which it will return errno
on Windows).
@tannergooding commented on Wed Jun 28 2017
As an aside, GetLastWin32Error
is really a terrible name for cross-platform use. Maybe adding a new API GetLastError
would be better...
@mellinoe commented on Wed Jun 28 2017
Many of the function names in Marshal
are Windows-specific. There was some effort to introduce a PInvokeMarshal
class which had better, platform-agnostic names, but I think we decided it wasn't worth it.
@tannergooding commented on Thu Jun 29 2017
Fair enough.
At the very least, documenting interop/marshalling functions with the behavior they take on non-Windows would be very beneficial.
Many API reference pages include section on "security", which explains which SecurityAction
is required to use them. As far as I know, using System.Security.Permissions
is discouraged on .Net Framework and they are not used on .Net Core at all.
Is there a reason why this information should still be included or can it be removed wholesale?
In the current documentation for ZipArchive's constructor, it states:
If the mode parameter is set to Read, the stream must support reading. If the mode parameter is set to Create, the stream must support writing. If the mode parameter is set to Update, the stream must support reading, writing, and seeking.
This is not correct in current versions of both .NET Core and .NET Framework due to a bug:
https://github.com/dotnet/corefx/issues/11497
The provided stream, if the mode is set to Create, must support writing and be able to get position information. Though most write-only streams do not support querying for position, you can create a stream subclass that tracks position to work around the issue, as described here:
https://stackoverflow.com/questions/16585488/writing-to-ziparchive-using-the-httpcontext-outputstream
Could the documentation be updated to explain how the class currently works? An example of the required wrapper class would also be helpful.
We migrated a lot of our legacy content which now applies to more than .NET Framework. This issue applies to both conceptual content and API reference.
We need to review the docs to make sure they don't mention Framework/Windows only, when they apply to other products and platforms and that samples work cross-platform. This might become a larger project.
For example:
This article has a link to this code sample. In this sample, existingVal
is changed on the existing object and returned. In this manner, existingVal.lastQueryDate
and existingVal.RecentHighTemperatures
may be inconsistent if another thread is modifying it at the same time. An solution is to return an new object, then AddOrUpdate
can handle the change correctly.
Source code: https://referencesource.microsoft.com/#mscorlib/system/Collections/Concurrent/ConcurrentDictionary.cs,1151
The IOException documentation needs to be improved to discuss the conditions under which an IOException are thrown.
The IOException documentation treats IOException as a base class of a number of other exceptions (such as FileLoadException, FileNotFoundException, etc.). However, an IOException rather than a derived class exception is thrown under a number of circumstances. For example, an IOException is thrown when no disk space is available; by convention, we don't document this exception condition, since any operation that touches storage can throw the exception.
See PR dotnet/docs#4171
Suggest reviewers
APIs might have a different behavior depending on the platform in .NET Core and might throw the PlatformNotSupported exception. We need to call that out in the Exception section of the APIs impacted.
I remember seeing spreadsheets flowing around with that information @terrajobst. Do we have the latest version of that @terrajobst?
/cc @bartonjs
Please consider adding the following to the System.Diagnostics.Eventing.Reader.EventLogInformation.Attributes documentation.
System.Diagnostics.Eventing.Reader.EventLogInformation eli;
System.IO.FileAttributes fa = (System.IO.FileAttributes)Enum.ToObject(typeof(System.IO.FileAttributes), eli.Attributes.Value);
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
Currently, the property summary for the MemoryCacheOptions.SizeLimit property is:
/// <summary>
/// Gets or sets the maximum size of the cache.
/// </summary>
It would be nice if this explicitly provided the unit of measure (bytes, kilobytes, etc.). Like this:
/// <summary>
/// Gets or sets the maximum size of the cache in kilobytes.
/// </summary>
System.Net.Mail.SmtpClient class page is currently states that class is obsolete, and offers https://github.com/jstedfast/MailKit as a replacement.
[System.Obsolete("SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead")]
public class SmtpClient : IDisposable
That class has no Obsolete
attribute in both Reference Source for 4.7 and corefx source.
Mono version of SmtpClient
was marked as Obsolete few years ago by @migueldeicaza, and then that external lib link somehow made its way to official 4.7 docs. Please remove it.
Updates were made to accommodate the GetHostEntry(IPAddress)
overload in the sample on dotnet/docs#2550 so that the API ref would show a proper (method call) example for this overload and not the example for GetHostEntry(String)
(hostname as String
), which was JustWrong:tm:.
Updates were made to:
samples/snippets/cpp/VS_Snippets_Remoting/System.Net.Dns/CPP/dnsnewmethods.cpp
samples/snippets/csharp/VS_Snippets_Remoting/System.Net.Dns/CS/dnsnewmethods.cs
samples/snippets/visualbasic/VS_Snippets_Remoting/System.Net.Dns/vb/dnsnewmethods.vb
However, this overload is best shown via its own sample as a complete executable example in the API coverage. Create a new set of samples to demo this overload and tie the new samples into xml/System.Net/Dns.xml.
When I have a MemoryStream
and want to access its underlying array as Span<byte>
, one possible approach is:
var ms = new MemoryStream();
// write to ms here
ms.TryGetBuffer(out ArraySegment<byte> buffer);
Span<byte> span = buffer;
As far as I can tell, this is safe with the current implementation, even though I'm not checking the return value of TryGetValue
to see if it succeeded.
But If I relied only on the documented behavior of TryGetBuffer
, I would have to write:
if (!ms.TryGetBuffer(out ArraySegment<byte> buffer))
{
buffer = ms.ToArray();
}
It's slightly more code, but what's worse is that it contains code that will never execute and also that it implies this code might allocate. Because of that, I think it would be nice if it was clearly documented that TryGetBuffer
returns true
(and that GetBuffer
doesn't throw) when MemoryStream
is constructed using:
MemoryStream()
and MemoryStream(int capacity)
MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible)
constructor with publiclyVisible
set to true
See PR dotnet/docs#4330 for background information.
The HttpClient documentation needs to be updated to address issues that are not discussed or differences between .NET implementations. These include:
Not sure the best way to handle/track this. .NET Core doesn't preemptively check for path lengths anymore (as it is impossible to accurately predict). We throw PathTooLong when the OS reports it. In most cases that means behavior stays the same, but in some rare cases you can get DirectoryNotFound instead of PathTooLong.
I give a somewhat detailed description here: https://github.com/dotnet/corefx/issues/24567#issuecomment-335936074
It may be enough to just make sure that all APIs that have PathTooLong also have DirectoryNotFound. We may also want to consider mentioning that in exceptional cases long paths can return DirectoryNotFound.
If there is a better way to reflect this behavior I'm open to suggestions.
There are a number of behavior changes to System.IO APIs in .NET Core 2.1 and new APIs. This issue summarizes the high level changes and links to relevant documents.
Still Needed:
APIs have been modified to better support cross platform code writing and substantially improve performance. Here is a summary of the API changes:
System.IO.Path
APIsPath.GetFullPath()
that allows specifying a base path for resolving the pathInitial details are below. I'll be adding more links and details shortly.
To facilitate writing cross platform code, System.IO.Path APIs have had their preemptive error checking simplified. Notably:
Path.GetFullPath()
only checks for embedded nulls, null strings, and empty stringsPath.GetDirectoryName()
returns null for empty strings, instead of throwingPath.IsPathRooted()
)https://github.com/dotnet/corefx/issues/25539
https://github.com/dotnet/corefx/issues/25539
This issue was reported by a .NET user a while ago via a different channel:
Hi alll, no authoritative response has been given on this in several discussions in the past, so I decided to report this as a documentation bug, because there is an obvious conflict in the documentation of the Socket.BeginSend and Socket.EndSend methods even in the latest .NET framework version. MSDN says in Socket.BeginSend: "When your application calls BeginSend, the system will use a separate thread to execute the specified callback method, and will block on EndSend until the Socket sends the number of bytes requested or throws an exception." From this sentence I infer, that BeginSend queues ALL data for sending or there will be an exception. But let's have a look what MSDN says in Socket.EndSend: "If you are using a connection-oriented protocol, EndSend will block until some of the buffer was sent. If the return value from EndSend indicates that the buffer was not completely sent, call the BeginSend method again, modifying the buffer to hold the unsent data." This sentence says, that EndSend might succeed even with less bytes sent than requested for connection-oriented protocols. Since it is realy important to know what the real behaviour of these methods is, the documentation should be fixed (or clariefied) to make this very old problem finally clear. According to our tests EndSend never returns less bytes than requested when it succeeds even for very large (MB) sents. So can you please explain to the public the behaviour of these two methods? Does it play a role if the socket is set to nonblocking? Thank you very much. Alex
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
Documentation for FileInfo.Exists and File.Exists is misleading
File.Exists "returns" currently reads:
true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. This method also returns false if path is null, an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path.
Should read:
true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. This method also returns false on an invalid filename or if any error prevents determining if the file exists or not.
FileSystemInfo.Exists "returns" currently reads:
true if the file or directory exists; otherwise, false.
Should read:
true if the file or directory is known to exist; otherwise, false. This method returns false if an error prevented determining if the file exists or not. If FileSystemInfo.Exists returns false, call FileSystemInfo.tLastWriteTimeUTC to throw the exception for the error. If LastWriteTimeUTC returns at all, the file or directory is known to not exist.
Remakrs on FileSystemInfo.Exists should contain this blob:
FileSystemInfo reports on existence based on a snapshot of the file in question that may be invalid by the time FileSystemInfo.Exists() returns. Therefore, the following code can still throw FileNotFoundException: var fileinfo = new FileInfo(pathstring); if (fileinfo.Exists()) using (var f = new FileStream(fileinfo.FullName, FileMode.Open) { /* ... */ } else {var ignoredvalue = fileInfo.LastWriteTimeUTC; }
General Commentary (why these specific changes):
Not checking if the result of FileInfo.Exists is trustworthy is almost always a bug, and is always a bug in batch processing (and therefore all library modules). File.Exists() has no use for the reason of there being no way to check if false was a successful false or an error. Just calling fileInfo.LastWriteTimeUTC != new DateTime(1601, 1, 1, 0, 0, 0) as FileInfo.Exists won't work because that's a valid time that somebody could have set a file to. (And I don't trust that value's right on Unix anyway but I digress.)
Most of the time, FileInfo isn't what you want anyway. The static file provider in MVC has some bizarre corner case bugs that would not exist had it checked for a file's existence by opening it and catching FileNotFoundException.
Original Discussion: https://github.com/dotnet/corefx/issues/26893
In addition to explicit interface implementations that support a custom comparison method, each generic ValueTuple
type has a CompareTo
method that compares the instance with a tuple of that type. However, the rules for comparison are not specified. Since they are specified in the case of the generic Tuple types, they should be documented for ValueTuple as well, so that there is parity between Tuple and ValueTuple generic types.
See also dotnet/docs#2956, which noted that the documentation for ValueTuple.CompareTo(ValueTuple)
, the comparison method for a 0-tuple, was incorrect.
/cc @int19h
The following methods all return 12:00:00.00000 January 1, 1601 as the date if the file represented by a FileSystemInfo object does not exit or if the operating system cannot supply the requested information:
In PR #4453, @BillWagner raised the question of how to detect this missing/incomplete information -- whether there's a constant available, or whether the returned date should be compared with some date. Since the .NET Framework does not include a predefined constant for this purpose, detection requires comparison with a specific date. The best alternative is probably to implement a utility method that converts the returned date back to UTC and tests whether the result is less than or equal to 12:00:00.00000 January 1, 1601. It's also possible to avoid the UTC conversion and simply pick some arbitrary date after that, since presumably no file should legitimately have a creation/last write time in the seventeenth century.
//cc @BillWagner @JeremyKuhne
The DispatcherTimer(TimeSpan, DispatcherPriority, EventHandler, Dispatcher)
Constructor automatically starts/enables the instance, and neither IntelliSense nor the documentation indicate that this is the case.
We were wondering why the code behaved differently, thinking this was only a short-hand form of specifying all parameters at once (vs. attaching the EventHandler using +=
afterwards); but looking at the source revealed that it actually calls Start
.
I have no idea how to express this concisely, otherwise I'd have opened a pull request right away.
Other than adding this note to the summary (which I believe should be done to make it clear in IntelliSense inside VS right away), it might be a good idea to provide an example on when this would be useful (or could be used over the other alternatives), or at least a remark highlighting this distinction.
Vance's comment for the F-level API docs:
dotnet/docs#3262 (comment)
There is a tutorial here
Which gives a quick example. (There are only two APIs the constructor and WriteMetric API). The EventCounter functionality is meant to be an extension of EventSource logging.
The goal of EventSource is logging. The idea is that to create new logging messages, you create a subclass System.Diagnostics.Tracing.EventSource, and you define methods for each distinct kind of message that you wish to log. . You declare arguments to this method to allow the instrumentation point to pass any information you wish to log
The bodies of these subclass methods then call 'WriteEvent' which pass the information long to whoever subscribes to your EventSource.
EventCounters allow you to instead of logging on every event, you simply gather aggregations on every event (computing just the count, sum, min, max and variance). It is these AGREGATES that then get logged (and the subscriber has control over how often the aggregates get sent). This allows even very high frequency events to be monitored cheaply.
The recommendation (which the tutorial illustrates), is to have the EventSource method call both the WriteEvent and WriteMetric API. The subscriber can then decide which of them (or both) to turn on at runtime, allowing the subscriber to have either low overhead or high detail logging.
In the short term, you can simply point at the tutorial in the remarks, but it would not hurt to have a short summary along the lines of the above for the class that you can refer to in both the constructor and WriteMetric methods.
@dbjorge commented on Tue Dec 06 2016
The documentation for IComparer
(@docs.microsoft.com, @msdn) and IComparer<T>
(@docs.microsoft.com, @msdn) do not note whether any particular ordering properties are expected of a valid implementation, but at least List<T>.Sort
assumes some (antisymmetry, per this Connect feedback circa .NET 4.5).
The interface documentation should note what sort of ordering properties the rest of the standard library will be assuming/demanding of a Compare
implementation. I'd expect this to be the usual properties of a total order.
@CIPop commented on Tue Dec 06 2016
cc: @rpetrusha, @AArnott
@karelz commented on Tue Dec 06 2016
cc: @mairaw
@JonHanna commented on Tue Dec 06 2016
Is that a responsibility of IComparer<T>
or of the caller of Sort
(or OrderBy
etc.). If one was going to implement an order that wasn't total (e.g. XmlSchema's rules on comparing datetimes without time zones, would doing so in an IComaprer<T>
be disallowed?
@dbjorge commented on Tue Dec 06 2016
I would consider it reasonable to either:
IComparer
interfacesIComparer
use sites may require certain ordering properties (with examples).I think either of those would be a big improvement over not documenting it either way. I could be convinced that the former would be too big a breaking change to be acceptable.
In either case, I think it would improve clarity to also document it on the individual IComparer
-based framework methods.
@JonHanna commented on Tue Dec 06 2016
I think the warning is a good idea.
I think the idea of documenting the relevant methods, even more so.
@mairaw commented on Tue Dec 06 2016
I own these docs so I'd be the one making the updates. Just let me know who I should be working with to figure out what's the guidance we want to provide there. /cc @karelz
@karelz commented on Wed Dec 07 2016
@dbjorge @JonHanna can you please suggest which text to change to what? (ideally mention the diff or old & new text) Thanks!
@JonHanna commented on Wed Dec 07 2016
Could an extra page be added describing total ordering? A concise statement linking to it would probably be clearer and with less text added to the individual pages affected.
@mairaw commented on Wed Dec 07 2016
@JonHanna yes, it's possible to add a separate article explaining the concepts and then link to it from the affected pages.
@JonHanna commented on Mon Jan 09 2017
A total order is a binary relation that has the following properties:
a <= b && b <= a
then a == b
a <= b && b <= c
then a <= c
a <= b || b <= a
In other words:
It can perhaps be easier to think of total order by considering cases that don’t have total order.
Because double.NaN <= double.NaN
returns false
, double.NaN < 0
returns false and 0 < double.NaN
returns false, we cannot use the arithmetic operators to determine a total order on a set of floating point numbers that includes NaN
.
XML Schema defines some datatypes that are only partially ordered. One example is dateTime
which represents a date and time without a timezone (comparable to DateTime
in .NET). By the rules of XML Schema, 2001-03-29T12:00:57 is always sorted before 2001-04-23T09:17:39 and 2001-04-23T11:31:09 is always sorted before 2001-04-29T23:09:10 but 2001-04-23T09:17:39 can be considered neither before nor after 2001-04-23T11:31:09.
Not knowing the time zone, it could be e.g. 2001-04-23T09:17:39 in Copenhagen compared to 2001-04-23T11:31:09 in Dublin (earlier), or 2001-04-23T09:17:39 in Montreal compared to 2001-04-23T11:31:09 in Bangalore (later).
To offer a dependable ordering within the international context XML Schema time-related data types consider, one dateTime
can only be considered as sorting before another if that holds for any of a possible range of timezones from -14:00 to +14:00 to have full confidence that the ordering would hold.
Many methods, especially sorting methods, that take an IComparer
or IComparer<T>
require that the Compare()
methods of those objects give a total order. Failure to do so can result in the results not being sorted at all, exceptions, or even infinite loops. Examples include List<T>.Sort()
, Array.Sort()
and Enumerable.OrderBy()
.
Other methods may have similar issues, such as those that find minima and maxima, such as Linq's Min()
and Max()
extension methods.
If you want to sort values that are not normally totally ordered, you need to define a total ordering for it. For example, as mentioned above double
is not totally ordered because NaN
cannot be placed into any meaningful position by the <
, <=
, =
, >
and >=
operators. Comparer<double>.Default
, Enumerable.Min()
and Enumerable.Max()
all solve this problem by adding their own rule that sorts NaN
before any other value. This results in the three properties mentioned at the start of this article applying to the ordering.
An approach that works for many cases, is to add a tie-breaker rule onto a partial ordering. This is used here, with most comparisons being the same as with <
but the "NaN equal to NaN and before everything else" providing that tie-breaking rule that makes it a total order.
@karelz commented on Wed Dec 14 2016
@ianhays @Priya91 can you please review the text as area experts? (or pull in appropriate folks please)
@ianhays commented on Thu Dec 15 2016
@JonHanna that's a great doc on total order. 👍very concise and informative. The DateTime section is a bit verbose but explains the reasoning behind the exception to total order well.
@JonHanna commented on Thu Dec 15 2016
I split up the sentences and hopefully clarified a bit (sometimes attempts at concision end up reading more verbose than otherwise) and added a sentence at the end about using tie-breaking rules in creating total orders out of parial.
@JonHanna commented on Thu Dec 15 2016
Also fixed the copy-pasting in the example dates, as I had Montreal and Bangalore in time zones over a week apart 😁
@svick commented on Fri Dec 16 2016
EqualityComparer<double>.Default
,Enumerable.Min()
andEnumerable.Max()
all solve this problem by adding their own rule that sortsNaN
before any other value.
Did you mean Comparer<double>.Default
? EqualityComparer
does not define ordering.
@JonHanna commented on Fri Dec 16 2016
@svick I did indeed. Fixed.
@ianhays commented on Mon Feb 13 2017
@mairaw did you get a chance to take a look at this?
@mairaw commented on Mon Feb 13 2017
Not yet @ianhays. I'm completely swamped at the moment with the .NET Core release.
@ianhays commented on Mon Feb 13 2017
Gotcha, thanks for the update :)
As discovered by @luboid in https://github.com/dotnet/coreclr/issues/14379#issuecomment-334959413, the example code for ILGenerator.BeginFinallyBlock
contains branch out of try block and is thus invalid. When I run it on .Net Framework 4.7 in x64 mode or .Net Core 2.0 (after changing myAppDomain.DefineDynamicAssembly
to AssemblyBuilder.DefineDynamicAssembly
and removing the permissions attribute to make it compile on .Net Core 2.0), I get the following exception:
Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidProgramException: Common Language Runtime detected an invalid program.
at Adder.DoAdd(Int32 , Int32 )
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args)
at ILGenerator_BeginFinallyBlock.Main() in C:\code\tmp\coreapp\Program.cs:line 109
I think the example should be changed, so that it produces valid IL.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.