fineui实时监控(增、删、改)+CDC+长连接(一)

一:前台页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestRealStoping.aspx.cs"
    Inherits="WebApp.StopGenerat.TestRealStoping" %>

<!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 id="Head1" runat="server">
    <title>实时停发电综合管理</title>
    <script type="text/javascript" src="/js/jquery-1.8.2.min.js"></script>
    <script charset="gb2312" type="text/javascript" src="/js/PublicFunction.js"></script>
    <script charset="gb2312" type="text/javascript" src="btnclick.js"></script>
    <link href="/css/DGrid.css" type="text/css" rel="stylesheet" />
    <link rel="stylesheet" href="/extjs/bootstrap.css" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <script type="text/javascript">
        //    因为在ext之前构成,而因为ext控件加载extjs对象较晚,则extjs 写在onready之后
        var highlightRowsClientID = '<%= highlightRows.ClientID %>';
        var gridClientID = '<%= DGrid.ClientID %>';
        var UserLscCode = '<%=UserLscCode.ClientID %>';
        var EXTMinId = '<%=EXTMinId.ClientID %>';
        var EXTMaxId = '<%=EXTMaxId.ClientID %>';
        var EXTCurpagelenth = '<%=EXTCurpagelenth.ClientID %>';

        var TxtSumAdd = '<%=TxtSumAdd.ClientID %>';
        var TxtSumDelete = '<%=TxtSumDelete.ClientID %>';
        var TxtSumUpdate = '<%=TxtSumUpdate.ClientID %>';
        var TxtPrevAdd = '<%=TxtPrevAdd.ClientID %>';
        var TxtPrevDelete = '<%=TxtPrevDelete.ClientID %>';
        var TxtPrevUpdate = '<%=TxtPrevUpdate.ClientID %>';
        var PrevTimeTag = '<%=PrevTimeTag.ClientID %>';


        var intSumAdd = 0;
        var intSumDelete = 0;
        var intSumUpdate = 0;
        var intPrevAdd = 0;
        var intPrevDelete = 0;
        var intPrevUpdate = 0;


        var grid;
        var currRecord;
        var currRowIndex;


        //本页变量--每次页面回发的时候重写。
        var minid = 0;
        var maxid = 0;
        var pagesizze = 50;
        var curpagelenth = 0;



        var rightClick;
        //右键菜单代码关键部分
        function rightClickFn(grid, rowindex, e) {

            e.preventDefault();
            if (rowindex < 0) {
                return;
            }
            grid.getSelectionModel().selectRow(rowindex);

            currRecord = grid.getStore().getAt(rowindex);
            currRowIndex = rowindex;
            rightClick.showAt(e.getXY());

        }

        var IDS;
        function highlightRows() {
            var highlightRows = X(highlightRowsClientID);

            grid.el.select('.x-grid3-row table.highlight').removeClass('highlight');

            Ext.each(highlightRows.getValue().split(','), function (item, index) {
                if (item !== '') {
                    ArrayTemp = item.split("-");

                    var row = grid.getView().getRow(parseInt(ArrayTemp[0], 10));
                    var styleColer = "ItemTxt";
                    switch (ArrayTemp[1]) {

                        case 1:
                            styleColer = "highlightBlue";
                            break;
                        case 2:
                            styleColer = "highlightGreen";
                            break;
                        case 3:
                            styleColer = "highlightOrange";
                            break;
                        case 4:
                            styleColer = "highlightYellow";
                            break;
                        case 5:
                            styleColer = "highlightRed";
                            break;
                        default: break;

                    }
                    var resultNode = Ext.get(row).query("td:nth(2) input:first-child");

                    Ext.get(resultNode).addClass(styleColer);

                }
            });

        }

        // 页面第一个加载完毕后执行的函数
        function onReady() {
            IDS = {};
            rightClick = new Ext.menu.Menu({
                id: 'rightClickCont',
                items: [
        {
            cls: "x-btn-text-icon",
            icon: "./res.axd?icon=Page",
            handler: function () {

                // alert(currRecord.get('ID'));
                btnclickme(currRecord.get('ID'), '3')
            },
            text: '基站详情'
        }, {
            cls: "x-btn-text-icon",
            icon: "./res.axd?icon=Page",
            handler: function () {
                btnclickme(currRecord.get('ID'), '1')
            },
            text: '市电来电'
        }, {
            cls: "x-btn-text-icon",
            icon: "./res.axd?icon=Page",
            handler: function () {
                btnclickme(currRecord.get('ID'), '2')
            },
            text: '信息错误'
        }, {
            cls: "x-btn-text-icon",
            icon: "./res.axd?icon=Page",
            handler: function () {
                btnclickme(currRecord.get('ID'), '4')
            },
            text: '停发电时刻表'
        }, {
            cls: "x-btn-text-icon",
            icon: "./res.axd?icon=Page",
            handler: function () {
                btnclickme(currRecord.get('ID'), '6')
            },
            text: '实时蓄电池曲线'
        }
    ]
            });

            grid = X(gridClientID);

            grid.addListener('viewready', function () {
                highlightRows();
            });

            grid.addListener('rowcontextmenu', rightClickFn);

            //            //如果要做隐藏列,则必须使用Cookies记录,然后myGrid.getColumnModel().setHidden(i,true);或者grid.columns[i].hide()/show()。第3 使用表格头部右键点击
            //            Ext.getCmp(gridClientID).on('headerclick', function (grid, columnIndex, e) {
            //                e.preventDefault();
            //                Ext.getCmp(gridClientID).getColumnModel().setHidden(columnIndex, true);
            //                //grid.getColumnModel().setColumnHeader(columnIndex, '<span style="color:red">改变颜色</span>');
            //            });



        }

        function resetvar() {
            intSumAdd = 0;
            intSumDelete = 0;
            intSumUpdate = 0;
            intPrevAdd = 0;
            intPrevDelete = 0;
            intPrevUpdate = 0;

            try {
                //id取得法
                minid = (Ext.getCmp(EXTMinId).getValue()) * 1;
                maxid = (Ext.getCmp(EXTMaxId).getValue()) * 1;
                curpagelenth = (Ext.getCmp(EXTCurpagelenth).getValue()) * 1;

            } catch (e) {
                //e.message
                //e.description
                //e.number
                //throw new erroe();
            }

        }

        var _timerQueryRealStop = setInterval("QueryRealStop()", 5000); //每隔5检查一次
        function QueryRealStop() {
            clearInterval(_timerQueryRealStop);
            Keepline();
        }


        function RequestArray() {
            this.params = new Object();
            this.length = 2;
            //            this.params["UserName"] = Global.Action;
            //            this.params["RoleId"] = Global.MyInfo.UserId;
            this.params["Type"] = 0;
            // this.params["Column"] = "";

            this.params["LSCCode"] = X(UserLscCode).getValue();
            // this.params["OtherParamter"] ="";
        }
        RequestArray.prototype.Add = function (key, value) {
            this.params[key] = value;
            this.length++;
        }
        RequestArray.prototype.ToJson = function () {
            var tempstr = "{";
            for (var key in this.params) {
                tempstr += key + ":\"" + this.params[key] + "\",";
            }
            tempstr = tempstr.substring(0, tempstr.length - 1);
            tempstr += "}";
            return (new Function("return " + tempstr))();
        }


        //循环post
        function Keepline() {
            var array = new RequestArray();
            $.post("comet_broadcast.asyn", array.ToJson(),

  function (data) {
      var loadrowdata = false;
      if (parent.parent.getActiveTabUrl().indexOf("RealStoping") > -1) {
          loadrowdata = true;
      }
      if (loadrowdata) {
          if (data.ResultStatus == 1 && data.ResultData != null) {
              //数值与时间 累加更新
              var fdtime = new Date();
              var txtcurdatetimeflash = fdtime.getFullYear() + "-" + (fdtime.getMonth() + 1) + "-" + fdtime.getDate() + ":" + fdtime.getHours() + ":" + fdtime.getMinutes() + ":" + fdtime.getSeconds();

              Ext.getCmp(PrevTimeTag).setValue(txtcurdatetimeflash);

              X.ajaxLoadingMask.show(); //遮罩

              if (data.ResultData.DeleteDT != null && data.ResultData.DeleteDT.length > 0) {
                  //得到当前页面是否被显示
                  if (loadrowdata) {
                      DeleteData(data.ResultData.DeleteDT); //删除  
                  }
                  intPrevDelete = (data.ResultData.DeleteDT.length) * 1;
              }

              if (data.ResultData.AddDT != null && data.ResultData.AddDT.length > 0) {
                  if (loadrowdata) {
                      AddData(data.ResultData.AddDT); //新增
                  }
                  intPrevAdd = (data.ResultData.AddDT.length) * 1;
              }

              if (data.ResultData.UpdateDT != null && data.ResultData.UpdateDT.length > 0) {
                  if (loadrowdata) {
                      UpdateData(data.ResultData.UpdateDT); //替换
                  }
                  intPrevUpdate = (data.ResultData.UpdateDT.length) * 1;
              }

              X.ajaxLoadingMask.hide(); //遮罩
              try {
                  //数值与时间 累加更新
                  intSumAdd = intSumAdd + intPrevAdd;
                  intSumDelete = intSumDelete + intPrevDelete;
                  intSumUpdate = intSumUpdate + intPrevUpdate;


                  Ext.getCmp(TxtPrevAdd).setValue(intPrevAdd)
                  Ext.getCmp(TxtPrevDelete).setValue(intPrevDelete)
                  Ext.getCmp(TxtPrevUpdate).setValue(intPrevUpdate)

                  Ext.getCmp(TxtSumAdd).setValue(intSumAdd)
                  Ext.getCmp(TxtSumDelete).setValue(intSumDelete)
                  Ext.getCmp(TxtSumUpdate).setValue(intSumUpdate)


              }
              catch (e) {
                  //e.message
                  //e.description
                  //e.number
                  //throw new erroe();
              }
          }
      }
      Keepline();
  }, "json");

        }

        function DeleteData(idobj) {
            try {

                for (var i = 0; i < idobj.length; i++) {
                    //查找 record 中 id 等于指定的, 进行删除操作
                    grid.getStore().each(function (record, index) {
                        var k = record.get('ID');
                        if (k == idobj[i].ID) {

                            grid.getStore().remove(record);
                            curpagelenth = curpagelenth - 1;
                            if (minid == idobj[i].ID) {
                                //得到当前第一行的id
                                minid = grid.getStore().getAt(0).get('ID');
                            } else {
                                if (maxid == idobj[i].ID) {
                                    //得到当前最后一行的id
                                    maxid = grid.getStore().getAt(curpagelenth - 1).get('ID');
                                }
                            }
                        }

                    });
                }
            } catch (e) {
                //e.message
                //e.description
                //e.number
                //throw new erroe();
            }
        }

        function AddData(idobj) {
            try {


                var ktest = Ext.getCmp(gridClientID).getColumnModel();
                var currRecordtest = grid.getStore();
                // var currRecordtest1 = grid.getStore().getAt(1);
                var namearray = new Array();

                Ext.each(Ext.getCmp(gridClientID).getColumnModel().columns, function () {
                    namearray.push({ name: this.dataIndex });
                    //this.header
                });

                var TopicRecord = Ext.data.Record.create(namearray);

                //循环添加
                //添加的位置不同, 首先,循环比较ID,找到每一个的插入索引位置,插入,并且修改长度与最大最小值

                for (var i = 0; i < idobj.length; i++) {
                    try {
                        if (curpagelenth < pagesizze) {
                            var key = {}; //map式添加
                            //var key1 = {};

                            var tagone = true;
                            for (var j = 0; j < namearray.length; j++) {

                                var tempkey = namearray[j].name;
                                if (tempkey.indexOf("_DGrid_") >= 0) {
                                    if (tagone) {
                                        tagone = false;
                                        //着色
                                        key[tempkey] = "<input name=\"MainRegionPanel$RegionRight$DGrid$ctl24$ctl00\" class=\"ItemTxt\" type=\"text\">";

                                    } else {
                                        tagone = true;
                                        key[tempkey] = "<img class=\".SuImg\" src=" + idobj[i].SuTypeUrl + " style=\"border-width:0px;\"><span>" + idobj[i].SuTypeTxt + "</span>";

                                    }
                                    continue;
                                }

                                key[tempkey] = idobj[i][tempkey]

                            }

                            var jieshu = 0; var previndex = -1; var da = 0; //0无,1大 2小
                            grid.getStore().each(function (record, index) {
                                var k = record.get('ID');
                                //大于 不结束 小于时结束。 从上向下做each
                                if (k < idobj[i].ID) {
                                    jieshu = 1;
                                    previndex = index;
                                    da = 2;
                                    return false;
                                } else {
                                    if (index == curpagelenth - 1 && k > idobj[i].ID)//k = idobj[i].ID  不计算
                                    {
                                        jieshu = 1;
                                        previndex = index;
                                        da = 1;
                                        return false;

                                    }

                                }

                            });

                            //INDEX=0  应该插入第一个,修改min值,长度值+1
                            if (da == 2) {
                                if (previndex == 0) {
                                    curpagelenth = curpagelenth + 1;
                                    minid = idobj[i].ID;
                                    var hahachacha = new TopicRecord(key);
                                    //  currRecordtest.add(hahachacha);
                                    currRecordtest.insert(previndex, hahachacha);
                                    Ext.get(grid.getView().getRow(previndex)).addClass("highlightRed");

                                }
                                else//中间
                                {
                                    curpagelenth = curpagelenth + 1;
                                    var hahachacha = new TopicRecord(key);
                                    if (da == 1) {
                                        currRecordtest.insert(previndex + 1, hahachacha);
                                        Ext.get(grid.getView().getRow(previndex + 1)).addClass("highlightRed");
                                    }
                                    if (da == 2) {
                                        currRecordtest.insert(previndex - 1, hahachacha);
                                        Ext.get(grid.getView().getRow(previndex - 1)).addClass("highlightRed");
                                    }
                                }
                            } else {
                                //INDEX==长度-1 应该插入最后一个,长度值+1
                                if (da == 1) {
                                    curpagelenth = curpagelenth + 1;
                                    maxid = idobj[i].ID;
                                    var hahachacha = new TopicRecord(key);
                                    currRecordtest.add(hahachacha);
                                    Ext.get(grid.getView().getRow(curpagelenth-1)).addClass("highlightRed");

                                }

                            }
                            //                            var jieshu = 0; var previndex = -1; var da = 0; //0无,1大 2小
                            //                            grid.getStore().each(function (record, index) {
                            //                                var k = record.get('ID');
                            //                                if (k > idobj[i].ID && jieshu == 0) {

                            //                                    jieshu = 1;
                            //                                    previndex = index;
                            //                                    da = 1;
                            //                                    return false;
                            //                                }
                            //                                if (k < idobj[i].ID && jieshu == 0) {

                            //                                    jieshu = 1;
                            //                                    previndex = index;
                            //                                    da = 2;
                            //                                    return false;
                            //                                }

                            //                            });

                            //                            //INDEX=0  应该插入第一个,修改min值,长度值+1
                            //                            if (previndex == 0 && da == 2) {
                            //                                curpagelenth = curpagelenth + 1;
                            //                                minid = idobj[i].ID;
                            //                                var hahachacha = new TopicRecord(key);
                            //                                //  currRecordtest.add(hahachacha);
                            //                                currRecordtest.insert(previndex, hahachacha);

                            //                            } else {
                            //                                //INDEX==长度-1 应该插入最后一个,长度值+1
                            //                                if (previndex == (curpagelenth - 1) && da == 1) {
                            //                                    curpagelenth = curpagelenth + 1;
                            //                                    maxid = idobj[i].ID;
                            //                                    var hahachacha = new TopicRecord(key);
                            //                                    currRecordtest.add(hahachacha);

                            //                                }
                            //                                else//中间
                            //                                {
                            //                                    curpagelenth = curpagelenth + 1;
                            //                                    var hahachacha = new TopicRecord(key);
                            //                                    if (da == 1) {
                            //                                        currRecordtest.insert(previndex + 1, hahachacha);
                            //                                    }
                            //                                    if (da == 2) {
                            //                                        currRecordtest.insert(previndex - 1, hahachacha);
                            //                                    }
                            //                                }
                            //                            }
                        }

                    } catch (e) { }

                }
            } catch (e) {
                //e.message
                //e.description
                //e.number
                //throw new erroe();
            }

        }


        function UpdateData(idobj) {
            try {

                var ktest = Ext.getCmp(gridClientID).getColumnModel();

                var currRecordtest = grid.getStore();
                var currRecordtest1 = grid.getStore().getAt(1);

                var namearray = new Array();

                Ext.each(Ext.getCmp(gridClientID).getColumnModel().columns, function () {
                    namearray.push({ name: this.dataIndex });
                    //this.header
                });

                var TopicRecord = Ext.data.Record.create(namearray);

                //循环添加
                for (var i = 0; i < idobj.length; i++) {
                    try {
                        var key = {}; //map式添加
                        var key1 = {};

                        var tagone = true;
                        for (var j = 0; j < namearray.length; j++) {

                            var tempkey = namearray[j].name;
                            if (tempkey.indexOf("_DGrid_") >= 0) {
                                if (tagone) {
                                    tagone = false;
                                    //着色
                                    key[tempkey] = "<input name=\"MainRegionPanel$RegionRight$DGrid$ctl24$ctl00\" class=\"ItemTxt\" type=\"text\">";

                                } else {
                                    tagone = true;
                                    key[tempkey] = "<img class=\".SuImg\" src=" + idobj[i].SuTypeUrl + " style=\"border-width:0px;\"><span>" + idobj[i].SuTypeTxt + "</span>";
                                    // key[tempkey] = "1";
                                }
                                continue;
                            }
                            key[tempkey] = idobj[i][tempkey];

                        }
                        var hahachacha = new TopicRecord(key);

                        var cur = -1;
                        grid.getStore().each(function (record, index) {
                            var k = record.get('ID');
                            if (k == idobj[i].ID) {
                                record = hahachacha;
                                cur = index;
                                grid.getStore().remove(this);
                            }

                        });
                        if (cur !== -1) {
                            //currRecordtest.first().addClass('highlight2');
                            currRecordtest.insert(cur, hahachacha);
                            Ext.get(grid.getView().getRow(cur)).addClass("highlightYellow");
                        }

                    } catch (e) { }
                }
            } catch (e) {
                //e.message
                //e.description
                //e.number
                //throw new erroe();
            }

        }
     
    </script>
    <ext:PageManager ID="PageManager1" runat="server" AutoSizePanelID="MainRegionPanel"
        EnableAjaxLoading="true" AjaxLoadingType="Mask" />
    <ext:RegionPanel ID="MainRegionPanel" runat="server" ShowBorder="false">
        <Regions>
            <ext:Region ID="RegionRight" runat="server" Position="Center" ShowHeader="false"
                Layout="Fit" Title="Center Region">
                <Toolbars>
                    <ext:Toolbar ID="Toolbar1" Position="Top" runat="server" Height="60px">
                        <Items>
                            <ext:Panel ID="columnPanel" runat="server" Layout="Column" Width="1200px" EnableBackgroundColor="true"
                                ShowHeader="false" ShowBorder="false" AutoScroll="false" ColumnWidth="600 200">
                                <Items>
                                    <ext:Form ID="Form2" runat="server" BodyPadding="5px" EnableBackgroundColor="true"
                                        Title="Form" Width="750px" ShowHeader="false" AutoScroll="false">
                                        <Rows>
                                            <ext:FormRow ID="FormRow1" runat="server" ColumnWidths="140 110  75 110 75 110 75">
                                                <Items>
                                                    <ext:Label ID="SumTimeTag" runat="server" Label="" Text="" Width="140px" EnableAjax="False"
                                                        EnableAjaxLoading="False" ShowLabel="False">
                                                    </ext:Label>
                                                    <ext:Label ID="Label3" runat="server" Label="" Text="停电基站(累计):" Width="60px" EnableAjax="False"
                                                        EnableAjaxLoading="False" ShowLabel="False">
                                                    </ext:Label>
                                                    <ext:TextBox ID="TxtSumAdd" runat="server" Readonly="true" Text="" CssClass="ItemTxt"
                                                        ShowLabel="False" Width="70px">
                                                    </ext:TextBox>
                                                    <ext:Label ID="Label1" runat="server" Label="" Text="停电结束基站(累计):" Width="60px" EnableAjax="False"
                                                        EnableAjaxLoading="False" ShowLabel="False">
                                                    </ext:Label>
                                                    <ext:TextBox ID="TxtSumDelete" runat="server" Readonly="true" Text="" CssClass="lbTxt"
                                                        ShowLabel="False" Width="70px">
                                                    </ext:TextBox>
                                                    <ext:Label ID="Label2" runat="server" Label="" Text="基站状态变化(累计):" Width="60px" EnableAjax="False"
                                                        EnableAjaxLoading="False" ShowLabel="False">
                                                    </ext:Label>
                                                    <ext:TextBox ID="TxtSumUpdate" runat="server" Readonly="true" Text="" CssClass="lbTxt"
                                                        ShowLabel="False" Width="70px">
                                                    </ext:TextBox>
                                                </Items>
                                            </ext:FormRow>
                                            <ext:FormRow ID="FormRow3" runat="server" ColumnWidths="140 110  75 110 75 110 75">
                                                <Items>
                                                    <ext:Label ID="PrevTimeTag" runat="server" Label="" Text="" Width="140px" EnableAjax="False"
                                                        EnableAjaxLoading="False" ShowLabel="False">
                                                    </ext:Label>
                                                    <ext:Label ID="Label7" runat="server" Label="" Text="停电基站(最新):" Width="60px" EnableAjax="False"
                                                        EnableAjaxLoading="False" ShowLabel="False">
                                                    </ext:Label>
                                                    <ext:TextBox ID="TxtPrevAdd" runat="server" Readonly="true" Text="" CssClass="ItemTxt"
                                                        ShowLabel="False" Width="70px">
                                                    </ext:TextBox>
                                                    <ext:Label ID="Label8" runat="server" Label="" Text="停电结束基站(最新):" Width="60px" EnableAjax="False"
                                                        EnableAjaxLoading="False" ShowLabel="False">
                                                    </ext:Label>
                                                    <ext:TextBox ID="TxtPrevDelete" runat="server" Readonly="true" Text="" CssClass="lbTxt"
                                                        ShowLabel="False" Width="70px">
                                                    </ext:TextBox>
                                                    <ext:Label ID="Label9" runat="server" Label="" Text="基站状态变化(最新):" Width="60px" EnableAjax="False"
                                                        EnableAjaxLoading="False" ShowLabel="False">
                                                    </ext:Label>
                                                    <ext:TextBox ID="TxtPrevUpdate" runat="server" Readonly="true" Text="" CssClass="lbTxt"
                                                        ShowLabel="False" Width="70px">
                                                    </ext:TextBox>
                                                </Items>
                                            </ext:FormRow>
                                        </Rows>
                                    </ext:Form>
                                    <ext:Button ID="btnQuery" IconUrl="~/image/search.png" Text="刷新" EnablePostBack="true"
                                        OnClick="BtnSearch_Click" runat="server">
                                    </ext:Button>
                                </Items>
                            </ext:Panel>
                        </Items>
                    </ext:Toolbar>
                </Toolbars>
                <Items>
                    <ext:Grid ID="DGrid" ShowBorder="true" ShowHeader="true" Title="停发电基站列表" RowHeight="60px"
                        runat="server" AutoScroll="true" AllowPaging="true" AutoHeight="true" AutoWidth="true"
                        PageSize="50" OnPageIndexChange="DGrid_PageIndexChange" IsDatabasePaging="true"
                        EnableRowNumber="true" EnableAlternateRowColor="true" EnableMouseOverColor="true"
                        EnableRowDoubleClick="true">
                        <Columns>
                            <%-- <ext:BoundField Width="90px" HeaderText="监控中心" ColumnID="LSCName" DataField="LSCName" />
                            <ext:BoundField Width="80px" HeaderText="所属区域" ColumnID="AreaName" DataField="AreaName" />
                            <ext:BoundField Width="170px" HeaderText="基站名称" ColumnID="SuName" DataField="SuName" />
                            <ext:TemplateField Width="70px" HeaderText="基站类型" ColumnID="SuTypeTxt">
                                <ItemTemplate>
                                    <img src='<%# DataBinder.Eval(Container, "DataItem.SuTypeUrl") %>' style="height: 16px;
                                        width: 16px" />
                                    <asp:TextBox ID="SuTypeTxt" runat="server" CssClass="ItemTxt" ReadOnly="True" Text='<%# DataBinder.Eval(Container, "DataItem.SuTypeTxt") %>' />
                                </ItemTemplate>
                            </ext:TemplateField>
                            <ext:BoundField Width="80px" HeaderText="停发电状态" ColumnID="StatusTypeTxt" DataField="StatusTypeTxt" />
                            <ext:BoundField Width="90px" HeaderText="基站当前状态" ColumnID="StationStatusTxt" DataField="StationStatusTxt" />
                            <ext:BoundField Width="140px" HeaderText="停电" ColumnID="StopPowerTime" DataField="StopPowerTime" />
                            <ext:BoundField Width="140px" HeaderText="停电时长(分钟)" ColumnID="StopDurTxt" DataField="StopDurTxt" />
                            <ext:BoundField Width="140px" HeaderText="发电" ColumnID="BeginGenerator" DataField="BeginGenerator" />
                            <ext:BoundField Width="140px" HeaderText="发电时长(分钟)" ColumnID="GeneratorDurTxt" DataField="GeneratorDurTxt" />
                            <ext:BoundField Width="90px" HeaderText="蓄电池状态" ColumnID="BatteryStatusTxt" DataField="BatteryStatusTxt" />
                            <ext:BoundField Width="90px" HeaderText="是否开门" ColumnID="DoorcardTimeTxt" DataField="DoorcardTimeTxt" />
                            <ext:BoundField Width="80px" HeaderText="蓄电池当前电压" ColumnID="BatteryVVal" DataField="BatteryVVal" />
                            <ext:BoundField Width="140px" HeaderText="剩余供电时长(分钟)" ColumnID="RemainTime" DataField="RemainTime" />
                            <ext:BoundField Width="90px" HeaderText="油机状态" ColumnID="OilStatusTxt" DataField="OilStatusTxt" />
                            <ext:BoundField Width="140px" HeaderText="油机停止时长(分钟)" ColumnID="OillastStopDurTxt"
                                DataField="OillastStopDurTxt" />
                            <ext:BoundField Width="50px" HeaderText="油机启动次数" ColumnID="OilBeginCount" DataField="OilBeginCount" />
                            <ext:BoundField Width="140px" HeaderText="油机最后一次启动时刻" ColumnID="OillastBeginTime"
                                DataField="OillastBeginTime" />
                            <ext:BoundField Width="140px" HeaderText="油机最后一次停止时刻" ColumnID="OillastStopTime"
                                DataField="OillastStopTime" />
                            <ext:BoundField Width="80px" HeaderText="阀值(V)" ColumnID="BatteryVLower" DataField="BatteryVLower" />
                            <ext:TemplateField Width="200px" HeaderText="结束停电" ColumnID="ID">
                                <ItemTemplate>
                                    <asp:TextBox ID="ID" runat="server" CssClass="hid" ReadOnly="True" Text='<%# DataBinder.Eval(Container, "DataItem.ID") %>' />
                                    <a class="btn btn-success" data-toggle="modal" onclick="javascript:btnclickme(this, '1');">
                                        市电来电</a> <a class="btn btn-danger" data-toggle="modal" onclick="javascript:btnclickme(this, '2');">
                                            信息错误</a>
                                </ItemTemplate>
                            </ext:TemplateField>--%>
                        </Columns>
                    </ext:Grid>
                    <ext:HiddenField ID="highlightRows" runat="server">
                    </ext:HiddenField>
                </Items>
            </ext:Region>
        </Regions>
    </ext:RegionPanel>
    <ext:Window ID="TimeWindow" IconUrl="~/images/(46,46).png" runat="server" Popup="false"
        EnableMaximize="true" IsModal="true" Target="Top" EnableResize="false" Title="停发电时刻表 "
        AutoScroll="true" EnableConfirmOnClose="true" EnableIFrame="true" IFrameUrl="about:blank"
        Width="850px" Height="600px">
    </ext:Window>
    <ext:Window ID="ChildWindow" IconUrl="~/images/(46,46).png" runat="server" Popup="false"
        EnableMaximize="true" IsModal="true" Target="Top" EnableResize="false" Title="基站停发电详情"
        AutoScroll="true" EnableConfirmOnClose="true" EnableIFrame="true" IFrameUrl="about:blank"
        Width="850px" Height="600px">
    </ext:Window>
    <ext:Window ID="BatteryWindow" runat="server" Popup="false" EnableMaximize="true"
        IsModal="true" Target="Top" EnableResize="false" Title="蓄电池充放电曲线图" AutoScroll="true"
        EnableConfirmOnClose="true" EnableIFrame="true" IFrameUrl="about:blank" Width="850px"
        Height="600px">
    </ext:Window>
    <ext:Window ID="ErrorWindow" IconUrl="~/images/(46,46).png" runat="server" Popup="false"
        EnableMaximize="true" IsModal="true" Target="Top" EnableResize="false" Title="信息错误"
        AutoScroll="true" EnableConfirmOnClose="true" EnableIFrame="true" IFrameUrl="about:blank"
        Width="618px" Height="204px">
    </ext:Window>
    <ext:HiddenField ID="UserLscCode" runat="server" Text="">
    </ext:HiddenField>
    <ext:HiddenField ID="EXTMinId" runat="server" Text="">
    </ext:HiddenField>
    <ext:HiddenField ID="EXTMaxId" runat="server" Text="">
    </ext:HiddenField>
    <ext:HiddenField ID="EXTCurpagelenth" runat="server" Text="">
    </ext:HiddenField>
    <input id="btnLoadDataButton" type="button" runat="server" style="width: 0px; height: 0px;
        display: none;" onclick=" resetvar();" />
    </form>
</body>
</html>



二:CDC语句

USE [DMS]
GO
/****** Object:  StoredProcedure [dbo].[RealCDC]    Script Date: 08/06/2014 15:23:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO








---监控ConfirmBK_StopGenerat表的变化
ALTER PROCEDURE [dbo].[RealCDC]
    @BeginTime datetime,--开始时间
    @BeginLSN varbinary(10),--开始LSN边界
    @ToLSN varbinary(10) output--返回值
AS
BEGIN

--结束 LSN边界
select @ToLSN = sys.fn_cdc_map_time_to_lsn
('largest less than or equal',getdate())


--首次
 if ISNULL(@BeginTime,'')<>''
   begin
    --最小开始LSN边界   通过@BeginTime算出赋值给@BeginLSN
   --declare @fromLSN varbinary(10)=sys.fn_cdc_map_time_to_lsn
   -- ('smallest greater than or equal',@BeginTime)
   
     select  @BeginLSN=sys.fn_cdc_map_time_to_lsn('smallest greater than or equal',@BeginTime)   
    end
    
        else
    begin
    
     select  @BeginLSN=sys.fn_cdc_increment_lsn(@BeginLSN)   
    end
    
  --返回三个select, 删除,新增,修改
  
  --返回一个输出变量@ToLSN
  
  --cdc对应
--when 1 then 'DELETE'
--when 2 then 'INSERT'
--when 3 then 'Before Update'
--when 4 then 'After Update'
 
  
  --最终状态--净变更
  

--删除---对应操作为更新- 发电结束(从页面删除)
select 
--  __$operation as operation
--,
[ID]  ,[LSCCode]
 
from cdc.fn_cdc_get_net_changes_dbo_ConfirmBK_StopGenerat(@BeginLSN,@ToLSN,'all with mask') as K where

__$operation=4 and  StatusType=3 
and sys.fn_cdc_is_bit_set(  sys.fn_cdc_get_column_ordinal('dbo_ConfirmBK_StopGenerat','StatusType')
,K.__$update_mask)=1
order by ID asc


----------不要用*代替列名,因为是CDC,不是表

---新增

select 
--  __$operation as operation
--,
 [ID]
      ,[LSCCode]
      ,[Sucode]
      ,[AreaID]
      ,[SuType]
      ,[AlarmId]
      ,[AlarmNo]
      ,[StatusType]
      ,[StationStatus]
      ,[OneDayTimes]
      ,[StopPowerTime]
      ,[Under47VTime]
      ,[RemainTime]
      ,[IsBlackouts]
      ,[PrevEndTime]
      ,[DispachNum]
      ,[DoorcardTime]
      ,[IsGenerator]
      ,[BeginGenerator]
      ,[RecoveryTime]
      ,[EndOfJobStyle]
      ,[EndOfJobTime]
      ,[DischargeTime]
      ,[BatteryVLower]
      ,[InType]
      ,[InSubType]
      ,[StopDur]
      ,[GeneratorDur]
      ,[RedundancyDur]
      ,[CreateStyle]
      ,[LSCName]
      ,[SuName]
      ,[AreaName]
      ,[ParentID]
      ,[SuSubType]
      ,[SuLevel]
      ,[SuAhValue]
      ,[BatteryContain]
      ,[StationCommStatus]
      ,[BatteryVVal]
      ,[BatteryStatus]
      ,[OilStatus]
      ,[OillastBeginTime]
      ,[OillastStopTime]
      ,[OillastStopReason]
      ,[CurStopDur]
      ,[CurGeneratorDur]
      ,[SumOilGeneratorDur]
      ,[OilBeginCount]
      ,[LastSMPSOutAAvg]
      ,[Flashing]
      ,[IsFake]
      ,[IsTimely]
      ,[IsPremature]
      ,[IsSuperShort]
      ,[IsMidWayReturn]
      ,[IsTakeback]
      ,[IsOilLongStop]
      ,[BatteryBad]
      ,[BatteryOneBad]
      ,[BatteryUnderLine]
      ,[ReplaceOil]
      ,[Timestamp]
      ,[CollectTime]
      ,[CreateTime]
      ,[UpdateTime]
      ,[Reserve]
      ,[Reserve1]
      ,[Reserve2]
      ,[Reserve3],
       CASE   StatusType 
      WHEN 1 THEN '停电中' 
      WHEN 2 THEN '发电中' 
      WHEN 3 THEN '来电--结束发电' 
      ELSE '' END 
      as 
      StatusTypeTxt,       CASE   StationStatus 
      WHEN 1 THEN '停电' 
      WHEN 2 THEN '油机发电' 
      WHEN 3 THEN '退服' 
      WHEN 4 THEN '来电' 
      ELSE '' END 
      as 
      StationStatusTxt,  CASE   IsBlackouts 
      WHEN 0 THEN '否' 
      WHEN 1 THEN '大面积停电' 
      ELSE '' END 
      as 
      IsBlackoutsTxt,   CASE isnull(DispachNum,'') 
      WHEN '' THEN '无' 
      ELSE '已派单' END 
      as 
      DispachNumTxt,  CASE isnull(DoorcardTime,'') 
      WHEN '' THEN '无' 
      ELSE '已开门' END 
      as 
      DoorcardTimeTxt,       CASE   IsGenerator 
      WHEN 0 THEN '否' 
      WHEN 1 THEN '已发电' 
      ELSE '' END 
      as 
      IsGeneratorTxt,  CASE   ReplaceOil  
      WHEN 0 THEN '否' 
      WHEN 1 THEN '是' 
      ELSE '' END 
      as 
      ReplaceOilTxt,    LTRIM(floor(
      (CASE WHEN  ISNULL(RecoveryTime,-1)<>-1
      THEN  datediff(minute,RecoveryTime,GETDATE())+ ISNULL(StopDur,0)  ELSE
      datediff(minute,StopPowerTime,GETDATE()) end)/60))  +':'+
      LTRIM( (CASE WHEN  ISNULL(RecoveryTime,-1)<>-1
      THEN  datediff(minute,RecoveryTime,GETDATE())+ISNULL(StopDur,0)  ELSE
      datediff(minute,StopPowerTime,GETDATE()) end)%60)
      as    StopDurTxt,
      
      CASE WHEN  IsGenerator=1
      THEN
      CASE WHEN  StationStatus=2 
      then 
      LTRIM(floor(
      ( CASE WHEN  ISNULL(RecoveryTime,-1)<>-1
      THEN  datediff(minute,OillastBeginTime,GETDATE())+ISNULL(GeneratorDur,0)
      ELSE    datediff(minute,BeginGenerator,GETDATE()) end) /60))
      +':'+
      LTRIM( ( CASE WHEN  ISNULL(RecoveryTime,-1)<>-1   THEN
      datediff(minute,OillastBeginTime,GETDATE())+ISNULL(GeneratorDur,0)    ELSE
      datediff(minute,BeginGenerator,GETDATE())   end )%60) 
      ELSE 
      LTRIM(floor( 
      ( ISNULL(GeneratorDur,0) /60))) 
      +':'+ 
      LTRIM( floor(( ISNULL(GeneratorDur,0)%60))) 
      end 
      ELSE '0' end
      as
      GeneratorDurTxt,  LTRIM(floor( StopDur/60))  +':'+  LTRIM(StopDur %60) as    TotalStopDurTxt,
      LTRIM(floor( GeneratorDur/60))  +':'+  LTRIM(GeneratorDur %60) as    TotalGeneratorDurTxt,
        LTRIM(floor( DischargeTime/60))  +':'+  LTRIM(DischargeTime %60) as    DischargeTimeTxt,
         LTRIM(floor(RemainTime/60))  +':'+  LTRIM(RemainTime %60) as RemainTimeTxt,
            CASE CreateStyle 
      WHEN 1 THEN '系统自动判断停电' 
      WHEN 2 THEN '人工判断停电' 
      ELSE '' END 
      as 
      CreateStyleTxt,     CASE EndOfJobStyle 
      WHEN 1 THEN '自动来电' 
      WHEN 2 THEN '手动来电' 
      WHEN 3 THEN '油机最后一次停止超过1小时(自动结束)' 
      WHEN 4 THEN '错误' 
      ELSE '' END 
      as 
      EndOfJobStyleTxt,   CASE   BatteryOneBad 
      WHEN 0 THEN '否' 
      WHEN 1 THEN '是' 
      ELSE '' END 
      as 
      BatteryOneBadTxt,  CASE   BatteryBad 
      WHEN 0 THEN '否' 
      WHEN 1 THEN '是' 
      ELSE '' END 
      as 
      BatteryBadTxt,   CASE   BatteryUnderLine 
      WHEN 0 THEN '否' 
      WHEN 1 THEN '是' 
      ELSE '' END 
      as 
      BatteryUnderLineTxt,     CASE   IsTakeback 
      WHEN 0 THEN '否' 
      WHEN 1 THEN '曾退服' 
      ELSE '' END 
      as 
      IsTakebackTxt,    CASE StationCommStatus 

      WHEN 1 THEN '正常' 
      WHEN 2 THEN '异常' 
      ELSE '' END 
      as 
      StationCommStatusTxt,   CASE BatteryStatus
      WHEN 1 THEN '浮充'
      WHEN 2 THEN '停电'
      WHEN 3 THEN '充电'
      WHEN 4 THEN '放电'
      ELSE '未监控' END
      as
      BatteryStatusTxt,     CASE OilStatus

      WHEN 1 THEN '油机发电'
      WHEN 2 THEN '油机停止'
      WHEN 3 THEN '未监控'

      ELSE '' END
      as
      OilStatusTxt, CASE  Flashing
      WHEN 0 THEN '否'
      WHEN 1 THEN '闪断'
      ELSE '' END
      as
      FlashingTxt,CASE  IsFake
      WHEN 0 THEN '否'
      WHEN 1 THEN '假发电'
      ELSE '' END
      as
      IsFakeTxt, CASE  IsTimely
      WHEN 0 THEN '否'
      WHEN 1 THEN '发电及时'
      ELSE '' END
      as
      IsTimelyTxt, CASE  IsPremature
      WHEN 0 THEN '否'
      WHEN 1 THEN '过早发电'
      ELSE '' END
      as
      IsPrematureTxt,CASE  IsSuperShort
      WHEN 0 THEN '否'
      WHEN 1 THEN '超短发电'
      ELSE '' END
      as
      IsSuperShortTxt,  CASE  IsMidWayReturn
      WHEN 0 THEN '否'
      WHEN 1 THEN '中途返回'
      ELSE '' END
      as
      IsMidWayReturnTxt, CASE  IsOilLongStop
      WHEN 0 THEN '否'
      WHEN 1 THEN '油机超长停止'
      ELSE '' END
      as
      IsOilLongStopTxt,  CASE WHEN ISNULL(OillastBeginTime,-1)<>-1 and ISNULL(OillastStopTime,-1)<>-1  AND (OillastBeginTime<OillastStopTime)
      THEN
      datediff(minute,OillastBeginTime,OillastStopTime)
      else
      0
      END
      as
      OillastStopDurTxt,  CASE SuType
      WHEN 0 THEN '机房'
      WHEN 1 THEN '节点'
      WHEN 2 THEN '基站'
      ELSE '' END
      as
      SuTypeTxt,   CASE SuType
      WHEN 0 THEN '/image/icons/16/home.png'
      WHEN 1 THEN '/image/icons/16/piechart.png'
      WHEN 2 THEN '/image/icons/16/search.png'
      ELSE '' END
      as SuTypeUrl,     CASE   InType
      WHEN 1 THEN '室内接入点接入'
      WHEN 2 THEN '室内非接入点接入'
      WHEN 3 THEN '室外'
      ELSE '' END
      as
      InTypeTxt,       CASE   SuLevel
      WHEN 1 THEN '重要基站51V'
      WHEN 2 THEN '一般基站47v'
      ELSE '' END
      as
      SuLevelTxt  ,
      LTRIM(floor( RedundancyDur/60))  +':'+  LTRIM(RedundancyDur %60) as    RedundancyDurTxt,
            CASE  OillastStopReason
      WHEN 0 THEN '市电恢复'
      WHEN 1 THEN '油机发电结束'
      ELSE '' END
      as
      OillastStopReasonTxt 
from cdc.fn_cdc_get_net_changes_dbo_ConfirmBK_StopGenerat(@BeginLSN,@ToLSN,'all with mask') where

__$operation=2 order by ID asc
  
 ---修改  ---对应操作为更新- 不包含发电结束

select 
--  __$operation as operation
--,
 [ID]
      ,[LSCCode]
      ,[Sucode]
      ,[AreaID]
      ,[SuType]
      ,[AlarmId]
      ,[AlarmNo]
      ,[StatusType]
      ,[StationStatus]
      ,[OneDayTimes]
      ,[StopPowerTime]
      ,[Under47VTime]
      ,[RemainTime]
      ,[IsBlackouts]
      ,[PrevEndTime]
      ,[DispachNum]
      ,[DoorcardTime]
      ,[IsGenerator]
      ,[BeginGenerator]
      ,[RecoveryTime]
      ,[EndOfJobStyle]
      ,[EndOfJobTime]
      ,[DischargeTime]
      ,[BatteryVLower]
      ,[InType]
      ,[InSubType]
      ,[StopDur]
      ,[GeneratorDur]
      ,[RedundancyDur]
      ,[CreateStyle]
      ,[LSCName]
      ,[SuName]
      ,[AreaName]
      ,[ParentID]
      ,[SuSubType]
      ,[SuLevel]
      ,[SuAhValue]
      ,[BatteryContain]
      ,[StationCommStatus]
      ,[BatteryVVal]
      ,[BatteryStatus]
      ,[OilStatus]
      ,[OillastBeginTime]
      ,[OillastStopTime]
      ,[OillastStopReason]
      ,[CurStopDur]
      ,[CurGeneratorDur]
      ,[SumOilGeneratorDur]
      ,[OilBeginCount]
      ,[LastSMPSOutAAvg]
      ,[Flashing]
      ,[IsFake]
      ,[IsTimely]
      ,[IsPremature]
      ,[IsSuperShort]
      ,[IsMidWayReturn]
      ,[IsTakeback]
      ,[IsOilLongStop]
      ,[BatteryBad]
      ,[BatteryOneBad]
      ,[BatteryUnderLine]
      ,[ReplaceOil]
      ,[Timestamp]
      ,[CollectTime]
      ,[CreateTime]
      ,[UpdateTime]
      ,[Reserve]
      ,[Reserve1]
      ,[Reserve2]
      ,[Reserve3]
      ,  CASE   StatusType 
      WHEN 1 THEN '停电中' 
      WHEN 2 THEN '发电中' 
      WHEN 3 THEN '来电--结束发电' 
      ELSE '' END 
      as 
      StatusTypeTxt,       CASE   StationStatus 
      WHEN 1 THEN '停电' 
      WHEN 2 THEN '油机发电' 
      WHEN 3 THEN '退服' 
      WHEN 4 THEN '来电' 
      ELSE '' END 
      as 
      StationStatusTxt,  CASE   IsBlackouts 
      WHEN 0 THEN '否' 
      WHEN 1 THEN '大面积停电' 
      ELSE '' END 
      as 
      IsBlackoutsTxt,   CASE isnull(DispachNum,'') 
      WHEN '' THEN '无' 
      ELSE '已派单' END 
      as 
      DispachNumTxt,  CASE isnull(DoorcardTime,'') 
      WHEN '' THEN '无' 
      ELSE '已开门' END 
      as 
      DoorcardTimeTxt,       CASE   IsGenerator 
      WHEN 0 THEN '否' 
      WHEN 1 THEN '已发电' 
      ELSE '' END 
      as 
      IsGeneratorTxt,  CASE   ReplaceOil  
      WHEN 0 THEN '否' 
      WHEN 1 THEN '是' 
      ELSE '' END 
      as 
      ReplaceOilTxt,    LTRIM(floor(
      (CASE WHEN  ISNULL(RecoveryTime,-1)<>-1
      THEN  datediff(minute,RecoveryTime,GETDATE())+ ISNULL(StopDur,0)  ELSE
      datediff(minute,StopPowerTime,GETDATE()) end)/60))  +':'+
      LTRIM( (CASE WHEN  ISNULL(RecoveryTime,-1)<>-1
      THEN  datediff(minute,RecoveryTime,GETDATE())+ISNULL(StopDur,0)  ELSE
      datediff(minute,StopPowerTime,GETDATE()) end)%60)
      as    StopDurTxt,
      
      CASE WHEN  IsGenerator=1
      THEN
      CASE WHEN  StationStatus=2 
      then 
      LTRIM(floor(
      ( CASE WHEN  ISNULL(RecoveryTime,-1)<>-1
      THEN  datediff(minute,OillastBeginTime,GETDATE())+ISNULL(GeneratorDur,0)
      ELSE    datediff(minute,BeginGenerator,GETDATE()) end) /60))
      +':'+
      LTRIM( ( CASE WHEN  ISNULL(RecoveryTime,-1)<>-1   THEN
      datediff(minute,OillastBeginTime,GETDATE())+ISNULL(GeneratorDur,0)    ELSE
      datediff(minute,BeginGenerator,GETDATE())   end )%60) 
      ELSE 
      LTRIM(floor( 
      ( ISNULL(GeneratorDur,0) /60))) 
      +':'+ 
      LTRIM( floor(( ISNULL(GeneratorDur,0)%60))) 
      end 
      ELSE '0' end
      as
      GeneratorDurTxt,  LTRIM(floor( StopDur/60))  +':'+  LTRIM(StopDur %60) as    TotalStopDurTxt,
      LTRIM(floor( GeneratorDur/60))  +':'+  LTRIM(GeneratorDur %60) as    TotalGeneratorDurTxt,
        LTRIM(floor( DischargeTime/60))  +':'+  LTRIM(DischargeTime %60) as    DischargeTimeTxt,
         LTRIM(floor(RemainTime/60))  +':'+  LTRIM(RemainTime %60) as RemainTimeTxt,
         
           CASE CreateStyle 
      WHEN 1 THEN '系统自动判断停电' 
      WHEN 2 THEN '人工判断停电' 
      ELSE '' END 
      as 
      CreateStyleTxt,     CASE EndOfJobStyle 
      WHEN 1 THEN '自动来电' 
      WHEN 2 THEN '手动来电' 
      WHEN 3 THEN '油机最后一次停止超过1小时(自动结束)' 
      WHEN 4 THEN '错误' 
      ELSE '' END 
      as 
      EndOfJobStyleTxt,   CASE   BatteryOneBad 
      WHEN 0 THEN '否' 
      WHEN 1 THEN '是' 
      ELSE '' END 
      as 
      BatteryOneBadTxt,  CASE   BatteryBad 
      WHEN 0 THEN '否' 
      WHEN 1 THEN '是' 
      ELSE '' END 
      as 
      BatteryBadTxt,   CASE   BatteryUnderLine 
      WHEN 0 THEN '否' 
      WHEN 1 THEN '是' 
      ELSE '' END 
      as 
      BatteryUnderLineTxt,     CASE   IsTakeback 
      WHEN 0 THEN '否' 
      WHEN 1 THEN '曾退服' 
      ELSE '' END 
      as 
      IsTakebackTxt,    CASE StationCommStatus 

      WHEN 1 THEN '正常' 
      WHEN 2 THEN '异常' 
      ELSE '' END 
      as 
      StationCommStatusTxt,   CASE BatteryStatus
      WHEN 1 THEN '浮充'
      WHEN 2 THEN '停电'
      WHEN 3 THEN '充电'
      WHEN 4 THEN '放电'
      ELSE '未监控' END
      as
      BatteryStatusTxt,     CASE OilStatus

      WHEN 1 THEN '油机发电'
      WHEN 2 THEN '油机停止'
      WHEN 3 THEN '未监控'

      ELSE '' END
      as
      OilStatusTxt, CASE  Flashing
      WHEN 0 THEN '否'
      WHEN 1 THEN '闪断'
      ELSE '' END
      as
      FlashingTxt,CASE  IsFake
      WHEN 0 THEN '否'
      WHEN 1 THEN '假发电'
      ELSE '' END
      as
      IsFakeTxt, CASE  IsTimely
      WHEN 0 THEN '否'
      WHEN 1 THEN '发电及时'
      ELSE '' END
      as
      IsTimelyTxt, CASE  IsPremature
      WHEN 0 THEN '否'
      WHEN 1 THEN '过早发电'
      ELSE '' END
      as
      IsPrematureTxt,CASE  IsSuperShort
      WHEN 0 THEN '否'
      WHEN 1 THEN '超短发电'
      ELSE '' END
      as
      IsSuperShortTxt,  CASE  IsMidWayReturn
      WHEN 0 THEN '否'
      WHEN 1 THEN '中途返回'
      ELSE '' END
      as
      IsMidWayReturnTxt, CASE  IsOilLongStop
      WHEN 0 THEN '否'
      WHEN 1 THEN '油机超长停止'
      ELSE '' END
      as
      IsOilLongStopTxt,  CASE WHEN ISNULL(OillastBeginTime,-1)<>-1 and ISNULL(OillastStopTime,-1)<>-1  AND (OillastBeginTime<OillastStopTime)
      THEN
      datediff(minute,OillastBeginTime,OillastStopTime)
      else
      0
      END
      as
      OillastStopDurTxt,  CASE SuType
      WHEN 0 THEN '机房'
      WHEN 1 THEN '节点'
      WHEN 2 THEN '基站'
      ELSE '' END
      as
      SuTypeTxt,   CASE SuType
      WHEN 0 THEN '/image/icons/16/home.png'
      WHEN 1 THEN '/image/icons/16/piechart.png'
      WHEN 2 THEN '/image/icons/16/search.png'
      ELSE '' END
      as SuTypeUrl,     CASE   InType
      WHEN 1 THEN '室内接入点接入'
      WHEN 2 THEN '室内非接入点接入'
      WHEN 3 THEN '室外'
      ELSE '' END
      as
      InTypeTxt,     CASE   SuLevel
      WHEN 1 THEN '重要基站51V'
      WHEN 2 THEN '一般基站47v'
      ELSE '' END
      as
      SuLevelTxt   ,
      LTRIM(floor( RedundancyDur/60))  +':'+  LTRIM(RedundancyDur %60) as    RedundancyDurTxt,
            CASE  OillastStopReason
      WHEN 0 THEN '市电恢复'
      WHEN 1 THEN '油机发电结束'
      ELSE '' END
      as
      OillastStopReasonTxt 
from cdc.fn_cdc_get_net_changes_dbo_ConfirmBK_StopGenerat(@BeginLSN,@ToLSN,'all with mask') as K where

__$operation=4 and  StatusType<>3 
and sys.fn_cdc_is_bit_set(  sys.fn_cdc_get_column_ordinal('dbo_ConfirmBK_StopGenerat','StatusType')
,K.__$update_mask)=1
 order by ID asc


---返回输出

    return  @ToLSN
END




三:长连接前台核心

//循环post
        function Keepline() {
            var array = new RequestArray();
            $.post("comet_broadcast.asyn", array.ToJson(),

  function (data) {
      var loadrowdata = false;
      if (parent.parent.getActiveTabUrl().indexOf("RealStoping") > -1) {
          loadrowdata = true;
      }
      if (loadrowdata) {
          if (data.ResultStatus == 1 && data.ResultData != null) {
              //数值与时间 累加更新
              var fdtime = new Date();
              var txtcurdatetimeflash = fdtime.getFullYear() + "-" + (fdtime.getMonth() + 1) + "-" + fdtime.getDate() + ":" + fdtime.getHours() + ":" + fdtime.getMinutes() + ":" + fdtime.getSeconds();

              Ext.getCmp(PrevTimeTag).setValue(txtcurdatetimeflash);

              X.ajaxLoadingMask.show(); //遮罩

              if (data.ResultData.DeleteDT != null && data.ResultData.DeleteDT.length > 0) {
                  //得到当前页面是否被显示
                  if (loadrowdata) {
                      DeleteData(data.ResultData.DeleteDT); //删除  
                  }
                  intPrevDelete = (data.ResultData.DeleteDT.length) * 1;
              }

              if (data.ResultData.AddDT != null && data.ResultData.AddDT.length > 0) {
                  if (loadrowdata) {
                      AddData(data.ResultData.AddDT); //新增
                  }
                  intPrevAdd = (data.ResultData.AddDT.length) * 1;
              }

              if (data.ResultData.UpdateDT != null && data.ResultData.UpdateDT.length > 0) {
                  if (loadrowdata) {
                      UpdateData(data.ResultData.UpdateDT); //替换
                  }
                  intPrevUpdate = (data.ResultData.UpdateDT.length) * 1;
              }

              X.ajaxLoadingMask.hide(); //遮罩
              try {
                  //数值与时间 累加更新
                  intSumAdd = intSumAdd + intPrevAdd;
                  intSumDelete = intSumDelete + intPrevDelete;
                  intSumUpdate = intSumUpdate + intPrevUpdate;


                  Ext.getCmp(TxtPrevAdd).setValue(intPrevAdd)
                  Ext.getCmp(TxtPrevDelete).setValue(intPrevDelete)
                  Ext.getCmp(TxtPrevUpdate).setValue(intPrevUpdate)

                  Ext.getCmp(TxtSumAdd).setValue(intSumAdd)
                  Ext.getCmp(TxtSumDelete).setValue(intSumDelete)
                  Ext.getCmp(TxtSumUpdate).setValue(intSumUpdate)


              }
              catch (e) {
                  //e.message
                  //e.description
                  //e.number
                  //throw new erroe();
              }
          }
      }
      Keepline();
  }, "json");



四:连接统一回发组件


4.1进入ashx

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

namespace ServerPushHttpHandler
{

    //1.主要做接收操作

    /// <summary>
    /// 异步处理程序
    /// </summary>
    public class ServerPushHandler : IHttpAsyncHandler, IReadOnlySessionState 
    {
        //进程开始异步调用
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) 
        {
            return new ServerPushManager(context, new ServerPushResult(context, cb, extraData)).ExecAction();
        }

        //进程结束
        public void EndProcessRequest(IAsyncResult result) 
        {

        }


        #region  防止IIS报错

        //不使用线程池
        public bool IsReusable 
        {
            get { return false; }
        }

        //同步时的处理方法
        public void ProcessRequest(HttpContext context) 
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}




4.2进入分析

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

namespace ServerPushHttpHandler
{
    public class ServerPushManager
    {

        //2.主要用来做请求处理

        #region 全局变量

        HttpContext m_Context;
        //推送结果
        ServerPushResult _IAsyncResult;
        //请求参数对象
        RequestModel rm = new RequestModel();

        #endregion

        #region 构造函数
        /// <summary>
        /// 构造方法
        /// </summary>
        public ServerPushManager(HttpContext context, ServerPushResult _IAsyncResult)
        {
            this.m_Context = context;
            this._IAsyncResult = _IAsyncResult;
        }
        #endregion

        /// <summary>
        /// 根据Action判断执行方法
        /// </summary>
        /// <returns></returns>
        public ServerPushResult ExecAction()
        {
            try
            {

                //角色--没有权限,直接返回-1
                if (m_Context.Session["roleid"] != null && !string.IsNullOrEmpty(m_Context.Session["roleid"].ToString()))
                {
                    rm.RoleId = int.Parse(m_Context.Session["roleid"].ToString());
                   
                }
                else
                {
                    //没有权限,直接返回-1
                    ResponseResultModel ResponseResult = new ResponseResultModel();
                    ResponseResult.ResultStatus = -1;
                    ResponseResult.ResultDetails = StatusCodeMsg.GetMsg(403);
                    _IAsyncResult.Result = ResponseResult.ResultString(); ;
                    _IAsyncResult.Send();
                    BLL.NLog.Current.Info("实时监控请求处理--没有角色权限");
                      
                }

                //用户
                rm.UserName = m_Context.User.Identity.Name;

                //类型
                if (!string.IsNullOrEmpty(m_Context.Request["Type"]))
                {
                    rm.Type = int.Parse(m_Context.Request["Type"]);
                }
                //请求时间戳
                 rm.InTimeStamp = DateTime.Now.ToString();

                 BLL.NLog.Current.Info("实时监控请求处理--用户:" + rm.UserName + "类型" + rm.Type + "请求时间戳:" + rm.InTimeStamp);

            }
            catch (Exception ex)
            {
                //参数错误
                ResponseResultModel ResponseResult = new ResponseResultModel();
                ResponseResult.ResultStatus = -1;
                ResponseResult.ResultDetails = StatusCodeMsg.GetMsg(400);
                _IAsyncResult.Result = ResponseResult.ResultString(); ;
                _IAsyncResult.Send();

                BLL.NLog.Current.Info("实时监控请求处理--"+ex.Message + Environment.NewLine + ex.StackTrace);
            }

            RealMonitor();

            ////参数选择--操作
            //switch (rm.Type)
            //{
            //    case 0://实时监控Column
            //        RealMonitor();
            //        break;
            //        //其他扩展OtherParamter
            //    default:
            //        break;
            //}
            return _IAsyncResult;
        }


        /// <summary>
        /// 实时监控
        /// </summary>
        /// <remarks>切割参数,存储进入实时监控List(CommonObj.Current.SPDict)中</remarks>
        private void RealMonitor()
        {
            //Column
            if (!string.IsNullOrEmpty(m_Context.Request["Column"]))
            {
                rm.Column = m_Context.Request["Column"];
            }

            //LSCCode
            if (!string.IsNullOrEmpty(m_Context.Request["LSCCode"]))
            {
                rm.LSCCode = m_Context.Request["LSCCode"];
            }

            //请求包装
            _IAsyncResult.rm = rm;

            BLL.NLog.Current.Info("实时监控请求处理--用户:" + rm.UserName + "列:" + rm.Column + "LSCCode:" +  rm.LSCCode );

            lock (CommonObj.Current.RealDict)
            {
                if (!CommonObj.Current.RealDict.ContainsKey(rm.UserName))
                    CommonObj.Current.RealDict.Add(rm.UserName, _IAsyncResult);
                else //登录时虽然保存了当前用户的连接,但是登录完后异步向客户端推送了数据,此时这个客户端连接已经失效,那么在connect时相当于才是此客户端与服务器端真正的连接,需要重新更新ServerPushResult的值
                    CommonObj.Current.RealDict[rm.UserName] = _IAsyncResult;
            }
        }


    }
}



4.3回发

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using DBUtility;
using Newtonsoft.Json;

namespace ServerPushHttpHandler
{
    //静态实时分发器  
    //检测当前数据,存入数据缓存中,LSN用作为标志。 
   public class StaticDistribution
   {
       //分发器。 主要用于时间扫描,集成在启动时asmx类,创建类,执行类启动方法,退出时,停止方法。
       //方法自动根据检测请求是否大于0决定是否执行数据库操作。如果不执行操作,则操作完成
       static System.Timers.Timer timer = new System.Timers.Timer();
       //开始时间,每次start时设置
       private System.DateTime beginTime = new DateTime();
       //上一次的EndLSN,下一次的BeginLSN
       private Byte[] LSNBytes = new Byte[10];
       //首次
       private bool isbeing = true;

       public StaticDistribution()
       {
           int RealTimeRefresh=int.Parse(ConfigurationManager.AppSettings["RealTimeRefresh"]);
           //30秒扫描一次CDC数据
           timer.Interval = RealTimeRefresh;
           timer.AutoReset = true;
         
       }

       public void start() 
       {
           beginTime = DateTime.Now;
           timer.Enabled = true;
           timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
           timer.Start();

       }
       public void end() 
       {
           beginTime = DateTime.MinValue;
           isbeing = true;
           timer.Enabled = false;
           timer.Stop();
           timer.Dispose();
       }


        void  timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            //有请求时执行
            if (CommonObj.Current.RealDict.Count > 0)
            {
                DataSet ds = new DataSet();
                try
                {
                    //select cdc 得到3个变动
                    if (isbeing)
                    {
                        isbeing = false;
                        LSNBytes = new Byte[10];

                        SqlParameter[] parameters = {
					new SqlParameter("@BeginTime", SqlDbType.DateTime),
                    new SqlParameter("@BeginLSN", SqlDbType.VarBinary,10),
                    new SqlParameter("@ToLSN", SqlDbType.VarBinary,10)
					};
                        parameters[0].Value = beginTime;
                        parameters[1].Value = DBNull.Value;
                        parameters[2].Direction = ParameterDirection.Output;
                        parameters[2].Value = LSNBytes;
                        BLL.NLog.Current.Info("实时监控分发器读取存储过程开始时间无LSN!" );
                        ds = DBUtility.DbHelperSQL.RunProcedure("RealCDC", parameters);//存储过程
                        LSNBytes = (Byte[])parameters[2].Value;
                        BLL.NLog.Current.Info("实时监控分发器读取存储过程开始时间结束LSN值为:" + HEX.byteToHexStr(LSNBytes));

                    }
                    else
                    {
                        SqlParameter[] parameters2 = {
					new SqlParameter("@BeginTime", SqlDbType.DateTime),
                    new SqlParameter("@BeginLSN", SqlDbType.VarBinary,10),
                    new SqlParameter("@ToLSN", SqlDbType.VarBinary,10)
					};
                        parameters2[0].Value = DBNull.Value;//进入存储过程不同的选择
                        parameters2[1].Value = LSNBytes;
                        parameters2[2].Direction = ParameterDirection.Output;           
                       parameters2[2].Value = LSNBytes;
                       BLL.NLog.Current.Info("实时监控分发器读取存储过程开始LSN值为:" + HEX.byteToHexStr(LSNBytes));
                       ds = DBUtility.DbHelperSQL.RunProcedure("RealCDC", parameters2);//存储过程
                       LSNBytes = (Byte[])parameters2[2].Value;
                       BLL.NLog.Current.Info("实时监控分发器读取存储过程结束LSN值为:" + HEX.byteToHexStr(LSNBytes));

                    }
                }catch(Exception ex1)
                {
                    BLL.NLog.Current.Info("实时监控分发器读取存储过程失败!"+ex1.Message + Environment.NewLine + ex1.StackTrace);
                }
                if (ds.Tables.Count == 3) 
                {
                     DataTable deleteTB=ds.Tables[0];
                     DataTable addTB=ds.Tables[1];
                     DataTable updateTB=ds.Tables[2];

                    lock (CommonObj.Current.RealDict)
                    {
                        for (int i = 0; i < CommonObj.Current.RealDict.Count; i++)
                        {
                            ServerPushResult sr = (ServerPushResult)CommonObj.Current.RealDict.ElementAt(i).Value;
                            ResponseResultModel srm = new ResponseResultModel();
                            try
                            {
                               
                                RealModel realModel=new RealModel();

                                srm.ResultStatus=1;   
                                realModel.InTimeStamp=sr.rm.InTimeStamp;
                                realModel.OutLSN = System.Text.Encoding.Default.GetString(LSNBytes);
                               
                                //抽取其对应的数据,构造JSON并返回

                                //1.请求解包rm
                                //2.抽取数据 lsccode 与 Column列

                               //要求LSCCODE权限
                                if(!String.IsNullOrEmpty(sr.rm.LSCCode))
                                {
                                    //单独查询LSCCODE
                                    if (deleteTB.Rows.Count > 0)
                                    {
                                        DataRow[] deleterows = deleteTB.Select("LSCCode in (" + sr.rm.LSCCode + ")");
                                        realModel.DeleteDT = deleteTB.Clone();
                                        for (int j = 0; j < deleterows.Length; j++)
                                        {
                                            realModel.DeleteDT.ImportRow((DataRow)deleterows[j]);
                                        }
                                    }

                                    if (addTB.Rows.Count > 0)
                                    {
                                        DataRow[] addrows = addTB.Select("LSCCode in (" + sr.rm.LSCCode + ")");
                                        realModel.AddDT = addTB.Clone();
                                        for (int j = 0; j < addrows.Length; j++)
                                        {
                                            realModel.AddDT.ImportRow((DataRow)addrows[j]);
                                        }
                                    }

                                    if (updateTB.Rows.Count > 0)
                                    {
                                        DataRow[] updaterows = updateTB.Select("LSCCode in (" + sr.rm.LSCCode + ")");

                                        realModel.UpdateDT = updateTB.Clone();
                                        for (int j = 0; j < updaterows.Length; j++)
                                        {
                                            realModel.UpdateDT.ImportRow((DataRow)updaterows[j]);
                                        }
                                    }
                                }
                                else
                                {
                                    //查询全部
                                    realModel.DeleteDT = deleteTB;
                                    realModel.AddDT = addTB;
                                    realModel.UpdateDT = updateTB;
                                }

                                //从datatable中得到定义列
                                //3.构造结果ResponseResultModel

                                srm.ResultData=realModel;
                                sr.Result=srm.ResultString();
                                //4.发送
                                sr.Send();
                                BLL.NLog.Current.Info("实时监控请求处理--发送成功:" + sr.rm.UserName + "请求时间戳:" + sr.rm.InTimeStamp + "回复时间:" + DateTime.Now);

                            }
                            catch(Exception ex2)
                            {
                                srm.ResultStatus = -1;
                                sr.Result =srm.ResultString();
                                sr.Send();
                                BLL.NLog.Current.Info("实时监控请求处理--发送异常处理:" + sr.rm.UserName  +ex2.Message + Environment.NewLine + ex2.StackTrace);

                            }
                        }
                       //清空全部
                       CommonObj.Current.RealDict.Clear();
                    }

                }

            }
            else { isbeing = true; }

        }
    }
}


你可能感兴趣的:(fineui实时监控(增、删、改)+CDC+长连接(一))