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'