Restoring and Building & MSBuild

Restoring and Building with MSBuild ”; Previous Next In this chapter, we will discuss how to restore and build your MSBuild (*.csproj) file using the command line utility. To see what commands are available in .NET Core 2.0 preview 1, let us run the following command. dotnet help You will see all the commands like new, restore, build, etc. Following is the default implementation in Program.cs file. using System; namespace MSBuild { class Program { static void Main(string[] args) { Console.WriteLine(“Hello World!”); } } } Let us now execute the following command to see the progress. dotnet build You will see a lot of errors. These errors need to be rectified. Let us now run the following command. dotnet restore You can see that all the packages are restored. Some new folders and files have also been generated. To see the directory structure, let us run the following command. tree /f Following is the directory structure − Let us now rebuild the project running the following command again. dotnet build Now you project will build successfully without any error(s) and MSBuild.dll is also created. To see the output, let us run the following command − dotnet run You can see the following output on your console. Print Page Previous Next Advertisements ”;

.NET Core – Garbage Collection

.NET Core – Garbage Collection ”; Previous Next In this chapter, we will cover the concept of Garbage collection which is one of most important features of the .NET managed code platform. The garbage collector (GC) manages the allocation and release of memory. The garbage collector serves as an automatic memory manager. You do not need to know how to allocate and release memory or manage the lifetime of the objects that use that memory An allocation is made any time you declare an object with a “new” keyword or a value type is boxed. Allocations are typically very fast When there isn’t enough memory to allocate an object, the GC must collect and dispose of garbage memory to make memory available for new allocations. This process is known as garbage collection. Advantages of Garbage Collection Garbage Collection provides the following benefits − You don’t need to free memory manually while developing your application. It also allocates objects on the managed heap efficiently. When objects are no longer used then it will reclaim those objects by clearing their memory, and keeps the memory available for future allocations. Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field. It also provides memory safety by making sure that an object cannot use the content of another object. Conditions for Garbage Collection Garbage collection occurs when one of the following conditions is true. The system has low physical memory. The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs. The GC.Collect method is called and in almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing. Generations The .NET Garbage Collector has 3 generations and each generation has its own heap that that is used for the storage of allocated objects. There is a basic principle that most objects are either short-lived or long-lived. Generation First (0) In Generation 0, objects are first allocated. In this generation, objects often don’t live past the first generation, since they are no longer in use (out of scope) by the time the next garbage collection occurs. Generation 0 is quick to collect because its associated heap is small. Generation Second (1) In Generation 1, objects have a second chance space. Objects that are short-lived but survive the generation 0 collection (often based on coincidental timing) go to generation 1. Generation 1 collections are also quick because its associated heap is also small. The first two heaps remain small because objects are either collected or promoted to the next generation heap. Generation Third (2) In Generation 2, all long objects are lived and its heap can grow to be very large. The objects in this generation can survive a long time and there is no next generation heap to further promote objects. The Garbage Collector has an additional heap for large objects known as Large Object Heap (LOH). It is reserved for objects that are 85,000 bytes or greater. Large objects are not allocated to the generational heaps but are allocated directly to the LOH Generation 2 and LOH collections can take noticeable time for programs that have run for a long time or operate over large amounts of data. Large server programs are known to have heaps in the 10s of GBs. The GC employs a variety of techniques to reduce the amount of time that it blocks program execution. The primary approach is to do as much garbage collection work as possible on a background thread in a way that does not interfere with program execution. The GC also exposes a few ways for developers to influence its behavior, which can be quite useful to improve performance. Print Page Previous Next Advertisements ”;

.NET Core – Discussion

Discuss .NET Core ”; Previous Next .NET Core is the latest general purpose development platform maintained by Microsoft. It works across different platforms and has been redesigned in a way that makes .NET fast, flexible and modern. .NET Core happens to be one of the major contributions by Microsoft. Developers can now build Android, iOS, Linux, Mac, and Windows applications with .NET, all in Open Source. Print Page Previous Next Advertisements ”;

Managed Extensibility Framework

Managed Extensibility Framework ”; Previous Next In this chapter, we will discuss the Managed Extensibility Framework (MEF). MEF can be used for third-party plugin extensibility, or it can bring the benefits of a loosely-coupled plugin-like architecture to regular applications. MEF is a library for creating lightweight, extensible applications. It allows application developers to discover and use extensions with no configuration required. MEF is an integral part of the .NET Framework 4, and is available wherever the .NET Framework is used that improves the flexibility, maintainability and testability of large applications. You can use MEF in your client applications, whether they use Windows Forms, WPF, or any other technology, or in server applications that use ASP.NET. MEF has been ported as Microsoft.Composition to .NET Core as well but partially. Only System.Composition is ported, and System.ComponentModel.Composition is not available yet. This means, we don’t have the catalogs which can load types from assemblies in a directory. In this chapter, we will only learn how we can use MEF in .NET Core application. Let us understand a simple example in which we will use MEF in .NET Core console application. Let us now create a new .NET Core console project. In the left pane, select Templates → Visual C# → .NET Core and then in the middle pane, select Console Application (.NET Core). Enter the name of the project in the Name field and click OK. Once the project is created, we need to add reference of Microsoft.Composition so that we can use MEF. To do so, let us right-click on the project in Solution Explorer and Manage NuGet Packages… Search for Microsoft.Composition and click Install. Click the OK button. Click the I Accept button. When the installation completes, you will find an error in References. Let us open the project.json file. { “version”: “1.0.0-*”, “buildOptions”: { “emitEntryPoint”: true }, “dependencies”: { “Microsoft.Composition”: “1.0.30”, “Microsoft.NETCore.App”: { “type”: “platform”, “version”: “1.0.1” } }, “frameworks”: { “netcoreapp1.0”: { “imports”: “dnxcore50” } } } You can see that the Microsoft.Composition dependency is added, but the problem is that this package is not compatible with dnxcore50. So we need to import portablenet45+win8+wp8+wpa81. Let us now replace your project.json file with the following code. { “version”: “1.0.0-*”, “buildOptions”: { “emitEntryPoint”: true }, “dependencies”: { “Microsoft.Composition”: “1.0.30”, “Microsoft.NETCore.App”: { “type”: “platform”, “version”: “1.0.1” } }, “frameworks”: { “netcoreapp1.0”: { “imports”: “portable-net45+win8+wp8+wpa81” } } } Save this file and you will see that the error is rectified. If you expand the References, then you will see a reference of Microsoft.Composition. First we need to create an interface that is to be exported and implement the interface and decorate the class with the export attribute. Let us now add a new class. Enter the name for your class in the Name field and click Add. Let us add the following code in the PrintData.cs file. using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading.Tasks; namespace MEFDemo { public interface IPrintData { void Send(string message); } [Export(typeof(IPrintData))] public class PrintData : IPrintData { public void Send(string message) { Console.WriteLine(message); } } } As mentioned above, Catalogs are not available in Microsoft.Composition namespace. So, it will load all the types from the Assembly with export attribute and attach to the import attribute as shown in the Compose method in the Program.cs file. using System; using System.Collections.Generic; using System.Composition; using System.Composition.Hosting; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace MEFDemo { public class Program { public static void Main(string[] args) { Program p = new Program(); p.Run(); } public void Run() { Compose(); PrintData.Send(“Hello,this is MEF demo”); } [Import] public IPrintData PrintData { get; set; } private void Compose() { var assemblies = new[] { typeof(Program).GetTypeInfo().Assembly }; var configuration = new ContainerConfiguration() .WithAssembly(typeof(Program).GetTypeInfo().Assembly); using (var container = configuration.CreateContainer()) { PrintData = container.GetExport<IPrintData>(); } } } } Let us now run your application and you will see that it is running by instantiating the PrintData class. To learn more about MEF, let us visit the following Url https://msdn.microsoft.com/en-us/library/dd460648%28v=vs.110%29.aspx for more details. Print Page Previous Next Advertisements ”;

Create .NET Standard Library

.NET Core – Create .NET Standard Library ”; Previous Next A class library defines the types and methods that can be called from any application. A class library developed using .NET Core supports the .NET Standard Library, which allows your library to be called by any .NET platform that supports that version of the .NET Standard Library. When you finish your class library, you can decide whether you want to distribute it as a third-party component, or whether you want to include it as a component that is bundled with one or more applications. Let us start by adding a class library project in our Console application; right-click on the src folder in Solution Explorer and select Add → New Project… In the Add New Project dialog box, choose the .NET Core node, then choose the Class Library (.NET Core) project template. In the Name text box, enter “UtilityLibrary” as the name of the project, as the following figure shows. Click OK to create the class library project. Once the project is created, let us add a new class. Right-click on project in Solution Explorer and select Add → Class… Select class in the middle pane and enter StringLib.cs in the name and field and then click Add. Once the class is added, then replace the following code in StringLib.cs file. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace UtilityLibrary { public static class StringLib { public static bool StartsWithUpper(this String str) { if (String.IsNullOrWhiteSpace(str)) return false; Char ch = str[0]; return Char.IsUpper(ch); } public static bool StartsWithLower(this String str) { if (String.IsNullOrWhiteSpace(str)) return false; Char ch = str[0]; return Char.IsLower(ch); } public static bool StartsWithNumber(this String str) { if (String.IsNullOrWhiteSpace(str)) return false; Char ch = str[0]; return Char.IsNumber(ch); } } } The class library, UtilityLibrary.StringLib, contains some methods like, StartsWithUpper, StartsWithLower, and StartsWithNumber which returns a Boolean value that indicates whether the current string instance begins with an uppercase, lowercase and number respectively. In .NET Core, the Char.IsUpper method returns true if a character is in uppercase, the Char.IsLower method returns true if a character is in lowercase, and similarly the Char.IsNumber method returns true if a character is a numeric. On the menu bar, choose Build, Build Solution. The project should compile without error. Our .NET Core console project doesn”t have access to our class library. Now to consume this class library we need to add reference of this class library in our console project. To do so, expand FirstApp and right-click on References and select Add Reference… In the Reference Manager dialog box, select UtilityLibrary, our class library project, and then click OK. Let us now open the Program.cs file of the console project and replace all of the code with the following code. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using UtilityLibrary; namespace FirstApp { public class Program { public static void Main(string[] args) { int rows = Console.WindowHeight; Console.Clear(); do { if (Console.CursorTop >= rows || Console.CursorTop == 0) { Console.Clear(); Console.WriteLine(“nPress <Enter> only to exit; otherwise, enter a string and press <Enter>:n”); } string input = Console.ReadLine(); if (String.IsNullOrEmpty(input)) break; Console.WriteLine(“Input: {0} {1,30}: {2}n”, input, “Begins with uppercase? “, input.StartsWithUpper() ? “Yes” : “No”); } while (true); } } } Let us now run your application and you will see the following output. For better understanding, let us make use of the other extension methods of your class library in your project. Print Page Previous Next Advertisements ”;

Running Tests in Visual Studio

.NET Core – Running Tests in Visual Studio ”; Previous Next In this chapter, we will discuss how to run tests in Visual Studio. The .NET Core has been designed with testability in mind, so that creating unit tests for your applications is easier than ever before. In this chapter, we will run and execute our test project in Visual Studio. Let us open the FirstApp solution in Visual Studio. You can see that it has only two projects and you will not be able to see the test project because we haven’t added that project in our solution. Let us add a folder first and call it test. Right-click on the test folder. Select project.json file and click Open. The following screenshot shows the code in Tests.cs file as output. It is the default implementation and it is just testing that True is equal to true. It is the xUnit testing framework and you will see the Fact attribute that annotates and denotes the test method. using System; using Xunit; namespace Tests { public class Tests { [Fact] public void Test1() { Assert.True(true); } } } Following is the implementation of project.json file. { “version”: “1.0.0-*”, “buildOptions”: { “debugType”: “portable” }, “dependencies”: { “System.Runtime.Serialization.Primitives”: “4.1.1”, “xunit”: “2.1.0”, “dotnet-test-xunit”: “1.0.0-rc2-192208-24” }, “testRunner”: “xunit”, “frameworks”: { “netcoreapp1.0”: { “dependencies”: { “Microsoft.NETCore.App”: { “type”: “platform”, “version”: “1.0.1” } }, “imports”: [ “dotnet5.4”, “portable-net451+win8″ ] } } } In project.json file, the most important dependency to the testing framework is the xunit, which brings in the Fact attribute. It brings in the testing framework and APIs for testing with xunit. We also have the dotnet-test-xunit, this is an adopter so that xunit can work with .NET Core, specifically with dotnet test command line utility. Then you will see the testRunner which will run xunit and you can also see the netcoreapp1.0 framework. You will see the .NETCore.App dependeny below. To run test in Visual Studio, let us open Test Explorer from the Test → Window → Test Explorer menu option. And you can see that Visual Studio automatically detects the test. The name of the test consists of namespace.className.TestMethodName. Let us now click on Run All button in Test Explorer. It will first build the code and the run the test and you will see the total time taken by the test. Let us change the test method so that we can see the output when the test fails. using System; using Xunit; namespace Tests { public class Tests { [Fact] public void Test1() { Assert.True(false); } } } Let us execute the test again by clicking on the Run All button link. You can now see the test failure. Print Page Previous Next Advertisements ”;

.NET Core – Portable Class Library

.NET Core – Portable Class Library ”; Previous Next In this chapter, we will discuss what is PCL (Portable Class Library), and also why we need PCL. To understand this concept, let us open the class library project folder which we have created in the previous chapter. In this folder, you can see that in addition to project.json and CS files we also have *.xproj file, and that is because Visual Studio setup .NET Core project type as *.xproj instead of *.csproj. As mentioned by Microsoft, *.xproj will be going away, but it is still here in preview 2 tooling. As we have covered that UWP application uses the *.csproj. Now it is actually not feasible to get *.csproj to reference and *.xproj and that functionality is not going to be implemented because *.xproj will move out. So instead, we need a class library which can be shared between the console app and the UWP app and here comes PCL. What is PCL Let us now understand what PCL is − The Portable Class Library project enables you to write and build managed assemblies that work on more than one .NET Framework platform. You can create classes that contain code you wish to share across many projects, such as shared business logic, and then reference those classes from different types of projects. It can also help you build cross-platform apps and libraries for Microsoft platforms quickly and easily. Portable class libraries can help you reduce the time and costs of developing and testing code. Use this project type to write and build portable .NET Framework assemblies, and then reference those assemblies from apps that target multiple platforms such as Windows and Windows Phone, etc. Let us now remove the class library which we have created from the Solution Explorer. At the same time, delete it from the Solution folder and further add a new project item. Select the Visual C# → Windows template in the left pane and select Class Library (Portable) in the middle pane. Enter StringLibrary in the name field and click OK to create this project. Now we need to select the target frameworks to reference. Let us select Windows Universal and ASP.NET Core for a moment then we will retarget it. Click OK. You can see that it has created a new project in PCF format. Let us now right-click StringLibrary project in the Solution Explorer and select Properties. Click on the Target .NET Platform Standard. Click Yes; it is now the same class library with one minor difference. The difference is that it can be used by UWP as well, because it contains *.csproj file instead of *.xproj. Let us now add a new class; for this, you need to right-click on project in Solution Explorer and select Add → Class… Select class in the middle pane and enter StringLib.cs in the name field and then Click Add. Once the class is added, then replace the following code in StringLib.cs file. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StringLibrary { public static class StringLib { public static bool StartsWithUpper(this String str) { if (String.IsNullOrWhiteSpace(str)) return false; Char ch = str[0]; return Char.IsUpper(ch); } public static bool StartsWithLower(this String str) { if (String.IsNullOrWhiteSpace(str)) return false; Char ch = str[0]; return Char.IsLower(ch); } public static bool StartsWithNumber(this String str) { if (String.IsNullOrWhiteSpace(str)) return false; Char ch = str[0]; return Char.IsNumber(ch); } } } Let us build this portable class library project and it should compile without error. Now we need to add reference of this portable class library in our console project. So, expand FirstApp and right-click on References and select Add Reference… In the Reference Manager dialog box, select StringLibrary which is our portable class library project, and then click OK. You can see that the StringLibrary reference is added to the console project and it can be seen in the project.json file as well. You can now run the application again and you will see the same output. Let us now use the other extension methods of your portable class library in your project. The same portable library will be consumed in your UWP application as well. Print Page Previous Next Advertisements ”;

Creating a Xamarin.Forms Project

Creating a Xamarin.Forms Project ”; Previous Next In this chapter, we will discuss how to consume the NuGet package which we have created and published to a private NuGet feed. So, first we will create a Xamarin.Forms project. We need to first understand what is Xamarin.Forms. Xamarin.Forms is a framework that allows developers to rapidly create crossplatform user interfaces. Xamarin.Forms is a cross-platform natively backed UI toolkit abstraction that allows developers to easily create user interfaces that can be shared across Android, iOS, Windows, and Windows Phone. The user interfaces are rendered using the native controls of the target platform, allowing Xamarin.Forms applications to retain the appropriate look and feel for each platform. To start Xamarin.Forms, we need some additional features in Visual Studio 2015. Let us modify your Visual Studio 2015 and make sure the following cross-platform mobile development option is selected. Once the installation is finished, let us update the Xamarin by selecting Tools → Options… Scroll down and expand Xamarin in the left pane and then select Other. On top right hand corner of the dialog box, click on Check Now to see if updates are available. You can see that updates are available, let us click on the Download button to start downloading. Once downloading is finished, you will be notified to install the updates. Let us now open the Visual studio again and select the File → New → Project… menu option. In the left pane, select the Visual C# → Cross-Platform template and in the middle pane, select Blank Xaml App (Xamarin.Forms Portable). Enter the name in the Name field and click OK. Select the Target Version and the Minimum Version and click OK. You will see a series of projects; at the top we have the PCL library which will be shared among all platforms like Android, iOS, UWP, Windows 8.1, and Windows Phone 8.1. Here, we will focus on the PCL library and will bring some code here. Let us expand the code. In this Xamarin.Forms template, you can see the generic App.xaml and MainPage.xaml, uses Xamarin.Forms XAML framework which works across these platforms. We need to import our codes and we also need the private NuGet feed we set up in the last chapter. Let us now open the NuGet Package Manager. Click on the wheel next to the Package source dropdown list. We need to add our private feed here, let us click on the plus (+) button. You will see that another checkbox is added in the Available package sources section, let us specify a name and source path and click OK. Let us now go to the Browse tab and select PrivateSource from the Package source dropdown list and you will see the StringLibrary NuGet package. Select StringLibrary and click Install. Click OK and you will see one error. We can’t use library with .NETPortable profile version 259, we will be fixing this error in the next chapter. Print Page Previous Next Advertisements ”;

.NET Core – Prerequisites

.NET Core – Prerequisites ”; Previous Next In this chapter, we will discuss the various dependencies that you need to deploy and run. These include the .NET Core applications on Windows machines that are developed using Visual Studio. Supported Windows Versions .NET Core is supported on the following versions of Windows − Windows 7 SP1 Windows 8.1 Windows 10 Windows Server 2008 R2 SP1 (Full Server or Server Core) Windows Server 2012 SP1 (Full Server or Server Core) Windows Server 2012 R2 SP1 (Full Server or Server Core) Windows Server 2016 (Full Server, Server Core or Nano Server) Dependencies If you are running your .NET Core application on Windows versions earlier than Windows 10 and Windows Server 2016, then it will also require the Visual C++ Redistributable. This dependency is automatically installed for you if you use the .NET Core installer. You need to manually install the Visual C++ Redistributable for Visual Studio 2015 if you are installing .NET Core via the installer script or deploying a self-contained .NET Core application. For Windows 7 and Windows Server 2008 machines, you need to make sure that your Windows installation is up-to-date and also includes hotfix KB2533623 installed through Windows Update. Prerequisites with Visual Studio To develop .NET Core applications using the .NET Core SDK, you can use any editor of your choice. However, if you want to develop .NET Core applications on Windows using Visual Studio, you can use the following two versions − Visual Studio 2015 Visual Studio 2017 RC Projects created with Visual Studio 2015 will be project.json-based by default while projects created with Visual Studio 2017 RC will always be MSBuild-based. Print Page Previous Next Advertisements ”;

.NET Core – Numerics

.NET Core – Numerics ”; Previous Next .NET Core supports the standard numeric integral and floating-point primitives. It also supports the following types − System.Numerics.BigInteger which is an integral type with no upper or lower bound. System.Numerics.Complex is a type that represents complex numbers. A set of Single Instruction Multiple Data (SIMD)-enabled vector types in the System.Numerics namespace. Integral types .NET Core supports both signed and unsigned integers of different ranges from one byte to eight bytes in length. All integers are value types. The following table represents the integral types and their size; Type Signed/ Unsigned Size (bytes) Minimum Value Maximum Value Byte Unsigned 1 0 255 Int16 Signed 2 −32,768 32,767 Int32 Signed 4 −2,147,483,648 2,147,483,647 Int64 Signed 8 −9,223,372,036,854,775,808 9,223,372,036,854,775,807 SByte Signed 1 -128 127 UInt16 Unsigned 2 0 65,535 UInt32 Unsigned 4 0 4,294,967,295 UInt64 Unsigned 8 0 18,446,744,073,709,551,615 Each integral type supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators. You can also work with the individual bits in an integer value by using the System.BitConverter class. Floating-point types .NET Core includes three primitive floating point types, which are shown in the following table. Type Size (bytes) Minimum Value Maximum Value Double 8 −1.79769313486232e308 1.79769313486232e308 Single 4 −3.402823e38 3.402823e38 Decimal 16 −79,228,162,514,264,337,593,5 43,950,335 79,228,162,514,264,337,593,543,9 50,335 Each floating-point type supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators. You can also work with the individual bits in Double and Single values by using the BitConverter class. The Decimal structure has its own methods, Decimal.GetBits and Decimal.Decimal(Int32()), for working with a decimal value”s individual bits, as well as its own set of methods for performing some additional mathematical operations. BigInteger System.Numerics.BigInteger is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds. The methods of the BigInteger type is closely parallel to those of the other integral types. Complex The System.Numerics.Complex type represents a complex number, i.e., a number with a real number part and an imaginary number part It supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators, as well as mathematical, algebraic, and trigonometric methods. SIMD The Numerics namespace includes a set of SIMD-enabled vector types for .NET Core. SIMD allows some operations to be parallelized at the hardware level, which results in huge performance improvements in mathematical, scientific, and graphics apps that perform computations over vectors. The SIMD-enabled vector types in .NET Core include the following − System.Numerics.Vector2, System.Numerics.Vector3, and System.Numerics.Vector4 types, which are 2, 3, and 4-dimensional vectors of type Single. The Vector <T> structure that allows you to create a vector of any primitive numeric type. The primitive numeric types include all numeric types in the System namespace except for Decimal. Two matrix types, System.Numerics.Matrix3×2, which represents a 3×2 matrix; and System.Numerics.Matrix4×4, which represents a 4×4 matrix. The System.Numerics.Plane type, which represents a three-dimensional plane, and the System.Numerics.Quaternion type, which represents a vector that is used to encode three-dimensional physical rotations. Print Page Previous Next Advertisements ”;