cgeier 187 Junior Poster

Ensure you are committing the data to the database.

cgeier 187 Junior Poster

Try a different AC adapter, to see if you still have the same problem.

cgeier 187 Junior Poster

Test your hard drive to see if it is bad.

cgeier 187 Junior Poster

Also, what happens when two or more users have the same first initial and same first 4 letters of the last name?

example:

  • Michael Richardson
  • Matthew Richards

Or if 2 or more people have the exact same names?

  • John Smith
  • John Smith

It is probably better to let the user choose his/her username. Check if the username is available. If not, prompt the user for a different username.

cgeier 187 Junior Poster

You could probably write your own installer in less time than it takes to troubleshoot the one you are currently using--considering you have to wait for response from someone else.

cgeier 187 Junior Poster

Call "Refresh" method. labelName.Refresh()

cgeier 187 Junior Poster

In that case, I recommend that you contact "InstallSimple" for support. You will have to work with them to identify the issue.

cgeier 187 Junior Poster

First of all there should be a way to exit the program without having to kill the process (in my opinion).

There are two versions of .NET 4--client and full version. Which version does your program use?

What version of the OS did you test it on? 32-bit or 64-bit? What version of the OS is the customer using (32-bit or 64-bit)?

It appears that your application requires Office. What version of Office did you test with (2007, 2010, 2013, etc...)? What version of Office is the customer using? Also, is the customer's Office 32-bit or 64-bit?

Did you compile your application for "Any CPU", or for "x86"?

It is difficult to know what the problem could be without knowing what your program does (seeing the code or you providing more information about it).

I would try compiling for "x86" rather than "Any CPU" and see if that resolves the issue. Or you could find an 64-bit OS to test it on.

Also the uninstaller doesn't work (32-bit Win 7).

cgeier 187 Junior Poster

I recommend you use an XML file (or a database) instead of a text file. You are using characters that could possibly be in the username or password ("-", "*").

cgeier 187 Junior Poster

PerplexedB: You can't do the following:

int positionSeparator = line.IndexOf("-");

if (line.Substring(0,positionSeparator) == name )
{

It will throw an exception for any line that doesn't contain a "-".
positionSeparator = -1 when a line doesn't contain a "-". line.Substring(0,-1) will throw an exception.

See my post here

cgeier 187 Junior Poster

To answer your original question:

            foreach (string line in lines)
            {
                string trimmedLine = line.Trim();

                if (trimmedLine.StartsWith("-"))
                {
                    int ID = line.IndexOf("-");

                    if (line.Substring(0,ID) == lines[i])
                    {

                        if (trimmedLine.StartsWith("*"))
                        {
                            int Pass = line.IndexOf("*");

                            if (line.Substring(Pass + 1) == txtPassword.Text)
                            {
                                Chapter_Home Home = new Chapter_Home();
                                Home.ShowDialog();
                                this.Close();
                            }//if
                            else
                            {
                                MessageBox.Show("Incorrent ID or Password");
                            }//else
                        }//if
                    }//if
                }//if
            }//foreach

*Note: The code in this post only prevents the issue that you previously mentioned--ArgumentOutOfRangeException.

cgeier 187 Junior Poster

The error isn't occuring on the line that contains "-". It is occuring when a line does NOT contain a "-". You didn't post enough of the text file. You need to post at least 2 - 3 complete records. You don't have to post the actual data, you can make up data as long as it is in the same format.

Why are you reading the file twice (using two different methods)? And why are you using two for loops?

Something like the following may help:

string[] lines = System.IO.File.ReadAllLines("Chapters.txt");

string userId  = string.Empty;
string userPassword = string.Empty;

foreach (string line in lines)
{
    string trimmedLine = line.Trim();

    if (trimmedLine.StartsWith("-"))
    {
        userId = trimmedLine.Substring(1);
    }//if
    else if (trimmedLine.StartsWith("*"))
    { 
        userPassword = trimmedLine.Substring(1);
    }//else if

}//foreach
cgeier 187 Junior Poster

String.IndexOf Documentation

Return Value: The zero-based index position of value if that string is found, or -1 if it is not. If value is String.Empty, the return value is 0.

line.Substring(0,ID): If value is not found "ID" = -1. You can't do the following: line.Substring(0, -1). It throws "ArgumentOutOfRangeException".

String.Substring Documentation

Exceptions:

ArgumentOutOfRangeException:

  • startIndex plus length indicates a position not within this instance.

-or-

  • startIndex or length is less than zero.

Fix: Ensure "ID" is >= 0 before trying to use it in your substring statement.

*Note: It is bad practice to use both "ID" and "Id" for variable names. It will lead to confusion and wasted time debugging.

cgeier 187 Junior Poster

If you host it on your computer you will need as static ip address. Or a domain name that will always resolve to your current ip address. If using a router, you'll need to forward the appropriate ports. Does each teacher use a pc? Or does someone use a mac or a tablet? You will need to implement user security. When a user is no longer employed their access needs to be revoked.

cgeier 187 Junior Poster

You'll want SQLEXP_..._Enu.exe and SQLManagementStudio. Although SQLEXPWT... may contain SQLEXP... and SQLManagement...

cgeier 187 Junior Poster

For VS2010 you will need to use Sql Server Express 2008.

cgeier 187 Junior Poster

How do they access the program now? Taking turns using a single computer? Does each teacher have his/her own text file or do all of the teachers use one text file? If all teachers use one text file then there is potential for issues--you may consider using a database like mySql or SQL Server Express (not Access because it is single-user).

Some people use something like DropBox to store the file and then access the text file there. There are many possibilities.

  • Create a web-based program
  • Create a way for the file to be accessed on the network (ie: VPN, DropBox, etc...)

*Note: If your program is submitting sensitive information such as credit card numbers, you'll want to make sure you are using an encrypted connection (ie: SSL).

cgeier 187 Junior Poster

Below is a link to an example using named parameters with OLEDB in Access 2007.

Access 2007 OleDb with parameters example

2007 Office System Driver: Data Connectivity Components

The "Create Database" code uses "ADOX.Catalog". There needs to be a reference to "Microsoft ADO Ext 2.8 for DDl and Security". If you are using XP, ensure you have MDAC 2.8 installed.

How to check for MDAC version

Microsoft Data Access Components (MDAC) Installation

Microsoft Data Access Components (MDAC) 2.8 SP1

Note: If using a 64-bit OS, you must compile for x86 because the data connectivity components are for x86.

cgeier 187 Junior Poster

Here's a copy of the project. It uses .NET 4.0.

  1. Build it.
  2. Run it.
  3. Click button to create database (CreateDB-Access).
  4. Click button to create table (CreateTbl-Access).
  5. Click button to insert test data (InsertTbl-Access).
  6. Click button to select from Product table (Select-Access).
cgeier 187 Junior Poster

It's difficult to know what your code is doing unless you post your code.

cgeier 187 Junior Poster

Although...I also have success with using named parameters with OleDb using the following:

Imports System.Data.OleDb

Public Module AccessDB

    Public dbName As String = "Inventory"
    Public connectStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\" & dbName & ".accdb"


    Public Sub SelectProductTbl()

        Try

            Using cn As New OleDbConnection(connectStr)
                Dim sqlText As String = String.Empty

                sqlText = "select [Item Id], [Item Name], [Item Type], [Quantity] from [Product] "
                sqlText += "where [Item Type] LIKE @parm"


                'open connection
                cn.Open()

                'create new OleDbCommand
                Using sqlCmd As New OleDbCommand(sqlText, cn)

                    sqlCmd.Parameters.AddWithValue("@parm", "B%")

                    'execute
                    Dim reader As OleDbDataReader = sqlCmd.ExecuteReader()

                    While (reader.Read())
                        Console.WriteLine("selectProductTbl: " & reader(0).ToString() & " " & reader(1).ToString())
                    End While
                End Using

            End Using

        Catch ex As OleDbException
            System.Windows.Forms.MessageBox.Show("Error:: SelectProductTbl: " & ex.Message, "Error - Select Table", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Catch ex As Exception
            System.Windows.Forms.MessageBox.Show("Error:: SelectProductTbl: " & ex.Message, "Error - Select Table", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

End Module
cgeier 187 Junior Poster

Using Parameters with an OleDbCommand or OdbcCommand

...The .NET Framework Data Provider for OLE DB and .NET Framework Data Provider for ODBC do not support named parameters for passing parameters to an SQL statement or a stored procedure. In this case, you must use the question mark (?) placeholder, as in the following example...

cgeier 187 Junior Poster

Create your report as a Word document using "Microsoft Word Object Library" (Microsoft.Office.Interop.Word).

cgeier 187 Junior Poster
cgeier 187 Junior Poster

Please post your code.

cgeier 187 Junior Poster

How is the second form opened? Does the first form open the second form? If so, create a constructor in the second form and pass the data in the constructor. If not, you can use events. See a tutorial here.

cgeier 187 Junior Poster

"Show" is not modal (ex: adminFrm.Show()), and execution continues after the form is opened. "ShowDialog" is modal, and further execution does not continue until the form is closed (ex: adminFrm.ShowDialog()). You can test this by putting Console.WriteLine statements before and after the statements:

        Dim adminFrm As AdministrationFrm

        adminFrm = New AdministrationFrm()

        Console.WriteLine("Before show")
        adminFrm.Show()
        Console.WriteLine("After Show")

and then

        Dim adminFrm As AdministrationFrm

        adminFrm = New AdministrationFrm()

        Console.WriteLine("Before ShowDialog")
        adminFrm.ShowDialog()
        Console.WriteLine("After ShowDialog")
cgeier 187 Junior Poster

The following changes will disable the timer while using the Adminstration form, and re-enable it when the Administration form is closed.

    Private Sub AdministrationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AdministrationToolStripMenuItem1.Click

        Dim adminFrm As AdministrationFrm

        adminFrm = New AdministrationFrm()

        'disable timer
        localTimer.Enabled = False

        adminFrm.ShowDialog()

        're-enable timer
        localTimer.Enabled = True
    End Sub

*Note: The Adminstration form should probably only be available to an application administrator--not to all users.

cgeier 187 Junior Poster

Rather than changing the database name in the connectStr like this:

Dim lConnectStr As String = connectStr

lConnectStr = lConnectStr.Replace("Database=" & dbName, "Database=master")
lConnectStr = lConnectStr.Replace("Catalog=" & dbName, "master")

Using cn As New SqlConnection(lConnectStr)

             ...

It would be better to create a new connection string and use it when necessary (in CreateDatabase, DropDatabase, and DatabaseExists):

Public managementConnectStr = "Server=.\SQLExpress;Database=master;Trusted_Connection=Yes;"

               ...

 Using cn As New SqlConnection(managementConnectStr)

               ...

SQLExpresDB.vb has been updated.

cgeier 187 Junior Poster

I added some functions to 'SQLExpress.vb' to check if the database exists, to check if a table exists, and modified "DropDatabase" as described above.

DatabaseExists:

    Public dbName = "ShiftRota"
    Public connectStr = "Server=.\SQLExpress;Database=" & dbname & ";Trusted_Connection=Yes;"

    Public Function DatabaseExists() As Boolean

        Dim dbExists As Boolean = False

        Dim lConnectStr As String = connectStr

        'attempting to connect to a db that doesn't exist, will 
        'throw an error. use master instead.
        lConnectStr = lConnectStr.Replace("Database=" & dbName, "Database=master")
        lConnectStr = lConnectStr.Replace("Catalog=" & dbName, "master")

        Using cn As New SqlConnection(lConnectStr)

            Dim sqlText As String = String.Empty

            sqlText = "use master; SELECT count(name) as DBCount from sys.sysdatabases where name = '" & dbName & "'"

            Try

                ' Open Connection

                cn.Open()

                ' Use SqlDataReader to get data from query

                Using sqlCmd As New SqlCommand(sqlText, cn)

                    Try

                        ' Use SqlDataReader to read data from query
                        Dim dr As SqlDataReader

                        dr = sqlCmd.ExecuteReader

                        While dr.Read()
                            If dr("DBCount") = 1 Then
                                dbExists = True
                            End If
                        End While

                    Catch ex1 As Exception

                        Throw New Exception("Error in DataReader. " + ex1.Message)

                    End Try

                End Using

            Catch ex As SqlException

                System.Windows.Forms.MessageBox.Show("Error:: DatabaseExists ( " & dbName & "): " & ex.Message, "Error - Database Exists", MessageBoxButtons.OK, MessageBoxIcon.Error)

            Catch ex As Exception

                System.Windows.Forms.MessageBox.Show("Error:: DatabaseExists ( " & dbName & "): " & ex.Message, "Error - Database Exists", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End Try

        End Using

        Return dbExists
    End Function

TableExists:

    Public Function TableExists(ByVal tableName As String) As Boolean

        Dim tblExists As Boolean = False

        Using cn As New …
cgeier 187 Junior Poster

When clicking on "Drop Tables", you need the offer the user the opportunity to cancel, in case the user accidently clicked the button.

Issue: The error "Error (Open Connection): Error in dataAdapter. Invalid object name 'Schedule'", is occuring during the table drop because the timer is still executing a query on the table.

Solution: Stop the timer (call "stopTimer") before dropping the tables.

Issue: Receiving "database in use" error when trying to drop the database.

Solution: Switch to 'master' before dropping the database. Also, set database to single-user mode before dropping.

    Public dbName = "ShiftRota"
    Public connectStr = "Server=.\SQLExpress;Database=" & dbname & ";Trusted_Connection=Yes;"

    Public Sub DropDatabase(ByVal dbName As String)

        If (System.Windows.Forms.MessageBox.Show("Are you sure you want to drop the database: '" & dbName & "'?  This will delete all TABLES and DATA in " & dbName & ".", "Database Drop", MessageBoxButtons.OK, MessageBoxIcon.Warning) = DialogResult.Cancel) Then

            ' Exit is user pressed Cancel

            Return

        End If

        Try


            Using cn As New SqlConnection(connectStr)

                Dim sqlText As String = String.Empty

                'switch to 'master' db and 
                'put db into single user mode to prevent connections, then drop it
                sqlText = "use master; Alter Database " & dbName & " set SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE " & dbName


                ' Open Connection

                cn.Open()

                ' Create new SqlCommand

                Using sqlCmd As New SqlCommand(sqlText, cn)

                    ' Execute

                    sqlCmd.ExecuteNonQuery()

                End Using

                System.Windows.Forms.MessageBox.Show("Database: '" & dbName & "' dropped.", "Drop Database", MessageBoxButtons.OK, MessageBoxIcon.Information)

            End Using

        Catch ex As SqlException

            System.Windows.Forms.MessageBox.Show("Error:: DropDatabase ( " & dbName & "): " …
cgeier 187 Junior Poster

Your original error was occuring in lines 26-31 above. You had the following:

Dim paramName2 As SqlParameter = New SqlParameter()

paramName1.ParameterName = "@finish"
paramName1.SqlDbType = SqlDbType.DateTime
paramName1.Value = finish
sqlCmd.Parameters.Add(paramName2)

The name is "paramName2", but you (accidently) wrote "paramName1" here (paramName1.ParameterName, paramName1.SqlDbType, paramName1.Value)

Change to the following:

Dim paramName2 As SqlParameter = New SqlParameter()

paramName2.ParameterName = "@finish"
paramName2.SqlDbType = SqlDbType.DateTime
paramName2.Value = finish
sqlCmd.Parameters.Add(paramName2)
cgeier 187 Junior Poster

Other than installing your program in %ProgramFiles%, you should not be writing to %ProgramFiles% (or HKEY_LOCAL_MACHINE in the registry).

Use one of the following directories to store your data:

Dim userProfileDir As String = Environment.GetEnvironmentVariable("USERPROFILE")

Dim allUsersProfileDir As String = Environment.GetEnvironmentVariable("ALLUSERSPROFILE")

Dim appDataDir As String = Environment.GetEnvironmentVariable("APPDATA")
cgeier 187 Junior Poster

Something like the following should work:

        'path from original file
        Dim source As String = "C:\temp\regextest.txt"

        'path new file
        Dim destination As String = "C:\temp\regextest2.txt"

        Dim newText As String = "300" 'new value

        Dim inputText As String = My.Computer.FileSystem.ReadAllText(source)

        'split lines
        Dim inputTextArray As String() = inputText.Split(New String() {"\r\n", "\n", "\r", System.Environment.NewLine}, StringSplitOptions.None)

        'used named capturing groups
        Dim pattern As String = "(?<label>l)=([""])(?<tag>.*)([""])"

        'create a substitution pattern for replace method
        Dim replacePattern As String = "${label}=""" & newText & """"

        Dim outputText As String = String.Empty

        For Each lineData As String In inputTextArray
            Dim result As String = Regex.Replace(lineData, pattern, replacePattern, RegexOptions.IgnoreCase)

            outputText += result & System.Environment.NewLine
        Next

        My.Computer.FileSystem.WriteAllText(destination, outputText, False)


        'My.Computer.FileSystem.WriteAllText(destination, My.Computer.FileSystem.ReadAllText(source).Replace(oldText, newText), False)
        Process.Start(destination) 'opens program in wordpath to control value

Adapted from here.

cgeier 187 Junior Poster
Dim dt As DateTime = DateTime.MinValue

dt = DateTime.Now.AddDays(7 - Weekday(DateTime.Now) + 1)

Console.WriteLine(dt.ToString("MM/dd/yyyy"))
cgeier 187 Junior Poster

Numerical values don't use quotes--only for text values. Remove single-quotes from Quantity, Min Shelf Stock, and Purchase Price.

cgeier 187 Junior Poster
Dim nextSunday As Integer

nextSunday = (DateTime.Now.AddDays(7)).Day - (Weekday(DateTime.Now)) + 1
cgeier 187 Junior Poster

Try posting more of your code. What version of VB .NET? What version of Outlook?

cgeier 187 Junior Poster

What are the data types for each of the columns in the database?

cgeier 187 Junior Poster

Why are you using all these parentheses?

FROM (((((Comp_Code INNER JOIN...

Also, why are you naming columns the same name as the table that contains it?

You're more likely to receive help if you provide some more information about the tables (or the create table syntax for each table). See here for an example of some table documentation that I created for that post.

cgeier 187 Junior Poster

I will be showing how to pass data between two forms in C#. I will be using two forms, two classes which we will define, a delegate, an event, and an event handler. It is a bit long because I wanted to make it easy to follow. If you want to skip the explanation and just see the code, scroll down to "The short version:"

  • A form named: MainFrm
  • A form named: ChildFrm
  • A class named: ScheduleInfo
  • A class named: ValueUpdatedEventsArgs

An instance of ChildFrm will be created and shown when clicking a button on the main form (MainFrm). After adding our data in the child form (ChildFrm), we will click a button on the child form to send the data back to the main form. Then on the main form we will display the newly received data, as well as add our data to a list (or update the data in the list if it was previously added).

Let’s start out by creating a new Project (select “Windows Forms Application”). Next, rename “Form1.cs” to “MainFrm.cs”. (Right-click "Form1.cs" in Solution Explorer and choose "Rename". Rename it to "MainFrm.cs". You should be prompted, "You are renaming a file. Would you like to perform a rename in this project of all references....?" Click, "Yes".) Right-click on the form, select “Properties” and change the “Text” property from “Form 1” to “MainFrm".

Now let’s create a new class called "ScheduleInfo.cs". An instance of this class will be used to hold the data that …

castajiz_2 commented: Well done!! +4
ddanbe commented: Great stuff! Must have missed it. Thanks. +15
cgeier 187 Junior Poster

On the computer that is running SQLExpress, ensure that the services are running:

  • SQL Server
  • SQL Server Browser

Database Connectivity

cgeier 187 Junior Poster

How are you connecting the computers? Through a router/switch? Or are you attempting to connect them using a cable between the LAN cards?

cgeier 187 Junior Poster
cgeier 187 Junior Poster

What version of XP (32-bit or 64-bit)? What version of Vista (32-bit or 64-bit)? What version of Win 7 (32-bit or 64-bit)?

Did you check that the necessary version of .NET is installed on the Vista and Win 7? There are two versions of .NET 4--a client version and a full version.

.Net 4 - Full

.Net 4 - Client

Another thing to check is if you do anything that requires elevated user permissions. UAC (user account control) settings could be preventing it from running

  • Control Panel
  • User Accounts
  • Change User Account Control settings
cgeier 187 Junior Poster
cgeier 187 Junior Poster

What do you mean by "different modules....in different project solutions"? Are you talking about a vb module (ex: Module1.vb, Module2.vb, etc)? Or are you talking about some forms that exist in different projects? Why did you choose to create them in separate projects? Is that a requirement for your project?

cgeier 187 Junior Poster

Here is a small program I wrote to help understand what nested for loops do:

        static void Main(string[] args)
        {
            string inputStr = String.Empty;
            int outerForLoopCount = 0;
            int firstNestedForLoopCount = 0;
            int secondNestedForLoopCount = 0;

            int totalOuterLoops = 0;
            int totalFirstNestedLoops = 0;
            int totalSecondNestedLoops = 0;

            do
            {
                Console.Write("How many times do you want to run the outer for loop? ");
                inputStr = Console.ReadLine();
            } while (Int32.TryParse(inputStr, out outerForLoopCount) == false);

            do
            {
                Console.Write("How many times do you want to run the 1st nested for loop? ");
                inputStr = Console.ReadLine();
            } while (Int32.TryParse(inputStr, out firstNestedForLoopCount) == false);

            do
            {
                Console.Write("How many times do you want to run the 2nd nested for loop? ");
                inputStr = Console.ReadLine();
            } while (Int32.TryParse(inputStr, out secondNestedForLoopCount) == false);

            for (int i = 0; i < outerForLoopCount; i++)
            {
                for (int j = 0; j < firstNestedForLoopCount; j++)
                {
                    for (int k = 0; k < secondNestedForLoopCount; k++)
                    {
                        totalSecondNestedLoops += 1;
                    }//for

                    totalFirstNestedLoops += 1;
                }//for

                totalOuterLoops += 1;
            }//for

            Console.WriteLine();
            Console.WriteLine("Outer for loop executed: " + totalOuterLoops + " time(s)");
            Console.WriteLine();
            Console.WriteLine("First nested for loop executed: " + totalFirstNestedLoops + " times(s)");
            Console.WriteLine("     This is " + outerForLoopCount + " * " + firstNestedForLoopCount);
            Console.WriteLine();
            Console.WriteLine("Second nested for loop executed: " + totalSecondNestedLoops + " times(s)");
            Console.WriteLine("     This is " + outerForLoopCount + " * " + firstNestedForLoopCount + " * " + secondNestedForLoopCount);
            Console.WriteLine("");
            Console.WriteLine("Press any key to quit");
            Console.ReadKey();
        }

14ef764bae9d7125ad1c57de5e47332a

cgeier 187 Junior Poster
cgeier 187 Junior Poster

I've updated 'getData' to use an SqlDataAdapter and added code that significantly reduces the number of times the labels are re-drawn (appearance of flashing on the form). This is an update to "DatabaseOnCallRotation-SqlDataReader.zip" but only contains a few of the changes that xrj made.

When other people make a lot of changes to your code, sometimes it no longer feels like it is your program. It is a good idea to separate the code into blocks that do a particular task (such as retrieving the data, showing the data, etc) as xrj did. This version is a progression towards that.

Using an SqlDataAdapter and DataTable will be better because it will make it easier for you to use your data as a DataSource should you decide to switch to another type of control (such as a DataGridView).

The code in 'getData' is still mostly your code, with a few additional modifications. It now uses a function called 'compareLabelLists'.

Add the following declaration inside 'Public Class MainFrm':

    'used to hold the names of the 
    'previous labels. This will prevent
    'controls from re-drawing every
    'updateInterval. Instead, only
    're-drawing if there are changes
    Dim previousLblList As List(Of Label) = New List(Of Label)

compareLabelLists:

    Private Function compareLabelLists(ByVal list1 As List(Of Label), ByVal list2 As List(Of Label))
        Dim areListsEqual As Boolean = True

        Try

            'if the number of elements is different
            'the lists can't be equal
            If list1.Count <> list2.Count Then
                areListsEqual = False
            Else

                'if the text of the …