Thursday, January 24, 2019

Dynamic ASP.NET Core Configurations 🗒️ With Consul KV

It's Very nice post about konsul.

Background

Usually, the configurations in .NET and .NET Core apps are stored in the configuration files, such as App.config and Web.config, or appsettings.json; however, all of them have some disadvantages.
hard-coded configuration files
difficult to manage
For example, if we need to frequently change the configuration files due to some reasons, how can we solve this problem? We cannot modify them one by one if there are lots of machines!

What we want is managing the configuration in one place, the "configuration center". Here are some awesome projects that can help us solve this problem, such as Apollo, Consul, etc.

And in this article, I will introduce three ways using Consul KV store.

Thursday, November 8, 2018

MSSQL search and replace value in all tables

It's little script for replace value in database


declare @from as nvarchar(50);
declare @to as nvarchar(50);

set @from  =[dbo].[getstringUUIDFromString] ('c3a5fb3e-745a-11e8-a209-0050568411f7'); 
set @to  =[dbo].[getstringUUIDFromString] ('c3a5fb3e-745a-11e8-a209-0050568411f7'); 



DECLARE @CURSOR CURSOR;DECLARE @script AS NVARCHAR(MAX);
SET @CURSOR = CURSOR SCROLL
FOR
 SELECT 
 '
 if exists (select top 1 * from  ['+isc.TABLE_CATALOG+'].['+isc.TABLE_SCHEMA+'].['+isc.TABLE_NAME+'] where '+isc.COLUMN_NAME + ' in ('+@from+'))
 begin
 print ''['+isc.TABLE_CATALOG+'].['+isc.TABLE_SCHEMA+'].['+isc.TABLE_NAME+']'';

 
 update ['+isc.TABLE_CATALOG+'].['+isc.TABLE_SCHEMA+'].['+isc.TABLE_NAME+']
 set '+isc.COLUMN_NAME + ' = '+@to+'
 where '+isc.COLUMN_NAME + ' in ('+@from+')
end;
 '
FROM information_schema.columns  isc
where  TABLE_CATALOG='DiachokERP' and TABLE_SCHEMA='dbo'
and data_type = 'binary' and CHARACTER_MAXIMUM_LENGTH=16

OPEN @CURSOR

FETCH NEXT
FROM @CURSOR
INTO @script
 

WHILE @@FETCH_STATUS = 0
BEGIN

 EXEC(@script);
 --print @script
 FETCH NEXT
 FROM @CURSOR
 INTO @script
END
CLOSE @CURSOR
DEALLOCATE @CURSOR;


and converting string from uid to uuid

CREATE function [dbo].[getstringUUIDFromString](@stringUUID as varchar(50))
returns nvarchar(50)
as
begin
--Возврат Сред(GUID, 20, 4) + Прав(GUID, 12) + Сред(GUID, 15, 4) + Сред(GUID, 10, 4) + Лев(GUID, 8);
declare @buffer nvarchar(50)
select @buffer ='0x'+ substring(@stringUUID,20,4)+right(@stringUUID,12)+substring(@stringUUID,15,4)+substring(@stringUUID,10,4)+left(@stringUUID,8)

return @buffer
end

GO

Saturday, October 13, 2018

add packages gdi plus to net core on macos

brew install mono-libgdiplus


I took it here

Sunday, September 2, 2018

Core install

install old drivers

pnputil.exe -i -a .\driversname.inf


install certs

Set-Location -Path Cert:\LocalMachine\Root\
Import-Certificate -FilePath "C:\install\FOR_SQL_1C\certnameshutdown -r.cer"

mount iso with show disk

Mount-DiskImage -ImagePath 'D:\ISO\Windows Server 2012 Trial\9200.16384.WIN8_RTM.120725-1247_X64FRE_SERVER_EVAL_EN-US-HRM_SSS_X64FREE_EN-US_DV5.ISO' -StorageType ISO -PassThru | Get-Volume


update SQL

.\setup.exe /Q /IACCEPTSQLSERVERLICENSETERMS /Action=Upgrade /InstanceName=MSSQLServer

update key(licence) SQL

.\setup.exe /q /ACTION=EditionUpgrade /INSTANCENAME=MSSQLSERVER /PID="insert your key" /IACCEPTSQLSERVERLICENSETERMS

Install patch

.\SQLServer2017-KB4464082-x64.exe /qs /IAcceptSQLServerLicenseTerms /Action=Patch /AllInstances

Sunday, August 5, 2018

Arduino

If You have next error in VS Code
"sketch\build\sketch\build\sketch\build\sketch\build\sketch\build\sketch\build\sketch\build\sketch\build\sketch\build\sketch\build\sketch\build\sketch\build\sketch\build\sketch\build\sketch\build\preproc\ctags_target_for_gcc_minus_e.cpp: The system cannot find the path specified.
[Error] Exit with code=1"

information this https://github.com/Microsoft/vscode/issues/38985
you need change setting.json.
Set "output": "../build"


{
"sketch": "app.ino",
"board": "arduino:avr:leonardoeth",
"output": "../build"
}


and delete all folders in folder "build/sketch"

Friday, June 29, 2018

useful step for ASP Core+Angular

I tried made ASP Core c# & Angular 6 & material.
It is only one good variant:
Download VS Code (work for windows & mac)
Download Node.js
Download SDK .Net Core 2.1
After install Node --> reboot
and install angular/cli https://cli.angular.io/

after
Create core project 'dotnet new webapi -o ProjectName'
Create Angular project 'ng new ProjectName'
Open project in VS Code & install extentions

connect to gitlab

git init
git remote add origin git or https
git add .
git commit -m "Initial commit"
git push -u origin master
//if error try this
git push --set-upstream origin master --force
run angular project 'npm start' -> go to ref 'http://localhost:4200'
If work -> show Angular page

In VSCode add nuget package manager
and add next packages:
- NLog.Web.AspNetCore
- Swashbuckle.AspNetCore.SwaggerGen
- Swashbuckle.AspNetCore.SwaggerUI
- Swashbuckle.AspNetCore.Swagger
- Microsoft.VisualStudio.Web.CodeGeneration.Tools

and add next code to csproj file

<ItemGroup>
    <Content Update="nlog.config">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DocumentationFile>bin\Debug\netcoreapp2.0\WebCoreAPI.xml</DocumentationFile>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <DocumentationFile>bin\Release\netcoreapp2.1\WebCoreAPI.xml</DocumentationFile>
  </PropertyGroup>
change project code



open 'startup.cs' and exchange next code
 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSpaStaticFiles(
                 c =>
     {
         c.RootPath = "wwwroot";
     }
   );
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v0", new Info { Title = "My API v0", Version = "v0" });
                c.SwaggerDoc("v1", new Info { Title = "My API v1", Version = "v1" });
                //string PathXML = System.AppDomain.CurrentDomain.BaseDirectory + @"WebCoreAPI.xml";
                //c.IncludeXmlComments(PathXML);
                var basePath = AppContext.BaseDirectory;
                var xmlPath = Path.Combine(basePath, "WebCoreAPI.xml");
                c.IncludeXmlComments(xmlPath);
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();
            app.UseSwagger(c =>
            {
                //Change the path of the end point , should also update UI middle ware for this change                
                c.RouteTemplate = "/api-docs/{documentName}/swagger.json";
            });
            app.UseSwaggerUI(c =>
            {
                //c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.RoutePrefix = "api-docs";
                c.SwaggerEndpoint("v0/swagger.json", "Api v0");
                c.SwaggerEndpoint("v1/swagger.json", "Api v1");

            });

            app.UseMvc(
            //     routes =>
            // {
            //     routes.MapRoute(
            //   name: "default",
            //   template: "{controller=Home}/{action=Index}/{id?}");

            //     routes.MapSpaFallbackRoute(
            //   name: "spa-fallback",
            //   defaults: new { controller = "Home", action = "Index" });
            // }
            );

            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "wwwroot";

                if (env.IsDevelopment())
                {
                    // spa.UseAngularCliServer(npmScript: "start");
                    spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
                }
            });
        }
    }

open Program.cs and change next:

 public class Program
    {
        public static void Main(string[] args)
        {
           var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
            try
            {
                logger.Debug("init main");
                BuildWebHost(args).Run();
            }
            catch (Exception ex)
            {
                //NLog: catch setup errors
                logger.Error(ex, "Stopped program because of exception");
                throw;
            }
            finally
            {
                // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
                NLog.LogManager.Shutdown();
            }
        }

         public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                })
                .UseNLog()  // NLog: setup NLog for Dependency injection
                .Build();
    }


change angular.json, set correct output path => "outputPath": "wwwroot"

change index.html, set correct path

<base href="./">


and "HAPPY", after run debug code it's work.
Next trable
npm install --save @angular/material@6.2.1 @angular/cdk@6.2.1
ng add @angular/material@6.2.1
ng generate @angular/material:material-nav --name app-nav
and generate component
ng generate component searchserial
ng g service api - generate service api
add bootstrap https://www.intertech.com/Blog/using-bootstrap-4-with-angular/
use bootstrap https://www.c-sharpcorner.com/article/how-to-install-jquery-popper-and-bootstrap-in-angular/

before public in iis you need build ng project

ng build --prod --aot

information about API versions

Friday, June 8, 2018

SQL Server Statistics: Maintenance and Best Practices

SQL Server Statistics: Maintenance and Best Practices:
This script show bad statistics for database
"WITH    autostats ( object_id, stats_id, name, column_id )   AS ( SELECT   sys.stats.object_id ,   sys.stats.stats_id ,   sys.stats.name ,   sys.stats_columns.column_id   FROM     sys.stats   INNER JOIN sys.stats_columns ON sys.stats.object_id = sys.stats_columns.object_id   AND sys.stats.stats_id = sys.stats_columns.stats_id   WHERE    sys.stats.auto_created = 1   AND sys.stats_columns.stats_column_id = 1   )   SELECT  OBJECT_NAME(sys.stats.object_id) AS [Table] ,   sys.columns.name AS [Column] ,   sys.stats.name AS [Overlapped] ,   autostats.name AS [Overlapping] ,   'DROP STATISTICS [' + OBJECT_SCHEMA_NAME(sys.stats.object_id)   + '].[' + OBJECT_NAME(sys.stats.object_id) + '].['   + autostats.name + ']'   FROM    sys.stats   INNER JOIN sys.stats_columns ON sys.stats.object_id = sys.stats_columns.object_id   AND sys.stats.stats_id = sys.stats_columns.stats_id   INNER JOIN autostats ON sys.stats_columns.object_id = autostats.object_id   AND sys.stats_columns.column_id = autostats.column_id   INNER JOIN sys.columns ON sys.stats.object_id = sys.columns.object_id   AND sys.stats_columns.column_id = sys.columns.column_id   WHERE   sys.stats.auto_created = 0   AND sys.stats_columns.stats_column_id = 1   AND sys.stats_columns.stats_id != autostats.stats_id   AND OBJECTPROPERTY(sys.stats.object_id, 'IsMsShipped') = 0"

'via Blog this'