Closed Thread
Results 1 to 5 of 5

Thread: Backup current text in textbox after x amount of time

  1. #1
    Grue is offline Newbie
    Join Date
    Apr 2009
    Location
    Upper Peninsula of Michigan
    Posts
    12
    Rep Power
    0

    Backup current text in textbox after x amount of time

    Hello again everyone!

    I'm working on a text editor that, at current, can have open several text documents at any given time. The text is displayed in a large RichTextBox and the open documents are displayed on a sidebar on the left side of the window.

    Now, I wanted to make it so that if the program should terminate because of abnormal circumstances, that it would be able to restore the work of the user upon reopening. How I have accomplished this is by making the program create a .tmp file which corresponds exactly to the Index Number of the filename it is associated to in a list. The tmp file, when the file opens, is filled with the data from the original file.

    When the user switches to another open document, whatever changes were made to the document they were on are saved and the text of the tmp file corresponding to their selection in the listed files takes the old text's place in the text box.

    This I've incorporated without a hitch (well, for the most part; some glitches remain). I've also made it successfully restore files from the .tmp files, which it determines if there was a crash by determining if constantly updated RestoreInfo file exists, as well as the .tmp files. If they do, the user has the option to recover their work. When the program closes normally, the tmp files and RestoreInfo file are deleted.

    What I would like to implement is a feature that backs up the currently opened text document after, say, 10 minutes and saves it to it's respective tmp file, as some users, whether it be programming or otherwise, take a while to think on what they're doing and unless they switch their document choice around constantly, the backup's do not stay current.

    I looked at the Background Worker that VB.NET comes with stock, but I have no idea if that would suit my purposes, or how to use it.

    This is the entire code for my text editor. Sorry for the sloppyness:
    Code:
    'Needed so we can use the constantly utilized StreamReader and StreamWriter functions.
    Imports System.IO
    Public Class Form1
        'The SyntaxDB File will be used later when the function colorizing feature is implemented.
        Dim SyntaxDBFileAvail As Boolean = True
    
        'Working directories for temporary application data.
        Dim Dir As String = "C:\Documents and Settings\" + Environ("USERNAME") + "\Application Data\Code!\"
        Dim TempDir As String = "C:\Documents and Settings\" + Environ("USERNAME") + "\Application Data\Code!\temp\"
        Dim DirFile As String = "C:\Documents and Settings\" + Environ("USERNAME") + "\Application Data\Code!\SyntaxDB.txt"
    
        Dim TempCount As Integer = 0
    
        'Not sure I need this anymore. I think I adjusted the syntax
        'enough that I can almost remove it without disrupting much.
        Dim SafeIndCount As Integer
    
        Dim PrevSelInd As Integer = 0
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim SyntaxDBYN As Boolean = My.Computer.FileSystem.FileExists(DirFile)
            Dim TempDirYN As Boolean = My.Computer.FileSystem.DirectoryExists(TempDir)
            Dim TempFYN As Boolean = My.Computer.FileSystem.FileExists(TempDir + "*.tmp")
            Dim FInfoYN As Boolean = My.Computer.FileSystem.FileExists(Dir + "RestoreInfo.info")
            If ListBox1.Items.Count() = 0 Then
            End If
    
            If FInfoYN = False Then
                File.CreateText(Dir + "RestoreInfo.info")
            ElseIf FInfoYN = True Then
                MessageBox.Show("Code! has detected that it was not closed properly the last time it was exited. Would you like to recover the your project as it was at the time of Code! closed?", "Recover Files?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly)
                If MessageBox.Show("Code! has detected that it was not closed properly the last time it was exited. Would you like to recover the your project as it was at the time of Code! closed?", "Recover Files?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly) = Windows.Forms.DialogResult.Yes Then
                    'Add filenames back to the listbox.
                    Dim reader As String
                    reader = My.Computer.FileSystem.ReadAllText(Dir + "RestoreInfo.info")
                    Dim strs() As String
                    strs = Split(reader, Environment.NewLine)
                    For Each s As String In strs
                        ListBox1.Items.Add(s)
                    Next
                    'Change SelectedIndex to first file listing.
                    Dim RStreamReader1 As New StreamReader(TempDir + "0.tmp")
                    RichTextBox1.Text = RStreamReader1.ReadToEnd.ToString()
                    RStreamReader1.Close()
                    'FOR FUTURE REFERENCE: TempCount tells how many temporary files there are stored,
                    'but it is only cumulative and likely will not be very adaptive to the future change
                    'which will allow users to choose files to close out selectively from the listbox.
                    TempCount = ListBox1.Items.Count()
                    SafeIndCount = TempCount
                ElseIf MessageBox.Show("Code! has detected that it was not closed properly the last time it was exited. Would you like to recover the your project as it was at the time of Code! closed?", "Recover Files?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly) = Windows.Forms.DialogResult.No Then
                    FInfoYN = False
                    'Clean the temp directory so it doesn't cause anomolies, such as old data appearing where it shouldn't.
                    If (Directory.Exists(TempDir)) Then
                        For Each fName As String In Directory.GetFiles(TempDir)
                            If File.Exists(fName) Then
                                File.Delete(fName)
                            End If
                        Next
                    End If
                End If
            End If
            'Create a fresh SyntaxDB file if there is none.
            If SyntaxDBYN = False Then
                My.Computer.FileSystem.CreateDirectory(Dir)
                SyntaxDBYN = True
                If SyntaxDBYN = True Then
                    Try
                        Dim SyntaxDBFile As New StreamWriter(DirFile)
                        SyntaxDBFile.Close()
                        MsgBox("Custom Syntax Database file created. It has been saved in the Application Data directory of your current account. However, if you would like to place it somewhere specific, you may do so by going to Edit>Syntax DB>Advanced and choosing a custom directory.")
                        SyntaxDBFileAvail = True
                        SyntaxDBFile.Close()
                    Catch ex As Exception
                        'Perhaps later we can detect whether or not user is running Vista and change
                        'the directory for the database and other app temp data to a user privlidge
                        'accessible folder.
                        MsgBox("Custom Syntax Database file creation failed! The program will continue without it, and it will store custom additions temporarily in memory which will be lost after program is closed. However, you may create one manually in a directory of your choosing and direct the program to it by going to Edit>Syntax DB>Advanced and choosing a custom directory.")
                        SyntaxDBFileAvail = False
                    End Try
                ElseIf SyntaxDBYN = True Then
                End If
            End If
    
            Try
                My.Computer.FileSystem.CreateDirectory(TempDir)
            Catch ex As Exception
                MsgBox("Could not create temporary file directory! Please determine that you have the privlidges to access the Application Data section of your user account and try again. For Vista users, you may wish to use the Administrator Mode with this program.")
            End Try
            MsgBox("Welcome to the Pre-Alpha version of Code! The program current implements a small number of the features it will have later on, such as build intiation functionality for a variety of compilers, syntax suggestion, and formatting aid. More mature Pre-release versions will be open source. Enjoy what you can for now! ;)")
            RichTextBox1.Enabled = False
        End Sub
    
        'If the user selects to open a single file, it is read to a string in Unicode format, it's name
        'is added to the file list of open text docs, a temporary file created when the selected index
        'changes, and the RestoreInfo file is appended to.
        Private Sub SingleFileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SingleFileToolStripMenuItem.Click
            OpenFileDialog1.ShowDialog()
    
            Dim OpenedFileReader As New StreamReader(OpenFileDialog1.FileName.ToString())
            Dim MoveString As String = OpenedFileReader.ReadToEnd()
            RichTextBox1.Text = MoveString.ToString()
            OpenedFileReader.Close()
    
            ListBox1.Items.Add(Path.GetFileName(OpenFileDialog1.FileName.ToString()))
            ListBox1.SelectedIndex = ListBox1.Items.Count() - 1
    
            Dim ItemArray(Me.ListBox1.Items.Count - 1) As Object
            Me.ListBox1.Items.CopyTo(ItemArray, 0)
            Dim Data As String = Join(ItemArray, Environment.NewLine)
            'Refresh names list for restore info file.
            File.WriteAllText(Dir + "RestoreInfo.info", Data)
    
            TempCount = TempCount + 1
            SafeIndCount = TempCount
            If TempCount = 1 Then
                PrevSelInd = 1
            End If
            RichTextBox1.Enabled = True
        End Sub
    
        'When the index changes, the text document currently in view is backed up to it's respective
        'temporary file so it is safe and may be reopened later, and the temporary file of the newly
        'chosen document is read and it's contents sent to the Rich Text Box.
        Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
            Dim i As Integer = ListBox1.SelectedIndex()
    
            Dim BackupStreamWriter As New StreamWriter(TempDir.ToString() + PrevSelInd.ToString() + ".tmp")
            BackupStreamWriter.Write(RichTextBox1.Text.ToString())
            BackupStreamWriter.Close()
    
            Dim BackupStreamReader As New StreamReader(TempDir.ToString() + i.ToString() + ".tmp")
            RichTextBox1.Text = BackupStreamReader.ReadToEnd.ToString()
            BackupStreamReader.Close()
            PrevSelInd = i
        End Sub
    
        'Clean the temporary files and restore information if the Form is properly closed.
        Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
            If (Directory.Exists(TempDir)) Then
                For Each fName As String In Directory.GetFiles(TempDir)
                    If File.Exists(fName) Then
                        File.Delete(fName)
                    End If
                Next
            End If
            File.Delete(Dir + "RestoreInfo.info")
        End Sub
    
        'Opens a Save File Dialog, and saves the document as shown in the Rich Text Box according to
        'parameters specified by the user in the SaveFileDialog.
        Private Sub CurrentFileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CurrentFileToolStripMenuItem.Click
            SaveFileDialog1.ShowDialog()
            File.WriteAllText(SaveFileDialog1.FileName(), RichTextBox1.ToString())
        End Sub
    
        'Loops through and saves all open text documents to a directory specified by the user.
        Private Sub WholeProjectToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles WholeProjectToolStripMenuItem1.Click
            FolderBrowserDialog1.ShowDialog()
    
            Dim i As Integer = 0
            Do Until i = ListBox1.Items.Count()
                MsgBox(FolderBrowserDialog1.SelectedPath.ToString() + "\")
                Dim SaveFileWriter As New StreamWriter(FolderBrowserDialog1.SelectedPath.ToString() + "\" + ListBox1.Items.Item(i).ToString())
                SaveFileWriter.Write(File.ReadAllText(TempDir.ToString() + i.ToString() + ".tmp"))
                SaveFileWriter.Close()
                i = i + 1
            Loop
        End Sub
    
        'Exit program. The Form Closed property still applies here, so this is considered a valid escape.
        Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
            Application.Exit()
        End Sub
    
        'This needs a cleanup, but it basically, using the Add button, lets the user create a blank
        'text document to work with.
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            If ListBox1.Items.Count >= 1 Then
                ListBox1.Items.Add(TextBox1.Text.ToString())
                RichTextBox1.Text = ""
    
                Dim NewTextFileWriter As New StreamWriter(TempDir + TempCount.ToString() + ".tmp")
                NewTextFileWriter.Close()
                TempCount = TempCount + 1
                SafeIndCount = TempCount
                PrevSelInd = TempCount
            ElseIf ListBox1.Items.Count = 0 Then
                ListBox1.Items.Add(TextBox1.Text.ToString())
                RichTextBox1.Text = ""
    
                Dim NewTextFileWriter As New StreamWriter(TempDir + TempCount.ToString() + ".tmp")
                NewTextFileWriter.Close()
                ListBox1.SelectedIndex = TempCount
                SafeIndCount = TempCount
                PrevSelInd = TempCount
                TempCount = TempCount + 1
                SafeIndCount = TempCount
            End If
            RichTextBox1.Enabled = True
        End Sub
    End Class
    Any ideas or suggestions would be greatly appreciated. :)

    EDIT: There's a mistake in something I did with this version of the code that causes an exception trying to load more than 2 files at once. Disregard it if you see it.

    EDIT2: I seemed to have screwed up more than that with this code version, but I hope it still gives a clear idea.
    Last edited by Grue; 06-10-2009 at 07:02 PM.

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Location
    Advertising world
    Posts
    Many

     
  3. #2
    Join Date
    Apr 2009
    Location
    Uppsala, Sweden
    Posts
    9,547
    Blog Entries
    5
    Rep Power
    98

    Re: Backup current text in textbox after x amount of time

    The thing you need, is that a way to check if 10 minutes have passed?

  4. #3
    Grue is offline Newbie
    Join Date
    Apr 2009
    Location
    Upper Peninsula of Michigan
    Posts
    12
    Rep Power
    0

    Re: Backup current text in textbox after x amount of time

    Umm...yes, and after ten minutes passes I need it to perform a backup of the text the user is working on, then wait for another ten minutes to pass.

    I could use My.Computer.Clock.LocalTime.Minute() to get data to determine if 10 minutes passed (well, until it reaches 59 anyway), but I don't know how I could do that without disrupting the program.

    That, I don't know how to accomplish.

  5. #4
    Join Date
    Apr 2009
    Location
    Uppsala, Sweden
    Posts
    9,547
    Blog Entries
    5
    Rep Power
    98

    Re: Backup current text in textbox after x amount of time

    You can just add a timer with the interval 600000.

  6. #5
    Grue is offline Newbie
    Join Date
    Apr 2009
    Location
    Upper Peninsula of Michigan
    Posts
    12
    Rep Power
    0

    Re: Backup current text in textbox after x amount of time

    Quote Originally Posted by Vswe View Post
    You can just add a timer with the interval 600000.
    Wow...I can't believe I didn't think of that.

    That works, though. Thanks for the suggestion. With that taken care of I can deuglify my code a bit and continue.

Closed Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. showing current date/time problem !!
    By Paulo_Jorge in forum PHP Development
    Replies: 4
    Last Post: 06-22-2011, 12:42 PM
  2. Textbox working issue to lessen the time in typing
    By newphpcoder in forum JavaScript and CSS
    Replies: 4
    Last Post: 03-06-2011, 05:18 PM
  3. Open File text into Textbox
    By Psynic in forum C# Programming
    Replies: 6
    Last Post: 02-12-2010, 12:19 AM
  4. Amount of Time Programming Vs. Debugging
    By Roybob in forum General Programming
    Replies: 3
    Last Post: 01-08-2009, 01:42 PM
  5. Displaying Current Time and Date
    By dcs in forum C Tutorials
    Replies: 2
    Last Post: 12-11-2008, 03:35 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts