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
编程 – 第 5 页 – 独立观察员

分类目录编程

OxyPlot.WPF 公共属性一览

OxyPlot.WPF 公共属性一览

注意:本文仅供需要时参阅,无休闲阅读属性,前方高能(枯燥),非战斗人员请速速撤离。

 

注释已提交到码云:https://gitee.com/DLGCY_Clone/oxyplot/tree/dlgcy

另外,之前《OxyPlot.Wpf 图表控件使用备忘》一文的例子程序有了后续,用 OxyPlot 的注解功能添加了一个可拖动的十字游标功能,后面不一定会写关于它的文章,大家感兴趣的话可以先看看代码:

https://gitee.com/dlgcy/DLGCY_OxyPlotTester

 

一、PlotModel

1、构造函数中设置的属性

%title插图%num

 

文字版:

public PlotModel()
{
    this.Axes = new ElementCollection(this);              //坐标轴集合;
    this.Series = new ElementCollection(this);            //线条集合;
    this.Annotations = new ElementCollection(this);       //注解;
    this.Legends = new ElementCollection(this);           //图例;
    this.PlotType = PlotType.XY;                          //坐标系类型;


    this.PlotMargins = new OxyThickness(double.NaN);    //外边距
    this.Padding = new OxyThickness(8);                 //内边距


    this.Background = OxyColors.Undefined;              //图表背景
    this.PlotAreaBackground = OxyColors.Undefined;      //图表区域背景


    this.TextColor = OxyColors.Black;                   //图表内的字体颜色(标题、图例、注解、坐标轴)
    this.TitleColor = OxyColors.Automatic;              //标题字体颜色
    this.SubtitleColor = OxyColors.Automatic;           //子标题字体颜色


    this.DefaultFont = "Segoe UI";                      //默认字体
    this.DefaultFontSize = 12;                          //默认字体大小


    this.TitleToolTip = null;                           //标题提示
    this.TitleFont = null;                              //标题字体
    this.TitleFontSize = 18;                            //标题字体大小
    this.TitleFontWeight = FontWeights.Bold;            //标题字重
    this.SubtitleFont = null;                           //子标题字体
    this.SubtitleFontSize = 14;                         //子标题字体大小
    this.SubtitleFontWeight = FontWeights.Normal;       //子标题字重
    this.TitlePadding = 6;                              //标题内边距
    this.ClipTitle = true;                              //是否裁剪标题
    this.TitleClippingLength = 0.9;                     //标题裁剪矩形长度


    this.PlotAreaBorderColor = OxyColors.Black;             //图表区域边框颜色
    this.PlotAreaBorderThickness = new OxyThickness(1);     //图表区域边框大小
    this.EdgeRenderingMode = EdgeRenderingMode.Automatic;   //边角渲染模式


    this.AssignColorsToInvisibleSeries = true;              //是否自动分配颜色给不可见的线条
    this.IsLegendVisible = true;                            //图例是否可见(要使用图例则必须设置线条标题)
    //默认颜色集合
    this.DefaultColors = new List                 
    {
            OxyColor.FromRgb(0x4E, 0x9A, 0x06),
            OxyColor.FromRgb(0xC8, 0x8D, 0x00),
            OxyColor.FromRgb(0xCC, 0x00, 0x00),
            OxyColor.FromRgb(0x20, 0x4A, 0x87),
            OxyColors.Red,
            OxyColors.Orange,
            OxyColors.Yellow,
            OxyColors.Green,
            OxyColors.Blue,
            OxyColors.Indigo,
            OxyColors.Violet
    };


    this.AxisTierDistance = 4.0;                            //坐标轴刻度距离
}

 

2、其它属性

RenderingDecorator  //渲染装饰器
Subtitle            //子标题
Title               //标题
TitleHorizontalAlignment    //标题和子标题的水平对齐方式

 

3、只读属性

ActualPlotMargins   //实际图表边距
PlotView            //图表视图
PlotBounds          //图表边界
Width ​              //图表宽
Height              //图表高
PlotAndAxisArea     //包含图表和坐标轴的区域
PlotArea            //图表区(不包含坐标轴和图例)
TitleArea           //标题区域
DefaultAngleAxis        //默认角轴
DefaultMagnitudeAxis    //默认级轴
DefaultXAxis            //默认X轴
DefaultYAxis            //默认Y轴
DefaultColorAxis        //默认颜色轴

 

二、Axis

1、构造函数中设置的属性

%title插图%num

%title插图%num

 

文字版:

protected Axis()
{
    this.Position = AxisPosition.Left;              //坐标轴位置
    this.PositionTier = 0;                          //坐标轴离图表的距离
    this.IsAxisVisible = true;                      //坐标轴是否显示
    this.Layer = AxisLayer.BelowSeries;             //坐标轴层级


    this.ViewMaximum = double.NaN;                  //视图最大值(用于缩放和平移时)
    this.ViewMinimum = double.NaN;                  //视图最小值


    this.AbsoluteMaximum = double.MaxValue;         //坐标轴绝对最大值(数据值范围)(不可缩放和平移超出此限制)
    this.AbsoluteMinimum = double.MinValue;         //坐标轴绝对最小值


    this.Minimum = double.NaN;                      //坐标轴固定范围最小值
    this.Maximum = double.NaN;                      //坐标轴固定范围最大值
    this.MinorStep = double.NaN;                    //辅刻度线间隔
    this.MajorStep = double.NaN;                    //主刻度线间隔
    this.MinimumMinorStep = 0;                      //辅刻度线间隔最小值
    this.MinimumMajorStep = 0;                      //主刻度线间隔最小值


    this.MinimumPadding = 0.01;                     //最小值额外空间(0.01表示1%)(设置了Minimum则此处无效)
    this.MaximumPadding = 0.01;                     //最大值额外空间
    this.MinimumRange = 0;                          //最小范围(ActualMaximum-ActualMinimum > MinimumRange)
    this.MaximumRange = double.PositiveInfinity;    //最大范围(ActualMaximum-ActualMinimum < MinimumRange)
    this.MinimumDataMargin = 0;                     //最小值的屏幕空间数据边距
    this.MaximumDataMargin = 0;                     //最大值的屏幕空间数据边距
    this.MinimumMargin = 0;                         //最小值的屏幕空间边距
    this.MaximumMargin = 0;                         //最大值的屏幕空间边距


    this.TickStyle = TickStyle.Outside;             //刻度样式
    this.TicklineColor = OxyColors.Black;           //刻度线颜色
    this.MinorTicklineColor = OxyColors.Automatic;  //辅刻度线颜色


    this.AxislineStyle = LineStyle.None;            //坐标轴线样式
    this.AxislineColor = OxyColors.Black;           //坐标轴线颜色
    this.AxislineThickness = 1.0;                   //坐标轴线粗细


    this.MajorGridlineStyle = LineStyle.None;                               //主网格线样式
    this.MajorGridlineColor = OxyColor.FromArgb(0x40, 0, 0, 0);             //主网格线颜色
    this.MajorGridlineThickness = 1;                                        //主网格线粗细


    this.MinorGridlineStyle = LineStyle.None;                               //辅网格线样式
    this.MinorGridlineColor = OxyColor.FromArgb(0x20, 0, 0, 0x00);          //辅网格线颜色
    this.MinorGridlineThickness = 1;                                        //辅网格线粗细


    this.ExtraGridlineStyle = LineStyle.Solid;                              //额外网格线样式
    this.ExtraGridlineColor = OxyColors.Black;                              //额外网格线颜色
    this.ExtraGridlineThickness = 1;                                        //额外网格线粗细


    this.MinorTickSize = 4;                         //辅刻度大小
    this.MajorTickSize = 7;                         //主刻度大小


    this.StartPosition = 0;                         //坐标轴在图表区的起点(0-1)
    this.EndPosition = 1;                           //坐标轴在图表区的终点(0-1)


    this.TitlePosition = 0.5;                       //标题位置(0-1)
    this.TitleFormatString = "{0} [{1}]";           //标题格式化字符串(0代表Title,1代表Unit)
    this.TitleClippingLength = 0.9;                 //标题长度(0-1)
    this.TitleColor = OxyColors.Automatic;          //标题颜色
    this.TitleFontSize = double.NaN;                //标题字体大小
    this.TitleFontWeight = FontWeights.Normal;      //标题字重
    this.ClipTitle = true;                          //是否截断标题


    this.Angle = 0;                                 //坐标轴标签角度


    this.IsZoomEnabled = true;                      //是否允许缩放
    this.IsPanEnabled = true;                       //是否允许平移


    this.FilterMinValue = double.MinValue;          //可显示的最小值(小等于该值将不会显示)
    this.FilterMaxValue = double.MaxValue;          //可显示的最大值(大等于该值将不会显示)
    this.FilterFunction = null;                     //过滤方法


    this.IntervalLength = 60;                       //主刻度划分份数


    this.AxisDistance = 0;                          //坐标轴和图表的距离
    this.AxisTitleDistance = 4;                     //坐标轴标题和标签的距离
    this.AxisTickToLabelDistance = 4;               //坐标轴刻度和标签的距离


    this.DataMaximum = double.NaN;                  //数据最大值
    this.DataMinimum = double.NaN;                  //数据最小值
}

 

2、其它属性

CropGridlines           //是否在开始和结束位置裁切与坐标轴垂直的网格线
ExtraGridlines          //额外的网格线
Key                     //坐标轴的键
LabelFormatter          //标签格式化方法
PositionAtZeroCrossing  //是否放置在相关坐标的零交点
StringFormat            //格式化字符串
Title                   //坐标轴标题
TitleFont               //标题字体
Unit                    //单位
UseSuperExponentialFormat   //是否使用上标指数格式

 

3、只读属性

ActualMajorStep         //实际主步长
ActualMaximum           //实际最大值
ActualMinimum           //实际最小值
ClipMaximum             //已显示的最大值(由ActualMaximum和MaximumDataMargin决定)
ClipMinimum             //已显示的最小值(由ActualMinimum和MinimumDataMargin决定)
ActualMinorStep         //实际辅步长
ActualStringFormat      //实际被使用的格式字符串
ActualTitle             //实际标题
IsReversed              //是否被反转(StartPosition > EndPosition)
Offset                  //偏移(用于在数据和屏幕坐标间转换)
Scale                   //比例因子(用于在数据和屏幕坐标间转换的换算系数)
ScreenMax               //最大端的屏幕坐标
ScreenMin               //最小端的屏幕坐标
DesiredMargin           //期望边距

 

三、Series

Background          //背景色
IsVisible           //是否可见
Title               //标题
LegendKey           //对应的图例的键
SeriesGroupName     //分组名称
RenderInLegend      //是否在图例中显示
TrackerFormatString //Tracker格式化字符串
TrackerKey          //对应的Tracker的键

 

四、LegendBase

Key                 //键
IsLegendVisible     //是否可见
LegendOrientation   //图例的方向(如果图例被放在图表的左边或者右边,水平方向会转为垂直方向)
LegendPadding       //图例内边距
LegendSymbolLength  //图例标志的长度(默认16)
LegendSymbolMargin  //图例标志外边距(标志和文字的距离)
LegendSymbolPlacement   //图例标志位置
LegendTitle             //图例标题
LegendTitleColor        //图例标题颜色
LegendTitleFont         //图例标题字体
LegendTitleFontSize     //图例标题字体大小
LegendTitleFontWeight   //图例标题字重
LegendArea              //图例区域
LegendSize              //图例尺寸
LegendBackground        //图例背景色
LegendBorder            //图例边框色
LegendBorderThickness   //图例边框粗细
LegendColumnSpacing     //图例列的间距(只针对垂直方向)
LegendFont              //图例字体
LegendFontSize          //图例字体大小
LegendTextColor         //图例字体颜色
LegendFontWeight        //图例字体字重
LegendItemAlignment     //图例项对齐方式
LegendItemOrder         //图例项排序
LegendItemSpacing       //水平排列时图例项的空间
LegendLineSpacing       //图例项垂直间距
LegendMargin            //图例外边距
LegendMaxWidth          //图例最大宽度
LegendMaxHeight         //图例最大高度
LegendPlacement         //图例摆放位置(内和外)
LegendPosition          //图例位置
AllowUseFullExtent      //图例放在外面时是否允许使用图表的完整extent
ShowInvisibleSeries     //是否显示不可见的序列数据的图例

 

五、Annotation

Layer               //注解渲染层(默认为AboveSeries)
XAxis               //X轴
XAxisKey            //X轴的键
YAxis               //Y轴
YAxisKey            //Y轴的键
ClipByXAxis         //是否由X轴范围裁剪
ClipByYAxis         //是否由Y轴范围裁剪

 

完。

 

OxyPlot.Wpf 图表控件使用备忘

OxyPlot.Wpf 图表控件使用备忘

独立观察员 2021 年 5 月 21 日

一、OxyPlot.Wpf 控件信息

GitHub:https://github.com/oxyplot/oxyplot

官方文档地址:https://oxyplot.readthedocs.io/en/latest/index.html

使用版本:NuGet 版 2.0.0

命名空间:xmlns:oxy=”http://oxyplot.org/wpf”

参考文章:《OxyPlot 在 wpf 中绘制实时动态曲线【更新 2.0 去掉 Smooth 属性】》

 

二、基本概念

(一) PlotView 和 Plot

界面上有两种使用方法:

(1)使用 PlotView(界面简单,设置都在代码中)

%title插图%num

 

(2)使用 Plot (坐标轴、线条等都在界面上设置)

[2023.03.21] 注意:新版本没有了 Plot,看官方文档好像说要自己添加到工具箱,但是试了一下没添加成功,使用 2.0.0 版本就好。

%title插图%num

 

我们使用第一种方法。

 

(二) PlotModel

PlotView 的 Model 属性需绑定一个 PlotModel 对象,它包含了整个图表的各种信息,比如边框、数据线条、坐标轴、图示 等。

%title插图%num

 

绑定的属性可按如下定义:

%title插图%num

 

(三) Axes

Axes 就是坐标轴集合,可分别添加四个方向的坐标轴,如果没有自行添加,默认会有一个底部的横坐标和一个左侧的纵坐标。

坐标轴也有好几种类型:

%title插图%num

 

本文使用的是 LinearAxis:

%title插图%num

 

(四) Series

Series 代表了一组数据,有很多种类型:

%title插图%num

 

本文以 线条(LineSeries)为例:

%title插图%num

 

注释部分是指定平滑模式,开启平滑模式后,两点之间以曲线相连,性能会降低;

关闭平滑模式,两点之间以直线相连,也就是形成折线图。

 

(五) Tracker

Tracker 指的是可浮现的线条上点的信息框,可以理解为 ToolTip 。Tracker 是属于 Series 的。

默认是按住鼠标左键,然后移动到点上,显示 Tracker 。

可使用如下代码改为鼠标移上就显示(其中 _PlotView 为 PlotView 控件对象):

%title插图%num

 

三、样式设置

(一) 效果对比

默认样式如下(不包括标题和坐标轴标题):

%title插图%num

 

Tracker 默认样式如下:

%title插图%num

 

可通过设置,改为如下样式:

%title插图%num

 

(二) 图表边框和数据线条样式

%title插图%num

 

图表边框四边的宽度可分别设置,某一边的边框设为 0 时,相应的坐标轴线样式才有效果。不过坐标轴线条好像有点 Bug,所以此处还是使用边框线来替代坐标轴线。

 

(三) 坐标轴样式

%title插图%num

 

分别设置左侧和底部的坐标轴,可进行缩放、平移、刻度线、网格线的开关和设置等。

 

(四) 自定义 Tracker

自定义 Tracker 在界面上设置,通过设置 Tracker 的控件模板来完成:

%title插图%num

 

更多样式可参考该控件库的示例代码:

%title插图%num

 

四、装配和数据填充

样式设置完成后,将坐标轴和线条装入 PlotModel 中:

%title插图%num

 

数据填充到线条的 Points 中,ResetAllAxes () 方法可重置坐标轴,InvalidatePlot () 方法刷新数据:

%title插图%num

 

五、示例代码

代码地址:https://gitee.com/dlgcy/DLGCY_OxyPlotTester

发行版下载:https://gitee.com/dlgcy/DLGCY_OxyPlotTester/releases 

说明:该项目使用 WPFTemplate 搭建,如果要克隆代码,注意需进行 Git 子模块拉取操作。

程序界面:

%title插图%num

 

 

 

Blazor 初探

Blazor 初探

独立观察员 2021 年 4 月 11 日

 

上个月发了篇文章《Blazor 中如何下载文件到浏览器》,介绍了调用《下载中转加速器 VPSDownloader.NET(.NET Core 程序部署到 Linux 系统)》中提到的 VPS 文件中转下载服务后,如何将下载的文件以 Blazor 的方式传出到浏览器的方法。那么这篇文章就回过头来,介绍一下本项目(VPSDownloader.NET)使用 Blazor 的过程。

 

一、新建项目

在 VisualStudio 中选择 “Blazor 应用” 项目模板:

%title插图%num

 

填写项目名称:

%title插图%num

 

选择 Blazor Server 应用:

%title插图%num

 

二、ASP.NET Core Blazor 项目结构

微软官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/blazor/project-structure?view=aspnetcore-5.0#blazor-server 

 

项目结构图示一:

%title插图%num

 

项目结构图示二:

%title插图%num

 

Startup.cs 分析:

%title插图%num

 

三、结合代码讲解

首先是 Pages 文件夹中的 _Host.cshtml,这个是应用的根页面,也就是整个网站的完整骨架,@page “/” 指定了路由,表明不带任何路径来访问就是到这个页面。

%title插图%num

 

可以看到它有着完整的 html 结构,非 html 常规标签的那些一般都是 Razor 组件,其中 body 后紧跟的一行的那个组件就是其它具体页面将会填充的位置:

%title插图%num

 

当然,也不是直接填充过来,而是通过一个 App 组件,分为找到页面和未找到页面的情况,找到的页面默认使用 MainLayout 布局模板:

%title插图%num

 

MainLayout.razor 通过使用 @inherits LayoutComponentBase 这个继承声明来表明自己布局模板的身份:

%title插图%num

 

可以看到整体布局包括侧边菜单栏和右侧主内容区,主内容区中又分为放关于按钮的顶栏以及实际内容区:

%title插图%num

 

侧边菜单栏由 NavMenu 组件渲染,菜单项中的导航链接是 NavLink 组件:

%title插图%num

 

网页宽度较小时,菜单栏可收缩,控制收缩和展开的逻辑是使用 C# 代码,写在 @code {} 块中,如上图,效果如下图:

%title插图%num

 

四、改造

首先我们的主页不需要关于栏,有些边距也要去掉,所以拷贝 MainLayout 布局模板并改名为 NoPaddingLayout.razor:

%title插图%num

 

site.css 中添加一些 CSS 类:

%title插图%num

 

然后主页 Index.razor 通过 @layout NoPaddingLayout 来使用这个布局页:

%title插图%num

 

@inject 就是注入,可参考开头提到的文章。剩下的就是拷贝之前前端页面然后修改的,简要解释:

%title插图%num

 

@xxx 就是绑定值,适用于标签;@bind=”yyy” 就是双向绑定,适用于输入框;@onclick=”zzz” 表明点击时调用 zzz () 方法。

这样页面逻辑就不需要使用 JS、Vue 这些的了,直接用 C# 就能完成,是不是很方便呀。

 

首页效果:

%title插图%num

 

五、配置文件的使用

配置文件是 appsettings.json,可以添加自己的配置项,修改监听地址就是直接加上 urls 配置项,其它地方都不需要修改(不过自动打开浏览器功能好像会失效):

%title插图%num

 

在代码中使用配置项(这里是 IsUseConfigUrl):

//引用和注入;
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

//使用示例;
bool.TryParse(Configuration[$"{nameof(IsUseConfigUrl)}"], out bool isUseConfigUrl);
IsUseConfigUrl = isUseConfigUrl;

 

六、发布到 Linux(CentOS)

项目上右键 — 发布,打开发布页面,配置目标框架 net5.0,目标运行时 linux-x64 等,点击发布,发布到本地文件夹:

%title插图%num

 

之后就是拷贝到 Linux 机器上,运行相关脚本,脚本在项目中有提供(使用方法以及 Linux 中 .NET 的 运行环境安装等可参考开头提到的文章):

%title插图%num

 

题外话,期间遇到个问题

现象一:使用配置文件设置 urls 时,直接运行是正常的,使用 Linux 服务方式启动则不能正确读取配置,会使用默认的 localhost:5000。

现象二:直接代码里写死 urls,使用服务方式运行,功能是正常的,但是样式、图片等都展示不出来:

%title插图%num

 

这两个现象结合起来思考,前者相当于读取不到目录下的配置文件,后者相当于读取不到目录下的静态文件,那么很容易想到是程序的运行环境(路径)不对,于是使用以下方式解决,也就是在启动脚本(Start.sh)中先 cd 到相应的目录再运行即可:

%title插图%num

 

其实以前我也是习惯这样写两行的,这次不知道为什么抽风了偷懒写成一行这种,还以为是一样的呢,害我排查了半天,吸取教训!

 

反向代理

由于启动的服务是带端口的,不方便记忆,也不美观,于是通过宝塔面板添加个反向代理网站:

%title插图%num

 

七、地址

项目地址:https://gitee.com/dlgcy/VPSDownloader.NET/tree/Blog20210411

发行版地址:https://gitee.com/dlgcy/VPSDownloader.NET/releases/Blog20210411

下载器地址:http://vps.dlgcy.com/

 

Blazor 中如何下载文件到浏览器

Blazor 中如何下载文件到浏览器

独立观察员 2021年3月28日

一、前言

最近想给之前文章《下载中转加速器 VPSDownloader.NET(.NET Core 程序部署到 Linux 系统)》中提到的 VPS 文件中转下载服务添加一个前端页面,其实之前也想使用热门的前端框架 Vue 来做,也做了点工作了,但是毕竟不是前端开发,上手起来还是比较慢的,而且引入了 NodeJS 等技术栈,和后端的 ASP.NET Core WebApi 也不共存于一个项目,开发和维护起来不太方便。后来了解到了发展如火如荼的 Blazor 框架,这个是微软开发的 .NET 领域的前端框架,在某种程度上和以前的 WebForm 有点类似,不过以前那个是微软自己搞的,大家都不待见它,现在这个是符合 Web 领域新标准 WebAssembly,而且 UI 方面也可以使用现有的成熟库。总之,使用 Blazor,可以使用 C# 代码来代替(当然也是兼容的)JavaScript 代码,使 .NET 开发人员能有极致的全栈开发体验,颠覆以往那种“师夷长技以制夷”的前端开发方式,所以决定学习使用一下。另外,本文的 Blazor 项目使用 Blazor Server 模式,而不是 Blazor WebAssembly 模式。

 

先来前情回顾一下,关键就是 WebApi 项目提供了一个 Download 控制器的 Get 方法:

/// <summary>
/// 通过HttpClient获取另外站点的文件流,再输出
/// </summary>
[HttpGet]
public async Task<IActionResult> Get(string url)
{
    if (string.IsNullOrWhiteSpace(url))
    {
        _logger.LogTrace("下载地址为空!");
        return Content("请在链接后跟上下载地址后再次访问");
    }

    try
    {
        //解决 CentOS7 Https 下载地址出错的问题;
        var httpClientHandler = new HttpClientHandler
        {
            ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
        };

        using HttpClient client = new HttpClient(httpClientHandler);
        var stream = await client.GetStreamAsync(url);
        return File(
            stream,
            "application/octet-stream", //二进制流
            Path.GetFileName(url));
    }
    catch (Exception ex)
    {
        return Content($"出错了:{ex}");
    }
}

 

之前是使用 Swagger 测试的,实际上用 Postman 也可以测试:

%title插图%num

 

二、方法一(导航跳转)

那么我们在 Blazor 中如何调用呢?先来看个简单的:

%title插图%num

 

可以看到直接使用 Navigation.NavigateTo 跳转到相关 WebApi 地址即可。由于该接口返回二进制流,浏览器就能直接识别进行下载了(动图):

%title插图%num

 

这种方法只是起个跳转的作用,实际下载动作还是在 WebApi  那边进行,缺点是下载结果不可知,优点是下载过程可见。

这个实际上不是本文讨论的重点,本文讨论的是,使用代替了 JS 代码的 C# 代码来下载文件到浏览器。

 

三、方法二(下载后传出)

那么如何实现呢?这个要分两步走,第一步是使用代码调用 API 进行下载文件,第二步是使用某种方法把文件通过浏览器传出给用户。

 

(一) 使用 RestSharp 下载

先来看看第一步,这里我们通过 Postman 得知可以使用 RestSharp 进行调用:

%title插图%num

 

我们通过 NuGet 安装 RestSharp 后,代码可以这样写:

var client = new RestClient($"http://frps.dlgcy.com:5000/Download?url={Url}");
var request = new RestRequest(Method.GET);
var response = await client.ExecuteAsync(request);

if (response.IsSuccessful)
{
    Tips = "下载成功!";

    var content = response.Content;
    var contentBytes = response.RawBytes;

    await BlazorDownloadFileService.DownloadFile(Path.GetFileName(Url), contentBytes, "application/octet-stream");
}
else
{
    Tips = "下载失败!";
}

 

(二) 使用 BlazorDownloadFile 传出

再来看看第二步,把下载的文件传出给用户,方法就是使用 BlazorDownloadFile 开源方案。

GitHub 地址:https://github.com/arivera12/BlazorDownloadFile

Blazor download files to the browser from c# without any JavaScript library or dependency.

BlazorDownloadFile is the solution to saving files on the client-side, and is perfect for web apps that generates files on the client.

However if the file is coming from the server we recommend you to first try to use Content-Disposition attachment response header as it has more cross-browser compatibility.

 

翻译:

在 Blazor 中通过 C#(不使用任何 JS 库和依赖)下载文件到浏览器。

BlazorDownloadFile 是在客户端保存文件的解决方案,它对于在客户端生成文件的应用来说是完美的。

然而如果文件是来自服务端,我们建议您优先使用 Content-Disposition 附件响应头,因为它有更好的跨浏览器兼容性。

 

1、安装(NuGet)

Install-Package BlazorDownloadFile -Version 2.1.6

 

2、添加服务

在 Startup 的 ConfigureServices() 中添加:

services.AddBlazorDownloadFile();

 

3、在 Blazor 的 Razor 页面中使用(2021.04.03更新)

//在页首添加引用:
@using BlazorDownloadFile
//可以直接这样注入;
@inject IBlazorDownloadFileService BlazorDownloadFileService

//在 code 中注入(可换为使用上面的注入方式):
//[Inject] IBlazorDownloadFileService BlazorDownloadFileService { get; set; }

//使用(这里是先获得了文件的字节数组再调用本方法)
await BlazorDownloadFileService.DownloadFile(Path.GetFileName(Url), contentBytes, "application/octet-stream");

 

图示:

%title插图%num

 
这样就可以根据下载是否成功来分别处理,成功时传出文件给用户,缺点是下载过程用户不可知,还需优化,效果如下(动图):
%title插图%num
 
最后给出源码地址:

https://gitee.com/dlgcy/VPSDownloader.NET/tree/Blog20210328

 

全文完,感谢阅读。

 

【翻译】WPF 中附加行为的介绍 Introduction to Attached Behaviors in WPF

【翻译】WPF 中附加行为的介绍 Introduction to Attached Behaviors in WPF

作者: 2008.08.30

翻译:独立观察员 2021.03.17

原文地址:https://www.codeproject.com/Articles/28959/Introduction-to-Attached-Behaviors-in-WPF

 

Explains the concept of attached behaviors and shows how to use them in the context of the MVVM pattern.

 

解释附加行为的概念并展示如何在 MVVM 模式上下文中使用它们。

 

[Demo 下载] Download demo project (requires Visual Studio 2008) – 21.3 KB

AttachedBehavior.jpg

 

引言 [Introduction]

This article explains what an attached behavior is, and how you can implement them in a WPF application. Readers of this article should be somewhat familiar with WPF, XAML, attached properties, and the Model-View-ViewModel (MVVM) pattern. I highly recommend that you also read my ‘Simplifying the WPF TreeView by Using the ViewModel Pattern’ article, because the material here is an extension of the material presented in it.

 

本文解释了什么是附加行为,以及您如何在 WPF 应用程序中实现它们。本文的读者需要稍微熟悉 WPF、XAML、附加属性、以及 MVVM 模式。我强烈建议您也阅读下我的文章《Simplifying the WPF TreeView by Using the ViewModel Pattern(通过使用 MVVM 模式来简化 WPF 的 TreeView)》,因为这里的素材就是对其中提及的素材的一个拓展。

 

背景 [Background]

Back in May of 2008, I published an article called ‘Simplifying the WPF TreeView by Using the ViewModel Pattern’. That article focused on the MVVM pattern. This morning, I woke up to find that a fellow by the name of Pascal Binggeli had asked an excellent question on that article’s message board.

 

回想 2008 年 5 月,我发布了一篇文章叫作《Simplifying the WPF TreeView by Using the ViewModel Pattern(通过使用 MVVM 模式来简化 WPF 的 TreeView)》的。那篇文章关注的是 MVVM 模式。今天早上,我醒来时发现一个叫 Pascal Binggeli 的家伙在那篇文章的留言板问了 一个极好的问题 。

 

Pascal wanted to know how to scroll a TreeViewItem into the viewable area of the TreeView control when its associated ViewModel object selects it. That seems simple enough, but upon further examination, it is not quite as straightforward as one might initially expect. The objective, and problem, is to find the proper place to put code that calls BringIntoView() on the selected TreeViewItem, such that the principles of the MVVM pattern are not violated.

 

Pascal 想知道怎样让一个 TreeViewItem 在与它关联的 ViewModel 对象中选中它时将它滚动到 TreeView 的可视区。这似乎足够简单,但在进一步检查之后,它似乎不像最初的期望那么简单。目标和问题是找到合适的地方放置代码来对选中的 TreeViewItem  调用 BringIntoView() ,同时不违反 MVVM 模式的理念。

 

For example, suppose that the user searches through a TreeView for an item whose display text matches a user-defined search string. When the search logic finds a matching item, the matching ViewModel object will have its IsSelected property set to true. Then, via the magic of data binding, the TreeViewItem associated with that ViewModel object enters into the selected state (i.e., its IsSelected property is set to true, too). However, that TreeViewItem will not necessarily be in view, which means the user will not see the item that matches their search string. Pascal wanted a TreeViewItem brought into view when the ViewModel determines that it is in the selected state.

 

例如,假设用户从一个 TreeView 中搜索显示文本匹配用户自定义搜索字符的一项。当搜索逻辑找到一个匹配项,ViewModel 中的匹配对象会将其 IsSelected 属性设置为 true 。然后,通过神奇的数据绑定,和这个 ViewModel 中的对象关联的 TreeViewItem 进入被选中的状态(比如,它的 IsSelected 属性也被设为 true )。然而,这个 TreeViewItem 不一定在视野中,这意味着用户将看不到匹配他搜索字符串的项。Pascal 想要 TreeViewItem 在 ViewModel 设定它为被选中状态时被带到视野中。

 

The ViewModel objects have no idea that a TreeViewItem exists, and is bound to them, so it does not make sense to expect the ViewModel objects to bring TreeViewItems into view. The question becomes, now, who is responsible for bringing a TreeViewItem into view when the ViewModel forces it to be selected?

 

ViewModel 对象不知道 TreeViewItem 的存在,也不能约束他们,所以期望 ViewModel 对象把 TreeViewItem 带到视野中是没有意义的。现在问题就变成了,当 ViewModel 设置一个 TreeViewItem 为被选中时谁负责将其带到视野中。

 

We certainly do not want to put that code into the ViewModel because it introduces an artificial, and unnecessary, coupling between a ViewModel object and a visual element. We do not want to put that code in the code-behind of every place a TreeView is bound to a ViewModel, because it reintroduces some of the problems that we avoid by using a ViewModel in the first place. We could create a TreeViewItem subclass that has built-in support for bringing itself into view when selected, but, in the WPF world, that is definitely a heavy-handed solution to a lightweight problem.

 

我们当然不想将代码放到 ViewModel 里,因为这将在 ViewModel 对象和视觉元素之间引入人工的不必要的耦合。我们也不想把代码放在每个放置了受 ViewModel 约束的 TreeView 的后置代码中,因为这将重新引入一些我们起初通过使用 ViewModel 避免了的问题。我们可以创建一个 TreeViewItem 子类,该类拥有当被选中时将自己带到视野中的内建支持,但是,在 WPF 的世界中,这肯定就是杀鸡用牛刀了。

 

How can we elegantly solve this problem in a lightweight and reusable way?

 

我们怎样通过一个轻量的、可复用的方式优雅地解决这个问题呢?

 

附加行为 [Attached Behaviors]

The solution to the problem explained above is to use an attached behavior. Attaching a behavior to an object simply means making the object do something that it would not do on its own. Here is the explanation of attached behaviors that I wrote in my ‘Working with CheckBoxes in the WPF TreeView’ article:

The idea is that you set an attached property on an element so that you can gain access to the element from the class that exposes the attached property. Once that class has access to the element, it can hook events on it and, in response to those events firing, make the element do things that it normally would not do. It is a very convenient alternative to creating and using subclasses, and is very XAML-friendly.

 

上面阐述的问题的解决方案就是使用 附加行为。附加行为到一个对象简单来说就是让一个对象做一些它之前自己不会做的事情。我把对附加行为的解释写在了我的文章《Working with CheckBoxes in the WPF TreeView(在 WPF 的 TreeView 中使用 CheckBoxes)》中:

这个点子就是,你在一个元素上设置一个附加属性,那么你就可以从暴露这个附加属性的类中获得该元素的访问。一旦那个类有权限访问那个元素,它就能在其上挂钩事件,响应这些事件的触发,使该元素做出它通常不会做的事情。创建和使用子类是个非常方便的选择,并且对 XAML 是非常友好的。

 

In that article, the demo application uses attached behaviors in complicated ways, but in this article, we will keep it simple. Enough with the background and theory, let’s see how to create an attached behavior that solves the problem posed by our friend Pascal.

 

在那篇文章中,Demo 程序以一种复杂的方式使用附加行为,但在这篇文章中,我们会让其简单。背景和理论足够了,让我们看看怎样创建一个附加行为来解决我们的朋友 Pascal 发布的问题吧。

 

论证 [Demonstration]

 

This article’s demo app, which is available for download at the top of this page, uses the Text Search demo provided by the ‘Simplifying the WPF TreeView by Using the ViewModel Pattern’ article. I made a few changes, such as adding more items to the TreeView, increasing the font size, and adding an attached behavior. The attached behavior is in a new static class called TreeViewItemBehavior. That class exposes a Boolean attached property that can be set on a TreeViewItem, called IsBroughtIntoViewWhenSelected. Here is the TreeViewItemBehavior class:

 

这篇文章的 Demo 程序(在本页顶部可供下载)使用了文章《Simplifying the WPF TreeView by Using the ViewModel Pattern》中提供的 “Text Search” 示例程序。我做了些修改,例如,往 TreeView 中添加了更多的项,增大了字体大小,添加了附加行为。附加行为在一个叫做 TreeViewItemBehavior 的新的静态类中。这个类暴露了一个可以被设置到 TreeViewItem 的 Boolean 类型的附加属性,叫作 IsBroughtIntoViewWhenSelected  。这就是 TreeViewItemBehavior 类:

 

/// <summary>
/// Exposes attached behaviors that can be applied to TreeViewItem objects.
/// 暴露可被应用到 TreeViewItem 对象的附加行为。
/// </summary>
public static class TreeViewItemBehavior
{
    #region IsBroughtIntoViewWhenSelected

    public static bool GetIsBroughtIntoViewWhenSelected(TreeViewItem treeViewItem)
    {
        return (bool)treeViewItem.GetValue(IsBroughtIntoViewWhenSelectedProperty);
    }

    public static void SetIsBroughtIntoViewWhenSelected(TreeViewItem treeViewItem, bool value)
    {
        treeViewItem.SetValue(IsBroughtIntoViewWhenSelectedProperty, value);
    }

    public static readonly DependencyProperty IsBroughtIntoViewWhenSelectedProperty =
        DependencyProperty.RegisterAttached(
        "IsBroughtIntoViewWhenSelected",
        typeof(bool),
        typeof(TreeViewItemBehavior),
        new UIPropertyMetadata(false, OnIsBroughtIntoViewWhenSelectedChanged));

    static void OnIsBroughtIntoViewWhenSelectedChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
    {
        TreeViewItem item = depObj as TreeViewItem;
        if (item == null)
            return;

        if (e.NewValue is bool == false)
            return;

        if ((bool)e.NewValue)
            item.Selected += OnTreeViewItemSelected;
        else
            item.Selected -= OnTreeViewItemSelected;
    }

    static void OnTreeViewItemSelected(object sender, RoutedEventArgs e)
    {
        // Only react to the Selected event raised by the TreeViewItem whose IsSelected property was modified. 
        // Ignore all ancestors who are merely reporting that a descendant's Selected fired.
        // 只对 IsSelected 属性被修改的 TreeViewItem 触发的 Selected 事件作出反应。
        // 忽略所有只是报告子孙的 Selected 被触发的祖先。
        if (!Object.ReferenceEquals(sender, e.OriginalSource))
            return;

        TreeViewItem item = e.OriginalSource as TreeViewItem;
        if (item != null)
            item.BringIntoView();
    }

    #endregion // IsBroughtIntoViewWhenSelected
}

 

The attached behavior seen above is basically just a fancy way of hooking the Selected property of a TreeViewItem and, when the event is raised, calling BringIntoView() on the item. The final piece of this puzzle is seeing how the TreeViewItemBehavior class gets a reference to every TreeViewItem in the TreeView. We accomplish that by adding a Setter to the Style applied to every item in the TreeView, as seen below:

 

上述附加行为从根本上来说只是一种挂钩 TreeViewItem 的  Selected 属性的一种有趣的方式,当事件被触发,就在该项上调用 BringIntoView() 。这个披萨的最后一块就是看看 TreeViewItemBehavior 类如何获得 TreeView 中的每个 TreeViewItem 。我们通过给应用到 TreeView 中的每一项的 Style 添加一个 Setter 来达成,如下所示:

 

 <TreeView.ItemContainerStyle>
  <Style TargetType="{x:Type TreeViewItem}">
    <!-- This Setter applies an attached behavior to all TreeViewItems. -->
    <!-- 这个 Setter 给所有 TreeViewItems 应用附加行为 -->
    <Setter Property="local:TreeViewItemBehavior.IsBroughtIntoViewWhenSelected" Value="True"/>

    <!-- These Setters bind a TreeViewItem to a PersonViewModel. -->
    <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
    <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
    <Setter Property="FontWeight" Value="Normal" />
    <Style.Triggers>
      <Trigger Property="IsSelected" Value="True">
        <Setter Property="FontWeight" Value="Bold" />
      </Trigger>
    </Style.Triggers>
  </Style>
</TreeView.ItemContainerStyle>

 

When the demo application loads up, the search text will be set to the letter Y automatically. Click the Find button a few times, and you will see that each time an item is selected, it will contain the letter Y and will scroll into view. The fact that it scrolls into view upon being selected means that the attached behavior is working properly.

 

当示例程序载入后,搜索文本会被自动设置为字母 Y。点击 Find 按钮几次,你会看到每次选中了一项,它包含了字母 Y 并且会滚动到视野中。一旦被选中就会滚动到视野中这个事实意味着附加行为工作正常。

 

结论 [Conclusion]

Hooking an event on an object and doing something when it fires is certainly not a breakthrough innovation, by any stretch of the imagination. In that sense, attached behaviors are just another way to do the same old thing. However, the importance of this technique is that it has a name, which is probably the most important aspect of any design pattern. In addition, you can create attached behaviors and apply them to any element without having to modify any other part of the system. It is a clean solution to the problem raised by Pascal Binggeli, and many, many other problems. It\’s a very useful tool to have in your toolbox.

 

无论你怎么想,在对象上挂钩事件并且在触发时做些事情当然不是一个突破性的创新。从这个层面来说,附加行为只是做相同旧事的另一种方式。然而,这个技术的重要之处就是它有个名称,这可能是任何设计模式的重要层面。而且,你可以创建附加行为并将它们应用到任何元素而无需修改系统的任何部分。它是对 Pascal Binggeli 提出的问题以及其它很多很多问题的一个清爽的解决方案,是您工具箱中非常有用的工具。

 

参考 [References]

 

版本历史 [Revision History]

  • August 30, 2008 – Created the article.
 

许可证 [License]

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

 

这篇文章,包括任何附带的源码和文件,在 The Code Project Open License (CPOL) 下被许可。

 

资源

[dlgcy] 源码下载:https://download.csdn.net/download/w19921004/15873706

[dlgcy] 效果演示(动图):

%title插图%num

 

2021年10月19日 更新:

[dlgcy] 附加属性帮助类修改为较通用的版本(添加支持 DataGridRow):https://gitee.com/dlgcy/WPFTemplateLib/blob/master/WpfHelpers/BringIntoViewBehavior.cs 

 

PostSharp 中 AOP 功能的简单使用

PostSharp 中 AOP 功能的简单使用

独立观察员 2021 年 2 月 21 日

 

年前在研究 .NET 中如何实现 AOP(Aspect-Oriented Programming,面向切面的编程)时看到了一篇叫做《C# 进阶系列 ——AOP?AOP!》的文章,作者在文章中介绍了静态拦截(装饰器模式)、动态代理(使用微软企业库)、IL 编织(使用 PostSharp)三种方式;而在作者提供的源码中,则是提供了前两者以及另外一种动态代理(使用 .Net Remoting / RealProxy)共三种方式;本人在原代码的基础上,改控制台测试程序为 Winform 测试程序,并补充上 PostSharp 的演示代码。

 

本文将介绍如何使用 PostSharp 中的 AOP 功能,实现在不修改原业务方法的情况下,记录方法运行的额外信息。

 

首先使用 NuGet 安装 PostSharp:

%title插图%num

 

然后我们就可以新建一个 AOP 的功能类(AOP_PostSharp),继承 PostSharp.Aspects.OnMethodBoundaryAspect,OnMethodBoundaryAspect 类的功能就是能够在被应用的方法体前后插入代码片段,该类也是有一系列的继承关系,最终的基类为 C# 的特性类 Attribute,所以我们新建的类实际上也是一个特性类。

%title插图%num

 

OnMethodBoundaryAspect 类有 OnEntry、OnException、OnExit、OnResume、OnSuccess、OnYield 等虚方法:

%title插图%num

 

我们重写了其中的 OnEntry、OnExit、OnException 三个方法,分别在方法执行前、执行后、发生异常时执行,我们这里就是记录了一下执行情况。

 

然后再加一个业务类,当作测试类(AOP_PostSharp_Tester),其中有个构造函数和两个业务方法,完整代码如下:

using PostSharp.Aspects;
using System;

namespace MyAOPApplication
{
    /// <summary>
    /// AOP 功能类
    /// </summary>
    [Serializable]
    public class AOP_PostSharp : PostSharp.Aspects.OnMethodBoundaryAspect
    {
        //发生异常时进入此方法
        public override void OnException(MethodExecutionArgs args)
        {
            base.OnException(args);
            Console.WriteLine($"发生异常了:{args.Exception}");
        }

        //执行方法前执行此方法
        public override void OnEntry(MethodExecutionArgs args)
        {
            base.OnEntry(args);
            Console.WriteLine($"即将执行方法 {args.Method}");
        }

        //执行方法后执行此方法
        public override void OnExit(MethodExecutionArgs args)
        {
            base.OnExit(args);
            Console.WriteLine($"方法执行结束 {args.Method}");
        }
    }

    /// <summary>
    /// AOP 测试类(业务类)
    /// </summary>
    [AOP_PostSharp]
    public class AOP_PostSharp_Tester
    {
        public AOP_PostSharp_Tester()
        {
            Console.WriteLine("构造函数");
        }

        //[AOP_PostSharp]
        public void Method1()
        {
            Console.WriteLine("方法一");
        }

        public void Method2()
        {
            Console.WriteLine("方法二");

            throw new Exception("测试抛出异常");
        }
    }
}

 

可以看到,我们在 AOP_PostSharp_Tester 类上添加了 AOP_PostSharp 特性,这样在该类中的每个方法执行过程中都会触发 AOP_PostSharp 类中的相关方法了。

 

接下来就是运行了,由于 PostSharp 从 2.0 开始要收费了,所以弹出了个选择许可证的窗口,同时编译出错了:

%title插图%num

 

许可证窗口有三个选项,分别是使用社区版(有限制)、试用旗舰版(45 天)、添加许可证,这里我们选择第一个:

%title插图%num

 

然后是同意许可条款:

%title插图%num

 

接下来是选择感兴趣的领域,可以看到 PostSharp 功能很强大,并不止局限于 AOP,这里至少要选择一项:

%title插图%num

 

按照我们代码的需求,应该只要选择第一个 Logging/tracing 就行了,为了保险起见,选择了 Diagnostics 类目下的全部三个:

%title插图%num

 

这样之后就能顺利编译了,测试程序中就是调用了测试类的两个方法:

%title插图%num

 

当把 AOP_PostSharp 特性放在类上时,从运行结果可以看出类中每个方法的执行过程都被记录了:

%title插图%num

 

而如果只把 AOP_PostSharp 特性放在某个方法上时,则只有这个方法的执行过程被记录了:

%title插图%num

 

由此可见 PostSharp 的 AOP 功能十分简单易用且强大,无需对业务类和方法做任何改动,只需加上个特性,就能达到记录信息的需求,可用于方法执行过程的监控、执行时间记录、异常记录等,大家可以自行探索,祝大家使用愉快。

 

最后,附上源码地址:https://gitee.com/dlgcy/MyAOPApplication

 

【分享】C# 字节帮助类 ByteHelper

【分享】C# 字节帮助类 ByteHelper

独立观察员 2021年2月3日

本文分享一个 C# 的字节(Byte)帮助类(ByteHelper),主要是一些字节、字节数组、十六进制、十六进制字符串等之间的转换操作,适用场景包括但不限于对于 M1 卡区块的读写时的数据转换等操作。

代码来源于网络,本人整理重构、仔细阅读代码并添加了较为详细的注释,一切说明见代码和注释,就不再赘述了,有不对的地方欢迎大家指出。

下面就是全部代码:

using System;
using System.Collections.Generic;
/*
 * 源码己托管: http://gitee.com/dlgcy/dotnetcodes
 */
namespace DotNet.Utilities
{
    /// <summary>
    /// 字节帮助类
    /// </summary>
    public class ByteHelper
    {
        /// <summary>
        /// 字节数组转为16进制字符串
        /// </summary>
        /// <param name="bytes">字节数组</param>
        /// <returns>16进制字符串</returns>
        public static string ToHexString(byte[] bytes)
        {
            string hexString = string.Empty;
            for (int i = 0; i < bytes.Length; i++)
            {
                hexString += ByteToHexStr(bytes[i]);
            }

            return hexString;
        }

        /// <summary>
        /// 字节转为16进制字符串(一个字节转为两个字符:[0-F][0-F])
        /// </summary>
        /// <param name="inByte">字节</param>
        /// <returns>字符串</returns>
        public static string ByteToHexStr(byte inByte)
        {
            string result = string.Empty;
            try
            {
                char[] hexDict = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
                char[] charParts = new char[2];
                charParts[0] = hexDict[(inByte >> 4) & 0x0F]; //放在byte左半部分的重新移回右边并匹配十六进制字符;
                charParts[1] = hexDict[inByte & 0x0F];        //放在byte右半部分的直接匹配十六进制字符;
                result = new string(charParts);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            return result;
        }

        /// <summary>
        /// 十六进制字符串转为字节数组
        /// </summary>
        /// <param name="hexStr">十六进制字符串</param>
        /// <returns>字节数组</returns>
        public static byte[] HexStrToBytes(string hexStr)
        {
            /* 说明:1byte=8bit,中文char=2byte(此处不考虑),英文char=1byte,
             1个“个位”的十六进制数占4bit,所以2个英文char转为十六进制数后占一个byte */
            byte[] bytes = new byte[hexStr.Length / 2 + (((hexStr.Length % 2) > 0) ? 1 : 0)];
            for (int i = 0; i < bytes.Length; i++)
            {
                char leftPart = hexStr[i * 2];
                char rightPart;

                if ((i * 2 + 1) < hexStr.Length)
                    rightPart = hexStr[i * 2 + 1];
                else
                    rightPart = '0';

                int a = ByteToHexValue((byte)leftPart);
                int b = ByteToHexValue((byte)rightPart);
                //由于16进制数的'个位'数只占4bit,所以左部分左移4位,加上右部分,共占8位,即一个byte;
                bytes[i] = (byte)((a << 4) + b);
            }

            return bytes;
        }

        /// <summary>
        /// 转换字节(实际为英文char)为16进制数据(0-15)
        /// </summary>
        /// <param name="b">字节</param>
        /// <returns>字节</returns>
        public static byte ByteToHexValue(byte b)
        {
            byte value = 0;

            if (b >= '0' && b <= '9')
            {
                //原值在ASCII中介于'0'-'9'之间的:减去0x30,即ASCII中'0'的十六进制表示(十进制为48),得到数值0-9。
                value = (byte)(b - 0x30);
            }

            if (b >= 'A' && b <= 'F')
            {
                //原值在ASCII中介于'A'-'F'之间的:减去0x37,十进制为55,‘A’的ASCII十进制为65,所以可得到数值10-15。
                value = (byte)(b - 0x37);
            }

            if (b >= 'a' && b <= 'f')
            {
                //原值在ASCII中介于'a'-'f'之间的:减去0x57,十进制为87,‘a’的ASCII十进制为97,所以可得到数值10-15。
                value = (byte)(b - 0x57);
            }

            return value;
        }

        /// <summary>
        /// 区块字符串数据转为区块字节数据(不足则补位:16字节)
        /// </summary>
        /// <param name="blockData">区块字符串数据</param>
        /// <returns>List<byte></returns>
        public static List<byte> GetBlockBytes(string blockData)
        {
            List<byte> blockBytes = new List<byte>();
            blockBytes.AddRange(HexStrToBytes(blockData));
            if (blockBytes.Count < 16)
            {
                for (int i = blockBytes.Count; i < 16; i++)
                {
                    blockBytes.Add(0x00);
                }
            }

            return blockBytes;
        }
    }
}

 

感谢阅读。

 

 

C# 在自定义的控制台输出重定向类中整合调用方信息

C# 在自定义的控制台输出重定向类中整合调用方信息

独立观察员 2021 年 1 月 6 日

 

一、前言

众所周知,在 .NET 的控制台应用程序(就是那种小黑框程序)中输出信息,使用的是控制台输出方法 Console.Write (“消息”) 或 Console.WriteLine (“消息”),这两个方法称为标准输出。而在 Winform、WPF、网页程序中,使用这种方法输出的信息是没有地方显示的,在这些程序中,我们一般把信息输出到相应的显示控件中,或者写入日志中。

 

比如我这有个 Winform 测试程序,相关按钮的后台逻辑就是向控制台输出 “哈哈哈”,一般情况下,点击这个按钮,左边的消息框将不会有任何消息输出:

%title插图%num

 

二、输出重定向基础版

但是这里却能显示出相关消息,是怎么回事呢?原来我在构造函数中添加了这么一句 —— Console.SetOut (new ConsoleWriter (ShowInfo));  —— 这就把原本输出到控制台的消息,重定向给了方法 ShowInfo 来进行输出,而 ShowInfo 方法内通过设置文本框的文本内容来达到了显示消息的效果:

%title插图%num

 

其中的关键就是自定义类 ConsoleWriter(后面有新版):

using System;
using System.IO;
using System.Text;
/*
 * 代码已托管 https://gitee.com/dlgcy/dotnetcodes/tree/dlgcy/DotNet.Utilities/ConsoleHelper
 */
namespace DotNet.Utilities.ConsoleHelper
{
    /// <summary>
    /// [dlgcy] Console 输出重定向
    /// 其他版本:DotNet.Utilities.WinformHelper.TextBoxWriter
    /// 用法示例:
    /// 在构造器里加上:Console.SetOut(new ConsoleWriter(s => { LogHelper.Write(s); }));
    /// </summary>
    /// <example>
    /// <code>
    /// public class Example
    /// {
    ///     public Example()
    ///     {
    ///         Console.SetOut(new ConsoleWriter(s => { LogHelper.Write(s); }));
    ///     }
    /// }
    /// </code>
    /// </example>
    public class ConsoleWriter : TextWriter
    {
        private readonly Action<string> _Write;
        private readonly Action<string> _WriteLine;
 
        /// <summary>
        /// Console 输出重定向
        /// </summary>
        /// <param name="write">日志方法委托(针对于 Write)</param>
        /// <param name="writeLine">日志方法委托(针对于 WriteLine)</param>
        public ConsoleWriter(Action<string> write, Action<string> writeLine)
        {
            _Write = write;
            _WriteLine = writeLine;
        }
 
        /// <summary>
        /// Console 输出重定向
        /// </summary>
        /// <param name="write">日志方法委托</param>
        public ConsoleWriter(Action<string> write)
        {
            _Write = write;
            _WriteLine = write;
        }
 
        // 使用 UTF-16 避免不必要的编码转换
        public override Encoding Encoding => Encoding.Unicode;
 
        // 最低限度需要重写的方法
        public override void Write(string value)
        {
            _Write(value);
        }
 
        // 为提高效率直接处理一行的输出
        public override void WriteLine(string value)
        {
            _WriteLine(value);
        }
    }
}

 

主要就是重写了 TextWriter 类的 Write 方法,然后在重写的 Write 方法中调用外部设置好的(通过构造函数)相关委托方法进行实际的信息输出。

 

以上就是之前的版本,工作地还不错。不过,当我们想在记录信息时同时记录调用方的信息时,问题就来了。

 

三、输出重定向进阶版(传递调用方信息)

要记录方法的调用方信息,我们很容易想到可以使用 C#5.0 中新增的获取调用方信息的方式,话不多说,改造 ShowInfo 方法如下即可:

/// <summary>
/// 显示消息
/// </summary>
private void ShowInfo(string info, [CallerFilePath] string filePath = "", [CallerMemberName] string memberName = "", [CallerLineNumber] int lineNumber = 0)
{
    TBInfo.Text += $"[{DateTime.Now:HH:mm:ss.ffff}][{filePath}][{memberName}][{lineNumber}] {info}\r\n\r\n";
}
 
//private void ShowInfo(string info)
//{
//    TBInfo.Text += $"[{DateTime.Now:HH:mm:ss.ffff}] {info}\r\n\r\n";
//} 

 

可以看到方法新增了以 CallerFilePath、CallerMemberName、CallerLineNumber 三个特性标注的三个可选参数,这样就能自动获得调用方法者的 文件名、成员名、行号了。

 

自然,构造函数中的重定向方法也需要更改:

public FormTest()
{
    InitializeComponent();
 
    //Console.SetOut(new ConsoleWriter(ShowInfo));
    Console.SetOut(new ConsoleWriter(msg => { ShowInfo(msg); }));
}

 

运行结果如下:

%title插图%num

 

表面上看好像信息都有了,但是定睛一看,怎么调用成员显示的是 .ctor 而不是 BtnConsoleRedirect_Click ?行号显示的是 18 而不是 69?其实这里显示的信息是构造函数的(因为重定向语句在那里)。那么有没有办法显示实际的调用位置呢?我们继续改造。

 

这次改造的是重定向类 ConsoleWriter:

using System;
using System.IO;
using System.Text;
/*
 * 代码已托管 https://gitee.com/dlgcy/dotnetcodes/tree/dlgcy/DotNet.Utilities/ConsoleHelper
 * 依赖:ClassHelper 类中获取调用信息的方法。
 */
namespace DotNet.Utilities.ConsoleHelper
{
    /// <summary>
    /// [dlgcy] Console 输出重定向
    /// 其他版本:DotNet.Utilities.WinformHelper.TextBoxWriter
    /// 用法示例:
    /// 在构造器里加上:Console.SetOut(new ConsoleWriter(s => { LogHelper.Write(s); }));
    /// </summary>
    /// <example>
    /// <code>
    /// public class Example
    /// {
    ///     public Example()
    ///     {
    ///         Console.SetOut(new ConsoleWriter(s => { LogHelper.Write(s); }));
    ///     }
    /// }
    /// </code>
    /// </example>
    public class ConsoleWriter : TextWriter
    {
        private readonly Action<string> _Write;
        private readonly Action<string> _WriteLine;
        private readonly Action<string, string, string, int> _WriteCallerInfo;
 
        /// <summary>
        /// Console 输出重定向
        /// </summary>
        /// <param name="write">日志方法委托(针对于 Write)</param>
        /// <param name="writeLine">日志方法委托(针对于 WriteLine)</param>
        public ConsoleWriter(Action<string> write, Action<string> writeLine)
        {
            _Write = write;
            _WriteLine = writeLine;
        }
 
        /// <summary>
        /// Console 输出重定向
        /// </summary>
        /// <param name="write">日志方法委托</param>
        public ConsoleWriter(Action<string> write)
        {
            _Write = write;
            _WriteLine = write;
        }
 
        /// <summary>
        /// Console 输出重定向(带调用方信息)
        /// </summary>
        /// <param name="write">日志方法委托(后三个参数为 CallerFilePath、CallerMemberName、CallerLineNumber)</param>
        public ConsoleWriter(Action<string, string, string, int> write)
        {
            _WriteCallerInfo = write;
        }
 
        /// <summary>
        /// 使用 UTF-16 避免不必要的编码转换
        /// </summary>
        public override Encoding Encoding => Encoding.Unicode;
 
        /// <summary>
        /// 最低限度需要重写的方法
        /// </summary>
        /// <param name="value">消息</param>
        public override void Write(string value)
        {
            if (_WriteCallerInfo != null)
            {
                WriteWithCallerInfo(value);
                return;
            }
 
            _Write(value);
        }
 
        /// <summary>
        /// 为提高效率直接处理一行的输出
        /// </summary>
        /// <param name="value">消息</param>
        public override void WriteLine(string value)
        {
            if (_WriteCallerInfo != null)
            {
                WriteWithCallerInfo(value);
                return;
            }
 
            _WriteLine(value);
        }
 
        /// <summary>
        /// 带调用方信息进行写消息
        /// </summary>
        /// <param name="value">消息</param>
        private void WriteWithCallerInfo(string value)
        {
            //3、System.Console.WriteLine -> 2、System.IO.TextWriter + SyncTextWriter.WriteLine -> 1、DotNet.Utilities.ConsoleHelper.ConsoleWriter.WriteLine -> 0、DotNet.Utilities.ConsoleHelper.ConsoleWriter.WriteWithCallerInfo
            var callInfo = ClassHelper.GetMethodInfo(4);
            _WriteCallerInfo(value, callInfo?.FileName, callInfo?.MethodName, callInfo?.LineNumber ?? 0);
        }
    }
}

 

即新增一个包含了调用方信息三个参数的委托 _WriteCallerInfo,以及配套的构造方法,然后在 Write 方法中优先使用 _WriteCallerInfo 委托方法。另外,引入了一个获取调用方信息的方法(改造自《C# 获取当前方法信息,上端调用方方法信息以及方法调用链》):

using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
/*
 * 代码已托管 https://gitee.com/dlgcy/dotnetcodes/tree/dlgcy/DotNet.Utilities/Object
 */
namespace DotNet.Utilities
{
    public class ClassHelper
    {
        #region 调用信息
 
        /* 参考:https://blog.csdn.net/m0_37886901/article/details/105266848 */
 
        /// <summary>
        /// 获取方法调用信息;
        /// </summary>
        /// <param name="index">0是本身,1是调用方,2是调用方的调用方...以此类推</param>
        /// <returns>MethodInfo 对象</returns>
        public static MethodInfo GetMethodInfo(int index)
        {
            try
            {
                index++; //由于这里是封装了方法,相当于上端想要获取本身,其实对于这里而言,上端的本身就是这里的上端,所以需要+1,以此类推
                var stack = new StackTrace(true);
 
                //0是本身,1是调用方,2是调用方的调用方...以此类推
                var currentFrame = stack.GetFrame(index);
                var method = currentFrame.GetMethod();
                var module = method.Module;
                var declaringType = method.DeclaringType;
                var stackFrames = stack.GetFrames();
 
                string callChain = string.Join(" -> ", stackFrames.Select((r, i) =>
                {
                    if (i == 0) return null;
                    var m = r.GetMethod();
                    return $"{m.DeclaringType.FullName}.{m.Name}";
                }).Where(r => !string.IsNullOrWhiteSpace(r)).Reverse());
 
                return new MethodInfo()
                {
                    Method = method,
                    ModuleName = module.Name,
                    Namespace = declaringType.Namespace,
                    ClassName = declaringType.Name,
                    FullClassName = declaringType.FullName,
                    MethodName = method.Name,
                    CallChain = callChain,
                    LineNumber = currentFrame.GetFileLineNumber(),
                    FileName = currentFrame.GetFileName(),
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return null;
            }
        }
 
        /// <summary>
        /// 方法调用信息
        /// </summary>
        public class MethodInfo
        {
            /// <summary>
            /// 方法完整信息;
            /// </summary>
            public MethodBase Method { get; set; }
 
            /// <summary>
            /// 模块名
            /// </summary>
            public string ModuleName { get; set; }
 
            /// <summary>
            /// 命名空间
            /// </summary>
            public string Namespace { get; set; }
 
            /// <summary>
            /// 类名
            /// </summary>
            public string ClassName { get; set; }
 
            /// <summary>
            /// 完整类名
            /// </summary>
            public string FullClassName { get; set; }
 
            /// <summary>
            /// 方法名
            /// </summary>
            public string MethodName { get; set; }
 
            /// <summary>
            /// 调用链
            /// </summary>
            public string CallChain { get; set; }
 
            /// <summary>
            /// 行号
            /// </summary>
            public int LineNumber { get; set; }
 
            /// <summary>
            /// 文件名
            /// </summary>
            public string FileName { get; set; }
        }
 
        #endregion
    }
}

 

最后,恢复测试程序构造函数处的重定向语句为之前的写法,自动识别为调用 ConsoleWriter 中我们新增的那个构造函数:

%title插图%num

 

运行,测试,可以看到方法名和行号都对了:

%title插图%num

 

四、后记及资源

这种重定向的方式个人觉得挺方便的,比如在动态库中全都写成输出控制台的方式,然后在主程序构造函数中指定重定向;另外,还可用于转录到日志:

%title插图%num

 

上图所示的日志方法参见:《『简易日志』NuGet 日志包 SimpleLogger》

 

本文测试程序相关代码:https://gitee.com/dlgcy/dotnetcodes/tree/dlgcy/DotNet.Utilities.Test

转录到日志的参考项目:https://gitee.com/dlgcy/WPFTemplate

 

.NET SDK-Style 项目(Core、Standard、.NET5)中的版本号

.NET SDK-Style 项目(Core、Standard、.NET5)中的版本号

独立观察员 2020 年 12 月 24 日

 

之前 .NET Framework 时,项目版本号等信息是存储在 AssemblyInfo.cs 文件中,通过程序集特性进行设置:

%title插图%num

 

.NET Core 之后,.NET 项目采用了新式的 SDK-Style 模式,将这些版本信息之类的也包含在项目文件里了,默认不再生成和使用 AssemblyInfo.cs 文件,而且如果你将这个文件添加上并填写相关信息,会提示有重复,编译不通过。虽然也有方法来恢复以前使用 AssemblyInfo.cs 的方式,但正所谓入乡随俗,既然人家改了模式,还是按规范来吧。

 

图形操作上和以前差不多,在 属性 – 打包 中有 “包版本”、“程序集版本” 和 “程序集文件版本”:

%title插图%num

 

编辑后就会在项目文件中出现,项目文件可通过在项目上右键 – 编辑项目文件 打开(此操作也是 SDK-Style 的特色):

%title插图%num

 

具体信息就是生成在 .csproj 的 PropertyGroup 节点内:

%title插图%num

 

程序集版本(AssemblyVersion)和以前一样(也支持通配符 *),包版本(Version)对应以前的程序集信息版本(AssemblyInformationalVersion),程序集文件版本(FileVersion)对应以前的(AssemblyFileVersion):

%title插图%num

 

另外,这里是在 WPF 中绑定了程序集版本信息,方法如下,也就是引入命名空间和使用:

%title插图%num

 

AssemblyHelper 如下:

using System.Reflection;
/*
 * 源码己托管:http://gitee.com/dlgcy/dotnetcodes
 */
namespace DotNet.Utilities
{
    /// <summary>
    /// 程序集帮助类
    /// </summary>
    public class AssemblyHelper
    {
        #region 程序集特性访问器

        /// <summary>
        /// 程序集标题
        /// </summary>
        public static string AssemblyTitle
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
                if (attributes.Length > 0)
                {
                    AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
                    if (titleAttribute.Title != "")
                    {
                        return titleAttribute.Title;
                    }
                }
                return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
            }
        }
        
        /// <summary>
        /// 程序集版本
        /// </summary>
        public static string AssemblyVersion
        {
            get
            {
                return Assembly.GetExecutingAssembly().GetName().Version.ToString();
            }
        }

        /// <summary>
        /// 程序集清单的其他版本信息
        /// </summary>
        public static string AssemblyInformationalVersion
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyInformationalVersionAttribute)attributes[0]).InformationalVersion;
            }
        }

        /// <summary>
        /// Win32 文件版本
        /// </summary>
        public static string AssemblyFileVersion
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyFileVersionAttribute)attributes[0]).Version;
            }
        }

        /// <summary>
        /// 程序集的文本说明
        /// </summary>
        public static string AssemblyDescription
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyDescriptionAttribute)attributes[0]).Description;
            }
        }

        /// <summary>
        /// 程序集清单的产品名
        /// </summary>
        public static string AssemblyProduct
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyProductAttribute)attributes[0]).Product;
            }
        }

        /// <summary>
        /// 程序集清单的版权
        /// </summary>
        public static string AssemblyCopyright
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
            }
        }

        /// <summary>
        /// 程序集清单的公司名称
        /// </summary>
        public static string AssemblyCompany
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyCompanyAttribute)attributes[0]).Company;
            }
        }

        #endregion
    }
}

 

这个和以前是通用的。

 

最后祝大家平安夜快乐!

 


后记(2020年12月26日):

版本号(Version)不是纯数字或带通配符可能会影响 Nuget 包还原,请知悉。程序集版本(AssemblyVersion)可带通配符,不受影响。

 

WPF 使用 Expression Design 画图导出及使用 Path 画图

WPF 使用 Expression Design 画图导出及使用 Path 画图

独立观察员 2020 年 11 月 21 日

 

一、软件介绍

最近接触到一个流程图画图软件,基本功能都有,但是不确定其中的提供的流程图完不完整,于是到在线画图网站 ProcessOn 上看了下。

%title插图%num

 

果然是缺少了几项,比如这个 “注释”:

%title插图%num

 

那么在 WPF 中如何添加图形呢?一种自然是使用图片,另一种则是使用 WPF 的 Xaml 语法生成图形,之前提到的软件是使用后者,本文探讨的也是这种。

 

使用代码(Xaml)生成图形毕竟也不是那么容易的,所以有没有什么简单的方法呢?毕竟 Xaml 的设计初衷之一就是让设计人员能够有方法按照其原有的工作方式进行设计,然后能生成相应的 WPF 或其它程序能使用的界面数据。众所周知,和 Visual Studio 同一家族的,还有个 Blend for Visual Studio,这个是用于做界面设计的,它能对界面效果做的设置项确实比 Visual Studio 多,但是如何使用它进行绘图设计,本人还是不得要领。

%title插图%num

 

有没有像 PhotoShop 一样能绘制图形,然后又能导出 Xaml 数据的软件呢?还真有,叫做 Microsoft Expression Design,可以从 MSDN, 我告诉你 网站下载  Expression Studio 4,里面包含了这个。(附 Ultimate 版激活码:6WDDQ-K7D4F-GQGF4-2VYBJ-8K6MB)。另外,微软已经放弃支持这套软件了,不过不影响我们使用它。

%title插图%num

 

二、Microsoft Expression Design 使用

下面来看看如何使用 Expression Design 4 来绘制之前说的注释流程图标志。

首先打开软件,新建一个 60*50 的画布(黑线框住的部分),然后拖一些标尺线来辅助定位:

%title插图%num

 

在左边的工具栏选择 折线 工具:

%title插图%num

 

在如下图的 1、2、3、4 四个点依次点击,然后按 ESC 键,就形成了目标图形,然后把线的宽度改为 5 像素:

%title插图%num

 

这就完成啦,可以导出了,选择文件 — 导出,会弹出导出窗口,具体可参考微软的说明:

https://docs.microsoft.com/zh-cn/previous-versions/visualstudio/design-tools/expression-studio-4/cc294753(v=expression.40)

 

导出格式可选项中和 WPF 有关的一个是 XAML WPF 画布:

%title插图%num

 

还有一个是 XAML WPF 资源字典:

%title插图%num

 

画布导出的是 Path 元素数据,资源字典导出的是画刷资源数据,不过可以看到两者的关键数据(对于画布来说就是 Path 的 Data 数据)是一致的:

%title插图%num

 

注意:本文探讨的是使用画布导出的这种数据形式,也就是使用 Path 元素来绘制图形,其 Data 中的字符串数据是一种被称为 微语言 的简便表示方式。

 

言归正传,大家可以看到之前我们选择 “要导出的项” 时选的是 “选定对象”,这就导致图形没有了边距,所以我们可以选择 “整个文档” 来避免这种问题:

%title插图%num

 

这样微语言数据中就体现出边距了:

%title插图%num

 

至此,导出的数据可以任君使用了。这种纯粹的 Xaml 文件还可以直接在浏览器中打开:

%title插图%num

 

三、微语言和 Path 绘图

先看看《WPF 编程宝典》中关于微语言图形命令的列举:

%title插图%num

 

1、”注释” 图形(中括号)

我们拿出之前导出数据的 Data 值:

F1 M 20,7.5625L 7.5,7.5625L 7.5,42.5L 20,42.5

 

F 命令设为 1 时具有穿透效果,此处可省略;太精细的小数位数可去除;所以可优化如下:

M 20,7.5 L 7.5,7.5 L 7.5,42.5 L 20,42.5

 

M 表示起点,L 表示直线,对应到图上则如下:

%title插图%num

 

以上所示实际上是通过把线条加粗来形成图形,所以无法再有描边了,设置非透明填充后效果如下:

%title插图%num

 

而一般是要用细线条围出图形,这样既有描边又有填充。Path 的 Data 数据如下:

M 20,5 L5,5 L5,45 L20,45 L20,40 L10,40 L10,10 L20,10 Z

这里多出个 Z 命令,表示终点和起点相连形成封闭图形。所以各命令和坐标对应到图形上就是:

%title插图%num

 

效果如下:

%title插图%num

 

2、”并行模式” 图形(平行线)

经过上一小节绘制 “注释” 的过程可以看出,实际上熟练了之后,我们确实不需要使用 Expression Design 来导出数据,只需要一个画图软件来辅助确定一下坐标就行了。甚至再熟练一点,我们在脑海中就能确定坐标了,哈哈。

 

这一小节我们来画下面这个 “并行模式”,实际上就是两条平行线:

%title插图%num

 

直接使用截图软件来画图了,确定下坐标: 

%title插图%num

 

这个图形需要两个起点,所以微语言命令中出现了两个 M:

M5,5 L55,5 L55,10 L5,10 Z M5,40 L55,40 L55,45 L5,45 Z

 

效果如下(改变了渐变方向):

%title插图%num

 

3、”页面内引用” 图形(圆形)

页面内引用 使用一个圆形来表示:

 %title插图%num

 

圆形需要使用画圆弧的命令 A 来绘制,具体可参考网上的文章《WPF 使用 PATH 来画圆》,以下为要点摘录:

Data=”M 300,300 A 100,100 0 1 1 300,299 Z”

    M 300,300  表示起始坐标,字母 M 为 Move, 意思是将画笔移到 300,300 处;

    A 100,100 0 1 1 300,299 这是圆弧的书写语法,详细格式如下:
        A 表示 Arc 圆弧,
        100,100 表示圆弧的 x, y 值,表示椭圆时表示大小半径,圆是两值相同;
        0 表示图形的旋转角度;
        1 当图形设置了旋转角度,并且大于 180 度时,才会生效,1 表示取大圆弧,0 表示取小圆弧;
        1 表示画圆时笔画是是顺时针画,需要逆时针时设置为 0;
        300,299 表示终止坐标。

    Z 表示路径闭合。

 

我们这里将起点设为上边的中间位置(30,0),半径为 25,终止坐标不能和起点重合,所以做个微小的偏移(29,1),最后使用 Z 命令闭合,所以微语言命令如下:

M 30,0 A 25,25 0 1 1 29,1 Z

 

最终效果如下:

%title插图%num

 

好了,就先到这里吧,算是抛砖引玉。

 

→←