Imports System.IO

Public Class MdiMain

    Enum E_MenuIdx
        NONE = 0
        입력존 = 1
        입력면
        공조처리
        난방기기
        난방공급시스템
        난방분배시스템
        냉방기기
        냉방분배시스템
        신재생및열병합
        열관류율
        건물개요 = 20
        월별에너지사용량
    End Enum

    '''현재열려있는폼의 이름을 변경한다.
    Public OpenedForm As E_MenuIdx = E_MenuIdx.NONE

    Private Sub MdiMain_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        pLog.Add("FormClosed", True)
    End Sub

    Private Sub MdiMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        'If PrjChanged Then
        '    Dim dlg As DialogResult = MsgBox("변경된 내역이 존재합니다" + vbCrLf + vbCrLf + _
        '        "저장하시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.YesNo, "확인")
        '    If dlg = Windows.Forms.DialogResult.Yes Then
        '        bt_filesave.PerformClick()
        '    End If
        'End If
        Dim quitmsg As String = CLang.종료할래

        If Not Prj.Opened Then
            If MsgBox(quitmsg, MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, CLang.확인) = MsgBoxResult.Ok Then
                End
            Else
                e.Cancel = True
            End If
        Else
            quitmsg = "현재 열려있는 파일을 저장 후 종료하시겠습니까?"
            Dim dlg As DialogResult = MsgBox(quitmsg, MsgBoxStyle.Question Or MsgBoxStyle.YesNoCancel, "확인")
            If dlg = Windows.Forms.DialogResult.Yes Then
                Me.Save_File(DSET1, DSETR1, Prj.FileName)
                '//저장
            ElseIf dlg = Windows.Forms.DialogResult.No Then
                '//quit
            ElseIf dlg = Windows.Forms.DialogResult.Cancel Then
                e.Cancel = True
                Return
            End If
        End If


    End Sub

    Private Sub MdiMain_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        Select Case e.KeyCode
            Case Keys.F1
                If e.Shift AndAlso e.Control Then
                    bt_test.Visible = True
                Else
                    Read_PreFile(0)
                End If
            Case Keys.F2
                Read_PreFile(1)
            Case Keys.F3
                Read_PreFile(2)
            Case Keys.F4
                Read_PreFile(3)
        End Select
    End Sub

    Private Sub MdiMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        '//v프로그ㅐㄻ이 켜질떄

        Me.Text = My.Application.Info.ProductName & " Ver" & My.Application.Info.Version.ToString()
        Me.bt_filesave.Enabled = False    '//저장버튼비활성
        Me.Show()
        My.Application.DoEvents() '//화면에 표시

        Refresh_info()



        Read_SEtting() '//환경설정을 가져온다. Splah를 변경했따.
        Read_FilHistory() '//파일사용내역

        Dim F As New Frm_Intro  '//로그인화면을 표시
        If F.ShowDialog <> Windows.Forms.DialogResult.OK Then End '//로그인을 완료하지 못했다면 프로그램을 종료한다.

        '//Version 정보를 확인

        Dim MyVersion As String = Format(My.Application.Info.Version.Minor, "0000") & Format(My.Application.Info.Version.Build, "0000")

        Dim L As New ArinLogin.ArinLOgin
        Dim VersionInfo As ArinLogin.ArinLOgin.sVersionInfo = Nothing

        Dim authtype As String = Prj.UserAuthType
        'If authtype.StartsWith("BOTH_C_") Then authtype = "BOTH"

        Select Case authtype
            Case "ADMIN"
                Me.bt_etc.Visible = True
                bt_데이터관리.Visible = True
                bt_설계개선그래프.Visible = True
                bt_계산결과.Visible = True
                bt_계산결과그래프.Visible = True
                'bt_계산결과그래프q.Visible = True
                bt_인증평가서.Visible = True
                btImport.Visible = True
                btMacro.Visible = True
            Case "BOTH0" '//일반사용자
                bt_데이터관리.Visible = False
                bt_계산결과그래프.Visible = True
                'bt_계산결과그래프q.Visible = True
                Me.bt_etc.Visible = False
                bt_설계개선그래프.Visible = False
                bt_계산결과.Visible = False
                bt_인증평가서.Visible = False
                btImport.Visible = False
                btMacro.Visible = False
                '//서버로부터 사용여부 체크
                'If L.Check_guest <> "OK" Then
                '    MsgBox("일반사용자에게는 아직 오픈되지 않았습니다.", MsgBoxStyle.Information, "확인")
                '    End
                'End If
            Case "BOTH" '
                bt_데이터관리.Visible = False
                Me.bt_etc.Visible = False
                bt_설계개선그래프.Visible = False
                bt_계산결과.Visible = True
                bt_계산결과그래프.Visible = True
                'bt_계산결과그래프q.Visible = True
                bt_인증평가서.Visible = True
                btImport.Visible = True
                btMacro.Visible = False
            Case "BOTH1"
                bt_데이터관리.Visible = True
                Me.bt_etc.Visible = False
                bt_설계개선그래프.Visible = False
                bt_계산결과.Visible = True
                bt_계산결과그래프.Visible = True
                'bt_계산결과그래프q.Visible = True
                bt_인증평가서.Visible = True
                btImport.Visible = True
                btMacro.Visible = False
            Case "BOTH2"
                bt_데이터관리.Visible = False
                Me.bt_etc.Visible = False
                bt_설계개선그래프.Visible = False
                bt_계산결과.Visible = False
                bt_계산결과그래프.Visible = False
                'bt_계산결과그래프q.Visible = False
                bt_인증평가서.Visible = False
                btImport.Visible = False
                btMacro.Visible = False
            Case Else
                bt_데이터관리.Visible = False
                bt_계산결과그래프.Visible = False
                Me.bt_etc.Visible = False
                bt_설계개선그래프.Visible = False
                bt_계산결과.Visible = False
                bt_인증평가서.Visible = False
                btImport.Visible = False
                btMacro.Visible = False
        End Select

        btMacro2.Visible = btMacro.Visible

        If Prj.UserAuthType_Real.StartsWith("BOTH_C_") Then
            btcustomprofile.Visible = True
        End If


        Try
            If Not Prj.UserId.ToLower().StartsWith("guest") AndAlso Not Prj.UserId.ToLower().StartsWith("user") Then
                Work_msg("프로그램 버젼확인중")
                If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가
                    VersionInfo = L.Get_LastVersion("E")   '//버젼을 가져오는데  eco 버젼만 가져오게 바꺼야겟죵 ^^ 구분자를 넣도록 합시닷!
                Else
                    VersionInfo = L.Get_LastVersion("EP")   '//버젼을 가져오는데  eco 버젼만 가져오게 바꺼야겟죵 ^^ 구분자를 넣도록 합시닷!
                End If
            Else
                VersionInfo.Ver = "0"
            End If

        Catch ex As Exception
            End
        End Try

        'Try
        '    If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가
        '        VersionInfo = L.Get_LastVersion("E")   '//버젼을 가져오는데  eco 버젼만 가져오게 바꺼야겟죵 ^^ 구분자를 넣도록 합시닷!
        '    Else
        '        VersionInfo = L.Get_LastVersion("EP")   '//버젼을 가져오는데  eco 버젼만 가져오게 바꺼야겟죵 ^^ 구분자를 넣도록 합시닷!
        '    End If
        'Catch ex As Exception
        '    End
        'End Try

        If VersionInfo.Ver <> "0" AndAlso (CInt(VersionInfo.Ver) > CInt(MyVersion)) Then   '//0은 없거나 관리안함의 뜻이므로 넘어간다.
            Dim Msg As New System.Text.StringBuilder
            Msg.AppendLine("새로운 버젼이 확인되었습니다" & vbCrLf)
            Msg.AppendLine("현재버젼:" & MyVersion & " 신규버젼:" & VersionInfo.Ver)
            Msg.AppendLine("----------------------------------")
            Msg.AppendLine(VersionInfo.Desc)
            Msg.AppendLine("----------------------------------")
            If VersionInfo.Link.Trim = "" Then VersionInfo.Link = "http://홈페이지주소"
            ' Msg.AppendLine("신규버젼을 확인하기위한 페이지를 여시겠습니까?")
            If MsgBox(Msg.ToString, MsgBoxStyle.Information, "버젼확인") = MsgBoxResult.Ok Then
                'Shell("explorer " & VersionInfo.Link, AppWinStyle.NormalFocus)
                ' End
            End If
            End '2011.03.08 프로그램이 최신버전이 아니면 프로그램을 종료시킨다.
        End If
        Work_msg("")

        '//20160327 임시저장폴더생성
        Dim tempsave As String = My.Application.Info.DirectoryPath & "\TempSave"
        If Not System.IO.Directory.Exists(tempsave) Then
            Try
                System.IO.Directory.CreateDirectory(tempsave)
            Catch ex As Exception
                MsgBox("임시저장폴더 생성실패" + vbCrLf + vbCrLf + tempsave + vbCrLf + vbCrLf + ex.Message, MsgBoxStyle.Critical, "확인")
            End Try
        End If

        '//파라미터확인
        Dim P As String = Command.ToString
        P = P.Replace(Chr(34), "")
        If P <> "" Then
            If System.IO.File.Exists(P) Then  '//해당파일이 존재하면
                ' MsgBox("open")
                Me.Open_File(P)
            End If
        End If

        pLog.Add("Program Start")

        ' WebView2 Fixed Version 체크
        CheckWebView2Runtime()


        If Me.bt_etc.Visible = False AndAlso System.Diagnostics.Debugger.IsAttached Then
            MsgBox("debugmode import on")
            Me.bt_etc.Visible = True
        End If


    End Sub

    Public Sub Refresh_info()
        'If Prj.Admin Then
        '    Me.lb_usermode.Text = "[관리자]"
        'Else
        '    Me.lb_usermode.Text = "[일반]"
        'End If
        '//템플릿 정보파일
        If Prj.EditTime = "" Then
            Me.lbl_lastedit.Text = "[최종변경]"
        Else
            Me.lbl_lastedit.Text = "[" & Prj.EditTime.Trim & "]"
        End If
        If Prj.Name = "" Then
            Me.lbl_prjname.Text = "[이름]"
            Me.lbl_prjname.ToolTipText = ""
        Else
            Me.lbl_prjname.Text = "[" & Prj.Name.Trim.Replace(Space(1), "") & "]"
            Me.lbl_prjname.ToolTipText = Prj.Desc
        End If
        If Prj.SFType = "" Then
            Me.lbl_FileInfo.Text = "[버젼]"
        Else
            Me.lbl_FileInfo.Text = "[" & Prj.UIVersion.Trim & "]"
        End If

        If Prj.Password = "" Then
            Me.lbl_password.Text = "[비보호]"
        Else
            Me.lbl_password.Text = "[보호]"
        End If

        Me.lbl_user.Text = "[" & Prj.UserId & "]"
        Me.lbl_mac.Text = "[" & Prj.CUrMac & "]"

    End Sub

    Private Sub bt_fileopen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub


    Sub ClearData()
        '//현재열려있는프로젝트를 닫는다.
        DSET1.Clear()
        DSET2.Clear()
        DSETR1.Clear()
        DSETR2.Clear()

        DSET1.AcceptChanges()
        DSET2.AcceptChanges()
        DSETR1.AcceptChanges()
        DSETR2.AcceptChanges()

        'DSET1 = New DS()
        'DSET2 = New DS()

        'DSETR1 = New DSR()
        'DSETR2 = New DSR()

        'DSET1.AcceptChanges()
        'DSET2.AcceptChanges()
        'DSETR1.AcceptChanges()
        'DSETR2.AcceptChanges()
    End Sub



    Public Function Open_File(ByVal FileName As String, Optional ByVal SyncServer As Boolean = False, Optional checkVersion As Boolean = True, Optional silent As Boolean = False, Optional isNew As Boolean = False) As Boolean

        If SyncServer Then
            If Prj.UserId.ToLower().StartsWith("user") Then
                SyncServer = False
            End If
        End If

        If Prj.Opened Then

            If silent Then

                '//auto close 171105
                For Each fChild As CForm In Me.MdiChildren
                    If fChild.HasChanged Then
                        fChild.AcceptChanged()
                    End If
                    fChild.Close()
                    fChild.Dispose()
                Next

                '//현재열려있는프로젝트를 닫는다.
                ClearData()

            Else
                Dim quitmsg As String = "현재 열려있는 프로젝트를 저장하시겠습니까?"
                Dim dlg As DialogResult = MsgBox(quitmsg, MsgBoxStyle.Question Or MsgBoxStyle.YesNoCancel, "확인")
                If dlg = Windows.Forms.DialogResult.Yes Then

                    If bt_filesave.Enabled = False Then
                        If Save_New() = False Then Return False '//취소를 누른경우 처리하지 않음

                    Else
                        Me.Save_File(DSET1, DSETR1, Prj.FileName, False)
                    End If


                    For Each fChild As CForm In Me.MdiChildren
                        If fChild.HasChanged Then
                            fChild.AcceptChanged()
                        End If
                        fChild.Close()
                        fChild.Dispose()
                    Next

                    '//현재열려있는프로젝트를 닫는다.
                    ClearData()
                    '//저장
                ElseIf dlg = Windows.Forms.DialogResult.No Then
                    For Each fChild As CForm In Me.MdiChildren
                        If fChild.HasChanged Then
                            fChild.AcceptChanged()
                        End If
                        fChild.Close()
                        fChild.Dispose()
                    Next

                    '//현재열려있는프로젝트를 닫는다.
                    ClearData()
                    '//quit
                ElseIf dlg = Windows.Forms.DialogResult.Cancel Then
                    Return False
                End If
            End If


        End If

        '//기존선택된 트리노드를 제거한다.
        Me.PreNode = Nothing
        pLog.Add("=======================================")
        pLog.Add(String.Format("Open File = {0}", FileName))
        pLog.Add("=======================================", True)
        Prj.IsError = False '//160509

        '//파일을 열어서 템플릿이름을 가져온다
        Dim FI As New System.IO.FileInfo(FileName)
        Dim Desbuf() As Byte = {}
        Dim FS As System.IO.Stream
        '///////////////////////////////////////////////////////////////////////////////////////////////////2011.03.16 입력파일 변조
        If Not (Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1") Then  '//2011.03.16 추가 //eco 파일 불러올때 ADMIN 제거 'Prj.UserAuthType = "ADMIN" OrElse 
            Dim Source() As Byte = My.Computer.FileSystem.ReadAllBytes(FI.FullName)

            If Source.Length < 4 Then
                Prj.IsError = True
                MsgboxE("알수없거나 손상된 파일입니다" + vbCrLf + FI.FullName, True)
                Return False
            End If
            pLog.Add("암호화 해제")
            Desbuf = DeCryptArea(Source, New Byte() {&HAC, &H29, &H55, &H42})

        Else
            'tpl file
            Desbuf = System.IO.File.ReadAllBytes(FileName)
            ' FS = New IO.FileStream(FileName, IO.FileMode.Open)
        End If

        If FI.Extension.ToLower().EndsWith("x") Then    '//확장자가 x로끝나면 압축된 포맷
            Dim datalen As Integer = BitConverter.ToInt32(Desbuf, 0)
            Dim RealData(Desbuf.Length - 4 - 1) As Byte
            Array.Copy(Desbuf, 4, RealData, 0, RealData.Length)
            Dim DeCompress(datalen - 1) As Byte
            Array.Clear(DeCompress, 0, DeCompress.Length)
            Utility.MiniLZO.Decompress(RealData, DeCompress)
            Array.Resize(Desbuf, DeCompress.Length)
            Array.Clear(Desbuf, 0, Desbuf.Length)
            Array.Copy(DeCompress, Desbuf, Desbuf.Length)
        End If



        FS = New IO.MemoryStream(Desbuf, True)

        '///////////////////////////////////////////////////////////////////////////////////////////////////2011.03.16 입력파일 변조



        Dim Br As New IO.BinaryReader(FS, System.Text.Encoding.Default)
        Prj.FileName = FileName : Myini.Write("presetting", "filename", Prj.FileName)
        Prj.Opened = False


        '//세이브파일구조(2)
        Prj.SFType = STB(Br.ReadBytes(2))
        pLog.Add("File Type = " + Prj.SFType)

        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가 //eco 파일 불러올때 ADMIN 제거 'Prj.UserAuthType = "ADMIN" OrElse 

            Select Case Prj.SFType
                Case "00"   '//기본버젼
                    Prj.UIVersion = STB(Br.ReadBytes(10))
                    Prj.LGVersino = STB(Br.ReadBytes(10))
                    Select Case Prj.LGVersino
                        Case "2009123100", "2010030700", "2010031400"
                            Prj.LGVersino = StartVersion
                    End Select
                    Select Case Prj.UIVersion
                        Case "2009123100", "2010030700", "2010031400"
                            Prj.UIVersion = StartVersion
                            Prj.UIVersion = StartVersion
                    End Select

                    Prj.Name = STB(Br.ReadBytes(100))
                    Prj.Desc = STB(Br.ReadBytes(256))
                    Prj.MakeTime = STB(Br.ReadBytes(19))
                    Prj.EditTime = STB(Br.ReadBytes(19))
                    ' MsgBox(Br.BaseStream.Position)

                    '//DS1 데이터초기화 및 오픈
                    DSET1.Clear()
                    DSET1.AcceptChanges()


                    Dim DS1Len As Int64 = Br.ReadInt64
                    If DS1Len = 0 Then
                        DS1Len = FS.Length - Br.BaseStream.Position - 2
                    End If
                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1Len, MsgBoxStyle.Information, Hex(DS1Len))
                    Dim DS1() As Byte = Nothing
                    Try
                        DS1 = Br.ReadBytes(CInt(DS1Len))
                    Catch ex As Exception
                        Prj.IsError = True
                        MsgBox("파일이 손상되었습니다(Read Data Array)." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1 byteRead Error")
                    End Try

                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1.Length, MsgBoxStyle.Information, DS1Len)
                    If Not Prj.IsError Then
                        Dim Ms As New IO.MemoryStream(DS1)
                        Try
                            Ms.Position = 0

                            Dim tempds As New DS()
                            tempds.ReadXml(Ms)

                            DSET1.Clear()
                            DSET1.Merge(tempds) '   DSET1.ReadXml(Ms)
                            DSET1.AcceptChanges()
                            Ms.Close()

                            tempds.Dispose()
                        Catch ex As Exception
                            Prj.IsError = True
                            MsgBox("파일이 손상되었습니다(Read DataSet)" & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1 Open Error")
                        End Try

                        If Prj.IsError Then
                            If silent Then
                                Return String.Empty
                            End If
                            If MsgBox("데이터를 복구모드로 확인하시겠습니까?", MsgBoxStyle.Question Or MsgBoxStyle.YesNo, "확인") = MsgBoxResult.Yes Then
                                '//메모리버퍼르 utf8를 이용하여 데이터처리를 해야한다
                                Dim accCount As UInteger = 0
                                Ms.Position = 0
                                Dim AllDataList As String = System.Text.Encoding.UTF8.GetString(DS1)
                                My.Computer.FileSystem.WriteAllText("c:\temp\1.txt", AllDataList, False)
                                Dim CurrentTable As String = ""
                                Dim dr As DataRow = Nothing

                                For Each line As String In AllDataList.Split(vbCrLf)



                                    '//각줄을 가지고 처리를 한다
                                    line = line.Trim
                                    If line.ToLower.StartsWith("<ds") AndAlso line.EndsWith(">") Then
                                        '//데이터셋선언부이므로 넘어간다
                                    ElseIf line.ToLower.StartsWith("<weather_") AndAlso line.EndsWith(">") Then
                                        CurrentTable = line.Substring(1, line.Length - 2)
                                        dr = DSET1.Tables(CurrentTable).NewRow
                                    ElseIf line.ToLower.StartsWith("</weather_") AndAlso line.EndsWith(">") Then
                                        '//테이블의 종료
                                        '//
                                        accCount += 1
                                        DSET1.Tables(CurrentTable).Rows.Add(dr)
                                        CurrentTable = ""
                                    ElseIf line.ToLower.StartsWith("<tbl_") AndAlso line.EndsWith(">") Then
                                        CurrentTable = line.Substring(1, line.Length - 2)
                                        dr = DSET1.Tables(CurrentTable).NewRow
                                    ElseIf line.ToLower.StartsWith("</tbl_") AndAlso line.EndsWith(">") Then
                                        '//테이블의 종료
                                        DSET1.Tables(CurrentTable).Rows.Add(dr)
                                        accCount += 1
                                        CurrentTable = ""
                                    Else
                                        '//일반데이터
                                        If String.IsNullOrWhiteSpace(CurrentTable) Then Continue For
                                        Dim 닫는태그위치 As Integer = line.IndexOf(">")
                                        If 닫는태그위치 > -1 Then
                                            Dim 필드명 As String = line.Substring(1, 닫는태그위치 - 1)
                                            Dim 값종료태그위치 As Integer = line.IndexOf("<", 닫는태그위치)
                                            If 값종료태그위치 > -1 Then
                                                Dim 내부값 As String = line.Substring(닫는태그위치 + 1, 값종료태그위치 - 닫는태그위치 - 1)
                                                dr(필드명) = 내부값
                                            End If
                                        End If
                                    End If
                                Next

                                '//만약입력존이 없고 입력면 데이터가 있다면 존분류값을 이용해서 존을 우선 생성해준다
                                If DSET1.tbl_zone.Rows.Count < 2 AndAlso DSET1.tbl_myoun.Rows.Count > 1 Then
                                    For Each drMn As DS.tbl_myounRow In DSET1.tbl_myoun.Rows
                                        Dim 존분류 As String = drMn.존분류.Trim
                                        If String.IsNullOrWhiteSpace(존분류) Then Continue For
                                        Dim 존데이터갯수 As Integer = DSET1.tbl_zone.Select("code='" + 존분류 + "'").Length
                                        If 존데이터갯수 = 0 Then
                                            Dim 뉴존 As DS.tbl_zoneRow = DSET1.tbl_zone.Newtbl_zoneRow
                                            뉴존.code = 존분류
                                            뉴존.설명 = "자동생성(" + 존분류 + ")"
                                            DSET1.tbl_zone.Addtbl_zoneRow(뉴존)
                                            accCount += 1
                                        End If
                                    Next
                                    DSET1.tbl_zone.AcceptChanges()
                                End If

                                MsgBox(accCount.ToString() + "건의 자료가 복구되었습니다", MsgBoxStyle.Critical, "확인")
                                DSET1.AcceptChanges()
                                DSETR1.Clear() : DSETR1.AcceptChanges()
                                Prj.IsError = False
                            End If
                        Else
                            '//에러가없는경우 다음진행

                            '//DS1가 있다면 게속 한다
                            DSETR1.Clear() : DSETR1.AcceptChanges()
                            DS1Len = Br.ReadInt64
                            DS1 = Br.ReadBytes(CInt(DS1Len))
                            Ms = New IO.MemoryStream(DS1)
                            Try

                                Dim tempds As New DS()
                                tempds.ReadXml(Ms)


                                DSETR1.Clear()
                                DSETR1.Merge(tempds) ' DSETR1.ReadXml(Ms)
                                DSETR1.AcceptChanges()
                                Ms.Close()

                                tempds.Dispose()
                            Catch ex As Exception
                                MsgBox("기존 버전의 계산결과를 가져올 수 없습니다." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds2 Open Error")
                            End Try

                            Prj.IsError = False

                        End If


                    End If

                Case "01"   '//기본버젼(+암호
                    Prj.UIVersion = STB(Br.ReadBytes(10))
                    Prj.LGVersino = STB(Br.ReadBytes(10))
                    Select Case Prj.LGVersino
                        Case "2009123100", "2010030700", "2010031400"
                            Prj.LGVersino = StartVersion
                    End Select
                    Select Case Prj.UIVersion
                        Case "2009123100", "2010030700", "2010031400"
                            Prj.UIVersion = StartVersion
                    End Select
                    Prj.Name = STB(Br.ReadBytes(100))
                    Prj.Desc = STB(Br.ReadBytes(256))
                    Prj.MakeTime = STB(Br.ReadBytes(19))
                    Prj.EditTime = STB(Br.ReadBytes(19))
                    Prj.Password = STB(Br.ReadBytes(8)) '//암호에 8바이트할당한다. 즉 8개의문자가가능 한글은 불가로한다
                    ' MsgBox(Br.BaseStream.Position)

                    '//DS1 데이터초기화 및 오픈
                    DSET1.Clear() : DSET1.AcceptChanges()
                    Dim DS1Len As Int64 = Br.ReadInt64
                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1Len, MsgBoxStyle.Information, Hex(DS1Len))
                    Dim DS1() As Byte = Br.ReadBytes(CInt(DS1Len))
                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1.Length, MsgBoxStyle.Information, DS1Len)
                    Dim Ms As New IO.MemoryStream(DS1)
                    Try

                        Dim tempds As New DS()
                        tempds.ReadXml(Ms)

                        DSET1.Clear()
                        DSET1.Merge(tempds) '  DSET1.ReadXml(Ms)
                        DSET1.AcceptChanges()
                        Ms.Close()

                        tempds.Dispose()
                    Catch ex As Exception
                        MsgBox("파일이 손상되었습니다." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1 Open Error")
                    End Try

                    '//DS1가 있다면 게속 한다
                    DSETR1.Clear() : DSETR1.AcceptChanges()
                    DS1Len = Br.ReadInt64
                    DS1 = Br.ReadBytes(CInt(DS1Len))
                    Ms = New IO.MemoryStream(DS1)
                    Try

                        Dim tempds As New DS()
                        tempds.ReadXml(Ms)

                        DSETR1.Clear()
                        DSETR1.Merge(tempds) '  DSETR1.ReadXml(Ms)
                        DSETR1.AcceptChanges()

                        tempds.Dispose()

                        Ms.Close()
                    Catch ex As Exception
                        MsgBox("기존 버전의 계산결과를 가져올 수 없습니다." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds2 Open Error")
                    End Try
                    Prj.IsError = False
                Case Else
                    MsgBox("파일을 불러올 수 없습니다1", MsgBoxStyle.Critical, "불러오기실패")
                    Prj.IsError = True
            End Select


        Else
            Select Case Prj.SFType
                Case "10"   '//일반공개버전


                    SyncServer = True ' 2011.06.15 추가 공개버전은 자동적으로 공용코드와 기상코드를 동기화
                    Prj.UIVersion = STB(Br.ReadBytes(10))
                    Prj.LGVersino = STB(Br.ReadBytes(10))
                    Select Case Prj.LGVersino
                        Case "2009123100", "2010030700", "2010031400"
                            Prj.LGVersino = StartVersion
                    End Select
                    Select Case Prj.UIVersion
                        Case "2009123100", "2010030700", "2010031400"
                            Prj.UIVersion = StartVersion
                            Prj.UIVersion = StartVersion
                    End Select

                    Prj.Name = STB(Br.ReadBytes(100))
                    Prj.Desc = STB(Br.ReadBytes(256))
                    Prj.MakeTime = STB(Br.ReadBytes(19))
                    Prj.EditTime = STB(Br.ReadBytes(19))
                    ' MsgBox(Br.BaseStream.Position)

                    '//DS1 데이터초기화 및 오픈
                    DSET1.Clear() : DSET1.AcceptChanges()
                    Dim DS1Len As Int64 = Br.ReadInt64
                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1Len, MsgBoxStyle.Information, Hex(DS1Len))
                    Dim DS1() As Byte = Br.ReadBytes(CInt(DS1Len))
                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1.Length, MsgBoxStyle.Information, DS1Len)
                    Dim Ms As New IO.MemoryStream(DS1)
                    Try
                        Dim tempds As New DS()
                        tempds.ReadXml(Ms)

                        DSET1.Clear()
                        DSET1.Merge(tempds) ' DSET1.ReadXml(Ms)
                        DSET1.AcceptChanges()
                        Ms.Close()

                        tempds.Dispose()

                    Catch ex As Exception
                        MsgBox("파일이 손상되었습니다." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1 Open Error")
                    End Try

                    Prj.IsError = False
                Case Else
                    MsgBox("파일을 불러올 수 없습니다2", MsgBoxStyle.Critical, "불러오기실패")
                    Prj.IsError = True
            End Select
        End If

        Br.Close()
        FS.Close()

        pLog.Add(String.Format("Project Name={0},Desc={1},Version={2}", Prj.Name, Prj.Desc, Prj.UIVersion))

        If Not Prj.IsError Then
            Prj.Opened = True
            'e.m_initdata.Enabled = True

            'Frm_Work.MdiParent = Me
            Frm_Work.Label1.Text = "데이터를 확인하고 있습니다"
            Frm_Work.Show()

            FixData(isNew)  '//221218   chi import 기능과 공유하기 위해 데이터 보정기능을 분리

            Frm_Work.Close()

            '//weather
            Read_WeatherFile()

            Calc = New Calculator(Prj.LGVersino, DSET1, DSETR1, Result1, False)    '//계삭식클래스 초기화
            Me.bt_filesave.Enabled = True
            'Me.bt_newsave.Enabled = True
            Refresh_info()  '//화면하단의 정보창표시

            'If Prj.UserId.ToLower() <> "guest" AndAlso SyncServer Then     '//공용및 기상데이터 자동싱크
            '    pLog.Add("SyncServer ON")
            '    Read_CommonCode()
            '    Read_WeatherData()
            '    Read_ProfileData()
            'End If

            '//접수일,인증데인터확인  / 13-12-05 / arin
            Dim Drdesc As DS.tbl_DescRow = DSET1.tbl_Desc.Rows(0)
            If Drdesc.injungdate.Trim = "" Then Drdesc.injungdate = Now.ToString("yyyy-MM-dd")
            If Drdesc.jubsudate.Trim = "" Then Drdesc.jubsudate = Now.ToString("yyyy-MM-dd")
            If Drdesc.용도수수료입금일 = "" Then Drdesc.용도수수료입금일 = Now.ToString("yyyy-MM-dd")
            If Drdesc.reqdate = "" Then Drdesc.reqdate = Now.ToString("yyyy-MM-dd")
            If Drdesc.existdate = "" Then Drdesc.existdate = Now.ToString("yyyy-MM-dd")
            If Drdesc.공공 = "" Then Drdesc.공공 = "1"

            DSET1.tbl_Desc.AcceptChanges()

            '//160327 ui버젼체크
            If checkVersion AndAlso silent = False Then
                If Prj.UIVersion <> CurrentUIVersion() Then

                    If CInt(Prj.UIVersion.Substring(0, 4)) >= 2016 Then
                        MsgBox("해당 파일은 현재 프로그램과 동일한 버젼에서 생성된 파일이 아닙니다" + vbCrLf + vbCrLf +
                                                           "파일 Version : " + Prj.UIVersion + vbCrLf +
                                                           "현재 Version : " + CurrentUIVersion() + vbCrLf + vbCrLf +
                                                           "파일을 생성한 버젼과 결과 혹은 화면이 일치하지 않을 수 있습니다", MsgBoxStyle.Information, "버전확인")
                    Else
                        MsgBox("해당 파일은 현재 프로그램과 동일한 버젼에서 생성된 파일이 아닙니다" + vbCrLf + vbCrLf +
                                        "파일 Version : " + vbCrLf +
                                           "현재 Version : " + CurrentUIVersion() + vbCrLf + vbCrLf +
                                           "파일을 생성한 버젼과 결과 혹은 화면이 일치하지 않을 수 있습니다", MsgBoxStyle.Information, "버전확인")

                    End If
                End If
            End If




            '//현재 연 파일명을 기록해준다.
            Me.Save_FilHistory(Prj.FileName)
            Me.Read_FilHistory()

            Calc.validation()    '//null보정

            '//팡리명이 너무길면안되니 경로를 뺴고 딱 파일명만 보여줍니다.
            Me.lbl_filename.Text = Prj.FileName.Substring(Prj.FileName.LastIndexOf("\") + 1)



            If Prj.UserId.ToLower() <> "guest" AndAlso Not Prj.UserId.ToLower().StartsWith("user") Then '//191020

                '//Version 정보를 확인
                Dim MyVersion As String = ""
                Dim VersionInfo As ArinLogin.ArinLOgin.sVersionInfo = Nothing

                Work_msg("데이터 버젼확인중")
                '= Format(My.Application.Info.Version.Minor, "0000") & Format(My.Application.Info.Version.Build, "0000")
                Dim L As New ArinLogin.ArinLOgin

                '/공용코드버젼확인
                Try
                    MyVersion = DSET1.tbl_Desc.Rows(0)("versionc").ToString
                    If MyVersion = "" Then MyVersion = "20100101"
                Catch ex As Exception
                    MyVersion = "20100101"
                End Try

                pLog.Add(String.Format("공용코드버젼 = {0}", MyVersion))

                Try

                    VersionInfo = L.Get_LastVersion("C2")   '//버젼을 가져오는데  eco 버젼만 가져오게 바꺼야겟죵 ^^ 구분자를 넣도록 합시닷!
                    If VersionInfo.Ver <> "0" AndAlso (CInt(VersionInfo.Ver) > CInt(MyVersion)) Then   '//0은 없거나 관리안함의 뜻이므로 넘어간다.
                        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.08 추가
                            Dim Msg As New System.Text.StringBuilder
                            Msg.AppendLine("새로운 버젼이 확인되었습니다" & vbCrLf)
                            Msg.AppendLine("현재버젼:" & MyVersion & " 신규버젼:" & VersionInfo.Ver)
                            Msg.AppendLine("----------------------------------")
                            Msg.AppendLine(VersionInfo.Desc)
                            Msg.AppendLine("----------------------------------")
                            If VersionInfo.Link.Trim = "" Then VersionInfo.Link = "http://홈페이지주소"
                            ' Msg.AppendLine("신규버젼을 확인하기위한 페이지를 여시겠습니까?")
                            If MsgBox(Msg.ToString, MsgBoxStyle.Information, "버젼확인") = MsgBoxResult.Ok Then
                                'Shell("explorer " & VersionInfo.Link, AppWinStyle.NormalFocus)
                                ' End
                            End If
                        End If
                    End If
                Catch ex As Exception
                    MsgBox("공용코드 에러" & ex.Message.ToString)
                End Try

                '/표준프로파일버젼확인 '//2010.12.06 추가
                Try
                    MyVersion = DSET1.tbl_Desc.Rows(0)("versionp").ToString
                    If MyVersion = "" Then MyVersion = "20100101"
                Catch ex As Exception
                    MyVersion = "20100101"
                End Try

                pLog.Add(String.Format("표준프로파일버젼 = {0}", MyVersion))

                Try
                    VersionInfo = L.Get_LastVersion("P2")   '//버젼을 가져오는데  eco 버젼만 가져오게 바꺼야겟죵 ^^ 구분자를 넣도록 합시닷!
                    If VersionInfo.Ver <> "0" AndAlso (CInt(VersionInfo.Ver) > CInt(MyVersion)) Then   '//0은 없거나 관리안함의 뜻이므로 넘어간다.
                        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.08 추가
                            Dim Msg As New System.Text.StringBuilder
                            Msg.AppendLine("새로운 버젼이 확인되었습니다" & vbCrLf)
                            Msg.AppendLine("현재버젼:" & MyVersion & " 신규버젼:" & VersionInfo.Ver)
                            Msg.AppendLine("----------------------------------")
                            Msg.AppendLine(VersionInfo.Desc)
                            Msg.AppendLine("----------------------------------")
                            If VersionInfo.Link.Trim = "" Then VersionInfo.Link = "http://홈페이지주소"
                            ' Msg.AppendLine("신규버젼을 확인하기위한 페이지를 여시겠습니까?")
                            If MsgBox(Msg.ToString, MsgBoxStyle.Information, "버젼확인") = MsgBoxResult.Ok Then
                                'Shell("explorer " & VersionInfo.Link, AppWinStyle.NormalFocus)
                                ' End
                            End If
                        End If
                    End If
                Catch ex As Exception
                    MsgBox("표준프로파일 에러" & ex.Message.ToString)
                End Try

            End If

            Read_WeatherFile()

            Menu_건물개요()

            'fix ; custom profile (9999 -> 0002)
            If Prj.UserAuthType_Real.StartsWith("BOTH_C") = False Then
                Dim bupdate As Boolean = False
                For Each dr As DS.tbl_zoneRow In DSET1.tbl_zone
                    If dr.프로필 = "9999" Then
                        dr.프로필 = "0002"
                        dr.EndEdit()
                        bupdate = True
                    End If
                Next
                If bupdate Then DSET1.AcceptChanges()
            End If

            '/기상데이터버젼확인
            'Try
            '    MyVersion = DSET1.tbl_Desc.Rows(0)("versionw").ToString
            '    If MyVersion = "" Then MyVersion = "20100101"
            'Catch ex As Exception
            '    MyVersion = "20100101"
            'End Try

            'pLog.Add(String.Format("기상데이터버젼 = {0}", MyVersion))
            'If Prj.UserId.ToLower() <> "guest" AndAlso Not Prj.UserId.ToLower().StartsWith("user") Then '//191020
            '    Try
            '        'MyVersion = DSET1.tbl_Desc.Rows(0)("versionw").ToString
            '        VersionInfo = L.Get_LastVersion("W2")   '//버젼을 가져오는데  eco 버젼만 가져오게 바꺼야겟죵 ^^ 구분자를 넣도록 합시닷!
            '        If VersionInfo.Ver <> "0" AndAlso (CInt(VersionInfo.Ver) > CInt(MyVersion)) Then   '//0은 없거나 관리안함의 뜻이므로 넘어간다.
            '            If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.08 추가
            '                Dim Msg As New System.Text.StringBuilder
            '                Msg.AppendLine("새로운 버젼이 확인되었습니다" & vbCrLf)
            '                Msg.AppendLine("현재버젼:" & MyVersion & " 신규버젼:" & VersionInfo.Ver)
            '                Msg.AppendLine("----------------------------------")
            '                Msg.AppendLine(VersionInfo.Desc)
            '                Msg.AppendLine("----------------------------------")
            '                If VersionInfo.Link.Trim = "" Then VersionInfo.Link = "http://홈페이지주소"
            '                ' Msg.AppendLine("신규버젼을 확인하기위한 페이지를 여시겠습니까?")
            '                If MsgBox(Msg.ToString, MsgBoxStyle.Information, "버젼확인") = MsgBoxResult.Ok Then
            '                    'Shell("explorer " & VersionInfo.Link, AppWinStyle.NormalFocus)
            '                    ' End
            '                End If
            '            End If
            '        End If
            '    Catch ex As Exception

            '    End Try
            'End If

            '//remove profile data 0023~0027   241229
            For Each dr As DS.tbl_profileRow In DSET1.tbl_profile
                If dr.code >= "0023" AndAlso dr.code <= "0027" Then
                    dr.Delete()
                End If
            Next
            DSET1.tbl_profile.AcceptChanges()


            Pub.Update_열관류율_140409()


            PrjChanged = False

            Me.RefreshMenuList("")
            Work_msg("")
            pLog.Add("FileOpened")

            '//백업기능을 넣는다 160509
            If Not FileName.ToLower.StartsWith("open_") Then
                Dim bakdi As New System.IO.DirectoryInfo(My.Application.Info.DirectoryPath & "\Backup")
                If bakdi.Exists = False Then bakdi.Create()
                Dim oldfi As New System.IO.FileInfo(FileName)
                Dim newfi As New System.IO.FileInfo(bakdi.FullName + "\open_" + oldfi.Name)
                Try
                    oldfi.CopyTo(newfi.FullName)
                Catch ex As Exception
                    pLog.Add("backup 실패 old=" + oldfi.FullName + ",new=" + newfi.FullName)
                End Try
            End If

            Return True

        Else
            pLog.Add("Open File Error", True)

            '//파일불러오기 실패로인해서 다음처리를 하지않는다.
            If silent = False Then
                Dim bakdi As New System.IO.DirectoryInfo(My.Application.Info.DirectoryPath & "\Backup")
                Dim oldfi As New System.IO.FileInfo(FileName)
                Dim newfi As New System.IO.FileInfo(bakdi.FullName + "\open_" + oldfi.Name)
                If newfi.Exists Then
                    If MsgBox("백업된 파일이 존재합니다." + vbCrLf + vbCrLf +
                              "백업일자 : " + newfi.CreationTime.ToShortDateString + " " + newfi.CreationTime.ToShortTimeString + vbCrLf + "백업된 파일을 불러오시겠습니까?", MsgBoxStyle.YesNo Or MsgBoxStyle.Question, "확인") = MsgBoxResult.Yes Then
                        Open_File(newfi.FullName)
                    End If
                End If
            End If
            Return False
        End If

    End Function

    Sub FixData(isNew As Boolean)

        If DSET1.tbl_buha.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_buha.Rows.Add(New String() {"0", "(없음)"})
        If DSET1.tbl_bunbae.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_bunbae.Rows.Add(New String() {"0", "(없음)"})
        If DSET1.tbl_kongjo.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_kongjo.Rows.Add(New String() {"0", "(없음)"})
        If DSET1.tbl_kongkub.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_kongkub.Rows.Add(New String() {"0", "(없음)"})
        If DSET1.tbl_myoun.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_myoun.Rows.Add(New String() {"0", "(없음)"})
        If DSET1.tbl_nanbangkiki.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_nanbangkiki.Rows.Add(New String() {"0", "(없음)"})
        If DSET1.tbl_nangbangkiki.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_nangbangkiki.Rows.Add(New String() {"0", "(없음)"})
        If DSET1.tbl_nbunbae.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_nbunbae.Rows.Add(New String() {"0", "(없음)"})
        If DSET1.tbl_new.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_new.Rows.Add(New String() {"0", "(없음)"})
        If DSET1.tbl_profile.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_profile.Rows.Add(New String() {"0", "(없음)"})
        If DSET1.tbl_weather.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_weather.Rows.Add(New String() {"0", "(없음)"})
        If DSET1.tbl_zone.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_zone.Rows.Add(New String() {"0", "(없음)"})
        If DSET1.tbl_yk.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_yk.Rows.Add(New String() {"0", "(없음)"})
        If DSET1.tbl_Desc.Rows.Count < 1 Then
            MsgBox("건물개요데이터가 없으므로 초기자료를 생성합니다", MsgBoxStyle.Critical, "확인")
            Dim newdescdr As DS.tbl_DescRow = DSET1.tbl_Desc.NewRow
            newdescdr.name = "오류"
            newdescdr.buildarea = "010100"
            DSET1.tbl_Desc.Addtbl_DescRow(newdescdr)
            DSET1.tbl_Desc.AcceptChanges()
        Else
            If isNew Then   '//신규작성파일이 ㄴ경우
                Dim drDesc1 As DS.tbl_DescRow = DSET1.tbl_Desc.Rows(0)
                drDesc1.buildarea = "010100" '//서울로 지정
                drDesc1.EndEdit()
            End If

        End If


        '//건물용도기본값
        Dim 용도 As String = DSET1.tbl_Desc.Rows(0)("isjugo").ToString
        If IsNumeric(용도) = False Then
            pLog.Add(String.Format("건물개요의 용도값이 숫자가아니므로 1로 설정합니다"))
            DSET1.tbl_Desc.Rows(0)("isjugo") = "1"
        End If

        '//그룹명이없는경우 처리함(130810:arin)
        For Each dr As DS.tbl_zoneRow In DSET1.tbl_zone.Select("isnull(그룹,'')=''")
            pLog.Add(String.Format("그룹명이없는 경우이므로 '기본'으로 설정합니다 Zone Code={0}", dr.code))
            dr.그룹 = "기본"
        Next

        '//월별에너지사용량데이터영역생성(130819:arin)
        If DSET1.tbl_monuse.Rows.Count = 0 Then
            For y As Integer = 1 To 3
                Dim idx As String = y.ToString("0000")
                For i As Integer = 1 To 12
                    DSET1.tbl_monuse.Rows.Add(New String() {y.ToString() + "차년도", i.ToString("00"), "0", "0", "0", idx})   '//년,월,도시가스,전력,지역난방,코드
                Next
            Next
        End If

        '//140808 데이터 기본값 처리
        '//입력존
        If Not DSET1 Is Nothing Then
            For i As Integer = 1 To DSET1.tbl_zone.Rows.Count

                '//순실체적 재계산  150111
                '순실체적NTb.Text = TOST(TOSG(면적NTb.Text) * TOSG(천장고NTb.Text))
                Dim 면적 As String = ""
                Dim 천장고 As String = ""
                Dim 순실체적 As String = ""
                Try
                    면적 = DSET1.tbl_zone.Rows(i - 1)("면적").ToString
                Catch ex As Exception
                    면적 = ""
                End Try
                Try
                    천장고 = DSET1.tbl_zone.Rows(i - 1)("천장고p").ToString
                Catch ex As Exception
                    천장고 = ""
                End Try
                Try
                    순실체적 = DSET1.tbl_zone.Rows(i - 1)("순실체적").ToString
                Catch ex As Exception
                    순실체적 = ""
                End Try
                If IsNumeric(면적) AndAlso IsNumeric(천장고) Then
                    If Not IsNumeric(순실체적) Then
                        ' MsgBox("순실체적값이 없으므로 재계산 합니다", MsgBoxStyle.Information, "확인")
                        DSET1.tbl_zone.Rows(i - 1)("순실체적") = CSng(면적) * CSng(천장고)
                    End If
                End If
                If DSET1.tbl_zone.Rows(i - 1).RowState = DataRowState.Deleted OrElse
                    DSET1.tbl_zone.Rows(i - 1).RowState = DataRowState.Detached Then
                    Continue For
                End If
                Dim StrCode As String = DSET1.tbl_zone.Rows(i - 1)("code").ToString
                If StrCode.Length = 4 Then
                    DSET1.tbl_zone.Rows(i - 1)("code") = "0" + StrCode
                End If
            Next
            DSET1.tbl_zone.AcceptChanges()
        End If

        If Not DSET2 Is Nothing Then
            For i As Integer = 1 To DSET2.tbl_zone.Rows.Count
                If DSET2.tbl_zone.Rows(i - 1).RowState = DataRowState.Deleted OrElse
                    DSET2.tbl_zone.Rows(i - 1).RowState = DataRowState.Detached Then
                    Continue For
                End If
                Dim StrCode As String = DSET2.tbl_zone.Rows(i - 1)("code").ToString
                If StrCode.Length = 4 Then
                    DSET2.tbl_zone.Rows(i - 1)("code") = "0" + StrCode
                End If
            Next
            DSET2.tbl_zone.AcceptChanges()
        End If

        '//입력면
        If Not DSET1 Is Nothing Then
            For i As Integer = 1 To DSET1.tbl_myoun.Rows.Count
                If DSET1.tbl_myoun.Rows(i - 1).RowState = DataRowState.Deleted OrElse
                    DSET1.tbl_myoun.Rows(i - 1).RowState = DataRowState.Detached Then
                    Continue For
                End If
                Dim StrCode As String = DSET1.tbl_myoun.Rows(i - 1)("code").ToString
                If StrCode.Length = 4 Then
                    DSET1.tbl_myoun.Rows(i - 1)("code") = "0" + StrCode
                End If

                Dim StrCode2 As String = DSET1.tbl_myoun.Rows(i - 1)("존분류").ToString
                If StrCode2.Length = 4 Then
                    DSET1.tbl_myoun.Rows(i - 1)("존분류") = "0" + StrCode2
                End If
            Next
            DSET1.tbl_myoun.AcceptChanges()
        End If

        If Not DSET2 Is Nothing Then
            For i As Integer = 1 To DSET2.tbl_myoun.Rows.Count
                If DSET2.tbl_myoun.Rows(i - 1).RowState = DataRowState.Deleted OrElse
                    DSET2.tbl_myoun.Rows(i - 1).RowState = DataRowState.Detached Then
                    Continue For
                End If
                Dim StrCode As String = DSET2.tbl_myoun.Rows(i - 1)("code").ToString
                If StrCode.Length = 4 Then
                    DSET2.tbl_myoun.Rows(i - 1)("code") = "0" + StrCode
                End If

                Dim StrCode2 As String = DSET2.tbl_myoun.Rows(i - 1)("존분류").ToString
                If StrCode2.Length = 4 Then
                    DSET2.tbl_myoun.Rows(i - 1)("존분류") = "0" + StrCode2
                End If

            Next
            DSET2.tbl_myoun.AcceptChanges()
        End If

    End Sub


    Dim batchfolder As String
    Public Sub Open_File_and_update_profile(ByVal path As String)
        '//지정한 폴더내의 모든 파일의 프로필을 업데이트한다.

        '//기존선택된 트리노드를 제거한다.
        Me.PreNode = Nothing
        pLog.Add("=======================================")
        pLog.Add(String.Format("folder = {0}", path))
        'pLog.Add(String.Format("targetfile File = {0}", targetfile))
        pLog.Add("=======================================", True)
        Prj_test.IsError = False '//160509
        Dim di As New System.IO.DirectoryInfo(path)

        prb1.Value = 0
        prb1.Maximum = di.GetFiles().Length

        For Each File As System.IO.FileInfo In di.GetFiles()

            If prb1.Value < prb1.Maximum Then prb1.Value += 1

            If File.Extension.ToUpper() <> ".TPL" AndAlso File.Extension.ToUpper() <> ".TPLX" Then Continue For
            If File.Name.ToUpper().EndsWith("_PROFILEUPDATE.TPL") OrElse File.Name.ToUpper().EndsWith("_PROFILEUPDATE.TPLX") Then Continue For



            '//파일을 열어서 템플릿이름을 가져온다
            pLog.Add(String.Format("open File = {0}", File.FullName))
            Dim FI As New System.IO.FileInfo(File.FullName)
            Dim Desbuf() As Byte = {}
            Dim FS As System.IO.Stream
            '///////////////////////////////////////////////////////////////////////////////////////////////////2011.03.16 입력파일 변조
            If Not (Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1") Then  '//2011.03.16 추가 //eco 파일 불러올때 ADMIN 제거 'Prj.UserAuthType = "ADMIN" OrElse 
                Dim Source() As Byte = My.Computer.FileSystem.ReadAllBytes(FI.FullName)

                If Source.Length < 4 Then
                    Prj.IsError = True
                    MsgboxE("알수없거나 손상된 파일입니다" + vbCrLf + FI.FullName, True)
                    Return
                End If
                pLog.Add("암호화 해제")
                Desbuf = DeCryptArea(Source, New Byte() {&HAC, &H29, &H55, &H42})

            Else
                Desbuf = System.IO.File.ReadAllBytes(FI.FullName)
                ' FS = New IO.FileStream(FileName, IO.FileMode.Open)
            End If

            If FI.Extension.ToLower().EndsWith("x") Then    '//확장자가 x로끝나면 압축된 포맷
                Dim datalen As Integer = BitConverter.ToInt32(Desbuf, 0)
                Dim RealData(Desbuf.Length - 4 - 1) As Byte
                Array.Copy(Desbuf, 4, RealData, 0, RealData.Length)
                Dim DeCompress(datalen - 1) As Byte
                Array.Clear(DeCompress, 0, DeCompress.Length)
                Utility.MiniLZO.Decompress(RealData, DeCompress)
                Array.Resize(Desbuf, DeCompress.Length)
                Array.Clear(Desbuf, 0, Desbuf.Length)
                Array.Copy(DeCompress, Desbuf, Desbuf.Length)
            End If



            FS = New IO.MemoryStream(Desbuf, True)

            '///////////////////////////////////////////////////////////////////////////////////////////////////2011.03.16 입력파일 변조

            Dim Br As New IO.BinaryReader(FS, System.Text.Encoding.Default)
            Prj_test.FileName = File.FullName ' : Myini.Write("presetting", "filename", Prj.FileName)
            Prj_test.Opened = False


            '//세이브파일구조(2)
            Prj_test.SFType = STB(Br.ReadBytes(2))
            pLog.Add("File Type = " + Prj_test.SFType)

            'im DSET1 As New DS()

            If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가 //eco 파일 불러올때 ADMIN 제거 'Prj.UserAuthType = "ADMIN" OrElse 

                Select Case Prj.SFType
                    Case "00"   '//기본버젼
                        Prj_test.UIVersion = STB(Br.ReadBytes(10))
                        Prj_test.LGVersino = STB(Br.ReadBytes(10))
                        Select Case Prj_test.LGVersino
                            Case "2009123100", "2010030700", "2010031400"
                                Prj_test.LGVersino = StartVersion
                        End Select
                        Select Case Prj_test.UIVersion
                            Case "2009123100", "2010030700", "2010031400"
                                Prj_test.UIVersion = StartVersion
                                Prj_test.UIVersion = StartVersion
                        End Select

                        Prj_test.Name = STB(Br.ReadBytes(100))
                        Prj_test.Desc = STB(Br.ReadBytes(256))
                        Prj_test.MakeTime = STB(Br.ReadBytes(19))
                        Prj_test.EditTime = STB(Br.ReadBytes(19))
                        ' MsgBox(Br.BaseStream.Position)

                        '//DS1 데이터초기화 및 오픈
                        DSET1_TEST.Clear() : DSET1_TEST.AcceptChanges()
                        Dim DS1Len As Int64 = Br.ReadInt64
                        If DS1Len = 0 Then
                            DS1Len = FS.Length - Br.BaseStream.Position - 2
                        End If
                        'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1Len, MsgBoxStyle.Information, Hex(DS1Len))
                        Dim DS1() As Byte = Nothing
                        Try
                            DS1 = Br.ReadBytes(CInt(DS1Len))
                        Catch ex As Exception
                            Prj_test.IsError = True
                            MsgBox("파일이 손상되었습니다(Read Data Array)." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1 byteRead Error")
                        End Try

                        'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1.Length, MsgBoxStyle.Information, DS1Len)
                        If Not Prj_test.IsError Then
                            Dim Ms As New IO.MemoryStream(DS1)
                            Try
                                DSET1_TEST.ReadXml(Ms)
                                DSET1_TEST.AcceptChanges()
                                Ms.Close()
                            Catch ex As Exception
                                Prj_test.IsError = True
                                MsgBox("파일이 손상되었습니다(Read DataSet)" & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1_test Open Error")
                            End Try

                            If Prj_test.IsError Then
                                MsgBox("load error")
                            Else
                                '//에러가없는경우 다음진행
                                DSET1_TEST.AcceptChanges()



                                'remove old data
                                DSET1_TEST.tbl_profile.Clear()
                                DSET1_TEST.AcceptChanges()

                                'merge data
                                DSET1_TEST.tbl_profile.Merge(DSET1.tbl_profile)
                                DSET1_TEST.AcceptChanges()


                                '//save file
                                Dim newfile As String = File.FullName.Replace(File.Extension, "") + "_ProfileUpdate" + FI.Extension
                                Save_File(DSET1_TEST, DSETR1, newfile, False, False)
                                ' MsgBox("(weather+profile) load ok")

                                '//DS1가 있다면 게속 한다
                                'DSETR1.Clear() : DSETR1.AcceptChanges()
                                'DS1Len = Br.ReadInt64
                                'DS1 = Br.ReadBytes(CInt(DS1Len))
                                'Ms = New IO.MemoryStream(DS1)
                                'Try
                                '    DSETR1.ReadXml(Ms)
                                '    DSETR1.AcceptChanges()
                                '    Ms.Close()
                                'Catch ex As Exception
                                '    MsgBox("기존 버전의 계산결과를 가져올 수 없습니다." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds2 Open Error")
                                'End Try

                                Prj.IsError = False

                                pLog.Add(String.Format("batch update profile file={0}", newfile))

                            End If


                        End If


                    Case Else
                        MsgBox("파일을 불러올 수 없습니다1", MsgBoxStyle.Critical, "불러오기실패")
                        Prj.IsError = True
                End Select

            End If

            Br.Close()
            FS.Close()

            pLog.Add(String.Format("batch update profile Name={0},Desc={1},Version={2}", Prj.Name, Prj.Desc, Prj.UIVersion))


        Next


        MsgboxI("update complete")




    End Sub


    Public Sub Open_File_Only_weather(ByVal FileName As String, Optional ByVal SyncServer As Boolean = False, Optional checkVersion As Boolean = True, Optional silent As Boolean = False, Optional isNew As Boolean = False)


        '//기존선택된 트리노드를 제거한다.
        Me.PreNode = Nothing
        pLog.Add("=======================================")
        pLog.Add(String.Format("Open File = {0}", FileName))
        pLog.Add("=======================================", True)
        Prj_test.IsError = False '//160509

        '//파일을 열어서 템플릿이름을 가져온다
        Dim FI As New System.IO.FileInfo(FileName)
        Dim Desbuf() As Byte = {}
        Dim FS As System.IO.Stream
        '///////////////////////////////////////////////////////////////////////////////////////////////////2011.03.16 입력파일 변조
        If Not (Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1") Then  '//2011.03.16 추가 //eco 파일 불러올때 ADMIN 제거 'Prj.UserAuthType = "ADMIN" OrElse 
            Dim Source() As Byte = My.Computer.FileSystem.ReadAllBytes(FI.FullName)

            If Source.Length < 4 Then
                Prj.IsError = True
                MsgboxE("알수없거나 손상된 파일입니다" + vbCrLf + FI.FullName, True)
                Return
            End If
            pLog.Add("암호화 해제")
            Desbuf = DeCryptArea(Source, New Byte() {&HAC, &H29, &H55, &H42})

        Else
            Desbuf = System.IO.File.ReadAllBytes(FileName)
            ' FS = New IO.FileStream(FileName, IO.FileMode.Open)
        End If

        If FI.Extension.ToLower().EndsWith("x") Then    '//확장자가 x로끝나면 압축된 포맷
            Dim datalen As Integer = BitConverter.ToInt32(Desbuf, 0)
            Dim RealData(Desbuf.Length - 4 - 1) As Byte
            Array.Copy(Desbuf, 4, RealData, 0, RealData.Length)
            Dim DeCompress(datalen - 1) As Byte
            Array.Clear(DeCompress, 0, DeCompress.Length)
            Utility.MiniLZO.Decompress(RealData, DeCompress)
            Array.Resize(Desbuf, DeCompress.Length)
            Array.Clear(Desbuf, 0, Desbuf.Length)
            Array.Copy(DeCompress, Desbuf, Desbuf.Length)
        End If



        FS = New IO.MemoryStream(Desbuf, True)

        '///////////////////////////////////////////////////////////////////////////////////////////////////2011.03.16 입력파일 변조

        Dim Br As New IO.BinaryReader(FS, System.Text.Encoding.Default)
        Prj_test.FileName = FileName ' : Myini.Write("presetting", "filename", Prj.FileName)
        Prj_test.Opened = False


        '//세이브파일구조(2)
        Prj_test.SFType = STB(Br.ReadBytes(2))
        pLog.Add("File Type = " + Prj_test.SFType)

        'im DSET1 As New DS()

        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가 //eco 파일 불러올때 ADMIN 제거 'Prj.UserAuthType = "ADMIN" OrElse 

            Select Case Prj.SFType
                Case "00"   '//기본버젼
                    Prj_test.UIVersion = STB(Br.ReadBytes(10))
                    Prj_test.LGVersino = STB(Br.ReadBytes(10))
                    Select Case Prj_test.LGVersino
                        Case "2009123100", "2010030700", "2010031400"
                            Prj_test.LGVersino = StartVersion
                    End Select
                    Select Case Prj_test.UIVersion
                        Case "2009123100", "2010030700", "2010031400"
                            Prj_test.UIVersion = StartVersion
                            Prj_test.UIVersion = StartVersion
                    End Select

                    Prj_test.Name = STB(Br.ReadBytes(100))
                    Prj_test.Desc = STB(Br.ReadBytes(256))
                    Prj_test.MakeTime = STB(Br.ReadBytes(19))
                    Prj_test.EditTime = STB(Br.ReadBytes(19))
                    ' MsgBox(Br.BaseStream.Position)

                    '//DS1 데이터초기화 및 오픈
                    DSET1_TEST.Clear() : DSET1_TEST.AcceptChanges()
                    Dim DS1Len As Int64 = Br.ReadInt64
                    If DS1Len = 0 Then
                        DS1Len = FS.Length - Br.BaseStream.Position - 2
                    End If
                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1Len, MsgBoxStyle.Information, Hex(DS1Len))
                    Dim DS1() As Byte = Nothing
                    Try
                        DS1 = Br.ReadBytes(CInt(DS1Len))
                    Catch ex As Exception
                        Prj_test.IsError = True
                        MsgBox("파일이 손상되었습니다(Read Data Array)." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1 byteRead Error")
                    End Try

                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1.Length, MsgBoxStyle.Information, DS1Len)
                    If Not Prj_test.IsError Then
                        Dim Ms As New IO.MemoryStream(DS1)
                        Try
                            DSET1_TEST.ReadXml(Ms)
                            DSET1_TEST.AcceptChanges()
                            Ms.Close()
                        Catch ex As Exception
                            Prj_test.IsError = True
                            MsgBox("파일이 손상되었습니다(Read DataSet)" & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1_test Open Error")
                        End Try

                        If Prj_test.IsError Then
                            MsgBox("load error")
                        Else
                            '//에러가없는경우 다음진행
                            DSET1_TEST.AcceptChanges()



                            'remove old data
                            DSET1.weather_cha.Clear()
                            DSET1.weather_group.Clear()
                            DSET1.weather_ilsa.Clear()
                            DSET1.weather_supdo.Clear()
                            DSET1.weather_temp.Clear()
                            DSET1.tbl_weather.Clear()
                            DSET1.tbl_profile.Clear()
                            DSET1.AcceptChanges()

                            'merge data
                            DSET1.weather_cha.Merge(DSET1_TEST.weather_cha)
                            DSET1.weather_group.Merge(DSET1_TEST.weather_group)
                            DSET1.weather_ilsa.Merge(DSET1_TEST.weather_ilsa)
                            DSET1.weather_supdo.Merge(DSET1_TEST.weather_supdo)
                            DSET1.weather_temp.Merge(DSET1_TEST.weather_temp)
                            DSET1.tbl_weather.Merge(DSET1_TEST.tbl_weather)
                            DSET1.tbl_profile.Merge(DSET1_TEST.tbl_profile)
                            DSET1.AcceptChanges()

                            MsgBox("(weather+profile) load ok")

                            '//DS1가 있다면 게속 한다
                            'DSETR1.Clear() : DSETR1.AcceptChanges()
                            'DS1Len = Br.ReadInt64
                            'DS1 = Br.ReadBytes(CInt(DS1Len))
                            'Ms = New IO.MemoryStream(DS1)
                            'Try
                            '    DSETR1.ReadXml(Ms)
                            '    DSETR1.AcceptChanges()
                            '    Ms.Close()
                            'Catch ex As Exception
                            '    MsgBox("기존 버전의 계산결과를 가져올 수 없습니다." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds2 Open Error")
                            'End Try

                            Prj.IsError = False

                        End If


                    End If


                Case Else
                    MsgBox("파일을 불러올 수 없습니다1", MsgBoxStyle.Critical, "불러오기실패")
                    Prj.IsError = True
            End Select

        End If

        Br.Close()
        FS.Close()

        pLog.Add(String.Format("Project Name={0},Desc={1},Version={2}", Prj.Name, Prj.Desc, Prj.UIVersion))



    End Sub

    Public Sub Open_File_checker(ByVal FileName As String, Optional ByVal SyncServer As Boolean = False, Optional checkVersion As Boolean = True, Optional silent As Boolean = False, Optional isNew As Boolean = False)


        '//기존선택된 트리노드를 제거한다.
        Me.PreNode = Nothing
        pLog.Add("=======================================")
        pLog.Add(String.Format("Open File = {0}", FileName))
        pLog.Add("=======================================", True)
        Prj_test.IsError = False '//160509

        '//파일을 열어서 템플릿이름을 가져온다
        Dim FI As New System.IO.FileInfo(FileName)
        Dim Desbuf() As Byte = {}
        Dim FS As System.IO.Stream
        '///////////////////////////////////////////////////////////////////////////////////////////////////2011.03.16 입력파일 변조
        If Not (Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1") Then  '//2011.03.16 추가 //eco 파일 불러올때 ADMIN 제거 'Prj.UserAuthType = "ADMIN" OrElse 
            Dim Source() As Byte = My.Computer.FileSystem.ReadAllBytes(FI.FullName)

            If Source.Length < 4 Then
                Prj.IsError = True
                MsgboxE("알수없거나 손상된 파일입니다" + vbCrLf + FI.FullName, True)
                Return
            End If
            pLog.Add("암호화 해제")
            Desbuf = DeCryptArea(Source, New Byte() {&HAC, &H29, &H55, &H42})

        Else
            Desbuf = System.IO.File.ReadAllBytes(FileName)
            ' FS = New IO.FileStream(FileName, IO.FileMode.Open)
        End If

        If FI.Extension.ToLower().EndsWith("x") Then    '//확장자가 x로끝나면 압축된 포맷
            Dim datalen As Integer = BitConverter.ToInt32(Desbuf, 0)
            Dim RealData(Desbuf.Length - 4 - 1) As Byte
            Array.Copy(Desbuf, 4, RealData, 0, RealData.Length)
            Dim DeCompress(datalen - 1) As Byte
            Array.Clear(DeCompress, 0, DeCompress.Length)
            Utility.MiniLZO.Decompress(RealData, DeCompress)
            Array.Resize(Desbuf, DeCompress.Length)
            Array.Clear(Desbuf, 0, Desbuf.Length)
            Array.Copy(DeCompress, Desbuf, Desbuf.Length)
        End If



        FS = New IO.MemoryStream(Desbuf, True)

        '///////////////////////////////////////////////////////////////////////////////////////////////////2011.03.16 입력파일 변조

        Dim Br As New IO.BinaryReader(FS, System.Text.Encoding.Default)
        Prj_test.FileName = FileName ' : Myini.Write("presetting", "filename", Prj.FileName)
        Prj_test.Opened = False


        '//세이브파일구조(2)
        Prj_test.SFType = STB(Br.ReadBytes(2))
        pLog.Add("File Type = " + Prj_test.SFType)

        'im DSET1 As New DS()

        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가 //eco 파일 불러올때 ADMIN 제거 'Prj.UserAuthType = "ADMIN" OrElse 

            Select Case Prj.SFType
                Case "00"   '//기본버젼
                    Prj_test.UIVersion = STB(Br.ReadBytes(10))
                    Prj_test.LGVersino = STB(Br.ReadBytes(10))
                    Select Case Prj_test.LGVersino
                        Case "2009123100", "2010030700", "2010031400"
                            Prj_test.LGVersino = StartVersion
                    End Select
                    Select Case Prj_test.UIVersion
                        Case "2009123100", "2010030700", "2010031400"
                            Prj_test.UIVersion = StartVersion
                            Prj_test.UIVersion = StartVersion
                    End Select

                    Prj_test.Name = STB(Br.ReadBytes(100))
                    Prj_test.Desc = STB(Br.ReadBytes(256))
                    Prj_test.MakeTime = STB(Br.ReadBytes(19))
                    Prj_test.EditTime = STB(Br.ReadBytes(19))
                    ' MsgBox(Br.BaseStream.Position)

                    '//DS1 데이터초기화 및 오픈
                    DSET1_TEST.Clear() : DSET1_TEST.AcceptChanges()
                    Dim DS1Len As Int64 = Br.ReadInt64
                    If DS1Len = 0 Then
                        DS1Len = FS.Length - Br.BaseStream.Position - 2
                    End If
                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1Len, MsgBoxStyle.Information, Hex(DS1Len))
                    Dim DS1() As Byte = Nothing
                    Try
                        DS1 = Br.ReadBytes(CInt(DS1Len))
                    Catch ex As Exception
                        Prj_test.IsError = True
                        MsgBox("파일이 손상되었습니다(Read Data Array)." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1 byteRead Error")
                    End Try

                    'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1.Length, MsgBoxStyle.Information, DS1Len)
                    If Not Prj_test.IsError Then
                        Dim Ms As New IO.MemoryStream(DS1)
                        Try
                            DSET1_TEST.ReadXml(Ms)
                            DSET1_TEST.AcceptChanges()
                            Ms.Close()
                        Catch ex As Exception
                            Prj_test.IsError = True
                            MsgBox("파일이 손상되었습니다(Read DataSet)" & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1_test Open Error")
                        End Try

                        If Prj_test.IsError Then
                            MsgBox("load error")
                        Else
                            '//에러가없는경우 다음진행
                            DSET1_TEST.AcceptChanges()


                            Dim sb As New System.Text.StringBuilder()

                            For Each dt As DataTable In DSET1.Tables
                                If dt.TableName.StartsWith("weather") Then
                                    If dt.Columns.Contains("pcode") Then

                                        Dim dt1 As DataTable = DSET1_TEST.Tables(dt.TableName)
                                        For Each dr As DataRow In dt.Rows
                                            Dim drows() As DataRow = dt1.Select("pcode='" + dr("pcode").ToString() + "' and code='" + dr("code").ToString() + "'")
                                            If drows.Length <> 1 Then
                                                '//too many
                                                sb.AppendLine("table many rows " + dt.TableName + "pcode='" + dr("pcode").ToString() + "' and code='" + dr("code").ToString() + "'")
                                            Else
                                                '//ok
                                                Dim dr1 As DataRow = drows(0)
                                                For Each dc As DataColumn In dt.Columns

                                                    If dr(dc.ColumnName) Is DBNull.Value Then
                                                        If dr1(dc.ColumnName) Is DBNull.Value Then

                                                        Else
                                                            sb.AppendLine("table diff value " + dt.TableName + "pcode='" + dr("pcode").ToString() + "' and code='" + dr("code").ToString() + "',column=" + dc.ColumnName + ",org=null,new=" + dr1(dc.ColumnName))
                                                        End If
                                                    ElseIf dr(dc.ColumnName) <> dr1(dc.ColumnName) Then
                                                        sb.AppendLine("table diff value " + dt.TableName + "pcode='" + dr("pcode").ToString() + "' and code='" + dr("code").ToString() + "',column=" + dc.ColumnName + ",org=" + dr(dc.ColumnName) + ",new=" + dr1(dc.ColumnName))
                                                    End If
                                                Next
                                            End If
                                        Next
                                    Else
                                        Dim dt1 As DataTable = DSET1_TEST.Tables(dt.TableName)
                                        For Each dr As DataRow In dt.Rows
                                            Dim drows() As DataRow = dt1.Select("code='" + dr("code").ToString() + "'")
                                            If drows.Length <> 1 Then
                                                '//too many
                                                sb.AppendLine("table many rows " + dt.TableName + "' and code='" + dr("code").ToString() + "'")
                                            Else
                                                '//ok
                                                Dim dr1 As DataRow = drows(0)
                                                For Each dc As DataColumn In dt.Columns
                                                    If dr(dc.ColumnName) Is DBNull.Value Then
                                                        If dr1(dc.ColumnName) Is DBNull.Value Then

                                                        Else
                                                            sb.AppendLine("table diff value " + dt.TableName + " code='" + dr("code").ToString() + "',column=" + dc.ColumnName + ",org=null,new=" + dr1(dc.ColumnName))
                                                        End If
                                                    ElseIf dr(dc.ColumnName) <> dr1(dc.ColumnName) Then
                                                        sb.AppendLine("table diff value " + dt.TableName + " code='" + dr("code").ToString() + "',column=" + dc.ColumnName + ",org=" + dr(dc.ColumnName) + ",new=" + dr1(dc.ColumnName))
                                                    End If
                                                Next
                                            End If
                                        Next
                                    End If
                                End If
                            Next


                            ' MsgboxI(sb.ToString())

                            Dim fn As String = "C:\ECO2\diff.txt"
                            System.IO.File.WriteAllText(fn, sb.ToString(), System.Text.Encoding.Default)
                            'Dim prc As New System.Diagnostics.Process()
                            Process.Start(fn)
                            Return


                            'remove old data
                            DSET1.weather_cha.Clear()
                            DSET1.weather_group.Clear()
                            DSET1.weather_ilsa.Clear()
                            DSET1.weather_supdo.Clear()
                            DSET1.weather_temp.Clear()
                            DSET1.tbl_weather.Clear()
                            DSET1.tbl_profile.Clear()
                            DSET1.AcceptChanges()

                            'merge data
                            DSET1.weather_cha.Merge(DSET1_TEST.weather_cha)
                            DSET1.weather_group.Merge(DSET1_TEST.weather_group)
                            DSET1.weather_ilsa.Merge(DSET1_TEST.weather_ilsa)
                            DSET1.weather_supdo.Merge(DSET1_TEST.weather_supdo)
                            DSET1.weather_temp.Merge(DSET1_TEST.weather_temp)
                            DSET1.tbl_weather.Merge(DSET1_TEST.tbl_weather)
                            DSET1.tbl_profile.Merge(DSET1_TEST.tbl_profile)
                            DSET1.AcceptChanges()

                            MsgBox("(weather+profile) load ok")

                            '//DS1가 있다면 게속 한다
                            'DSETR1.Clear() : DSETR1.AcceptChanges()
                            'DS1Len = Br.ReadInt64
                            'DS1 = Br.ReadBytes(CInt(DS1Len))
                            'Ms = New IO.MemoryStream(DS1)
                            'Try
                            '    DSETR1.ReadXml(Ms)
                            '    DSETR1.AcceptChanges()
                            '    Ms.Close()
                            'Catch ex As Exception
                            '    MsgBox("기존 버전의 계산결과를 가져올 수 없습니다." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds2 Open Error")
                            'End Try

                            Prj.IsError = False

                        End If


                    End If


                Case Else
                    MsgBox("파일을 불러올 수 없습니다1", MsgBoxStyle.Critical, "불러오기실패")
                    Prj.IsError = True
            End Select

        End If

        Br.Close()
        FS.Close()

        pLog.Add(String.Format("Project Name={0},Desc={1},Version={2}", Prj.Name, Prj.Desc, Prj.UIVersion))



    End Sub

    Private GroupList_Zone As ArrayList
    Private GroupList_nanbangkiki As ArrayList
    Private GroupList_NanbangKongkub As ArrayList
    Private GroupList_Kongjo As ArrayList
    Private GroupList_NanbangBunbae As ArrayList
    Private GroupList_Naengbankiki As ArrayList
    Private GroupList_New As ArrayList
    Private GroupList_Yk As ArrayList
    Private GroupList_Bunbae As ArrayList


    Sub DeSerialize(buffer As Byte(), ByRef data As DataTable)

        'If System.IO.File.Exists(filename) = False Then Return
        'Dim ms As New MemoryStream()

        Using stm As System.IO.Stream = New System.IO.MemoryStream(buffer)
            Dim bf As System.Runtime.Serialization.Formatters.Binary.BinaryFormatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter '역직렬화 후 객체 클래스로 형변환... Dim a As clsTEST = CType(bf.Deserialize(stm), clsTEST) stm.Close()
            Dim dt As DataTable = bf.Deserialize(stm)
            data.Clear()
            data.Merge(dt)
        End Using

    End Sub

    Sub DeSerialize(filename As String, ByRef data As DataTable)

        If System.IO.File.Exists(filename) = False Then Return

        Using stm As System.IO.Stream = System.IO.File.Open(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read)
            Dim bf As System.Runtime.Serialization.Formatters.Binary.BinaryFormatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter '역직렬화 후 객체 클래스로 형변환... Dim a As clsTEST = CType(bf.Deserialize(stm), clsTEST) stm.Close()
            Dim dt As DataTable = bf.Deserialize(stm)
            data.Clear()
            data.Merge(dt)
        End Using

    End Sub
    Sub Read_WeatherFile()
        '//날씨정보는 외부파일에서 사용한다
        DSET1.weather_cha.Clear()
        DSET1.weather_ilsa.Clear()
        DSET1.weather_supdo.Clear()
        DSET1.weather_temp.Clear()
        DSET1.weather_group.Clear()

        DSET1.weather_wind.Clear()
        DSET1.weather_river.Clear()
        DSET1.weather_water.Clear()

        DSET1.tbl_weather.Clear()

        Dim DataPath As String = AppDomain.CurrentDomain.BaseDirectory + "Data"
        Dim fi1d As String = System.IO.Path.Combine(DataPath, DSET1.weather_cha.TableName + ".dat")
        Dim fi2d As String = System.IO.Path.Combine(DataPath, DSET1.weather_ilsa.TableName + ".dat")
        Dim fi3d As String = System.IO.Path.Combine(DataPath, DSET1.weather_supdo.TableName + ".dat")
        Dim fi4d As String = System.IO.Path.Combine(DataPath, DSET1.weather_temp.TableName + ".dat")
        Dim fi5d As String = System.IO.Path.Combine(DataPath, DSET1.tbl_weather.TableName + ".dat")
        Dim fi6d As String = System.IO.Path.Combine(DataPath, DSET1.weather_group.TableName + ".dat")

        Dim fi7d As String = System.IO.Path.Combine(DataPath, DSET1.weather_wind.TableName + ".dat")
        Dim fi8d As String = System.IO.Path.Combine(DataPath, DSET1.weather_river.TableName + ".dat")
        Dim fi9d As String = System.IO.Path.Combine(DataPath, DSET1.weather_water.TableName + ".dat")

        If System.IO.File.Exists(fi1d) Then

            '//check contents
            Dim buffer As String = System.IO.File.ReadAllText(fi1d, System.Text.Encoding.Default)

            Dim commpressed As Boolean
            Try
                DeSerialize(fi1d, CType(DSET1.weather_cha, DS.weather_chaDataTable))
                commpressed = False
            Catch ex As Exception
                commpressed = True
            End Try

            If commpressed = False Then
                '//class data
                DeSerialize(fi1d, CType(DSET1.weather_cha, DS.weather_chaDataTable))
                DeSerialize(fi2d, CType(DSET1.weather_ilsa, DS.weather_ilsaDataTable))
                DeSerialize(fi3d, CType(DSET1.weather_supdo, DS.weather_supdoDataTable))
                DeSerialize(fi4d, CType(DSET1.weather_temp, DS.weather_tempDataTable))
                DeSerialize(fi5d, CType(DSET1.tbl_weather, DS.tbl_weatherDataTable))
                DeSerialize(fi6d, CType(DSET1.weather_group, DS.weather_groupDataTable))
                DeSerialize(fi7d, CType(DSET1.weather_wind, DS.weather_windDataTable))
                DeSerialize(fi8d, CType(DSET1.weather_river, DS.weather_riverDataTable))
                DeSerialize(fi9d, CType(DSET1.weather_water, DS.weather_waterDataTable))
            Else
                '//lzo data
                Dim buffer1 As Byte() = System.IO.File.ReadAllBytes(fi1d)
                Dim buffer2 As Byte() = System.IO.File.ReadAllBytes(fi2d)
                Dim buffer3 As Byte() = System.IO.File.ReadAllBytes(fi3d)
                Dim buffer4 As Byte() = System.IO.File.ReadAllBytes(fi4d)
                Dim buffer5 As Byte() = System.IO.File.ReadAllBytes(fi5d)
                Dim buffer6 As Byte() = System.IO.File.ReadAllBytes(fi6d)
                Dim buffer7 As Byte() = System.IO.File.ReadAllBytes(fi7d)
                Dim buffer8 As Byte() = System.IO.File.ReadAllBytes(fi8d)
                Dim buffer9 As Byte() = System.IO.File.ReadAllBytes(fi9d)

                '데이터의 처음4바이트에는 파일 크기가 들어있음
                Dim len1 As UInt32 = BitConverter.ToUInt32(buffer1, 0)
                Dim len2 As UInt32 = BitConverter.ToUInt32(buffer2, 0)
                Dim len3 As UInt32 = BitConverter.ToUInt32(buffer3, 0)
                Dim len4 As UInt32 = BitConverter.ToUInt32(buffer4, 0)
                Dim len5 As UInt32 = BitConverter.ToUInt32(buffer5, 0)
                Dim len6 As UInt32 = BitConverter.ToUInt32(buffer6, 0)
                Dim len7 As UInt32 = BitConverter.ToUInt32(buffer7, 0)
                Dim len8 As UInt32 = BitConverter.ToUInt32(buffer8, 0)
                Dim len9 As UInt32 = BitConverter.ToUInt32(buffer9, 0)

                Dim dbuffer1(len1 - 1) As Byte
                Dim dbuffer2(len2 - 1) As Byte
                Dim dbuffer3(len3 - 1) As Byte
                Dim dbuffer4(len4 - 1) As Byte
                Dim dbuffer5(len5 - 1) As Byte
                Dim dbuffer6(len6 - 1) As Byte
                Dim dbuffer7(len7 - 1) As Byte
                Dim dbuffer8(len8 - 1) As Byte
                Dim dbuffer9(len9 - 1) As Byte

                Dim body1(buffer1.Length - 4 - 1) As Byte
                Dim body2(buffer2.Length - 4 - 1) As Byte
                Dim body3(buffer3.Length - 4 - 1) As Byte
                Dim body4(buffer4.Length - 4 - 1) As Byte
                Dim body5(buffer5.Length - 4 - 1) As Byte
                Dim body6(buffer6.Length - 4 - 1) As Byte
                Dim body7(buffer7.Length - 4 - 1) As Byte
                Dim body8(buffer8.Length - 4 - 1) As Byte
                Dim body9(buffer9.Length - 4 - 1) As Byte

                Array.Copy(buffer1, 4, body1, 0, body1.Length)
                Array.Copy(buffer2, 4, body2, 0, body2.Length)
                Array.Copy(buffer3, 4, body3, 0, body3.Length)
                Array.Copy(buffer4, 4, body4, 0, body4.Length)
                Array.Copy(buffer5, 4, body5, 0, body5.Length)
                Array.Copy(buffer6, 4, body6, 0, body6.Length)
                Array.Copy(buffer7, 4, body7, 0, body7.Length)
                Array.Copy(buffer8, 4, body8, 0, body8.Length)
                Array.Copy(buffer9, 4, body9, 0, body9.Length)


                Utility.MiniLZO.Decompress(body1, dbuffer1) '67682 -> 304964
                Utility.MiniLZO.Decompress(body2, dbuffer2)
                Utility.MiniLZO.Decompress(body3, dbuffer3)
                Utility.MiniLZO.Decompress(body4, dbuffer4)
                Utility.MiniLZO.Decompress(body5, dbuffer5)
                Utility.MiniLZO.Decompress(body6, dbuffer6)
                Utility.MiniLZO.Decompress(body7, dbuffer7)
                Utility.MiniLZO.Decompress(body8, dbuffer8)
                Utility.MiniLZO.Decompress(body9, dbuffer9)


                DeSerialize(dbuffer1, CType(DSET1.weather_cha, DS.weather_chaDataTable))
                DeSerialize(dbuffer2, CType(DSET1.weather_ilsa, DS.weather_ilsaDataTable))
                DeSerialize(dbuffer3, CType(DSET1.weather_supdo, DS.weather_supdoDataTable))
                DeSerialize(dbuffer4, CType(DSET1.weather_temp, DS.weather_tempDataTable))
                DeSerialize(dbuffer5, CType(DSET1.tbl_weather, DS.tbl_weatherDataTable))
                DeSerialize(dbuffer6, CType(DSET1.weather_group, DS.weather_groupDataTable))
                DeSerialize(dbuffer7, CType(DSET1.weather_wind, DS.weather_windDataTable))
                DeSerialize(dbuffer8, CType(DSET1.weather_river, DS.weather_riverDataTable))
                DeSerialize(dbuffer9, CType(DSET1.weather_water, DS.weather_waterDataTable))
            End If



        Else
            '//암호화파이링 없으면 원본 불러오기
            Dim fi1 As String = System.IO.Path.Combine(DataPath, DSET1.weather_cha.TableName + ".xml")
            Dim fi2 As String = System.IO.Path.Combine(DataPath, DSET1.weather_ilsa.TableName + ".xml")
            Dim fi3 As String = System.IO.Path.Combine(DataPath, DSET1.weather_supdo.TableName + ".xml")
            Dim fi4 As String = System.IO.Path.Combine(DataPath, DSET1.weather_temp.TableName + ".xml")
            Dim fi5 As String = System.IO.Path.Combine(DataPath, DSET1.tbl_weather.TableName + ".xml")
            Dim fi6 As String = System.IO.Path.Combine(DataPath, DSET1.weather_group.TableName + ".xml")

            Dim fi7 As String = System.IO.Path.Combine(DataPath, DSET1.weather_wind.TableName + ".xml")
            Dim fi8 As String = System.IO.Path.Combine(DataPath, DSET1.weather_river.TableName + ".xml")
            Dim fi9 As String = System.IO.Path.Combine(DataPath, DSET1.weather_water.TableName + ".xml")



            If System.IO.File.Exists(fi1) Then
                DSET1.weather_cha.ReadXml(fi1)
            Else
                MsgBox("날씨데이터파일#1 이 없습니다\r\n프로그램을 다시 설치하세요")
            End If
            If System.IO.File.Exists(fi2) Then
                DSET1.weather_ilsa.ReadXml(fi2)
            Else
                MsgBox("날씨데이터파일#2 이 없습니다\r\n프로그램을 다시 설치하세요")
            End If
            If System.IO.File.Exists(fi3) Then
                DSET1.weather_supdo.ReadXml(fi3)
            Else
                MsgBox("날씨데이터파일#3 이 없습니다\r\n프로그램을 다시 설치하세요")
            End If
            If System.IO.File.Exists(fi4) Then
                DSET1.weather_temp.ReadXml(fi4)
            Else
                MsgBox("날씨데이터파일#4 이 없습니다\r\n프로그램을 다시 설치하세요")
            End If
            If System.IO.File.Exists(fi5) Then
                DSET1.tbl_weather.ReadXml(fi5)
            Else
                MsgBox("날씨데이터파일#5 이 없습니다\r\n프로그램을 다시 설치하세요")
            End If
            If System.IO.File.Exists(fi6) Then
                DSET1.weather_group.ReadXml(fi6)
            Else
                MsgBox("날씨데이터파일#6 이 없습니다\r\n프로그램을 다시 설치하세요")
            End If
            If System.IO.File.Exists(fi7) Then
                DSET1.weather_wind.ReadXml(fi7)
            Else
                MsgBox("날씨데이터파일#7 이 없습니다\r\n프로그램을 다시 설치하세요")
            End If
            If System.IO.File.Exists(fi8) Then
                DSET1.weather_river.ReadXml(fi8)
            Else
                MsgBox("날씨데이터파일#8 이 없습니다\r\n프로그램을 다시 설치하세요")
            End If
            If System.IO.File.Exists(fi9) Then
                DSET1.weather_water.ReadXml(fi9)
            Else
                MsgBox("날씨데이터파일#9 이 없습니다\r\n프로그램을 다시 설치하세요")
            End If

        End If



        DSET1.weather_cha.AcceptChanges()
        DSET1.weather_ilsa.AcceptChanges()
        DSET1.weather_supdo.AcceptChanges()
        DSET1.weather_temp.AcceptChanges()
        DSET1.tbl_weather.AcceptChanges()

        DSET1.weather_wind.AcceptChanges()
        DSET1.weather_river.AcceptChanges()
        DSET1.weather_water.AcceptChanges()


        DSET1.weather_group.AcceptChanges()
    End Sub

    '''좌측메뉴를 재구성하는소스
    Public Sub RefreshMenuList(autoselecttagname)
        Me.TreeView1.Nodes.Clear()  '//기존트리목록초기화

        Dim 건물이름 As String = DSET1.Tables("tbl_desc").Rows(0)("buildname").ToString()
        Dim Tn As TreeNode = Me.TreeView1.Nodes.Add(건물이름)    '//먼저건물이름을 표시한다.
        Tn.ForeColor = Color.Blue
        Tn.Tag = ""

        'MsgBox(autoselecttagname)

        '//추가할메뉴선택
        Dim Menus() As String = New String() {"입력존", "공조처리",
                                              "난방기기", "난방공급시스템", "난방분배시스템", "냉방기기",
                                              "냉방분배시스템", "신재생및열병합", "열관류율", "월별에너지사용량"}
        For Each m As String In Menus

            Select Case m
                Case "입력존"
                    '//전체데이터갯수를 반환해준다.
                    Dim DataCount As Integer = DSET1.tbl_zone.Select("code <> '0'").Length
                    Dim ntn As TreeNode = Me.TreeView1.Nodes.Add(m + "(" + DataCount.ToString() + ")") : ntn.Tag = ""
                    GroupList_Zone = New ArrayList

                    '//그룹별로 표시해준다.
                    If DataCount = 0 Then
                        ntn.Tag = m.ToString() + "|"
                    Else
                        For Each dr As DataRow In DSET1.tbl_zone.Select("code <> '0'")
                            Dim gname As String = dr("그룹").ToString()
                            If GroupList_Zone.IndexOf(gname) = -1 Then   '//해당그룹이없다면 추가한다.

                                '//이그룹을
                                Dim drrow() As DS.tbl_zoneRow = DSET1.tbl_zone.Select("code <> '0' and 그룹='" + gname + "'")
                                Dim ntc As Integer = drrow.Length
                                Dim ntn2 As TreeNode = ntn.Nodes.Add(gname, gname + "(" + ntc.ToString() + ")")
                                ntn2.Tag = m.ToString() + "|" + gname
                                GroupList_Zone.Add(gname)


                            End If
                        Next

                        '//하위그룹에대한
                        For Each stn As TreeNode In ntn.Nodes

                            '//해당그룹에 속한 존을 사용하는 입력면을 모두 찾아서 갯수를 센다.
                            Dim gname As String = stn.Tag.ToString.Split("|")(1)
                            Dim drrow() As DS.tbl_zoneRow = DSET1.tbl_zone.Select("code <> '0' and 그룹='" + gname + "'")
                            Dim myouncount As UInt32 = 0
                            For Each drzrow As DS.tbl_zoneRow In drrow
                                '  myouncount += DSET1.tbl_myoun.Select("code <> '0' and 존분류='" + drzrow.code + "'").Length
                            Next

                            Dim stnm As TreeNode = stn.Nodes.Add("입력면")
                            stnm.Tag = "입력면|" + gname


                            '//
                        Next

                    End If

                    ntn.ExpandAll()

                Case "냉방분배시스템"
                    Dim ntn As TreeNode = Me.TreeView1.Nodes.Add(m + "(" + DSET1.tbl_bunbae.Select("code <> '0'").Length.ToString() + ")") : ntn.Tag = m.ToString()
                Case "난방기기"
                    Dim ntn As TreeNode = Me.TreeView1.Nodes.Add(m + "(" + DSET1.tbl_nanbangkiki.Select("code <> '0'").Length.ToString() + ")") : ntn.Tag = m.ToString()
                Case "난방공급시스템"
                    Dim ntn As TreeNode = Me.TreeView1.Nodes.Add(m + "(" + DSET1.tbl_kongkub.Select("code <> '0'").Length.ToString() + ")") : ntn.Tag = m.ToString()
                Case "공조처리"
                    Dim ntn As TreeNode = Me.TreeView1.Nodes.Add(m + "(" + DSET1.tbl_kongjo.Select("code <> '0'").Length.ToString() + ")") : ntn.Tag = m.ToString()
                Case "난방분배시스템"
                    Dim ntn As TreeNode = Me.TreeView1.Nodes.Add(m + "(" + DSET1.tbl_nbunbae.Select("code <> '0'").Length.ToString() + ")") : ntn.Tag = m.ToString()
                Case "냉방기기"
                    Dim ntn As TreeNode = Me.TreeView1.Nodes.Add(m + "(" + DSET1.tbl_nangbangkiki.Select("code <> '0'").Length.ToString() + ")") : ntn.Tag = m.ToString()
                Case "신재생및열병합"
                    Dim ntn As TreeNode = Me.TreeView1.Nodes.Add(m + "(" + DSET1.tbl_new.Select("code <> '0'").Length.ToString() + ")") : ntn.Tag = m.ToString()
                Case "열관류율"
                    Dim ntn As TreeNode = Me.TreeView1.Nodes.Add(m + "(" + DSET1.tbl_yk.Select("code <> '0'").Length.ToString() + ")") : ntn.Tag = m.ToString()
                Case "설정프로필"
                    Dim ntn As TreeNode = Me.TreeView1.Nodes.Add(m + "(" + DSET1.tbl_profile.Select("code <> '0'").Length.ToString() + ")") : ntn.Tag = m.ToString()
                    'Case "입력면"
                    '    Dim ntn As TreeNode = Me.TreeView1.Nodes.Add(m + "(" + DSET1.tbl_myoun.Select("code <> '0'").Length.ToString() + ")") : ntn.Tag = m.ToString()
                Case Else
                    Dim ntn As TreeNode = Me.TreeView1.Nodes.Add(m)
                    ntn.Tag = m.ToString()
            End Select
        Next

        '//트리뷰를 모두 갱신했다. 만약 자동선택해야할 트리뷰가 있었다면 그것을 선택해준다(자동확장) 없다면 기선택데이터를 처리함
        Dim seltag As String = autoselecttagname
        If seltag = "" AndAlso Not PreNode Is Nothing Then seltag = PreNode.Tag.ToString
        If seltag <> "" Then
            Dim buf() As String = autoselecttagname.Split("|")
            Dim astn As TreeNode = fintreenode(Nothing, seltag)
            If Not astn Is Nothing Then '//선택된태그가잇다?
                Me.TreeView1.SelectedNode = astn
                Me.TreeView1.SelectedNode.ExpandAll()
                Me.TreeView1.SelectedNode.ForeColor = Color.Blue
                Me.PreNode = Me.TreeView1.SelectedNode
            End If
        End If
    End Sub

    Private Function fintreenode(basenode As TreeNode, tag As String) As TreeNode
        Dim retval As TreeNode = Nothing

        Dim tnc As TreeNodeCollection
        If basenode Is Nothing Then
            tnc = Me.TreeView1.Nodes
        Else
            tnc = basenode.Nodes
        End If

        For Each tn As TreeNode In tnc
            If tn.Nodes.Count > 0 Then
                retval = fintreenode(tn, tag)
                If Not retval Is Nothing Then
                    Exit For
                End If
            Else
                If tn.Tag.ToString = tag Then
                    retval = tn
                    Exit For
                End If
            End If
        Next
        Return retval
    End Function


    Private Sub Save_FilHistory(ByVal filename As String)
        Dim Path As String = filename.Substring(0, filename.LastIndexOf("\"))
        Dim Name As String = filename.Substring(filename.LastIndexOf("\"))
        Path = Path.ToUpper.Replace(My.Application.Info.DirectoryPath.ToUpper, ".\")
        Path = Path.Replace("\\", "\")
        Name = Name.Trim(CChar("\"))

        '//현재 리스트가 존재하는지확인
        Dim Exist As Boolean = False
        For i As Integer = 0 To 4
            If PreFile(i).ToLower.Trim = filename.ToLower.Trim Then
                PreFile(i) = Path & "\" & Name
                Exist = True
                Exit For
            End If
        Next

        If Exist = False Then    '//미뤄서 1번에 넣도록 한다.
            PreFile(4) = PreFile(3)
            PreFile(3) = PreFile(2)
            PreFile(2) = PreFile(1)
            PreFile(1) = PreFile(0)
            PreFile(0) = filename
        End If
        For i As Integer = 1 To 5
            Myini.Write("presetting", "filename" & i, PreFile(i - 1))
        Next
        Read_FilHistory() '//저장한후에는 다시 읽어오도록한다.
    End Sub
    Private Sub Read_FilHistory()

        Dim Path As String
        Dim Name As String
        '//현재 리스트가 존재하는지확인
        For i As Integer = 1 To 5
            Dim Filename As String = Myini.Read("presetting", "filename" & i, "")
            Filename = Filename.Replace(".\", My.Application.Info.DirectoryPath & "\")
            PreFile(i - 1) = Filename

            Path = "" : Name = ""
            If Filename.Trim <> "" Then
                Path = Filename.Substring(0, Filename.LastIndexOf("\")) & "\"
                Path = Path.Replace("\\", "\")
                Name = Filename.Substring(Filename.LastIndexOf("\"))
                Name = Name.Trim(CChar("\"))
            End If

            Select Case i
                Case 1
                    Me.lbl_p1.Text = "F" & i & "." & Name
                    ' Me.ToolTip1.SetToolTip(Me.lbl_p1, Path)
                    Me.lbl_p1.ForeColor = CType(IIf(Name <> "", Color.Black, Color.Gray), Color)
                Case 2
                    Me.lbl_p2.Text = "F" & i & "." & Name
                    'Me.ToolTip1.SetToolTip(Me.lbl_p2, Path)
                    Me.lbl_p2.ForeColor = CType(IIf(Name <> "", Color.Black, Color.Gray), Color)
                Case 3
                    Me.lbl_p3.Text = "F" & i & "." & Name
                    ' Me.ToolTip1.SetToolTip(Me.lbl_p3, Path)
                    Me.lbl_p3.ForeColor = CType(IIf(Name <> "", Color.Black, Color.Gray), Color)
                Case 4
                    Me.lbl_p4.Text = "F" & i & "." & Name
                    ' Me.ToolTip1.SetToolTip(Me.lbl_p4, Path)
                    Me.lbl_p4.ForeColor = CType(IIf(Name <> "", Color.Black, Color.Gray), Color)
                Case 5
                    Me.lbl_p5.Text = "F" & i & "." & Name
                    'Me.ToolTip1.SetToolTip(Me.lbl_p5, Path)
                    Me.lbl_p5.ForeColor = CType(IIf(Name <> "", Color.Black, Color.Gray), Color)
            End Select
        Next

    End Sub

    Private Sub Save_File(ByRef ds1 As DS, ByRef dsr1 As DSR, ByVal FileName As String, Optional prompt As Boolean = True, Optional updatemenulist As Boolean = True)

        ds1.AcceptChanges()
        dsr1.AcceptChanges()

        '//파일을 열어서 템플릿이름을 가져온다
        Dim Fs As New IO.FileStream(FileName, IO.FileMode.Create)
        Dim Bw As New IO.BinaryWriter(Fs, System.Text.Encoding.Default)

        '//세이브파일구조번호저장(2)
        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가 eco 파일 저장할 때 admin 제거 Prj.UserAuthType = "ADMIN" OrElse
            Prj.SFType = "00"
        Else
            Prj.SFType = "10"
        End If

        Bw.Write(System.Text.Encoding.Default.GetBytes(Prj.SFType))

        '//저장순서는 ReadMe.txt 참조
        Dim uiverstr As String = CurrentUIVersion()
        Dim UIVer() As Byte = System.Text.Encoding.Default.GetBytes(uiverstr)
        If UIVer.Length <> 10 Then
            MsgBox("UI버젼의 길이 오류(" & UIVer.Length & ")")
            GoTo ENDSTAT
        End If
        Bw.Write(UIVer)

        Dim LGVer() As Byte = System.Text.Encoding.Default.GetBytes(Prj.LGVersino)
        If LGVer.Length <> 10 Then
            MsgBox("LG버젼의 길이 오류(" & LGVer.Length & ")")
            GoTo ENDSTAT
        End If
        Bw.Write(LGVer)

        '//템플릿 이름 저장(100한글 50자)
        Dim Name() As Byte = System.Text.Encoding.Default.GetBytes(Prj.Name)
        ReDim Preserve Name(99)
        'MsgBox(Name.Length)
        Bw.Write(Name)

        '//템플릿 설명 저장(256 한글 128자)
        Dim Desc() As Byte = System.Text.Encoding.Default.GetBytes(Prj.Desc)
        ReDim Preserve Desc(255)
        'MsgBox(Desc.Length)
        Bw.Write(Desc)

        '//템플릿 생성시간
        Bw.Write(System.Text.Encoding.Default.GetBytes(Prj.MakeTime))

        '//템플릿 최종변경시간(항상현재시간을 저장한다)
        Bw.Write(System.Text.Encoding.Default.GetBytes(CStr(Format(Now, "yyyy-MM-dd HH:mm:ss"))))

        Select Case Prj.SFType
            Case "01"   '//암호 8바이트추가한다.
                If Prj.Password.Length > 8 Then
                    MsgBox("암호의길이가 8을 초과합니다" & vbCrLf & "암호는 저장되지않습니다", MsgBoxStyle.Information, "확인")
                    Prj.Password = ""
                End If
                Dim Pass() As Byte = System.Text.Encoding.Default.GetBytes(Prj.Password)
                ReDim Preserve Pass(7)
                Bw.Write(Pass)
        End Select

        '//1번쨰 데이터소스를 저장합니다.
        Dim Pos1 As Int64 = Bw.BaseStream.Position
        ds1.WriteXml(Fs)
        Dim Pos1e As Int64 = Bw.BaseStream.Position
        Dim Dse1Len As Int64 = Pos1e - Pos1   '//데이터셋의 길이
        Bw.BaseStream.Position = Pos1   '//처음위치로이동
        Bw.Write(Dse1Len)   '//데이터셋길이저장
        ds1.WriteXml(Fs)   '//데이터셋다시저장

        '//데이터세 xml 임시저장
        'Dim dsfile As String = My.Application.Info.DirectoryPath & "\ds1.xml"
        'ds1.WriteXml(dsfile)

        '//2번쨰 데이터소스를 저장합니다.
        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가 eco 파일 저장할 때 admin 제거 Prj.UserAuthType = "ADMIN" OrElse
            Dim Pos2 As Int64 = Bw.BaseStream.Position
            dsr1.WriteXml(Fs)
            Dim Pos2e As Int64 = Bw.BaseStream.Position
            Dim Dse2Len As Int64 = Pos2e - Pos2  '//데이터셋의 길이
            Bw.BaseStream.Position = Pos2   '//처음위치로이동
            Bw.Write(Dse2Len)   '//데이터셋길이저장
            dsr1.WriteXml(Fs)   '//데이터셋다시저장
        End If

ENDSTAT:  '//오류발생시 강제종료를 위한 분기문
        Bw.Flush()
        Bw.Close()
        Fs.Close()

        '//파일열때랑 저장할때(새이름포함) 이름이 바뀔수잇으므로 해당 이벤트에만 화면을 갱신할거에요~
        Dim fi As New System.IO.FileInfo(FileName)
        Me.lbl_filename.Text = fi.Name ' Prj.FileName.Substring(Prj.FileName.LastIndexOf("\") + 1)


        '//압축을먼저진행한다 220919
        Dim Source() As Byte = My.Computer.FileSystem.ReadAllBytes(FileName)
        Dim Desbuf() As Byte = {}

        If FileName.ToLower().EndsWith("x") Then  '//compressed 
            Utility.MiniLZO.Compress(Source, Desbuf)
            Dim OrgLength As Integer = Source.Length
            Dim NewLength As Integer = Desbuf.Length
            Array.Clear(Source, 0, Source.Length)
            Array.Resize(Source, Desbuf.Length + 4)
            Dim datalen() As Byte = BitConverter.GetBytes(OrgLength)
            Array.Copy(datalen, Source, datalen.Length)
            Array.Copy(Desbuf, 0, Source, 4, Desbuf.Length)
        End If

        '/////////////////////////////////////////////////////////////////////////////////////////////////////////////저장파일 변조2011.03.16추가
        '//Encoding
        If Not (Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1") Then  '//2011.03.09 추가 eco 파일 저장할 때 admin 제거 Prj.UserAuthType = "ADMIN" OrElse 
            'Dim Source() As Byte = My.Computer.FileSystem.ReadAllBytes(FileName)
            Desbuf = DeCryptArea(Source, New Byte() {&HAC, &H29, &H55, &H42})
            My.Computer.FileSystem.WriteAllBytes(FileName, Desbuf, False)
        Else
            My.Computer.FileSystem.WriteAllBytes(FileName, Source, False)
        End If



        '/////////////////////////////////////////////////////////////////////////////////////////////////////////////저장파일 변조2011.03.16추가

        If prompt Then MsgBox("파일이 저장되었습니다", MsgBoxStyle.Information, "확인")
        If updatemenulist Then Me.RefreshMenuList("")

        'Me.bt_desc.PerformClick()

        'Bw.Write(CStr(Prj.UIVersion))
        'Bw.Write(CStr(Prj.LGVersino))
        'Bw.Write(CStr(IIf(Prj.Name = "", "프로젝트이름", Prj.Name)))
        'Bw.Write(CStr(IIf(Prj.Desc = "", "프로젝트설명", Prj.Desc)))
        ''//템플릿 생성시간
        'Bw.Write(CStr(Format(Now, "yyyy-MM-dd HH:mm:ss")))
        'ds1.WriteXml(Fs)
    End Sub

#Region "Show_Menu"

    Public Sub Menu_건물개요()
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        'Me.Toggle_Menu_Color(E_MenuIdx.건물개요)
        show_menu(E_MenuIdx.건물개요.ToString)
    End Sub

#End Region

    Private Sub Read_SEtting()
        Work_msg("설정을 확인하는중")

        Pub.pLog = New ArinLog.ArinLog()
        pLog.Add("Read Setting")

        '프로젝트 버젼정보
        Prj.MaxUI = "20091231"
        Prj.MaxLG = "20091231"
        Prj.Admin = True
        Prj.Password = ""   '//암호는 기본해제되어있음

        Try
            For Each A As Net.NetworkInformation.NetworkInterface In ArinNet.MyNet.GetMacArray
                If A.NetworkInterfaceType <> Net.NetworkInformation.NetworkInterfaceType.Loopback Then
                    Prj.CUrMac = A.GetPhysicalAddress.ToString
                End If
            Next
            Dim ipentry As Net.IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName)
            For Each C As Net.IPAddress In ipentry.AddressList
                If C.ToString.Length <= 15 AndAlso C.ToString.Length > 4 Then
                    Prj.CUrIP = C.ToString
                    Exit For
                End If
            Next
        Catch ex As Exception
            Prj.CUrMac = "NOMAC"
            Prj.CUrIP = "127.0.0.1"
        End Try




        '//데이터디렉토리정보를 확인한다 이곳에서 데이터베이스및 기타 설정파일을 저장하게한다 
        '//이는 인터넷설치버젼의경우 사용자폴더로 들어가기떄문이다
        Work_msg("데이터폴더를 확인합니다")
        If DataDir.Exists = False Then DataDir.Create() '//데이터폴더가없다면 생성
        If TemplateDir.Exists = False Then
            TemplateDir.Create()
            'If System.IO.File.Exists(My.Application.Info.DirectoryPath & "\template\sample.tpl") = True Then
            '    My.Computer.FileSystem.CopyFile(My.Application.Info.DirectoryPath & "\template\sample.tpl", TemplateDir.FullName & "\sample.tpl", True)
            'End If
        End If

        Work_msg("기본정보를 설정합니다")
        Myini = New CEnergy.MyINI(DataDir.FullName & "\arinwaret4.ini")
        Work_msg("")
        Me.Activate()
    End Sub

    Private Sub Read_PreFile(ByVal i As Short)
        If Prj.LoginTime = "" Then
            MsgBox("먼저 로그인을 하세요", MsgBoxStyle.Information, "확인")
            Frm_Intro.Activate()
            Frm_Intro.tb_id.Focus()
            Return
        End If
        If PreFile(i).Trim <> "" Then
            If MsgBox(PreFile(i) & "파일을 불러오시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "불러오기") <> MsgBoxResult.Ok Then Return
            Dim Filename As String = PreFile(i)
            If System.IO.File.Exists(Filename) = True Then
                Me.Open_File(Filename)
            Else
                MsgBox("기존파일이 없거나 불러올 수 없습니다", MsgBoxStyle.Critical, "확인")
            End If
        End If
    End Sub


    '''기존사용파일목록 1~5까지의 버튼처리
    Private Sub ToolStripMenuItem10_Click(sender As System.Object, e As System.EventArgs) Handles lbl_p1.Click, lbl_p2.Click, lbl_p3.Click, lbl_p4.Click, lbl_p5.Click
        Dim but As Windows.Forms.ToolStripMenuItem = CType(sender, Windows.Forms.ToolStripMenuItem)
        Dim idx As Integer = CInt(but.Tag.ToString)
        Read_PreFile(idx)
    End Sub

    Private Sub 신규ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles btNew.Click


        '물어야하니 if
        If MsgBox("새파일을 작성하시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") <> MsgBoxResult.Ok Then Return '//ok 안하면 빠져나가기
        Dim new_string As String
        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가
            new_string = "\newx.tplx"
        Else
            new_string = "\newx.ecox"
        End If
        Dim Srcfile As New System.IO.FileInfo(My.Application.Info.DirectoryPath & new_string)
        If Srcfile.Exists = False Then
            MsgBox("원본샘플파일이 존재하지않습니다", MsgBoxStyle.Critical, "확인")
            Return '//복사할원본이 없으면 빠져나가기
        End If

        'Dim SD As New SaveFileDialog
        'If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가
        '    SD.FileName = "new" & Format(Now, "mmdd") & ".tpl"
        '    SD.Filter = "템플릿파일(*.tplx)|*.tplx|모든파일(*.*)|*.*"
        'Else
        '    SD.FileName = "new" & Format(Now, "mmdd") & ".eco"
        '    SD.Filter = "데이터파일(*.ecox)|*.ecox|모든파일(*.*)|*.*"
        'End If

        'If SD.ShowDialog <> Windows.Forms.DialogResult.OK Then Return '//저장할 파일명을 입력안하면 빠져나가기

        ''//ㅊ복사해서 열어주기
        'If System.IO.File.Exists(SD.FileName) Then System.IO.File.Delete(SD.FileName)
        'Srcfile.CopyTo(SD.FileName)

        '/////////////////////////////////////////////////////////////////////////////////////////////////////////////저장파일 변조2011.03.16추가
        'If Not (Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1") Then  '//2011.03.09 추가
        '    Dim Desbuf() As Byte = {}
        '    Dim Source() As Byte = My.Computer.FileSystem.ReadAllBytes(SD.FileName)
        '    Desbuf = DeCryptArea(Source, New Byte() {&HAC, &H29, &H55, &H42})
        '    My.Computer.FileSystem.WriteAllBytes(SD.FileName, Desbuf, False)   
        'End If
        '/////////////////////////////////////////////////////////////////////////////////////////////////////////////저장파일 변조2011.03.16추가
        Dim filesync As Boolean = False
        Me.Open_File(Srcfile.FullName, filesync, False, False, True)
        Prj.UIVersion = CurrentUIVersion()  '//항상현재버젼으로 160327
        Refresh_info()
        ToolStripButton3.Enabled = False
        bt_filesave.Enabled = False
        'Me.Save_File(Prj.FileName, False)
    End Sub

    Public PreNode As TreeNode = Nothing
    Private Sub TreeView1_MouseDoubleClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles TreeView1.MouseDoubleClick
        If Me.TreeView1.SelectedNode Is Nothing Then Return '//선택된노드가없다면 취소한다.
        Dim NodeID As String = Me.TreeView1.SelectedNode.Tag.ToString   '//현재선택된노드의이름
        ' MsgBox(NodeID)
        show_menu(NodeID)   '//해당노드에해당하는 폼을 오픈한다.
        If Not PreNode Is Nothing Then PreNode.ForeColor = Color.Black '//이전에 선택된 노드가잇다면 검정색으로 색상변경

        PreNode = Me.TreeView1.SelectedNode '//현재선택된노드값을 저장한다.
        If PreNode Is Nothing Then Return
        PreNode.ForeColor = Color.Blue  '//글씨색을 청색으로변경
    End Sub

    '''현재열려있는 메뉴를 닫습니다.
    Private Sub Close_menu()
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If

        If Me.OpenedForm <> E_MenuIdx.NONE Then
            MsgBox("현재열려있는폼 :" + Me.OpenedForm.ToString())
        End If
    End Sub

    '''메뉴인덱스에해당하는 폼을 반환합니다.
    Private Function GetFormfromMenuIDX(nidx As E_MenuIdx) As CForm
        Dim f As CForm
        Select Case nidx
            Case E_MenuIdx.공조처리
                f = New Frm_kongjo(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
            Case E_MenuIdx.난방공급시스템
                f = New Frm_kongkub(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
            Case E_MenuIdx.난방기기
                f = New Frm_Nanbang(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
            Case E_MenuIdx.난방분배시스템
                f = New Frm_nBunbae(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
            Case E_MenuIdx.냉방기기
                f = New Frm_NaengBang(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
            Case E_MenuIdx.냉방분배시스템
                f = New Frm_Bunbae(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
            Case E_MenuIdx.신재생및열병합
                f = New Frm_New(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
            Case E_MenuIdx.열관류율
                f = New Frm_YK(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
            Case E_MenuIdx.입력면
                f = New Frm_V20091231_Myoun(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
            Case E_MenuIdx.입력존
                f = New Frm_Zone(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
            Case E_MenuIdx.건물개요
                f = New Frm_Desc(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
            Case E_MenuIdx.월별에너지사용량
                f = New Frm_monuse(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
            Case Else
                f = Nothing
        End Select
        Return f
    End Function
    Private Function GetMenuIDX(tagstring As String) As E_MenuIdx
        Dim v As Array = [Enum].GetValues(GetType(E_MenuIdx))
        For i As Integer = 0 To v.Length - 1
            Dim val As Integer = v(i)
            Dim str As String = [Enum].GetName(GetType(E_MenuIdx), val)
            If str = tagstring Then
                Return val
            End If
        Next
        Return E_MenuIdx.NONE
    End Function

    Private Sub Selectnode(basenode As TreeNodeCollection, nodetag As String)
        For Each nd As TreeNode In basenode
            If nd.GetNodeCount(True) > 0 Then
                Selectnode(nd.Nodes, nodetag)
            Else
                If nd.Tag = nodetag Then
                    nd.ForeColor = Color.Blue
                    TreeView1.SelectedNode = nd
                End If
            End If
        Next
    End Sub

    Dim lastmenutag As String = ""
    Private Sub show_menu(menutag As String)
        If menutag.Trim = "" Then Return
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If

        lastmenutag = menutag

        Dim MenuName As String = menutag
        Dim MenuParam As String = ""
        If menutag.IndexOf("|") <> -1 Then
            MenuName = menutag.Split("|")(0)
            MenuParam = menutag.Split("|")(1)
        End If

        Dim nidx As E_MenuIdx = GetMenuIDX(MenuName)

        For Each fChild As CForm In Me.MdiChildren
            If fChild.HasChanged Then
                fChild.AcceptChanged()
                PrjChanged = True
            End If
            fChild.Close()
            fChild.Dispose()
        Next

        If Me.OpenedForm <> E_MenuIdx.NONE Then
            '//새로여는 화면이 기존화면과 같다면 그냥 있늦다.
            Dim curf As CForm = GetFormfromMenuIDX(Me.OpenedForm)
            If Not curf Is Nothing Then '//구폼데이터가 잇다면
                If curf.HasChanged Then
                    curf.AcceptChanged()
                    PrjChanged = True
                End If
                curf.Close()
                curf.Dispose()
                OpenedForm = E_MenuIdx.NONE
            End If
        End If

        Dim f As CForm = GetFormfromMenuIDX(nidx)
        If Not f Is Nothing Then
            f.Parameter = MenuParam
            f.ControlBox = False
            f.FormBorderStyle = Windows.Forms.FormBorderStyle.Sizable
            f.MdiParent = Me
            f.WindowState = FormWindowState.Maximized
            f.TreeTag = menutag
            f.Show()
            f.Activate()    '//현재열려있는폼을 변경해준다.
            Me.OpenedForm = nidx

            '//입력존은 새로 추가함
            If Me.OpenedForm = E_MenuIdx.입력존 Then
                Dim drzonerow() As DataRow = DSET1.tbl_zone.Select("그룹='" + MenuParam + "'")
                If drzonerow.Length = 0 Then
                    'CType(f, Frm_Zone).bt_add.PerformClick()  '140410 임시제거 오류낫음;; 존을 저장하면 하나가 무조건 생겨버린다.
                End If
            End If
        End If

        '//트리뷰를 갱신한다.
        'MsgBox("트리뷰갱신및 선택된프리뷰를 처리해준다.")
        RefreshMenuList(menutag)
        Selectnode(Me.TreeView1.Nodes, menutag)

    End Sub

    Private Sub 프로그램정보ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs)

    End Sub

    Private Sub 나눔고딕설치ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs)
        Process.Start("http://hangeul.naver.com/share.nhn")
    End Sub

    Private Sub ToolStripMenuItem8_Click_1(sender As System.Object, e As System.EventArgs) Handles ToolStripMenuItem8.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        Dim f As New Frm_V20091231_Weather(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
        f.ControlBox = True
        f.ShowDialog()
    End Sub

    Private Sub ToolStripMenuItem10_Click_1(sender As System.Object, e As System.EventArgs) Handles ToolStripMenuItem10.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        'Me.Toggle_Menu_Color(E_MenuIdx.부분부하율)
        Dim f As New Frm_V20091231_buha(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
        f.ControlBox = True
        f.ShowDialog()
    End Sub

    Private Sub ToolStripMenuItem11_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripMenuItem11.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        Frm_Common.ControlBox = True
        Frm_Common.ShowDialog()
        'Show_menu(New Frm_Common)
    End Sub

    Private Sub ToolStripMenuItem12_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripMenuItem12.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        Frm_RepResult_Admin.ControlBox = True
        Frm_RepResult_Admin.Show()
    End Sub

    Private Sub ToolStripMenuItem13_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripMenuItem13.Click

        If MsgBox("정말로 서버의 데이터를 수정하시겠습니까?" & vbCrLf &
                  "서버의 기상데이터가 삭제되고 현재데이터가 씌여집니다." & vbCrLf &
                  "이작업은 되돌릴 수없습니다", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") <> MsgBoxResult.Ok Then Return

        Dim pass As String = InputBox("암호입력")
        If pass <> "raytrace" Then Return

        Dim Cn As New SqlClient.SqlConnection(My.Settings.cs)
        Cn.Open()
        Dim CMd As New SqlClient.SqlCommand("delete from tbl_weather", Cn)
        CMd.ExecuteNonQuery()
        CMd.CommandText = "delete from weather_cha" : CMd.ExecuteNonQuery()
        CMd.CommandText = "delete from weather_ilsa" : CMd.ExecuteNonQuery()
        CMd.CommandText = "delete from weather_temp" : CMd.ExecuteNonQuery()
        CMd.CommandText = "delete from weather_supdo" : CMd.ExecuteNonQuery()
        CMd.Dispose()
        Cn.Close()
        Cn.Dispose()

        Dim Taw As New DSTableAdapters.tbl_weatherTableAdapter
        Dim Ta1 As New DSTableAdapters.weather_chaTableAdapter
        Dim Ta2 As New DSTableAdapters.weather_ilsaTableAdapter
        Dim Ta3 As New DSTableAdapters.weather_supdoTableAdapter
        Dim Ta4 As New DSTableAdapters.weather_tempTableAdapter
        Dim Rcnt As Integer = 0
        For Each Dr As DS.tbl_weatherRow In DSET1.tbl_weather.Rows
            Rcnt += Taw.Insert(Dr.code, Dr.건물위치, Dr.난방기, Dr.냉방기, Dr.m01, Dr.m02, Dr.m03, Dr.m04, Dr.m05, Dr.m06, Dr.m07, Dr.m08, Dr.m09, Dr.m10, Dr.m11, Dr.m12)
        Next
        For Each Dr As DS.weather_chaRow In DSET1.weather_cha.Rows
            Rcnt += Ta1.Insert(Dr.pcode, Dr.code, Dr.설명, Dr.m01, Dr.m02, Dr.m03, Dr.m04, Dr.m05, Dr.m06, Dr.m07, Dr.m08, Dr.m09, Dr.m10, Dr.m11, Dr.m12)
        Next
        For Each Dr As DS.weather_ilsaRow In DSET1.weather_ilsa.Rows
            Rcnt += Ta2.Insert(Dr.pcode, Dr.code, Dr.설명, Dr.최대부하, Dr.m01, Dr.m02, Dr.m03, Dr.m04, Dr.m05, Dr.m06, Dr.m07, Dr.m08, Dr.m09, Dr.m10, Dr.m11, Dr.m12)
        Next
        For Each Dr As DS.weather_supdoRow In DSET1.weather_supdo.Rows
            Rcnt += Ta3.Insert(Dr.pcode, Dr.code, Dr.설명, Dr.t01, Dr.t02, Dr.t03, Dr.t04, Dr.t05, Dr.t06, Dr.t07, Dr.t08, Dr.t09, Dr.t10,
                               Dr.t11, Dr.t12, Dr.t13, Dr.t14, Dr.t15, Dr.t16, Dr.t17, Dr.t18, Dr.t19, Dr.t20, Dr.t21, Dr.t22, Dr.t23, Dr.t24)
        Next
        For Each Dr As DS.weather_tempRow In DSET1.weather_temp.Rows
            Rcnt += Ta4.Insert(Dr.pcode, Dr.code, Dr.설명, Dr.t01, Dr.t02, Dr.t03, Dr.t04, Dr.t05, Dr.t06, Dr.t07, Dr.t08, Dr.t09, Dr.t10,
                               Dr.t11, Dr.t12, Dr.t13, Dr.t14, Dr.t15, Dr.t16, Dr.t17, Dr.t18, Dr.t19, Dr.t20, Dr.t21, Dr.t22, Dr.t23, Dr.t24)
        Next
        MsgBox("업데이트완료", MsgBoxStyle.Information, "확인")
    End Sub

#Region "상단메뉴"

    Private Sub 설정프로필ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 설정프로필ToolStripMenuItem.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        Dim f As New Frm_V20091231_Profile(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
        f.ControlBox = True
        f.ShowDialog()

    End Sub

    Private Sub 열기ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles btOpen.Click
        OpenFile()
    End Sub

    Sub OpenFile()
        If Prj.LoginTime = "" Then
            MsgBox("먼저 로그인을 하세요", MsgBoxStyle.Information, "확인")
            Frm_Intro.Activate()
            Frm_Intro.tb_id.Focus()
            Return
        End If

        Dim Od As New OpenFileDialog
        'Od.InitialDirectory = TemplateDir.FullName
        Od.FileName = Prj.FileName
        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가
            Od.Filter = "템플릿파일(*.TPL,*.TPLX)|*.tpl;*.tplx|모든파일(*.*)|*.*"
        Else
            Od.Filter = "데이터파일(*.ECO,*.ECOX)|*.eco;*.ecox|모든파일(*.*)|*.*"
        End If
        Od.FilterIndex = 0
        If Od.ShowDialog <> Windows.Forms.DialogResult.OK Then Return
        Open_File(Od.FileName)
        ToolStripButton3.Enabled = True
        bt_filesave.Enabled = True
    End Sub

    Private Sub 저장ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles bt_filesave.Click
        '/여긴 버튼 클릭됫을떄 일어나는 이벤트 아시죵 ^^?
        If Prj.LoginTime = "" Then
            MsgBox("먼저 로그인을 하세요", MsgBoxStyle.Information, "확인")
            Frm_Intro.Activate()
            Frm_Intro.tb_id.Focus()
            Return
        End If

        If Not Prj.Opened Then
            MsgBox(CLang.열린파일없음, MsgBoxStyle.Information, "확인")
            Return
        End If

        Dim fi As New System.IO.FileInfo(Prj.FileName)
        If fi.Extension.ToLower().EndsWith("x") = False Then
            MsgBox("이 파일은 구버젼 형식입니다. [다른 이름]으로 저장 하세요", MsgBoxStyle.Information, "확인")
            Return
        End If

        ' Dim lastmenu As String = ""
        If Me.OpenedForm <> E_MenuIdx.NONE Then '//뭔가열려있다.
            '  lastmenu = Me.OpenedForm.ToString
            Dim curf As CForm = GetFormfromMenuIDX(Me.OpenedForm)
            curf.AcceptChanged()
            curf.Close()
        End If

        Me.Save_File(DSET1, DSETR1, Prj.FileName)

        If lastmenutag <> "" Then
            Me.show_menu(lastmenutag)
        End If

    End Sub

    Private Sub 정보ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 정보ToolStripMenuItem.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            'MsgBox(CLang.열린파일없음, MsgBoxStyle.Information, "확인")
            Return
        End If
        If Frm_FileInfo.ShowDialog = Windows.Forms.DialogResult.OK Then
            Refresh_info()
        End If
    End Sub

    Private Sub 종료ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 종료ToolStripMenuItem.Click
        Me.Close()
    End Sub

#End Region

    Private Sub TreeView1_AfterSelect(sender As System.Object, e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect

    End Sub

    Private Sub 정보ToolStripMenuItem1_Click(sender As System.Object, e As System.EventArgs) Handles 정보ToolStripMenuItem1.Click
        Frm_About.ShowDialog()
    End Sub

    Private Sub 월별에너지사용량등록ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub TestToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        '//db테스트영역
        Dim msg As String = ""

        msg = "난방기기 개별기기적용/헤더적용여부확인(체크된것만)"
        For Each dr As DS.tbl_nanbangkikiRow In DSET1.tbl_nanbangkiki.Select("개별기기적용=true")
            MsgBox("개별기적용:" + dr.code + "," + dr.설명)
        Next
        For Each dr As DS.tbl_nanbangkikiRow In DSET1.tbl_nanbangkiki.Select("헤더적용=true")
            MsgBox("헤더적용여부:" + dr.code + "," + dr.설명)
        Next

        '//월별사용량데이터(1년차)
        Dim str As New System.Text.StringBuilder
        Dim 년차1 As String = ""
        For Each dr As DS.tbl_monuseRow In DSET1.tbl_monuse.Select("code='0001'", "월")
            If 년차1 = "" Then 년차1 = dr.년
            str.AppendLine(dr.code.ToString() + "," + dr.월 + "월,도시가스=" + dr.도시가스 + ",전력=" + dr.전력 + ",지역난방=" + dr.지역난방)
        Next
        MsgBox(str.ToString, MsgBoxStyle.Information, 년차1)
    End Sub


#Region "COntextMenu"


    Private Sub ContextMenuStrip1_Opening(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip1.Opening
        If Me.TreeView1.SelectedNode Is Nothing Then Return
        Dim tagstring As String = Me.TreeView1.SelectedNode.Tag.ToString()

        If Me.TreeView1.SelectedNode.Level = 0 Then '//상단메뉴이고
            If Me.TreeView1.SelectedNode.Text.Substring(0, 3) = "입력존" Then
                Me.그룹추가ToolStripMenuItem.Enabled = True
                Me.그룹변경ToolStripMenuItem.Enabled = False
                Me.그룹복사ToolStripMenuItem.Enabled = False
                Me.그룹삭제ToolStripMenuItem.Enabled = False
            Else
                e.Cancel = True
            End If
        ElseIf Me.TreeView1.SelectedNode.Level = 1 AndAlso tagstring.Length > 3 Then
            If tagstring.Substring(0, 3) = "입력존" Then
                Me.그룹추가ToolStripMenuItem.Enabled = True
                Me.그룹변경ToolStripMenuItem.Enabled = True
                Me.그룹복사ToolStripMenuItem.Enabled = True
                Me.그룹삭제ToolStripMenuItem.Enabled = True
            Else
                e.Cancel = True
            End If
        End If
    End Sub

    Private Sub 그룹추가ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 그룹추가ToolStripMenuItem.Click
        If Me.TreeView1.SelectedNode Is Nothing Then Return
        Dim newname As String = InputBox("그룹이름", "신규그룹이름을 입력하세요", "그룹명")
        If newname.Trim = "" Then Return
        If Me.TreeView1.SelectedNode.Level = 1 Then
            If Me.TreeView1.SelectedNode.Parent.Nodes.Find(newname, True).Length = 0 Then
                Dim ntv As TreeNode = Me.TreeView1.SelectedNode.Parent.Nodes.Add(newname, newname + "(0)")
                ntv.Tag = "입력존|" + newname
                Me.TreeView1.SelectedNode = ntv
                'TreeView1_MouseDoubleClick(Nothing, Nothing)
            End If
        Else
            If Me.TreeView1.SelectedNode.Nodes.Find(newname, True).Length = 0 Then
                Dim ntv As TreeNode = Me.TreeView1.SelectedNode.Nodes.Add(newname, newname + "(0)")
                ntv.Tag = "입력존|" + newname
                Me.TreeView1.SelectedNode = ntv
                'TreeView1_MouseDoubleClick(Nothing, Nothing)
            End If
        End If
    End Sub

    Private Sub 그룹삭제ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 그룹삭제ToolStripMenuItem.Click
        '//선택된그룹을 삭제
        If Me.TreeView1.SelectedNode Is Nothing Then Return
        Dim tn As TreeNode = Me.TreeView1.SelectedNode
        If Me.TreeView1.SelectedNode.Level <> 1 Then Return
        Dim tag As String = Me.TreeView1.SelectedNode.Tag.ToString()
        Dim t() As String = tag.Split("|")
        If MsgBox("선택된그룹 [" + t(1) + "]을(를) 삭제하시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") = MsgBoxResult.Ok Then
            For Each dr As DS.tbl_zoneRow In DSET1.tbl_zone.Select("code <> '0' and 그룹='" + t(1) + "'")
                DeleteMyunFromZoneCode(dr.code)
                dr.Delete()
            Next
            DSET1.tbl_zone.AcceptChanges()
            RefreshMenuList("")
        End If
    End Sub

    '''해당존을 사용한 면을 삭제합니다.
    Private Sub DeleteMyunFromZoneCode(Zonecode As String)
        For Each dr As DS.tbl_myounRow In DSET1.tbl_myoun.Select("code <> '0' and 존분류='" + Zonecode + "'")
            dr.Delete()
        Next
        DSET1.tbl_myoun.AcceptChanges()
    End Sub

    Private Sub 그룹변경ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 그룹변경ToolStripMenuItem.Click
        '//선택된그룹을 삭제
        If Me.TreeView1.SelectedNode Is Nothing Then Return
        Dim tn As TreeNode = Me.TreeView1.SelectedNode
        If Me.TreeView1.SelectedNode.Level <> 1 Then Return
        Dim tag As String = Me.TreeView1.SelectedNode.Tag.ToString()
        Dim t() As String = tag.Split("|")

        Dim m As New System.Text.StringBuilder
        Dim newname As String = InputBox("변경할 그룹이름을 입력하세요", "그룹변경", t(1))
        If newname.Trim = "" Then Return
        If newname.Trim = t(1) Then Return

        If MsgBox("선택된그룹 [" + t(1) + "]을(를) [" + newname + "]로 변경하시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") = MsgBoxResult.Ok Then
            For Each dr As DS.tbl_zoneRow In DSET1.tbl_zone.Select("code <> '0' and 그룹='" + t(1) + "'")
                dr.그룹 = newname
            Next
            DSET1.tbl_zone.AcceptChanges()
            RefreshMenuList("")
        End If
    End Sub
    Private Sub 그룹복사ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 그룹복사ToolStripMenuItem.Click
        '//선택된그룹을 삭제
        If Me.TreeView1.SelectedNode Is Nothing Then Return
        Dim tn As TreeNode = Me.TreeView1.SelectedNode
        If Me.TreeView1.SelectedNode.Level <> 1 Then Return
        Dim tag As String = Me.TreeView1.SelectedNode.Tag.ToString()
        Dim t() As String = tag.Split("|")

        Dim m As New System.Text.StringBuilder
        Dim newname As String = InputBox("새로운 그룹이름을 입력하세요", "그룹복사", t(1))
        If newname.Trim = "" Then Return
        If newname.Trim = t(1) Then Return

        If MsgBox("선택된그룹 [" + t(1) + "]을(를) [" + newname + "]로 복사하시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") = MsgBoxResult.Ok Then
            For Each dr As DS.tbl_zoneRow In DSET1.tbl_zone.Select("code <> '0' and 그룹='" + t(1) + "'")
                Dim newcode As String = GetNewZoneCode()
                Dim newdr As DataRow = DSET1.tbl_zone.NewRow
                For Each c As DataColumn In DSET1.tbl_zone.Columns
                    newdr(c.ColumnName) = dr(c.ColumnName)
                Next
                newdr("code") = newcode
                newdr("그룹") = newname
                DuplicateZoneRow(dr.code, newcode)   '//이존의코드값을 지정해준다.
                DSET1.tbl_zone.Rows.Add(newdr)
            Next
            DSET1.tbl_zone.AcceptChanges()
            RefreshMenuList("")
        End If
    End Sub

    Private Sub DuplicateZoneRow(ZoneCode As String, newzoneCode As String)
        '//이입력존을 사용하는 입력면을 복제해서 연결해준다.
        Dim 사용입력면() As DS.tbl_myounRow = DSET1.tbl_myoun.Select("존분류='" + ZoneCode + "'")
        For Each 기존입력면 As DS.tbl_myounRow In 사용입력면
            Dim 신규입력면 As DS.tbl_myounRow = DSET1.tbl_myoun.Newtbl_myounRow
            For Each 기존컬럼 As DataColumn In DSET1.tbl_myoun.Columns
                If 기존컬럼.ColumnName.ToUpper = "CODE" Then
                    신규입력면.code = GetMyounMaxCode(DSET1.tbl_myoun)
                Else
                    신규입력면(기존컬럼.ColumnName) = 기존입력면(기존컬럼.ColumnName)
                End If
            Next
            신규입력면.존분류 = newzoneCode
            DSET1.tbl_myoun.Rows.Add(신규입력면)
            DSET1.tbl_myoun.AcceptChanges()
        Next
    End Sub

    '''면의새로운코드값을계산할때사용한다.
    Private Function GetMyounMaxCode(ByVal dt As DataTable) As String
        Try
            Dim Dr As DataRow = dt.Select("", "code desc")(0)
            Return Format(CInt(Dr("code")) + 1, "00000")
        Catch ex As Exception
            Return "00001"
        End Try
    End Function

    Private Function GetNewZoneCode() As String
        Try
            Dim Dr As DataRow = DSET1.tbl_zone.Select("", "code desc")(0)
            Dim Dr_myoun As DataRow = DSET1.tbl_myoun.Select("", "존분류 desc")(0)
            If Dr("code") >= Dr_myoun("존분류") Then
                Return Format(CInt(Dr("code")) + 1, "00000")
            Else
                Return Format(CInt(Dr_myoun("존분류")) + 1, "00000")
            End If
        Catch ex As Exception
            Return "00001"
        End Try
    End Function


#End Region



    Private Sub TestToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_계산결과그래프.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        Report_그래프.ControlBox = True
        Report_그래프.Show()
    End Sub

    Private Sub 설계개선그래프ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_설계개선그래프.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        Report_설계개선.ControlBox = True
        Report_설계개선.Show()
    End Sub

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        btNew.PerformClick()
    End Sub

    Private Sub 월별에너지사용량등록ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        Dim f As New Frm_monuse(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
        f.ControlBox = True
        f.ShowDialog()
        'Show_menu(New Frm_Common)
    End Sub

    Private Sub ToolStripButton2_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton2.Click
        OpenFile()
    End Sub


    Private Sub ToolStripButton3_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton3.Click
        bt_filesave.PerformClick()
    End Sub
    Private Sub ToolStripButton4_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton4.Click
        btSaveNew.PerformClick()
    End Sub
    Private Sub ToolStripButton5_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton5.Click
        실행ToolStripMenuItem1.PerformClick()
    End Sub

    Private Sub ToolStripButton6_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton6.Click
        실행ToolStripMenuItem.PerformClick()
    End Sub

    Private Sub ToolStripButton7_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton7.Click
        bt_계산결과그래프.PerformClick()
    End Sub


    Private Sub 실행ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 실행ToolStripMenuItem.Click

        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If

        ' Dim lastmenu As String = ""
        If Me.OpenedForm <> E_MenuIdx.NONE Then '//뭔가열려있다.
            '   lastmenu = Me.OpenedForm.ToString
            Dim curf As CForm = GetFormfromMenuIDX(Me.OpenedForm)
            curf.AcceptChanged()
            curf.Close()
        End If



        '//현재데이터상태를 저장
        DSET1.AcceptChanges()
        DSETR1.AcceptChanges()

        '//계산하고자하는 형태를 화면에서 선택하게한다.
        If Frm_Calc.ShowDialog <> Windows.Forms.DialogResult.OK Then Return



        '//
        Dim Type As Calculator.ECalc = Frm_Calc.Type    '//계산타입
        Dim showmsg As String = ""  '//추가표시메세지
        Dim St As Date = Now    '//계산시작

        pLog.Add(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        pLog.Add(String.Format("계산실행({0})", Type.ToString()))
        pLog.Add(String.Format("시작시간 : {0}", St.ToString()))
        pLog.Add("----------------------------------")

        '//설계개선안의경우 임시데이터에서 계산을 진행한다.
        '//임시데이터계산을위해서 현재데이터를 모두 복제해서 사용한다.
        If Type = Calculator.ECalc.설계개선안 Then
            showmsg = "설계개선안" + vbCrLf
            DSET2.Clear()
            DSET2.AcceptChanges()
            DSET2.Merge(DSET1)
            DSET2.AcceptChanges()
            DSETR2.Clear()
            DSETR2.AcceptChanges()
            DSETR2.Merge(DSETR1)
            DSETR2.AcceptChanges()
            Calc = New Calculator(Prj.LGVersino, DSET2, DSETR2, Result2, True)    '//계삭식클래스 초기화
        End If

        Dim Result As Boolean = Calc.Start(showmsg, Type, LogSB, 0)
        Dim Ts As TimeSpan = Now - St   '//계산경과시간을 표시해준다.
        Dim calc_ok As Integer = 0
        If Result Then   '//파라미터 True 라면 소요량이 추가로 게산된다.
            Calc.Summary.All()
            If LogSB.ToString <> "" Then
                '//에러기록이 발생했다면 저장후에 보여주도록한다.
                Dim logfile As New System.IO.FileInfo(My.Application.Info.DirectoryPath & "\log\calc_okmsg_" + Now.ToString("yyMMddHHmmss") + ".txt")
                If logfile.Directory.Exists = False Then logfile.Directory.Create()
                My.Computer.FileSystem.WriteAllText(logfile.FullName, LogSB.ToString, False)
                Shell("notepad " + logfile.FullName, AppWinStyle.NormalFocus)
            Else
                MsgBox("계산작업이 완료되었습니다." & vbCrLf & "경과시간:" + Ts.ToString, MsgBoxStyle.Information, "완료")
                calc_ok = 1 '================================2014.04.17 계산이 완료되면 그래프를 보여줌

            End If
        Else
            If LogSB.ToString <> "" Then
                Dim logfile As New System.IO.FileInfo(My.Application.Info.DirectoryPath & "\log\calc_errmsg_" + Now.ToString("yyMMddHHmmss") + ".txt")
                If logfile.Directory.Exists = False Then logfile.Directory.Create()
                My.Computer.FileSystem.WriteAllText(logfile.FullName, LogSB.ToString, False)
                Shell("notepad " + logfile.FullName, AppWinStyle.NormalFocus)
            End If
            MsgBox("계산작업이 중단되었습니다." & vbCrLf & "경과시간:" + Ts.ToString, MsgBoxStyle.Critical, "완료(오류발생)")
        End If

        closemessagewindow()

        '//시뮬레이션모드였다면 원래계산모드로 변경한다.
        If Calc.IsSimulation Then Calc = New Calculator(Prj.LGVersino, DSET1, DSETR1, Result1, False) '//원래계산식으로변경함

        If lastmenutag <> "" Then
            Me.show_menu(lastmenutag)
        End If

        If calc_ok = 1 Then
            If Type <> Calculator.ECalc.설계개선안 Then
                Report_그래프.Visible = False
                Report_그래프.Show()
            Else
                Report_설계개선.Visible = False
                Report_설계개선.Show()
            End If

        End If


    End Sub

    Sub closemessagewindow()
        '//상태메세지창이 열려있다면 제거해준다.
        If Not msgf Is Nothing Then
            msgf.Close()
            msgf.Dispose()
            msgf = Nothing
        End If

    End Sub

    Private Sub 실행ToolStripMenuItem1_Click(sender As System.Object, e As System.EventArgs) Handles 실행ToolStripMenuItem1.Click
        Menu_건물개요()
    End Sub

    Private Sub 계산결과ToolStripMenuItem_Click_1(sender As System.Object, e As System.EventArgs) Handles 계산결과ToolStripMenuItem.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.08 추가
            Report_Total.ControlBox = True
            Report_Total.Show()
        End If
    End Sub

    Private Sub 인증평가서ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles bt_인증평가서.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If

        Report_pyonga.ControlBox = True
        Report_pyonga.Show()
    End Sub

    Private Sub ToolStripMenuItem1_Click(sender As System.Object, e As System.EventArgs)
        For Each dr As DSR.생산에너지Row In DSETR1.생산에너지.Rows
            MsgBox(dr.전력열병합)
        Next
    End Sub

    Private Sub 다른이름으로저장ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles btSaveNew.Click

        Save_New()
    End Sub


    Function Save_New() As Boolean
        If Prj.LoginTime = "" Then
            MsgBox("먼저 로그인을 하세요", MsgBoxStyle.Information, "확인")
            Frm_Intro.Activate()
            Frm_Intro.tb_id.Focus()
            Return False
        End If

        If Prj.FileName = "" Then
            MsgBox(CLang.열린파일없음, MsgBoxStyle.Information, "확인")
            Return False
        End If


        Dim newfilename As String = Prj.FileName
        If newfilename.ToLower().EndsWith("x") = False Then
            newfilename = newfilename + "x"
        End If



        Dim SD As New SaveFileDialog
        SD.FileName = newfilename
        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가
            SD.Filter = "템플릿파일(*.tplx)|*.tplx"
        Else
            SD.Filter = "데이터파일(*.ecox)|*.ecox"
        End If

        SD.FilterIndex = 0
        If SD.ShowDialog <> Windows.Forms.DialogResult.OK Then Return False
        Prj.FileName = SD.FileName

        '    Dim lastmenu As String = ""
        If Me.OpenedForm <> E_MenuIdx.NONE Then '//뭔가열려있다.
            '   lastmenu = Me.OpenedForm.ToString
            Dim curf As CForm = GetFormfromMenuIDX(Me.OpenedForm)
            curf.AcceptChanged()
            curf.Close()
        End If

        Me.Save_File(DSET1, DSETR1, Prj.FileName)

        If lastmenutag <> "" Then
            Me.show_menu(lastmenutag)
        End If

        Return True
    End Function



    Private Sub 환경설정ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 환경설정ToolStripMenuItem.Click

    End Sub

    Private Sub ToolStripMenuItem1_Click_1(sender As System.Object, e As System.EventArgs) Handles bt_데이터관리.Click
        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2010.12.27 추가
            If Not Prj.Opened Then
                Work_msg_timer(CLang.열린파일없음)
                Return
            End If
            Frm_Import.ShowDialog()
        End If
    End Sub

    Dim Bak_DS As DS
    Dim Bak_DSR As DSR
    Private Sub 비교데이터백업ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 비교데이터백업ToolStripMenuItem.Click
        Bak_DS = New DS
        Bak_DSR = New DSR

        Bak_DS = Pub.DSET1.Copy
        Bak_DSR = Pub.DSETR1.Copy

        MsgBox("데이터가 백업되었습니다" + vbCrLf + "비교기능을 사용할 수 있습니다", MsgBoxStyle.Information, "확인")

    End Sub

    Private Sub 데이터비교ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 데이터비교ToolStripMenuItem.Click
        If Bak_DS Is Nothing OrElse Bak_DSR Is Nothing Then
            MsgBox("백업된 원본데이터가 없습니다", MsgBoxStyle.Information, "확인")
            Return
        End If

        Dim Data As New System.Text.StringBuilder
        Dim TLine As New System.Text.StringBuilder
        Dim Line As New System.Text.StringBuilder
        Dim Lines As New System.Text.StringBuilder

        '//모든테이블의 데이터를 비교한다.
        For i As Integer = 1 To Bak_DS.Tables.Count
            Dim Tb As DataTable = Bak_DS.Tables(i - 1)
            Dim TbS As DataTable = DSET1.Tables(i - 1)

            TLine = New System.Text.StringBuilder()
            Lines = New System.Text.StringBuilder

            TLine.AppendLine("## Table : " + Tb.TableName)
            TLine.Append("Row" + "," + "Col")
            For ic As Integer = 1 To Tb.Columns.Count
                Dim Tc As DataColumn = Tb.Columns(ic - 1)
                If ic = Tb.Columns.Count Then
                    TLine.AppendLine("," + Tc.ColumnName)
                Else
                    TLine.Append("," + Tc.ColumnName)
                End If
            Next

            Dim LineChange As Boolean = False
            '//각줄의 데이터를 확인한다.
            For r As Integer = 1 To Tb.Rows.Count

                Dim Change As Boolean = False
                Line = New System.Text.StringBuilder

                Dim Dr As DataRow = Tb.Rows(r - 1)
                Dim Drs As DataRow = TbS.Rows(r - 1)

                Line.Append("줄번호=" + r.ToString())

                For ic As Integer = 1 To Tb.Columns.Count
                    Try
                        If Dr(ic - 1) <> Drs(ic - 1) Then
                            Change = True
                            Line.Append("," + Tb.Columns(ic - 1).ColumnName + "" + Dr(ic - 1).ToString() + " => " + Drs(ic - 1).ToString())
                        Else
                            Line.Append("," + "")
                        End If
                    Catch ex As Exception

                    End Try

                Next
                If Change Then
                    LineChange = True
                    Lines.AppendLine(Line.ToString)
                End If
            Next

            If LineChange Then
                Data.AppendLine(TLine.ToString)
                Data.AppendLine(Lines.ToString)
            End If

        Next


        ''//모든테이블의 데이터를 비교한다.
        'For i As Integer = 1 To Bak_DSR.Tables.Count
        '    Dim Tb As DataTable = Bak_DSR.Tables(i - 1)
        '    Dim TbS As DataTable = DSETR1.Tables(i - 1)

        '    TLine = New System.Text.StringBuilder()
        '    Lines = New System.Text.StringBuilder

        '    TLine.AppendLine("## Table : " + Tb.TableName)
        '    TLine.Append("Row" + "," + "Col")
        '    For ic As Integer = 1 To Tb.Columns.Count
        '        Dim Tc As DataColumn = Tb.Columns(ic - 1)
        '        If ic = Tb.Columns.Count Then
        '            TLine.AppendLine("," + Tc.ColumnName)
        '        Else
        '            TLine.Append("," + Tc.ColumnName)
        '        End If
        '    Next

        '    Dim LineChange As Boolean = False
        '    '//각줄의 데이터를 확인한다.
        '    For r As Integer = 1 To Tb.Rows.Count

        '        Dim Change As Boolean = False
        '        Line = New System.Text.StringBuilder

        '        Dim Dr As DataRow = Tb.Rows(r - 1)
        '        Dim Drs As DataRow = TbS.Rows(r - 1)

        '        Line.Append(r.ToString())

        '        For ic As Integer = 1 To Tb.Columns.Count
        '            Try
        '                If Dr(ic - 1) <> Drs(ic - 1) Then
        '                    Change = True
        '                    Line.Append("," + ic.ToString() + "," + Dr(ic - 1).ToString() + " => " + Drs(ic - 1).ToString())
        '                Else
        '                    Line.Append("," + ic.ToString() + "," + "")
        '                End If
        '            Catch ex As Exception

        '            End Try
        '        Next
        '        If Change Then
        '            LineChange = True
        '            Lines.AppendLine(Line.ToString)
        '        End If
        '    Next

        '    If LineChange Then
        '        Data.AppendLine(TLine.ToString)
        '        Data.AppendLine(Lines.ToString)
        '    End If

        'Next

        Dim file As String = My.Application.Info.DirectoryPath & "\summary.csv"
        My.Computer.FileSystem.WriteAllText(file, Data.ToString, False, System.Text.Encoding.Default)
        Shell("explorer " + file, AppWinStyle.NormalFocus)
    End Sub

    Private Sub 순실체적ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 순실체적ToolStripMenuItem.Click
        Dim b As New System.Text.StringBuilder
        Dim i As Integer = 0
        For Each dr As DS.tbl_zoneRow In DSET1.tbl_zone.Rows
            i += 1
            b.AppendLine("," + i.ToString() + ": 면적(" + dr.면적 + "),천장고p(" + dr.천장고p + "),순실체적(" + dr.순실체적 + ")")
        Next
        MsgBox(b.ToString)

    End Sub

    Private Sub 업로드양식ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 업로드양식ToolStripMenuItem.Click

        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If

        Dim sd As New SaveFileDialog()
        sd.Filter = "Excel(*.xls)|*.xls"
        sd.FilterIndex = 0
        If sd.ShowDialog = Windows.Forms.DialogResult.OK Then

            Dim f As New Frm_Upload(sd.FileName, 10, "")
            f.ShowDialog()

            If System.Diagnostics.Debugger.IsAttached OrElse lbl_user.Text.ToLower = "[arin]" Then '//160327
                Shell("explorer " + Chr(&H22) + sd.FileName + Chr(&H22), AppWinStyle.NormalFocus)
            End If

        End If


    End Sub

    Private Sub CascadeToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CascadeToolStripMenuItem.Click
        Me.LayoutMdi(MdiLayout.Cascade)
    End Sub

    Private Sub TileVerticalToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles TileVerticalToolStripMenuItem.Click
        Me.LayoutMdi(MdiLayout.TileVertical)
    End Sub

    Private Sub TileHorizontalToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles TileHorizontalToolStripMenuItem.Click
        Me.LayoutMdi(MdiLayout.TileHorizontal)
    End Sub

    Private Sub CloseAllToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CloseAllToolStripMenuItem.Click
        For Each ChildForm As Form In Me.MdiChildren
            ChildForm.Close()
        Next
    End Sub

    Private Sub ArrangeIconsToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ArrangeIconsToolStripMenuItem.Click
        Me.LayoutMdi(MdiLayout.ArrangeIcons)
    End Sub


    Private Sub ExportToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ExportToolStripMenuItem.Click
        Frm_Export.Show()
    End Sub

    Private Sub 건물개요ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 건물개요ToolStripMenuItem.Click

    End Sub

    Private Sub UpdateNewToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs)

    End Sub

    Private Sub 파일로부터기상데이터가져오기ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 파일로부터기상데이터가져오기ToolStripMenuItem.Click
        '//기상데이터가져오기

        If Prj.LoginTime = "" Then
            MsgBox("먼저 로그인을 하세요", MsgBoxStyle.Information, "확인")
            Frm_Intro.Activate()
            Frm_Intro.tb_id.Focus()
            Return
        End If

        Dim Od As New OpenFileDialog
        'Od.InitialDirectory = TemplateDir.FullName
        Od.FileName = Prj.FileName
        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가
            Od.Filter = "템플릿파일(*.TPL)|*.tpl|모든파일(*.*)|*.*"
        Else
            Od.Filter = "데이터파일(*.ECO)|*.eco|모든파일(*.*)|*.*"
        End If
        Od.FilterIndex = 0
        If Od.ShowDialog <> Windows.Forms.DialogResult.OK Then Return
        Open_File_Only_weather(Od.FileName)


    End Sub

    Private Sub 파일로부터용도프로필변환ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs)
        '//용도프로필가져오기


        If Prj.LoginTime = "" Then
            MsgBox("먼저 로그인을 하세요", MsgBoxStyle.Information, "확인")
            Frm_Intro.Activate()
            Frm_Intro.tb_id.Focus()
            Return
        End If

        Dim Od As New OpenFileDialog
        'Od.InitialDirectory = TemplateDir.FullName
        Od.FileName = Prj.FileName
        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가
            Od.Filter = "템플릿파일(*.TPL)|*.tpl|모든파일(*.*)|*.*"
        Else
            Od.Filter = "데이터파일(*.ECO)|*.eco|모든파일(*.*)|*.*"
        End If
        Od.FilterIndex = 0
        If Od.ShowDialog <> Windows.Forms.DialogResult.OK Then Return
        'Open_File_Only_profile(Od.FileName)

    End Sub

    Private Sub SaveXmlRawToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles SaveXmlRawToolStripMenuItem.Click
        Dim sd As New SaveFileDialog()
        sd.Filter = "XML|*.xml"
        If sd.ShowDialog = Windows.Forms.DialogResult.OK Then
            DSET1.WriteXml(sd.FileName)
        End If

    End Sub

    Private Sub FielCheckerToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles FielCheckerToolStripMenuItem.Click
        '//기상데이터가져오기

        If Prj.LoginTime = "" Then
            MsgBox("먼저 로그인을 하세요", MsgBoxStyle.Information, "확인")
            Frm_Intro.Activate()
            Frm_Intro.tb_id.Focus()
            Return
        End If

        Dim Od As New OpenFileDialog
        'Od.InitialDirectory = TemplateDir.FullName
        Od.FileName = Prj.FileName
        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.09 추가
            Od.Filter = "템플릿파일(*.TPL)|*.tpl|모든파일(*.*)|*.*"
        Else
            Od.Filter = "데이터파일(*.ECO)|*.eco|모든파일(*.*)|*.*"
        End If
        Od.FilterIndex = 0
        If Od.ShowDialog <> Windows.Forms.DialogResult.OK Then Return
        Open_File_checker(Od.FileName)
    End Sub

    Private Sub XmlImportToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs)


    End Sub

    Private Sub ImportToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles btImport.Click

        If Prj.Opened = False Then
            MsgBox("파일을 불러온 후 다시 시도하세요", MsgBoxStyle.Information, "확인")
            Return
        End If


        Dim od As New OpenFileDialog
        od.Filter = "xml file|*.xml|모든파일(*.*)|*.*"
        od.RestoreDirectory = True
        If od.ShowDialog <> Windows.Forms.DialogResult.OK Then Return

        Try




            Dim buffer As String = System.IO.File.ReadAllText(od.FileName, System.Text.Encoding.UTF8)
            Dim data As String = My.Settings.xmlformat.Replace("{data}", buffer)
            Dim fn As String = "import.xml"
            System.IO.File.WriteAllText(fn, data, System.Text.Encoding.UTF8)

            Dim tempds As New DS()
            Dim xr As XmlReadMode = tempds.ReadXml(fn)

            DSET1.AcceptChanges()
            tempds.AcceptChanges()

            Dim sb As New System.Text.StringBuilder()
            sb.AppendLine("--- 추가된 정보 ---")

            '//가져온 테이블을 기본 정보에서 삭제한다
            For Each tb As DataTable In tempds.Tables

                '//자료가 없는 테이블은 처리하지 않는다
                If tb.Rows.Count < 1 Then Continue For

                Dim tablename As String = tb.TableName.ToLower()
                If tablename.StartsWith("tbl_common") Then Continue For
                If tablename.StartsWith("tbl_profile") Then Continue For
                If tablename.StartsWith("tbl_weather") Then Continue For
                If tablename.StartsWith("weather") Then Continue For


                sb.AppendLine("[" + tb.TableName + "] " + tb.Rows.Count.ToString() + " Lines")

                '//값의 공백제거
                For Each dr As DataRow In tb.Rows
                    For Each dc As DataColumn In tb.Columns
                        If dr(dc.ColumnName) Is DBNull.Value OrElse dc.ReadOnly Then

                        Else

                            dr(dc.ColumnName) = dr(dc.ColumnName).ToString().Trim() '//공백 자동 제거
                        End If
                    Next
                    dr.EndEdit()
                    dr.AcceptChanges()
                Next

                '//기존자료삭제
                DSET1.Tables(tb.TableName).Clear()
                DSET1.Tables(tb.TableName).AcceptChanges()

                '//현재 정보로 저장
                DSET1.Tables(tb.TableName).Merge(tb)
            Next

            DSET1.AcceptChanges()

            FixData(False)  '//데이터보정
            Calc.validation()    '//null보정
            Menu_건물개요()
            Me.RefreshMenuList("")

            MsgboxI(sb.ToString())

        Catch ex As Exception
            MsgboxE("외부파일 가져오기 실패\n" + ex.Message)
        End Try
    End Sub

    Private Function func_calc(Optional msg As String = "계산중", Optional silent As Boolean = False) As Boolean

        Dim ST As Date = Now
        Dim LogSB As New System.Text.StringBuilder
        Dim Result As Boolean = Calc.Start(msg, Calculator.ECalc.All, LogSB, 0)
        Dim Ts As TimeSpan = Now - ST   '//계산경과시간을 표시해준다.
        Dim calc_ok As Integer = 0
        If Result Then   '//파라미터 True 라면 소요량이 추가로 게산된다.
            Calc.Summary.All()
            If LogSB.ToString <> "" Then
                '//에러기록이 발생했다면 저장후에 보여주도록한다.
                Dim logfile As New System.IO.FileInfo(My.Application.Info.DirectoryPath & "\log\calc_okmsg_" + Now.ToString("yyMMddHHmmss") + ".txt")
                If logfile.Directory.Exists = False Then logfile.Directory.Create()
                My.Computer.FileSystem.WriteAllText(logfile.FullName, LogSB.ToString, False)
                Shell("notepad " + logfile.FullName, AppWinStyle.NormalFocus)
                Return False
            Else
                If silent = False Then
                    MsgBox("계산작업이 완료되었습니다." & vbCrLf & "경과시간:" + Ts.ToString, MsgBoxStyle.Information, "완료")
                End If

                calc_ok = 1 '================================2014.04.17 계산이 완료되면 그래프를 보여줌
                Return True
            End If
        Else
            If LogSB.ToString <> "" Then
                Dim logfile As New System.IO.FileInfo(My.Application.Info.DirectoryPath & "\log\calc_errmsg_" + Now.ToString("yyMMddHHmmss") + ".txt")
                If logfile.Directory.Exists = False Then logfile.Directory.Create()
                My.Computer.FileSystem.WriteAllText(logfile.FullName, LogSB.ToString, False)
                Shell("notepad " + logfile.FullName, AppWinStyle.NormalFocus)
            End If

            MsgBox("계산작업이 중단되었습니다." & vbCrLf & "경과시간:" + Ts.ToString, MsgBoxStyle.Critical, "완료(오류발생)")
            Return False
        End If


    End Function

    Private Sub 일괄계산ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 일괄계산ToolStripMenuItem.Click
        Dim f As New frm_batch()
        If f.ShowDialog() = Windows.Forms.DialogResult.OK Then
            If MsgBox("run?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") <> MsgBoxResult.Ok Then Return '//ok 안하면 빠져나가기

            '//히트펌프임시계산 240106
            Dim heatcalc As Boolean = f.heatpumpcalc


            Dim path As String = f.tbPath.Text
            Dim di As New System.IO.DirectoryInfo(path)
            Dim files() As System.IO.FileInfo

            files = di.GetFiles("*.tpl", IO.SearchOption.TopDirectoryOnly)

            Dim files2 As New SortedDictionary(Of String, System.IO.FileInfo)
            For Each fi As System.IO.FileInfo In files
                files2.Add(fi.Name, fi)
            Next


            prb1.Value = 0
            prb1.Maximum = files.Length
            Dim ermsg As New System.Text.StringBuilder
            Dim first As Boolean = True

            If heatcalc Then

                '//리포트파일 생성
                Dim reportfile As String = System.IO.Path.Combine(path, "batchreport_heat.tab")

                Dim sb As New System.Text.StringBuilder
                sb.AppendLine("file" + vbTab + "히트펌프용량_가스_난방" + vbTab + "히트펌프용량_전기_난방" + vbTab + "히트펌프용량_가스_냉방" + vbTab + "히트펌프용량_전기_냉방")

                Dim writecol As Integer = 10
                For Each fitem As KeyValuePair(Of String, System.IO.FileInfo) In files2

                    Dim fi As System.IO.FileInfo = fitem.Value
                    writecol += 1
                    If prb1.Value < prb1.Maximum Then prb1.Value += 1

                    Dim dataitem As New List(Of String)
                    dataitem.Add(fi.Name) '(0) = fi.Name
                    '//close file

                    '//open file
                    Dim retopen As String = Open_File(fi.FullName, False, True, True)


                    '//히트펌프
                    Dim 히트펌프용량_가스_난방 As Decimal = 0
                    Dim 히트펌프용량_전기_난방 As Decimal = 0
                    Dim 히트펌프용량_가스_냉방 As Decimal = 0
                    Dim 히트펌프용량_전기_냉방 As Decimal = 0

                    For Each dr As DS.tbl_nanbangkikiRow In DSET1.tbl_nanbangkiki
                        If dr.히트연료.EndsWith("가스") Then
                            히트펌프용량_가스_난방 += dr.히트난방용량
                        ElseIf dr.히트연료 = "전기" Then
                            히트펌프용량_전기_난방 += dr.히트난방용량
                        End If
                    Next

                    For Each dr As DS.tbl_nangbangkikiRow In DSET1.tbl_nangbangkiki
                        If dr.냉동기종류 <> "실내공조시스템" Then Continue For
                        If dr.냉동기방식 = "압축식(LNG)" Then
                            히트펌프용량_가스_냉방 += dr.냉동기용량
                        ElseIf dr.냉동기방식 = "압축식" Then
                            히트펌프용량_전기_냉방 += dr.냉동기용량
                        End If
                    Next
                    sb.AppendLine(fi.Name + vbTab + 히트펌프용량_가스_난방.ToString("N1") + vbTab _
                                  + 히트펌프용량_전기_난방.ToString("N1") + vbTab _
                                  + 히트펌프용량_가스_냉방.ToString("N1") + vbTab _
                                  + 히트펌프용량_전기_냉방.ToString("N1"))

                    Dim msg As String = String.Format("계산중({0}/{1}) 열번호={3}" + vbCrLf + "{2}" + vbCrLf, prb1.Value, prb1.Maximum, fi.Name, writecol)

                Next

                System.IO.File.WriteAllText(reportfile, sb.ToString(), System.Text.Encoding.Default)
                If System.Diagnostics.Debugger.IsAttached OrElse lbl_user.Text.ToLower = "[arin]" Then '//160327
                    Shell("explorer " + Chr(&H22) + reportfile + Chr(&H22), AppWinStyle.NormalFocus)
                End If
            Else

                '//리포트파일 생성
                Dim reportorg As String = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "batchreport.tab")
                Dim reportfile As String = System.IO.Path.Combine(path, "batchreport.tab")

                If System.IO.File.Exists(reportorg) Then
                    System.IO.File.Copy(reportorg, reportfile, True)
                ElseIf System.IO.File.Exists(reportfile) Then
                    System.IO.File.Delete(reportfile)
                End If

                Dim 입력면추출 As Boolean = f.chkMyoun.Checked

                Dim writecol As Integer = 10
                For Each fitem As KeyValuePair(Of String, System.IO.FileInfo) In files2

                    Dim fi As System.IO.FileInfo = fitem.Value
                    writecol += 1
                    If prb1.Value < prb1.Maximum Then prb1.Value += 1

                    Dim dataitem As New List(Of String)
                    dataitem.Add(fi.Name) '(0) = fi.Name
                    '//close file

                    '//open file
                    Dim retopen As String = Open_File(fi.FullName, False, True, True)

                    '//calc
                    Dim ret As Boolean = False

                    Dim msg As String = String.Format("계산중({0}/{1}) 열번호={3}" + vbCrLf + "{2}" + vbCrLf, prb1.Value, prb1.Maximum, fi.Name, writecol)
                    If String.IsNullOrWhiteSpace(retopen) = False Then ret = func_calc(msg, True)

                    '//get message


                    '//업로드 양식 데이터 생성
                    Dim fxls As New Frm_Upload(reportfile, writecol, fi.Name, True)
                    Dim drlt = fxls.ShowDialog()
                    If drlt = DialogResult.OK Then
                        ermsg.AppendLine("OK" + vbTab + fi.FullName)
                        dataitem.Add("OK")
                    Else
                        ermsg.AppendLine("NG" + vbTab + fi.FullName)
                        dataitem.Add("NG")
                    End If

                    '//입력면 추출
                    If 입력면추출 Then

                        '//엑셀내보내기기능 추가
                        Dim content As New System.Text.StringBuilder()
                        Dim newfile As String = fi.Directory.FullName + "\" + System.IO.Path.GetFileNameWithoutExtension(fi.FullName) + "_입력면.tab"
                        For Each drz As DS.tbl_zoneRow In DSET1.tbl_zone.Rows
                            If drz.code = "0" Then Continue For
                            content.Append(drz.설명)
                            For Each drm As DS.tbl_myounRow In DSET1.tbl_myoun.Select("존분류='" + drz.code + "'")
                                If drm.code = "0" Then Continue For
                                '입력존1, 입력면1_1, 건축부위방식1_1, 면적1_1, 
                                '열관류율1_1, 방위1_1, 입력면1_2, 건축부위방식1_2, 면적1_2, 열관류율1_2, 방위1_2, 입력면1_3, 건축부위방식1_3, 면적1_3, 열관류율1_3, 방위1_3

                                Dim 열관류율 As String = drm.열관류율
                                If drm.열관류율2 <> "" AndAlso drm.열관류율2 <> "0" Then
                                    Dim ykrows() As DS.tbl_ykRow = DSET1.tbl_yk.Select("code='" + drm.열관류율2 + "'")
                                    If ykrows.Length = 1 Then
                                        열관류율 = ykrows(0).열관류율
                                    End If
                                End If


                                content.Append(vbTab + drm.설명 + vbTab + drm.건축부위방식 + vbTab +
                                                    drm.건축부위면적 + vbTab +
                                                    열관류율 + vbTab + drm.방위)
                            Next
                            content.AppendLine()
                        Next

                        System.IO.File.WriteAllText(newfile, content.ToString(), System.Text.Encoding.Default)

                    End If

                Next


            End If


            closemessagewindow()

            Dim logfile As String = System.IO.Path.Combine(path, "log.txt")
            System.IO.File.WriteAllText(logfile, ermsg.ToString(), System.Text.Encoding.Default)

            MsgBox("end")

        End If
    End Sub

    Private Sub btMacro_Click(sender As System.Object, e As System.EventArgs) Handles btMacro.Click
        Menu_건물개요()
        Dim f As New Frm_Macro
        f.Show()
    End Sub

    Private Sub BatchUpdateProfileToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles BatchUpdateProfileToolStripMenuItem.Click

        '//update profile 

        If Prj.LoginTime = "" Then
            MsgBox("먼저 로그인을 하세요", MsgBoxStyle.Information, "확인")
            Frm_Intro.Activate()
            Frm_Intro.tb_id.Focus()
            Return
        End If

        MsgBox("프로필을 일괄 변경할 파일이 있는 폴더를 선택하세요")
        Dim fd As New FolderBrowserDialog
        'Od.InitialDirectory = TemplateDir.FullName
        fd.SelectedPath = batchfolder
        If fd.ShowDialog() <> Windows.Forms.DialogResult.OK Then Return

        batchfolder = fd.SelectedPath

        If Prj.FileName = "" Then
            MsgBox(CLang.열린파일없음, MsgBoxStyle.Information, "확인")
            Return
        End If




        'MsgBox("프로필 파일을 선택하세요")
        'Dim od As New OpenFileDialog
        'If od.ShowDialog() <> Windows.Forms.DialogResult.OK Then Return


        Open_File_and_update_profile(batchfolder)


    End Sub

    Private Sub btcustomprofile_Click(sender As System.Object, e As System.EventArgs) Handles btcustomprofile.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        Dim f As New Frm_custom_profile(Now.Second.ToString() + "00" + Now.Millisecond.ToString())
        f.ControlBox = True
        f.ShowDialog()
    End Sub

    Private Sub MacroIIToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles btMacro2.Click
        Menu_건물개요()
        Dim f As New Frm_Macro2
        f.Show()
    End Sub


    Dim frmManual As Frm_WebManual = Nothing
    Private Sub ManualToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ManualToolStripMenuItem.Click
        Try
            If frmManual Is Nothing OrElse frmManual.IsDisposed Then
                frmManual = New Frm_WebManual()
            End If


            If frmManual.WindowState = FormWindowState.Minimized Then
                frmManual.WindowState = FormWindowState.Normal
            End If

            frmManual.Show()
            frmManual.Activate()
        Catch ex As Exception
            MessageBox.Show("매뉴얼 표시 중 오류가 발생했습니다: " & ex.Message,
                          "오류", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ''' <summary>
    ''' WebView2 Fixed Version 런타임 체크
    ''' </summary>
    Private Sub CheckWebView2Runtime()
        Try
            Dim fixedVersionPath = Path.Combine(Application.StartupPath, "WebView2Runtime")

            ' Fixed Version 폴더가 없으면 경고 (하지만 계속 실행)
            If Not Directory.Exists(fixedVersionPath) Then
                Debug.WriteLine("경고: WebView2 Fixed Version을 찾을 수 없습니다. Manual 기능이 제한될 수 있습니다.")
                ' 사용자에게는 Manual 메뉴를 클릭할 때만 알림
            End If

        Catch ex As Exception
            Debug.WriteLine("WebView2 체크 중 오류: " & ex.Message)
        End Try
    End Sub
End Class