在 .Net 6/7 中修改配置让生成项目时版本号自增长

项目里先添加一个“程序集信息文件” :AssemblyInfo.cs

[assembly: AssemblyVersion("1.0.0.*")] //修订号为*
//[assembly: AssemblyFileVersion("1.0.0.0")] //此行文件版本注释掉

双击项目文件,进行编辑,在<PropertyGroup>节点中加入以下内容:

<!-- 自定义版本开关-->
		<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
		<Deterministic>False</Deterministic>

		<VersionSuffix>1.0.1.$([System.DateTime]::UtcNow.ToString(mmff))</VersionSuffix>
		<AssemblyVersion Condition=" '$(VersionSuffix)' == '' ">0.0.0.1</AssemblyVersion>
		<AssemblyVersion Condition=" '$(VersionSuffix)' != '' ">$(VersionSuffix)</AssemblyVersion>
		<Version Condition=" '$(VersionSuffix)' == '' ">0.0.1.0</Version>
		<Version Condition=" '$(VersionSuffix)' != '' ">$(VersionSuffix)</Version>
<!-- 自定义版本开关-->

然后生成就行了,每次文件版本最后的修订号根据时间递增。

我个人是这样用的,也可以按自己习惯自己改下。

解决VS2019/VsCode 错误提示 No SDKs were found.

装了 .net core 5.0的SDK,在VS2019建了个项目,打开发现解决方案中是空的。换VScode也是提示: No SDKs were found.

CMD下 “dotnet –info”,.NET SDKs 下没有条目,只有.NET runtimes。

发现问题在于环境变量的path设置:

原先的是:”C:\Program Files (x86)\dotnet” ,但目录下没有SDK文件夹

应该添加路径:“C:\Program Files\dotnet” ,此目录下有SDK

添加过问题依然。

原来应用程序会去环境变量path条目的目录中,按顺序,查找“dotnet.exe”,在”C:\Program Files (x86)\dotnet”找到一个,就停止寻找下面的路径条目,

所以“C:\Program Files\dotnet”,要放在 “C:\Program Files (x86)\dotnet”之前。

在环境变量列表,选择“C:\Program Files\dotnet”,上移此条目至 “C:\Program Files (x86)\dotnet”之前,就可以找到SDK了。

设置后,在CMD下 “dotnet –info”,已经看到 .NET SDKs 条目了。

但之前创建的项目,直接打开解决方案还是不能加载,要去打开.csproj文件才能加载。或者重新新建项目。

sqlite 简单手记

delete from TableName;  //清空数据 
update sqlite_sequence SET seq = 0 where name ='TableName';//自增长ID为0
更新删除时,如何插入有单引号(')的字符串,将所有单引号替换为两个单引号

sql = sql.Replace("'","''");

保存到SQLite数据库中时自动恢复为单引号,也就是说使用双单引号即可,例如:
INSERT INTO TableName VALUES('James''s Street');
插入数据库的是: James's Street 。

sqlite数据库在搜索的时候,一些特殊的字符需要进行转义, 具体的转义如下: 
     /   ->    //
     ‘   ->    ”
     [   ->    /[
     ]   ->    /]
     %   ->    /%
     &   ->    /&
        ->    /
     (   ->    /(
     )   ->    /)

Asp.Net core Linux 监听端口的设置

在linux测试跑.net core,默认端口是5000,5001. 需要修改

尝试有以下几种方式:

1. 在项目csproj文件在linux中,编辑Properties/launchSettings.json文件中的 “applicationUrl”: “http://*:5000;http://*:5050”

2.编辑Program,直接在代码里定义

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://*:5001/")
            .Build();

        host.Run();
    }
}

3.添加配置文件hosting.json,然后在Program中加载配置文件

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", true)
        .Build();

    var host = new WebHostBuilder()
        .UseKestrel(options => options.AddServerHeader = false)
        .UseConfiguration(config)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

4. 直接启动时增加参数,两种

在发布文件夹下直接加载dll:

dotnet WebApp1.dll --server.urls "http://*:5001;http://*:5002"

在项目文件下:

dotnet run --urls="http://*:5001/;http://*:5051/"

 

解决NuGet程序包更新安装失败的错误

管理NuGet程序包 中更新程序包,出现:

Failed to initialize the PowerShell host. If your PowerShell execution policy setting is set to AllSigned, open the Package Manager Console to initialize the host first

1. Step

Open Windows PowerShell, run as Administrator

2. Step

Setting an execution policy to RemoteSigned or Unrestricted should work. It must be changed under an administrator mode via a PowerShell console. Be aware that changes will be applied according to the bit version of the PowerShell console, so 32bit or 64 bit. So if you want to install a package in Visual Studio (32 bit version) which requires a specific policy you should change settings of the policy via PowerShell (x86).

The command in PowerShell (as administrator) to set the policy to unrestricted (as noted by @Gabriel in the comments) is:

start-job { Set-ExecutionPolicy Unrestricted } -RunAs32 | wait-job | Receive-Job

OR

NuGet is using the 32 bit console, so it wont be affected by changes to the 64 bit console. Run the following script to make sure you are configuring the 32 bit console.

start-job { Set-ExecutionPolicy RemoteSigned } -RunAs32 | wait-job | Receive-Job

3. Step

Restart Visual Studio

————————————————————-

如果所有的政策是正确的,但安装包时,仍有错误

无法初始化PowerShell主机。如果你的PowerShell执行策略设置为使用AllSigned,打开包管理器控制台首先初始化主机。

解决方案卸载  NuGet包管理器 插件,并重新安装它。

农转公/公转农 System.Globalization.ChineseLunisolarCalendar 农历转公历/公历转农历

项目中有一个生日短信提醒功能,需要每年提醒。选农历, 每年提醒, 第二年的公历是不一样的,所以每一年的都需要自己计算。

设计的要求 ,他们说因为年纪大的人是只记得农历的。。。

网上资料不少,公历转农历现成的一堆。都是用微软的System.Globalization.ChineseLunisolarCalendar类写的,
但是农历转公历的很少,也有,但都是只提到方法的调用,比如下面:
 
正确的应该是1982-10-12 。由于 并没有详细说到关键的闰月计算, 所以起初很困惑,以为计算不准确。

检查全年的月份,发现有因为有闰月的情况,有润月则应该从该闰月起月份自动加一, 如1982年润四月,或则闰五月为6月,后面的月加一处理。
方便理解自己做个对照图:

正确的方法是,要先计算当年农历生日之前的月份有没有闰月,

有了就 直接构造农历日期对象是就把农历的月+1 为9月:

只要明白闰月这一点,其实就很简单了!

///////////
//公历转农历
///////////
            DateTime date = Convert.ToDateTime(textBox1.Text);	//格式:2000-1-1
            ChineseLunisolarCalendar cc = new ChineseLunisolarCalendar();

            if (date > cc.MaxSupportedDateTime || date < cc.MinSupportedDateTime)  
                MessageBox.Show("参数日期时间不在支持的范围内,支持范围:"+cc.MinSupportedDateTime.ToShortDateString()+"到"+cc.MaxSupportedDateTime.ToShortDateString());
            
            int year = cc.GetYear(date);
            int month = cc.GetMonth(date);
            int dayOfMonth = cc.GetDayOfMonth(date);
            int leapMonth = cc.GetLeapMonth(year);
            bool isLeapMonth = cc.IsLeapMonth(year, month);
            bool isLeapYear = cc.IsLeapYear(year);

            if (isLeapMonth || isLeapYear && month >= leapMonth)
                month -= 1;

            textBox2.Text = string.Concat(year, "-", month, "-", dayOfMonth);
///////////
//农历转公历
///////////

	    ChineseLunisolarCalendar cc = new ChineseLunisolarCalendar();
            DateTime date = Convert.ToDateTime(textBox2.Text);	//格式:2000-1-1
            int MonthsInYear = cc.GetMonthsInYear(date.Year);
            int LeapMonth = cc.GetLeapMonth(date.Year, 1);
            bool isLeapMonth = cc.IsLeapMonth(date.Year, date.Month);
            bool isLeapYear = cc.IsLeapYear(date.Year);

            if (isLeapMonth)
                date = cc.ToDateTime(date.Year, date.Month - 1, date.Day, 0, 0, 0, 0);
            else if(date.Month > LeapMonth)
                date = cc.ToDateTime(date.Year, date.Month + 1, date.Day, 0, 0, 0, 0);
            else
                date = cc.ToDateTime(date.Year, date.Month, date.Day, 0, 0, 0, 0);
            
            textBox1.Text = date.ToString("yyyy-MM-dd");

这是一个WinForm做的的实例Demo: WindowsFormsApplication1

通过动态字符串获取变量值 & 获取变量名称

一段实例代码, 在 c#中通过 Linq 取变量的名称, 以及 将字符串转为变量名,通过字符串给变量赋值.

        string strApp = "app";
        public string app = "AAA";
        public string strTest = "TEST";
        protected void Button1_Click(object sender, EventArgs e)
        {

            //通过字符串获得变量值
            string aaa1 = this.GetType().GetField("app").GetValue(this).ToString();
            //或者
            string aaa2 = this.GetType().GetField(strApp).GetValue(this).ToString();
            //通过给变量赋值
            this.GetType().GetField("strTest").SetValue(this, "C#123");
            //新的值
            string bbb = this.GetType().GetField("strTest").GetValue(this).ToString();

            //获取变量名称
            string ccc = GetVarName(p=>this.strTest);
        }

        //获取变量名称
        public static string GetVarName(System.Linq.Expressions.Expression<Func<string, string>> exp)
      {
            return ((System.Linq.Expressions.MemberExpression)exp.Body).Member.Name;
      }

 

Team Foundation Server(TFS) 源代码管理服务器 更换IP地址或端口

源码管理服务器 Team Foundation Server(TFS) 的ip地址发生改变后, 解决方案连不上了.

解决方法是:

  • 1  打开”团队” -> “连接到 Team Foundation Server”, 移除原服务器地址

20140804104552

  • 2  编辑 项目解决方案.sln文件, 修改里面的 “SccTeamFoundationServer” 后面的TFS地址为新地址

  20140804105319

  • 3  打开 “C:\Users\Administrator\AppData\Local\Microsoft\Team Foundation\3.0\Cache”  版本不同, 文件夹可能是4.0.

修改 LocationServerMap.xml 文件, 删除其中的 “location” = 原地址的条目.

 20140804104744

  • 4  重新打来项目连接到TFS

 20140804104621

修改启动 Windows 服务时允许花费的时间

今天安装 Team Foundation Server。

20140725163301

在安装结果信息中有点以为的收获:
信息

启动 Windows 服务时允许花费的时间已从 30 秒增加为 600 秒。这会影响此服务器上的所有 Windows 服务。(注册表值设置是 HKLM\SYSTEM\CurrentControlSet\Control\!ServicesPipeTimeout。)

通过设置此注册表键值,调整加载服务所允许使用的时间。

C#中的’?号’及用法

1. 可空类型修饰符(?):

  引用类型可以使用空引用表示一个不存在的值,而值类型通常不能表示为空。
  例如:
    string str=null;是正确的。
    int i=null;编译器将报错。
    为了使值类型也可为空,可空类型出现了,可空类型使用可空类型修饰符?来表示,表现形式为T?。
  例:int?表示是可空的整形,DateTime?表示为可空的时间。
  T?其实是System.Nullable<T>(泛型结构)的缩写形式,也就意味着当你用到T?时编译器在编译时会把T?编译成System.Nullable<T>的形式,
  例如:int?,编译后便是System.Nullable<int>的形式。

2. 三元(运算符)表达式(?:):

语法为:条件表达式?表达式1:表达式2;
该操作首先求出条件表达式的值(bool类型),为true时调用表达式1,为flase时调用表达式2。
其逻辑为:"如果为真执行第一个,否则执行第二个。"

 例:
 test ? expression1 : expression2
 test 任何 Boolean 表达式。
 expression1 test 为 true 时返回的表达式。可能是逗点表达式。
 expression2 test 为 false 时返回的表达式。可能是逗点表达式。

 例如:
 string prm1="4"; string prm2="5";
 string prm3 = prm1==prm2?"yes":"no" // 此时prm3值为"no".

3. 空合并运算符(??):

空合并运算符 (null coalescing operator) ??
  用于定义可空类型和引用类型的默认值。如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数。
  例:a??b 如果 a 为非空,则 a ?? b 的结果为 a;否则结果为 b 。

空合并运算符为右结合运算符,即操作时从右向左进行组合的。
  例:“a??b??c”的形式按“a??(b??c)”计算。