Code Monkey home page Code Monkey logo

dotnet / dotnet-api-docs Goto Github PK

View Code? Open in Web Editor NEW
665.0 107.0 1.5K 941.55 MB

.NET API reference documentation (.NET 5+, .NET Core, .NET Framework)

Home Page: https://docs.microsoft.com/dotnet/api/

License: Other

PowerShell 0.01% Shell 0.01% C# 33.38% F# 2.95% ASP.NET 11.65% C++ 11.72% Makefile 0.38% C 0.01% TSQL 0.01% Batchfile 0.01% JavaScript 0.02% Visual Basic .NET 29.56% 1C Enterprise 0.01% XSLT 0.01% CSS 0.03% HTML 0.01% Rich Text Format 10.26% HLSL 0.01% Lex 0.01%
hacktoberfest

dotnet-api-docs's Introduction

.NET API Reference Docs

This repository contains documentation for the .NET API reference. We track all work for this repository using GitHub issues. The documentation for APIs is built from the text and code snippets in this repo, and from the samples in the dotnet/samples repository.

The repository for conceptual .NET documentation is the dotnet/docs repository.

💜 Contribute

We welcome contributions to help us improve and complete the .NET API reference docs.

To contribute, see:

📑 Code of conduct

This project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behavior in our community. For more information, see the .NET Foundation Code of Conduct.

dotnet-api-docs's People

Contributors

aaronrobinsonmsft avatar albert-du avatar bartonjs avatar billwagner avatar carlossanlop avatar chrismaddock avatar dakersnar avatar danmoseley avatar dependabot[bot] avatar eiriktsarpalis avatar gewarren avatar jkotas avatar jozkee avatar krwq avatar liveans avatar mackiovello avatar mairaw avatar msdn-whiteknight avatar nschonni avatar nxtn avatar pkulikov avatar rzikm avatar steveharter avatar svick avatar tarekgh avatar tdykstra avatar tianqizhang avatar tompratt-aq avatar v-mepa avatar yishengjin1413 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dotnet-api-docs's Issues

ValueTuple generic types do not specify rules for comparison

ValueTuple generic types do not specify rules for comparison

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

Update System.Exception.StackTrace remark to reflect the new behavior for rethrown exceptions

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:

  1. 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.

  2. 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://github.com/dotnet/docs/blob/f66fe50bf0c637bfd9ca305c7ca30c3f37e50620/xml/System/Exception.xml#L1061

Docs for FileStream constructors are confusing about accessing devices

The API reference for various constructors of FileStream contain these two paragraphs:

  1. The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\.\PHYSICALDRIVE0 ".

  2. 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?

XmlDsigXPathTransform sample fails

Moved from dotnet/AspNetCore.Docs#5641
cc @rpetrusha
See XmlDsigXPathTransform Class

test sample. Copy from this bug


Problem Description

Description: After MS16-035 security update this code from MSDN doesn't work:

[Edit: here is the dotnet link] See XmlDsigXPathTransform Class

https://msdn.microsoft.com/library/system.security.cryptography.xml.xmldsigxpathtransform.xmldsigxpathtransform%28v=vs.110%29.aspx

[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.

ZipArchive constructor remarks are incorrect for current .NET Framework and .NET Core

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.

Document when XmlNode.SelectNodes() can return null

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!)

Missing exception type on xml docs for SingleOrDefault(src, predicate)

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);

System.Net.Mail.SmtpClient is marked as obsolete in docs, but not in the source code

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.

Add remarks for EventCounter APIs

Vance's comment for the F-level API docs:
dotnet/docs#3262 (comment)

There is a tutorial here

https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.Tracing/documentation/EventCounterTutorial.md

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.

Incorrectly rendered xref link

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.

Document correct serialization of exceptions in security-transparent assemblies

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_).

Clarify MemoryCacheOptions.SizeLimit doc comments

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>

[Feature] .NET Core 2.1 System.IO API changes

.NET Core 2.1 System.IO API changes

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:

  • Content Types
  • Table of Contents
  • Prioritization

General

APIs have been modified to better support cross platform code writing and substantially improve performance. Here is a summary of the API changes:

  1. Path validation has been simplified
  2. Span overloads have been added for a number of System.IO.Path APIs
  3. There is a new overload for Path.GetFullPath() that allows specifying a base path for resolving the path
  4. Directory enumeration results are more consistent cross-plat
  5. New enumeration options have been added
  6. A new extensible enumeration API has been added

Initial details are below. I'll be adding more links and details shortly.

Path Validation

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 strings
  • No IO APIs check for invalid characters
  • Path.GetDirectoryName() returns null for empty strings, instead of throwing
  • Search patterns are no longer validated beyond null check and rooting (they cannot return true from Path.IsPathRooted())

Span overloads

https://github.com/dotnet/corefx/issues/25539

Path.GetFullPath overload

https://github.com/dotnet/corefx/issues/25539

Enumeration API changes

https://github.com/dotnet/corefx/issues/25873

Correct description of PathTooLongException

Update description of PathTooLongException

General

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

DispatcherTimer ctor does not indicate that Start will be called automatically

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.

Add detail in HttpClient documentation

Add detail in HttpClient documentation

See PR dotnet/docs#4330 for background information.

Issues with Existing Topics

The HttpClient documentation needs to be updated to address issues that are not discussed or differences between .NET implementations. These include:

  • The connection limit, on a per-implementation basis.
  • Issues related to using a single instance of HttpClient
  • HttpClient and the DNS refresh problem
  • Guidance on when to instantiate a new HttpClient instance

Suggest reviewers

@feherzsolt @davidsh @karelz

API reference doesn't show members for .Net Standard types not referenced from NETStandard.Library

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.

Documentation on `Marshal.GetLastWin32Error` should be updated.

@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.

ILGenerator.BeginFinallyBlock example is invalid

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.

Detecting that a file is not found or has no appropriate date information

Detecting that a file is not found or has no appropriate date information

General

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:

  • FileSystemInfo.CreationTime
  • FileSystemInfo.CreationTimeUtc
  • FileSystemInfo.LastWriteTime
  • FileSystemInfo.LastWriteTimeUtc

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

[NewTopic] ZipArchive memory usage should be documented

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.

Please provide CipherMode availability matrix

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.

https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.symmetricalgorithm.mode?view=netcore-2.0#System_Security_Cryptography_SymmetricAlgorithm_Mode

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.

Review APIs with System.MonoTODO attribute

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

Document when MemoryStream.TryGetBuffer returns false

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:

  • one of the constructors that don't take an array: MemoryStream() and MemoryStream(int capacity)
  • the MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) constructor with publiclyVisible set to true

CreateSafeFileHandle not documented

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.

APIs that throw PathTooLongException may sometimes throw DirectoryNotFoundException

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.

Should API reference keep including permission information?

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?

Split GetHostEntry(IPAddress) into its own sample

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.

How can I access the encoding of the DisplayName property in MailAddress

Hi,
The third constructor of Mail​Address, 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 Mail​Address, 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

ThreadException notice confusing

https://docs.microsoft.com/en-gb/dotnet/api/system.windows.forms.application.threadexception?view=netframework-4.7

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?

sample for ConcurrentDictionaryis not thread safety

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

Expand list of exceptions for methods calling into GetFullPath

Expand list of exceptions for methods calling into GetFullPath

General

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.

//cc @mriehm @mairaw @JeremyKuhne @pjanotti

Documentation for FileInfo.Exists and File.Exists is misleading

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

List sample path for each Environment.SpecialFolder field and update the description of the fields for targeting to multiple platforms.

Current document for Environment.SpecialFolder only lists the meaning of each field on Windows. There're several problems since .NET Core targets multiple platform:

  1. The field description is not accuracy. For instance, ProgramFilesX86 indicates nothing for Linux and Mac. We need to let user know what platforms are supported for each field.
  2. When it comes only to Windows, we probably are able to guess what these fields stand for. However, .NET core is now targeting to multiple platforms. Without explicit examples, people are confusing about the value of the fields. It would be great if we list sample path for each Environment.SpecialFolder field to make it more intuitive. It'll save a lot of time for developers.

Socket.EndSend reference doc inaccuracy

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


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Improve System.ComponentModel.BackgroundWorker-related documentation

Improve System.ComponentModel.BackgroundWorker-related documentation

General

See PR dotnet/docs#4548

Issues with Existing Topics

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.

@Tanya-Solyanik @SimpleSamples

IComparer and IComparer<T> documentation should note ordering properties required

@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:

  • Explicitly demand a well-defined set of ordering properties as a contract of the IComparer interfaces
  • Explicitly disclaim requiring any particular ordering guarantees as an interface contract, but include an informational warning that IComparer 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

Total Order

A total order is a binary relation that has the following properties:

  1. If a <= b && b <= a then a == b
  2. If a <= b && b <= c then a <= c
  3. a <= b || b <= a

In other words:

  1. For any two elements x and y, either we can decide that x should be sorted before y, that y can be sorted before x, or that they are equivalent in sort order.
  2. For any three elements, x, y and z. If we would sort x before y and y before z we would also always sort x before z. The same holds in that if we would consider x to sort equivalently to y and y to sort equivalently to z we would always consider x to sort equivalently to z.

Exceptions to Total Order

It can perhaps be easier to think of total order by considering cases that don’t have total order.

Floating point operators.

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 Datetimes without Time Zones

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.

Importance or Total Order to Sort operations.

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.

Providing a Total Order on Partially Ordered values.

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

@JonHanna

EqualityComparer<double>.Default, Enumerable.Min() and Enumerable.Max() all solve this problem by adding their own rule that sorts NaN 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 :)

Task.Wait docs don't tell what happens to Task after timeout

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?

Define conditions under which IOException is thrown

Define conditions under which IOException is thrown

General

The IOException documentation needs to be improved to discuss the conditions under which an IOException are thrown.

Issues with Existing Topics

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

//cc @mairaw @ahman0

  1. Suggest reviewers

    • If you know someone who can provide feedback, use '@' to ask them to review.

Ensure our cross-platform docs are not Framework-centric and Windows-centric any longer

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:

Environment.OSVersion has misleading notes on 8/10 compatibility

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

Better documentation of asynchronous I/O implementation per OS

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

Lines in API reference XML files are too long

The lines in XML files in API reference are way too long. This causes several fairly minor, but noticeable annoyances to contributors like me:

  • When viewing the source or editing it on GitHub, I have to keep scrolling horizontally.
  • When viewing PRs or diffs, I have to switch to Split mode to see the differences without horizontal scrolling.
  • I think that long lines mean that GitHub does not highlight which words changed (see e.g. the diff for dotnet/docs#1930 and try to figure out what changed in remarks; compare it with svick/dotnet-docs@24815ef).

My questions (similar to those in dotnet/docs#1951):

  • Is this something that's worth fixing (considering it would change many files)?
  • Would a PR by me be welcome, or do you have a better way to deal with this?
  • Should it be fixed all at the same time, or would some kind of gradual process make more sense?
  • Would it help to fix this in the same PR as 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.

Documentation missing for ProcessStartInfo.RedirectStandardOutput

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.


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Documentation of Math library

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).

Document which SocketType is required for each ProtocolType

The documentation for the Socket constructor says:

The addressFamily parameter specifies the addressing scheme that the Socket class uses, the socketType parameter specifies the type of the Socket class, and the protocolType parameter specifies the protocol used by Socket. The three parameters are not independent. Some address families restrict which protocols can be used with them, and often the Socket type is implicit in the protocol. If the combination of address family, Socket type, and protocol type results in an invalid Socket, this constructor throws a SocketException.

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.


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Add this to the System.Diagnostics.Eventing.Reader.EventLogInformation.Attributes documentation

Please consider adding the following to the System.Diagnostics.Eventing.Reader.EventLogInformation.Attributes documentation.

System.Diagnostics.Eventing.Reader.EventLogInformation eli;

System.IO.File​Attributes fa = (System.IO.File​Attributes)Enum.ToObject(typeof(System.IO.File​Attributes), eli.Attributes.Value);

Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.