[转载]Documentation TreeGrid- jQuery EasyUI

mikel阅读(1043)

[转载]Documentation – jQuery EasyUI.

TreeGrid

Extend from $.fn.datagrid.defaults. Override defaults with $.fn.treegrid.defaults.

Dependencies

  • datagrid

Usage

  1. <table id=“tt”></table>
  1. $(‘#tt’).treegrid({
  2. url:‘treegrid_data.json’,
  3. treeField:‘name’,
  4. columns:[[
  5. {title:‘Task Name’,field:‘name’,width:180},
  6. {field:‘persons’,title:‘Persons’,width:60,align:‘right’},
  7. {field:‘begin’,title:‘Begin Date’,width:80},
  8. {field:‘end’,title:‘End Date’,width:80}
  9. ]]
  10. });

Properties

The properties extend from datagrid, below is the added properties for treegrid.

Name Type Description Default
treeField string Defines the tree node field. null
animate boolean Defines if to show animation effect when node expand or collapse. false

Events

The events extend from datagrid, below is the added events for treegrid.

Name Parameters Description
onClickRow row Fires when user click a node.
onDblClickRow row Fires when user dblclick a node.
onBeforeLoad row, param Fires before a request is made to load data, return false to cancel this load action.
onLoadSuccess row, data Fires when data loaded successfully.
onLoadError arguments Fires when data loaded fail, the arguments parameter is same as the ‘error’ function of JQuery.ajax.
onBeforeExpand row Fires before node is expanded, return false to cancel this expand action.
onExpand row Fires when node is expanded.
onBeforeCollapse row Fires before node is collapsed, return false to cancel this collapse action.
onCollapse row Fires when node is collapsed.
onContextMenu e, row Fires when node is right clicked.
onBeforeEdit row Fires when user start editing a node.
onAfterEdit row,changes Fires when user finish editing.
onCancelEdit row Fires when user cancel editing a node.

Methods

Name Parameter Description
options none Return the options of treegrid.
resize options Set treegrid size, the options contains two properties:
width: the new width of treegrid.
height: the new height of treegrid.
fixRowHeight id fix the specified row height.
loadData data Load the treegrid data.
reload id Reload treegrid data.
reloadFooter footer Reload footer data.
getData none Get the loaded data.
getFooterRows none Get the footer data.
getRoot none Get the root node, return node object
getRoots none Get the root nodes, return node array.
getParent id Get the parent node.
getChildren id Get the children nodes.
getSelected none Get the selected node and return it, if no node selected return null.
getSelections none Get all selected nodes.
getLevel id Get the specified node level.
find id Find the specifed node and return the node data.
select id Select a node.
unselect id Unselect a node.
selectAll none Select all nodes.
unselectAll none Unselect all nodes.
collapse id Collapse a node.
expand id Expand a node.
collapseAll id Collapse all nodes.
expandAll id Expand all nodes.
expandTo id Expand from root to specified node.
toggle id Toggles expanded/collapsed state of the node.
append param Append nodes to a parent node. The ‘param’ parameter contains following properties:
parent: DOM object, the parent node to append to, if not assigned, append as root nodes.
data: array, the nodes data.
remove id Remove a node and it’s children nodes.
refresh id Refresh the specified node.
beginEdit id Begin editing a node.
endEdit id End editing a node.
cancelEdit id Cancel editing a node.
getEditors id Get the specified row editors. Each editor has the following properties:
actions: the actions that the editor can do.
target: the target editor JQuery object.
field: the field name.
type: the editor type.
getEditor options Get the specified editor, the options contains two properties:
id: the row node id.
field: the field name.

[转载]Mozilla Firefox 8.0 正式发布

mikel阅读(821)

[转载]Mozilla Firefox 8.0 正式发布

Mozilla FTP的releases目录已经出现了Mozilla Firefox 8.0 正式版的身影,现在已经可以下载,本次发布包含全平台全语种,这意味着微软的蛋糕又要送出了。

  • Add-ons installed by third party programs are now disabled by default
  • Added a one-time add-on selection dialog to manage previously installed add-ons
  • Added Twitter to the search bar
  • Added a preference to load tabs on demand, improving start-up time when windows are restored
  • Improved tab animations when moving, reordering, or detaching tabs
  • Improved performance and memory handling when using <audio> and <video> elements
  • Added CORS support for cross-domain textures in WebGL
  • Added support for HTML5 context menus
  • Added support for insertAdjacentHTML
  • Improved CSS hyphen support for many languages
  • Improved WebSocket support
  • Fixed several stability issues

下载:Mozilla Firefox 8.0

[转载]注册Sqldmo.dll

mikel阅读(1088)

[转载]注册SQLdmo.dll

.

在不安装客户端实用程序的情况下启用 SQL DMO 客户端
(http://support.microsoft.com/kb/248241/zh-cn)

概要
本文介绍在无需安装 SQL Server 客户端实用程序的情况下启用 SQL Server 分布式管理对象 (SQL-DMO) 客户端功能所需的步骤。

典型情况
您 编写一个利用 SQL Server 中的 SQL-DMO 对象模型的应用程序。您的应用程序在服务器计算机中能正常运行,而在安装 了 SQL Server 客户端实用程序的客户端计算机中也能正常运行。但是,该应用程序无法单独运行。此外,您还可能看到几个与此相关的错误。最常见 的错误是:
ActiveX can’t create object
Field is not bound correctly
Cannot find entry point
注意:安装  Microsoft 数据访问组件 (MDAC) 无法解决此问题。

MDAC 不 会安装 Sqldmo.dll 文件或与该文件关联的许多从属 DLL 中的任何一个。MDAC 所包括的是 SQL-DMO 客户端连接使用的许多相 关 DLL。无论如何,将 MDAC 与您的应用程序安装绑定都不是最理想的解决办法,因为要使您的 DMO 连接工作,您无需安装所有 的 MDAC DLL。另外,MDAC 还会在客户端计算机上安装许多您可能永远都不会用到的其他功能。这里的主要意思是,您不必安装所有 MDAC 来 获取您需要的功能,而是只安装必需的 DLL 即可。本文后面将介绍这些 DLL。

在讨论不同类型的 DLL 以及需要将它们放置在哪里 之前,让我们偏离一下主题,简要回顾一下基于 Win32 和 COM 的 DLL。在本文中,您只需了解如何区分这些 DLL 以及在识别它们之后如何 处理它们。了解这一点之后,看看以下您需要了解的内容: • 您需要通过 Regsvr32 实用程序注册基于 COM 的 DLL。
• 您需要将本机 Win32 DLL 放置在应用程序路径中。
• 可能还需要将本机 Win32 DLL 放置在 Win32 目录中。
有时候很难区分基于 COM 的 DLL 和非基于 COM 的 DLL;但是,通常情况下,基于 COM 的 DLL 始终具有以下入口点:
• DllGetClassObject
• DllRegisterServer
• DllUnregisterServer
• DllCanUnloadNow
要查看入口点,请右键单击 DLL,然后单击快捷菜单中的“快速查看”。所显示的信息记录在 DLL 信息的“导出表”部分中。

以下是您从客户端启用 DMO 所需的与 SQL-DMO 有关的 DLL 列表:
• Sqldmo.dll
• Sqldmo.rll
• Sqlsvc.dll
• Sqlsvc.rll
• Sqlwoa.dll
• Sqlresld.dll
• Sqlwid.dll
• W95scm.dll
在上面的 DLL 列表中,Sqldmo.dll 是唯一您需要在客户端计算机上注册的 DLL。但是,要成功注册 Sqldmo.dll 文件,Sqldmo.rll 文件必须存在于客户端计算机上的以下目录中:
(服务器端位置):c:\Mssql7\Binn\Resources\1033
(客户端位置):c:\Winnt\System32\Resources\1033
Sqldmo.rll 文 件总是会引发问题。.rll 文件是本地化的资源文件。资源目录会根据 SQL Server 和客户端安装上配置的国家/地区语言的不同而异。在本例 中,目录 1033 是语言标识符 0X0409 的十进制表示,代表美国英语。将该 .rll 文件放置在适当的位置之后,可以通过调 用 Regsvr32 实用程序来注册 Sqldmo.dll 文件。注册该文件的命令是: C:\Regsvr32 Sqldmo.dll

注册成功后,应收到以下消息:
SQLDMO.dll 中的 DLLRegisterServer 成功。
如果您希望在您的应用程序安装例行过程中自动进行此类注册,请参见与 Regsvr32 实用程序关联的各个开关。以静默方式注册该文件的命令是: c:\regsvr32 /s- sqldmo.dll

客户端计算机上包含 Sqldmo.dll 文件的目录必须具有特定的结构,否则您可能会收到类似如下的错误消息:
LoadLibrary(“C:\Winnt\System32\sqldmo.dll”) 失败。
GetLastError 返回 0x0000007e
该 错误意味着发生了错误 126(以十进制表示),该错误对应于“找不到指定模块”错误。在本例中,此错误与 Sqldmo.rll 文件有关。 即,Regsvr32 实用程序找到了 Sqldmo.dll 文件,但无法完成该文件的注册,因为 Sqldmo.rll 文件不在预期 的 1033 子目录中。

要避免该问题,请执行下列操作:
1. 在 Sqldmo.dll 所在的目录中添加名为“Resources”的目录。
2. 在“Resources”目录下添加名为“1033”的子目录。
3. 将 Sqldmo.rll 文件复制到该目录中。
完成后,目录结构应类似如下:
包含 Sqldmo.dll 的目录\Resources\1033
且该 1033 目录应包含 Sqldmo.rll 文件。

除了前面提到的 DLL,您还需要确保您安装了正确的网络库 DLL。您在此需要的主要网络库 DLL 为: • 命名管道:Dbnmpntw.dll
• 套接字:Dbmssocn.dll
• 多协议:Dbmsrpcn.dll
这些 DLL 都是基于 Win32 的 DLL,因此您不必注册它们。只需将这些 DLL 放入  Microsoft Windows NT 的 System32 目录中,或  Microsoft Windows 95/Windows 98 的 System 目录中。

完成前面的步骤之后,客户端应用程序应当能够正常启动,不会出现最初由于缺少必要文件而导致的任何问题。

2008/01/17
实际案例:
在一台机器上布置SQLWEBADMIN后发现运行时出现如下错误:

Retrieving the COM class factory for component with CLSID {10020200-E260-11CF-AE68-00AA004A34D5} failed due to the following error: 80040154.

解决方案:
根据上面的文档,找到相应的文件,

Sqldmo.dll,Sqlsvc.dll,Sqlwoa.dll,Sqlresld.dll,Sqlwid.dll,W95scm.dll
复制到 %windir%\system32

Sqldmo.rll
Sqlsvc.rll
复制到 %windir%\system32\Resources\1033\
或(和)%windir%\system32\Resources\2052\
然后运行:regsvr32 Sqldmo.dll
成功注册,最终也解决了上述布署过程中遇到的问题.

[转载]Build CRUD Application with edit form in expanded row details - jQuery EasyUI

mikel阅读(1170)

[转载]Build CRUD Application with edit form in expanded row details – jQuery EasyUI.

When switch the datagrid view to ‘detailview’, users can expand a row to show any details below that row. This feature allows you to provide any possible layout for its edit form that placed in detail row panel. In this tutorial, we are using datagrid component to reduce the space occupied by the edit form.

Step 1: Create DataGrid in HTML tag

  1. <table id=“dg” title=“My Users” style=“width:550px;height:250px” url=“get_users.php” toolbar=“#toolbar” fitcolumns=“true” singleselect=“true”>
  2. <thead>
  3. <tr>
  4. <th field=“firstname” width=“50”>First Name</th>
  5. <th field=“lastname” width=“50”>Last Name</th>
  6. <th field=“phone” width=“50”>Phone</th>
  7. <th field=“email” width=“50”>Email</th>
  8. </tr>
  9. </thead>
  10. </table>
  11. <div id=“toolbar”>
  12. <a href=“#” class=“easyui-linkbutton” iconcls=“icon-add” plain=“true” onclick=“newItem()”>New</a>
  13. <a href=“#” class=“easyui-linkbutton” iconcls=“icon-remove” plain=“true” onclick=“destroyItem()”>Destroy</a>
  14. </div>

Step 2: Apply Detail View for DataGrid

  1. $(‘#dg’).datagrid({
  2. view: detailview,
  3. detailFormatter:function(index,row){
  4. return ‘<div class=”ddv”></div>’;
  5. },
  6. onExpandRow: function(index,row){
  7. var ddv = $(this).datagrid(‘getRowDetail’,index).find(‘div.ddv’);
  8. ddv.panel({
  9. border:false,
  10. cache:true,
  11. href:‘show_form.php?index=’+index,
  12. onLoad:function(){
  13. $(‘#dg’).datagrid(‘fixDetailRowHeight’,index);
  14. $(‘#dg’).datagrid(‘selectRow’,index);
  15. $(‘#dg’).datagrid(‘getRowDetail’,index).find(‘form’).form(‘load’,row);
  16. }
  17. });
  18. $(‘#dg’).datagrid(‘fixDetailRowHeight’,index);
  19. }
  20. });

To use the detail view for datagrid, include the ‘datagrid-detailview.js’ file to your page header.

We use the ‘detailFormatter’ function to generate the row detail content. In this case, we return the empty <div> that the edit form will be placed in. When users click the row expand button(‘+’), the ‘onExpandRow’ event will be triggered and we can load the edit form via ajax. Call ‘getRowDetail’ method to get the row detail container, so we can find the row detail panel. Create the panel in row details and load the edit form that returned from ‘show_form.php’.

Step 3: Create Edit Form

The edit form is loaded from server.

show_form.php
  1. <form method=“post”>
  2. <table class=“dv-table” style=“width:100%;background:#fafafa;padding:5px;margin-top:5px;”>
  3. <tbody><tr>
  4. <td>First Name</td>
  5. <td><input name=“firstname” class=“easyui-validatebox” required=“true”></td>
  6. <td>Last Name</td>
  7. <td><input name=“lastname” class=“easyui-validatebox” required=“true”></td>
  8. </tr>
  9. <tr>
  10. <td>Phone</td>
  11. <td><input name=“phone”></td>
  12. <td>Email</td>
  13. <td><input name=“email” class=“easyui-validatebox” validtype=“email”></td>
  14. </tr>
  15. </tbody></table>
  16. <div style=“padding:5px 0;text-align:right;padding-right:30px”>
  17. <a href=“#” class=“easyui-linkbutton” iconcls=“icon-save” plain=“true” onclick=“saveItem(<?php echo $_REQUEST[‘index’];?>)”>Save</a>
  18. <a href=“#” class=“easyui-linkbutton” iconcls=“icon-cancel” plain=“true” onclick=“cancelItem(<?php echo $_REQUEST[‘index’];?>)”>Cancel</a>
  19. </div>
  20. </form>

Step 4: Save or Cancel editing

Call the ‘saveItem’ function to save a user or ‘cancelItem’ function to cancel the editing.

  1. function saveItem(index){
  2. var row = $(‘#dg’).datagrid(‘getRows’)[index];
  3. var url = row.isNewRecord ? ‘save_user.php’ : ‘update_user.php?id=’+row.id;
  4. $(‘#dg’).datagrid(‘getRowDetail’,index).find(‘form’).form(‘submit’,{
  5. url: url,
  6. onSubmit: function(){
  7. return $(this).form(‘validate’);
  8. },
  9. success: function(data){
  10. data = eval(‘(‘+data+‘)’);
  11. data.isNewRecord = false;
  12. $(‘#dg’).datagrid(‘collapseRow’,index);
  13. $(‘#dg’).datagrid(‘updateRow’,{
  14. index: index,
  15. row: data
  16. });
  17. }
  18. });
  19. }

Determine what is the URL to post to first and then find form object and call ‘submit’ method to post the form data. Collapse and update the row data while saving data successfully.

  1. function cancelItem(index){
  2. var row = $(‘#dg’).datagrid(‘getRows’)[index];
  3. if (row.isNewRecord){
  4. $(‘#dg’).datagrid(‘deleteRow’,index);
  5. else {
  6. $(‘#dg’).datagrid(‘collapseRow’,index);
  7. }
  8. }

When cancel the editing action, if the row is new and not save yet, delete the row directly, otherwise collapse the row.

Download the EasyUI example:

[转载]使用Power Designer正反向数据库及生成设计报告

mikel阅读(845)

[转载]使用Power Designer正反向数据库及生成设计报告 – shishanyuan – 博客园.

正反向数据库及生成设计报告

最近使用Power Designer 12 越发觉得这个工具的强大,特此总结共享给大家。共享主要是经常正向、反向数据库,以及每次手工写数据库设计说明书的工作可以让Power Designer来实现,而且生成的类型丰富、格式可自定义。
1. 反向数据库
这个工作一般是在没有E-R设计的数据库进行的,可以反向生成数据库的E-R设计。其步骤如下:
1.1. 设置当前操作数据库系统
选择菜单Database->Change Current DBMS


弹出如下窗口,选择Oracle10g(具体按实际情况),并确认。


1.2. 设置ODBC数据源
有两种方式可以设置ODBC数据源:
(1)通过系统ODBC设计进行
首先选择“管理工具->数据源(ODBC)”


打开如下界面,选择“系统DSN”,然后点击“添加”按钮


选择“Oracle in OraDb10g home1”选项,点击”完成“按钮


在如下窗口中填入相关连接信息,并进行测试连接
数据源:设置ODBC连接名称
TNS名称:在Oracle设置实例访问的名称
用户:反向用户名

输入密码,点击“OK”按钮

测试成功


即成功加入ODBC数据源

(2)通过PowerDesigner反向提示进行
选择菜单“Database->Reverse engineer Database”

在该界面上,如果存在反向数据库则选择即可;如果没有存在反向数据库的连接则如图示点击按钮进行新增

在该界面上点击“Add”按钮进入系统ODBC增加页面


1.3. 选择需要反向的数据库ODBC源
选择菜单“Database->Reverse engineer Database”,点击数据库连接按钮

设置用户名和密码,然后点击”Connect“


选定了需连接的数据源


1.4. 选择反向对象生成E-R关系图
在上图中点击“确定”按钮,进入了反向对象界面,在该界面上可以选择表、视图、用户等对象类型,然后点击“OK”按钮


进入如下图


生成的关系图如下


2. 生成数据库
2.1. 设置当前操作数据库系统

按照1.1项设置当前操作数据库系统
2.2. 设置生成数据库选项
选择菜单atabase->Generate Database”


进入如下界面,在该界面设置生成脚本的文件夹、文件名,并且可以选择不同的选项卡进行


在“Options”选项卡中,选择生成脚本不同内容


在”Selection”选项卡中,选择生成脚本不同对象


2.3. 生成数据库脚本
在设置界面上,选择”Check model”值,进行有效性检查

正在生成数据库脚本


成功生成


3. 生成数据设计报告
在了解PowerDesigner报告生成方式以后我只能感叹该功能太强大了,没有做不到,只有想不到!可向导、定模板、直接生成报告等方式生成,生成的类型有html、RTF等,具体提供功能如下,在下面我介绍直接生成报告方式。


3.1. 新建报告内容模板
选择菜单”Report->Reports”,进入如下界面,点击新增报告按钮


设置报告名称、语言和模板,设置完毕后点击“OK“按钮


进入如下界面,在中间栏中是数据库设计中所有可以选择内容,右栏是设置报告格式


3.2. 设置报告格式
双击中间栏中的”Titile“格式,自动加载到右栏中,右键选择编辑,进入如下界面设置该级标题,

分别选择E-R关系图、表属性说明和表字段说明

3.3. 生成数据设计报告
设置完毕后,选择菜单”Report->Generate RTF”


设置文件生成的文件名称,确认生成即可


生成的样式如下,可以调整该报告的格式行程最终的数据库说明书

[转载]Form Validation - jQuery EasyUI

mikel阅读(921)

[转载]Form Validation – jQuery EasyUI.

This tutorial will show you how to validate a form. The easyui framework provides a validatebox plugin to validate a form. In this tutorial we will build a contact form and apply the validatebox plugin to validate the form. You can then adapt this form to your own requirements.

Build form

Let’s build a simple contact form with name, email, subject and message field:

  1. <div style=“padding:3px 2px;border-bottom:1px solid #ccc”>Form Validation</div>
  2. <form id=“ff” method=“post”>
  3. <div>
  4. <label for=“name”>Name:</label>
  5. <input class=“easyui-validatebox” type=“text” name=“name” required=“true”></input>
  6. </div>
  7. <div>
  8. <label for=“email”>Email:</label>
  9. <input class=“easyui-validatebox” type=“text” name=“email” required=“true” validType=“email”></input>
  10. </div>
  11. <div>
  12. <label for=“subject”>Subject:</label>
  13. <input class=“easyui-validatebox” type=“text” name=“subject” required=“true”></input>
  14. </div>
  15. <div>
  16. <label for=“message”>Message:</label>
  17. <textarea name=“message” style=“height:60px;”></textarea>
  18. </div>
  19. <div>
  20. <input type=“submit” value=“Submit”>
  21. </div>
  22. </form>

We add a class named easyui-validatebox to input markup so the input markup will be applied the validation according the validType attribute.

Prevent the form to submit when invalid

When users click the submit button of form, we should prevent the form to submit if the form is invalid.

  1. $(‘#ff’).form({
  2. url:‘form3_proc.php’,
  3. onSubmit:function(){
  4. return $(this).form(‘validate’);
  5. },
  6. success:function(data){
  7. $.messager.alert(‘Info’, data, ‘info’);
  8. }
  9. });

If the form is invalid, a tooltip message will show.

Download the EasyUI example:

[转载]easyui表单数据验证

mikel阅读(901)

[转载]easyui表单数据验证.

   <form id="ff" method="post">
        <div>
            <label for="name">
                Name:</label>
            <input class="easyui-validatebox" type="text" name="name" required="true" validtype="length[5,12]"></input>
        </div>
        <div>
            <label for="email">
                Email:</label>
            <input class="easyui-validatebox" type="text" name="email" required="true" validtype="email" invalidMessage="邮箱格式错误"></input>
        </div>
        <div>
            <label for="subject">
                Subject:</label>
            <input class="easyui-validatebox" type="text" name="subject" required="true" missingMessage="不能为空"></input>
        </div>
        <div>
            <label for="message">
                Message:</label>
            <textarea name="message" style="height: 60px;"></textarea>
        </div>
        <div>
            <input type="submit" value="Submit">
        </div>
        </form>

Validate Rule

The validate rule is defined by using required and validType property, here are the rules already implemented:

  • email: Match email regex rule.
  • url: Match URL regex rule.
  • length[0,100]: Between x and x characters allowed.
  • remote[‘http://…/action.do’,’paramName’]: Send ajax request to do validate value, return ‘true’ when successfully.

Properties

Name Type Description Default
required boolean Defines if the field should be inputed. false
validType string Defines the field valid type, such as email, url, etc. null
missingMessage string Tooltip text that appears when the text box is empty. This field is required.
invalidMessage string Tooltip text that appears when the content of text box is invalid. null

http://www.jeasyui.com/documentation/validatebox.php

[转载]SQL Server插入记录后获取自动增长的列值

mikel阅读(949)

[转载]SQL Server插入记录后获取自动增长的列值 – Allen_Li – 博客园.

在关系数据库中,我们经常会给一个表的主键设置为自增列,而在开发过程中,有时又会需要在插入一条记录后获得它的主键值,我们可以通过创建带有输出参数的 存储过程来完成这一任务。在T-SQL中,有三个函数可以用来检索标识列值:SCOPE_IDENTITY, @@IDENTITY, IDENT_CURRENT.

其中,SCOPE_IDENTITY为微软推荐使用函数,它返回当前执行范围内的最后一个标识值,大部分情况下都适用;@@IDENTITY函数包含当前 会话中任何表生成的最后一个标识值,由于这个函数受触发其影响,可能不会返回我们预期的值;IDENT_CURRENT函数返回在任何会话中以及任何范围 内为特定表生成的最后一个标识值。推荐大家使用SCOPE_IDENTITY函数。

下面我们就来创建一个可以返回标识值的存储过程:

   1: CREATE PROCEDURE dbo.CustomerInsert
   2:   @Name varchar(15),
   3:   @Age int,
   4:   @Sex bit,
   5:   @id int OUT
   6: AS
   7: INSERT INTO Customer(Name,Age,Sex) VALUES(@Name,@Age,@Sex)
   8: SET @id = SCOPE_IDENTITY()

然后我们可以在数据访问层写这样一个方法:

   1: /// <summary>
   2:     /// 插入一条Customer记录
   3:     /// </summary>
   4:     /// <param name="cus">要插入的Customer</param>
   5:     /// <param name="dt">要更新的数据表</param>
   6:     /// <returns>插入的Customer的id值</returns>
   7:     public int InsertCustomer(Customer cus, DataTable dt)
   8:     {
   9:         using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=test;Integrated Security=True"))
  10:         {
  11:             // 创建SqlDataAdapter
  12:             SqlDataAdapter adp = new SqlDataAdapter();
  13:
  14:             //创建InsertCommand命令
  15:             adp.InsertCommand = new SqlCommand("dbo.CustomerInsert", con);
  16:             //指定InsertCommand类型为存储过程
  17:             adp.InsertCommand.CommandType = CommandType.StoredProcedure;
  18:
  19:             //向InsertCommand加入参数
  20:             adp.InsertCommand.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar, 20, "Name"));
  21:             adp.InsertCommand.Parameters.Add(new SqlParameter("@Age", SqlDbType.Int, 4, "Age"));
  22:             adp.InsertCommand.Parameters.Add(new SqlParameter("@Sex", SqlDbType.Bit, 1, "Sex"));
  23:             SqlParameter parId = adp.InsertCommand.Parameters.Add(new SqlParameter("@id", SqlDbType.Int, 0, "id"));
  24:
  25:             //指定id为输出参数
  26:             parId.Direction = ParameterDirection.Output;
  27:
  28:             DataRow row = dt.NewRow();
  29:             row["Name"] = cus.Name;
  30:             row["Sex"] = cus.Sex;
  31:             row["Age"] = cus.Age;
  32:             dt.Rows.Add(row);
  33:
  34:             //更新数据库
  35:             adp.Update(dt);
  36:
  37:             //返回id值
  38:             return Convert.ToInt32(row["id"].ToString());
  39:         }
  40:     }

传入的DataTable为数据库中现有数据填充后的表,在需要插入后得到id的时候调用这样的方法就可以接收到返回的id值了。

[转载]尝鲜Jumony for MVC,体验插件化网站开发

mikel阅读(1015)

[转载]尝鲜Jumony for MVC,体验插件化网站开发 – Ivony… – 博客园.

Jumony for MVC是这一年来Jumony项目的重头戏,Jumony for MVC是Jumony技术与ASP.NET MVC的结合,尽管现在Jumony for MVC还未发布稳定版本,但确实是非常值得一试的一个视图引擎。希望这篇文章能给大家带来眼前一亮的感觉。

在“用网站(WebSite而不是WebProject)项目构建ASP.NET MVC网站”文章中,我已经说明了如何在网站项目上搭建MVC框架,那么这一次,我同样在网站项目上搭建Jumony for MVC。如果您已经安装了NuGet,这一切将变得非常简单,如果还没有,那么可以到NuGet的官方网站http://www.nuget.org/) 上下载,或者通过VS2010的扩展管理器直接搜索安装。由于Jumony for MVC要求.NET 4.0的环境,所以这一篇文章将基于VS2010 + .NET Framework 4.0 + NuGet等这些高科技武器来介绍,如果你缺乏其中的任何一样,说明你该升级你的装备了。

关于NuGet的使用,博客园也有很多文章介绍,例如dudu的这篇:http://www.cnblogs.com/dudu/archive/2011/07/15/nuget.html。在这篇文章中,我假定大家了解NuGet的基本用法,其实NuGet用起来很简单的。

一、安装Jumony for MVC

废话不多说,首先,当然还是要建立一个解决方案。然后,新建一个空白的网站:

image

掏空web.config中多余的设置:

image

然后通过NuGet安装Jumony for MVC的预览版。首先在网站上点击右键,选择Manage NuGet Packages

image

在搜索框中输入Jumony,然后选择Jumony for MVC,点击旁边的Install按钮

image

当跳出许可协议时,选择Accept(Jumony采用LGPL协议发布)。然后NuGet就会开始下载Jumony for MVC的预览版,同时安装到网站中。

安装完毕后网站应该是这样的:

image

同时web.config文件会被修改,添加大量配置,这些配置已经足够在网站项目运行MVC框架了。

二、准备Controller

然后我们开始来构建我们的第一个Controller,这一次我们尝试用一个独立的项目来承载Controller,这是插件化的第一步。那么新建一个项目,我命名为Demo.Test,这个项目仅仅用来测试我们的环境:

image

为这个项目添加System.Web.Mvc的引用,这里可能要特别注意版本,Jumony for MVC默认是使用MVC2的,所以这里也添加MVC2的引用。

当然你也可以修改web.config中的MVC程序集的版本。要确保你的Controller项目所引用MVC的版本和网站所引用的一致,否则就要添加MVC版本兼容的配置了,我在这里不详述。就用MVC2来做示范。

添加引用后,就可以删除默认的cs文件,添加一个Controller,我命名为TestController,然后往里面随便塞一个Action,像这样:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Demo.Test
{
   public class TestController : Controller
   {
     public ActionResult Index()
     {
        //这个Action就是输出一个视图
      return View();
     }
   }
}

OK,接下来是配置路由,如果路由都在global.asax中配置,那是多么没有创意的事情,而且,这会造成所有的功能都要到那边去配置一下,不 利于我们所追求的插件化。所以,这一次我在Controller程序集里面配置路由,这样,只要这个程序集的DLL放在了网站的bin文件夹,那么路由就 自动被配置了,是不是很酷呢?这么酷的功能利用ASP.NET 4的新特性其实非常好实现。首先我们要添加System.Web程序集的引用,然后添加如下代码:

[assembly: System.Web.PreApplicationStartMethod( typeof( Demo.Test.RoutingRegister ), "RegisterRouting" )]
namespace Demo.Test
{
   public static class RoutingRegister
   {
     public static void RegisterRouting()
     {
     }
   }

注意PreApplicationStartMethod这个特性要注册在程序集范畴(assembly),所以除了在前面要加上assembly:之外,还需要放到namespace块的外面去。

通过这样的代码,我们就能确保在网站应用程序启动前执行RegisterRouting这个方法了,所以,我们可以在这里添加路由注册的代码。不过 在这里,我要向大家介绍一下Jumony for MVC提供的一个MVC框架改善,简单路由表(SimpleRoutingTable)。

首先,通过同样的方法,利用NuGet为这个项目添加Jumony for MVC的引用。然后引用Jumony for MVC的命名空间Ivony.Html.Web.Mvc,最后在RegisterRouting方法中注册一个路由:

    public static void RegisterRouting()
    {
      MvcEnvironment.SimpleRoutingTable.MapAction( "~/", "Test", "Index" );
    }

简单路由表的实例总是可以通过MvcEnvironment静态类型来获取,通过同样的手法,Jumony for MVC会自动为系统注册简单路由表为一个路由服务。在这里简单说一下简单路由表相对于ASP.NET Routing默认实现的一部分改善。

  1. 首先是简单路由表没有RouteTable的先到先得的原则,在简单路由表中的路由规则遵循的是谁更适合就选谁的原则,这更符合使用者的直觉。也使得我们可以把路由规则注册分散到各个项目,即使这些路由规则被注册的时间不可控。(这可是插件化的关键问题之一)
  2. 由于简单路由表遵循的是谁更适合的原则,所以简单路由表不允许注册存在冲突的路由规则,这样更不容易犯错。
  3. 简单路由表取消了复杂的概念,像上面那个路由规则,其实非常简单,就是在”~/”这个虚拟路径和{ controller: Test, action: Test }之间建立一个对应的关系。取消了默认值和有效值的概念,尽管牺牲了灵活性,但提高了对URL的可控性。不会产生令人惊讶的结果。

简单路由表事实上只是RouteBase的一个实现(也就是一个路由),所以尽管通过简单路由表注册的路由规则没有先到先得的规则,但简单路由表与 其他RouteBase实现一起在RouteTable中仍然遵循ASP.NET框架所设定的先到先得规则。关于这一点,我在后面的系列文章中再详细的讨 论简单路由表。

最终的代码像这样:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Ivony.Html.Web.Mvc;

[assembly: System.Web.PreApplicationStartMethod( typeof( Demo.Test.RoutingRegister ), "RegisterRouting" )]
namespace Demo.Test
{
   public static class RoutingRegister
   {
     public static void RegisterRouting()
     {
       MvcEnvironment.SimpleRoutingTable.MapAction( "~/", "Test", "Index" );
     }
   }
   public class TestController : Controller
   {
     public ActionResult Index()
     {
       //这个Action就是输出一个视图
       return View();
     }
   }
}

三、配置视图

Controller和路由都已经配置完毕,现在回到网站,我们为网站添加刚刚Demo.Test项目的引用:

image

然后生成网站,运行之,检查我们的路由和Controller是否正常运行。(记得一定要先生成网站,这样我们的Demo.Test才会被编译为DLL并放到bin文件夹)。

image

如果您看到的是这个界面,就说明已经成功了。细心的您可能已经发现,查找路径中已然包含了html文件的查找,这就是JumonyViewEngine被注册的结果。这一切都是通过同样的手法(PreApplicationStartMethod特性)在悄声无息中完成的。

那么接下来就是弄一个视图出来,我比较习惯把所有视图页面都放在Views目录下,不要带上Controller名字的文件夹,所以我弄了一个index.html文件放在Views文件夹下:

image

内容就像这样子:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Hello Jumony</title>
</head>
<body>
  Jumony for MVC
</body>
</html>

因为不是放在指定的位置,所以我们需要修改一下JumonyViewEngine的设置,打开global.asax文件,修改为下面这样:

  void Application_Start( object sender, EventArgs e )
  {
    MvcEnvironment.JumonyViewEngine.ViewLocationFormats = new[] { "~/Views/{0}.html" };
  }

要搜索多个路径,可以在数组中多添加几个路径模版。当修改完了后,再次打开网站应该是这样了:

image

四、留言板

当然这个网站毫无意义,我们做个有意义的东西,留言板,只包含两个功能添加留言和浏览留言的留言板(尽管还是没啥意义,但是Demo,大家总不能让我弄个论坛来做示范)。

以前做网站都是需要先出来页面,程序才开始动手,那么这一次,我们可以先不要管页面,先构建留言板的功能实现,即Controller实现。

同样的,我新建了一个独立的项目:Demo.MessageController,添加引用创建Controller的过程和之前一样,在此不再赘述,最终实现的Controller像这样:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using System.Web.Hosting;
using System.IO;
using Ivony.Html.Web.Mvc;

[assembly: System.Web.PreApplicationStartMethod( typeof( Demo.MessageBoard.RoutingRegister ), "RegisterRouting" )]
namespace Demo.MessageBoard
{
   public static class RoutingRegister
  {
    public static void RegisterRouting()
    {
      MvcEnvironment.SimpleRoutingTable.MapAction( "~/messages", "MessageBoard", "List" );
      MvcEnvironment.SimpleRoutingTable.MapAction( "~/messages/add", "MessageBoard", "add" );
    }
  }
 
  public class MessageBoardController : Controller
  {
 
    private const string dataPath = "~/Data";
 
    private string physicalPath;
 
    protected override void OnActionExecuting( ActionExecutingContext filterContext )
    {
      physicalPath = HostingEnvironment.MapPath( dataPath );
      Directory.CreateDirectory( physicalPath );
 
      base.OnActionExecuting( filterContext );
    }
 
    public ActionResult List()
    {
 
      var messages = new DirectoryInfo( physicalPath )
        .EnumerateFiles()
        .OrderBy( file => file.CreationTime )
        .Select( file => System.IO.File.ReadAllText( file.FullName ) );
 
      return View( "Message_List", messages );
    }
 
    public ActionResult Add( string message )
    {
      var filepath = Path.Combine( physicalPath, Guid.NewGuid().ToString() + ".txt" );
 
      System.IO.File.WriteAllText( filepath, message );
 
      return RedirectToAction( "List" );
 
    }
 
  }
 
}

两个Action,简单明了,为了避免配置数据库等麻烦事儿,这里直接用文件系统担任了数据库,所有的留言都以文本文件保存了下来。然后我们为网站添加这个功能,也就是让网站项目引用这个 Controller所在的项目。

然后要为这个留言板提供一个视图,在List这个Action中,已经显示指定了视图的名称,Message_List。所以我在Views文件夹添加了这样一个HTML文件:

image

内容如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>留言板</title>
  <style>
    body
    {
      font-size: 12px;
      margin: 10px;
    }
    .message
    {
      margin: 15px 0px;
      border: dashed 1px;
      padding: 10px;
    }
  </style>
</head>
<body>
  <div class="message">
  </div>
  <form method="post" action="Add" controller>
  <div>
    <textarea id="message" name="message" style="width: 500px; height: 100px;"></textarea>
  </div>

  <div>
    <input type="submit" value="提交留言" />
  </div>
  </form>
</body>
</html>

注意form标签里面的属性,这样写的意思就是,提交到相同Controller的名为Add的Action去。这就是Jumony视图引擎,自然 流畅。由于action本来就是标准form元素的一个属性,所以加一个controller强调不是提交到Add这个URL,controller不设 置值,则会从当前上下文继承。

接下来我们在那个测试首页添加一个链接,让我们可以访问到留言板的页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Hello Jumony</title>
</head>
<body>
  <a action="List" controller="MessageBoard">MessageBoard</a>
</body>
</html>

<a>标签中的action和controller就不解释了,这时候再打开网站,看到的应该是这样的效果:

image

点击链接就可以到达留言板:

image

我们可以随便留言,但提交后,页面一闪而过,还是老样子。这是因为我们还没有为留言板页面绑定留言数据。

Jumony现阶段对这种简单重复N次的工作并不比WebForm或是Razor好,所以我决定将绑定数据外包给WebForm来做,顺便也可以看看Jumony for MVC是如何与其他视图引擎无缝兼容的。

WebFormViewEngine的视图查找逻辑也是可以修改的,但比较麻烦,所以这一次我决定按照他的规则,新建一个Shared文件夹,在下面创建一个部分视图。

image

如何在网站创建WebFormViewEngine的视图已经在上一篇文章中探讨过,主要就是设置Inherits属性,作为用户控件(部分视图),应从ViewUserControl继承,以下是部分视图完整代码:

<%@ Control Language="C#" ClassName="MessageListPartial" Inherits="System.Web.Mvc.ViewUserControl" %>
<%
  foreach ( var message in (IEnumerable<string>) Model )
  {
%>
<div class="message">
  <%=message %>
</div>
<% }%>

当然,如果用Razor,这里的代码能够更为简洁和优雅。

接下来是如何将这个部分视图拼合到Jumony视图引擎的html视图中去,其实也非常简单,使用partial标签,将原来的<div class=”message”></div>修改为这样:

  <partial view="MessageListPartial"></partial>

重新打开留言板看看,应该可以看到留言了:

image

Jumony for MVC,值得您关注。。。。。

http://jumony.codeplex.com/

[原创]自定义ASP.NET MVC JsonResult序列化结果

mikel阅读(1856)

自定义ASP.NET MVC JsonResult序列化结果

自定义ASP.NET MVC 控制器和JsonResult

最近项目中前台页面使用EasyUIJQuery插件开发中遇到,EasyUI Form中的Datebox组件绑定ASP.NET MVC返回的DateTime类型的数据错误,因为ASP.NET MVC返回的DateTime类型的JsonResult的结果中的值是“\/Date(277630788015)\/”,于是EasyUI显示的就是返回的值,没有将日期转换,直接显示在DateBox组件中,解决这个问题其实有两种办法:

1. 扩展EasyUIdatebox组件的parser函数自定义格式化日期格式,不过存在一个问题是如果使用form.load数据是先将值赋给datebox不会调用dateboxparser方法,只有在加载完form后再改变datebox的值为”2011-11-3”格式的值;

2. 第二种方式就是本文要讲得修改ASP.NET MVCJson序列化方法,也就是修改JsonResult的序列化方法,下面就来详细说下这种方法。

首先看下ASP.NET MVC中的Controller Json方法的源码:

protected internal JsonResult Json(object data) {

return Json(data, null /* contentType */);

}

protected internal JsonResult Json(object data, string contentType) {

return Json(data, contentType, null /* contentEncoding */);

}

protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding) {

return new JsonResult {

Data = data,

ContentType = contentType,

ContentEncoding = contentEncoding

};

}

可以看出关键还是在JsonResult这个结果类中,JsonResult类的源码如下:

[AspNetHostingPermission(System.Security.Permissions.SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]

[AspNetHostingPermission(System.Security.Permissions.SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]

public class JsonResult : ActionResult {

public Encoding ContentEncoding {

get;

set;

}

public string ContentType {

get;

set;

}

public object Data {

get;

set;

}

public override void ExecuteResult(ControllerContext context) {

if (context == null) {

throw new ArgumentNullException(“context”);

}

HttpResponseBase response = context.HttpContext.Response;

if (!String.IsNullOrEmpty(ContentType)) {

response.ContentType = ContentType;

}

else {

response.ContentType = “application/json”;

}

if (ContentEncoding != null) {

response.ContentEncoding = ContentEncoding;

}

if (Data != null) {

#pragma warning disable 0618

JavaScriptSerializer serializer = new JavaScriptSerializer();

response.Write(serializer.Serialize(Data));

#pragma warning restore 0618

}

}

}

}

看到这里大家应该明确我们的修改目标了,对,就是ExecuteResult这个方法,这个方法是序列化Data对象为Json格式的,可见ASP.NET MVC 使用的是System.Web.Script.Serialization.JavaScriptSerializer

既然明确了目标,那么就开始动手吧。

1. 扩展JsonResult类自定义个CustomJsonResult类,重写ExecuteResult方法代码如下:


public class CustomJsonResult:JsonResult

{

public override void ExecuteResult(ControllerContext context)

{

if (context == null)

{

throw new ArgumentNullException(“context”);

}

HttpResponseBase response = context.HttpContext.Response;

if (!String.IsNullOrEmpty(ContentType))

{

response.ContentType = ContentType;

}

else

{

response.ContentType = “application/json”;

}

if (ContentEncoding != null)

{

response.ContentEncoding = ContentEncoding;

}

if (Data != null)

{

#pragma warning disable 0618

response.Write(JsonConvert.SerializeObject(Data));

#pragma warning restore 0618

}

}

我们使用的是Newtonsoft.Json.JsonConvert类序列化对象为Json的,具体集中.NET中的序列化对比可以参考文章:.NET使用JSON作为数据交换格式

2. 扩展Controller重写Json方法,代码如下:


public class BaseController:Controller

{

protected override JsonResult Json(object data, string contentType, Encoding contentEncoding)

{

return new CustomJsonResult

{

Data = data,

ContentType = contentType,

ContentEncoding = contentEncoding

};

}

}

下面就是我们实际使用方法了,因为Newtonsoft.Json.JsonConvertDateTime类型可以指定序列化日期的类型为: [JsonConverter(typeof(IsoDateTimeConverter))] [JsonConverter(typeof(JavaScriptDateTimeConverter))]

[JsonConverter(typeof(IsoDateTimeConverter))]序列化后的格式为:1981-03-16T00:20:12.1875+08:00

[JsonConverter(typeof(JavaScriptDateTimeConverter))]序列化后的格式为:new Date(-277630787812)

于是我们指定实体类的DateTime属性为IsoDateTimeConverter,代码如下:

[Field(“P_Date”, “更新日期“)]

[JsonConverter(typeof(IsoDateTimeConverter))]

public DateTime P_Date { get; set; }

控制器继承自BaseControllerAction的返回结果还是JsonResult格式,代码如下:

public class GoodsController:BaseController

{

public JsonResult List(string page, string rows)

{

Page thepage = new Page() { PageSize = 20, CurrentPage = 1 };

if (!String.IsNullOrEmpty(rows))

{

thepage.PageSize = Convert.ToInt32(rows);

}

if (!String.IsNullOrEmpty(page))

{

thepage.CurrentPage = Convert.ToInt32(page);

}

Dictionary<string, object> result = new Dictionary<string, object>();

result.Add(“rows”, new BusinessLogic().SelectByPage<GoodsList>(ref thepage));

result.Add(“total”, thepage.SumCount);

return Json(result);

}

}