Code Monkey home page Code Monkey logo

extensions's Introduction

Enriched Capabilities

This repository contains a suite of libraries that provide facilities commonly needed when creating production-ready applications. Initially developed to support high-scale and high-availability services within Microsoft, such as Microsoft Teams, these libraries deliver functionality that can help make applications more efficient, more robust, and more manageable.

The major functional areas this repo addresses are:

  • Compliance: Mechanisms to help manage application data according to privacy regulations and policies, which includes a data annotation framework, audit report generation, and telemetry redaction.
  • Diagnostics: Provides a set of APIs that can be used to gather and report diagnostic information about the health of a service.
  • Contextual Options: Extends the .NET Options model to enable experimentations in production.
  • Resilience: Builds on top of the popular Polly library to provide sophisticated resilience pipelines to make applications robust to transient errors.
  • Telemetry: Sophisticated telemetry facilities provide enhanced logging, metering, tracing, and latency measuring functionality.
  • AspNetCore extensions: Provides different middlewares and extensions that can be used to build high-performance and high-availability ASP.NET Core services.
  • Static Analysis: Curated static analysis settings to help improve your code.
  • Testing: Dramatically simplifies testing around common .NET abstractions such as ILogger and the TimeProvider.

Build Status Help Wanted Discord

How can I contribute?

We welcome contributions! Many people all over the world have helped make this project better.

Reporting security issues and security bugs

Security issues and bugs should be reported privately, via email, to the Microsoft Security Response Center (MSRC) [email protected]. You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Further information, including the MSRC PGP key, can be found in the Security TechCenter. You can also find these instructions in this repo's Security doc.

Also see info about related Microsoft .NET Core and ASP.NET Core Bug Bounty Program.

Useful Links

.NET Foundation

This project is a .NET Foundation project.

There are many .NET related projects on GitHub.

  • .NET home repo - links to 100s of .NET projects, from Microsoft and the community.
  • ASP.NET Core home - the best place to start learning about ASP.NET Core.

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.

General .NET OSS discussions: .NET Foundation Discussions

License

.NET (including the runtime repo) is licensed under the MIT license.

extensions's People

Contributors

brennanconroy avatar carlossanlop avatar danmoseley avatar dariusclay avatar dbarbosapn avatar dotnet-bot avatar dotnet-maestro-bot avatar dotnet-maestro[bot] avatar dotnet-policy-service[bot] avatar eerhardt avatar egil avatar geeknoid avatar gewarren avatar github-actions[bot] avatar iliar-turdushev avatar jamesnk avatar jeffhandley avatar joegoldman2 avatar joperezr avatar mackinnonbuck avatar martincostello avatar martintmk avatar mobratil avatar nezdali avatar rafal-mz avatar russkie avatar sebastienros avatar tekian avatar tratcher avatar xakep139 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

extensions's Issues

Consider changing the contract of IMemoryCache to use a generic key

The current signatures for IMemoryCache use an object key for all its operations. There are extension methods that use TKey, TValue but they cast from object. Consequently for value types with custom comparers, cache lookups result in an extra boxing.

We could avoid this by modifying IMemoryCache to use a generic key argument:

    public interface IMemoryCache : IDisposable
    {
        object Set<TKey>(TKey key, object value, MemoryCacheEntryOptions options);

        bool TryGetValue<TKey>(TKey key, out object value);

        void Remove<TKey>(TKey key);
    }

This would additionally allow us to partition the backing dictionaries using the type of TKey.

CommandLineUtils help is always listed as the second item

From @dotnetshadow on January 29, 2016 3:37

Hi I noticed that the help command appears second in the list of commands irrespective of the order of commands: This is as of version asp.net 5 rc1

   var app = new CommandLineApplication
            {
                Name = "dnx mytest",
                FullName = "MyTest Commands"
            };
            app.VersionOption("--version", PlatformServices.Default.Application.ApplicationVersion);
            app.HelpOption("-?|-h|--help");

            app.OnExecute(() =>
                {
                    //ShowLogo();
                    app.ShowHelp();

                    return 0;
                });

            app.Command(
               "command1",
               database =>
               {                   

               });

            app.Command(
              "command2",
              database =>
              {

              });
            return app.Execute(args);

image

Copied from original issue: aspnet/dnx#3343

`TypeNameHelper` does not handle most nested classes correctly

With a simple, non-generic nested class such as

namespace Namespace
{
  public class OuterClass
  {
    public class InnerClass
    {
    }
  }
}

TypeNameHelper.GetTypeDisplayName(typeof(InnerClass)) returns "Namespace.OuterClass+InnerClass" instead of "Namespace.OuterClass.InnerClass". This is not useful when generating C# code.

Note TypeNameHelper does the correct thing (special-cases the +) for nested generic classes. In other words, it handles the more complex case and not the simple one.

Move Reporters used for logging in tools into a shared project

We're in the process of removing Microsoft.DotNet.Cli.Utils from our tools. One of the side effects was that we had to copy in some code which allows for printing output with color to the console. For RC2, we'll copy the code in to individual repos. For RTM, we should commonize this code.

Add ChangeToken static methods to Primitives

We want to add these boilerplate combinators for IChangeToken

public static class ChangeToken
{
    public static void OnChange(Func<IChangeToken> changeTokenProducer, Action changeTokenConsumer)
    {
        Action<object> callback = null;
        callback = (s) => 
        {
            var token = changeTokenProducer();
            changeTokenConsumer();
            token.Register(callback, null);
        }

        token.Register(callback, null);
    }

    public static void OnChange<T>(Func<IChangeToken> changeTokenProducer, Action<T> changeTokenConsumer, T state)
    {
        Action<object> callback = null;
        callback = (s) => 
        {
            var token = changeTokenProducer();
            changeTokenConsumer((T)s);
            token.Register(callback, s);
        }

        token.Register(callback, state);
    }
}

Unable to resolve service for type 'Microsoft.Extensions.PlatformAbstractions.ApplicationEnvironment'

In RC1, i'm using the following link action to display the corresponding source file content.

<a href="/Employee?file=Views\Accounts\default.cshtml" class="e-link">Default</a>
<a href="/Employee?file=Views\Accounts\Banking.cshtml" class="e-link">Accounts</a>

In recent RC2 update, when i'm click the same link will throws the error like as below

error

If there is any steps i need to resolve this one?

Greetings...
Manikandan

Change to IDisposable BeginScope(TState state) API

You should consider to change the IDisposable BeginScope(TState state) API,
to something that return IScopedLogger (which is sub set of the logging functionality)
this way you can encapsulate the scope and can log data to different scope simultaneously on different threads.
when encapsulating the log this way it is easier to maintain and understand logging data related to specific scope.


public interface IScopedLogger : IDisposable
{
    bool IsEnabled(LogLevel logLevel);
    void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter);
}

ASP.NET 5 distributed cache implementation on appfabric

Are we going to have Caching implementation for AppFabric as well, the way we have implementation for Redis (Microsoft.Extensions.Caching.Redis)

Can I use my existing implementation of cache providers that was built and targeted .Net 4.5.1 using App Fabric (Microsoft.ApplicationServer.Caching.Client.dll, and Microsoft.ApplicationServer.Caching.Core.dll) by following ASPNET's classic ProviderBase model.

I have custom CacheConfiguration that read the configuration from Web config, and instantiate the provider. But this solution was completely design and used for MVC5, I want to use App Fabric with ASPNET 5 solution now

Show where each configuration key came from

It would be nice if on the most verbose level you could get a log message when calling ConfigurationBuilder.Build showing you from where each loaded key comes from. Something like:

k1 (json:app.json)
- k2: v2(env var)
- k3: v3(json:app.json)
- k4: v4 (xml:app.xml)

Formatters Improvement

If we have look to the ILogger definition here https://github.com/aspnet/Logging/blob/dev/src/Microsoft.Framework.Logging.Abstractions/ILogger.cs#L22 we will notice that Log method contains Func<object, Exception, string> formatter a formatter that allow us to format the logged message, but what I have notice from many Logger Provider implementations that Formatters should give the ability to format the entire LogEntry not the message.
Have a look to the following lines:
TraceSourceLogger https://github.com/aspnet/Logging/blob/dev/src/Microsoft.Framework.Logging.Abstractions/ILogger.cs#L22
DebugLogger https://github.com/aspnet/Logging/blob/dev/src/Microsoft.Framework.Logging.Debug/DebugLogger.cs#L85
ConsoleLogger https://github.com/aspnet/Logging/blob/dev/src/Microsoft.Framework.Logging.Console/ConsoleLogger.cs#L79
we will notice that the devs don't have a control for the entire LogEntry , they have ability to format the logged message, i think our APIs lack in this point, because the actual message is surrounded with some metadata out of the box, furthermore there's no why to subclass the actual loggers to provide such things. For instance if i wanna add TimeStamp into the message using DebugLogger I can use the formatter parameter to achieve that, but I will see myself repeating this in places, someone may say "You can create your own method extension", that's true but what if wanna use the following format [LogLevel] TimeStamp - Message
I think this is impossible in the current implementation not only in DebugLogger but in all logger implementation!! i suggest to provide some way to achieve that - doesn't matter the implementation - either using virtual method or delegate .. etc.
Also this will open up the possibility to provide differnt kind of formmaters such as TextFormatter, JsonFormatter, XmlFormatter and so on ..
Let me know your feedback, I can provide code sample if you are interest 😄

Pkg rename: .Internal -> .Sources

Change .Internal for the packages below to .Sources, and update the references to these packages elsewhere.

  • Microsoft.Framework.BufferEntryCollection.Internal
  • Microsoft.Framework.CopyOnWriteDictionary.Internal
  • Microsoft.Framework.NotNullAttribute.Internal
  • Microsoft.Framework.PropertyActivator.Internal
  • Microsoft.Framework.PropertyHelper.Internal
  • Microsoft.Framework.TypeNameHelper.Internal

Clean up package metadata and pre-Core references

NuGet package metadata

The project.json file of every shipping NuGet package has two properties that must be non-empty:

  1. description
  2. tags

Description guidance

Description should be at least something like this:
"description": "ASP.NET Core MVC view rendering features. Contains common types used in most MVC applications as well as view rendering features such as view engines, views, view components, and HTML helpers.",

And if there are types in the package that are frequently referenced in source code, add this:
"description": "%description%\r\nCommonly used types:\r\nNS1.Type1\r\nNS1.Type2\r\nNS2.Type1\r\nNS3.Type1",
Note: Sort the types by the full namespace+type name

Tags guidance

The tags should generally include a "product" tag indicating the main product this is a part of (e.g. aspnetcore), and also "subject" or "feature" tags to associate this package with other related packages (e.g. aspnetcoremvc, logging, json).

Examples of tags:

  "tags": [
    "aspnetcore"
  ],
  "tags": [
    "aspnetcore",
    "aspnetcoremvc",
    "XYZ"
  ],

Note: Certain packages are not part of ASP.NET Core or Entity Framework Core, so be careful not to add those tags to the metadata of these packages.

Other stuff to clean up related to the "Core" product rename

Need to do a search in all files in the repo for strings such as asp.net, aspnet, entity framework, and entityframework. This obviously has a lot of false positives because these strings appear in namespace names all over the place. However, it's not too hard to weed through those (despite thousands of hits) because when scrolling in the output of the commands it's easy to see breaks in the pattern that need to be investigated.

Some useful commands to run:

findstr /snip /c:"entityframework" *
findstr /snip /c:"entity framework" *
findstr /snip /c:"asp.net" *
findstr /snip /c:"aspnet" *

Update readme.md in the root of the repo

This is a fairly simple task of ensuring the content in the readme.md file also doesn't have references to pre-Core naming.

Need to add missing doc comments in some projects

For XML files to be generated as part of the build, dotnet needs "xmlDoc": true to be added to project.json. For this to be done we first need to fix all the warnings(which show as errors) about missing XML doc comments. There are a bunch of those errors in the following projects.

  1. Microsoft.Extensions.CommandLineUtils
  2. Microsoft.Extensions.ObjectPool
  3. Microsoft.Extensions.Primitives

@muratg @victorhurdugaci

`PropertyHelper` does not provide information about inherited properties for interfaces

Due to this problem, callers see fewer properties than expected e.g. IList<T> appears to have no properties (we ignore the indexer but that's expected) and MVC throws NREs whenever it attempts to use metadata for its Count property. The same thing would happen for a user's hierarchy of interfaces.

For example, including the following in a view

<h3>@Html.DisplayNameFor(m => m.Count)</h3>
<p>@Model.Count</p>

results in

NullReferenceException: Object reference not set to an instance of an object.
Microsoft.AspNet.Mvc.Rendering.HtmlHelper.GenerateDisplayName(ModelExplorer modelExplorer, String expression)
Microsoft.AspNet.Mvc.Rendering.HtmlHelper`1.DisplayNameFor[TResult](Expression`1 expression)
Asp.ASPV__Views_Home_About_cshtml.<ExecuteAsync>d__17.MoveNext() in About.cshtml
    <h3>@Html.DisplayNameFor(m => m.Count)</h3>

Remove duplicated `WebEncoders` class

A big chunk of Microsoft.AspNetCore.WebUtilities.WebEncoders (for base64url-encoding and -decoding) is duplicated in Microsoft.AspNetCore.DataProtection.WebEncoders. With aspnet/HttpAbstractions#563, these classes are getting less aligned and DataProtection can't take advantage of the expanded API.

After a few offline discussions, have two ways to remove this wart:

  1. Move WebEncoders from HttpAbstractions to Common
    • #if the code such that it is placed in Microsoft.AspNetCore.DataProtection.Internal or Microsoft.AspNetCore.WebUtilities, depending on a flag.
      • In the DataProtection version, could make the class internal and leave it in Microsoft.AspNetCore.DataProtection if anyone feels strongly.
    • Use the new Common version in both DataProtection and HttpAbstractions (where it remains publicly exposed).
    • Leave Antiforgery and MVC alone; they will continue to rely on the public class in HttpAbstractions.
  2. Reuse the approach we took for ActivatorUtilities and place WebEncoders as an internal class in Microsoft.Extensions.Internal then expose it through a facade in HttpAbstractions. That avoids the oddity of a public class in a Blah.Blah.Blah.Sources package and makes the moved class more consistent w/ others in Common. But it involves more ceremony.

More reliable cache operations

As part of discussions while working on aspnet/Session#99, there were proposals for adding logic in caching to make database operations more reliable. For example, sql database operations may fail intermittently. In this case it may be a good idea to add retry logic and allow users to specify retry policies. This probably needs some more design work.

cc @mikeharder @Tratcher @davidfowl

Add a binary constant mode to StringValues

Something like the following

        public StringValues(string value, Encoding encoding)
        {
            _value = value;
            _values = null;
            _bytes = encoding.GetBytes(value);
            _encoding = encoding;
        }

        public static StringValues CreateBinaryConstant(string value, Encoding encoding)
        {
            return new StringValues(value, encoding);
        }

        public bool TryGetBinaryConstant(out byte[] bytes, out Encoding encoding)
        {
            bytes = _bytes;
            encoding = _encoding;
            return _bytes != null;
        }

would enable an application to contain

  static readonly StringValues _textPlain = StringValues.CreateBinaryConstant("text/plain", Encoding.ASCII);

// and later
    httpResponse.Headers["Content-Type"] = _textPlain;

this would enable a server to optimize the header output

  byte[] bytes; Encoding encoding;
  if (theHeaderValues.TryGetBinaryConstant(out bytes, out encoding) && encoding == _ascii)
  {
    // blit "\r\nThe-Header: " 
    // blit {bytes}
  }
  else
  {
    foreach(var value in headerValues)
    {
      // blit "\r\nThe-Header: "
      // ascii encode {value}
    }
  }

Using any ADO.NET provider

I want use another data provider, but i do not want to duplicate code from sql server cache.
Add please this ability to use any data provider out of box
Thanks.

p.s.
Why 'DataOperations' does not use 'using' for disposing datareader and other disposable objects?


I copied code and replaced all 'sql' on 'Db' (except SqlError)
Created manually table

-- Table: public.aspnet_session

-- DROP TABLE public.aspnet_session;

CREATE TABLE public.aspnet_session
(
    id character varying(455) COLLATE "default".pg_catalog NOT NULL,
    "Value" bytea NOT NULL,
    slidingexpirationinseconds bigint NOT NULL,
    expiresattime timestamp with time zone NOT NULL,
    absoluteexpiration timestamp with time zone,
    CONSTRAINT aspnet_session_pkey PRIMARY KEY (id)
)

I use it with Npgsql and new DbQueries

public class NpqsqlQueries : IDbQueries
    {
        private const string TableInfoFormat =
            "SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE " +
            "FROM INFORMATION_SCHEMA.TABLES " +
            "WHERE TABLE_SCHEMA = '{0}' " +
            "AND TABLE_NAME = '{1}'";

        private const string UpdateCacheItemFormat =
        "UPDATE {0} " +
        "SET ExpiresAtTime = " +
            @"(CASE WHEN  AbsoluteExpiration - @UtcNow
 <= CAST((CAST(SlidingExpirationInSeconds as varchar) || ' seconds') as INTERVAL)
 THEN
 AbsoluteExpiration
 ELSE
 @UtcNow +  CAST( (CAST(SlidingExpirationInSeconds as varchar) || ' seconds' ) as INTERVAL )
 END) " +
        "WHERE Id = @Id " +
        "AND @UtcNow <= ExpiresAtTime " +
        "AND SlidingExpirationInSeconds IS NOT NULL " +
        "AND (AbsoluteExpiration IS NULL OR AbsoluteExpiration <> ExpiresAtTime) ;";

        private const string GetCacheItemFormat =
            "SELECT Id, ExpiresAtTime, SlidingExpirationInSeconds, AbsoluteExpiration, \"Value\" " +
            "FROM {0} WHERE Id = @Id AND @UtcNow <= ExpiresAtTime;";

        private const string SetCacheItemFormat =
            @"with upsert as ( UPDATE {0} SET ""Value"" = @Value, 
ExpiresAtTime = (CASE WHEN(@SlidingExpirationInSeconds IS NUll)
THEN @AbsoluteExpiration
ELSE @UtcNow + CAST( (CAST(@SlidingExpirationInSeconds as varchar) || ' seconds') 
as INTERVAL )
END),
SlidingExpirationInSeconds = @SlidingExpirationInSeconds,
AbsoluteExpiration = @AbsoluteExpiration
WHERE Id = @Id RETURNING *)
INSERT INTO {0}
(Id, ""Value"", ExpiresAtTime, SlidingExpirationInSeconds, AbsoluteExpiration)
 SELECT @Id, @Value, (CASE WHEN (@SlidingExpirationInSeconds IS NUll)
THEN @AbsoluteExpiration
ELSE @UtcNow + CAST( (CAST(@SlidingExpirationInSeconds as varchar) || ' seconds') 
as INTERVAL )
END), @SlidingExpirationInSeconds, @AbsoluteExpiration
WHERE NOT EXISTS (SELECT * FROM upsert)
  ";

        private const string DeleteCacheItemFormat = "DELETE FROM {0} WHERE Id = @Id";

        public const string DeleteExpiredCacheItemsFormat = "DELETE FROM {0} WHERE @UtcNow > ExpiresAtTime";

        public NpqsqlQueries(string schemaName, string tableName)
        {
            var tableNameWithSchema = string.Format(
                "{0}.{1}", DelimitIdentifier(schemaName), DelimitIdentifier(tableName));

            // when retrieving an item, we do an UPDATE first and then a SELECT
            GetCacheItem = string.Format(UpdateCacheItemFormat + GetCacheItemFormat, tableNameWithSchema);
            GetCacheItemWithoutValue = string.Format(UpdateCacheItemFormat, tableNameWithSchema);
            DeleteCacheItem = string.Format(DeleteCacheItemFormat, tableNameWithSchema);
            DeleteExpiredCacheItems = string.Format(DeleteExpiredCacheItemsFormat, tableNameWithSchema);
            SetCacheItem = string.Format(SetCacheItemFormat, tableNameWithSchema);
            TableInfo = string.Format(TableInfoFormat, EscapeLiteral(schemaName), EscapeLiteral(tableName));
        }

        public string TableInfo { get; }

        public string GetCacheItem { get; }

        public string GetCacheItemWithoutValue { get; }

        public string SetCacheItem { get; }

        public string DeleteCacheItem { get; }

        public string DeleteExpiredCacheItems { get; }

        // From EF's SqlServerQuerySqlGenerator
        private string DelimitIdentifier(string identifier)
        {
            // return "[" + identifier.Replace("]", "]]") + "]";
            return '"' + identifier + '"';
        }

        private string EscapeLiteral(string literal)
        {
            return literal.Replace("'", "''");
        }
    }

All ok.
(sorry for SQL, i'm newbie)
Microsoft.Extensions.Caching.Db.zip

NpqsqlQueries.cs.txt

Include eventId as factory Add extensions filter parameter

Currently we are given the ability to filter logs for each provider based on the category/name string and log level enum when adding them to the factory like so:

loggerFactory.AddDebug( ( category, level ) => level >= LogLevel.Information );

It would be nice if the we were given the option to filter by eventId as well:

loggerFactory.AddDebug( ( category, level, event ) => 
    level >= LogLevel.Information
    && event != 10 );

I know we can easily just create our own provider that implements this extension overload (which is what I have done for now), but my suggestion is to include it with the providers that come with the library by default.

Remove chaining from HashCodeCombiner

Spot the bug:

public class TagBuilder
{
    private Dictionary<string, string> _attributes;
    private string _tagName;
    private string _innerContent;

    public override int GetHashCode()
    {
        var hash = HashCodeCombiner.Start()
            .Add(_tagName, StringComparer.Ordinal)
            .Add(_innerContent, StringComparer.Ordinal);

        foreach (var kvp in _attributes)
        {
            hash.Add(kvp.Key, StringComparer.Ordinal).Add(kvp.Value, StringComparer.Ordinal);
        }

        return hash.Build();
    }
}

It's too easy to get this wrong combining a builder and a mutable struct. We rarely have good unit tests for things like GetHashCode(). It's a better investment for us to remove chaining and write the extra 20 characters in each of these GetHashCode() methods than it is for us to write all the unit tests it would take to ensure correctness that way.

Introduce a time-constant comparer for crypto purposes

Both DataProtection and Identity have their time-constant comparison helper but none of them is public. It would be nice to refactor that and have a common implementation in a shared sources package that could also be used by third-party packages.

Note: as mentioned by @blowdart, CoreFX will likely get such a method in the future (1.2 or 2.0?), but I suppose it will require a newer .NET Standard contract (1.7/1.8?) or .NET Desktop TFM (4.6.3), which will make it incompatible with packages that need to target .NET 4.5.1 or older .NET Standard TFMs.

LoggerExtensions Can't Combine Exception and Format String

If you want to log:

  1. eventId
  2. Exception
  3. Formatted message

There is currently no extension method allowing this. Can we add one, or should this scenario just use the Log method? Here is the proposed signature:

public static LogCritical([NotNull] this ILogger logger, int eventId, string format, Exception error, params object[] args)

I just ran into this while trying to log an exception in a catch {} block in which I also wanted to include some details about the request:

_logger.LogCritical(eventId, "{eventId}: Unexpected error handling request {path}.", ex, eventId, context.Request.Path);

It doesn't work as desired because the exception (ex) is part of the args array for this overload (so the exception is output in place of {eventId} and the eventId is output in place of {path}).

Adding Diagnostics Source events/insight to Caching

As a consumer of diagnostics data we would like to be able to know when a cache hits and misses occur. Having this data will allow us to start realizing/showing "case and effect" with cache hits and misses. I would imagine that as a very minimum we would find out when hits occur, what was the key, the data, how long it took, and the source of the data (in memory vs not), and when misses occur, what was the key, how long it took, and the source of the data (in memory vs not), etc. There might be more data that would be interesting, but we can flush that out in the issue.

@Tratcher @Eilon

Custom ILogValues objects are ignored with the LoggerExtensions

Custom ILogValues types are currently ignored when producing the log output. The ILogValues contract suggests that you just need to expose a key/value enumerable in order to have them somewhat nicely outputted to the log.

However, because of how the Log methods are implemented that take the ILogValues objects, they always pass in the default _messageFormatter which in the end just uses ILogValues.ToString() to produce the output.

The logger implementations, for example the ConsoleLogger actually checks for the ILogValues objects and produces a nice output, but since the logger extension passed in a non-null formatter, this all is for nothing.

Since the ILogValues interface seems to be something meant as high-level as the extensions themselves, it would probably make most sense to implement a custom handling within the MessageFormatter there. Alternatively, the ILogValues interface should be changed to make clear that implementing ToString is required in order to produce an acceptable output.

Add CommonTasks

There are a lot of uses of Task.FromResult(0) in the aspnet repos for returning a completed Task.

There are also a bunch of uses of Task.FromResult(true) and Task.FromResult(false), along with some uses of Task.FromResult<T>(null).

Instead of calling Task.FromResult in these cases, which allocates a new Task instance each time, these can be created once and cached and reused, to reduce allocations.

The SignalR-Server repo already does this with its TaskAsyncHelper.

Other projects do this as well:

I was going to submit PRs in each repo to use one-off cached instances, but this looks like a cross-repo concern that might fit better as a common build-time package (like NotNullAttribute, PropertyHelper, etc.)

Something like Microsoft.Framework.CommonTasks.Sources with the following:

namespace Microsoft.Framework.Internal
{
    internal static class CommonTasks
    {
        public static readonly Task Completed = Empty<object>.Default;
        public static readonly Task<bool> True = Task.FromResult<bool>(true);
        public static readonly Task<bool> False = Task.FromResult<bool>(false);

        public static Task<T> Default<T>()
        {
            return Empty<T>.Default;
        }

        private static class Empty<T>
        {
            public static readonly Task<T> Default = Task.FromResult<T>(default(T));
        }
    }
}

Logs include control characters (in place of coloring) in Visual Studio output window when using Docker

Repro Steps

  1. Install Docker for Windows Beta and Docker Tools for Visual Studio
  2. New ASP.NET Core Application
  3. Add -> Docker Support
  4. Debug -> Start Without Debugging

Issue

Logs in output window include garbage characters in place of coloring:

DockerTask.ps1 -WaitForUrl -Machine ''
Hosting environment: Production
Content root path: /app
Now listening on: http://*:80
Application started. Press Ctrl+C to shut down.
�[0m�[32minfo�[39m�[0m�[0m�[32m: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]�[39m�[0m
      Request starting HTTP/1.1 GET http://docker/  

CC: @glennc

SqlServer Cache Dependency

Hello,

I have a few questions here.

  1. Do we still support SqlServer cache dependency on SQLServer Cache in ASP.NET? If yes how should I configure it?
  2. How can I define DI for SQLCacheDependency and what should I put in the constructor of Controller ( IDistributedCache?)
  3. I have been using table based cache dependency, is there a solution to manage SQLCacheDependency at record level?
  4. I'm using RedisCache in ASP.NET 4, do you have performance benchmark between RedisCache on Azure cloud and SQL Cache in a local DB?

Thanks lot!
Gary

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.