Warning: realpath(): open_basedir restriction in effect. File(/www/wwwroot) is not within the allowed path(s): (/www/wwwroot/dlgcy_com/:/tmp/) in /www/wwwroot/dlgcy_com/wp-content/plugins/wp-file-manager/classes/backup-storage.php on line 119

Warning: realpath(): open_basedir restriction in effect. File(/www) is not within the allowed path(s): (/www/wwwroot/dlgcy_com/:/tmp/) in /www/wwwroot/dlgcy_com/wp-content/plugins/wp-file-manager/classes/backup-storage.php on line 119

Warning: realpath(): open_basedir restriction in effect. File(/) is not within the allowed path(s): (/www/wwwroot/dlgcy_com/:/tmp/) in /www/wwwroot/dlgcy_com/wp-content/plugins/wp-file-manager/classes/backup-storage.php on line 119
独立观察员作者主页 - 独立观察员 - 第 7 页

在 Linux(树莓派)系统的 Chromium 浏览器上连接代理网络

在 Linux(树莓派)系统的 Chromium 浏览器上连接 V2Ray 代理网络

独立观察员 2022年7月30日

1、首先需要有 V2Ray 代理网络

可以自己搭建 https://github.com/dlgcy/V2Ray_ws-tls_bash_onekey

wget -N --no-check-certificate -q -O install-v2ray.sh "https://raw.githubusercontent.com/wulabing/V2Ray_ws-tls_bash_onekey/master/install.sh" && chmod  x install-v2ray.sh && bash install-v2ray.sh

 

Windows 电脑上可使用 v2rayN 进行连接, 安卓手机可使用 v2rayNG 进行连接。

 

2、Linux 系统上安装配置 v2rayA

我是在树莓派系统中安装的,安装过程略。

%title插图%num

 

安装后通过浏览器打开,配置好 Server 节点(填写 V2Ray 服务器信息)并连接:

%title插图%num

 

然后点击右上角设置,全局透明代理 选择关闭:

%title插图%num

 

本来这个功能应该比较强大(不过我没有成功过),而且设置之后,我的 VNC 就连不上了,即使是按照它提示的设置了 出方向端口白名单 也不行。

%title插图%num

 

即使是它自己的 2017 端口,设置了白名单,在局域网中还是访问不了,更别说 VNC 的端口(听说是 5900)了:

%title插图%num

 

总之,选择了全局透明代理选项,就会导致各种连不上,而且直接在系统本地浏览器访问谷歌还是不行,所以不能开启全局透明代理。

%title插图%num

 

那么不使用全局透明代理,我们怎么使用呢?答案还是在设置界面,就藏在左下角的 “地址与端口” 中:

%title插图%num

 

可以看到,它给我们提供了 socks5 端口和 http 端口,后者只能用于 http 协议,socks5 则更加底层更加通用。所以接下来我们需要找一个支持 Socks5 的客户端。

 

3、安装和使用 SwitchyOmega 浏览器插件

由于没找到能在树莓派系统下使用的图形化的 socks 客户端软件,所以只能转向浏览器插件,发现大受欢迎的 SwitchyOmega 确实好用,接下来就来介绍怎么使用它。

 

3.1 下载安装

由于还没使用上代理,所以什么 Chrome 应用商店 之类的途径就不行了,还是从 GitHub 的 Release 处下载吧,地址如下:

https://github.com/FelisCatus/SwitchyOmega/releases 

%title插图%num

 

基于 Chromium 的浏览器就下载 .crx 后缀的那个文件即可。下载后打开 Chromium 浏览器的 扩展程序 界面,将下载好的 crx 文件直接拖放到界面中进行安装:

%title插图%num

 

3.2 配置使用

安装好之后,在浏览器上出现扩展图标,右键弹出菜单,点击 “选项”:

%title插图%num

 

会有个新手引导,所以还是比较容易上手的。我们这里直接将默认的情景模式 “proxy” 中的信息改为前面配置好的 v2rayA 的 socks5 端口信息:

%title插图%num

 

现在我们直接在插件图标上点击,在下拉菜单中选择刚才的情景模式 “proxy”:

%title插图%num

 

现在我们来试着访问一下不存在的网站,Google:

%title插图%num

 

FaceBook:

%title插图%num

 

可以看到,都很完美。当然,SwitchyOmega 说功劳主要还是 v2rayA 的,v2rayA 说功劳主要还是 V2Ray 的,V2Ray 说功劳主要还是服务器 “狗云(https://www.dogyun.com/?ref=mydog)” 的…… 现场一派祥和的氛围。

 

另外,局域网下其它电脑(Windows11,Edge)也使用成功了:

%title插图%num

 

3.3 自动切换

上面介绍的情景模式类型是 “代理服务器” 模式,也就是说开启后,浏览器的所有流量都经过代理服务器,这样的话就会导致本来不需要代理的网站访问很慢或者访问不了。那么怎么解决呢?插件作者自然也是提供了方法,他为我们准备了四种类型的情景模式:

%title插图%num

 

我们需要的是 “自动切换模式”,作者也很贴心地帮我们默认创建了,叫做 “auto switch”,那我们就直接打开编辑吧!嗯。。。还是先看下新手引导吧:

%title插图%num

%title插图%num

%title插图%num

%title插图%num

%title插图%num

 

是不是说得很清楚啦,哈哈哈,那我就不再赘述了,接下来说说 “导入在线规则列表”。

 

点击 “添加规则列表” 按钮:

%title插图%num

 

将 “规则列表规则” 这一行的情景模式选择为之前配置好的 “proxy”,然后 “规则列表格式” 选择 “AutoProxy”:

%title插图%num

 

从网络上找到了如下规则列表网址:

https://raw.githubusercontent.com/gfwlist/gfwlist/master/gfwlist.txt 

 

填入输入框之后,点击 “立即更新情景模式” 按钮:

%title插图%num

 

注意,需要在连接了代理的情况下(按照之前的步骤,目前就是连着的)进行更新,否则可能会更新失败。更新成功后,规则列表正文中就有内容了:

%title插图%num

 

然后我们点击扩展图标,切换情景模式为 “auto switch”,即可愉快滴玩耍啦:

%title插图%num

 

可以做个实验,在 FaceBook 页面,将鼠标移上扩展图标,显示当前使用的是 “auto switch”,不过 facebook.com 匹配了 “proxy” 情景模式,也就是进行代理:

%title插图%num

 

而访问微信公众号文章页面,鼠标移上,显示的是 “auto switch” 匹配了 “直接连接”:

%title插图%num

 

而且两种情况的图标也不一样,作者真的很用心。

 

全文完。

 

SVN 命令行获取提交日志

SVN 命令行获取提交日志

独立观察员 2022年7月24日

一、命令帮助

svn help log

 

帮助内容:

>svn help log
log: Show the log messages for a set of revision(s) and/or path(s).
usage: 1. log [PATH][@REV]
       2. log URL[@REV] [PATH...]

  1. Print the log messages for the URL corresponding to PATH (default: '.'). 
     If specified, REV is the revision in which the URL is first looked up, and the default revision range is REV:1.
     If REV is not specified, the default revision range is BASE:1, since the URL might not exist in the HEAD revision.

  2. Print the log messages for the PATHs (default: '.') under URL.
     If specified, REV is the revision in which the URL is first looked up, and the default revision range is REV:1; 
     otherwise, the URL is looked up in HEAD, and the default revision range is HEAD:1.

  Multiple '-c' or '-r' options may be specified (but not a combination of '-c' and '-r' options), and mixing of forward and reverse ranges is allowed.

  With -v, also print all affected paths with each log message.
  Each changed path is preceded with a symbol describing the change:
    A: The path was added or copied.
    D: The path was deleted.
    R: The path was replaced (deleted and re-added in the same revision).
    M: The path's file and/or property content was modified.
  If an added or replaced path was copied from somewhere else, the copy source path and revision are shown in parentheses.
  If a file or directory was moved from one path to another with 'svn move' the old path will be listed as deleted and the new path will be listed as copied from the old path at a prior revision.

  With -q, don't print the log message body itself (note that this is compatible with -v).

  Each log message is printed just once, even if more than one of the affected paths for that revision were explicitly requested.  
  Logs follow copy history by default.  
  Use --stop-on-copy to disable this behavior, which can be useful for determining branchpoints.

  The --depth option is only valid in combination with the --diff option and limits the scope of the displayed diff to the specified depth.

  If the --search option is used, log messages are displayed only if the provided search pattern matches any of the author, date, log message text (unless --quiet is used), or, if the --verbose option is also  provided, a changed path.
  The search pattern may include "glob syntax" wildcards:
      ?      matches any single character
      *      matches a sequence of arbitrary characters
      [abc]  matches any of the characters listed inside the brackets
  If multiple --search options are provided, a log message is shown if it matches any of the provided search patterns. If the --search-and option is used, that option's argument is combined with the pattern
  from the previous --search or --search-and option, and a log message is shown only if it matches the combined search pattern.
  If --limit is used in combination with --search, --limit restricts the number of log messages searched, rather than restricting the output to a particular number of matching log messages.

  Examples:

    Show the latest 5 log messages for the current working copy directory and display paths changed in each commit:
      svn log -l 5 -v

    Show the log for bar.c as of revision 42:
      svn log bar.c@42

    Show log messages and diffs for each commit to foo.c:
      svn log --diff http://www.example.com/repo/project/foo.c
    (Because the above command uses a full URL it does not require a working copy.)

    Show log messages for the children foo.c and bar.c of the directory '/trunk' as it appeared in revision 50, using the ^/ URL shortcut:
      svn log ^/trunk@50 foo.c bar.c

    Show the log messages for any incoming changes to foo.c during the next 'svn update':
      svn log -r BASE:HEAD foo.c

    Show the log message for the revision in which /branches/foo was created:
      svn log --stop-on-copy --limit 1 -r0:HEAD ^/branches/foo

    Show all log messages for commits between the tags ^/tags/2.0 and ^/tags/3.0; assuming that tag 2.0 was created in revision 100:
      svn log -rHEAD:100 ^/tags/3.0

    If ^/trunk/foo.c was moved to ^/trunk/bar.c' in revision 22, 'svn log -v' shows a deletion and a copy in its changed paths list, such as:
       D /trunk/foo.c
       A /trunk/bar.c (from /trunk/foo.c:21)

Valid options:
  -r [--revision] ARG      : ARG (some commands also take ARG1:ARG2 range)
                             A revision argument can be one of:
                                NUMBER       revision number
                                '{' DATE '}' revision at start of the date
                                'HEAD'       latest in repository
                                'BASE'       base rev of item's working copy
                                'COMMITTED'  last commit at or before BASE
                                'PREV'       revision just before COMMITTED
  -c [--change] ARG        : the change made in revision ARG
  -q [--quiet]             : do not print the log message
  -v [--verbose]           : also print all affected paths
  -g [--use-merge-history] : use/display additional information from merge
                             history
  --targets ARG            : pass contents of file ARG as additional args
  --stop-on-copy           : do not cross copies while traversing history
  --incremental            : give output suitable for concatenation
  --xml                    : output in XML
  -l [--limit] ARG         : maximum number of log entries
  --with-all-revprops      : retrieve all revision properties
  --with-no-revprops       : retrieve no revision properties
  --with-revprop ARG       : retrieve revision property ARG
  --depth ARG              : limit operation by depth ARG ('empty', 'files',
                             'immediates', or 'infinity')
  --diff                   : produce diff output
  --diff-cmd ARG           : use ARG as diff command
  --internal-diff          : override diff-cmd specified in config file
  -x [--extensions] ARG    : Specify differencing options for external diff or internal diff or blame. Default: '-u'. 
                             Options are separated by spaces. Internal diff and blame take:
                               -u, --unified: Show 3 lines of unified context
                               -b, --ignore-space-change: Ignore changes in
                                 amount of white space
                               -w, --ignore-all-space: Ignore all white space
                               --ignore-eol-style: Ignore changes in EOL style
                               -U ARG, --context ARG: Show ARG lines of context
                               -p, --show-c-function: Show C function name
  --search ARG             : use ARG as search pattern (glob syntax, case-
                             and accent-insensitive, may require quotation marks to prevent shell expansion)
  --search-and ARG         : combine ARG with the previous search pattern

(Use '-v' to show global and experimental options.)

 

二、显示某个日期或日期范围的日志

2.1 某个日期的日志

svn log -r '{20220719}'

 

这个命令参数解释是:revision at start of the date。

实际情况如下:

%title插图%num

 

可以看到,每次基本只能显示一条记录,大致是给定的日期开始时的最新版本的提交日志,所以获取的是给定日期前(前一天或更早之前)。但是有一个参数为当天(20220720)的,获取结果为空,不知何故。

 

2.2 某个日期范围的日志

这个需求,帮助文档中没有体现,经过摸索,命令格式如下:

svn log -r '{20220719}:{20220720}'

 

效果:

%title插图%num

 

当天(20220720)更新到新的提交后,使用范围命令感觉就正常了(但是和前面的效果感觉是两套逻辑呀):

%title插图%num

 

以上为在 PowerShell 中的情况,在命令提示符中需要将参数的引号去掉:

%title插图%num

 

2.3 获取当天的提交日志

说明:基于 “2.2 某个日期范围的日志”,动态获取当天和第二天的日期并拼接为参数。

GetCommitLog.bat:

:@echo off

set Today=%date:~0,4%-%date:~5,2%-%date:~8,2%
echo 当前日期是:%Today%

echo Wscript.echo dateadd("d",1,date)>vbs.vbs
for /f %%a in ('cscript /nologo vbs.vbs') do del vbs.vbs&&set yyyymmdd=%%a
for /f "tokens=1,2,3* delims=// " %%i in ('echo %yyyymmdd%') do set yyyy=%%i&set mm=%%j&set dd=%%k
if   %mm%   LSS   9   set   mm=0%mm%
if   %dd%   LSS   9   set   dd=0%dd%
set tomorrow=%yyyy%-%mm%-%dd%
echo tomorrow is : %tomorrow%

set para={%Today%}:{%tomorrow%}

SETLOCAL ENABLEDELAYEDEXPANSION
for /f "delims=" %%i in ('svn log -r %para%') do ( set str=!str! %%i )
echo "%str%"
pause

 

效果(乱入了前一天的日志,这是之前说过的问题):

%title插图%num

 

注:获取当天和第二天日期的脚本参考以下两篇文章,《[bat 文件 cmd 命令获取系统日期格式](https://blog.51cto.com/lexsaints/2806267)》和《[bat 获取明天日期](https://blog.csdn.net/weixin_41710606/article/details/115673362)》

 

全文完。

 

MSBuild 命令的简单使用

MSBuild 命令的简单使用

独立观察员 2022年7月7日

位置

在 VS 安装目录下,如:D:\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin

%title插图%num

 

命令

MSBuild 命令行参考 – MSBuild | Microsoft Docs(https://docs.microsoft.com/zh-cn/visualstudio/msbuild/msbuild-command-line-reference?view=vs-2022)

使用 MSBuild.exe 生成项目或解决方案文件时,可以包含几个开关来指定过程的各个方面。

每个开关都有两种形式:-switch 和 /switch。 本文档仅介绍 -switch 形式。 开关不区分大小写。 如果从 Windows 命令提示符之外的 shell 运行 MSBuild,则开关的参数列表(用分号或逗号分隔)可能需要单引号或双引号,以确保将列表传递到 MSBuild,而不是由 shell 解释。

语法

MSBuild.exe [Switches] [ProjectFile]

参数

参数 描述
ProjectFile 在指定项目文件中生成目标。 如果不指定项目文件,则 MSBuild 会在当前工作目录中搜索以 “proj” 结尾的文件扩展名并使用该文件。 还可以为此参数指定 Visual Studio 解决方案文件。

 

开关

略(见原文)

 

示例

MSBuild.exe MyProject.proj -t:rebuild

 

问题

1、VS 中的生成前事件中参数未被识别的问题

项目中有如下生成事件,其中使用了 $(SolutionDir) 参数:

%title插图%num

 

在使用 Jenkins 的 MSBuild 插件进行编译项目时发现该命令不能被识别:

%title插图%num

 

参考《[使用 MSBuild Tools 调用 csproj 项目文件发布网站时 $(SolutionDir) 宏参数值丢失为空的解决方案](https://www.cnblogs.com/VAllen/p/how-to-get-rid-of-solutiondir-when-building-vs-project-from-outside-visual.html)》可知,可以使用 -p 开关来指定参数的值,如下:

MSBuild D:\JenkinsData\workspace\Src\desktop.sln -p:SolutionDir=D:\JenkinsData\workspace\Src\

 

-p 和 /p 应该是等价的。官网介绍如下:

%title插图%num

 

2、阻止输出警告信息

使用如下命令:

msbuild /p:WarningLevel=0

 

关于警告等级:

0 关闭所有的警告。

1 仅显示严重警告。

2 显示 1 级的警告以及某些不太严重的警告,例如有关隐藏类成员的警告。

3 显示级别 2 警告以及某些不太严重的警告,例如关于始终评估为 true 或 false 的表达式的警告。

4 默认值 显示所有 3 级警告和普通信息警告。

 

参考:《[在 MSBuild 编译项目时阻止输出所有的警告信息](https://blog.csdn.net/WPwalter/article/details/88796146/)》

 

示例

使用 MSBuild 命令编译项目(:注释的代码部分为 devenv 方式编译),各部分解释看脚本中的中文注释:

rem v20220705
ECHO OFF

:以管理员身份运行
echo SetAdmin...
@echo off
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' NEQ '0' (
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
exit /B
:gotAdmin
if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
pushd "%CD%"
CD /D "%~dp0"
echo SetAdmin Done.

:杀死进程
taskkill /F /IM Main.Gui.exe

:设置相关变量
set bg_dir=E:\Build\exe
set src_dir=%~pd0\Src
:Jenkins 工作空间路径为 %WORKSPACE%
:set src_dir=%WORKSPACE%\Src
set desktop_dir=%src_dir%\desktop

:设置编译的环境变量
:set PATH="D:\Microsoft Visual Studio\2022\Enterprise\Common7\IDE";%PATH%
set PATH="D:\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin";%PATH%

:执行编译
ECHO ***************************************** Build desktop ***************************************** 
:devenv %desktop_dir%\desktop.sln /rebuild DEBUG
:devenv %desktop_dir%\desktop.sln /build DEBUG /project %desktop_dir%\UI\Main.Gui.csproj 
MSBuild %desktop_dir%\UI\Main.Gui.csproj -p:WarningLevel=0;SolutionDir=%desktop_dir%\
ECHO ================================================desktop Done===========================================================
ECHO .
ECHO .

:拷贝文件
ECHO Copy desktop
xcopy /Y /E /Q /I /exclude:%src_dir%\exclude.txt %desktop_dir%\Build %bg_dir%\desktop

:调用 Advanced Installer 打包
D:
cd D:\Advanced Installer\16.7\bin\x86\
advinst.exe /rebuild "E:\Build\ddPCR.aip"

pause

 

其中存放忽略规则的文件 exclude.txt 的内容为:

logs
.gitignore
.xml
.pdb
data

 

感谢阅读!

 

在 Windows 上搭建配置 Jenkins 然后编译打包 VS 项目

在 Windows 上搭建配置 Jenkins 然后编译打包 VS 项目

魏刘宏 2022 年 7 月 6 日

 

一、安装

1、下载并安装 JRE (Java 运行环境)。

2、下载 Windows 版本的 Jenkins 安装包并安装。

3、安装 Visual Studio,以供编译项目使用。

4、安装 Advanced Installer,以供打包项目使用。

 

二、Jenkins 配置

Jenkins 安装完成后,使用 IP 端口,在浏览器中可打开使用 Jenkins,如 http://192.168.70.150:8080/manage

%title插图%num

 

Jenkins 的配置文件在其安装目录下,可修改其中一些配置(如数据存放目录),重启 Jenkins 后生效。

%title插图%num

 

重启 Jenkins 的方法为:在主页地址后加 “/restart” 并访问,如下:

%title插图%num

 

2.1、管理插件

首先在 “高级” 选项卡中可进行一些设置,如 设置代理、手动安装插件、设置升级站点:

%title插图%num

%title插图%num

 

一个可用的升级站点为 https://updates.jenkins-zh.cn/update-center.json

 

接下来介绍一些已安装的插件:

%title插图%num

%title插图%num

%title插图%num

%title插图%num

%title插图%num

%title插图%num

%title插图%num

 

2.2、全局工具配置

可对一些插件进行配置,如下。

 

2.2.1、配置 Advanced Installer 安装路径

%title插图%num

 

2.2.2、配置 MSBuild 路径

%title插图%num

 

2.3、配置系统

有一些 Jenkins 的配置,一般无需更改。

%title插图%num

 

也会有些插件的功能需要在这里配置,如下。

 

2.3.1 配置全局构建超时

%title插图%num

 

2.3.2 配置时间戳

%title插图%num

 

2.3.3 SVN 配置

%title插图%num

 

三、构建项目编译任务

%title插图%num

 

输入任务名称,选择 Freestyle project 即可,也可以使用复制功能:

%title插图%num

 

下面以 MD96_Bugfix_MSBuild 为例,点击配置开始编辑:

%title插图%num

 

3.1、设置 丢弃旧的构建

%title插图%num

 

3.2、源码管理

源码管理选择 SVN 并配置相关信息:

%title插图%num

 

其它的默认即可:

%title插图%num

 

3.3、构建触发器

定期构建(2022.07.17 更新)

勾上 Build periodically,在 “日程表” 框中填写规则:

%title插图%num

 

“日程表” 后问号的详细规则:

%title插图%num

 

基本规则就是:

MINUTE HOUR DOM MONTH DOW​
分钟 小时 日 月 星期几

 

H H * * *  代表每日执行,不过时间是不固定的(对于不同任务来说)。* 号代表所有。H 是任务名称的某种 hash 值,所以每个任务的 H 值是稳定的。当然,可以在 H 后指定范围。

例如,H(0-20) H(17-18) * * 1-5 代表在【周一到周五的每一天的 17:00-18:59 的 0-20 分钟之间】进行构建:

%title插图%num

 

3.4、构建环境

%title插图%num

 

3.5、增加构建步骤

增加构建步骤选择 “Build a Visual Studio project or solution using MSBuild”:

%title插图%num

 

配置 MSBuild 的相关编译参数:

%title插图%num

 

需要编译几个项目,就建几个步骤,不再赘述。

 

最后来一段拷贝文件的 bat 指令,步骤类型为 “Execute Windows batch command”:

%title插图%num

 

如果会有 SVN Checkout 操作后产生冲突的情况,还可以再添加一个 “Execute Windows batch command” 的步骤,调用 SVN 命令行工具来进行还原:

%title插图%num

 

四、构建打包任务

以 MD96_Package_Plugin 任务为例:

%title插图%num

 

丢弃旧的构建和上一章一样配置;无需配置源码管理;构建触发器、构建环境等按需配置。

 

直接增加一个类型为 “Invoke Advanced Installer” 的构建步骤。

如果 Run Type 选择第一个,调用,则没有具体配置选项,应该就是唤起打包程序吧(未测试):

%title插图%num

 

所以选择第二个,调用并构建项目,填入 aip 打包文件路径:

%title插图%num

 

其余配置全部留空:

%title插图%num

 

完成后点击 “Build Now” 即可开始构建。

 

五、简单使用介绍

5.1、运行

5.1.1、方法一

鼠标移到列表中相关任务右边,点击出现的下拉箭头:

%title插图%num

 

在下拉列表中点击 “Build Now”:

%title插图%num

 

5.1.2、方法二

点击列表中的某个任务,在打开的页面左侧点击 “Build Now”:

%title插图%num

 

5.2、查看结果

开始构建后,左下角构建历史区会出现正在进行的构建,鼠标移上会出现下拉箭头:

%title插图%num

 

点击下拉框中的 “控制台输出” 可实时查看输出,也可查看之前的构建的输出:

%title插图%num

 

以下为打包任务正在进行的输出:

%title插图%num

 

最终输出如下(有中文乱码,不影响):

%title插图%num

 

感谢阅读!

 

分享一个 WPF 气泡弹框

分享一个 WPF 气泡弹框

独立观察员 2022 年 5 月 28 日

 

一、前言

前段时间,公司项目软件(WPF)中,有个需求是,有些显示文件夹路径的地方,由于路径可能比较长,显示不下,界面只显示出一部分,要求点击时出现气泡弹框来显示完整内容。所要求的 “气泡弹框” 其实就是类似安卓手机上那种吐司(Toast)提示框,显示几秒会自动消失的。项目中倒是有一两处已经添加了这种弹框,就是操作成功后会弹出来提示一下,但是那些是直接加在相关的 Xaml 页面中,通过控制其显示和隐藏来实现需求的。而本次涉及比较多页面,所以应该寻找一个比较通用的解决方案。

 

二、参考文章介绍

前面说了,需求就是实现一个类似安卓 Toast 的功能,自然而然地就进行相应的百度搜索,果然找到了一篇博文,从标题上看就很符合需求 ——《WPF 中自制类似微信消息提示框 Toast 控件》(https://blog.csdn.net/weixin_44448313/article/details/107469089),以下是原文实现的功能:

%title插图%num

 

可以看到功能还是很强大的,以下是原文实现的效果(动图):

%title插图%num

 

三、我的修改点

1、Placement 定位示例

动图:

%title插图%num

 

这个是演示气泡弹框(Popup)定位机制中的一个叫做 Placement 的属性,代表位置;还有她配套的 PlacementTarget 属性,代表定位的目标对象;这里演示了矩形、窗口、空(Null)这三个定位目标,以及 上下左右、中间、相对、绝对 等位置;界面布局如下:

%title插图%num

 

显示和隐藏通过控制 Popup 的 IsOpen 属性来实现,该属性通过样式设置绑定相关的动态资源:

%title插图%num

 

在后台更改动态资源的值:

%title插图%num

 

由于有些位置是重叠的,所以我给每个 Popup 中的内容(TextBlock)加了个鼠标移上会变淡的动画:

%title插图%num

 

2、修正在有些系统环境显示错位的问题

这个主要是加入了一个系统左撇子、右撇子的修正方法,该方法来源于网络,用于解决 Popup 定位异常的问题,也适用于一些有下拉框的控件(因为它们的下拉框也是 Popup),比如日历控件。直接给出方法代码:

/// <summary>
/// 转换系统的左撇子显示模式为右撇子显示模式
/// </summary>
public static void SetAlignment()
{
    //获取系统是以Left-handed(true)还是Right-handed(false)
    var ifLeft = SystemParameters.MenuDropAlignment;

    if (ifLeft)
    {
        Console.WriteLine($"系统为左撇子,转换为右撇子。");

        // change to false
        var t = typeof(SystemParameters);
        var field = t.GetField("_menuDropAlignment", BindingFlags.NonPublic | BindingFlags.Static);
        field.SetValue(null, false);

        ifLeft = SystemParameters.MenuDropAlignment;
    }
}

 

在窗口构造函数中调用:

%title插图%num

 

其实现在看这个方法名,应该叫做 设置对齐方式。

 

3、更改弹框风格

由于原文是要仿安卓的 Toast,所以它的风格是那种灰色透明的小框框。而本次的使用对象是一个 Windows 的全屏应用,且风格是那种白色偏多的明快风格,所以气泡弹框也要大一些,同时改为白色风格,最终效果如下(动图):

%title插图%num

 

4、支持设置宽高和边距

动图:

%title插图%num

 

原版是固定的宽度,我改为了支持自动宽度,这样就能根据文字长度自动变宽。

可以注意到上图在演示长文本时,左右两个弹框的高度都比较高,但是左边的文字被截断了,而右边的能自动换行,这是为什么呢?原来左边设置的 ToastWidth,而右边设置的是 TextWidth,如下所示:

%title插图%num

 

至于边距,是通过 ToastMargin 属性来设置的:

%title插图%num

 

5、其它调用方式

(1)输入框点击调用

这个就是通过鼠标点击事件来触发而已(动图):

%title插图%num

 

(2)通过命令调用

这个效果就不演示了,主要就是在绑定基类中添加了一个针对屏幕的弹框命令和一个针对窗体的弹框命令:

%title插图%num

 

针对屏幕的命令需要一个参数,传递弹框内容;针对窗体的命令需要两个参数(通过多值绑定来传递),传递弹框内容和窗体对象:

%title插图%num

 

四、代码资源

本文主要是展示一些效果,以及部分修改的代码。实现机制可以通过查看原版文章讲解以及修改前后的代码来学习了解,具体资源链接如下。

原文链接:https://blog.csdn.net/weixin_44448313/article/details/107469089 

原文原始代码:https://gitee.com/DLGCY_Clone/WpfToast/tree/master/ 

包含修改点的原文风格代码:https://gitee.com/DLGCY_Clone/WpfToast/tree/Gray 

本文对应的代码:https://gitee.com/DLGCY_Clone/WpfToast/tree/Blog20220528 

最新代码(新风格):https://gitee.com/DLGCY_Clone/WpfToast/tree/dlgcy 

效果:

%title插图%num

 

全文完,谢谢阅读!

 

WPF 表单验证之 INotifyDataErrorlnfo 接口的使用示例

WPF 表单验证之 INotifyDataErrorlnfo 接口的使用示例

魏刘宏 2022 年 4 月 17 日

一、前言

众所周知,无论是做网站开发还是软件开发,当涉及到需要用户填写信息之后提交的操作时,我们都需要对他填写的内容进行限制和验证,这类问题可以统称为表单验证问题。本文将针对 WPF 的 TextBox 文本框,探究其中的一种验证方式 —— 使用 INotifyDataErrorInfo 在数据对象中进行验证。

 

二、参考

主要参考《WPF 编程宝典》一书的 19.4.1 一节:

%title插图%num

 

之前在网上找资料,大多是提到了基于异常的验证(ExceptionValidationRule)和另一种数据错误验证 IDataErrorInfo,没有看到关于 INotifyDataErrorInfo 的描述。而按《WPF 编程宝典》一书的描述,INotifyDataErrorInfo 其实可以看作是 IDataErrorInfo 的升级版:

IDataErrorInfo 和 INotifyDataErrorInfo 接口具有共同的目标,即用更加人性化的错误通知系统替换未处理的异常。IDataErrorInfo 是初始的错误跟踪接口,可追溯至第一个.NET 版本,WPF 包含它是为了达到向后兼容的目的。INotifyDataErrorInfo 接口具有类似的作用,但界面更丰富,是针对 Silverlight 创建的,并且已移植到了 WPF 4.5。它还支持其他功能,如每个属性多个错误以及异步验证。  (《WPF 编程宝典》19.4.1 在数据对象中进行验证)

 

至于 ExceptionValidationRule,有个缺点就是在开发调试时,遇到抛出的异常,会进入中断状态。所以,本文直接研究 INotifyDataErrorInfo。后续可能还会研究其它不是针对数据对象的验证方式,这是后话了,暂且不表。

 

三、问题现象

我们在界面上构建一个加法计算的功能,有两个输入框可以用于输入两个加数,在右边显示计算结果,最右边是执行计算的按钮,如下图:

%title插图%num

 

两个加数和一个结果都使用可绑定的属性;其中两个加数是完整属性的形式,方便之后添加验证代码;结果为自动属性形式,使用了 Fody 来实现变动通知;目前三个数都为 int 类型,如下:

%title插图%num

 

加法命令就是简单的计算两个数相加,为了便于演示问题,先将结果置为 0,然后再延迟 200 毫秒,最后才是计算: 

%title插图%num

 

演示如下(动图),正常计算没什么问题,如果将输入框内容清空,再进行计算,就可以看出不对的地方了 —— 前台绑定失败了,所以后台的值不变,进而导致计算结果还是保持了上次的状态,最终就形成了界面显示与数据结果不一致的尴尬局面:

%title插图%num

 

其中输入框的水印为 TextBox 上指定的样式(文末会给出代码地址),验证失败的红框为 WPF 自带的。我们的目标是,这种情况,在点击计算时,能够进行拦截和提示。

 

四、实现验证接口

首先我们让绑定基类实现 INotifyDataErrorInfo 接口,实现该接口要实现三个成员:

%title插图%num

 

具体为,一个获取错误列表的方法 GetErrors,一个指示是否存在错误的属性 HasErrors,以及一个错误变动事件 ErrorsChanged,如下:

%title插图%num

 

《宝典》中还有如下辅助的代码,一个错误列表,一个设置错误的方法 SetErrors,以及一个清除错误的方法 ClearErrors。其中,错误列表是个字典,键为属性名,值为该属性的错误信息字符串列表。而两个方法主要是对错误列表进行相应的操作,并且触发变动事件。代码如下图:

%title插图%num

 

本人添加了一个针对于属性的是否存在错误的方法 IsContainErrors(因为前面那个 HasErrors 是用于判断整体是否存在错误的),还有一个重载方法用于判断给定的几个属性是否存在错误。另外还重载了一个 GetErrors 方法,也是针对于同时处理几个属性的场景,并且之前返回类型为 List<List>,相当于只是把错误列表的 key 去掉了,并没有整合,而我这个方法返回值为 List,更方便使用。代码如下图:

%title插图%num

 

还给了个验证是否为空的参考方法 ValidateBlank,主要就是使用了 SetErrors 和 ClearErrors 这两个方法:

%title插图%num

 

所以最终改造后的绑定基类完整代码如下:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
/*
 * 源码已托管:https://gitee.com/dlgcy/WPFTemplateLib
 */
namespace WPFTemplateLib.WpfHelpers
{
    /// <summary>
    /// WPF绑定属性基类;
    /// </summary>
    /// <example>
    /// <code>
    /// class Sample : BindableBase
    /// {
    ///     private List<string> _stuList;
    ///     public List<string> StuList
    ///     {
    ///         get => _stuList;
    ///         set => SetProperty(ref _stuList, value);
    ///     }
    /// }
    /// </code>
    /// </example>
    public abstract class BindableBase : INotifyPropertyChanged, INotifyDataErrorInfo
    {
        #region BindableBase

        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// 属性变动通知
        /// </summary>
        /// <param name="propertyName"></param>
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
        {
            if (Equals(storage, value)) return false;

            storage = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        protected bool SetPropertyWithoutCompare<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
        {
            storage = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        #endregion

        #region 验证

        /// <summary>
        /// 错误列表
        /// </summary>
        private Dictionary<string, List<string>> _Errors = new Dictionary<string, List<string>>();

        private void SetErrors(string propertyName, List<string> propertyErrors)
        {
            //clear any errors that already exist for this property.
            _Errors.Remove(propertyName);

            //Add the list collection for the specified property.
            _Errors.Add(propertyName, propertyErrors);

            //Raise the error-notification event.
            if (ErrorsChanged != null)
                ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }

        private void ClearErrors(string propertyName)
        {
            //Remove the error list for this property.
            _Errors.Remove(propertyName);

            //Raise the error-notification event.
            if (ErrorsChanged != null)
                ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }

        /// <summary>
        /// 是否包含错误
        /// </summary>
        /// <param name="propertyName">属性名</param>
        public bool IsContainErrors(string propertyName)
        {
            return (GetErrors(propertyName) as List<string>)?.Count > 0;
        }

        /// <summary>
        /// 是否包含错误
        /// </summary>
        /// <param name="propertyName">属性名列表</param>
        public bool IsContainErrors(List<string> propertyNameList)
        {
            return propertyNameList.Exists(x => IsContainErrors(x));
        }

        /// <summary>
        /// 获取给定属性列表的错误列表(参数传空则获取所有错误列表)
        /// </summary>
        /// <param name="propertyName">属性名列表</param>
        /// <returns>错误列表(List<string>)</returns>
        public List<string> GetErrors(List<string> propertyNameList)
        {
            if (!propertyNameList?.Any() ?? true)
            {
                return _Errors.Values.SelectMany(x => x).ToList();
            }
            else
            {
                List<string> errors = new List<string>();
                foreach (string propertyName in propertyNameList)
                {
                    if (_Errors.ContainsKey(propertyName))
                    {
                        errors.AddRange(_Errors[propertyName]);
                    }
                }

                return errors;
            }
        }

        #region INotifyDataErrorInfo

        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

        /// <summary>
        /// 获取属性错误列表(属性名传空则获取所有错误列表)
        /// </summary>
        /// <param name="propertyName">属性名</param>
        /// <returns>错误列表(List<List<string>>)</returns>
        public IEnumerable GetErrors(string propertyName)
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                //Provide all the error collections.
                return _Errors.Values;
            }
            else
            {
                //Provice the error collection for the requested property (if it has errors).
                if (_Errors.ContainsKey(propertyName))
                {
                    return _Errors[propertyName];
                }
                else
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 整个类是否存在错误
        /// </summary>
        public bool HasErrors => _Errors.Count > 0;

        #endregion

        #region 实用方法(供参考)

        /// <summary>
        /// 验证是否为空
        /// </summary>
        /// <returns>true-不为空,false-为空</returns>
        public virtual bool ValidateBlank(object value, string errMsg = "", [CallerMemberName] string propertyName = null)
        {
            bool valid = !string.IsNullOrWhiteSpace(value + "");
            if (!valid) //为空;
            {
                if (string.IsNullOrWhiteSpace(errMsg))
                {
                    errMsg = $"[{propertyName}] can't be blank";
                }

                SetErrors(propertyName, new List<string>() { errMsg });
            }
            else
            {
                ClearErrors(propertyName);
            }

            return valid;
        }

        #endregion

        #endregion
    }
}

 

五、使用

首先是 Xaml 中,在绑定时添加 ValidatesOnNotifyDataErrors=True :

%title插图%num

 

实际上,按照《宝典》的说法,这也可以不加,因为默认就是 true,不过为了明确起见还是加上比较好:

%title插图%num

 

然后是在需要验证的属性的 set 块中加上具体的验证代码,我这里使用了之前添加的验证是否为空的方法 ValidateBlank:

%title插图%num

 

另外,之前这两个操作数是 int 类型,如果保持的话,当删除内容,红框还是会出现,但是 set 块没被执行,也就达不到验证的效果,没有找到解决方法,知道的朋友可以告知一下。我这里是把它们两个改成了 string 类型,满足本次需求。

 

然后是加法命令中的改造,主要就是使用了我加的那两个方法(IsContainErrors 和 GetErrors),传递的都是两个操作数属性名称列表,如果有错误(为空),就弹窗提示,并拦截代码执行逻辑(直接返回跳出):

%title插图%num

 

六、效果演示及代码地址

首先来看看 Demo 的启动位置:

%title插图%num

 

操作演示如下(动图),可以看到,输入框为空时点击计算,会弹出不能为空的提示:

%title插图%num

 

最后给出代码地址,大家多多交流:https://gitee.com/dlgcy/DLGCY_WPFPractice/tree/Blog20220417 

 

全文完,祝大家生活愉快!

 

Git 服务端软件 Gitea 的 Windows 版安装笔记

Git 服务端软件 Gitea 的 Windows 版安装笔记

独立观察员 2022年4月15日

官网:https://gitea.io/zh-cn/ 

二进制文件下载:https://dl.gitea.io/gitea 

演示网站:https://try.gitea.io/ 

%title插图%num

 

从二进制安装

所有下载均包括 SQLite, MySQL 和 PostgreSQL 的支持,同时所有资源均已嵌入到可执行程序中,这一点和老版本有所不同。 基于二进制的安装非常简单,只要从 下载页面 选择对应平台。

%title插图%num

 

双击可执行程序即可运行起来,是个单文件绿色版:

%title插图%num

 

注册为 Windows 服务

要注册为 Windows 服务,首先以 Administrator 身份运行 cmd,然后执行以下命令:

sc create gitea start= auto binPath= "\"C:\gitea\gitea.exe\" web --config \"C:\gitea\custom\conf\app.ini\""

 

别忘了将 C:gitea 替换成你的 Gitea 安装目录。

之后在控制面板打开 “Windows Services”,搜索 “gitea”,右键选择 “Run”。在浏览器打开 http://localhost:3000 就可以访问了。(如果你修改了端口,请访问对应的端口,3000 是默认端口)。

 

从 Windows 服务中删除

以 Administrator 身份运行 cmd,然后执行以下命令:

sc delete gitea

 

安装配套软件

1、安装 Git 并配置 Path 环境

安装略。配置 Path 环境变量如下,配置完需要重启电脑(注销应该也行)。

%title插图%num

 

2、安装数据库(MySql)

下载地址:https://dev.mysql.com/downloads/installer/ 

%title插图%num

 

选的是 Developer Default 类型:

%title插图%num

 

还需要安装 Python(https://registry.npmmirror.com/binary.html?path=python/ ):

%title插图%num

 

安完 Python 后下一步:

%title插图%num

 

安装完成:

%title插图%num

 

开始安装

注册为 Windows 服务 并运行后,打开安装地址:http://localhost:3000/ 

%title插图%num

%title插图%num

%title插图%num

 

注意:需要先在 MySql 中创建相关数据库:

%title插图%num

 

安装完成:

%title插图%num

 

 

[翻译] WPF 中用户控件 DataContext/Binding 和依赖属性的问题

[翻译] WPF 中用户控件 DataContext/Binding 和依赖属性的问题

User Control DataContext/Binding Issue with Dependency Property WPF

 

[译者] 独立观察员 2022年3月24日

提问

ProgrammingDude(asked Dec 8, 2015 at 21:24)

Ok, so my problem is I have a user control. In the xaml I bind some colors to color properties that I have created as shown below.

好,我的问题是,我有一个用户控件,在 Xaml 中,我绑定了一些颜色到颜色属性,如下所示:

<GradientStop x:Name="stop1" Color="{Binding Color1}" Offset="0"/>
<GradientStop x:Name="stop2" Color="{Binding Color2}" Offset="1"/>

 

In my code behind I have a DependencyProperty that I have declared as shown below.

在后台代码中,我声明了一个依赖属性,如下所示:

public static readonly DependencyProperty IsActiveProperty = 
    DependencyProperty.Register("IsActive", typeof(bool), typeof(Bin), 
        new PropertyMetadata(new PropertyChangedCallback(Bin.IsActivePropertyChanged)));

 

The dependency property has a PropertyChangedCallback that it calls called IsActivePropertyChanged as shown below.

该依赖属性有一个 PropertyChangedCallback 方法,名称为 IsActivePropertyChanged,如下所示:

private static void IsActivePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    Bin b = (Bin)d;
    if((bool)e.NewValue)
    {
        b.Color1 = Color.FromArgb(0xFF, 0x3E, 0x3E, 0x3E);
        b.Color2 = Colors.Red;
        b.Color3 = Colors.Red;
        b.Color4 = Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF);
    }
    else
    {
        b.Color1 = Color.FromArgb(0xFF, 0x3E, 0x3E, 0x3E);
        b.Color2 = Color.FromArgb(0xFF, 0x83, 0x83, 0x83);
        b.Color3 = Color.FromArgb(0xFF, 0x63, 0x63, 0x63);
        b.Color4 = Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF);
    }
}

 

If I use the constructor below, the color changes inside of the constructor work fine, however, my IsActivePropertyChangedEvent never gets fired. I am assuming because of the DataContext assignment in the constructor.

如果我使用下面的构造函数,在构造函数中的颜色改变工作正常,然而,我的 IsActivePropertyChangedEvent 从未被触发。我估计是因为在构造函数中指定了 DataContext。

public Bin()
{
    Color1 = Color.FromArgb(0xFF, 0x3E, 0x3E, 0x3E);
    Color2 = Color.FromArgb(0xFF, 0x83, 0x83, 0x83);
    Color3 = Color.FromArgb(0xFF, 0x63, 0x63, 0x63);
    Color4 = Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF);
    InitializeComponent();
    DataContext = this;
}

 

If I comment out the DataContext assignment and use the constructor below, my Color assignments do not work, but the IsActivePropertyChanged event fires fine.

如果我注释掉 DataContext 赋值,使用如下的构造函数,我的颜色赋值就没起作用,但 IsActivePropertyChanged 事件能够被触发。

public Bin()
{
    Color1 = Color.FromArgb(0xFF, 0x3E, 0x3E, 0x3E);
    Color2 = Color.FromArgb(0xFF, 0x83, 0x83, 0x83);
    Color3 = Color.FromArgb(0xFF, 0x63, 0x63, 0x63);
    Color4 = Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF);
    InitializeComponent();
    //DataContext = this;
}

 

My question is how can i get the binding to work correctly and have my event fire as well. I have tried setting the DataContext="{Binding RelativeSource={RelativeSource Self}}" (instead of setting the DataContext in the code behind) of the items that are bound to the Color Properties in XAML, a rectangle and a polygon, but that didn’t seem to work. Thanks in advance for any help.

我的问题就是,怎样能让绑定和事件触发都正常工作。我尝试了为 Xaml 中绑定到 Color 属性的元素设置 DataContext="{Binding RelativeSource={RelativeSource Self}}" (而不是在后台代码中设置 DataContext),一个矩形和一个多边形,但似乎不起作用。提前感谢任何提供的帮助。

 

回答

vesan(answered Dec 9, 2015 at 22:48)

When writing your own control, you shouldn’t mess with the DataContext of the control itself.

Instead, on the binding of the GradientStop, you can use RelativeSource={RelativeSource AncestorType=Bin} (assuming Bin is your control). Or you can define a template and use TemplateBinding. Check this answer I wrote a while back for a similar question – it has more detailed description of how this works.

在写你自己的控件时,你不应当把控件自身的 DataContext 弄乱。

取而代之的是,在绑定 GradientStop 时,你可以使用 RelativeSource={RelativeSource AncestorType=Bin} (假设 Bin 是你的控件)。或者,你可以定义一个模板并且使用 TemplateBinding。查看我不久之前为一个类似的问题写的 这个回答 ,其中有关于这如何工作的更多详细描述。

 

(译者注:他上面提到的详细回答如下)

vesan(answered May 28, 2015 at 2:26)

Although this has now been solved there seems to be some, in my opinion, inappropriate use of the DataContext.

When developing a custom reusable control, you should not set DataContext at all. What the DataContext will be, that is for the user of the control to decide, not for the developer. Consider the following common pattern of code:

虽然这个现在已经被解决了(译者注:另一个回答被标记为答案),在我看来,似乎有一些,对 DataContext  的不正确使用。

当开发一个定制的可复用的控件,你根本不应该设置 DataContext  。DataContext 将会是什么,应当是控件使用者来决定的,而不是开发者。思考下面的常见模式代码:

<Grid DataContext="{Binding Data}">
    <TextBox Text="{Binding TextValue1}" />
    <!-- Some more controls -->
</Grid>

 

Notice that here, you are using the Grid control. The developer of the control (in this case, the WPF team), didn’t touch the DataContext at all – that is up to you. What does it mean for you as a control developer? Your DependencyProperty definition is fine, but you shouldn’t touch the DataContext. How will you then bind something inside your control to the DependencyProperty value? A good way is using a template (namespaces omitted):

注意这里,你正在使用 Grid 控件。控件的开发者(这个例子中,是 WPF 团队),根本没有碰 DataContext —— 这个是你来用的。那么这对于作为控件开发者的你来说意味着什么呢?你的依赖属性定义是没问题的,但你不应该碰 DataContext 。那么你之后怎么将控件中的一些东西绑定到依赖属性的值呢?一个好的方式就是使用模板(命名空间省略了):

<MyTimePicker>
    <MyTimePicker.Template>
        <ControlTemplate TargetType="MyTimePicker">
            <!-- Stuff in your control -->
            <TextBlock Text="{TemplateBinding Time}" />
            <TextBox Text="{Binding Time, RelativeSource={RelativeSource TemplatedParent}}" />
        </ControlTemplate>
    <MyTimePicker.Template>
</MyTimePicker>

 

Note that TemplateBinding is always one-way only, so if you need any editing at all, you need to use normal binding (as you can see on the TextBox in the example).

This only means that the TextBlock/Box inside your control will get its Time value from your custom control itself, ignoring any DataContext you might have set.

注意 TemplateBinding 总是 one-way 的,所以如果你需要任何编辑,你需要使用普通的 binding (正如你在 TextBox 示例中看到的那样)。

这仅仅意味着你的控件内部的 TextBlock/Box 会从你自定义控件自身获得它的 Time 值,忽略任何你可能设置的 DataContext 。

 

Then, when you use the control, you do it like this (added to my first example):

然后,当你使用这个控件时,你会这样做(被添加到我的第一个示例):

<Grid DataContext="{Binding Data}">
    <TextBox Text="{Binding TextValue1}" />
    <!-- Some more controls -->
    <MyTimePicker Time="{Binding TimeValue}" />
</Grid>

 

What just happened here is that the MyTimePicker does not have DataContext set anywhere at all – it gets it from the parent control (the Grid). So the value goes like this: Data-->(binding)-->MyTimePicker.Time-->(template binding)-->TextBlock.Text.

这里发生的是, MyTimePicker 的 DataContext 根本没有在任何地方被设置,而是从父控件(Grid)获取。所以数值(译者注:这里是 TimeValue)像这样流转:Data-->(binding)-->MyTimePicker.Time-->(template binding)-->TextBlock.Text 。

 

And above all, avoid doing this in the constructor of your custom control:

首要的是,避免在你的自定义控件的构造函数中这样做:

public MyTimePicker()
{
    InitializeComponent();
    DataContext = this;
}

 

This will override any DataContext set in XAML, which will make binding a huge pain (because you’ll have to always set Source manually). The previous example would not work, and this wouldn’t work either:

这会覆盖在 Xaml 中设置的任何 DataContext ,会使得绑定变成一个大痛苦(因为你将不得不总是手动设置 Source )。之前的示例将不能工作,下面这个也不能工作:

<MyTimePicker DataContext="{Binding Data}" Time="{Binding TimeValue}" />

 

You would think this is OK, but the DataContext will be resolved in the InitializeComponent() call, so the value will be immediately overwritten. So the binding to TimeValue will look for it in the control instead (which will, of course, fail).

你可能认为这是可以的,但 DataContext 会在 InitializeComponent() 调用中被重新处理,所以值会被立即重写。所以目标为 TimeValue 的绑定反而会在控件中搜寻(这个当然会失败)。

 

Just don’t touch the DataContext when developing a control and you’ll be fine.

(总之,)开发一个控件时就别碰 DataContext ,你将会一切顺利。

 

OxyPlot 导出图片及 WPF 元素导出为图片的方法

OxyPlot 导出图片及 WPF 元素导出为图片的方法

独立观察员 2022 年 2 月 26 日

 

最近有个需求,就是将 OxyPlot 图形导出图片。经过尝试,本文记录三种方法:1、OxyPlot 自带导出方法;2、网上找的导出 WPF 界面元素的方法;3、基于方法 2 的附加属性调用方式。下面将逐一介绍。

 

一、OxyPlot 自带导出方法

同事说这个用 OxyPlot 官方提供的导出方法即可,我在 Demo 中试了一下,是可以的,代码如下:

/// <summary>
/// 曲线数据源(OxyPlot)
/// </summary>
public PlotModel PlotModel { get; set; } = new PlotModel();

ExportPngCmd ??= new RelayCommand(o => true, async o =>
{
    var pngExporter = new PngExporter { Width = (int)PlotModel.Width, Height = (int)PlotModel.Height, };
    //string exportPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Export");
    string exportPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Export");
    if (!Directory.Exists(exportPath))
    {
        Directory.CreateDirectory(exportPath);
    }

    pngExporter.ExportToFile(PlotModel, Path.Combine(exportPath, $"{DateTime.Now:yyyyMMdd_HHmmss}.png"));
    await ConfirmBoxHelper.ShowMessage(DialogVm, "导出完成", 3);
});

 

各种导出方法可以在 OxyPlot 官方文档(https://oxyplot.readthedocs.io/en/latest/export/index.html)中查看

%title插图%num

 

这里用到的是导出到 PNG 文件的方法,不过用的 NuGet 包最新版(2.1.0)中,PngExporter 中并没有 Background 属性:

%title插图%num

 

所以如果图表没有设置背景色的话,导出背景为透明的,可以设置上:

PlotModel.Background = OxyColor.Parse("#FFFFFF");

 

总的来说,这个方法简单快捷,而且对 MVVM 友好。不过也有缺点,就是如果有些元素(比如说标题、坐标轴文字)不是使用 OxyPlot 图表控件来生成的话,则导出的图片就不会包含它们了:

%title插图%num

 

我在实际项目中确实遇到了这个问题,所以需要寻找其它方法,我们接着看。

 

二、导出 WPF 界面元素的方法

首先给出能够导出任意 WPF 界面元素(FrameworkElement)为图片的方法,来源于网络,地址在方法注释中已给出,略作修改,代码如下:

using System;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace WPFTemplateLib.WpfHelpers
{
    /// <summary>
    /// 导出图片帮助类
    /// </summary>
    public class ExportPicHelper
    {
        /// <summary>
        /// 保存为图片
        /// (修改自:https://blog.csdn.net/dhl11/article/details/108621634)
        /// </summary>
        /// <param name="frameworkElement">可视化元素,可以是Grid、StackPanel等类型的所有可视化元素</param>
        /// <param name="filePath">文件路径</param>
        /// <param name="errorMsg">错误消息</param>
        /// <returns>是否成功</returns>
        public static bool SaveToImage(FrameworkElement frameworkElement, string filePath, out string errorMsg)
        {
            try
            {
                errorMsg = string.Empty;
                FileStream fs = new FileStream(filePath, FileMode.Create);
                RenderTargetBitmap bmp = new RenderTargetBitmap(
                    (int)frameworkElement.ActualWidth, 
                    (int)frameworkElement.ActualHeight, 
                    1 / 96, 1 / 96, PixelFormats.Default);

                bmp.Render(frameworkElement);
                BitmapEncoder encoder = new TiffBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmp));
                encoder.Save(fs);
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存图片异常:{ex}");
                errorMsg = ex.Message;
                return false;
            }
        }
    }
}

 

用这个方法首先要给界面元素起个名字,我这里给图表区用户控件元素起了个 “Plot” 名称:

%title插图%num

 

这样在后台代码中就可以用来导出了:

private void ExportPicBtn_OnClick(object sender, RoutedEventArgs e)
{
    ExportPicture(Plot);
}

/// <summary>
/// 导出图片
/// </summary>
/// <param name="element">xaml里面的某个可视化元素对象</param>
private void ExportPicture(FrameworkElement element)
{
    SaveFileDialog saveFileDialog = new SaveFileDialog
    {
        Filter = "PNG文件(*.png)|*.png|JPG文件(*.jpg)|*.jpg|BMP文件(*.bmp)|*.bmp|GIF文件(*.gif)|*.gif|TIF文件(*.tif)|*.tif"
    };

    if (saveFileDialog.ShowDialog() == true)
    {
        string dir = System.IO.Path.GetDirectoryName(saveFileDialog.FileName);
        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }

        string filePath = saveFileDialog.FileName;
        if (File.Exists(filePath))
        {
            File.Delete(filePath);
        }

        bool success = ExportPicHelper.SaveToImage(element, filePath, out string errorMsg);
        if (success)
        {
            MessageBox.Show($"导出成功");
        }
        else
        {
            MessageBox.Show($"导出失败 {errorMsg}");
        }
    }
}

 

可以看到想要导出的内容都导出成功了:

%title插图%num

 

优点是显而易见的,缺点就是导出逻辑要写在后台代码中,对 MVVM 模式不友好。下面来看看本人修改的使用附加属性的方案,尝试解决这个问题。

 

三、通过附加属性来使用

还是先给出代码:

using System;
using System.IO;
using System.Windows;
using WPFTemplateLib.WpfHelpers;

namespace WPFTemplateLib.Attached
{
    /// <summary>
    /// 导出图片附加属性类
    /// </summary>
    public class ExportPicAttached : DependencyObject
    {
        #region 是否开始导出

        public static bool GetIsExporting(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsExportingProperty);
        }

        public static void SetIsExporting(DependencyObject obj, bool value)
        {
            obj.SetValue(IsExportingProperty, value);
        }

        /// <summary>
        /// 是否正在导出(运行时设置为 true 则将附加的元素导出为图片)
        /// </summary>
        public static readonly DependencyProperty IsExportingProperty =
            DependencyProperty.RegisterAttached("IsExporting", typeof(bool), typeof(ExportPicAttached),
                new PropertyMetadata(false, OnIsExportingValueChanged));

        private static void OnIsExportingValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            FrameworkElement element = d as FrameworkElement;

            if (element == null)
                return;

            if ((e.NewValue as bool?) == false)
                return;

            try
            {
                string exportPath = GetExportPath(d);
                if (string.IsNullOrEmpty(exportPath))
                {
                    exportPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
                        "Export");
                }

                if (!Directory.Exists(exportPath))
                {
                    Directory.CreateDirectory(exportPath);
                }

                string filePath = Path.Combine(exportPath, $"{DateTime.Now:yyyyMMddHHmmss}.png");

                bool success = ExportPicHelper.SaveToImage(element, filePath, out string errorMsg);
                if (success)
                {
                    MessageBox.Show($"导出成功");
                }
                else
                {
                    Console.WriteLine($"导出失败:{errorMsg}");
                    MessageBox.Show($"导出失败 {errorMsg}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"导出异常:{ex}");
                MessageBox.Show($"导出异常:{ex.Message}");
            }
            finally
            {
                //此处设置为 false 没什么用,还是需要业务层在设置为 true 前先设置为 false 才行。
                SetIsExporting(d, false);
            }
        }

        #endregion

        #region 导出文件夹

        public static string GetExportPath(DependencyObject obj)
        {
            return (string)obj.GetValue(ExportPathProperty);
        }

        public static void SetExportPath(DependencyObject obj, string value)
        {
            obj.SetValue(ExportPathProperty, value);
        }

        /// <summary>
        /// 导出文件夹路径
        /// </summary>
        public static readonly DependencyProperty ExportPathProperty =
            DependencyProperty.RegisterAttached("ExportPath", typeof(string), typeof(ExportPicAttached), new PropertyMetadata(string.Empty));

        #endregion
    }
}

 

ExportPicAttached 类中包含两个附加属性,一个是导出文件夹路径 ExportPath,一个是是否开始导出 IsExporting。当 IsExporting 被设置为 true 则开始导出,如果导出文件夹路径没被设定,则导出到桌面文件夹,然后就是调用方案二中出现的 ExportPicHelper.SaveToImage 方法。

 

使用方法就是在要导出的元素上设置上这两个附加属性,然后把值进行绑定:

%title插图%num

 

在 ViewModel 中,先设定导出路径,然后把 IsExporting 置为 true 即可开始导出:

%title插图%num

 

也是能正常导出的:

%title插图%num

 

这个方案结合了前两个方案的优点,既能导出所有想要的内容,又对 MVVM 友好。

缺点就是导出的控制有点奇怪,需要先将 IsExporting 置为 false,不然第二次就导出不了了。尝试了在附加属性逻辑中自动置为 false,但是好像值传递不到 VM 中的相关绑定属性中,有了解解决方法的朋友们请不吝赐教。

%title插图%num

 

源码地址:https://gitee.com/dlgcy/DLGCY_OxyPlotTester/tree/Blog20220226

 

全文完,感谢阅读,祝大家天天开心。

 

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

独立观察员 2022 年 2 月 13 日

 

一、问题

时间拉回到 2015 年,那年 3 月,我还没有毕业,不过已经在公司里实习了,从大三暑假开始,到那时候,已经快实习一年了(毕业后才能转正)。对于工作还是比较满意的,九点多上班(看班车什么时候到),十一点可以吃午饭,吃完饭周边散个步,然后回公司午休,下午基本坐 5 点四十 的班车回家,双休;当时组里的小伙伴们气氛也比较好,组长也比较好,我们主要负责公司内部二十多个 OA 系统(全公司一两千人),任务安排得也不是很紧;本来大学学的是 Java,公选课学了 C# 就爱上了,实习用的是现在早已过时的 Webform,当然还有 SQL;实习嘛,经常也是边学边做,经常在网上找解决方案,用麦库记事(已倒闭)做笔记,还有用问答网站进行提问,用得比较多的就是待会儿要出场的 “思否”,偶尔用的还有昙花一现的 “德问”。

 

当时有一个业务,具体的忘了,只记得用到了反射,当时为了写更少的代码,想要在方法中获取调用者传参时的实参的变量名,不知道怎么弄,于是在 segmentfault.com(思否)网站上提了这么一个问题 ——“C# 如何通过形参获得实参的名字?”:

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

经过一番讨论与思考,当时我妥协了,认识到这是不可能实现的:

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

二、转机

直到昨天看到有人转载了一篇 微软中国 MSDN 的公众号文章《C# 10 的新特性》,在最后部分写了这么一段(灰色的原文链接有误,后面会给出正确的):

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

当看到下图框出的字符 b 时,我的思绪一下被拉到了七年前,这不就是我当时说服了自己把它当作不可能的事吗,现在竟然变成了可能!只能说,微软 NB!

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

而且,上图没有框出的另外两个例子还展示了这个功能更强大的地方 —— 不光是形参名称(或者应该叫字面量?),任何表达式它都能原样获取,比如 “true” 和 “a > 5”。

 

那么这个强大的功能叫什么名字呢?它就是 CallerArgumentExpressionAttribute,可以称之为 “调用方参数表达式特性”。上面公众号文章截图中的参考链接有误,正确的应该是这个 ——https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/attributes/caller-information#argument-expressions :

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

可以看到它也是在 System.Runtime.CompilerServices 命名空间中,相当于扩充了原先的调用方信息,之前的调用方信息有三项,分别是 文件路径、行号、方法名,现在新增了参数表达式。关于旧的调用方信息三巨头的使用,可以参考我之前的文章《C# 在自定义的控制台输出重定向类中整合调用方信息》。

 

三、实践

下面开始实践,例子都来源于微软,上面也都提到了。

 

1、演示输出各种形式的参数表达式

首先就给我来了个下马威,我用 VS2022 打开之前的解决方案总是有各种问题:项目都被卸载了,也重新加载不了;点击重新加载具有依赖项的项目也不行;点击安装缺少的功能,提示已安装,点击启动就会又启动一个 VS2022,打开解决方案还是这样;感觉就是有 Bug。

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

然后用 VS2019 进行开发,代码都写完了,运行也没有报错,但是没有效果:

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

当然,这可能不能怪 VS2019,因为公众号文章开头是这样说的:

我们很高兴地宣布 C# 10 作为 .NET 6 和 Visual Studio 2022 的一部分已经发布了。

 

就是说应该是需要满足 .NET 6 和 VS2022 这两个条件的。然后既然 Visual Studio 2022 不争气,那么我们来试试 Rider:

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

果然成功了!jetbrains NB!

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

2、参数不符合条件时抛出异常

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

帮助方法如下:

using System;
using System.Runtime.CompilerServices;

namespace WPFPractice.Utils
{
    public class MethodHelper
    {
        ///
        /// 验证参数(不符合条件则抛出异常)
        /// 
        ///参数名
        ///条件结果(调用时传条件表达式)
        ///消息(无需填写,通过调用方参数表达式功能自动获取条件参数的输入表达式)
        public static void ValidateArgument(string parameterName, bool condition,
            [CallerArgumentExpression("condition")] string? message = null)
        {
            if (!condition)
            {
                throw new ArgumentException($"Argument failed validation: <{message}>", parameterName);
            }
        }
    }
}

 

当然,如果只是为了判断参数是否为 null,且为 null 时抛出异常,微软公众号文章中提到了一个现成的方法:

void MyMethod(object value)
{
    ArgumentNullException.ThrowIfNull(value);
}

 

反编译后可以看到是微软库 Microsoft.NETCore.App6.0.2System.Private.CoreLib.dll​ 中的功能,也是用到了 “调用方参数表达式”:

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

3、获取调用扩展方法的表达式

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

因为扩展方法也可以当做静态方法来使用( var sequence = ExtensionTester.GetNewSequence (Enumerable.Range (0, 10), 100); ),所以也就很好理解了。另外,微软的例子中没有我后面加的那句 ToList () 的操作,我试了是不行的,因为 Linq 的延迟执行的特性(要实际用到才会执行),如果没有那句,本例的扩展方法不会被执行。

 

四、结语

就像开头讲述的那样,实际上我昨天看到这个功能时还是挺激动的,虽然只是个不起眼的小功能,但是那种感觉就像是:一件尘封多年的悬案,因为时代的局限,基本被视作无法找到真相了,突然有一天,由于科技的进步(比如指纹技术或者 DNA 检测技术),终于真相大白。

 

好了,有点晚了,本文明天再发布,明天是情人节,祝我好运吧,也不知道我这个人生的 “悬案” 什么时候能告破。

 

最后给出源码地址:https://gitee.com/dlgcy/DLGCY_WPFPractice/tree/Blog20220213 

感谢阅读。

 

五、后续

5.1、在 .Net Framework 中使用 [260821]

在 net48 项目中用不了:

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

于是在 NuGet 库中查找 CallerArgumentExpression:

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

可以看到,Hafner.Compatibility.CallerInformationAttributes.G2 包是专门解决这个问题的:

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

或者使用同作者的更齐全的包 Hafner.Compatibility.MetaPackage:

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

源码仓库地址为:https://github.com/HugoRoss/Hafner.Compatibility.Packages 

克隆地址:https://gitee.com/DLGCY_Clone/Hafner.Compatibility.Packages 

 

我们这里使用 Hafner.Compatibility.CallerInformationAttributes.G2 包,添加引用:

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

测试一下,确实功能正常:

C#10 新特性 [调用方参数表达式] 解决了我七年前的困惑

 

→←