.NET Framework – walk-through – Part 12

.NET Core

The following is a partial list of the commands.

The telemetry feature is on by default. The data collected is anonymous in nature and will be published in an aggregated form for use by both Microsoft and community engineers under a Creative Commons license.

You can opt-out of the telemetry feature by setting an environment variable DOTNET_CLI_TELEMETRY_OPTOUT (e.g. export on OS X/Linux, set on Windows) to true (e.g. “true”, 1). Doing this will stop the collection process from running.

Testrunner

Fact

.NET Core is a platform made of NuGet packages.

The ‘lib’ and ‘ref‘ terms refer to folders in NuGet packages. ‘ref’ folders describe the public API of a package via assembly metadata. ‘lib’ folders
contain the implementation of that public API for a given framework.

Note that a portable app with third-party dependencies will only be as portable as its third-party dependencies. For example, if a third-party
library only supports macOS, the app will not be portable to Windows systems.

Sample project.json file

Note that you can only deploy a self-contained app with a third-party library to platforms supported by that library.

The version number of the .NET Framework doesn’t necessarily correspond to the version number of the CLR it includes.
It’s good programming practice to catch a specific type of exception rather than use a basic catch statement.

It is good coding practice to add information to an exception that is re-thrown to provide more information when debugging.

Throw exceptions instead of returning an error code.

Exceptions ensure that failures do not go unnoticed because calling code didn’t check a return code.

.NET includes a set of delegate types that programmers can reuse and not have to create new types. These are Func<>, Action<> and Predicate<>, and
they can be used in various places throughout the .NET APIs without the need to define new delegate types.

● Action<> is used when there is a need to perform an action using the arguments of the delegate.
● Func<> is used usually when you have a transformation on hand, that is, you need to transform the arguments of the delegate into a different
result. Projections are a prime example of this.
● Predicate<> is used when you need to determine if the argument satisfies the condition of the delegate. It can also be written as a Func<T,
bool>.

It’s important to reason about tasks as abstractions of work happening asynchronously, and not an abstraction over threading. Tasks can be
explicitly requested to run on a separate thread via the Task.Run API.

async and await are the best practice managing CPU-bound work when you need responsiveness.

PerfView traces show that the performance of the new C# and Visual Basic compilers is rarely CPU bound.

Keep in mind the four facts for tuning your apps:
Don’t prematurely optimize – be productive and tune your app when you spot problems.
Profiles don’t lie – you’re guessing if you’re not measuring.
Good tools make all the difference – download PerfView and try it out.
It’s all about allocations – that is where the compiler platform team spent most of their time improving the performance of the new compilers.

After the Lazy object is created, no instance of Orders is created until the Value property of the Lazy variable is accessed for the first time. On first access, the wrapped type is created and returned, and stored for any future access.

For example, to analyze foo.dll against .NET Core and the latest .NET Framework and get an HTML report, the following command would be run:
ApiPort.exe analyze -f foo.dll -t “.NET CORE, Version=5.0” -t “.NET Framework” -r HTML

Line #5 introduces the DllImport attribute. This attribute is crucial, as it tells the runtime that it should load the unmanaged DLL. This is the DLL into which we wish to invoke.

Line #6 is the crux of the P/Invoke work. It defines a managed method that has the exact same signature as the unmanaged one. The declaration has a new keyword that you can notice, extern, which tells the runtime this is an external method, and that when you invoke it, the runtime should find it in the DLL specified in DllImport attribute.

If you are only reading from a shared collection, then you can use the classes in the System.Collections.Generic namespace. We recommend that you do not use System.Collections collection classes unless you are required to target the .NET Framework 1.1 or earlier runtime.

The ConcurrentQueue<T> and ConcurrentStack<T> classes do not use locks at all. Instead, they rely on Interlocked operations to achieve thread-safety.

Interlocked Notes:

1. INTERLOCKED METHODS ARE CONCURRENTLY SAFE ON ANY NUMBER OF COREs OR CPUs.
2. Interlocked methods apply a full fence around instructions they execute, so reordering does not happen.
3. Interlocked methods do not need or even do not support access to a volatile field, as volatile is places a half fence around operations on given
field and interlocked is using the full fence.

Interlocked functions do not lock. They are atomic, meaning that they can complete without the possibility of a context switch during increment. So
there is no chance of deadlock or wait.

This is safe to do (provided you remember to lock everywhere else that you access this.counter). It prevents any other threads from executing any other code which is guarded by locker. Using locks also, prevents the multi-CPU reordering problems as above, which is great.

The problem is, locking is slow, and if you re-use the locker in some other place which is not really related then you can end up blocking your other threads for no reason.

Any time two threads operate on a shared variable concurrently, and one of those operations performs a write, both threads must use atomic operations.

Atomic operations are ones which manipulate memory in a way that appears indivisible (incapable of being divided by a specific integer without leaving a remainder): No thread can observe the operation half-complete. On modern processors, lots of operations are already atomic.
For example, aligned reads and writes of simple types are usually atomic.

Lock method will call a Monitor.Enter(Object) and Monitor.Exit() in System.Threading.Monitor Class to mark if the current object has been locked or unlocked. So Lock’s performance should be slower than Interlocked.

SpinLock A very low-level, CPU-intensive lock. Good for situations where the lock is held a very short amount of time.

.NET Framework 4.6 and 4.5 – walk-through – (Part 11)

When you pass an Action to Task.Run:

Task.Run(someAction);

that’s exactly equivalent to:

Task.Factory.StartNew(someAction,
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

Task.Run provides eight overloads, to support all combinations of the following:

  1. Task vs Task<TResult>
  2. Cancelable vs non-cancelable
  3. Synchronous vs asynchronous delegate

Calling Unwrap on a Task<Task> gives you back a new Task (which we often refer to as a proxy) which represents the eventual completion of the inner task.  Similarly, calling Unwrap on a Task<Task<TResult>> gives you back a new Task<TResult> which represents the eventual completion of that inner task. (In both cases, if the outer task is Faulted or Canceled, there is no inner task, since there’s no result from a task that doesn’t run to completion, so the proxy task then represents the state of the outer task.)

var t = Task.Run(async delegate
{
await Task.Delay(1000);
return 42;
});

the type of ‘t’ is Task<int>, and the implementation of this overload of Task.Run is basically equivalent to:

var t = Task.Factory.StartNew(async delegate
{
await Task.Delay(1000);
return 42;
}, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Unwrap();

 

int result = await Task.Factory.StartNew(async delegate
{
await Task.Delay(1000);
return 42;
}, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Unwrap();

or, instead of using Unwrap, I could use a second await:

int result = await await Task.Factory.StartNew(async delegate
{
await Task.Delay(1000);
return 42;
}, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

await await” here is not a typo. Task.Factory.StartNew is returning a Task<Task<int>>. Await’ing that Task<Task<int>> returns a Task<int>, and awaiting that Task<int> returns an int.

The ‘await’ keyword has nothing to do with invoking methods in this regard… nothing.  It doesn’t influence how a method is invoked, nor is it somehow associated by the compiler with a subsequent method call.

await keyword isn’t operating on the method or somehow influencing the method’s invocation.  Rather, it’s operating on the result of the method’s invocation.  The statement:

await FooAsync();

is functionally identical to:

var t = FooAsync();
await t;

just as:

return Foo();

is functionally identical to:

var t = Foo();
return t;

Interlocked.CompareExchange

Compares two 32-bit signed integers for equality and, if they are equal, replaces the first value.

public static int CompareExchange(
	ref int location1,
	int value,
	int comparand
)

If comparand and the value in location1 are equal, then value is stored in location1. Otherwise, no operation is performed. The compare and exchange operations are performed as an atomic operation. The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.

 The following code example demonstrates a thread-safe method that accumulates a running total. The initial value of the running total is saved, and then the CompareExchange method is used to exchange the newly computed total with the old total. If the return value is not equal to the saved value of the running total, then another thread has updated the total in the meantime. In that case, the attempt to update the running total must be repeated.

In many scenarios, it is useful to enable a Task<TResult> to represent an external asynchronous operation. TaskCompletionSource<TResult> is provided for this purpose. It enables the creation of a task that can be handed out to consumers, and those consumers can use the members of the task as they would any other.

 

Nano Server

 

.NET Framework 4.6 and 4.5 – walk-through – (Part 10)

To ensure predictable behavior, all transactions must possess the basic ACID properties (atomic, consistent, isolated, and durable). These properties reinforce the role of mission-critical transactions as all-or-none propositions.

You can utilize the explicit programming model by using the Transaction class, or the implicit programming model in which transactions are automatically managed by the infrastructure, by using the TransactionScope class. It is recommended that you use the implicit transaction (TransactionScope) model for development.

Due to its ease of use and efficiency, it is recommended that you use the TransactionScope class when developing a transaction application.

scope.Complete()

The Complete method commits the transaction. If an exception has been thrown, Complete is not called and the transaction is rolled backFailing to call this method aborts the transaction, because the transaction manager interprets this as a system failure, or equivalent to an exception thrown within the scope of transaction. However, calling this method does not guarantee that the transaction will be committed. It is merely a way of informing the transaction manager of your status.

The using statement ensures that the Dispose method of the TransactionScope object is called even if an exception occurs.

rollback a transaction

If you want to rollback a transaction, you should not call the Complete method within the transaction scope. For example, you can throw an exception within the scope. The transaction in which it participates in will be rolled back.

 TransactionScope Options

CommittableTransaction

To commit the transaction, you need to explicitly call the Commit method. For rolling back a transaction, you should call the Rollback method. It is important to note that until a CommittableTransaction has been committed or rolled back, all the resources involved in that transaction are still locked. It is up to the application developer to handle exceptions and specifically call the Rollback(Exception) method in case of failures.

You can call BeginCommit to dispatch the commit holdup to a thread from the thread pool. You can also call EndCommit to determine if the transaction has actually been committed.

Traces are the publishing of specific messages that are generated during application execution.

Trace Level Description
Critical Serious failures, such as the following, have occurred:

  • An error that can cause an immediate loss in user functionality.
  • An event that requires an administrator to take action to avoid loss of functionality.
  • Code hangs.
  • This tracing level can also provide sufficient context for interpreting other critical traces. This can help to identify the sequence of operations leading to a serious failure.
Error An error (for example, invalid configuration or network behavior) has occurred that can result in a loss of user functionality.
Warning A condition exists that can subsequently result in an error or critical failure (for example, allocation failing or approaching a limit). Normal processing of errors from user code (for example, transaction aborted, timeouts, authentication failed) can also generate a warning.
Information Messages helpful for monitoring and diagnosing system status, measuring performance, or profiling are generated. These can include transaction and enlistment lifetime events, such as a transaction being created or committed, the crossing of a significant boundary, or the allocation of significant resources. A developer can then utilize such information for capacity planning and performance management.

 

When you as an administrator turn on tracing, sensitive information might be written to a trace log that is publicly viewable by default. To mitigate any possible security threat, you should consider storing the trace log in a secure location controlled by share and file system access permissions.

Post build event execute powershell

if $(ConfigurationName) == Debug (
“C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe” -file “$(ProjectDir)\$(ProjectName).ps1” $(TargetDir)
) ELSE (
echo “This is a release build.”.
)

You will typically use Windows authentication with an application deployed on a corporate intranet. Forms authentication means that you must include login controls in your application and pass the acquired credentials to the authentication provider. You will typically use forms authentication with an application deployed on the Internet.

To validate a user, you call the static Membership.ValidateUser method.

When using Windows authentication, you must pass empty strings or null as the parameters of the ValidateUser method. When using Windows authentication, this method call will always return true.

With forms authentication, the ValidateUser method will return a value indicating whether the remote service has authenticated the user. If validation is successful, an authentication cookie is stored on the local hard disk. This cookie is used to confirm validation when accessing the roles and settings services.

All client application services APIs are synchronous. Client application services do not directly support asynchronous behavior.

Determine Which .NET Framework Versions Are Installed https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx#net_b

csc.exe will do the job.

Authentication Services

Logout deletes the local authentication cookie so that login will be required when the application is restarted. After logout, the event handler restarts the application. When the application restarts, it displays the welcome message followed by the login dialog box. The welcome message makes it clear that the application has restarted. This prevents potential confusion if the user must log in to save settings, and then must log in again because the application has restarted.

The value of the Console.In property is a System.IO.TextReader object, whereas the values of the Console.Out and Console.Error properties are System.IO.TextWriter objects. You can associate these properties with streams that do not represent the console, making it possible for you to point the stream to a different location for input or output. For example, you can redirect the output to a file by setting the Console.Out property to a System.IO.StreamWriter, which encapsulates a System.IO.FileStream by means of the Console.SetOut method. The Console.In and Console.Out properties do not need to refer to the same stream.

WCF provides ASP.NET compatibility mode to grant developers full access to the features in the ASP.NET HTTP pipeline when writing WCF services. To use this mode, you must set the aspNetCompatibilityEnabled attribute to true in the <serviceHostingEnvironment> section of web.config. Additionally, any service in this appDomain needs to have the RequirementsMode property on its AspNetCompatibilityRequirementsAttribute set to Allowed or Required. By default AspNetCompatibilityRequirementsAttribute is now set to Allowed.

WCF supports for true asynchronous streaming where the send side now does not block threads if the receive side is not reading or slow in reading thereby increasing scalability. Removed the limitation of message buffering when a client sends a streamed message to an IIS hosted WCF service.

WCF – An HTTPS protocol mapping has been added to simplify exposing an endpoint over HTTPS. To enable an HTTPS endpoint, ensure your website has an HTTPS binding and SSL certificate configured, and then simply enable HTTPS for the virtual directory that hosts the service. If metadata is enabled for the service, it will be exposed over HTTPS as well.

WebSockets is a technology that provides true bidirectional communication over ports 80 and 443 with performance characteristics similar to TCP.

The following table describes the settings that have changed and where to find additional information.

Client applications use the ChannelFactory<TChannel> class to create a communication channel with a WCF service.

In a WCF project, data types defined in XML (such as are exposed in a service) can be pasted directly into a code page. The XML type will be pasted as a CLR type.

IHttpCookieContainerManager makes working with cookies on the client side much easier. When AllowCookies is set to true on the binding, you can access cookies by using the following code: