WPF+Nhibernate小项目总结

三三进销存系统项目总结

  1. 系统开发主要技术工具简述

本系统开发使用工具为Visual Studio 2010旗舰版,开发语言为C#, 开发平台为.net Frame Work 4,用户界面框架使用WPF,使用Nhibernate数据框架,数据库使用Sql Server 2008 R2,软件体系架构为三层架构(UI表示层,BLL业务逻辑层,DAL数据访问层),日志记录使用log4net,目的实现“高内聚,低耦合”的思想。

 

  2. 用户界面框架WPF

2.1   WPF(Windows Presentation Foundation)布局。布局引入XAML(公开表示Windows应用程序用户界面的标记语言),个人感觉有HTML基础的会比较容易的上手。主要使用的布局控件有StackPanel、WrapPanel、DockPanel、Grid等控件,这些均为Panel基类的派生类。

2.2   WPF的数据绑定。WPF的数据绑定可以很容易的把数据从.Net对象传递给UI或从UI传递给.Net对象。

2.2.1          XAML的绑定语法。在XAML中主要使用Binding关键字,如

<TextBox Name="txtId" Width="90" Text="{Binding Id}"></TextBox>

, ComboBox等集合类控件的绑定方法为

<ComboBox Name="cbbStorage" DataContext="{Binding}" SelectedValue="{Binding Storage.Id}" SelectedValuePath="Id" DisplayMemberPath="Name" Width="80"></ComboBox>

2.2.2          在C#代码中的绑定方法。大多数控件可以直接将数据对象复制DataContext属性即可。部分控件(如ComboBox、ListView等集合类控件)控件可以将数据对象复制给ItemSource属性。

2.2.3          主从绑定。主从绑定实现显示选中项的详细信息,不用再做太多复杂的工作,可以直接将选中对象赋予DataContext。绑定方法为

DataContext="{Binding ElementName=控件名, Path=SelectedItem}"

,在指定的要详细显示的控件上{Binding 字段}即可。

2.2.4          字符串的格式化显示。时间字符串的格式化可以直接使用StringFormat,如将时间格式化为yyyy-MM-dd HH:mm:ss格式显示,可以

{Binding Time, StringFormat={}\{0:yyyy-MM-dd HH:mm:ss\}}

即可。也可以使用Converter类进行转换,例如要格式布尔类型的显示,可以新建类BoolConverter实现IValueConverter接口,然后定义本地资源

注意:使用local标签要先引入命名空间

然后在绑定对象上使用Converter ,如

Binding =”{Binding 字段, Converter={StaticResource boolConverter}}”

2.2.5          Binding的中文翻译在网上的专家之间争议比较大,在这里先暂时理解为数据绑定。

2.3   WPF自定义窗口形状。有时候为了界面的美观,使窗口的形状不局限于传统的矩形,WPF可以实现不规则的形状。将窗口的属性设置为WindowStyle="None" ResizeMode="NoResize" AllowsTransparency="True"即可以根据背景图的形状来显示窗口。如果要实现拖动可以在MouseLeftButtonDown事件中添加this.DragMove();代码。要实现关闭、最大化、最小化等功能,可以自己添加按钮实现即可。

2.4   WPF窗口的Aero效果

2.5   对于程序集属性的访问。

代码如下:

#region 程序集特性访问器(要引用System.Reflection命名空间)

 

        public 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);

            }

        }

 

        public string AssemblyVersion

        {

            get

            {

                return Assembly.GetExecutingAssembly().GetName().Version.ToString();

            }

        }

 

        public string AssemblyDescription

        {

            get

            {

                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);

                if (attributes.Length == 0)

                {

                    return "";

                }

                return ((AssemblyDescriptionAttribute)attributes[0]).Description;

            }

        }

 

        public string AssemblyProduct

        {

            get

            {

                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);

                if (attributes.Length == 0)

                {

                    return "";

                }

                return ((AssemblyProductAttribute)attributes[0]).Product;

            }

        }

 

        public string AssemblyCopyright

        {

            get

            {

                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);

                if (attributes.Length == 0)

                {

                    return "";

                }

                return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;

            }

        }

 

        public string AssemblyCompany

        {

            get

            {

                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);

                if (attributes.Length == 0)

                {

                    return "";

                }

                return ((AssemblyCompanyAttribute)attributes[0]).Company;

            }

        }

        #endregion

 

  3. 对系统配置文件APP.config的修改可以使用System.Configuration.ConfigurationManager类。

  4. Nhibernate。博客园中有李永京的Nibernate之旅系列文章http://www.cnblogs.com/lyj/archive/2008/10/30/1323099.html,个人感觉将的很好,可以参考学习。我在这里只简单总结我的项目中的实际应用。我使用的是Nhibernate3.4.0版本。

4.1   使用到dll:

  

4.2   配置文件。可以新建hibernate.cfg.xml文件,也可以直接在App.config中配置。我是直接在App.config中配置的,具体配置如下:

 

<configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
  </configSections>
  <!--Nhibernate配置-->
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="connection.provider">
        NHibernate.Connection.DriverConnectionProvider
      </property>
      <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
      <property name="connection.connection_string">
        Database=SSS;Data Source=192.168.1.***;User Id=sa;Password=****
      </property>
      <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
      <property name="show_sql">true</property>
      <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
      <!--<property name="proxyfactory.factory_class">
        NHibernate.ByteCode.Castle.ProxyFactoryFactory,
        NHibernate.ByteCode.Castle
      </property>-->
      <mapping assembly="Com.SSS.Model" />
    </session-factory>
  </hibernate-configuration>

 

4.3   Mapping的配置。文件名为”实体.hbm.xml”,文件属性中的生成操作属性一定要为嵌入的资源,复制到输出目录属性是始终复制。

4.4   获取SessionFactory的方法为

ISessionFactory _sessionFactory = (new Configuration()).Configure().BuildSessionFactory();

  ,指定配置文件路径的获取SessionFactory的方法为

ISessionFactory _sessionFactory = (new Configuration()).Configure(文件路径).BuildSessionFactory();

  。获取Session的方法为

ISession _session = _sessionFactory.OpenSession();

  。

4.4.1          增加一个实体的方法

public TId Save(TEntity entity)

        {

            TId id = (TId)_session.Save(entity);

_session.Flush();//添加 _session.Flush();语句,防止主键不是数据库生成自动的实体没有及时insert到数据库中

            return id;

        }

4.4.2   更新一个实体,应该用到事务处理ITransaction,在_session.Update(entity)操作之前最好作_session.Clear()操作,是为了解决可能遇见的异常“a different object with the same identifier value was already associated with the session: 2, of class…“。

4.4.3   Projections提供了大量的SQL函数供使用。

4.4.4   如果一个方法中含有多条非查询语句的语句,建议使用存储过程或者事务处理,所有语句没有异常再提交,有异常则回滚。

  5. log4net。版本为1.2.10

5.1 配置文件。在App.config的configSections中添加

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

,在configuration中添加

<!--log4net配置-->
<
log4net> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender, log4net"> <layout type="log4net.Layout.PatternLayout, log4net"> <param name="ConversionPattern" value="%d %p %m%n" /> </layout> </appender> <appender name="RollingFile" type="log4net.Appender.RollingFileAppender,log4net"> <param name="File" value="logs\log.zsm" /> <param name="AppendToFile" value="true" /> <param name="DatePattern" value="yyyy.MM.dd" /> <layout type="log4net.Layout.PatternLayout,log4net"> <conversionPattern value="%d %p %m%n" /> </layout> </appender> <root> <priority value="DEBUG" /> <appender-ref ref="ConsoleAppender" /> </root> <logger name="NHibernate" additivity="false"> <level value="WARN" /> <appender-ref ref="RollingFile" /> <appender-ref ref="ConsoleAppender" /> </logger> <logger name="NHibernate.SQL" additivity="false"> <level value="ALL" /> <appender-ref ref="RollingFile" /> <appender-ref ref="ConsoleAppender" /> </logger> </log4net>

 

5.2 必须在App.xaml.cs中的构造中添加

 public App() 
        {
            //log4net获取配置
            log4net.Config.XmlConfigurator.Configure();            
        }

6. office2010导出Excel.dll的方法:

    第一步:将Excel.exe生成Interop.Excel.dll。生成办法:进入你的visual studio的sdk下的bin目录,找到TlbImp.exe文件,如果没有,请用光盘安装此文件,详细说明请参照MSDN。拷贝Excel.exe到该<bin>目录,点击“开始”——“运行”——输入“cmd”进入命令行方式——进入<bin>目录

     ——输入“TlbImp /out:Interop.Excel.dll Excel.exe”,提示“Type library imported to Interop.Excel.dll路径”。此时应该可以在bin目录下找到Interop.Excel.dll文件。

第二步:在你的visual studio里点击:“你的项目——添加引用——浏览——找到该Interop.Excel.dll”——“确定”,即可完成引用。

posted on 2013-03-04 13:55  张世民  阅读(1331)  评论(0编辑  收藏  举报