Showing posts with label Dot Net Core. Show all posts
Showing posts with label Dot Net Core. Show all posts

Friday, September 10, 2021

how to fix "The SSL connection could not be established," in Web Api development with ASP.Net Core and .Net 5.0

I implemented two MicroServices in my local machine,  I try to call one service from another with HttpClient. the error was shown as blew after the service call.

"cound not send data to commandservice with errror The SSL connection could not be established, see inner exception. System.Security.Authentication.AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot   at System.Net.Security.SslStream.SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception)

   at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)"

the error indicated that th SSL connection cannot be established due to certificate issue.

we can the  use the following command to trust the self-singed certificate

dotnet dev-certs https --trust

for more information about this command you can check out the microsoft document website with the link below


https://docs.microsoft.com/en-us/dotnet/core/additional-tools/self-signed-certificates-guide

Friday, March 13, 2020

how to fix "project.assets.json' doesn't have a target for '.NETCoreApp,Version=v3.0"?

After I changed my target framework and rebuild it is fine, then I try to publish my solution again..

then the issue comes up immediately with the following error message.

"Severity    Code    Description    Project    File    Line    Suppression State
Error        Assets file 'C:\Users\admin\source\repos\dandotnetcore\dandotnetcore\obj\project.assets.json' doesn't have a target for '.NETCoreApp,Version=v3.0'. Ensure that restore has run and that you have included 'netcoreapp3.0' in the TargetFrameworks for your project.    dandotnetcore        0
   
"

the root cause of this issue is that i had create the publish profile first, then i changed the target framework. however Visual Studio never update the target framework in the publish profile.



I had to go the publish xml file and manually update it to be netcoreapp3.1







Before

<?xml version="1.0" encoding="utf-8"?>
<!--
This file is used by the publish/package process of your Web project. You can customize the behavior of this process
by editing this MSBuild file. In order to learn more about this please visit https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <WebPublishMethod>FileSystem</WebPublishMethod>
    <PublishProvider>FileSystem</PublishProvider>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish />
    <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
    <ExcludeApp_Data>False</ExcludeApp_Data>
    <ProjectGuid>d30dbc67-142e-4bb0-a07a-5abb280b4ecc</ProjectGuid>
    <publishUrl>C:\Temp\publish</publishUrl>
    <DeleteExistingFiles>True</DeleteExistingFiles>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <SelfContained>false</SelfContained>
  </PropertyGroup>
</Project>




After

<?xml version="1.0" encoding="utf-8"?>
<!--
This file is used by the publish/package process of your Web project. You can customize the behavior of this process
by editing this MSBuild file. In order to learn more about this please visit https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <WebPublishMethod>FileSystem</WebPublishMethod>
    <PublishProvider>FileSystem</PublishProvider>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish />
    <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
    <ExcludeApp_Data>False</ExcludeApp_Data>
    <ProjectGuid>d30dbc67-142e-4bb0-a07a-5abb280b4ecc</ProjectGuid>
    <publishUrl>C:\Temp\publish</publishUrl>
    <DeleteExistingFiles>True</DeleteExistingFiles>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <SelfContained>false</SelfContained>
  </PropertyGroup>
</Project>


how to deploy a dotnet core web api to IIS Server?

my web api was implemented in dot.net core 3.1. i did not have to add services to the container like the previous version of Dot Net Core.





for example we have to use app.UseIISIntegration() in version 2.0

I only have to publish the project to a folder, then set up a new web site with physical path pointing to publish folder.

here is the step to set up the web site for my Dot Net Core Web API.

1. create a new application pool called DotNetCoreAppPool with No Managed Code for .net CLR version






2. create a new website and set the physical to path to publish folder and select the app pool that created in step one.
















Monday, February 24, 2020

A cool tool to validate the yaml content on building the docker-compose.yml file.

after i added a docker-compose project the asp.net solution, then i try to build the docker-compose file to generate all the images.

however i always encounter error without specific message. the root of cause this issue is that
YAML follows indentation structure very strictly. one extra space or tab will cause this issue.

this online tool will be a great help on validation your content in YAML.

https://onlineyamltools.com/validate-yaml

here is my sample docker-compose file, after i pasted it in the yaml box, the line causes the issue highlights immediately in the errors box

version: '3.7'

services:
  webapi_dotnetcore:
    image: ${DOCKER_REGISTRY-}webapidotnetcore
    build:
      context: .
      dockerfile: WebAPI_DotNetCore/Dockerfile

  db:
    image: mcr.microsoft.com/mssql/server
    environment:
         - ACCEPT_EULA=Y
         - SA_PASSWORD=Password_01
  ports:
   - '1433:1433'


Thursday, January 16, 2020

how to quickly setup a swagger in asp.net core Web API project with visual studio

1. Create a ASP.Net web project with Visual studio

2. Install the Swagger package in the Package Manager window

              Install-Package Swashbuckle.AspNetCore

 3. add swagger generator to services collection which is the dependency injection container

        services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
            });

4. setup the swagger in the configure method
         // enable the swagger middleware
           app.UseSwagger();

            // Enable middleware to serve swagger-ui
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

5. launch the app and view the swagger ui from the link below, please note the port will be different

  https://localhost:{port}/swagger/index.html

   for my local development i had the following

     https://localhost:44392/swagger/index.html



Tuesday, April 9, 2019

how to setup a schedule task for DotNet Core Console App?

When we publish the dotnet core project either from publish command in visual studio, or use the command line dotnet publish -c Release -r win10-x64 in CMD window.

after we execute the publish command. we can have the following message from the Visual Studio Output Windows

1>------ Publish started: Project: ConsoleAppEncryptDecrypt, Configuration: Release Any CPU ------
1>ConsoleAppEncryptDecrypt -> C:\Users\ddeng\Source\Repos\ConsoleAppEncryptDecrypt\ConsoleAppEncryptDecrypt\bin\Release\netcoreapp2.1\ConsoleAppEncryptDecrypt.dll
1>ConsoleAppEncryptDecrypt -> C:\Users\ddeng\Source\Repos\ConsoleAppEncryptDecrypt\ConsoleAppEncryptDecrypt\bin\Release\netcoreapp2.1\publish\
1>ConsoleAppEncryptDecrypt was published successfully to bin\Release\netcoreapp2.1\publish\
========== Build: 0 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========
========== Publish: 1 succeeded, 0 failed, 0 skipped ==========

and we can see the compile output in this folder




when we schedule a task with action from this folder. we can use both paths

ConsoleAppEncryptDecrypt\bin\Release\netcoreapp2.1

ConsoleAppEncryptDecrypt\bin\Release\netcoreapp2.1\publish

the schedule task can run succesfully without an error.

However when we move the production server,

if we use this path  ConsoleAppEncryptDecrypt\bin\Release\netcoreapp2.1, the schedule task completed with an error code  3762504530.

the root cause of this issue is that the hosting server do not have the same environment as my local desktop. I have to use the publish folder (ConsoleAppEncryptDecrypt\bin\Release\netcoreapp2.1\publish) which will copy all necessary DLL to folder, in order to run the dotnet core Console app.

Tuesday, August 14, 2018

how to quickly write a console application to delete file within period of time with .Net Core

when we a console application to clean some historical files from the folder, we will add an app settings section in the app.config file in project, which is run under .net framework. however it is much flexible to run with .Net Core.

i will show you my first sample DotNet Core Console App to handle this task.

1. Launch Visual Studio and create a  new project by selecting the Console App (.Net Core)



2.  Open the management studio and select the project, then right click to show the menu, select Add to get the New Item from slide out menu. to add JSon Config file





3.  Open the JSon file and filll with the following information

 {
  "PrintFolder": "the folder you want to delete files",

  "FileExtension": ".pdf",

  "DaysToMaintain":  "15"
}




4. Load the config information into the program using the snippet of code below

IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
var fileExtension = config["FileExtension"];
var daysToKeepFiles = -1* Convert.ToInt32(config["DaysToMaintain"]);
var ltlPrintFolder = config["LTLPrintFolder"];
Console.WriteLine($"ltl print folder path : { ltlPrintFolder}");


5. Use the LINQ to manipulate the logic on what kind of file and Periods based on the file creation time.
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(ltlPrintFolder); IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
 IEnumerable<System.IO.FileInfo> fileQuery =
                from file in fileList
                where file.Extension == fileExtension && file.CreationTime < DateTime.Now.AddMonths(daysToKeepFiles)
                orderby file.Name
                select file;




6. loop through the result from the query

foreach (System.IO.FileInfo fi in fileQuery)
            {
                Console.WriteLine(fi.FullName);
                fi.Delete();
            }


Now you can delete file with Dot Net Core App