2015年1月24日 星期六

Kendo UI MultiSelect, 連搜尋的功能都有,方便又好用~~

有時候我們會遇到一個需求,某個選項是可以複選的,並且希望還要附帶可以搜尋的功能,如果要手刻的話…實在是個大工程,今天要介紹一下Kendo UI的MultiSelect元件,輕鬆的就可以做到這件事囉~~
官網說明

1. 首先一樣要加加入Kendo UI的css和js,就不額外說明了

2.  加入tag
<select id="PeopleCC" name="PeopleCC" multiple="multiple" ></select>

3. 加入js


$("#PeopleTO").kendoMultiSelect({
                placeholder: "Select employee...",
                dataTextField: "Display",
                dataValueField: "Id",
                autoBind: false,
                filter: 'contains',
                dataSource: {
                    type: "json",
                    transport: {
                        read: {
                            type: "POST",
                            dataType: "json",
                            contentType: "application/json",
                            url: "/Alarm/GetMutiSelect",
                        }
                    }
                }
                //value: [
                //    { ProductName: "Chang", ProductID: 2 },
                //    { ProductName: "Uncle Bob's Organic Dried Pears", ProductID: 7 }
                //]
            });

如果是一到這個頁面,就要自動進行Binding的話autoBind要記得改成true,例如在要編輯資料時,需要預設從db取出上次選擇的資料,這時如果沒有將autoBind改為true的話,MultiSelect會一直沒有資料可以選擇,因為MultiSelect是當第一次使用者點了它之後,才去做binding的動作,如果裡面已經有填資料進去,就不會binding囉

filter: 'contains',這個選項就是開啟搜尋的功能
value: 如果需要預設值,就可以在value裡設定

使用方法非常簡單,到目前為止小艾差不說試了4、5種Kendo UI的元件了,用法上大同小異,就是設好datasource,然後指給tag就對了

2015年1月8日 星期四

asp.net Common Logging + NLog 設定方法

log4net和nlog應該是一般工程師比較常使用的log機制,這兩個log套件雖然類似,但各自有各自的優點,如何讓它們能夠輕鬆的轉換呢?那就要使用Common.Logging

Common Logging是一個Log的介面,支援log4net、nlog、enterprise library logging...等,可透過log設定的方式,輕鬆的轉換不同的log機制,詳細請看請點我

設定方式也十分簡單,首先打開NuGet
1. 先安裝Common.Logging

今天小艾打算要配合NLog來使用

2.安裝Common.Logging.NLogXX (XX是版本號)

加入NLog的,為了方便使用

3.安裝NLog.Configuration

安裝完後就會自動產生NLog.config檔了,接下來只要設定好config就完成囉

4.在web.config的<configuration></configuration>裡加入

<configSections>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
</configSections>
<common>
<logging>
<factoryAdapter type="Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog31">
<arg key="configType" value="FILE" />
<arg key="configFile" value="~/NLog.config" />
</factoryAdapter>
</logging>
</common>

其中的Common.Logging.NLog31的31記得要改成第2步驟安裝的版號,這樣web.config的設定就完成了,接下來只要設定好NLog.config就大功告成了

5. 設定NLog.config

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->

<targets>

<target xsi:type="File" name="debug"
fileName="${basedir}/logs/debug/logfile.log"
layout="${longdate} ${uppercase:${level}} ${message}"
archiveEvery="Day"
archiveNumbering="Date"
maxArchiveFiles="30"
keepFileOpen="false"
archiveFileName="${basedir}/logs/debug/log.{#}.txt" />

<target xsi:type="File" name="info"
fileName="${basedir}/logs/info/logfile.log"
layout="${longdate} ${uppercase:${level}} ${message}"
archiveEvery="Day"
archiveNumbering="Date"
maxArchiveFiles="30"
keepFileOpen="false"
archiveFileName="${basedir}/logs/info/log.{#}.txt" />

<target xsi:type="File" name="error"
fileName="${basedir}/logs/error/logfile.log"
layout="${longdate} - ${onexception:inner=${exception:format=ToString}${newline}}"
archiveEvery="Day"
archiveNumbering="Date"
maxArchiveFiles="30"
keepFileOpen="false"
archiveFileName="${basedir}/logs/error/log.{#}.txt" />

</targets>

<rules>
<logger name="*" minlevel="Trace" writeTo="debug" />
<logger name="*" level="Info" writeTo="info" />
<logger name="*" level="Error" writeTo="error" />
</rules>
</nlog>

target裡的詳細設定
fileName:設定log要放的位置
layout:log寫入的格式
archiveEvery="Day" : 每天產生一個log檔
archiveNumbering="Date" : 檔名的產生方式 {#} 就會以日期來替換
maxArchiveFiles="30" : 只保存30個檔案
archiveFileName :  自動產生出來檔案的檔名,照這裡的設定,當天的log檔名是logfile.log
前一天的是log.日期.txt,以此類推

rules裡的詳細設定
minlevel :只定要記到哪個層級的log,在nlog裡共有Trace, Debug, Info, Warn, Error, Fatal這幾個層級
witeTo :對應到target裡的name,設定記錄要記到哪個檔案

6.以上的設定就全部完成了,接下來只要在code裡寫上log就會成功將log寫進file裡了

private static readonly ILog Log = LogManager.GetCurrentClassLogger();
Log.Info("Application Start");

這樣就會在Info寫進Appliction Start的訊息了,只要把Info改成Debug, Error...就能夠偵對Log分層了,相當簡單實用,log寫的好,debug也會輕鬆許多~~

關於NLog的一些設定,可以參考這裡請點我


2015年1月6日 星期二

Kendo UI Grid 全AJAX的CRUD功能範例

Grid有許多的套件都有提供,今天小艾要介紹一套,Kendo UI的Grid使用方式,先附上官網
Kendo UI

1.   首先套用css和javascript

<link rel="stylesheet" href="styles/kendo.common.min.css" />
<link rel="stylesheet" href="styles/kendo.default.min.css" />
<link rel="stylesheet" href="styles/kendo.dataviz.min.css" />
<link rel="stylesheet" href="styles/kendo.dataviz.default.min.css" />

<script src="js/jquery.min.js"></script>
<script src="js/kendo.all.min.js"></script>

2. 加入html
<div id="example">
    <div id="grid"></div>

</div>

3. 接下來都是javascript的處理了

設定dataSource
var dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                type: "POST",
                url: "/PeopleData/PeopleList",
                dataType: "json",
                contentType: "application/json"
            },
            update: {
                type: "POST",
                url: "/PeopleData/Edit",
                dataType: "json",
                contentType: "application/json"
            },
            destroy: {
                type: "POST",
                url: "/PeopleData/Delete",
                dataType: "json",
                contentType: "application/json"
            },
            create: {
                type: "POST",
                url: "/PeopleData/Create",
                dataType: "json",
                contentType: "application/json"
            },
            parameterMap: function (data, operation) {
                if (operation === "read") {
                    return JSON.stringify({ skip: data.skip, take: data.take });
                }
                else if ((operation === "update" || operation === "create") && data) {
                    return JSON.stringify({ peopleData: data });
                }
                else if (operation === "destroy" && data.PeopleID) {
                    return JSON.stringify({ personId: data.PeopleID });
                }
                return data;
            }
        },
        //batch: true,
        schema: {
            //取出資料陣列
            data: function (d) { return d.PeopleDataList; },
            //取出資料總筆數(計算頁數用)
            total: function (d) { return d.Count; },
            model: {
                id: "PeopleID",
                fields: {
                    PeopleID: { editable: false, nullable: true },
                    CN: { validation: { required: true } },
                    Depart: { defaultValue: { DepartID: 0, DepartName: "Please wait" } },
                    Pasd: { validation: { required: true } },
                    Name: { validation: { required: true } },
                    Mail: { type: "email", validation: { required: true } },
                }
            }
        },
        pageSize: 10,
        serverPaging: true,
        serverSorting: true
    });

transport裡的read,update,destroy,create分別對應到讀取,修改,新增,刪除的動作。
parameterMap裡偵對不同的指令,把值傳入後端做處理。
schema設定grid顯示對應的資料,還可以加上vaildation的設定

設定好Datasource後,就要準備把資料塞給kendo ui grid了

$("#grid").kendoGrid({
        dataSource: dataSource,
        pageable: true,
        height: 550,
        toolbar: ["create"],
        columns: [
            "Name",
            { field: "CN", title: "CN" },
            { field: "Depart", title: "Depart", width: "180px", editor: departDropDownEditor, template: "#=Depart.DepartName#" },
            { field: "Pasd", title: "Pasd" },
            { field: "Mail", title: "Mail" },
            { command: ["edit", "destroy"], title: " ", width: "250px" }],
        editable: "inline"
    });

值得注意的是,Depart以DropDownList的方式呈現,所以需要設定departDropDownEditor,到後端去取得Depart List的資料
PS. 下面的 $('input  應該是  $('<input,不過blogger會顯示成text…所以就把 < 拿掉了,複製code時別忘了加回去哦!

function departDropDownEditor(container, options) {
        $('input data-bind="value:' + options.field + '" data-text-field="DepartName" data-value-field="DepartID" required="" />')
            .appendTo(container)
            .kendoDropDownList({
                autoBind: false,
                dataSource: {
                    type: "json",
                    transport: {
                        read: {
                            type: "POST",
                            url: "/PeopleData/GetDepartList",
                            dataType: "json",
                            contentType: "application/json"
                        },
                    }
                }
            });
    }

departDropDownEditor去後端取出資料後,把name和id bind給list就大功告成囉!!簡單明瞭,出來的效果也不錯,完全不需要導頁,全AJAX就搞定CRUD功能。

附上範例程式:請點我

最後推薦個新創日本求職網站
Trails會慢慢的提供一些有用的資訊給想到日本去工作的朋友,只要簡單的註冊會員後就可以免費看文章,找工作囉~~目前日本企業職缺正在募集中,會陸陸續續更新上來!

2015年1月2日 星期五

jQuery UI Sortable 拖曳更改順序並記錄

jQuery UI有個很好用的功能,可以使用拖曳的方式,直接調整畫面的順序,請見jQuery UI官網 jqueryui.com

但拖曳完後,要怎麼把排列順序存入後端呢?

資料庫設計了CategoryId、CategoryName、CategoryOrder三個欄位(CategoryOrder記錄順序)

首先先處理html的部份

1. 先加入jvavscript (因為套bootstrap畫面較好看,所以順便加入)
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery-ui-1.11.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>

2. 加入css (可省略,只是為了加入bootstrap畫面較好看)
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />

3. 設計表格,Sortable 也可支援<ul></ul>不一定要使用table
<table id="mytable" class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.CategoryName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CategoryOrder)
        </th>
        <th></th>
    </tr>
    <tbody id="myfruit">
        @foreach (var item in Model.OrderBy(r => r.CategoryOrder))
        {
            <tr id="@Html.DisplayFor(modelItem => item.CategoryOrder)">
                <td>
                    @Html.DisplayFor(modelItem => item.CategoryName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.CategoryOrder)
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.CategoryId }) |
                    @Html.ActionLink("Details", "Details", new { id = item.CategoryId }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.CategoryId })
                </td>
            </tr>
        }
    </tbody>
</table>

4.套入jQuery UI Sortable效果,在update裡使用$(this).sortable('toArray').toString();將表格裡的<tr id="@Html.DisplayFor(modelItem => item.CategoryOrder)">串成字串,但此方法只能將id轉成字串,較好的方法應該是取td裡的CategoryOrder欄位,但sortable好像沒辦法直接取到,可能要用jquery想辦法去取…就沒有做測試了

最後將組好的字串傳到後端處理,存進資料庫就大功告成囉~~
另外,因為沒有使用Angular或Knockout來做Data binding,而且傳到後端的是取tr的id…所以每次必需Reload畫面,讓id更新才行,較好的方法應該是使用Data binding,讓畫面上的CategoryOrder會即時更改,並取出傳至後端,就不需要每次重load了。

$(function () {
    $('#mytable tbody').sortable({
        opacity: 0.6,
        cursor: 'move',
        axis: 'y',
        update: function (event, ui) {
            var productOrder = $(this).sortable('toArray').toString();
            $.ajax({
                type: 'post',
                url: '/Home/DragItem',
                data: {
                    orders: productOrder
                },
                success: function (result) {
                    window.location.href = result.redirectToUrl;
                }
            });
        }
    });
});
-------------------------2015.01.17更新------------------------------------------------

更新jQuery UI Sortable取得oldIndex和newIndex的方法,只需要傳兩個值到後端,就能夠偵對order進行排序,無需傳入一整個list囉。
$('#grid tbody').sortable({
        opacity: 0.6,
        cursor: 'move',
        axis: 'y',
        start: function (event, ui) {
            var start_pos = ui.item.index();
            ui.item.data('start_pos', start_pos);
        },
        update: function (event, ui) {
            //var productOrder = $(this).sortable('toArray').toString();
            var oldIndex = ui.item.data('start_pos');
            var newIndex = ui.item.context.rowIndex;
            $.ajax({
                type: 'post',
                url: '/PeopleGroups/DropOrderItem',
                data: {
                    oldIndex: oldIndex + 1,
                    newIndex: newIndex + 1,
                    page: currPage,
                    pageSize: pageSize
                }
            });
        }
    });


1. start,當拖曳動作開始,就會先執行這一段,這使用ui.item.index(),就可以取得目前使用者拖曳的item的index,在用ui.item.data('start_pos', start_pos),把index填進此item的'start_pos'(這個名字可以自訂),tag中,產生出來的html會變成 <tr start_pos = "index"></tr>

2. 在update時,就可以使用ui.item.data('start_pos'),將剛才存下來的index取出來,在使用ui.item.context.rowIndex取得最新的index,將這兩個index傳到後端就大空告成了!!

3.  順便附上後端的c# code供大家參考

if (oldIndex < newIndex)
            {
                var currGroup = ESHCloudsContext.PeopleGroups.SingleOrDefault(r => r.GroupOrder == oldIndex);
                if (currGroup == null)
                    return false;

                var peopleGroupList = ESHCloudsContext.PeopleGroups
                    .Where(r =>
                        r.GroupOrder <= newIndex &&
                        r.GroupOrder > oldIndex &&
                        r.GroupID != currGroup.GroupID
                    ).ToList();

                foreach (var peopleGroup in peopleGroupList)
                    peopleGroup.GroupOrder--;

                currGroup.GroupOrder = newIndex;
                ESHCloudsContext.SaveChanges();
            }
            else
            {
                var currGroup = ESHCloudsContext.PeopleGroups.SingleOrDefault(r => r.GroupOrder == oldIndex);
                if (currGroup == null)
                    return false;

                var peopleGroupList = ESHCloudsContext.PeopleGroups
                    .Where(r =>
                        r.GroupOrder < oldIndex &&
                        r.GroupOrder >= newIndex &&
                        r.GroupID != currGroup.GroupID
                    ).ToList();

                foreach (var peopleGroup in peopleGroupList)
                    peopleGroup.GroupOrder++;

                currGroup.GroupOrder = newIndex;
                ESHCloudsContext.SaveChanges();
            }


比上次的方法容易且合理多了,如果grid有設定分頁的話,別忘了把page和pagesize也傳到後端進行判斷囉!!

最後推薦個新創日本求職網站
Trails會慢慢的提供一些有用的資訊給想到日本去工作的朋友,只要簡單的註冊會員後就可以免費看文章,找工作囉~~目前日本企業職缺正在募集中,會陸陸續續更新上來!

[泰國] 芭達雅大城八日遊 Day7、8 - 瑪哈泰寺、Wat Ratchaburana、帕蒙空博碧寺、帕席桑碧寺、Hua Ro market、Chantharakasem National Museum、Amporn Department Store

第七天行程,早上吃飯店早餐,算不錯吃,只是有螞蟻,但吃完沒拉,所以應該還好 吃飽後飽嘟嘟車,一小時 200 泰銖,比自己叫還便宜,終於要來世界遺產之旅了 第一站:瑪哈泰寺,應該是大城最有名的景點了,入門票大人 120 ,小孩免費,其實不便宜 大城指標性景點...