Showing posts with label vs for mac. Show all posts
Showing posts with label vs for mac. Show all posts

Sunday, May 19, 2019

Error with Cert when starting an Asp.Net core website on the Mac

On my Mac I tried to run a Asp.Net core web site and got an error when starting the web site about ssl cert was invalid.

Adding the certificate to the Trusted Root Certficates store failed with the following error: Failed with a critical error.

The sites were working a few days before so I tried this command line.

     

dotnet dev-certs https --trust


Got a response A valid HTTPS certificate is already present.

Ran app again and still got same error.


The way I fixed it on my Mac was to open the KeyChain Access app and deleted the localhost certificate




Ran 

dotnet dev-certs https --trust 




After this I was able to debug my asp.net core apps in vs for Mac 2019 and Rider



Sunday, April 8, 2018

Asp.Net Core 2 Configuration Values

In this blog post I will show you how to access the site settings in an asp.net core 2.0 website.  I am using Visual Studio for the Mac to doing the coding but it should work the same in the windows version of Visual Studio.

Configuration values are store in the file appsettings.json.   It is a json based configuration file.  An example file could look something like this.

{
  "NumberOfItemsToShow": 20,
  "Title": "Demo Application",
  "Topics": ["Asp.net","Asp.net core", ".net core", "Xamarin"],
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}


In asp.net you stored your app settings in a file called web.config.  If you wanted different values for different environments you wrote a config transform to change the value for that environment.  In asp.net core you create a appsettings.[environment name].json to overwrite values for the other environment.


To start off we are going to create a class to hold our config values.  I am going to call it SiteSettings.

using System;
using System.Collections.Generic;
namespace SettingsDemo.Models
{
    public class SiteSettings
    {
        public int NumberOfItemsToShow { get; set; }
        public string Title { get; set; }

        public List<string> Topics { get; set; }
    }
}


Now in the file startup.cs we need to update the startup function to get the hosting environment and load the config values.

        private readonly IHostingEnvironment hostingEnvironment;


        public Startup(IHostingEnvironment env, IConfiguration config)
        {
            var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath)
               .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
               .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
               .AddEnvironmentVariables(); 
            hostingEnvironment = env;
            Configuration = config;
        }


To load the setting we need to change the Configure Service method.


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<SiteSettings>(Configuration);
            services.AddMvc();
        }


Finally we need to use dependency injection to get access to them in the controller we need to use them in.


        private SiteSettings siteSettings;

        public HomeController(IOptions<SiteSettings> settings)
        {
            siteSettings = settings.Value;
            
        }


Hope this helps

You can find the sample code on GitHub

https://github.com/vb2ae/AspNetCoreConfiguration

Saturday, April 7, 2018

Visual Studio for Mac MSTests project wont load

I opened a Xamarin Forms project I created on a windows pc with visual studio for Mac.




Besides the UWP version of the app not being able to load the MS Tests unit tests could not be loaded either.  Since I really need the unit tests to run I edited the project so it would work.

This is the original

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.props" Condition="Exists('..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{11CF56D3-607A-4251-B491-E88D59114CFE}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>App4.test</RootNamespace>
<AssemblyName>App4.test</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\MSTest.TestFramework.1.2.0\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll</HintPath>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\MSTest.TestFramework.1.2.0\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="UnitTest1.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.props'))" />
<Error Condition="!Exists('..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.targets'))" />
</Target>
<Import Project="..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.targets" Condition="Exists('..\packages\MSTest.TestAdapter.1.2.0\build\net45\MSTest.TestAdapter.targets')" />
</Project>

I changed the project to a dot net core unit test project by editing the project file.  Here is what I changed it to.  The updated test project uses MS Test V2


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>

    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0-preview-20170628-02" />
    <PackageReference Include="MSTest.TestAdapter" Version="1.1.18" />
    <PackageReference Include="MSTest.TestFramework" Version="1.1.18" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\App4\App4\App4.csproj" />
  </ItemGroup>
</Project>

Sunday, March 25, 2018

ASP.Net core 2 caching

With classic Asp.Net you used the HtppContext in the System.Web namespace for caching. Since Asp.Net Core was created to be cross platform caching is done differently.

I am using Visual Studio for Mac to do this but it will work the same in Visual Studio 2017 (for windows).

Lets create a new Asp.Net core application





Once the app is created go to the startup.cs class. and change the ConfigureServices method to this

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddMemoryCache();
        }
  


Now to use this we need to get access to the IMemoryCache in the controllers constructor.  In the demo I will use the about page in the project created

        IMemoryCache caching= null;


        public HomeController(IMemoryCache cache)
        {
            caching = cache;
        }

To use it. I am just going to cache the DateTime

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";
            DateTime currentTime;
            if (!caching.TryGetValue<DateTime>("currentTime", out currentTime))
            {
                currentTime = DateTime.Now;
                caching.Set<DateTime>("currentTime", currentTime, DateTimeOffset.Now.AddMinutes(10));
            }
        
                
            ViewBag.Time = currentTime;

            return View();
        }

To cache something use the Set method.  I would recommend using the version that allow you to specify the type of object.

When setting the cache you pass in the key, what you want cached and optionally how long you want it cached.  I set it to 10 minutes in this example.

Getting items from the cache you use TryGetValue it will return true if the value was found and it passes it out in an out parameter.

If you need to remove something use the cache Remove method where you pass in the key of the object you want to remove.

To show the item is cached I changed the About.cshtml to show the current date time and the cached value

@{
    ViewData["Title"] = "About";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>

<p>Use this area to provide additional information.</p>
@DateTime.Now
<br/>
@ViewBag.Time





Please be sure to check out my course on Packt about asp.net core to learn more about asp.net core