xJoker的记事本

懒… 不定期更新

2018年1月11日
by xjoker
0 comments

C#强制释放内存的方法

EmptyWorkingSet用于尽可能多的从 Working Set 中回收内存。基本所有的内存优化软件都是调用此接口。
这个方法在服务和站点中测试过,可行!

https://msdn.microsoft.com/en-us/library/windows/desktop/ms682606(v=vs.85).aspx

// 声明
[DllImport("psapi.dll")]
public static extern bool EmptyWorkingSet(IntPtr hProcess);

// 使用
// 获得当前进程句柄
Process pProcess = Process.GetCurrentProcess();
bool bRes = EmptyWorkingSet(pProcess.Handle);
if (!bRes)
{
  // 释放失败时做的操作
}

2017年12月18日
by xjoker
0 comments

.Net Core 内存数据库

DBContext类

using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

public class MemoryContext : DbContext
    {

        public MemoryContext()
        { }

        public MemoryContext(DbContextOptions<MemoryContext> options)
            : base(options)
        {

        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseInMemoryDatabase("memDB");
            }
        }

        public DbSet<MemGUIDValue> MemGUIDValue { get; set; }


    }

    public class MemGUIDValue
    {
        [Key]
        public string Key { get; set; }
        public string Value { get; set; }
    }

使用方法

    public static class MemDB
    {
        public static void Add(string k,string v)
        {
            using (MemoryContext mc = new MemoryContext())
            {
                var i = new MemGUIDValue() { Key = k, Value = v };
                mc.MemGUIDValue.Add(i);
                mc.SaveChanges();
            }
        }
    }

2017年12月18日
by xjoker
0 comments

.Net Core App 使用Nlog

首先需要引用两个文件
nlog.config
NLog.xsd

nlog.config配置如下

<?xml version="1.0" encoding="utf-8" ?>
<!-- XSD manual extracted from package NLog.Schema: https://www.nuget.org/packages/NLog.Schema-->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogFile="c:\temp\console-example-internal.log"
      internalLogLevel="Info" >
  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file -->
    <target xsi:type="File" name="target1" fileName="c:\temp\console-example.log"
            layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />
    <target xsi:type="Console" name="target2"
            layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />
  </targets>
  <!-- rules to map from logger name to target -->
  <rules>
    <logger name="*" minlevel="Trace" writeTo="target1,target2" />
  </rules>
</nlog>

接着创建一个NLogHelper.cs

“`c#
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System;
namespace ConsoleApp10
{
public class NLogHelper
{
private readonly ILogger<NLogHelper> _logger;
public NLogHelper(ILogger<NLogHelper> logger)
{
_logger = logger;
}
public static IServiceProvider BuildDi()
{
var services = new ServiceCollection();
//Runner is the custom class
services.AddTransient<NLogHelper>();
services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.AddLogging((builder) => builder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace));
var serviceProvider = services.BuildServiceProvider();
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
//configure NLog
loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
loggerFactory.ConfigureNLog("nlog.config");
return serviceProvider;
}
}
}

<pre class="line-numbers prism-highlight" data-start="1"><code class="language-null"><br />这样就可以使用NLog记录和显示日志了

使用方法
在类内需要声明一个私有的Logger类型 用于创建本类内的日志
这样日志内就能体现出日志记录的类

“`c#
using NLog;
namespace ConsoleApp10
{
public class TestLog
{
static Logger logger = LogManager.GetCurrentClassLogger();
public void MyMethod1()
{
logger.Trace(“Sample trace message”);
logger.Debug(“Sample debug message”);
logger.Info(“Sample informational message”);
logger.Warn(“Sample warning message”);
logger.Error(“Sample error message”);
logger.Fatal(“Sample fatal error message”);
// alternatively you can call the Log() method
// and pass log level as the parameter.
logger.Log(NLog.LogLevel.Info, “Sample informational message”);
}
}
}

2017/12/18 11:32:17.316|INFO|Sample informational message |ConsoleApp10.TestLog|
2017/12/18 11:32:17.316|WARN|Sample warning message |ConsoleApp10.TestLog|
2017/12/18 11:32:17.316|ERROR|Sample error message |ConsoleApp10.TestLog|
2017/12/18 11:32:17.316|FATAL|Sample fatal error message |ConsoleApp10.TestLog|
2017/12/18 11:32:17.316|INFO|Sample informational message |ConsoleApp10.TestLog|

2017年12月15日
by xjoker
0 comments

ASP.NET CORE 502.5 等问题的解决

因为每次在新服务器上部署 ASP.NET CORE 都会爆出错误
顺带记录下Check Point

  • Windows Hosting 包是否安装 – Windows Hosting 包是否安装

包不一定是最新版本的
IIS 需要安装 windows hosting 包
https://download.microsoft.com/download/5/C/1/5C190037-632B-443D-842D-39085F02E1E8/DotNetCore.2.0.3-WindowsHosting.exe

  • 是否安装VC++ 2015 Runtime

安装C++ 2015
https://download.microsoft.com/download/6/A/A/6AA4EDFF-645B-48C5-81CC-ED5963AEAD48/vc_redist.x64.exe

  • 如果是Windows 2012 R2系统 需要安装KB2999226

https://download.microsoft.com/download/D/1/3/D13E3150-3BB2-4B22-9D8A-47EE2D609FFF/Windows8.1-KB2999226-x64.msu

  • 检查下Dotnet SDK 是否安装

https://download.microsoft.com/download/1/1/5/115B762D-2B41-4AF3-9A63-92D9680B9409/dotnet-sdk-2.1.4-win-gs-x64.exe

操作完成后 记得重启下

net stop was /y
net start was /y
iisreset