Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Configuration
Imports System.Text.RegularExpressions
Imports System.Web.UI.HtmlControls
Imports System.Collections.Specialized
Imports System.Security.Permissions
Imports System.Web.Script.Serialization

<Assembly: WebResource("PageControl.CorePlug.js", "application/x-javascript", PerformSubstitution:=True)> 
<Assembly: WebResource("PageControl.JSBase64.js", "application/x-javascript", PerformSubstitution:=True)> 
<Assembly: WebResource("PageControl.Upload.css", "text/css", PerformSubstitution:=True)> 
<ParseChildren(True, "Value")> _
    <AspNetHostingPermission(SecurityAction.Demand, _
       Level:=AspNetHostingPermissionLevel.Minimal)> _
Public Class CoreControl
    Inherits CompositeControl
    Implements IPostBackEventHandler
    Private _OutHTML As New XrenCache.clsHTML
    Private _Value As String
    Private _SQLlist As List(Of DB_SQL.SQLData)
    Private _PageSize As Integer
    Private Structure CounterInfo
        Dim OnLineCount As Integer
        Dim IPCounter As Integer
        Dim PageCounter As Integer
        Dim TodayCount As Integer
        Dim YesterDayCount As Integer
        Dim MaxCounter As Integer
        Dim MaxTime As String
    End Structure

    Private Structure PagingList
        Dim ReplaceString As String
        Dim PagingString As String
    End Structure
    Private Structure TagInfo
        Dim ValueType As String
        Dim Name As String
        Dim Condition As String
        Dim iOperator As String
        Dim Connect As String
        Dim Decrypt As String
        Dim IsEmpty As Boolean
        Dim IsIgnore As Boolean
        Dim strTag As String
    End Structure
    Public Sub RaisePostBackEvent(ByVal eventArgument As String) Implements IPostBackEventHandler.RaisePostBackEvent
    End Sub

    Private Property PageSize() As Integer
        Get
            Return _PageSize
        End Get
        Set(ByVal value As Integer)
            _PageSize = value
        End Set
    End Property

    Public Property Value() As String
        Get
            Return _Value
        End Get
        Set(ByVal value As String)
            _Value = value
        End Set
    End Property
    ''' <summary>
    ''' 获取当前页码
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public ReadOnly Property ThisPage() As Integer
        Get
            Dim mPage As Integer = 0
            Integer.TryParse(HttpContext.Current.Request(Me.ID & "_Page"), mPage)
            If mPage = 0 Then mPage = 1
            Return mPage
        End Get
    End Property

    Protected Overrides Sub RecreateChildControls()
        EnsureChildControls()
    End Sub
    Protected Overrides Sub CreateChildControls()
        Controls.Clear()
    End Sub

    Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)
        If _OutHTML IsNot Nothing Then
            writer.Write(_OutHTML.HTML)
        End If
        'AddAttributesToRender(writer)
    End Sub
    Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
        MyBase.OnPreRender(e)
    End Sub

    Protected Overrides Sub OnLoad(ByVal e As EventArgs)
        _OutHTML.HTML = ResolveTag(Page)
        If _OutHTML IsNot Nothing Then
            If _OutHTML.Title IsNot Nothing AndAlso _OutHTML.Title.Length > 0 Then
                Page.Title = _OutHTML.Title
            End If
            If _OutHTML.KeyWords IsNot Nothing AndAlso _OutHTML.KeyWords.Length > 0 Then
                Page.Header.Controls.Add(New HtmlMeta With {.Name = "keywords", .Content = _OutHTML.KeyWords})
            End If
            If _OutHTML.Description IsNot Nothing AndAlso _OutHTML.Description.Length > 0 Then
                Page.Header.Controls.Add(New HtmlMeta With {.Name = "Description", .Content = _OutHTML.Description})
            End If
        End If
    End Sub

    Private Property SQLlist() As List(Of DB_SQL.SQLData)
        Get
            If _SQLlist IsNot Nothing AndAlso _SQLlist.Count > 0 Then
                Return _SQLlist
            Else
                Dim mSiteID As Integer = CType(BaseFunction.PublicMethod.GetApplication("SiteID"), Integer)
                _SQLlist = XrenCache.XrCache.GetList(New DB_SQL.DB_SQLDataContext, "SQL" & mSiteID.ToString, DB_SQL.clsSQLData.GetLinq(mSiteID), XrenCache.XrCache.CacheLifeType.File, HttpContext.Current.Request.PhysicalApplicationPath & "CacheFile\SQL" & mSiteID.ToString & ".txt", , , , CType(BaseFunction.PublicMethod.GetApplication("SecCache"), Boolean))
                Return _SQLlist
            End If
        End Get
        Set(ByVal value As List(Of DB_SQL.SQLData))
            _SQLlist = value
        End Set
    End Property

    ''' <summary>
    ''' 执行逻辑分析
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ResolveTag(ByVal mPage As Page) As String
        Dim TagID As Integer
        Dim ctlID As String = New Regex("ctl", RegexOptions.IgnoreCase).Replace(Me.ID, "")
        If Integer.TryParse(ctlID, TagID) Then
            Dim mSiteID As Integer = CType(BaseFunction.PublicMethod.GetApplication("SiteID"), Integer)
            Dim mTagList As List(Of DB_Tag.TagData) = XrenCache.XrCache.GetList(New DB_Tag.DB_TagDataContext, "Tag" & mSiteID.ToString & mSiteID.ToString, DB_Tag.clsTagData.GetLinq(mSiteID), XrenCache.XrCache.CacheLifeType.File, HttpContext.Current.Request.PhysicalApplicationPath & "CacheFile\Tag" & mSiteID.ToString & ".txt", , , , CType(BaseFunction.PublicMethod.GetApplication("SecCache"), Boolean))
            Dim mTag As DB_Tag.TagData = (From t In mTagList _
                                         Where t.ID = TagID _
                                         Select t).FirstOrDefault
            If mTag IsNot Nothing Then
                Dim strHTML As String = BaseFunction.PublicMethod.Base64DecryptData(mTag.TagContent)
                strHTML = "<root><data><![CDATA[" & strHTML.Replace("<@", "]]></data><").Replace("@>", "><data><![CDATA[") & "]]></data></root>"
                Dim mXDoc As XDocument = XDocument.Parse(strHTML)
                Return ResolveFunction(mXDoc.Root, mPage)
            Else
                Return "错误的参数！"
            End If
        Else
            Return "错误的参数！"
        End If
    End Function

    Private Function ResolveFunction(ByVal ParentNote As XElement, ByVal mPage As Page) As String
        If ParentNote Is Nothing Then Return ""
        Dim Html As New StringBuilder
        Dim mDoc = From a As XElement In ParentNote.Elements _
                   Select a
        For Each n In mDoc
            '处理函数
            Select Case n.Name.LocalName
                Case "if"
                    If HanderIf(n) Then
                        Html.Append(ResolveFunction(n, mPage))
                    Else
                        Html.Append(ResolveFunction(n.Element("else"), mPage))
                    End If
                Case "select"
                    Html.Append(ResolveFunction(HanderSelect(n), mPage))
                Case "function"
                    Html.Append(HanderFunction(n, mPage))
                Case "data"
                    Html.Append(n.Value)
                Case "sitecounter"
                    Html.Append(SiteCounter)
            End Select
        Next
        Return Html.ToString
    End Function
    Private Function SiteCounter() As String
        Dim PageCounter As Integer
        Dim IPCounter As Integer
        Dim TodayCount As Integer
        Dim YesterDayCount As Integer
        Dim MaxCounter As Integer
        Dim MaxTime As Date
        Dim StartTime As Date
        Dim ToDayTime As Date
        Dim mSiteID As String = BaseFunction.PublicMethod.GetApplication("SiteID")
        Dim UserIPCount As Integer
        Dim returnCounter As New CounterInfo
        Dim mJson As New JavaScriptSerializer
        Dim UserIP As String = Context.Request.ServerVariables("Remote_Addr")
        Using mConn As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("XrenCRMConnString").ConnectionString)
            mConn.Open()
            Dim mCMD As New Data.SqlClient.SqlCommand("select top 1 * from sitecounter where siteid=" & mSiteID, mConn)
            Dim mRd As Data.SqlClient.SqlDataReader = mCMD.ExecuteReader
            '------------------- 初始化
            If mRd.Read Then
                Integer.TryParse(mRd("PageCounter"), PageCounter)
                Integer.TryParse(mRd("IPCounter"), IPCounter)
                Integer.TryParse(mRd("TodayCount"), TodayCount)
                Integer.TryParse(mRd("YesterDayCount"), YesterDayCount)
                Integer.TryParse(mRd("MaxCounter"), MaxCounter)
                Date.TryParse(mRd("MaxTime"), MaxTime)
                Date.TryParse(mRd("StartTime"), StartTime)
                Date.TryParse(mRd("ToDayTime"), ToDayTime)
                PageCounter += 1
                mRd.Close()
            Else
                mRd.Close()
                PageCounter = 1
                IPCounter = 1
                TodayCount = 1
                YesterDayCount = 0
                StartTime = Now
                MaxCounter = 1
                MaxTime = Now
                mCMD.CommandText = "insert into sitecounteronline (SiteID,IPAddress) values(" & mSiteID & ",'" & UserIP & "');Insert into SiteCounter (SiteID,IPCounter,MaxCounter,MaxTime,PageCounter,StartTime,TodayCount,ToDayTime,YesterDayCount)values(" & mSiteID & "," & IPCounter & "," & MaxCounter & ",'" & MaxTime & "'," & PageCounter & ",'" & StartTime & "'," & TodayCount & ",'" & ToDayTime & "'," & YesterDayCount & ")"
                mCMD.ExecuteNonQuery()
                mConn.Close()
                With returnCounter
                    .OnLineCount = 1
                    .IPCounter = IPCounter
                    .PageCounter = PageCounter
                    .TodayCount = TodayCount
                    .YesterDayCount = YesterDayCount
                    .MaxCounter = MaxCounter
                    .MaxTime = MaxTime.ToString("yyyy年MM月dd日hh时mm分ss秒")
                End With
                Return mJson.Serialize(returnCounter)
            End If

            If Now.Year = ToDayTime.Year AndAlso Now.Month = ToDayTime.Month AndAlso Now.Day = ToDayTime.Day Then '判断是否是当天
                mCMD.CommandText = "select count(IPAddress) from sitecounteronline where SiteID=" & mSiteID & " AND IPAddress ='" & UserIP & "' and LoginDate >= '" & Now.AddMinutes(-20) & "'"
                Integer.TryParse(mCMD.ExecuteScalar, UserIPCount)
                If UserIPCount = 0 Then
                    TodayCount += 1
                    IPCounter += 1
                    mCMD.CommandText = "insert into sitecounteronline (SiteID,IPAddress) values(" & mSiteID & ",'" & UserIP & "');"
                End If
            Else
                YesterDayCount = TodayCount
                TodayCount = 1
                ToDayTime = Now.ToString
                mCMD.CommandText = "delete from sitecounteronline Where SiteID=" & mSiteID & ";insert into sitecounteronline (SiteID,IPAddress) values(" & mSiteID & ",'" & UserIP & "');"
            End If
            If TodayCount > MaxCounter Then '--------------------------------------------是否更新最大访问记录
                If MaxCounter = 0 Then
                    PageCounter = 1
                    IPCounter = 1
                    TodayCount = 1
                    YesterDayCount = 0
                    StartTime = Now
                End If
                MaxCounter = TodayCount
                MaxTime = Now
            End If
            Dim OnLineCount As Integer
            mCMD.CommandText = mCMD.CommandText & "update SiteCounter Set IPCounter=" & IPCounter & ",MaxCounter=" & MaxCounter & ",MaxTime='" & MaxTime & "',PageCounter=" & PageCounter & ",StartTime='" & StartTime & "',TodayCount=" & TodayCount & ",ToDayTime='" & ToDayTime & "',YesterDayCount=" & YesterDayCount & " Where SiteID=" & mSiteID & ";"
            mCMD.CommandText = mCMD.CommandText & "select count(IPAddress) from sitecounteronline where SiteID=" & mSiteID & " AND LoginDate >= '" & Now.AddMinutes(-20) & "'"
            Integer.TryParse(mCMD.ExecuteScalar, OnLineCount)
            mConn.Close()
            With returnCounter
                .OnLineCount = OnLineCount
                .IPCounter = IPCounter
                .PageCounter = PageCounter
                .TodayCount = TodayCount
                .YesterDayCount = YesterDayCount
                .MaxCounter = MaxCounter
                .MaxTime = MaxTime.ToString("yyyy年MM月dd日hh时mm分ss秒")
            End With
            Return mJson.Serialize(returnCounter)
        End Using
    End Function
    Private Function HanderData(ByVal FunctionNode As XElement) As String
        Dim DataSQLID As String = FunctionNode.Attribute("sqlid").Value
        Dim strPageSize As String = FunctionNode.Attribute("pagesize").Value
        Integer.TryParse(strPageSize, PageSize)
        Dim mSQLID As Integer = 0
        If Integer.TryParse(DataSQLID, mSQLID) Then
            Dim mSQL As DB_SQL.SQLData = (From s In SQLlist _
                                         Where s.ID = mSQLID _
                                         Select s).FirstOrDefault
            Dim mOpenTrace As Boolean = CType(BaseFunction.PublicMethod.GetApplication("OpenTrace"), Boolean)
            Dim mCountSQL As XrenCache.clsSQLAndCacheName = ReplaceSQLTag(mSQL.CountSQL)
            Dim mMainSQL As XrenCache.clsSQLAndCacheName = ReplaceSQLTag(mSQL.SQLData)
            mMainSQL.CacheName = "SQLID" & mSQLID.ToString & mMainSQL.CacheName
            Dim mclsHTML As XrenCache.clsHTML = XrenCache.XrCache.GetList(mSQL.ID, mSQL.SQLName, mSQL.CacheLifeType, mSQL.DependOf, mMainSQL, mCountSQL, FunctionNode, Me.ID, CType(BaseFunction.PublicMethod.GetApplication("SecCache"), Boolean))
            If mclsHTML IsNot Nothing Then
                _OutHTML.Title = mclsHTML.Title
                _OutHTML.KeyWords = mclsHTML.KeyWords
                _OutHTML.Description = mclsHTML.Description
                If mOpenTrace Then
                    mclsHTML.HTML = "查询名称：" & mSQL.SQLName & "<br />主查询语句：" & mMainSQL.SQL & "<br />记录数查询：" & mCountSQL.SQL & "<br />" & mclsHTML.HTML
                End If
                Return mclsHTML.HTML
            Else
                If mOpenTrace Then
                    Return "查询错误！<br />查询名称：" & mSQL.SQLName & "<br />主查询语句：" & mMainSQL.SQL & "<br />记录数查询：" & mCountSQL.SQL
                Else
                    Return "查询错误，如需调试，请打开网站配置中调试选项！"
                End If
            End If
        Else
            Return "错误的查询，请检查标签设置！"
        End If
    End Function
    Private Function HanderJson(ByVal FunctionNode As XElement) As String
        Dim DataSQLID As String = FunctionNode.Attribute("sqlid").Value
        Dim Result As String = ""
        Dim mSQLID As Integer = 0
        If Integer.TryParse(DataSQLID, mSQLID) Then
            Dim mSQL As DB_SQL.SQLData = (From s In SQLlist _
                                         Where s.ID = mSQLID _
                                         Select s).FirstOrDefault

            Dim mCountSQL As XrenCache.clsSQLAndCacheName = ReplaceSQLTag(mSQL.CountSQL)
            Dim mMainSQL As XrenCache.clsSQLAndCacheName = ReplaceSQLTag(mSQL.SQLData)
            mMainSQL.CacheName = "SQLID" & mSQLID.ToString & mMainSQL.CacheName
            Dim mOpenTrace As Boolean = CType(BaseFunction.PublicMethod.GetApplication("OpenTrace"), Boolean)
            Dim iTable As Data.DataTable = XrenCache.XrCache.GetList(mMainSQL.CacheName, mCountSQL.SQL, mMainSQL.SQL, mSQL.CacheLifeType, mSQL.DependOf, , CType(BaseFunction.PublicMethod.GetApplication("SecCache"), Boolean))
            If iTable IsNot Nothing Then
                Dim mclsHTML As New XrenCache.clsHTML
                mclsHTML.HTML = DataTable2Json(iTable)
                If mOpenTrace Then
                    Result = "查询名称：" & mSQL.SQLName & "<br />查询语句：" & mMainSQL.SQL & "<br />" & mclsHTML.HTML
                Else
                    HttpContext.Current.Response.Write(mclsHTML.HTML)
                    HttpContext.Current.Response.End()
                End If
            Else
                If mOpenTrace Then
                    Result = "查询错误！<br />查询名称：" & mSQL.SQLName & "<br />主查询语句：" & mMainSQL.SQL & "<br />记录数查询：" & mCountSQL.SQL
                Else
                    Result = "查询错误，如需调试，请打开网站配置中调试选项！"
                End If
            End If
        Else
            Result = "错误的查询，请检查标签设置！"
        End If
        Return Result
    End Function
    Private Function DataTable2Json(ByVal dt As DataTable) As String
        Dim jsonBuilder As New StringBuilder
        jsonBuilder.Append("[")
        For i As Integer = 0 To dt.Rows.Count - 1
            jsonBuilder.Append("{")
            For j As Integer = 0 To dt.Columns.Count - 1
                jsonBuilder.Append(Chr(34))
                jsonBuilder.Append(dt.Columns(j).ColumnName)
                jsonBuilder.Append(Chr(34) & ":" & Chr(34))
                jsonBuilder.Append(dt.Rows(i)(j).ToString())
                jsonBuilder.Append(Chr(34) & ",")
            Next
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1)
            jsonBuilder.Append("},")
        Next
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1)
        jsonBuilder.Append("]")
        Return jsonBuilder.ToString()
    End Function

    Private Function HanderFunction(ByVal node As XElement, ByVal mPage As Page) As String
        Dim FunctionType As String = node.Attribute("type").Value
        Dim mValue As String = ""
        Select Case FunctionType
            Case "html"
                Return HanderData(node)
            Case "json"
                Return HanderJson(node)
            Case "randomimage"
                If Not mPage.ClientScript.IsClientScriptIncludeRegistered("jqueryminScript") Then mPage.ClientScript.RegisterClientScriptInclude("jqueryminScript", BaseFunction.PublicMethod.GetBaseUrl & "/App_Themes/ManagerTheme/js/jquery.min.js")
                If Not mPage.ClientScript.IsClientScriptIncludeRegistered("CorePlug") Then Page.ClientScript.RegisterClientScriptResource(GetType(CoreControl), "PageControl.CorePlug.js")
                Dim CodeLen As String = node.Attribute("len").Value
                Dim CookieName As String = node.Attribute("cookiename").Value
                Return "<img style=""cursor:hand;"" src=""/ResponseRndImage.gdr?RndCodeLen=" & CodeLen & "&CodeCookie=" & CookieName & """ alt=""看不清，更换一张"" onclick=""javascript:MadeRndURL('" & CodeLen & "','" & CookieName & "',this);"" />"
            Case "execute"
                Dim mSQLID As Integer = 0
                Dim strSQLID As String = node.Attribute("sqlid").Value
                If Integer.TryParse(strSQLID, mSQLID) Then
                    Dim mSQL As DB_SQL.SQLData = (From s In SQLlist _
                                                  Where s.ID = mSQLID _
                                                  Select s).FirstOrDefault
                    Dim mMainSQL As XrenCache.clsSQLAndCacheName = ReplaceSQLTag(mSQL.SQLData)
                    Dim ExCount As Integer = 0
                    Dim WirteString As String = ""
                    Using mConn As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("XrenCRMConnString").ConnectionString)
                        mConn.Open()
                        Dim mCMD As New Data.SqlClient.SqlCommand(mMainSQL.SQL, mConn)
                        Try
                            ExCount = mCMD.ExecuteNonQuery
                            WirteString = ExCount.ToString
                        Catch ex As Exception
                            If CType(BaseFunction.PublicMethod.GetApplication("OpenTrace"), Boolean) Then
                                WirteString = "查询错误！<br />错误信息：" & ex.Message & "<br />查询名称：" & mSQL.SQLName & "<br />主查询语句：" & mMainSQL.SQL
                            Else
                                WirteString = "查询错误，如需调试，请打开网站配置中调试选项！"
                            End If
                        End Try
                        mConn.Close()
                    End Using
                    HttpContext.Current.Response.Write(WirteString)
                    HttpContext.Current.Response.End()
                End If
            Case "upload"
                Dim UploadPath As String = node.Attribute("path").Value
                Dim btnImage As String = node.Attribute("button").Value
                Dim fileEx As String = node.Attribute("fileex").Value
                Dim callbackFunction As String = node.Attribute("callback").Value
                Dim mWidth As String = node.Attribute("width").Value
                Dim mHeight As String = node.Attribute("height").Value
                If UploadPath IsNot Nothing AndAlso UploadPath.Length > 0 AndAlso btnImage IsNot Nothing AndAlso btnImage.Length > 0 AndAlso callbackFunction IsNot Nothing AndAlso callbackFunction.Length > 0 Then
                    If Not mPage.ClientScript.IsClientScriptIncludeRegistered("jqueryminScript") Then mPage.ClientScript.RegisterClientScriptInclude("jqueryminScript", BaseFunction.PublicMethod.GetBaseUrl & "/App_Themes/ManagerTheme/js/jquery.min.js")
                    If Not mPage.ClientScript.IsClientScriptIncludeRegistered("swfobject") Then mPage.ClientScript.RegisterClientScriptInclude("swfobject", BaseFunction.PublicMethod.GetBaseUrl & "/App_Themes/ManagerTheme/js/swfobject.js")
                    If Not mPage.ClientScript.IsClientScriptIncludeRegistered("jqueryuploadifyv210min") Then mPage.ClientScript.RegisterClientScriptInclude("jqueryuploadifyv210min", BaseFunction.PublicMethod.GetBaseUrl & "/App_Themes/ManagerTheme/js/jquery.uploadify.v2.1.0.min.js")
                    If Not mPage.ClientScript.IsClientScriptIncludeRegistered("CorePlug") Then Page.ClientScript.RegisterClientScriptResource(GetType(CoreControl), "PageControl.CorePlug.js")
                    Dim autoCompleteCss As New HtmlLink()
                    autoCompleteCss.Href = Page.ClientScript.GetWebResourceUrl(GetType(CoreControl), "PageControl.Upload.css")
                    autoCompleteCss.Attributes.Add("rel", "stylesheet")
                    autoCompleteCss.Attributes.Add("type", "text/css")
                    mPage.Header.Controls.Add(autoCompleteCss)
                    mValue = "<div class=""uploadify""><div><input type=""file"" name=""uploadify" & Me.ID & """ id=""uploadify" & Me.ID & """ /></div><div id=""fileQueue" & Me.ID & """></div></div>" & _
                             "<script>InitUpload('uploadify" & Me.ID & "','fileQueue" & Me.ID & "','" & btnImage & "','" & UploadPath & "','" & callbackFunction & "'," & mWidth & "," & mHeight & ",'" + fileEx + "');</script>"
                Else
                    mValue = "设置参数错误！"
                End If
            Case "submit"
                Dim strText As String = node.Attribute("text").Value
                Dim strImage As String = node.Attribute("button").Value
                Dim strSubmit As String = node.Attribute("submit").Value
                Dim strCode As String = node.Element("data").Value

                If Not mPage.ClientScript.IsClientScriptIncludeRegistered("jqueryminScript") Then mPage.ClientScript.RegisterClientScriptInclude("jqueryminScript", BaseFunction.PublicMethod.GetBaseUrl & "/App_Themes/ManagerTheme/js/jquery.min.js")
                If Not mPage.ClientScript.IsClientScriptIncludeRegistered("CorePlug") Then Page.ClientScript.RegisterClientScriptResource(GetType(CoreControl), "PageControl.CorePlug.js")
                If Not mPage.ClientScript.IsClientScriptIncludeRegistered("JSBase64") Then Page.ClientScript.RegisterClientScriptResource(GetType(CoreControl), "PageControl.JSBase64.js")

                If strSubmit Is Nothing OrElse strSubmit.Length = 0 Then strSubmit = mPage.Request.RawUrl
                If strSubmit = "/" Then strSubmit = ""
                If strImage.Trim.Length > 0 Then
                    mValue = "<img style=""cursor:pointer;"" alt=""" & strText & """ src=""" & strImage & """ onclick=""FormSubmit('" & BaseFunction.PublicMethod.Base64EncryptData(strCode) & "','" & strSubmit & "');"" />"
                    'mValue = "<img style=""cursor:pointer;"" alt=""" & strText & """ src=""" & strImage & """ onclick=""FormSubmit('" & strSubmit & "');"" />"
                Else
                    If strText.Trim.Length > 0 Then
                        mValue = "<span style=""cursor:pointer;""  onclick=""FormSubmit('" & BaseFunction.PublicMethod.Base64EncryptData(strCode) & "','" & strSubmit & "');"">" & strText & "</span>"
                    Else
                        mValue = "提交参数设置错误！"
                    End If
                End If
            Case "cookiewrite"
                Dim iSourcetype As String = node.Attribute("sourcetype").Value
                Dim iValue As String = node.Attribute("value").Value
                Select Case iSourcetype
                    Case "sql"
                        Dim mSQLID As Integer = 0
                        If Integer.TryParse(iValue, mSQLID) Then
                            Dim mSQL As DB_SQL.SQLData = (From s In SQLlist _
                                                          Where s.ID = mSQLID _
                                                          Select s).FirstOrDefault
                            Dim mMainSQL As XrenCache.clsSQLAndCacheName = ReplaceSQLTag(mSQL.SQLData)
                            Dim iTable As Data.DataTable = Nothing
                            Using mConn As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("XrenCRMConnString").ConnectionString)
                                Dim mDA As New Data.SqlClient.SqlDataAdapter(mMainSQL.SQL, mConn)
                                Dim mDT As New Data.DataSet
                                Try
                                    mDA.Fill(mDT)
                                Catch ex As Exception
                                    If CType(BaseFunction.PublicMethod.GetApplication("OpenTrace"), Boolean) Then
                                        HttpContext.Current.Response.Write("查询错误！<br />错误信息：" & ex.Message & "<br />查询名称：" & mSQL.SQLName & "<br />主查询语句：" & mMainSQL.SQL)
                                        HttpContext.Current.Response.End()
                                    Else
                                        HttpContext.Current.Response.Write("查询错误，如需调试，请打开网站配置中调试选项！")
                                        HttpContext.Current.Response.End()
                                    End If
                                    Return ""
                                End Try
                                If mDT.Tables.Count > 0 Then
                                    iTable = mDT.Tables(0)
                                End If
                            End Using
                            Dim strField As String = ""
                            If iTable IsNot Nothing AndAlso iTable.Rows.Count > 0 Then
                                For j As Integer = 0 To iTable.Columns.Count - 1
                                    HttpContext.Current.Response.Cookies(iTable.Columns(j).ColumnName).Value = iTable.Rows(0)(j)
                                Next
                            End If
                        End If
                    Case "request"
                        Dim iRequest As String = HttpContext.Current.Request(iValue)
                        HttpContext.Current.Response.Cookies(iValue).Value = iRequest
                End Select
            Case "cookieread"
                Dim iCookies As String = node.Attribute("cookies").Value
                Dim iCookieValue As String = ""
                If iCookies IsNot Nothing AndAlso iCookies.Length > 0 Then
                    If node.Element("data") IsNot Nothing Then
                        mValue = node.Element("data").Value
                    End If
                    For Each i As String In iCookies.Split(",")
                        If HttpContext.Current.Request.Cookies(i) IsNot Nothing Then
                            iCookieValue = HttpContext.Current.Request.Cookies(i).Value
                            mValue = mValue.Replace("<field name=""" & i & """ />", iCookieValue)
                        End If
                    Next
                End If
        End Select
        Return mValue
    End Function

    Private Function HanderSelect(ByVal node As XElement) As XElement
        Dim selType As String = node.Attribute("type").Value
        Dim selCondition As String = node.Attribute("condition").Value
        Dim mValue As String = ""
        Select Case selType
            Case "request"
                mValue = HttpContext.Current.Request(selCondition)
            Case "cookie"
                If HttpContext.Current.Request.Cookies(selCondition) IsNot Nothing Then
                    mValue = HttpContext.Current.Request.Cookies(selCondition).Value
                End If
            Case "sql"
                Dim mSQLID As Integer = 0
                If Integer.TryParse(selCondition, mSQLID) Then
                    Dim mSQL As DB_SQL.SQLData = (From s In SQLlist _
                                                  Where s.ID = mSQLID _
                                                  Select s).FirstOrDefault
                    Dim mMainSQL As XrenCache.clsSQLAndCacheName = ReplaceSQLTag(mSQL.SQLData)
                    Using mConn As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("XrenCRMConnString").ConnectionString)
                        mConn.Open()
                        Dim mCMD As New Data.SqlClient.SqlCommand
                        mCMD.Connection = mConn
                        mCMD.CommandText = mMainSQL.SQL

                        If mSQL.SQLType = -1 Then
                            Try
                                mValue = mCMD.ExecuteScalar.ToString
                            Catch ex As Exception
                                mConn.Close()
                                If CType(BaseFunction.PublicMethod.GetApplication("OpenTrace"), Boolean) Then
                                    HttpContext.Current.Response.Write("查询错误！<br />错误信息：" & ex.Message & "<br />查询名称：" & mSQL.SQLName & "<br />主查询语句：" & mMainSQL.SQL)
                                    HttpContext.Current.Response.End()
                                Else
                                    HttpContext.Current.Response.Write("查询错误，如需调试，请打开网站配置中调试选项！")
                                    HttpContext.Current.Response.End()
                                End If
                            End Try
                        Else
                            Try
                                mValue = mCMD.ExecuteNonQuery
                            Catch ex As Exception
                                mConn.Close()
                                If CType(BaseFunction.PublicMethod.GetApplication("OpenTrace"), Boolean) Then
                                    HttpContext.Current.Response.Write("查询错误！<br />错误信息：" & ex.Message & "<br />查询名称：" & mSQL.SQLName & "<br />主查询语句：" & mMainSQL.SQL)
                                    HttpContext.Current.Response.End()
                                Else
                                    HttpContext.Current.Response.Write("查询错误，如需调试，请打开网站配置中调试选项！")
                                    HttpContext.Current.Response.End()
                                End If
                            End Try
                        End If
                        
                        mConn.Close()
                    End Using
                End If
        End Select
        Dim mCaseNode = (From n As XElement In node.Elements("case") _
                        Where n.Attribute("value") = mValue _
                        Select n).FirstOrDefault
        If mCaseNode Is Nothing Then
            Return (From n As XElement In node.Elements("case") _
                    Where n.Attribute("value") = "default" _
                    Select n).FirstOrDefault
        Else
            Return mCaseNode
        End If
    End Function


    Private Function HanderIf(ByVal node As XElement) As Boolean
        Dim ifType As String = node.Attribute("type").Value
        Dim ifcondition As String = node.Attribute("condition").Value
        Dim ifoperator As String = HttpContext.Current.Server.UrlDecode(node.Attribute("operator").Value)
        Dim ifvaluetype As String = node.Attribute("valuetype").Value
        Dim ifvalueanme As String = node.Attribute("valueanme").Value
        Dim mValue As String = ""
        Dim mCompareValue As String = ""
        Dim mComplate As Boolean = False
        Select Case ifType
            Case "request"
                mValue = HttpContext.Current.Request(ifcondition)
            Case "cookie"
                If HttpContext.Current.Request.Cookies(ifcondition) IsNot Nothing Then
                    mValue = HttpContext.Current.Request.Cookies(ifcondition).Value
                End If
            Case "sql"
                Dim mSQLID As Integer = 0
                If Integer.TryParse(ifcondition, mSQLID) Then
                    Dim mSQL As DB_SQL.SQLData = (From s In SQLlist _
                                                  Where s.ID = mSQLID _
                                                  Select s).FirstOrDefault
                    Dim mMainSQL As XrenCache.clsSQLAndCacheName = ReplaceSQLTag(mSQL.SQLData)
                    Using mConn As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("XrenCRMConnString").ConnectionString)
                        mConn.Open()
                        Dim mCMD As New Data.SqlClient.SqlCommand
                        mCMD.Connection = mConn
                        mCMD.CommandText = mMainSQL.SQL
                        If mSQL.SQLType = -1 Then
                            Try
                                mValue = mCMD.ExecuteScalar.ToString
                            Catch ex As Exception
                                mConn.Close()
                                If CType(BaseFunction.PublicMethod.GetApplication("OpenTrace"), Boolean) Then
                                    HttpContext.Current.Response.Write("查询错误！<br />错误信息：" & ex.Message & "<br />查询名称：" & mSQL.SQLName & "<br />主查询语句：" & mMainSQL.SQL)
                                    HttpContext.Current.Response.End()
                                Else
                                    HttpContext.Current.Response.Write("查询错误，如需调试，请打开网站配置中调试选项！")
                                    HttpContext.Current.Response.End()
                                End If
                            End Try
                        Else
                            Try
                                mValue = mCMD.ExecuteNonQuery
                            Catch ex As Exception
                                mConn.Close()
                                If CType(BaseFunction.PublicMethod.GetApplication("OpenTrace"), Boolean) Then
                                    HttpContext.Current.Response.Write("查询错误！<br />错误信息：" & ex.Message & "<br />查询名称：" & mSQL.SQLName & "<br />主查询语句：" & mMainSQL.SQL)
                                    HttpContext.Current.Response.End()
                                Else
                                    HttpContext.Current.Response.Write("查询错误，如需调试，请打开网站配置中调试选项！")
                                    HttpContext.Current.Response.End()
                                End If
                            End Try
                        End If
                        mConn.Close()
                    End Using
                End If
        End Select
        Select Case ifvaluetype
            Case "request"
                mCompareValue = HttpContext.Current.Request(ifvalueanme)
            Case "cookie"
                If HttpContext.Current.Request.Cookies(ifvalueanme) IsNot Nothing Then
                    mCompareValue = HttpContext.Current.Request.Cookies(ifcondition).Value
                End If
            Case "sql"
                Dim mSQLID As Integer = 0
                If Integer.TryParse(ifvalueanme, mSQLID) Then
                    Dim mSQL As DB_SQL.SQLData = (From s In SQLlist _
                                                  Where s.ID = mSQLID _
                                                  Select s).FirstOrDefault
                    Dim mMainSQL As XrenCache.clsSQLAndCacheName = ReplaceSQLTag(mSQL.SQLData)
                    Using mConn As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("XrenCRMConnString").ConnectionString)
                        mConn.Open()
                        Dim mCMD As New Data.SqlClient.SqlCommand
                        mCMD.Connection = mConn
                        mCMD.CommandText = mMainSQL.SQL
                        If mSQL.SQLType = -1 Then
                            Try
                                mCompareValue = mCMD.ExecuteScalar.ToString
                            Catch ex As Exception
                                mConn.Close()
                                If CType(BaseFunction.PublicMethod.GetApplication("OpenTrace"), Boolean) Then
                                    HttpContext.Current.Response.Write("查询错误！<br />错误信息：" & ex.Message & "<br />查询名称：" & mSQL.SQLName & "<br />主查询语句：" & mMainSQL.SQL)
                                    HttpContext.Current.Response.End()
                                Else
                                    HttpContext.Current.Response.Write("查询错误，如需调试，请打开网站配置中调试选项！")
                                    HttpContext.Current.Response.End()
                                End If
                            End Try
                        Else
                            Try
                                mCompareValue = mCMD.ExecuteNonQuery
                            Catch ex As Exception
                                mConn.Close()
                                If CType(BaseFunction.PublicMethod.GetApplication("OpenTrace"), Boolean) Then
                                    HttpContext.Current.Response.Write("查询错误！<br />错误信息：" & ex.Message & "<br />查询名称：" & mSQL.SQLName & "<br />主查询语句：" & mMainSQL.SQL)
                                    HttpContext.Current.Response.End()
                                Else
                                    HttpContext.Current.Response.Write("查询错误，如需调试，请打开网站配置中调试选项！")
                                    HttpContext.Current.Response.End()
                                End If
                            End Try
                        End If
                        Try
                            mCompareValue = mCMD.ExecuteScalar.ToString
                        Catch ex As Exception
                            mConn.Close()
                            If CType(BaseFunction.PublicMethod.GetApplication("OpenTrace"), Boolean) Then
                                HttpContext.Current.Response.Write("查询错误！<br />错误信息：" & ex.Message & "<br />查询名称：" & mSQL.SQLName & "<br />主查询语句：" & mMainSQL.SQL)
                                HttpContext.Current.Response.End()
                            Else
                                HttpContext.Current.Response.Write("查询错误，如需调试，请打开网站配置中调试选项！")
                                HttpContext.Current.Response.End()
                            End If
                        End Try

                        mConn.Close()
                    End Using
                End If
            Case "value"
                mCompareValue = ifvalueanme
        End Select
        Select Case ifoperator
            Case "大于"
                If mValue > mCompareValue Then mComplate = True
            Case "小于"
                If mValue < mCompareValue Then mComplate = True
            Case "等于"
                If mValue = mCompareValue Then mComplate = True
            Case "大于等于"
                If mValue >= mCompareValue Then mComplate = True
            Case "小于等于"
                If mValue <= mCompareValue Then mComplate = True
            Case "不等于"
                If mValue <> mCompareValue Then mComplate = True
        End Select
        Return mComplate
    End Function

    ''' <summary>
    ''' 处理SQL中的标签
    ''' </summary>
    ''' <param name="SQLTag">带标签的SQL语句</param>
    ''' <returns>标准SQL语句</returns>
    ''' <remarks></remarks>
    Private Function ReplaceSQLTag(ByVal SQLTag As String) As XrenCache.clsSQLAndCacheName
        Dim returnValue As New XrenCache.clsSQLAndCacheName
        Dim strCacheName As New StringBuilder
        Dim mXDoc As XDocument = XDocument.Parse("<root>" & SQLTag & "</root>")
        Dim mWhere = (From w In mXDoc.Root.Elements _
                     Where w.Attribute("Type").Value = "WHERE" _
                     Select New TagInfo With {.valueType = w.Attribute("ValueType").Value, _
                                              .Name = w.Attribute("Name").Value, _
                                              .Decrypt = w.Attribute("Decrypt").Value, _
                                              .Condition = w.Attribute("Condition").Value, _
                                              .Connect = w.Attribute("Connect").Value, _
                                              .iOperator = w.Attribute("Operator").Value, _
                                              .IsEmpty = CType(w.Attribute("IsEmpty").Value, Boolean), _
                                              .IsIgnore = CType(w.Attribute("IsIgnore").Value, Boolean), _
                                              .strTag = w.ToString}).ToList
        Dim mOrder = From o In mXDoc.Root.Elements _
                          Where o.Attribute("Type").Value = "ORDER" _
                          Select o


        Dim mVariable = From v In mXDoc.Root.Elements _
                        Where v.Attribute("Type").Value = "Variable" _
                        Select v
        Dim strWhere As String = ""
        Dim strValue As String = ""
        Dim mFirst As Boolean = True
        '==================================处理WHERE子句========================
        For Each w In mWhere
            If Not mFirst Then
                strWhere = w.Connect
            Else
                mFirst = False
            End If
            strWhere = strWhere & " " & w.Condition
            strWhere = strWhere & strToOperator(w.iOperator)
            Select Case w.ValueType.ToLower
                Case "request"
                    strValue = HttpContext.Current.Request(w.Name)
                    Select Case w.Decrypt
                        Case "MD5"
                            strValue = BaseFunction.PublicMethod.MD5(strValue, 16)
                        Case "编码"
                            strValue = HttpContext.Current.Server.UrlDecode(strValue)
                    End Select
                Case "cookie"
                    If HttpContext.Current.Request.Cookies(w.Name) IsNot Nothing Then
                        strValue = HttpContext.Current.Request.Cookies(w.Name).Value
                        Select Case w.Decrypt
                            Case "MD5"
                                strValue = BaseFunction.PublicMethod.MD5(strValue, 16)
                            Case "编码"
                                strValue = HttpContext.Current.Server.UrlDecode(strValue)
                        End Select
                    Else
                        strValue = ""
                    End If
                Case "value"
                    strValue = w.Name
            End Select
            If Not CheckRequest(strValue) Then
                returnValue.SQL = ""
                returnValue.CacheName = ""
                Return returnValue
            End If
            If w.iOperator <> "LIKE" Then
                strWhere = strWhere & "'" & strValue & "'"
            Else
                strWhere = strWhere & "'%" & strValue & "%'"
            End If

            If strValue Is Nothing OrElse strValue.Length = 0 Then
                If w.IsIgnore Then '可忽略
                    SQLTag = SQLTag.Replace(w.strTag, "")
                Else
                    If w.IsEmpty Then
                        SQLTag = SQLTag.Replace(w.strTag, strWhere)
                    Else
                        returnValue.SQL = ""
                        returnValue.CacheName = ""
                        Return returnValue
                    End If
                End If
            Else
                SQLTag = SQLTag.Replace(w.strTag, strWhere)
            End If
            strWhere = ""
            strCacheName.Append("_W_" & strValue)
        Next
        '====================================处理Orderby子句========================================
        Dim strOrderField As String = ""
        Dim strOrderDesc As String = ""
        Dim hasFirst As Boolean = False
        For Each o In mOrder
            Select Case o.Attribute("FieldSource").Value.ToLower
                Case "request"
                    strOrderField = HttpContext.Current.Request(o.Attribute("FieldName").Value)
                Case "cookie"
                    If HttpContext.Current.Request.Cookies(o.Attribute("FieldName").Value) IsNot Nothing Then
                        strOrderField = HttpContext.Current.Request.Cookies(o.Attribute("FieldName").Value).Value
                    Else
                        strOrderField = ""
                    End If
                Case Else
                    strOrderField = o.Attribute("FieldSource").Value & "." & o.Attribute("FieldName").Value
            End Select
            Select Case o.Attribute("DescSource").Value.ToLower
                Case "request"
                    strOrderDesc = HttpContext.Current.Request(o.Attribute("DescName").Value)
                Case "cookie"
                    If HttpContext.Current.Request.Cookies(o.Attribute("DescName").Value) IsNot Nothing Then
                        strOrderDesc = HttpContext.Current.Request.Cookies(o.Attribute("DescName").Value).Value
                    Else
                        strOrderDesc = ""
                    End If
                Case Else
                    strOrderDesc = o.Attribute("DescName").Value
            End Select

            If Not CheckRequest(strOrderField) OrElse Not CheckRequest(strOrderDesc) Then
                returnValue.SQL = ""
                returnValue.CacheName = ""
                Return returnValue
            End If
            If strOrderField IsNot Nothing AndAlso strOrderField.Length > 0 Then
                If Not hasFirst Then
                    SQLTag = SQLTag.Replace(o.ToString, strOrderField & " " & strOrderDesc)
                    hasFirst = True
                Else
                    SQLTag = SQLTag.Replace(o.ToString, "," & strOrderField & " " & strOrderDesc)
                End If
            Else
                SQLTag = SQLTag.Replace(o.ToString, "")
            End If
            strCacheName.Append("_OF_" & strOrderField & "_OD_" & strOrderDesc)
        Next

        '==========================================处理查询语句中的自定义变量========================================
        Dim mDecrypt As String
        For Each v In mVariable
            Select Case v.Attribute("ValueType").Value.ToLower
                Case "request"
                    strValue = HttpContext.Current.Request(v.Attribute("Name").Value)
                Case "cookie"
                    If HttpContext.Current.Request.Cookies(v.Attribute("Name").Value) IsNot Nothing Then
                        strValue = HttpContext.Current.Request.Cookies(v.Attribute("Name").Value).Value
                    Else
                        strValue = ""
                    End If
                Case "value"
                    strValue = v.Attribute("Name").Value
            End Select
            mDecrypt = v.Attribute("Decrypt")
            Select Case mDecrypt
                Case "MD5"
                    strValue = BaseFunction.PublicMethod.MD5(strValue, 16)
                Case "编码"
                    strValue = HttpContext.Current.Server.UrlDecode(strValue)
            End Select
            If Not CheckRequest(strValue) Then
                returnValue.SQL = ""
                returnValue.CacheName = ""
                Return returnValue
            End If
            SQLTag = SQLTag.Replace(v.ToString, strValue)
            strCacheName.Append("_V_" & strValue)
        Next
        Dim mPage As String = ThisPage
        If mPage Is Nothing OrElse mPage.Length = 0 Then
            mPage = "0"
        End If
        returnValue.SQL = SQLTag.Replace("@PageSize", PageSize).Replace("@Page", mPage)
        returnValue.CacheName = strCacheName.Append("_P" & mPage).ToString
        Return returnValue
    End Function
    Private Function strToOperator(ByVal intHTML As String) As String
        Select Case intHTML
            Case "等于"
                Return "="
            Case "大于"
                Return ">"
            Case "小于"
                Return "<"
            Case "大于等于"
                Return ">="
            Case "小于等于"
                Return "<="
            Case "不等于"
                Return "<>"
            Case "LIKE"
                Return " LIKE "
            Case Else
                Return ""
        End Select
    End Function
  
 
    Private Function CheckRequest(ByVal strRequest As String) As Boolean
        If strRequest Is Nothing OrElse strRequest.Length = 0 Then Return True
        Dim strInto() As String = {":", ";", ">", "<", "--", "sp_", "xp_", "\", "dir", "cmd", "^", "(", ")", "+", "$", "'", "copy", "format", "and", "exec", "insert", "select", "delete", "update", "count", "*", "%", "chr", "mid", "master", "truncate", "char", "declare"}
        Dim Findstr As String = (From s In strInto _
                                 Where strRequest.ToLower.Contains(s) _
                                 Select s).FirstOrDefault
        If Findstr IsNot Nothing AndAlso Findstr.Length > 0 Then
            Return False
        Else
            Return True
        End If
    End Function
End Class
