分类目录编程

在WPF的MVVM模式中使用OCX组件

在WPF的MVVM模式中使用OCX组件

独立观察员 2018.09.11

OCX的正确使用姿势是在网页上使用,那么如果第三方只提供了OCX,我们在WPF程序中该如何调用呢?本文就来探讨该问题。

一、从OCX生成dll

按照《WPF 引用 OCX 控件 – CSDN 博客》的方法来:

1、先注册 OCX 控件;(有的把 OCX 控件封装到 EXE 文件中,安装即可);

2、打开 vs,新建一个 winform 程序,在工具箱中添加 COM 组件(把刚才注册的 OCX 控件)引用进来,这时就会看到当前 winform 程序 Debug 目录下会多出 2 个 DLL;

3、打开 vs,新建一个 WPF 程序,把上面的 2 个 DLL 引用上就可以了。

 

比如,我有一个 “TZ_SignMainDevOcx.ocx” 组件,经过以上方法,可得到以下两个文件:”AxInterop.TZ_SignMainDevOcxLib.dll” 和 “Interop.TZ_SignMainDevOcxLib.dll”。

 

二、添加到WPF项目中

我们要引用的是”AxInterop.TZ_SignMainDevOcxLib.dll”,”Interop.TZ_SignMainDevOcxLib.dll”是它的依赖项:

%title插图%num

 

换言之,我们需要的方法都在带 “AxInterop” 前缀的dll中,而带 “Interop” 前缀的则是其依赖项。从图中还可以看出,实际要使用的类是在原OCX中的类前加上了 “Ax” 前缀。

 

三、MVVM方式调用

1、Xaml 添加一个隐藏的占位:

<ContentControl Grid.Row="1" Content="{Binding OcxContent}" Visibility="Collapsed"/>

 

2、ViewModel 中(使用AxTZ_SignMainDevOcx类):

// 绑定的对象
private object _ocxContent;
public object OcxContent
{
	get => _ocxContent;
	set => SetProperty(ref _ocxContent, value);
}

// 。。。

// 在主线程中实例化 com 组件
var axtz = new AxTZ_SignMainDevOcx();

// WPF 承载 windows 组件
System.Windows.Forms.Integration.WindowsFormsHost host = new System.Windows.Forms.Integration.WindowsFormsHost();
host.Child = axtz;

// 除了实例化 com 组件,还要将该对象进行初始化
((System.ComponentModel.ISupportInitialize)axtz).BeginInit();
OcxContent = new StackPanel
{
	Children = { host}
};
((System.ComponentModel.ISupportInitialize)axtz).EndInit();

// 调用
int ret = axtz.TZ_QrCodePrinter(0, "USB001", 0, 0, 5, info.barCode);

 

关键一点就是,除了要实例化相关对象,还要对其进行初始化。所以,如果是在Winform中使用,只要在 BeginInit 和 EndInit 之间,将实例化出的控件对象添加到界面中即可。

这里展示的是WPF的情况:

(1)要在主线程实例化相关对象,参见《当前线程不在单线程单元中, 因此无法实例化 ActiveX 控件的解决方案》

(2)WPF 承载 windows 组件必须用 WindowsFormsHost(需引用WindowsFormslntegration),参见《WPF 中实例化 Com 组件,调用组件的方法时报 System.Windows.Forms.AxHost+InvalidActiveXStateException 的异常》

(3)添加控件的方法我采用了MVVM的方式:Xaml中内容控件 ContentControl 的内容绑定了一个对象,然后新建一个StackPanel(或其它合适的容器)赋值给它,并将com组件的宿主(host)放在其中(赋值给Children),以此来完成初始化。

 

3、最后,就可以像调用普通方法一样调用了。

Unity容器依赖注入之属性注入使用备忘

Unity容器依赖注入之属性注入使用备忘

——独立观察员 2018.08.18

最近在做我的毛坯项目”笔记扩展“,使用了WPF的MVVM模式,使用了Prism框架的一些功能,还没有使用依赖注入功能,于是打算尝试一下。

Prism框架官方支持Unity 和 MEF 两种 DI 容器,也就是官方实现了这两种容器的初始化配置等,当然你也可以使用其他的容器,只不过需要自己配置而已。Unity是微软团队Practices开发的,目前已转为社区维护,代码托管于GitHub。

Unity容器支持三种依赖注入方式:构造器注入 (Constructor Injection)、属性注入 (Property Injection),以及方法调用注入 (Method Call Injection)。本文主要讨论属性注入方式。

本人认为,依赖注入的好处,除了老生常谈的方便切换依赖项的实现外,还有就是可以方便地传值,有点像是全局变量的感觉。当然,这一点应该是要设置容器内使用单例模式。本文主要展示这方面的用法,有不对的地方欢迎指正。

好了,废话少说,Let’s go!

 

1、建立模型

 

首先,新建一个模型类的接口和其默认实现:

namespace Note.Models
{
    public interface IModifyConfigModel
    {
        string Key { get; set; }

        string Value { get; set; }
    }

    public class ModifyConfigModel : IModifyConfigModel
    {
        public string Key { get; set; }

        public string Value { get; set; }
    }
}

 

2、注册类型

 

然后我们打开Bootstrapper.cs文件,这个是Prism的启动类,可以通过让它继承哪个类,来决定使用哪个容器:

%title插图%num

这里我们继承的是UnityBootstrapper类,也就是说我们使用的是Unity容器。

 

UnityBoostrapper类做了很多初始化工作,其中,在ConfigureContainer方法中注册了很多类型,使用的是RegisterTypeIfMissing方法:

%title插图%num

 

所以,如果我们要注册自己的类型,就需要在Bootstrapper类中覆写ConfigureContainer方法:

protected override void ConfigureContainer()
{
	base.ConfigureContainer();

	RegisterTypeIfMissing(typeof(IModifyConfigModel), typeof(ModifyConfigModel), true);
}

 

同样使用 RegisterTypeIfMissing 方法,第一个参数传递接口类型,第二个参数传递实现类型,第三个参数指定是否使用单例模式。

 

下面来看看RegisterTypeIfMissing方法是怎样的:

%title插图%num

 

其中Container就是Unity的容器对象,如果不是使用Prism框架而是直接使用Unity的话,需要自己初始化这个对象。

然后其内部是使用Container的RegisterType方法来注册类型的。

 

3、存数据

 

注册好类型之后,我们就可以使用了。

属性注入的语法是使用Dependency特性,我们在ViewModel中添加一个属性:

[Dependency]
public IModifyConfigModel ModifyConfigModel { get; set; }

 

然后就可以对该对象的属性进行赋值了,不需要创建该对象,因为容器会代劳的:

ModifyConfigModel.Key = nameof(DbPath);
ModifyConfigModel.Value = DbPath;
ConfigManager.SetValueTestIoc();

 

赋的值是什么不用管,其中第三行的方法中使用了这些值,在另一个类中。为什么舍近求远?只是为了测试。

 

4、取数据

 

上面提到的方法如下:

//[Dependency]
//public static IModifyConfigModel ModifyConfigModel { get; set; }

public static bool SetValueTestIoc()
{
	//return SetValue(ModifyConfigModel.Key, ModifyConfigModel.Value);

	IModifyConfigModel modifyConfigModel = 
		ServiceLocator.Current.GetInstance<IModifyConfigModel>();
	return SetValue(modifyConfigModel.Key, modifyConfigModel.Value);
}

 

其中注释掉的部分我们称之为”方式一”,未注释的部分自然就是”方式二”了。

 

通常是使用方式一的,只要像这样声明同样的依赖注入属性,就可以取得里面的值。但是这种方式有的时候会失效,比如这里的ModifyConfigModel就为null。听说是生命周期的原因,我也没有去深究,因为我们可以使用方式二。

 

方式二使用了ServiceLocator来获取实例,可以完美达到预期效果。

 

最后提一下,ServiceLocator 的命名空间为Microsoft.Practices.ServiceLocation,Unity的命名空间为Microsoft.Practices.Unity,感兴趣的朋友可以自行探索其中的异同点。

 

5、参考

 

(1)《Microsoft.Practices.Unity 入门 – 在 delphi 路上 – 博客园》

(2)《Prism 5 程序初始化过程 – Andy Ho – 博客园》

添加服务引用来使用WebService

添加服务引用来使用WebService

——独立观察员 2018.05.26

众所周知,当今社会是个合作的时代,所以,即使是以往特立独行的程序员,如今也是时常要与各方合作的。这其中,有的情况是需要提供服务给其他人的,而在其中起支撑作用的技术之一就是今天的主角——WebService。

提供服务的一方会给出一个WebService的地址,形如:http://192.168.16.19:1010/WebServicePublic.asmx。当然,如果需要提供给大众使用,自然需要提供的是公网地址。

当我们拿到这个地址,就可以在VS中”添加服务引用”了。但是,如果是像上面这样的内网地址,那么直接添加是添加不上的。

此时就需要使用wsdl方式了:在地址后面添加”?wsdl”,然后在浏览器中打开,就是一篇XML格式的内容,将这些内容保存为”.wsdl”后缀的文件,备用。(注意,将第一个<wsdl>节点前面的内容删去。)

然后,我们点击添加服务引用,将刚才准备的wsdl文件路径填入地址栏,按下回车,就能发现服务了(命名空间可改):

%title插图%num

 

点击确定后,就添加进项目中了。并在App.config中添加了配置信息,从中可以看到,绑定的名字为”WebServicePublicSoap”,在节点client下:

%title插图%num

 

这样我们实例化一下相关类型(这里是一个以Client结尾的类型)的对象后就能使用其中提供的方法了:

ServiceReference1.WebServicePublicSoapClient webService = new WebServicePublicSoapClient();
webService.intZHYLService();

 

另外,如果因为某些原因使用不了App.config配置信息的话,也可以手动设置服务地址:

public static string HISAddress { get; set; } = "http://192.168.16.19:1010/WebServicePublic.asmx";
public static ServiceReference.WebServicePublicSoapClient HisService { get; set; }


HisService = new ServiceReference.WebServicePublicSoapClient(
new BasicHttpBinding()
{
	MaxReceivedMessageSize = int.MaxValue,
	MaxBufferPoolSize = int.MaxValue,
	MaxBufferSize = int.MaxValue,
	SendTimeout = new TimeSpan(0, 2, 0)
	},
	new EndpointAddress(HISAddress)
);


HisService.intZHYLService(tradeType, str, ref recStr);

 

完。

VisualStudio 使用 DialogPage 存储配置信息

VisualStudio 使用 DialogPage 存储配置信息

——独立观察员 2018.04.01

最近在使用和修改VisualStudio扩展插件 CopyWithLocation (该插件功能为:复制代码时自动带上方法名、类名等,本人略作修改,添加带上命名空间功能)时留意到它的配置选项功能,由于该插件比较简单,所以正好借此研究一下VS插件的配置选项功能如何实现。

我在该插件的原有的相关功能处添加了一个”Test”项,以测试该功能,完整代码如下:

public class CopyWithLocationOptions : DialogPage
{
    [DisplayName("Method copy format")]
    [Description("Use \"{0}.{1}.{2} [{3}] \\r\\n{4}\" to copy method like \"NameSpace.MyClass.MyMethod [LineStart-LineEnd] \r\n Selected code\"")]
    public string MethodCopyFormat { get; set; }
   
    [DisplayName("Class copy format")]
    [Description("Use \"{0}.{1} [{3}] \\r\\n{4}\" to copy class like \"NameSpace.MyClass [LineStart-LineEnd] \r\n Selected code\"")]
    public string ClassCopyFormat { get; set; }
   
    [DisplayName("Code block copy format")]
    [Description("Use \"{1}\\{2} [{3}] \\r\\n{4}\" to copy code block like \"FilePath\\FileName [LineStart-LineEnd] \r\n Selected code\"")]
    public string CodeBlockCopyFormat { get; set; }
   
    [DisplayName("配置项名称")]
    [Description("配置项介绍")]
    public string Test { get; set; }
   
    public override void ResetSettings()
    {
        MethodCopyFormat = null;
        ClassCopyFormat = null;
        CodeBlockCopyFormat = null;
   
        base.ResetSettings();
    }
   
    protected override void OnActivate(CancelEventArgs e)
    {
        LoadDefaultSettingsIfNecessary();
   
        base.OnActivate(e);
    }
   
    public void LoadDefaultSettingsIfNecessary()
    {
        MethodCopyFormat = string.IsNullOrEmpty(MethodCopyFormat) ? "{0}.{1}.{2} [{3}] \r\n{4}" : MethodCopyFormat;
        ClassCopyFormat = string.IsNullOrEmpty(ClassCopyFormat) ? "{0}.{1} [{3}] \r\n{4}" : ClassCopyFormat;
        CodeBlockCopyFormat = string.IsNullOrEmpty(CodeBlockCopyFormat) ? "{1}\\{2} [{3}] \r\n{4}" : CodeBlockCopyFormat;
        Test = string.IsNullOrEmpty(Test) ? "配置项默认值" : Test;
    }
}

 

效果(点击VS菜单栏”工具”->”选项”):

%title插图%num

 

分析:

只需添加一个类(应该是组件类模板,不过我是通过普通类模板创建的,也行),继承 Microsoft.VisualStudio.Shell.DialogPage 类,然后设置一个公共属性,即可作为一个配置项,可自动存取配置信息。

[DisplayName("配置项名称")]
[Description("配置项介绍")]
public string Test { get; set; }

 

可在重写的 OnActivate 方法中对配置项的值进行初始化,比如为空时设置一个默认值,这样用户删除配置项的值,保存后重新打开设置窗口就可以获取默认值了。

Test = string.IsNullOrEmpty(Test) ? "配置项默认值" : Test;

 

然后需要在 XXXPackage.cs 文件中,使用 ProvideOptionPage 特性来指定配置页:

[ProvideOptionPage(typeof(NoteExtensionsOptions), "NoteExtensionsOptions Category", "NoteExtensionsOptions Page", 1000, 1001, true)]
public sealed class Command1Package : Package{//...}

 

第一个参数指定配置项设置类,第二个参数是配置项名字,第三个参数是配置页(放在配置项下的)名字,效果:

%title插图%num

 

可以设置多个ProvideOptionPage来组织配置页面:

[ProvideOptionPage(typeof(NoteExtensionsOptions), "NoteExtensionsOptions Category", "NoteExtensionsOptions Page", 1000, 1001, true)]
[ProvideOptionPage(typeof(NoteExtensionsOptions), "NoteExtensionsOptions Category", "NoteExtensionsOptions Page 2", 1000, 1001, true)]
[ProvideOptionPage(typeof(NoteExtensionsOptions), "NoteExtensionsOptions Category 2", "NoteExtensionsOptions Page", 1000, 1001, true)]
public sealed class Command1Package : Package

 

效果:

%title插图%num

 

最后,使用 Category 特性设置配置类里的属性可进行配置项的分组,未设置则分到”杂项”组:

[Category("设置项类别")]
[DisplayName("设置项1")]
[Description("描述1")]
public string MethodCopyFormat { get; set; }
  
[DisplayName("设置项2")]
[Description("描述2")]
public string ClassCopyFormat { get; set; }
   
[DisplayName("设置项3")]
[Description("描述3")]
public string CodeBlockCopyFormat { get; set; }

 

效果:

%title插图%num

 

好了,就说这么多吧。网上这方面的内容还是比较少的,希望大家多多交流。

 

分页SQL语句

分页SQL语句

——独立观察员 2018.01.21

做网站开发的都知道,显示列表项过多时会采取分页。本文主要讨论分页中的SQL语句,仅供参考。

以下是C#中的参数化的SQL语句片段,展示了分页时的情况:

string strSql = @"select top(@num) *

            from (

                select id, c_info_title,

                    count(*) over() AS Total,

                    row_number() over(order by n_is_head, n_order desc, d_list_date desc, id desc) AS num

                from B_NEWS

                where n_is_active=1

            ) AS T

            where num>@index";



SqlParameter[] paras ={

    new SqlParameter("@num", perPageCount)

    new SqlParameter("@index", perPageCount*(curPage-1))

};

 

可以看出,该SQL语句中使用了嵌套查询。内层查询中使用了开窗函数over(),关于开窗函数,可参考文章《sql开窗函数over()用法》,总之,开窗函数能很方便让我们把聚集函数的值放到查询项中。话归正题,上面的SQL语句使用了count(*) over()来查询出总行数,使用row_number() over()来设置行号,其它都是常规查询。

然后是外层查询,使用top()来限定最终查询几条,参数@num传递的就是每页的条数。使用where num>@index来限定外层查询的起始位置,@index也就是当前页第一条的上一条的位置,或者说是当前页的上一页的最后一条的位置,num是内层查询出的行号。

以上就是本次介绍的分页SQL语句,再配合Ajax查询、JS翻页插件,就能实现列表页的翻页了。

接下来我们再说说详情页的SQL语句:

string sql =

    @"DECLARE @TempTable Table(num int, id int, title nvarchar(200), date varchar(100), c_info_content ntext

    

    insert into @TempTable

    select row_number() over(order by n_is_head, n_order desc, d_list_date desc, id desc) AS num, id, c_info_title AS title, CONVERT(varchar(100), d_list_date, 111) AS date, c_info_content

    from B_NEWS where n_is_active=1 and c_kind_num=@kind

    

    DECLARE @num int

    set @num=(select top(1) num from @TempTable where id=@id)

    

    select *,

        (select top(1) id from @TempTable where num=@num-1) AS id_up,

        (select top(1) id from @TempTable where num=@num+1) AS id_down,

        (select top(1) title from @TempTable where num=@num-1) AS title_up,

        (select top(1) title from @TempTable where num=@num+1) AS title_down,

        (select top(1) date from @TempTable where num=@num-1) AS date_up,

        (select top(1) date from @TempTable where num=@num+1) AS date_down

    from @TempTable where id=@id";

    

SqlParameter[] paras =

{

    new SqlParameter("@id", id),

    new SqlParameter("@kind", curKind)

};

 

该语句首先声明了一个表变量@TempTable用于存放查询的中间结果(听说表变量会有性能损失,可考虑用公用表(with as),不过公用表限制比较大,试过了,不合适)。然后将带行号的查询结果插入表变量中。第三部分是声明了一个变量@num用于存放当前要查询记录的行号。最后就是复用表变量,分别查询出当前记录数据、上一条相关信息、下一条相关信息。参数@id就是待查询记录的ID。另外,此处的”上一条”指在列表页中排列在更上面的一条,所以查询时为行号减一。

全剧终!谢谢观赏!

 

『笔记分享』GridView 自定义分页

『笔记分享』GridView 自定义分页

——独立观察员 2016.01.19

参加工作也有一段时间了,如果要找出在学习方面,参加工作后与在学校时的区别的话,那就是,工作后(从实习开始),我无师自通地就开始使用云笔记产品摘录各种知识和遇到的问题,积累了很多,也从中受益匪浅。当然,这一切如此自然而然地发生了,还要感谢我使用的这款云笔记产品——”麦库记事”,在此隆重推荐。我觉得”麦库记事”是最适合程序员使用的一款”云笔记”,我尤其喜欢它的代码高亮功能,以及直接粘贴图片的功能,当然,它还有其它比如收藏微信文章、粘贴Word内容等强大功能,真是令人爱不释手,甚至对于其偶尔的服务不畅都能容忍了。

好了,免费打了这么久广告,还是言归正传吧,当然,如果”麦库记事”的人员看到了请来付下广告费哈。说到我积累了好多笔记,然后我又这么爱分享,所以决定今后时不时地就分享些笔记。这次分享的呢,就如标题所示,是关于ASP.NET中的GridView的分页问题的,接下来就进入正题了。

先来看看效果(可能混合了其它样式):

%title插图%num

1、前台 GridView 中:

<PagerTemplate>
    <div class="pager">
        <div class="pagerLittleBlock">
            <asp:LinkButton ID="LinkButtonFirstPage" runat="server" CommandArgument="First" CommandName="Page" Text="First" />
            <asp:LinkButton ID="LinkButtonPreviousPage" runat="server" CommandArgument="Prev" CommandName="Page" Text="Previous" />
        </div>
        <div class="pagerLittleBlock">
            <asp:Label runat="server" Text="Page" />
            <asp:Label ID="LabelCurrentPage" runat="server" Text="<%# ((GridView) Container.NamingContainer).PageIndex + 1 %>" />
            <asp:Label runat="server" Text="of" />
            <asp:Label ID="LabelPageCount" runat="server" Text="<%# ((GridView) Container.NamingContainer).PageCount %>" />
        </div>
        <div class="pagerLittleBlock">
            <asp:LinkButton ID="LinkButtonNextPage" runat="server" CommandArgument="Next" CommandName="Page" Text="Next" />
            <asp:LinkButton ID="LinkButtonLastPage" runat="server" CommandArgument="Last" CommandName="Page" Text="Last" />
        </div>
        <div class="pagerLittleBlock">
            <asp:Label runat="server" Text="Turn To Page:" />
            <asp:TextBox ID="txtNewPageIndex" runat="server" Text='<%# ((GridView)Container.Parent.Parent).PageIndex + 1 %>' />
            <asp:LinkButton ID="btnGo" runat="server" CausesValidation="False" CommandArgument="-2" CommandName="Page" Text="GO" />
        </div>
 
        <%--PageSize需要后台配合--%>
        <asp:DropDownList ID="ddlPageCount" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlPageCount_OnSelectedIndexChanged" Text="<%# ((GridView) Container.NamingContainer).PageSize %>" CssClass="pageSizeLabel">
            <asp:ListItem>10</asp:ListItem>
            <asp:ListItem>15</asp:ListItem>
            <asp:ListItem>20</asp:ListItem>
            <asp:ListItem>30</asp:ListItem>
            <asp:ListItem>50</asp:ListItem>
        </asp:DropDownList>
        <asp:Label runat="server" Text="Page size:" CssClass="pageSizeLabel" />
 
        <div class="pageSizeLabel">(Total <%# ((System.Data.DataTable)((GridView) Container.NamingContainer).DataSource).Rows.Count %> Items)</div>
    </div>
</PagerTemplate>

 

单击 CommandName 属性设置为”Page”的按钮控件时,GridView 控件会执行分页操作。按钮的 CommandArgument 属性确定要执行的分页操作的类型。”Next”导航至下一页,”Prev”导航至上一页, “First”导航至第一页, “Last”导航至最后一页,整数值导航至指定页码。(参考:《GridView >PagerTemplate> 页码》)

 

2、后台:

#region 翻页事件;
 
public delegate void BindGridViewDelegate();
protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e, BindGridViewDelegate bindGridView)
{
    GridView theGrid = sender as GridView;
    int newPageIndex = 0;
 
    if (e.NewPageIndex == -3) //点击了Go按钮; "-3"是按钮的CommandArgument-1;
    {           
        TextBox txtNewPageIndex = null;
 
        GridViewRow pagerRow = theGrid.BottomPagerRow;
        if (pagerRow != null)
        {                  
            txtNewPageIndex = pagerRow.FindControl("txtNewPageIndex") as TextBox;
        }
        if (txtNewPageIndex != null)
        {
            newPageIndex = int.Parse(txtNewPageIndex.Text) - 1; //得到索引
        }
    }
    else //点击了其他的按钮
    {              
        newPageIndex = e.NewPageIndex;
    }
    //防止新索引溢出
    newPageIndex = newPageIndex < 0 ? 0 : newPageIndex;
    newPageIndex = newPageIndex >= theGrid.PageCount ? theGrid.PageCount - 1 : newPageIndex;
    //得到新的值
    theGrid.PageIndex = newPageIndex;
 
    //重新绑定数据;使用了委托;
    bindGridView();
}
 
protected void gvMonthProductivity_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView_PageIndexChanging(sender, e, gvMonthProductivityBind);
}
 
protected void ddlPageCount_OnSelectedIndexChanged(object sender, EventArgs e)
{
    gvMonthProductivity.PageSize = int.Parse((sender as DropDownList).SelectedValue.ToString());
    gvMonthProductivityBind();
}
 
#endregion

 

其中,后两个方法中需要按实际修改,也就是注意替换绑定数据的方法,以及GridView对象。

 

3、CSS参考:

/* GridView 翻页区 */

.pager

{

font-size:15px;

margin-top:2px;

margin-bottom:4px;

}

.pager a:link{ color:#000}

.pager a:hover{ color:#000}

.pager a:active{ color:#000}

.pager a:visited{ color:#000}



.pagerLittleBlock {

float: left;

margin-left: 10px;

}

.pagerLittleBlock a {

display: inline-block;

margin-right: 4px;

margin-left: 4px;

}

.pagerLittleBlock input {

width: 30px;

text-align: center;

}



.pageSizeLabel {

float: right;

margin-right: 10px;

}

 

参考:《GridView自定义分页》

分享ASP.NET固定GridView表头的方法

分享ASP.NET固定GridView表头的方法

——独立观察员 2015.03.27

最近接到一个任务,是需要将ASP.NET页面中的GridView的表头固定住,不随滚动条滚动,只是表身滚动。其实要实现得很完美,对我来说还是很难的,因为我对JS不熟练,虽然也自学过很多次,但总感觉一直入不了门,就像Android一样。还是C#给人一种平易近人的感觉,很好上手。

老大倒是给我指了条思路,说可以自己用html写表头,然后将GridView自身的表头隐藏就好了。我觉得这个听上去容易,真正做起来应该不简单吧。完全搞不定啊,还是问问度娘吧。

 

在网上看到有人推荐这个:

%title插图%num

用了一下,确实可以,也没有”ScrollableGridPlugin.js方法“的表头与表身错位的问题。

但问题还是有的,就是表格中文字都未换行,后来找到了原因:

%title插图%num(原先是 “nowarp”)

 

附——”white-space”介绍:

white-space属性设置如何处理元素内的空白。所有浏览器都支持 white-space 属性。

可能的值

值

描述

normal

默认。空白会被浏览器忽略。

pre

空白会被浏览器保留。其行为方式类似 HTML 中的 <pre> 标签。

nowrap

文本不会换行,文本会在在同一行上继续,直到遇到 <br> 标签为止。

pre-wrap

保留空白符序列,但是正常地进行换行。

pre-line

合并空白符序列,但是保留换行符。

inherit

规定应该从父元素继承 white-space 属性的值。

(值 pre-wrap 和 pre-line 是 CSS 2.1 中新增的。)

 

言归正传,还有的问题就是浏览器窗口缩小后右边比较难看,且底部滑动条形同虚设,滑动后并不能展现到右边的表格内容:

%title插图%num

(尝试解决但未成功,请大家不吝赐教)

 

接下来先说说任务方面的处理:

由于菜单以下是iframe页面:

%title插图%num

 

所以可通过设置这个iframe引用的页面的高度,使得iframe页向上滚动到顶时刚好到合适的位置:

%title插图%num

 

这里主要就是设置这个表格的高度,这就要牵涉到本次固定表头方法的用法了。

 

之前提到的网页可下载2个JS文件和1个CSS文件(我用了Chrome插件”Quick Source Viewer”方便下载)。其中superTables.js 存放主要方法,jquery.superTable.js 存放快捷调用方法,superTables.css 则是样式了,三者都遵循MIT授权,是很宽松的一种Lisence。

 

调用方法(完整用法可看源代码):

%title插图%num

使用Jquery选取GridView,用width和height设置宽和高,fixedCols参数设置前几列固定,colWidths可指定各列的宽度,还有其它一些参数,比如有个可设置几行作为表头的(即固定前几行)。

 

有些人可能喜欢先在线看看代码再决定使不使用,我就满足他们吧:

1、jquery.superTable.js

/////////////////////////////////////////////////////////////////////////////////////////
// Super Tables Plugin for jQuery - MIT Style License
// Copyright (c) 2009 Jeffrey Lee --- blog.darkthread.net
//
// A wrapper for Matt Murphy's Super Tables http://www.matts411.com/post/super_tables/
//
// Contributors:
//
/////////////////////////////////////////////////////////////////////////////////////////
////// TO CALL: 
// $("...").toSuperTable(options)
//
////// OPTIONS: (order does not matter )
// cssSkin : string ( eg. "sDefault", "sSky", "sOrange", "sDark" )
// headerRows : integer ( default is 1 )
// fixedCols : integer ( default is 0 )
// colWidths : integer array ( use -1 for auto sizing )
// onStart : function ( any this.variableNameHere variables you create here can be used later ( eg. onFinish function ) )
// onFinish : function ( all this.variableNameHere variables created in this script can be used in this function )
// margin, padding, width, height, overflow...: Styles for "fakeContainer"
//
////// Example:
// $("#GridView1").toSuperTable(
//              { width: "640px", height: "480px", fixedCols: 2,
//                onFinish: function() { alert('Done!'); } })

(function($) {
    $.fn.extend(
            {
                toSuperTable: function(options) {
                    var setting = $.extend(
                    {
                        width: "640px", height: "320px",
                        margin: "10px", padding: "0px",
                        overflow: "hidden", colWidths: undefined,
                        fixedCols: 0, headerRows: 1,
                        onStart: function() { },
                        onFinish: function() { },
                        cssSkin: "sSky"
                    }, options);
                    return this.each(function() {
                        var q = $(this);
                        var id = q.attr("id");
                        q.removeAttr("style").wrap("<div id='" + id + "_box'></div>");

                        var nonCssProps = ["fixedCols", "headerRows", "onStart", "onFinish", "cssSkin", "colWidths"];
                        var container = $("#" + id + "_box");

                        for (var p in setting) {
                            if ($.inArray(p, nonCssProps) == -1) {
                                container.css(p, setting[p]);
                                delete setting[p];
                            }
                        }
                        
                        var mySt = new superTable(id, setting);

                    });
                }
            });
})(jQuery);

 

2、superTables.js

/////////////////////////////////////////////////////////////////////////////////////////
// Super Tables v0.30 - MIT Style License
// Copyright (c) 2008 Matt Murphy --- www.matts411.com
//
// Contributors:
// Joe Gallo
/////////////////////////////////////////////////////////////////////////////////////////
////// TO CALL: 
// new superTable([string] tableId, [object] options);
//
////// OPTIONS: (order does not matter )
// cssSkin : string ( eg. "sDefault", "sSky", "sOrange", "sDark" )
// headerRows : integer ( default is 1 )
// fixedCols : integer ( default is 0 )
// colWidths : integer array ( use -1 for auto sizing )
// onStart : function ( any this.variableNameHere variables you create here can be used later ( eg. onFinish function ) )
// onFinish : function ( all this.variableNameHere variables created in this script can be used in this function )
//
////// EXAMPLES:
// var myST = new superTable("myTableId");
//
// var myST = new superTable("myTableId", {
//		cssSkin : "sDefault",
//		headerRows : 1,
//		fixedCols : 2,
//		colWidths : [100, 230, 220, -1, 120, -1, -1, 120],
//		onStart : function () {
//			this.start = new Date();
//		},
//		onFinish : function () {
//			alert("Finished... " + ((new Date()) - this.start) + "ms.");
//		}
// });
//
////// ISSUES / NOTES:
// 1. No quirksmode support (officially, but still should work)
// 2. Element id's may be duplicated when fixedCols > 0, causing getElementById() issues
// 3. Safari will render the header row incorrectly if the fixed header row count is 1 and there is a colspan > 1 in one 
//		or more of the cells (fix available)
/////////////////////////////////////////////////////////////////////////////////////////

var superTable = function (tableId, options) {
/////* Initialize */
	options = options || {};
	this.cssSkin = options.cssSkin || "";
	this.headerRows = parseInt(options.headerRows || "1");
	this.fixedCols = parseInt(options.fixedCols || "0");
	this.colWidths = options.colWidths || [];
	this.initFunc = options.onStart || null;
	this.callbackFunc = options.onFinish || null;
	this.initFunc && this.initFunc();
	
/////* Create the framework dom */
	this.sBase = document.createElement("DIV");
	this.sFHeader = this.sBase.cloneNode(false);
	this.sHeader = this.sBase.cloneNode(false);
	this.sHeaderInner = this.sBase.cloneNode(false);
	this.sFData = this.sBase.cloneNode(false);
	this.sFDataInner = this.sBase.cloneNode(false);
	this.sData = this.sBase.cloneNode(false);
	this.sColGroup = document.createElement("COLGROUP");
	
	this.sDataTable = document.getElementById(tableId);
	this.sDataTable.style.margin = "0px"; /* Otherwise looks bad */
	if (this.cssSkin !== "") {
		this.sDataTable.className += " " + this.cssSkin;
	}
	if (this.sDataTable.getElementsByTagName("COLGROUP").length > 0) {
		this.sDataTable.removeChild(this.sDataTable.getElementsByTagName("COLGROUP")[0]); /* Making our own */
	}
	this.sParent = this.sDataTable.parentNode;
	this.sParentHeight = this.sParent.offsetHeight;
	this.sParentWidth = this.sParent.offsetWidth;
	
/////* Attach the required classNames */
	this.sBase.className = "sBase";
	this.sFHeader.className = "sFHeader";
	this.sHeader.className = "sHeader";
	this.sHeaderInner.className = "sHeaderInner";
	this.sFData.className = "sFData";
	this.sFDataInner.className = "sFDataInner";
	this.sData.className = "sData";
	
/////* Clone parts of the data table for the new header table */
	var alpha, beta, touched, clean, cleanRow, i, j, k, m, n, p;
	this.sHeaderTable = this.sDataTable.cloneNode(false);
	if (this.sDataTable.tHead) {
		alpha = this.sDataTable.tHead;
		this.sHeaderTable.appendChild(alpha.cloneNode(false));
		beta = this.sHeaderTable.tHead;
	} else {
		alpha = this.sDataTable.tBodies[0];
		this.sHeaderTable.appendChild(alpha.cloneNode(false));
		beta = this.sHeaderTable.tBodies[0];
	}
	alpha = alpha.rows;
	for (i=0; i<this.headerRows; i++) {
		beta.appendChild(alpha[i].cloneNode(true));
	}
	this.sHeaderInner.appendChild(this.sHeaderTable);
	
	if (this.fixedCols > 0) {
		this.sFHeaderTable = this.sHeaderTable.cloneNode(true);
		this.sFHeader.appendChild(this.sFHeaderTable);
		this.sFDataTable = this.sDataTable.cloneNode(true);
		this.sFDataInner.appendChild(this.sFDataTable);
	}
	
/////* Set up the colGroup */
	alpha = this.sDataTable.tBodies[0].rows;
	for (i=0, j=alpha.length; i<j; i++) {
		clean = true;
		for (k=0, m=alpha[i].cells.length; k<m; k++) {
			if (alpha[i].cells[k].colSpan !== 1 || alpha[i].cells[k].rowSpan !== 1) {
				i += alpha[i].cells[k].rowSpan - 1;
				clean = false;
				break;
			}
		}
		if (clean === true) break; /* A row with no cells of colSpan > 1 || rowSpan > 1 has been found */
	}
	cleanRow = (clean === true) ? i : 0; /* Use this row index to calculate the column widths */
	for (i=0, j=alpha[cleanRow].cells.length; i<j; i++) {
		if (i === this.colWidths.length || this.colWidths[i] === -1) {
			this.colWidths[i] = alpha[cleanRow].cells[i].offsetWidth;
		}
	}
	for (i=0, j=this.colWidths.length; i<j; i++) {
		this.sColGroup.appendChild(document.createElement("COL"));
		this.sColGroup.lastChild.setAttribute("width", this.colWidths[i]);
	}
	this.sDataTable.insertBefore(this.sColGroup.cloneNode(true), this.sDataTable.firstChild);
	this.sHeaderTable.insertBefore(this.sColGroup.cloneNode(true), this.sHeaderTable.firstChild);
	if (this.fixedCols > 0) {
		this.sFDataTable.insertBefore(this.sColGroup.cloneNode(true), this.sFDataTable.firstChild);
		this.sFHeaderTable.insertBefore(this.sColGroup.cloneNode(true), this.sFHeaderTable.firstChild);
	}
	
/////* Style the tables individually if applicable */
	if (this.cssSkin !== "") {
		this.sDataTable.className += " " + this.cssSkin + "-Main";
		this.sHeaderTable.className += " " + this.cssSkin + "-Headers";
		if (this.fixedCols > 0) {
			this.sFDataTable.className += " " + this.cssSkin + "-Fixed";
			this.sFHeaderTable.className += " " + this.cssSkin + "-FixedHeaders";
		}
	}
	
/////* Throw everything into sBase */
	if (this.fixedCols > 0) {
		this.sBase.appendChild(this.sFHeader);
	}
	this.sHeader.appendChild(this.sHeaderInner);
	this.sBase.appendChild(this.sHeader);
	if (this.fixedCols > 0) {
		this.sFData.appendChild(this.sFDataInner);
		this.sBase.appendChild(this.sFData);
	}
	this.sBase.appendChild(this.sData);
	this.sParent.insertBefore(this.sBase, this.sDataTable);
	this.sData.appendChild(this.sDataTable);
	
/////* Align the tables */
	var sDataStyles, sDataTableStyles;
	this.sHeaderHeight = this.sDataTable.tBodies[0].rows[(this.sDataTable.tHead) ? 0 : this.headerRows].offsetTop;
	sDataTableStyles = "margin-top: " + (this.sHeaderHeight * -1) + "px;";
	sDataStyles = "margin-top: " + this.sHeaderHeight + "px;";
	sDataStyles += "height: " + (this.sParentHeight - this.sHeaderHeight) + "px;";
	if (this.fixedCols > 0) {		
		/* A collapsed table's cell's offsetLeft is calculated differently (w/ or w/out border included) across broswers - adjust: */
		this.sFHeaderWidth = this.sDataTable.tBodies[0].rows[cleanRow].cells[this.fixedCols].offsetLeft;
		if (window.getComputedStyle) {
			alpha = document.defaultView;
			beta = this.sDataTable.tBodies[0].rows[0].cells[0];
			if (navigator.taintEnabled) { /* If not Safari */
				this.sFHeaderWidth += Math.ceil(parseInt(alpha.getComputedStyle(beta, null).getPropertyValue("border-right-width")) / 2);
			} else {
				this.sFHeaderWidth += parseInt(alpha.getComputedStyle(beta, null).getPropertyValue("border-right-width"));
			}
		} else if (/*@cc_on!@*/0) { /* Internet Explorer */
			alpha = this.sDataTable.tBodies[0].rows[0].cells[0];
			beta = [alpha.currentStyle["borderRightWidth"], alpha.currentStyle["borderLeftWidth"]];
			if(/px/i.test(beta[0]) && /px/i.test(beta[1])) {
				beta = [parseInt(beta[0]), parseInt(beta[1])].sort();
				this.sFHeaderWidth += Math.ceil(parseInt(beta[1]) / 2);
			}
		}
		
		/* Opera 9.5 issue - a sizeable data table may cause the document scrollbars to appear without this: */
		if (window.opera) {
			this.sFData.style.height = this.sParentHeight + "px";
		}
		
		this.sFHeader.style.width = this.sFHeaderWidth + "px";
		sDataTableStyles += "margin-left: " + (this.sFHeaderWidth * -1) + "px;";
		sDataStyles += "margin-left: " + this.sFHeaderWidth + "px;";
		sDataStyles += "width: " + (this.sParentWidth - this.sFHeaderWidth) + "px;";	    
	} else {
		sDataStyles += "width: " + this.sParentWidth + "px;";
	}
	this.sData.style.cssText = sDataStyles;
	this.sDataTable.style.cssText = sDataTableStyles;
	
/////* Set up table scrolling and IE's onunload event for garbage collection */
	(function (st) {
		if (st.fixedCols > 0) {
			st.sData.onscroll = function () {
				st.sHeaderInner.style.right = st.sData.scrollLeft + "px";
				st.sFDataInner.style.top = (st.sData.scrollTop * -1) + "px";
			};
		} else {
			st.sData.onscroll = function () {
				st.sHeaderInner.style.right = st.sData.scrollLeft + "px";
			};
		}
		if (/*@cc_on!@*/0) { /* Internet Explorer */
			window.attachEvent("onunload", function () {
				st.sData.onscroll = null;
				st = null;
			});
		}
	})(this);
	
	this.callbackFunc && this.callbackFunc();
};

 

3、superTables.css

/*
///////////////////////////////////////////////////////////////////////////////////////// 
// Super Tables v0.30 - MIT Style License
// Copyright (c) 2008 Matt Murphy --- www.matts411.com
//
// Contributors:
// Joe Gallo
///////////////////////////////////////////////////////////////////////////////////////// 
*/
.sBase {
	position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
}

/* HEADERS */
.sHeader {
	position: absolute;
	z-index: 3;
	background-color: #ffffff;
}
.sHeaderInner {
	position: relative;
}
.sHeaderInner table {
	border-spacing: 0px 0px !important;
	border-collapse: collapse !important;
	width: 1px !important;
	table-layout: fixed !important;
	background-color: #ffffff; /* Here b/c of Opera 9.25 :( */
}

/* HEADERS - FIXED */
.sFHeader {
	position: absolute;
	z-index: 4;
	overflow: hidden;
}
.sFHeader table {
	border-spacing: 0px 0px !important;
	border-collapse: collapse !important;
	width: 1px !important;
	table-layout: fixed !important;
	background-color: #ffffff; /* Here b/c of Opera 9.25 :( */
}

/* BODY */
.sData {
	position: absolute;
	z-index: 2;
	overflow: auto;
	background-color: #ffffff;    
}
.sData table {
	border-spacing: 0px 0px !important;
	border-collapse: collapse !important;
	width: 1px !important;
	table-layout: fixed !important;
}

/* BODY - FIXED */
.sFData {
	position: absolute;
	z-index: 1;
	background-color: #ffffff;
}
.sFDataInner {
	position: relative;
}
.sFData table {
	border-spacing: 0px 0px !important;
	border-collapse: collapse !important;
	width: 1px !important;	
	table-layout: fixed !important;
}


/*
///////////////////////////////////////////////////////////////////////////////////////// 
// Super Tables - Skin Classes
// Remove if not needed
///////////////////////////////////////////////////////////////////////////////////////// 
*/

/* sDefault */
.sDefault {
	margin: 0px;
	padding: 0px;
	border: none;
	font-family: Verdana, Arial, sans serif;
	font-size: 0.8em;
}
.sDefault th, .sDefault td {
	border: 1px solid #cccccc;
	padding: 3px 6px 3px 4px;
	white-space: nowrap;
}
.sDefault th {
	background-color: #e5e5e5;
	border-color: #c5c5c5;
}
.sDefault-Fixed {
	background-color: #eeeeee;
	border-color: #c5c5c5;
}

/* sSky */
.sSky {
	margin: 0px;
	padding: 0px;
	border: none;
	font-family: Verdana, Arial, sans serif;
	font-size: 0.8em;
}
.sSky th, .sSky td {
	border: 1px solid #9eb6ce;
	padding: 3px 6px 3px 4px;
	white-space: normal; /*单元格自动换行*/
}
.sSky th {
	background-color: #CFDCEE;
}
.sSky-Fixed {
	background-color: #e4ecf7;
}

/* sOrange */
.sOrange {
	margin: 0px;
	padding: 0px;
	border: none;
	font-family: Verdana, Arial, sans serif;
	font-size: 0.8em;
}
.sOrange th, .sOrange td {
	border: 1px solid #cebb9e;
	padding: 3px 6px 3px 4px;
	white-space: nowrap;
}
.sOrange th {
	background-color: #ECD8C7;
}
.sOrange-Fixed {
	background-color: #f7ede4;
}

/* sDark */
.sDark {
	margin: 0px;
	padding: 0px;
	border: none;
	font-family: Verdana, Arial, sans serif;
	font-size: 0.8em;
	color: #ffffff;
}
.sDark th, .sDark td {
	border: 1px solid #555555;
	padding: 3px 6px 3px 4px;
	white-space: nowrap;
}
.sDark th {
	background-color: #000000;
}
.sDark-Fixed {
	background-color: #222222;
}
.sDark-Main {
	background-color: #333333;
}
.altRow {
    background-color: #ddddff;
}

 

4、调用方法参考

<script type="text/javascript">

    $(document).ready(function () {

        $(function () { /*固定表头*/

            $("#gvPMOSuggestShow").toSuperTable({

                width: "1210px",

                height: "730px",

                fixedCols: 3,

                colWidths: [30, 50, 80, 70, 60, 50, 110, 300, 250, 100, 50, 40]

            }).find("tr:even").addClass("altRow");

        });

    });

</script>

 

最后奉上文件地址:

http://download.csdn.net/detail/w19921004/8539125

 

为博客文章中的引用添加引用样式

为博客文章中的引用添加引用样式

——独立观察员 2014.10.15

自古就有”天下文章一大抄,你抄我来我抄他”的说法,可见,”参考”和”借鉴”是在所难免的。尤其是在如今这个网络时代,复制粘贴毫不费劲,各种言论的来源已变得难以考据。一句话、一个意思,如果经过化用,自然可以”据为己有”,注明出处反而不太合适;但如果是整段引用,则至少应该标明是引用来的,举手之劳,净化网络环境。

我在逛论坛时,看到回帖时在自己的回帖内容上方有用引用的样式带上所回复的内容,我觉得效果不错:

%title插图%num

 

然后我就想,能不能在自己的文章中加入这一特性呢?

我先是了解到有两个HTML标签是用于引用的,以下是它们的介绍:

 

<blockquote>

http://www.w3school.com.cn/tags/tag_blockquote.asp

<blockquote>标签定义块引用。

<blockquote> 与 </blockquote> 之间的所有文本都会从常规文本中分离出来,经常会在左、右两边进行缩进(增加外边距),而且有时会使用斜体。也就是说,块引用拥有它们自己的空间。

如需把页面作为 strict XHTML 进行验证,那么 <blockquote> 元素必须包含块级元素,比如<p>元素。 

<q>

http://www.w3school.com.cn/tags/tag_q.asp

<q> 标签定义短的引用。

浏览器经常在引用的内容周围添加引号。

<q> 标签用于简短的行内引用。如果需要从周围内容分离出来比较长的部分(通常显示为缩进的块),请使用 <blockquote> 标签。

 

我试用了一下,感觉效果不明显,还是两边有双引号图片的效果比较好。

稍微想一想就知道,要实现这一效果,需要至少两层div进行嵌套,双引号的一半放在一层div中,另一半放在另一个div中。

好,开动起来,先把”窃取”的双引号图片素材PS一下……

然后准备好用于嵌套的div:

<div class="q-left"><div class="q-right"> </div></div>

以及相应的CSS代码:

.q-left{background:url(http://dlgcy.com/dlgcy/pic/quote_left.png) no-repeat; padding-left:35px;padding-top:10px;}

.q-right{background:url(http://dlgcy.com/dlgcy/pic/quote_right.png) no-repeat right bottom; padding-right:32px;padding-bottom:10px;}

(事先已经把图片传到网站空间中了,大家需要的话,可以自己取,或者直接引用)

简要说明:.q-left是外围的div,背景图片在默认位置(左上角);.q-right是内层div,背景图片放在了右下角;调整好边距。

使用方法:把CSS代码写在能影响页面的地方,我自己是写在了HeadWay主题的Live CSS区;写文章时,或之后编辑时,切换到HTML代码模式,将上面提供的div套在相关内容上即可。

效果展示:

%title插图%num

还行吧?哈哈^_^

C#的WPF中的Image控件中载入图片的方法

C#的WPF中的Image控件中载入图片的方法

——独立观察员 2014.06.23

最近在做学校短学期课程”软件工程-软件项目管理与开发实践”的作业,选择用WPF(C#)做客户端。这是我第一次用WPF,以前学过C#,用的是Winform。

简而言之就是界面上需要载入图片(动态),折腾了挺久的,终于成功,特此记录在此。

 

开始时,我按照 WPF–Image控件动态显示图片问题笔记 里写的去做:

Uri uri = new Uri(“/Images/” + curImage,UriKind.Relative);

BitmapImage bitmap = new BitmapImage(uri);

myImage.Source = bitmap;

但始终无法显示出图片。

 

花开两朵,各表一枝。在搜索过程中,我试了一下在XAML里调用图片,这个成功了,不过可能不够规范:

Source=”/OrderFood_WPF;component/bin/Debug/picture/1.jpg” />

%title插图%num

其中OrderFood_WPF是项目名,整个/OrderFood_WPF;component就是项目所在路径,而我的图片在其下的/bin/Debug/picture路径内,由上图可见图片载入成功。

 

但是在.cs文件(代码文件)中动态地载入图片还是不行。浏览 WPF中Image控件的Source属性 文章时发现他是这样写的:

imageEditImage是一个Image控件,在后台代码中我想给它指定Source的属性。我先如下方式进行:

BitmapImage image = new BitmapImage(new Uri(strImagePath, UriKind.Absolute));

imageEditImage.Source = image;

strImagePath是图片的绝对路径。

第一篇文章里作者没有详细说明UriKind参数的作用,现在看到这个才恍然大悟,原来这个顾名思义,是指定Uri的类型的,可设为”相对路径”或”绝对路径”,那就好办了。

既然之前使用的是相对路径(Relative),但搞不清楚,那现在就用绝对路径(Absolute)吧:

 

//载入图片;

Uri uri = new Uri(System.Environment.CurrentDirectory + “\\” + food.food_pic_url, UriKind.Absolute);

BitmapImage bitmap = new BitmapImage(uri);

image.Source = bitmap;

 

其中System.Environment.CurrentDirectory用于获取当前目录(该进程从中启动的目录)的完全限定目录,即可执行文件(.exe)所在的路径,具体可参考——总结C#获取当前路径的7种方法 。

 

最后效果:

%title插图%num

 

%title插图%num

 

谢谢阅读!

『作业』网络安全实验_凯撒密码与DES的C实现

『作业』网络安全实验_凯撒密码与DES的C实现

——独立观察员 2014.04.27

一、凯撒密码的C实现

(一)代码

#include<stdio.h>
#include<string.h>
#define LEN 50

int main()
{
	char msg[LEN];
	int move,i;

	printf("请输入移位数:\n");
	scanf("%d",&move);
	getchar();

	printf("请输入明文:\n");
	gets(msg);

	for(i=0;i<LEN;i++)
	{
		if((msg[i]>='A')&&(msg[i]<='Z'))
		{
			msg[i] += move; //移位;
			if(( (msg[i]>='A')&&(msg[i]<='Z') )==0)
				msg[i] -= 26;
		}
		else if((msg[i]>='a')&&(msg[i]<='z'))
		{
			msg[i] += move;
			if(( (msg[i]>='a')&&(msg[i]<='z') )==0)
				msg[i] -= 26;
		}
		/*else
		{
			printf("您的输入中包含非字母的内容,不符合凯撒密码的规定,程序将终止。\n");
			return -1;
		}*/
	}

	printf("已加密得到密文:\n");
	puts(msg);
	printf("\n");

	printf("请输入密文:\n");
	gets(msg);

	for(i=0;i<LEN;i++)
	{
		if(msg[i]>='A'&&msg[i]<='Z')
		{
			msg[i] -= move; //移位;
			if((msg[i]>='A'&&msg[i]<='Z')==0)
				msg[i] += 26;
		}
		else if(msg[i]>='a'&&msg[i]<='z')
		{
			msg[i] -= move;
			if((msg[i]>='a'&&msg[i]<='z')==0)
				msg[i] += 26;
		}
	}
	
	printf("已解密得到明文:\n");
	puts(msg);

	return 0;
}

 

(二)运行截图及说明

%title插图%num

 

说明:

移位数应是26以内的正整数;

明文和密文只支持大小写字母;

解密时使用与加密时相同的移位数;

大写字母加密或解密后还是大写字母,小写字母加密或解密后也还是小写字母。

 

二、DES的C语言实现

说明:只要求找到可运行的代码并读懂。

(一)代码

(来源于网络)

(1)main.c

/*-------------------------------------------------------
      Data Encryption Standard  56位密钥加密64位数据 
				  2011.10
--------------------------------------------------------*/
#include <stdlib.h>
#include <stdio.h>
#include "bool.h"   // 位处理 
#include "tables.h"

void BitsCopy(bool *DatOut,bool *DatIn,int Len);  // 数组复制 

void ByteToBit(bool *DatOut,char *DatIn,int Num); // 字节到位 
void BitToByte(char *DatOut,bool *DatIn,int Num); // 位到字节

void BitToHex(char *DatOut,bool *DatIn,int Num);  // 二进制到十六进制 64位 to 4*16字符
void HexToBit(bool *DatOut,char *DatIn,int Num);  // 十六进制到二进制 

void TablePermute(bool *DatOut,bool *DatIn,const char *Table,int Num); // 位表置换函数 
void LoopMove(bool *DatIn,int Len,int Num);     // 循环左移 Len长度 Num移动位数 
void Xor(bool *DatA,bool *DatB,int Num);         // 异或函数 

void S_Change(bool DatOut[32],bool DatIn[48]);   // S盒变换 
void F_Change(bool DatIn[32],bool DatKi[48]);    // F函数                                  

void SetKey(char KeyIn[8]);                         // 设置密钥
void PlayDes(char MesOut[8],char MesIn[8]);       // 执行DES加密
void KickDes(char MesOut[8],char MesIn[8]);             // 执行DES解密 

 

int main()
{
	int i=0; 
	char MesHex[16]={0};         // 16个字符数组用于存放 64位16进制的密文
 	char MyKey[8]={0};           // 初始密钥 8字节*8
	char YourKey[8]={0};         // 输入的解密密钥 8字节*8
	char MyMessage[8]={0};       // 初始明文 
	
/*-----------------------------------------------*/

	printf("请输入明文(8个字符/64bit):\n");
	gets(MyMessage);            // 明文
	printf("请输入密钥(8个字符):\n");
	gets(MyKey);                // 密钥

	while(MyKey[i]!='\0')        // 计算密钥长度
	{
		i++;
	}

	while(i!=8)                  // 不是8 提示错误
	{
		printf("请输入符合规定的密钥(8个字符/64bit):\n");
		gets(MyKey);
		i=0;
		while(MyKey[i]!='\0')    // 再次检测
		{
			i++;
		}
	}

	SetKey(MyKey);               // 设置密钥 得到子密钥Ki
	
	PlayDes(MesHex,MyMessage);   // 执行DES加密

	printf("明文已加密:\n");  // 信息已加密
	for(i=0;i<16;i++)           
	{
		printf("%c ",MesHex[i]);
	}
	printf("\n");
	printf("\n");
	
	printf("请输入密钥来解密:\n");  // 请输入密钥以解密
	gets(YourKey);                                         // 得到密钥
	SetKey(YourKey);                                       // 设置密钥

	KickDes(MyMessage,MesHex);                     // 解密输出到MyMessage
	
	printf("解密结束:\n");                     // 解密结束
	for(i=0;i<8;i++)
	{
		printf("%c ",MyMessage[i]);
	}
	printf("\n");
	system("pause");
		
/*------------------------------------------------*/	
}

/*-------------------------------
 把DatIn开始的长度位Len位的二进制
 复制到DatOut后
--------------------------------*/
void BitsCopy(bool *DatOut,bool *DatIn,int Len)     // 数组复制 OK 
{
	int i=0;
	for(i=0;i<Len;i++)
	{
		DatOut[i]=DatIn[i];
	}
}

/*-------------------------------
 字节转换成位函数 
 每8次换一个字节 每次向右移一位
 和1与取最后一位 共64位 
--------------------------------*/
void ByteToBit(bool *DatOut,char *DatIn,int Num)       // OK
{
	int i=0;
	for(i=0;i<Num;i++)
	{
		DatOut[i]=(DatIn[i/8]>>(i%8))&0x01;   
	}                                       
}

/*-------------------------------
 位转换成字节函数
 字节数组每8次移一位
 位每次向左移 与上一次或   
---------------------------------*/
void BitToByte(char *DatOut,bool *DatIn,int Num)        // OK
{
	int i=0;
	for(i=0;i<(Num/8);i++)
	{
		DatOut[i]=0;
	} 
	for(i=0;i<Num;i++)
	{
		DatOut[i/8]|=DatIn[i]<<(i%8);	
	}		
}


/*----------------------------------
 二进制密文转换为十六进制
 需要16个字符表示
-----------------------------------*/
void BitToHex(char *DatOut,bool *DatIn,int Num)
{
	int i=0;
	for(i=0;i<Num/4;i++)
	{
		DatOut[i]=0;
	}
	for(i=0;i<Num/4;i++)
	{
		DatOut[i] = DatIn[i*4]+(DatIn[i*4+1]<<1)
					+(DatIn[i*4+2]<<2)+(DatIn[i*4+3]<<3);
		if((DatOut[i]%16)>9)
		{
			DatOut[i]=DatOut[i]%16+'7';       //  余数大于9时处理 10-15 to A-F
		}                                     //  输出字符 
		else
		{
			DatOut[i]=DatOut[i]%16+'0';       //  输出字符	   
		}
	}
	
}

/*---------------------------------------------
 十六进制字符转二进制
----------------------------------------------*/
void HexToBit(bool *DatOut,char *DatIn,int Num)
{
	int i=0;                        // 字符型输入 
	for(i=0;i<Num;i++)
	{
		if((DatIn[i/4])>'9')         //  大于9 
		{
			DatOut[i]=((DatIn[i/4]-'7')>>(i%4))&0x01;   			
		}
		else
		{
			DatOut[i]=((DatIn[i/4]-'0')>>(i%4))&0x01; 	
		} 
	}	
}

// 表置换函数  OK
void TablePermute(bool *DatOut,bool *DatIn,const char *Table,int Num)  
{
	int i=0;
	static bool Temp[256]={0};
	for(i=0;i<Num;i++)                // Num为置换的长度 
	{
		Temp[i]=DatIn[Table[i]-1];  // 原来的数据按对应的表上的位置排列 
	}
	BitsCopy(DatOut,Temp,Num);       // 把缓存Temp的值输出 
} 

// 子密钥的移位
void LoopMove(bool *DatIn,int Len,int Num) // 循环左移 Len数据长度 Num移动位数
{
	static bool Temp[256]={0};    // 缓存   OK
	BitsCopy(Temp,DatIn,Num);       // 将数据最左边的Num位(被移出去的)存入Temp 
	BitsCopy(DatIn,DatIn+Num,Len-Num); // 将数据左边开始的第Num移入原来的空间
	BitsCopy(DatIn+Len-Num,Temp,Num);  // 将缓存中移出去的数据加到最右边 
} 

// 按位异或
void Xor(bool *DatA,bool *DatB,int Num)           // 异或函数
{
	int i=0;
	for(i=0;i<Num;i++)
	{
		DatA[i]=DatA[i]^DatB[i];                  // 异或 
	}
} 

// 输入48位 输出32位 与Ri异或
void S_Change(bool DatOut[32],bool DatIn[48])     // S盒变换
{
	int i,X,Y;                                    // i为8个S盒 
	for(i=0,Y=0,X=0;i<8;i++,DatIn+=6,DatOut+=4)   // 每执行一次,输入数据偏移6位 
	{    										  // 每执行一次,输出数据偏移4位
		Y=(DatIn[0]<<1)+DatIn[5];                          // af代表第几行
		X=(DatIn[1]<<3)+(DatIn[2]<<2)+(DatIn[3]<<1)+DatIn[4]; // bcde代表第几列
		ByteToBit(DatOut,&S_Box[i][Y][X],4);      // 把找到的点数据换为二进制	
	}
}

// F函数
void F_Change(bool DatIn[32],bool DatKi[48])       // F函数
{
	static bool MiR[48]={0};             // 输入32位通过E选位变为48位
	TablePermute(MiR,DatIn,E_Table,48); 
	Xor(MiR,DatKi,48);                   // 和子密钥异或
	S_Change(DatIn,MiR);                 // S盒变换
	TablePermute(DatIn,DatIn,P_Table,32);   // P置换后输出
}



void SetKey(char KeyIn[8])               // 设置密钥 获取子密钥Ki 
{
	int i=0;
	static bool KeyBit[64]={0};                // 密钥二进制存储空间 
	static bool *KiL=&KeyBit[0],*KiR=&KeyBit[28];  // 前28,后28共56
	ByteToBit(KeyBit,KeyIn,64);                    // 把密钥转为二进制存入KeyBit 
	TablePermute(KeyBit,KeyBit,PC1_Table,56);      // PC1表置换 56次
	for(i=0;i<16;i++)
	{
		LoopMove(KiL,28,Move_Table[i]);       // 前28位左移 
		LoopMove(KiR,28,Move_Table[i]);	      // 后28位左移 
	 	TablePermute(SubKey[i],KeyBit,PC2_Table,48); 
	 	// 二维数组 SubKey[i]为每一行起始地址 
	 	// 每移一次位进行PC2置换得 Ki 48位 
	}		
}

void PlayDes(char MesOut[8],char MesIn[8])  // 执行DES加密
{                                           // 字节输入 Bin运算 Hex输出 
	int i=0;
	static bool MesBit[64]={0};        // 明文二进制存储空间 64位
	static bool Temp[32]={0};
	static bool *MiL=&MesBit[0],*MiR=&MesBit[32]; // 前32位 后32位 
	ByteToBit(MesBit,MesIn,64);                 // 把明文换成二进制存入MesBit
	TablePermute(MesBit,MesBit,IP_Table,64);    // IP置换 
	for(i=0;i<16;i++)                       // 迭代16次 
	{
		BitsCopy(Temp,MiR,32);            // 临时存储
		F_Change(MiR,SubKey[i]);           // F函数变换
		Xor(MiR,MiL,32);                  // 得到Ri 
		BitsCopy(MiL,Temp,32);            // 得到Li 
	}					
	TablePermute(MesBit,MesBit,IPR_Table,64);
	BitToHex(MesOut,MesBit,64);
}

void KickDes(char MesOut[8],char MesIn[8])       // 执行DES解密
{												// Hex输入 Bin运算 字节输出 
	int i=0;
	static bool MesBit[64]={0};        // 密文二进制存储空间 64位
	static bool Temp[32]={0};
	static bool *MiL=&MesBit[0],*MiR=&MesBit[32]; // 前32位 后32位
	HexToBit(MesBit,MesIn,64);                 // 把密文换成二进制存入MesBit
	TablePermute(MesBit,MesBit,IP_Table,64);    // IP置换 
	for(i=15;i>=0;i--)
	{
		BitsCopy(Temp,MiL,32);
		F_Change(MiL,SubKey[i]);
		Xor(MiL,MiR,32);
		BitsCopy(MiR,Temp,32);
	}	
	TablePermute(MesBit,MesBit,IPR_Table,64);
	BitToByte(MesOut,MesBit,64);		
} 

 

(2)bool.h

/*--------------------------------------*/
#ifndef __BOOL_H__
#define __BOOL_H__
typedef enum
  {
    false = 0,
    true  = 1
  } bool;
#endif
/*-------------------------------------*/

 

(3)tables.h

/*-------------------------------------------------------------
		置换表 
-------------------------------------------------------------*/

#ifndef _TABLES_H_    // 防重复编译 
#define _TABLES_H_  

// 对明文执行IP置换得到L0,R0 (L左32位,R右32位)               [明文操作]
const char IP_Table[64]={             
	58,50,42,34,26,18,10, 2,60,52,44,36,28,20,12, 4,
	62,54,46,38,30,22,14, 6,64,56,48,40,32,24,16, 8,
	57,49,41,33,25,17, 9, 1,59,51,43,35,27,19,11, 3,
	61,53,45,37,29,21,13, 5,63,55,47,39,31,23,15, 7 
};

// 对迭代后的L16,R16执行IP逆置换,输出密文
const char IPR_Table[64]={              
	40, 8,48,16,56,24,64,32,39, 7,47,15,55,23,63,31,
	38, 6,46,14,54,22,62,30,37, 5,45,13,53,21,61,29,
	36, 4,44,12,52,20,60,28,35, 3,43,11,51,19,59,27,
	34, 2,42,10,50,18,58,26,33, 1,41, 9,49,17,57,25	
};

/*--------------------------- 迭代法则 ----------------------------*/ 

// F函数,32位的R0进行E变换,扩为48位输出 (R1~R16)        [备用A]  [明文操作] 
static char E_Table[48]={
	32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9,
	 8, 9,10,11,12,13,12,13,14,15,16,17,
    16,17,18,19,20,21,20,21,22,23,24,25,
    24,25,26,27,28,29,28,29,30,31,32, 1
};

// 子密钥K(i)的获取 密钥为K 抛弃第6,16,24,32,40,48,64位          [密钥操作] 
// 用PC1选位 分为 前28位C0,后28位D0 两部分  
static char PC1_Table[56]={
	57,49,41,33,25,17, 9, 1,58,50,42,34,26,18,
	10, 2,59,51,43,35,27,19,11, 3,60,52,44,36,
	63,55,47,39,31,23,15, 7,62,54,46,38,30,22,
	14, 6,61,53,45,37,29,21,13, 5,28,20,12, 4
};

// 对C0,D0分别进行左移,共16次,左移位数与下面对应                 [密钥操作]
static char Move_Table[16]={
	 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
};

// C1,D1为第一次左移后得到,进行PC2选位,得到48位输出K1   [备用B]   [密钥操作]     
static char PC2_Table[48]={
	14,17,11,24, 1, 5, 3,28,15, 6,21,10,
	23,19,12, 4,26, 8,16, 7,27,20,13, 2,
	41,52,31,37,47,55,30,40,51,34,33,48,
	44,49,39,56,34,53,46,42,50,36,29,32	
};

/*------------- F函数 备用A和备用B 异或 得到48位输出 ---------------*/ 

// 异或后的结果48位分为8组,每组6位,作为8个S盒的输入             [组合操作] 
// S盒以6位作为输入(8组),4位作为输出(4*(8组)=32位)
// S工作原理 假设输入为A=abcdef ,则bcde所代表的数是0-15之间的
// 一个数记为 X=bcde ,af代表的是0-3之间的一个数,记为 Y=af 
// 在S1的X列,Y行找到一个数Value,它在0-15之间,可以用二进制表示
// 所以为4bit (共32位)  
static char S_Box[8][4][16]={
	//S1
	14, 4,13, 1, 2,15,11, 8, 3,10, 6,12, 5, 9, 0, 7,
	 0,15, 7, 4,14, 2,13, 1,10, 6,12,11, 9, 5, 3, 8,
	 4, 1,14, 8,13, 6, 2,11,15,12, 9, 7, 3,10, 5, 0,
	15,12, 8, 2, 4, 9, 1, 7, 5,11, 3,14,10, 0, 6,13,
	//S2
	15, 1, 8,14, 6,11, 3, 4, 9, 7, 2,13,12, 0, 5,10,
	 3,13, 4, 7,15, 2, 8,14,12, 0, 1,10, 6, 9,11, 5,
	 0,14, 7,11,10, 4,13, 1, 5, 8,12, 6, 9, 3, 2,15,
	13, 8,10, 1, 3,15, 4, 2,11, 6, 7,12, 0, 5,14, 9,
	//S3
	10, 0, 9,14, 6, 3,15, 5, 1,13,12, 7,11, 4, 2, 8,
	13, 7, 0, 9, 3, 4, 6,10, 2, 8, 5,14,12,11,15, 1,
	13, 6, 4, 9, 8,15, 3, 0,11, 1, 2,12, 5,10,14, 7,
	 1,10,13, 0, 6, 9, 8, 7, 4,15,14, 3,11, 5, 2,12,
	//S4
	 7,13,14, 3, 0, 6, 9,10, 1, 2, 8, 5,11,12, 4,15,
	13, 8,11, 5, 6,15, 0, 3, 4, 7, 2,12, 1,10,14, 9,
	10, 6, 9, 0,12,11, 7,13,15, 1, 3,14, 5, 2, 8, 4,
	 3,15, 0, 6,10, 1,13, 8, 9, 4, 5,11,12, 7, 2,14,
	//S5
	 2,12, 4, 1, 7,10,11, 6, 8, 5, 3,15,13, 0,14, 9,
	14,11, 2,12, 4, 7,13, 1, 5, 0,15,10, 3, 9, 8, 6,
	 4, 2, 1,11,10,13, 7, 8,15, 9,12, 5, 6, 3, 0,14,
	11, 8,12, 7, 1,14, 2,13, 6,15, 0, 9,10, 4, 5, 3,
	//S6
	12, 1,10,15, 9, 2, 6, 8, 0,13, 3, 4,14, 7, 5,11,
	10,15, 4, 2, 7,12, 0, 5, 6, 1,13,14, 0,11, 3, 8,
	 9,14,15, 5, 2, 8,12, 3, 7, 0, 4,10, 1,13,11, 6,
   	 4, 3, 2,12, 9, 5,15,10,11,14, 1, 7, 6, 0, 8,13,
	//S7
	 4,11, 2,14,15, 0, 8,13, 3,12, 9, 7, 5,10, 6, 1,
	13, 0,11, 7, 4, 0, 1,10,14, 3, 5,12, 2,15, 8, 6,
	 1, 4,11,13,12, 3, 7,14,10,15, 6, 8, 0, 5, 9, 2,
	 6,11,13, 8, 1, 4,10, 7, 9, 5, 0,15,14, 2, 3,12,
	//S8
	13, 2, 8, 4, 6,15,11, 1,10, 9, 3,14, 5, 0,12, 7,
	 1,15,13, 8,10, 3, 7, 4,12, 5, 6,11, 0,14, 9, 2,
	 7,11, 4, 1, 9,12,14, 2, 0, 6,10,13,15, 3, 5, 8,
	 2, 1,14, 7, 4,10, 8,13,15,12, 9, 0, 3, 5, 6,11
};

// F函数 最后第二步,对S盒输出的32进行P置换             [组合操作]
// 输出的值参与一次迭代:
// L(i)=R(i-1)
// R(i)=L(i-1)^f(R(i-1),K(i)) 异或 
static char P_Table[32]={
	16, 7,20,21,29,12,28,17, 1,15,23,26, 5,18,31,10,
	 2, 8,24,14,32,27, 3, 9,19,13,30, 6,22,11, 4,25
};

// 16个子密钥K(1~16) 
static bool SubKey[16][48]={0};

#endif

 

 

 

(二)运行截图及分析

(1)截图

%title插图%num

 

%title插图%num

 

%title插图%num

 

%title插图%num

(2)分析

由截图可见,明文和密钥都要求8个字符(64bit),明文位数超过会截断,密钥位数不对会要求重输;支持字母和数字,不支持汉字;解密密钥与加密密钥需相同,不同则解密结果不对。

 

→←