Reading appSettings in .NET Core 2 console application

In .NET Core application settings are no longer stored in the app.config file.  We need to use a separate file for this purpose. A common approach is to create an appsettings.json file for storing this kind of information.

Let’s build a simple HelloWorld console app using command line interface (CLI) and any text editor. No Visual Studio is required. This app will read a couple of settings from a config file. You will need to install .NET Core 2 from Microsoft site. BTW, it may work under a different version of the framework, but I only tested it in .NET Core 2.

Let’s navigate to C:\Temp folder, open command prompt and issue this command.

dotnet new console -o Core2Console

It will create a new console application in Core2Console subfolder. Navigate to this subfolder and replace its content with these 3 files:

  1. Program.cs
using System;
using Microsoft.Extensions.Configuration;

namespace Core2Console
{
 // To product EXE use a command like this: dotnet publish -c Release -r win7-x64
 // See: https://docs.microsoft.com/en-us/dotnet/core/deploying/deploy-with-cli
 class Program
 {
   static void Main(string[] args)
   {
     // Adding JSON file into IConfiguration.
     IConfiguration config = new ConfigurationBuilder()
          .AddJsonFile("appsettings.json", true, true)
          .Build();

     // Read configuration
     string FirstName = config["FirstName"];
     string LastName = config["LastName"];
     Console.WriteLine($"Hello {FirstName} {LastName}!");

     var address = config.GetSection("Address");
     string street = address["Street"];
     string city = address["City"];
     string zip = address["Zip"];
     string state = address["State"];
     Console.WriteLine($"Your address is: {street}, {city}, {state} {zip}");
   }
 }
}

2. Core2Console.csproj

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
 <OutputType>Exe</OutputType>
 <TargetFramework>netcoreapp2.0</TargetFramework>
 </PropertyGroup>

<ItemGroup>
 <PackageReference Include="Microsoft.Extensions.Configuration" Version="2.0.0" />
 <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.0.0" />
 <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.0" />
 </ItemGroup>

<ItemGroup>
 <None Update="appsettings.json">
 <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
 </None>
 </ItemGroup>
</Project

3. appsettings.json

{
 "FirstName": "John",
 "LastName": "Smith",

"Address": {
 "Street": "100 Main St",
 "City": "Boston",
 "Zip": "02102",
 "State": "MA"
 }
}

Run the application. It will build and execute the code. When running reads configuration from both individual keys (FirstName, LastName) and a configuration section (Address).

dotnet run

It will output something like this:

C:\Temp\Core2Console>dotnet run
Hello John Smith!
Your address is: 100 Main St, Boston, MA 02102

The CopyToOutputDirectory flag in the project file is important. Without it the settings will always be null.

As we can see reading configuration settings from a file in a console app in .NET Core is not that difficult even it’s not what we used to see for the last 15 years when working with .NET applications.

More on configuration settings from Microsoft.

Advertisements
Posted in .NET | Leave a comment

Set focus the Angular way

If we want to set a focus on a text box in the code from inside a controller method (skipping the use of directives) we can do it this way. A small timeout is usually required to give it some time to settle. Obviously the $timeout service needs to be injected into the controller.

  $timeout(function () { angular.element("#myInputId").trigger("focus"); }, 100);
Posted in Angular, web | Leave a comment

Promises, promises…

This post was inspired by a beautiful article published on WebDevEasy. It contains detailed description of the $q Service implemented by Angular, along with multiple examples on how to use Deferred and Promise objects. I just wanted to take out a single example and present it as a standalone page.

It uses Geo Location services and displays latitude and longitude (if supported by browser/provider) . I placed all code into one HTML file just to conserve space.

The geoService has just one method which invokes  built-in navigator.geolocation.getCurrentPosition() method and passes deferred.resolve() for both success and failure possible outcomes. This method returns a promise object to the caller as the article suggests.

While deferred has methods for changing the state of an operation, a promise exposes only methods needed to handle and figure out the state, but not methods that can change the state. This is why in a function, returning a promise and not a deferred is a good practice. This prevents from external code to interfere the progress or the state of an operation.

        app.factory("geoService", function ($q) {
            function getGeolocationCoordinates() {
                var deferred = $q.defer();
                navigator.geolocation.getCurrentPosition(
                    function (position) { deferred.resolve(position.coords); },
                    function (error) { deferred.resolve(null); }
                );
                return deferred.promise;
            }
            return {
                getGeolocationCoordinates: getGeolocationCoordinates
            };
        });

Controller processes button click by invoking the service method and updating the scope with coordinates it receives. The then() method of promise object replaces the need for a callback we would have used in a traditional approach.

        app.controller("geoCtrl", function ($scope, geoService) {
            function setCoords(coords) {
                if (coords) {
                    $scope.latitude = coords.latitude;
                    $scope.longitude = coords.longitude;
                }
            }
            // Call getGeolocationCoordinates() from the service and pass results to setCoords().
            $scope.getCoordinates = function () {
                geoService.getGeolocationCoordinates().then(setCoords);
            };
        });

That’s it. Very elegant solution…

See it in action.

Posted in Angular, web | Leave a comment

EURO-2016 in Angular

While the Euro-2016 soccer cup is over and Portugal is celebrating its victory over France with a single goal I just decided to visualize playoff results in one group using pure client-side solution based on Angular 1.5 code.

In this interactive page games are listed on the left. Scores can be modified using HTML5 built-in number increment/decrement controls. When a team wins it gets 3 points while a draw brings just 1 point.

Changing the game result will automatically order standings table on the right.
Thus at least on this page I could make Russia to finish first…

http://spwebparts.host56.com/angular/

Posted in Angular, web | Leave a comment

SharePoint 2010: Hiding SIP Address field on User information page

Here is my quick solution — 100% client-side.

1. In HIVE14\TEMPLATE\LAYOUTS folder open userdisp.aspx file in Notepad.

2.  At the bottom of asp:Content ContentPlaceHolderId=”PlaceHolderMain” tag add this Javascript code:

<script type="text/javascript">
var sip_a = document.getElementsByName("SPBookmark_SipAddress");
if (sip_a.length)
{
  var sip_tr = sip_a[0].parentElement.parentElement.parentElement;
  if (sip_tr && sip_tr.nodeName == "TR")
    sip_tr.style.display = "none";
}
</script>

Obviously this way other fields on  User information page can be hidden as well.

Posted in SharePoint 2010 | Leave a comment

Disk Cleanup Wizard add-on

A useful add-on to Disk Cleanup Wizard from Microsoft to remove old Windows updates.

Disk Cleanup Wizard add-on lets users delete outdated Windows updates on Windows 7 SP1 or Windows Server 2008 R2 SP1

http://support.microsoft.com/kb/2852386

Posted in Computers and Internet | Leave a comment

Copying large files between document libraries

Using WebDAV (Explorer mode) seems to be very handy to quickly copy files between document libraries. It works especially well if our farms are on different versions of SharePoint, files don’t  have metadata and don’t need version support. Open 2 windows in Explorer mode for source and destination, drag and drop files between  them and you are done.

One problem exists though. The file size. If it exceeds 50Mb — you’ll get an error:

Error 0x800700DF: The file size exceeds the limit allowed and cannot be saved.

The max upload file size set in CA in the web application settings does not help. This is a client setting in the registry of the computer you are doing file copy operation.

Here is the solution form MS:

1. Click Start, click Run, type regedit, and then click OK.
2. Locate and then click the following registry subkey:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WebClient\Parameters
3. In the right pane, right-click the FileSizeLimitInBytes value, and then click Modify.
4. If you cannot see the FileSizeLimitInBytes value, right-click the blank space in the right pane, click New, click DWORD Value, type FileSizeLimitInBytes, and then click OK.
5. In the Edit DWORD Value box, click to select the Decimal option. In the box under Value data, type a value that is larger than the size of the file that you want to download. Click OK.

Note The default value for the file size limit is 50000000 bytes.
Quit Registry Editor. Restart the computer.

https://support.microsoft.com/kb/900900/en-us?wa=wsignin1.0

Posted in SharePoint | Leave a comment