⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mainform.vb

📁 使用Access数据库演示的任务分配管理程序 一个使用ADO.NET基于Microsoft Access数据库演示的任务分配管理的程序
💻 VB
📖 第 1 页 / 共 4 页
字号:
'---------------------------------------------------------------------
'  This file is part of the Microsoft .NET Framework SDK Code Samples.
' 
'  Copyright (C) Microsoft Corporation.  All rights reserved.
' 
' This source code is intended only as a supplement to Microsoft
' Development Tools and/or on-line documentation.  See these other
' materials for detailed information regarding Microsoft code samples.
' 
' THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
' KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
' IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
' PARTICULAR PURPOSE.
'---------------------------------------------------------------------

Imports System.IO
Imports Microsoft.Win32
Imports System.Threading
Imports System.Deployment.Application

Public Class MainForm
    Inherits System.Windows.Forms.Form

    Private dsProjects As New DataSet
    Private dsTasks As New DataSet

    Public Sub New()
        MyBase.New()

        'workaround for OS thread culture (check documentation for more info)
        Dim selectedLanguage As String = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName

        Try
            selectedLanguage = My.Settings.Language
            If selectedLanguage <> String.Empty Then
                Thread.CurrentThread.CurrentUICulture = New System.Globalization.CultureInfo(selectedLanguage)
            End If
        Catch ex As Exception
            LogError.Write(ex.Message & vbNewLine & ex.StackTrace)
        End Try

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'get the my documents path
        m_MyDocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\"

        'set the correct menu item to be checked
        If (selectedLanguage = c_GermanCultureName) Then
            EnglishToolStripMenuItem.Checked = False
            GermanToolStripMenuItem.Checked = True
        Else
            EnglishToolStripMenuItem.Checked = True
            GermanToolStripMenuItem.Checked = False
        End If
    End Sub


    'primary middle tier component
    Private m_DataLayer As DataLayer = Nothing

    'background objects
    Private m_AsyncTasksResult As IAsyncResult = Nothing
    Private m_AsyncHistoryResult As IAsyncResult = Nothing

    'misc
    Private m_ControlsLocked As Boolean = False
    Private m_DataGridPrinter As DataGridPrinter = Nothing
    Private ReadOnly m_MyDocumentsPath As String = String.Empty
    Private m_IsOnline As Boolean = True 'default mode is online
    Private m_ProjectID As Integer = -1 'is our magic number for nothing
    Private m_SelectedFilter As TaskFilterValue = TaskFilterValue.AllTasks
    Private m_ResourceManager As New Resources.ResourceManager("TeamVision.Localize", System.Reflection.Assembly.GetExecutingAssembly())
    
    'offline file names
    Private Const c_OfflineTasksFile As String = "Tasks.xml"
    Private Const c_OfflineProjectsFile As String = "Projects.xml"
    Private Const c_OfflineTaskChangesFile As String = "TaskChanges.xml"
    Private Const c_OfflineLookUpTablesFile As String = "LookupTables.xml"

    'misc
    Private Const c_DefaultCultureName As String = ""
    Private Const c_GermanCultureName As String = "de"

    'custom exception for exiting the application
    Private Class ExitException
        Inherits ApplicationException

        Private m_Msg As String = String.Empty

        Public Sub New()
        End Sub

        Public Sub New(ByVal msg As String)
            m_Msg = msg
        End Sub

        Public Sub Show()
            If m_Msg <> String.Empty Then MessageBox.Show(m_Msg)
        End Sub
    End Class

#Region " MainForm Load & Close "
    Private Sub MainForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'display a splash screen because m_DataLayer takes considerable time to instantiate
        Dim sForm As New SplashForm()
        sForm.Show()
        Application.DoEvents()

        Try
            'instantiate the datalayer
            m_DataLayer = New DataLayer()
        Catch ex As UriFormatException
            'close the splash screen
            sForm.Close()

            MessageBox.Show(m_ResourceManager.GetString("Bad_DataLayerURL"), "Invalid URL")
            Me.Close()
            Return
        End Try

        'adjust the backcolor for the text box (default readonly color is grey)
        txtDescriptionText.BackColor = System.Drawing.SystemColors.Window

        'close the splash screen
        sForm.Close()

        'when data is data bound to a control, and it's data is updated,
        'the control will usally fire events as it updates itself
        'because we are doing something with these events, we decided to use a bit
        'to help us ignore unwanted events
        LockControls(True)

        'by default collaspe these expanding panels
        xpProgress.Collapse()
        xpHistory.Collapse()

        xpList.AutoScroll = True 'workaround for expanderlist designer bug

        LoadSettings()

        Try
            'check for the offline files
            If File.Exists(m_MyDocumentsPath & c_OfflineTasksFile) AndAlso File.Exists(m_MyDocumentsPath & c_OfflineProjectsFile) AndAlso File.Exists(m_MyDocumentsPath & c_OfflineLookUpTablesFile) Then
                Try
                    'engage offline mode
                    ChangeOnlineStatus(False)

                    'try to read the offline data
                    dsProjects.ReadXml(m_MyDocumentsPath & c_OfflineProjectsFile, XmlReadMode.ReadSchema)
                    dsTasks.ReadXml(m_MyDocumentsPath & c_OfflineTasksFile, XmlReadMode.ReadSchema)

                    'workaround: scheme doesn't include autoincrement
                    dsTasks.Tables(0).Columns("TaskID").AutoIncrement = True

                    'we now have exact data when the user went offline
                    dsTasks.AcceptChanges()

                    'if we have any changes then read them in
                    If File.Exists(m_MyDocumentsPath & c_OfflineTaskChangesFile) Then
                        dsTasks.ReadXml(m_MyDocumentsPath & c_OfflineTaskChangesFile, XmlReadMode.DiffGram)
                    End If

                    'because our project could have come from the registry let's verify it
                    'otherwise choose the first project id
                    If dsProjects.Tables(0).Rows.Find(m_ProjectID) Is Nothing Then
                        m_ProjectID = CType(dsProjects.Tables(0).Rows(0)("ProjectID"), Integer)
                    End If

                Catch ex As Exception
                    LogError.Write(ex.Message & vbNewLine & ex.StackTrace)
                    'we don't care what the error is, lets dump it and move on
                    Dim mbResult As DialogResult = MessageBox.Show(m_ResourceManager.GetString("MessageBoxShow_There_was_an_error_reading_theoffline_files") _
                        & vbNewLine & vbNewLine & m_ResourceManager.GetString("Do_you_want_to_go_online"), _
                            "", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, _
                                MessageBoxOptions.DefaultDesktopOnly)

                    Me.Refresh()
                    If mbResult = System.Windows.Forms.DialogResult.Yes Then
                        'user choose to go online
                        ChangeOnlineStatus(True)

                        DeleteOfflineFiles()
                        DsProjects.Clear()
                        DsTasks.Clear()
                    Else
                        Throw New ExitException()
                    End If
                End Try
            End If

            'if we didn't engage offline mode
            If m_IsOnline Then

                If DisplayLoginForm() = System.Windows.Forms.DialogResult.Cancel Then Throw New ExitException()
                ChangeOnlineStatus(True)

                'the user is authenticated
                'get the projects from the web service
                If Not GetProjects() Then Throw New ExitException(m_ResourceManager.GetString("ExitException_Unable_to_load_projects"))
                InitializeTasks()

                'we have project table let's verify the last projectID if we have projects
                If dsProjects.Tables(0).Rows.Count > 0 Then
                    dsProjects.Tables(0).PrimaryKey = New DataColumn() {dsProjects.Tables(0).Columns("ProjectID")}
                    If dsProjects.Tables(0).Rows.Find(m_ProjectID) Is Nothing Then
                        'projectID not found, select the first project
                        m_ProjectID = CType(dsProjects.Tables(0).Rows(0)("ProjectID"), Integer)
                    End If

                    'get the tasks for this project
                    If Not GetTasks(m_ProjectID, True) Then Throw New ExitException(m_ResourceManager.GetString("ExitException_Unable_to_load_tasks"))

                Else
                    m_ProjectID = -1 'no projects exist
                End If
            End If
        Catch ex As ExitException
            ex.Show()
            Me.Close()
            Return
        End Try

        'now that we have all three required datatables
        'we're going start binding the data to the controls
        DataGridViewTasks1.DataSource = dsTasks.Tables(0).DefaultView


        'databind the charts
        chartPriority.DataTable = dsTasks.Tables(0)
        chartPriority.DataMember = "PriorityID"

        chartProgress.DataTable = dsTasks.Tables(0)
        chartProgress.DataMember = "Progress"

        'note that the datasource for this history panel
        'is set when the asyncronous get history call is finished
        hPanel.TaskIDMember = "TaskID"
        hPanel.DisplayMember = "UserID"
        hPanel.OptionalDateMember = "DateModified"
        hPanel.MaxListItems = 5

        'bind the combo boxes
        cbProjects.DataSource = dsProjects.Tables(0).DefaultView
        cbProjects.DisplayMember = "Name"
        cbProjects.ValueMember = "ProjectID"
        cbProjects.SelectedValue = m_ProjectID

        cbFilter.DataSource = TaskFilter.GetValues()
        cbFilter.DisplayMember = "Text"
        cbFilter.ValueMember = "Value"
        LockControls(False)

        'set the task filter (either default or from registry)
        cbFilter.SelectedValue = m_SelectedFilter

        'make sure the first item is selected in the datagrid
        ResetDataGrid(True)

        UpdateStatusBarText()

        DataGridViewTasks1.Focus()
    End Sub

    ' Purpose here is to set the primarykey column
    Private Sub InitializeTasks()
        Dim db As New Database.AccessDb
        Dim ds As DataSet = db.GetDataSet("SELECT * FROM Tasks")

        dsTasks.Clear()
        dsTasks.Merge(ds)
        dsTasks.Tables(0).PrimaryKey = New DataColumn() {dsTasks.Tables(0).Columns("TaskID")}
    End Sub

    Private Sub MainForm_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing, MyBase.Closing, MyBase.Closing, MyBase.Closing
        Try
            'write out change file
            If Not m_IsOnline AndAlso dsTasks.HasChanges() Then
                dsTasks.GetChanges().WriteXml(m_MyDocumentsPath & c_OfflineTaskChangesFile, XmlWriteMode.DiffGram)
            Else
                'make sure there isn't a change file.
                Try
                    File.Delete(m_MyDocumentsPath & c_OfflineTaskChangesFile)
                Catch

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -