cgeier 187 Junior Poster

movementClass.cs:

Add the following "using" statements:

using System.Drawing; and
using System.Windows.Forms;

public static class movementClass 
{
    public static void moveLeft(PictureBox moveBox)
    {
        Point p = moveBox.Location;
        p.X -= 20;
        moveBox.Location = p;
    }

    public static void moveDown(PictureBox moveBox)
    {
        Point p = moveBox.Location;
        p.Y += 20;
        moveBox.Location = p;
    }
}

Then in Form1.cs:

private void downBut_Click(object sender, EventArgs e)
{
    movementClass.moveDown(moveBox);
}

private void leftBut_Click(object sender, EventArgs e)
{
    movementClass.moveLeft(moveBox);
}
cgeier 187 Junior Poster

Try the following:

Boot into Safe Mode, then

  • Click "Start"
  • Select "Control Panel"
  • For View by, select "Small Icons" (or Large Icons)
  • Click "System"
  • Click "Advanced System Settings"
  • Do you want to allow the following program to make changes...? Click, "Yes"
  • Click "Advanced" tab
  • Under "Startup and Recovery", click "Settings"
  • Under "System failure", uncheck "Automatically restart"
  • Click "OK"
  • Click "OK"
  • Reboot computer.

If it successfully boots, you may see an error message which should help you identify what is causing the error.

cgeier 187 Junior Poster

Here's "doTasks" that is in the attached file above:

    Public Sub doTasks(ByVal username As String, _
                        ByVal ToolStripStatusLabel1 As ToolStripStatusLabel, _
                        ByVal StatusStrip1 As StatusStrip, _
                        ByVal MenuStrip1 As MenuStrip, _
                        ByVal databaseProduct As String)

        Dim errMessage As String = String.Empty
        Dim permissionsDt As DataTable = Nothing

        'set private variable values
        'used by other methods
        _ToolStripStatusLabel1 = ToolStripStatusLabel1
        _StatusStrip1 = StatusStrip1

        Try

            If databaseProduct = "SQLExpress" Then
                'get user permissions from db
                permissionsDt = getPermissionsSQLExpress(username)
            ElseIf databaseProduct = "mySQL" Then
                'get user permissions from db
                permissionsDt = getPermissionsMySQL(username)
            Else
                errMessage = "Error: (doTasks): " & " Database product not supported. "
                errMessage += "Must be 'SQLExpress' or 'mySQL'."
                MessageBox.Show(errMessage)
                ToolStripStatusLabel1.Text = errMessage
                _StatusStrip1.Refresh()
            End If


            If permissionsDt IsNot Nothing Then
                setPermissions(permissionsDt, MenuStrip1)
            End If

        Catch ex As Exception
            errMessage = "Error: (doTasks): " & ex.Message
            MessageBox.Show(errMessage)
            ToolStripStatusLabel1.Text = errMessage
            _StatusStrip1.Refresh()
        End Try
    End Sub
cgeier 187 Junior Poster

You haven't show your declaration for "ImageCenterLock". I haven't used lock, but you should only maintain your lock as long as you need it. I'm not familiar with the implementation of lock in C#, but I believe your issue may be because you are returning before releasing the lock.

return

"The return statement terminates execution of the method in which it appears and returns control to the calling method. It can also return an optional value. If the method is a void type, the return statement can be omitted.

If the return statement is inside a try block, the finally block, if one exists, will be executed before control returns to the calling method."

Try commenting out value.Dispose(); and moving the closing bracket for your lock before the return statement.

       //value.Dispose(); //clear out the passed in image (seems to drastically reduce memory usage)

    }//release lock

    return TempImage;
}//ResizeCenter

Note: In my limited research, I couldn't find an example of "lock" being used in a method that returns a value. It may be possible that if you return before releasing the lock, the lock may be maintained and result in deadlocking. Which would explain the high memory usage.

cgeier 187 Junior Poster

To get a list of menus that exist in the MenuStrip (ex: MenuStrip1):

I use a class called "MenuInfo" to store the data.

MenuInfo.vb

Public Class MenuInfo
    Public Property name As String
    Public Property depth As Integer
    Public Property parent As String

    'constructor
    Public Sub New()
    End Sub

    'constructor
    Public Sub New(ByVal name As String, ByVal depth As Integer, ByVal parent As String)
        Me.name = name
        Me.depth = depth
        Me.parent = parent
    End Sub
End Class

The following recursive method will get all of the sub-menus (DropDownItems). The initial call to "getToolStripChildMenuNames" is in "getToolStripMenuNames".

getToolStripChildMenuNames:

    Private Sub getToolStripChildMenuNames(ByVal myToolStripMenuItem As ToolStripMenuItem, ByRef menuList As List(Of MenuInfo), ByRef depth As Integer)

        'increment depth
        depth += 1

        For Each child As ToolStripMenuItem In myToolStripMenuItem.DropDownItems

            'add menu name to list
            menuList.Add(New MenuInfo(child.Name, depth, myToolStripMenuItem.Name))

            'recursivesly call function to get all children
            getToolStripChildMenuNames(child, menuList, depth)
        Next

        'decrement depth
        depth -= 1

    End Sub

The following method will get the menu names on the MenuStrip and call "getToolStripChildMenuNames" to get the sub-menus:

getToolStripMenuNames:

    Private Sub getToolStripMenuNames(ByVal myMenuStrip As MenuStrip)

        Dim output As String = String.Empty

        'hold menu info
        Dim menuList As New List(Of MenuInfo)

        'keeps track of depth
        Dim depth As Integer = 0

        'get top level menus - File, Tools, etc...
        For Each item As ToolStripMenuItem In myMenuStrip.Items

            'add menu to list
            menuList.Add(New MenuInfo(item.Name, depth, ""))

            'get all child menu items - DropDownMenus
            getToolStripChildMenuNames(item, menuList, depth)
        Next

        output = "List of Menus:" + System.Environment.NewLine + System.Environment.NewLine …
cgeier 187 Junior Poster

The code above in AppPermissionTbl is how to do it for SQL Server and SQL Server Express.

cgeier 187 Junior Poster

Some of the sample data didn't get posted in the proper place. The 30 minute cut-off didn't allow me to edit it further. Here's the sample data with it's table:

AppPermission:
8ed48e48feb3bbc4b494ed738839f264

AppGroup:
66b90ac218ea776cb53c78031aa9b919

AppUser:
2ed94ff7aea05b5bf765b08b7e4b5d97

AppGroupPermission:
c2b796face8e6e1f894c375b42218d4e

AppUserGroup:
a24386456f4a95ad30e667d96bde91fa

Sample SQL Queries:

To get permissions for "user2":

SELECT AppGroupPermission.groupName, AppGroupPermission.permissionName 
FROM AppGroupPermission
INNER JOIN AppUserGroup
ON AppGroupPermission.groupName = AppUserGroup.groupName
WHERE AppUserGroup.userId = 'user2'

To get permissions for "user2" along with the description of the permissions:

SELECT t2.groupName, t2.permissionName, AppPermission.description 
FROM AppPermission
INNER JOIN
(SELECT AppGroupPermission.groupName, AppGroupPermission.permissionName 
FROM AppGroupPermission
INNER JOIN AppUserGroup 
ON AppGroupPermission.groupName = AppUserGroup.groupName
WHERE AppUserGroup.userId = 'user2') t2 
ON t2.permissionName = AppPermission.name

Here's how to create a table programmatically:

Need to add Imports System.Data.SqlClient

    Public Sub AppPermissionTbl()

        Try

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

                sqlText = "CREATE TABLE AppPermission (name nvarchar(50) NOT NULL "
                sqlText += "CONSTRAINT PK_AppPermission_name PRIMARY KEY, "
                sqlText += "description nvarchar(100))"

                'open connection
                cn.Open()

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

                    'execute
                    sqlCmd.ExecuteNonQuery()
                End Using

                System.Windows.Forms.MessageBox.Show("Table created: AppPermission", "Table Created.", MessageBoxButtons.OK, MessageBoxIcon.Information)

            End Using

        Catch ex As SqlClient.SqlException
            System.Windows.Forms.MessageBox.Show("Error:: AppPermissionTbl: " & ex.Message, "Error - Create Table", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Catch ex As Exception
            System.Windows.Forms.MessageBox.Show("Error:: AppPermissionTbl: " & ex.Message, "Error - Create Table", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

There are documents attached below (in rich text format) that contain …

savedlema commented: Thank you very much. +2
cgeier 187 Junior Poster

My previous post used some reserved words. Also, I've worked on the db structure a little more.

The table names are as follows:

  • AppPermission
  • AppGroup
  • AppUser
  • AppGroupPermission
  • AppUserGroup

AppPermission:
1108c510eabdb09a80eb1b5db286a1d1

Version 1:

CREATE TABLE AppPermission (name nvarchar(50) NOT NULL
CONSTRAINT PK_AppPermission_name PRIMARY KEY,
description nvarchar(100))

02a60930a312d51d1647e31911ae938b

AppGroup:
e4affaf657ed9f90d3ebb933470bea98

CREATE TABLE AppGroup (name nvarchar(50) NOT NULL
CONSTRAINT PK_AppGroup_name PRIMARY KEY,
description nvarchar(100))

AppUser:
5685619a43cf330db55a84e8f5094f75

CREATE TABLE AppUser (id nvarchar(25) NOT NULL
CONSTRAINT PK_AppUser_id PRIMARY KEY,
firstName nvarchar(50) NOT NULL,
lastName nvarchar(50) NOT NULL,
password nvarchar(25))

AppGroupPermission:
0d55775e82e90340697876b52d6b9822

CREATE TABLE AppGroupPermission (groupName nvarchar(50) NOT NULL,
permissionName nvarchar(50) NOT NULL,
CONSTRAINT PK_groupName_permissionName
PRIMARY KEY(groupName, permissionName), 
CONSTRAINT FK_AppGroupPermission_AppGroup_groupName 
FOREIGN KEY (groupName) 
REFERENCES AppGroup(name) 
ON DELETE CASCADE ON UPDATE CASCADE, 
CONSTRAINT FK_AppGroupPermission_AppPermission_permissionName 
FOREIGN KEY (permissionName) 
REFERENCES AppPermission(name) 
ON DELETE CASCADE ON UPDATE CASCADE)

AppUserGroup:
356438f2e06fc98e99d7dd8d2304221d

CREATE TABLE AppUserGroup (userId nvarchar(25) NOT NULL,
groupName nvarchar(50) NOT NULL,
CONSTRAINT PK_userId_groupName
PRIMARY KEY(userId, groupName), 
CONSTRAINT FK_AppUserGroup_AppGroup_groupName 
FOREIGN KEY (groupName) 
REFERENCES AppGroup(name) 
ON DELETE CASCADE ON UPDATE CASCADE, 
CONSTRAINT FK_AppUserGroup_AppUser_userId 
FOREIGN KEY (userId) 
REFERENCES AppUser(id) 
ON DELETE CASCADE ON UPDATE CASCADE)

3e7b4dad8cac132b7487a93187c47a56

savedlema commented: Thank you very much. +0
cgeier 187 Junior Poster

Store all of the menu names that will require access permissions in a table.

Create table: Menu
Column: name (PK)

or

Column: id (PK)
Column: name

Create table: Group
Column: name (PK)
Column: menuPermissions (PK); FK references Menu.name

Create table: UserPermission
Column: id (PK); FK references User.id
Column: groupName (PK); FK references Group.name

Create table: User
Column: id (PK)
Column: firstName
Column: lastName
Column: password

Add a permission for each menu item--some of the items you may be able to group together and some menu items may be dependent on others. If someone doesn't have access to the file menu, they shouldn't have access to the edit menu under file menu. The following is not tested:

Dim FileMenuAccess as Boolean = False
Dim FileEditMenuAccess as Boolean = False
Dim FileBackupMenuAccess as Boolean = False
          ...

If FileMenuAccess = True Then
   'enable file menu

   If FileEditMenuAccess = True Then
      'enable file-edit menu
   Else
      'disable file-edit menu
   End If
Else
   'disable file menu
End If

Private Sub GetMenuPermissions()
   'get menu permissions for user from database

End Sub

Or

You could use a dictionary:

Dim menuDict as New Dictionary(Of String, Boolean)

If menuDict.Contains("FileMenuAccess") Then
   'enable file menu

   If menuDict.Contains("FileEditMenuAccess") Then
      'enable file-edit menu

   Else
      'disable file-edit menu

   End If
Else
   'disable file menu

End If

Private Sub GetMenuPermissions()
   'get menu permissions for user from database
   'add each menu permission to menuDict

End Sub
savedlema commented: Thank you very much. You solved my problem and now I'm okay. +2
cgeier 187 Junior Poster

That's not how it works in the real world. You need to identify your requirements and then figure out how to translate that into a program. How does one do that? Here are some steps to get you started:

  1. Get a copy of your transcript--so you know what one looks like
  2. Make an appointment with a few of your teachers. Tell them briefly about your project and ask them about the process they use to submit your grades. Ask him/her if there are any features that he/she would like that don't currently exist.
  3. Make an appointment with someone in the registrar's office, and find out as much as you can about the process they use to process student grades--you may need to meet with different people as they may do/use different parts. Take pictures or draw sketches of what you see. If a computer system already exists, you may be able to mimic what currently exists. If no computer system exists, document the current process--make sure to meet with multiple people to identify "best practices".
  4. Read a book on software engineering.
  5. Identify approximately how much data there will be. How does one do that? How many students are there at the university? Approximately how many classes does each student take each semester/quarter? Identify the best data structure to hold your data. In this case, it is probably a database. If we use a database, identify which database software can handle the amount of data that will be produced.

Note:

cgeier 187 Junior Poster

This is not an expert with this, but I believe you need to use a programmable microcontroller. Or a pre-built product that contains a microcontroller.

cgeier 187 Junior Poster

Also, line #20 should probably be:

printf("Approximate value of PI is %.9f\n", PI);

Changed from %9.f to %.9f and from sum to PI

cgeier 187 Junior Poster

In line #10, you trying to use x, but it has not been initialized (x doesn't have a value).

for (i=1; i<x; i++)

ddanbe commented: keen eye +15
cgeier 187 Junior Poster

Use another do-while loop (ie: use nested do-while loop)

do{

   do{

       ...
       case 1:
       ...
       case 2:
       ...

   }while(....);

}while(....);
cgeier 187 Junior Poster

Where is the definition for AMSCONN?

Using statement:

You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. In this case, the object remains in scope after control leaves the using block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it is generally better to instantiate the object in the using statement and limit its scope to the using block.

GagaCode commented: that really helped a lot thank you so much +0
cgeier 187 Junior Poster

I've never used "Xml.Serialization", but the following has been tested with the XML file you provided above:

    Private Sub getEmployeeData(ByVal filename As String)
        Dim doc As New Xml.XmlDocument

        Dim numEmpleado As String = String.Empty
        Dim selloSAT As String = String.Empty
        Dim selloCFD As String = String.Empty
        Dim noCertificadoSAT As String = String.Empty
        Dim uuid As String = String.Empty
        Dim fechaTimbrado As String = String.Empty

        If Not (System.IO.File.Exists(filename)) Then
            MessageBox.Show(filename + " not found.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Return 'exit
        End If


        Try
            'load XML document
            doc.Load(filename)

            'set up NameSpaceManager
            Dim man As Xml.XmlNamespaceManager = New Xml.XmlNamespaceManager(doc.NameTable)

            'get the following information from the line that has
            'the following format:
            'xmlns:<prefix>=<url>

            'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            'add "xsi" to namespace
            man.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3")

            'xmlns:nomina="http://www.sat.gob.mx/nomina"
            'add "nomina" to namespace
            man.AddNamespace("nomina", "http://www.sat.gob.mx/nomina")

            'xmlns:tfd="http://www.sat.gob.mx/TimbreFiscalDigital"
            'add "tfd" to namespace
            man.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital")

            'get "nomina:Nomina" node
            Dim xmlNominaNominaNode As Xml.XmlNode
            xmlNominaNominaNode = doc.SelectSingleNode("/cfdi:Comprobante/cfdi:Complemento/nomina:Nomina", man)


            'if xmlNominaNominaNode has attributes, read them
            If Not (xmlNominaNominaNode.Attributes Is Nothing) Then
                For Each myAttrib As Xml.XmlAttribute In xmlNominaNominaNode.Attributes

                    'Console.WriteLine("     " & myAttrib.Name & ":" + myAttrib.Value)

                    If myAttrib.Name = "NumEmpleado" Then
                        numEmpleado = myAttrib.Value
                    End If
                Next
            End If


            'get "tfd:TimbreFiscalDigital" node
            Dim xmlTfdTimbreFiscalDigital As Xml.XmlNode
            xmlTfdTimbreFiscalDigital = doc.SelectSingleNode("/cfdi:Comprobante/cfdi:Complemento/tfd:TimbreFiscalDigital", man)


            'if xmlTfdTimbreFiscalDigital has attributes, read them
            If Not (xmlTfdTimbreFiscalDigital.Attributes Is Nothing) Then
                For Each myAttrib As Xml.XmlAttribute In xmlTfdTimbreFiscalDigital.Attributes

                    'Console.WriteLine("     " & myAttrib.Name & ":" + myAttrib.Value)

                    If myAttrib.Name = "selloSAT" Then
                        selloSAT = myAttrib.Value

                    ElseIf myAttrib.Name = "selloCFD" Then
                        selloCFD = myAttrib.Value

                    ElseIf myAttrib.Name …
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

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

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

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 …
cgeier 187 Junior Poster
cgeier 187 Junior Poster

Please review the following documentation:

For-each loop

"...When you see the colon (:) read it as “in.” "

Applied to one of your loops:
for(int bigTemp: studentsArray){

The loop reads as “for each int bigTemp in studentArray.”

Arrays

"a one-dimensional array is created of the specified length, and each component of the array is initialized to its default value"

Initial Values of Variables

"For type int, the default value is zero, that is, 0."

For loop

"...the variable...holds the current value from the...array..."

Applied to one of your loops:
for(int bigTemp: studentsArray){

Assume we entered "3" for students.

Then,

students = 3

The code states:

int[] studentsArray = new int[students];

So,

int[] studentsArray = new int[3]; 

On the first iteration,
bigTemp = studentsArray[0] which contains 0.

On the second iteration,
bigTemp = studentsArray[1] which contains 0.

On the third iteration,
bigTemp = studentsArray[2] which contains 0.

So, as you can see the value "n" you have in line 25:

int n = bigTemp+1;

is always 1.

students: 2
exam grades: 4

students x exam grades = 2 x 4 = 8

which is the number of times the following occurs:

System.out.println("Enter a score for student number: "+n);
cgeier 187 Junior Poster

What seems to be the issue?

Sentintel value

cgeier 187 Junior Poster

I will be showing how to pass data between two forms in VB .NET. I will be using two forms, two classes which we will define, a delegate, an event, and an event handler. It is my first tutorial and 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:"

Here is what I will be using:

  • 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 "ScheduleInfo.vb". An instance of this class will be used to hold the data that we want to pass between the forms. It only contains two variables. You can add more if you like.

Public Class ScheduleInfo
    Public Name As String = String.Empty
    Public EventType As String = String.Empty
End Class

Next, we create "ValueUpdatedEventArgs.vb":

Public Class ValueUpdatedEventArgs

End Class

We want to inherit from System.EventArgs, so we add …

Reverend Jim commented: Nice tutorial. +12
ddanbe commented: An often asked subject well done! +15
cgeier 187 Junior Poster

Place numbers 1-16 in an ArrayList:

        //holds numbers 1-16
        ArrayList uniqueNums = new ArrayList();

        //add numbers 1-16
        for (int i=0; i < 16; i++)
        {
            uniqueNums.add(i+1);
        }//for

Use the following random number generator method. It was taken from here.

randInt:

    public static int randInt(int min, int max) {

        // Usually this can be a field rather than a method variable
        Random rand = new Random();

        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        int randomNum = rand.nextInt((max - min) + 1) + min;

        return randomNum;
    }

"randInt" is used below.
Generate unique random numbers like this:

        //choose random int
        for (int j = 15; j >= 0; j--)
        {
            int selectedNum = randInt(0,j);

            //i print out the selected number.
            //you will add it to your matrix here
            System.out.println("selected:  " + uniqueNums.get(selectedNum));

            //after a number is added to the
            //matrix, remove it from
            //the arraylist
            uniqueNums.remove(selectedNum);

            System.out.println();
        }//for

You can add your numbers to the matrix where I have the "System.out.println...." statement.

cgeier 187 Junior Poster

Where are you clearing the items? It should be

OleDbDataReader CMBRdr = DBcmd.ExecuteReader();           

//add it here
PhoneCombo.Items.Clear();

while (CMBRdr.Read())
{
GagaCode commented: that did get the job done +0
cgeier 187 Junior Poster

Backup your favorites from "C:\Users\<username>\Favorites" to somewhere else. Un-install IE 11. Reboot. Then re-install IE 11.

Also run a chkdsk on your hard drive. Start => Computer => Right-click "C:" => and select "Properties", Tools => Check Now = > select both checkboxes => Start

cgeier 187 Junior Poster

I think Reverend Jim found your error. An update to my post. I incorrectly converted to decimal. Line 7 in "Usage" should be Decimal.TryParse(TextBox1.Text, myVal1) instead of myVal1 = Convert.ToDecimal(TextBox1).

Also, you may consider doing some error handling:

    Dim sqlText as String
    Dim sqlCmd As SqlCommand

    Try

        .......

        sqlText = @"INSERT INTO myTable(col1, col2) VALUES(@myVal1, @myVal2)"

        .......

    Catch ex As System.Data.SqlClient.SqlException
            Console.WriteLine(ex.Message + " (SQL: " + query + ")")

            'if using OleDb
    Catch ex As System.Data.OleDb.OleDbException
        Console.WriteLine(ex.Message + " (SQL: " + sqlText + ")")

    Catch ex As Exception
        Console.WriteLine(ex.Message + " (SQL: " + sqlText + ")")
    Finally
        sqlCmd.Dispose()
    End Try
cgeier 187 Junior Poster

I left out some things in my previous post. Try this:

Add Imports System.Data.SqlClient

    Private Sub insertMyTable(ByRef conn As SqlConnection, ByVal myVal1 As Decimal, ByVal myVal2 As String)

        Dim sqlCmd As SqlCommand
        Dim sqlText As String

        If (conn.State <> System.Data.ConnectionState.Open) Then
            conn.Open()
        End If

        sqlCmd = New SqlCommand()

        sqlText = @"INSERT INTO myTable(col1, col2) VALUES(@myVal1, @myVal2)"
        sqlCmd.Connection = conn
        sqlCmd.CommandText = sqlText

        Dim paramName0 As SqlParameter
        paramName0 = New SqlParameter()

        paramName0.SqlDbType = SqlDbType.Decimal
        'paramName0.SqlDbType = SqlDbType.Float
        'paramName0.SqlDbType = SqlDbType.Int
        'paramName0.SqlDbType = SqlDbType.Money
        paramName0.Direction = ParameterDirection.Input
        paramName0.Value = myVal1
        sqlCmd.Parameters.Add(paramName0)

        Dim paramName1 As SqlParameter
        paramName1 = New SqlParameter()
        paramName1.SqlDbType = SqlDbType.VarChar
        paramName1.Direction = ParameterDirection.Input

        If (myVal2 Is Nothing) Then
            paramName1.Value = DBNull.Value
        Else
            paramName1.Value = myVal2
        End If

        sqlCmd.Parameters.Add(paramName1)

        sqlCmd.ExecuteNonQuery()
    End Sub

Usage:

        Dim conn As SqlConnection
        conn = New SqlConnection("Server=GEN-PC;Data Source=GEN-PC\SQLEXPRESS;Initial Catalog=Brgy;Integrated Security=True;")

        Dim myVal1 As Decimal
        Dim myVal2 As String

        myVal1 = Convert.ToDecimal(TextBox1)
        myVal2 = TextBox2.Text

        insertMyTable(conn, myVal1, myVal2)

Alternatively you could use sqlCmd.Parameters.AddWithValue("@myVal1", myVal1). The important thing is to make sure "myVal1" is the correct data type before passing it to the statement. This version may cause implicit data conversions during insert which may cause performance issues.

cgeier 187 Junior Poster

You're still passing "string" data.

    Private Sub insertMyTable(ByRef conn As SqlConnection, ByVal myVal1 As Decimal, ByVal myVal2 As String)

        Dim sqlCmd As SqlCommand

        Dim sqlText As String

        sqlCmd = New SqlCommand()

        sqlText = @"INSERT INTO myTable(col1, col2) VALUES(@myVal1, @myVal2)"

        Dim paramName0 As SqlParameter
        paramName0 = New SqlParameter()

        paramName0.SqlDbType = SqlDbType.Decimal
        'paramName0.SqlDbType = SqlDbType.Float
        'paramName0.SqlDbType = SqlDbType.Int
        'paramName0.SqlDbType = SqlDbType.Money
        paramName0.Direction = ParameterDirection.Input
        paramName0.Value = myVal1
        sqlCmd.Parameters.Add(paramName0)

        Dim paramName1 As SqlParameter
        paramName1 = New SqlParameter()
        paramName1.SqlDbType = SqlDbType.VarChar
        paramName1.Direction = ParameterDirection.Input
        paramName1.Value = myVal2
        sqlCmd.Parameters.Add(paramName1)

        sqlCmd.ExecuteNonQuery()
    End Sub
cgeier 187 Junior Poster

I'm not an expert with regex, but have used it. I think that many of the regex engines use similar syntax although there are some small differences. What worked for me was to start with a small regex expression, test it and then keep adding to it until it did everything I needed. I don't know anything about groovy, but I think that the regular java regex may work.

Rather than starting with:

static propertyPattern = ~/@property\s([\w, =]+)\s(\w+)\s(*?)\w/

Start with

static propertyPattern = ~/@property\s([\w, =]+)/

or less if that is not returning any results.

Here is some basic stuff:
The regular expression is surrounded by forward slashes:

~/ your_regular_expression_goes_here /

\s matches a space, a tab, a line break, or a form feed

\w matches word character [A-Za-z0-9_]

? at end matches zero or one of the preceeding element

* at end matches zero or more of the preceeding element

+ at end matches one or more of the preceeding element

$ at end, matches the end of the string

[] : anything inside bracket are "or"...if it matches anything inside the bracket, it matches.

*? matches like *, however match is smallest possible match

(x) matches "x" and remembers the match (capturing)

(?:x) matches "x" but does not remember the match (non-capturing)

x|y matches either x or y

Also check out regex flags (such as multi-line)

Here are some resources:

cgeier 187 Junior Poster

I'm not an expert in this, but have you checked "Local Security Policy?

  • Control Panel
  • Administrative Tools
  • Local Security Policy
  • Security Settings
  • Local Policies
  • Security Options (and perhaps "User Rights Assignment")

Check the event logs:

  • Control Panel
  • Administrative Tools
  • Event Viewer
  • Applications and Services Log
  • Microsoft
  • Windows
  • NTLM
  • Operational

and

  • Control Panel
  • Administrative Tools
  • Event Viewer
  • Windows Logs
  • Security

Can you be more specific as to what you are clicking on?

cgeier 187 Junior Poster

As far as formatting goes, create a function call "space"

string space(int numSpaces)
{
    string mySpace;

    for (int i=0; i < numSpaces; i++)
    {
        mySpace += " ";
    }//for

    return mySpace;
}//

To use it: cout << space(9)

Change line 20 (and some of the other ones) to:

cout<< space(9) << "It is "<<word2.length()<<" characters long\n";

In line 38, move most of the output line outside of the for loops (to line 31):

cout<<"The leters in <"<<word1<<"> which are also in <"<<word2<<"> are:" << endl;

Line 38 becomes:

cout << word1[i] << space(1);

Put the following after the for loop (after line 41):

cout << endl;
Ezekiel_1 commented: I have actually used \t to create the tab. I wanted to get the codes right before formatting. thanks +0
cgeier 187 Junior Poster

If you have the ability to modify the database, you could change "Required" to "false" for the column, or assign a default value.

Alternatively, you could programmatically assign a default value. See below for an example:

*Note: Need using System.Data.OleDb; statement.

private static OleDbConnection dbConn = null;
static string connectStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|Vendors.accdb;";




    public static void InsertAddressBookMainTbl(ref OleDbConnection dbConn, string Country, string State)
    {
        OleDbCommand sqlCmd = null;
        string sqlText = string.Empty;
        string msg = string.Empty;

        try 
        {
            if (dbConn == null)
            {
                dbConn = new OleDbConnection(connectStr);
            } //if 

            if (dbConn.State != System.Data.ConnectionState.Open)
            {
                dbConn.Open();
            } //if 

            sqlCmd = new OleDbCommand();
            sqlText = @"INSERT INTO AddressBookMain(Country, State)
                            VALUES(@Country, @State)";

            sqlCmd.CommandText = sqlText;
            sqlCmd.Connection = dbConn; 

            OleDbParameter paramName0 = new OleDbParameter();
            paramName0.ParameterName = "@Country"; 
            paramName0.OleDbType = OleDbType.VarChar; 
            paramName0.Direction = ParameterDirection.Input; 
            //paramName0.Value = (object)Country ?? DBNull.Value; 

            //if the value is null or empty
            //the value will be "unavailable"
            paramName0.Value = (object)Country ?? "unavailable"; 
            sqlCmd.Parameters.Add(paramName0); 

            OleDbParameter paramName1 = new OleDbParameter();
            paramName1.ParameterName = "@State"; 
            paramName1.OleDbType = OleDbType.VarChar; 
            paramName1.Direction = ParameterDirection.Input; 
            //paramName1.Value = (object)State ?? DBNull.Value; 

            //if the value is null or empty
            //the value will be "unavailable"
            paramName1.Value = (object)State ?? "unavailable"; 
            sqlCmd.Parameters.Add(paramName1); 

            sqlCmd.ExecuteNonQuery();
        } //try
        catch(System.Data.OleDb.OleDbException ex)
        {
            msg = "ERROR: InsertAddressBookMainTbl: " + ex.Message + System.Environment.NewLine + System.Environment.NewLine;
            Console.WriteLine(msg);
            throw ex;
        } //catch
        catch(Exception ex)
        {
            msg = "ERROR: InsertAddressBookMainTbl: " + ex.Message + System.Environment.NewLine + "SQL:" + sqlText + System.Environment.NewLine;
            Console.WriteLine(msg);
            throw ex;
        } //catch
        finally
        {
            if (sqlCmd != null)
            {
                sqlCmd.Dispose();
            } //if
        } //finally
    } //InsertAddressBookMainTbl
GagaCode commented: a great answer i did not use the same function but it really helped me alot to find the answer thank you for the second time +0
cgeier 187 Junior Poster

Line 75, public Prog4() throws FileNotFoundException, delete throws FileNotFoundException, your program already catches this error, and it is not thrown again.

Line 98-103 & 132-137, a user doesn't want to see a stack trace, he/she wants to see a "friendly" error message. A stack trace gives the impression that something has gone terribly wrong. Try something like the following:

        filename = new File("machine.txt");

        try {
                input = new Scanner(filename);
        } catch (FileNotFoundException e) {

            System.out.println();
            System.out.println("Error: File: '" + filename.getAbsolutePath() + "' not found.");
            System.out.println();
            return;

        }//catch

Reading from a file is slow, if possible you only want to read the file once--not over and over again.

Many of your "case" statements are missing the "break;" statement.

Your indentation is inconsistent, and makes your code difficult to follow.

Line 234-236, you use a while statement without braces, only the first statement will be executed. Always use braces, even if not required. It will help to prevent unexpected results. Click Here
to read about some pitfalls in Java.

There may be more things, but this should help.

cgeier 187 Junior Poster

On your combobox, use either event "SelectedValueChanged" or "SelectedIndexChanged".

SelectedValueChanged

        private void EMP_CB_SelectedValueChanged(object sender, EventArgs e)
        {
            Console.WriteLine("ValueMember A: " + EMP_CB.ValueMember.ToString() + " DisplayMember A: " + EMP_CB.DisplayMember.ToString());

            //---------------------------
            //Get data for selected item
            //---------------------------
            DataRow selectedDataRow = ((DataRowView)EMP_CB.SelectedItem).Row;
            int empId = Convert.ToInt32(selectedDataRow["EMPCODE"]);
            string empName = selectedDataRow["EMPNAME"].ToString();

            Console.WriteLine("empId A: " + empId + " empName A: " + empName);
            Console.WriteLine();
        }

SelectedIndexChanged

        private void EMP_CB_SelectedIndexChanged(object sender, EventArgs e)
        {
            Console.WriteLine("ValueMember B: " + EMP_CB.ValueMember.ToString() + " DisplayMember B: " + EMP_CB.DisplayMember.ToString());

            //---------------------------
            //Get data for selected item
            //---------------------------
            DataRow selectedDataRow = ((DataRowView)EMP_CB.SelectedItem).Row;
            int empId = Convert.ToInt32(selectedDataRow["EMPCODE"]);
            string empName = selectedDataRow["EMPNAME"].ToString();

            Console.WriteLine("empId B: " + empId + " empName B: " + empName);
            Console.WriteLine();
        }

The code is the same inside both.

Taken from: Here and Here

GagaCode commented: that One Answered it +0
cgeier 187 Junior Poster

Need to use exception handling.

try
{
   //run your code here...

}
catch (FileNotFoundException e) {
    System.err.println("FileNotFoundException: " + e.getMessage());

    //do whatever you want to do when 
    //this exception happens
}//

Click Here for documentation.

cgeier 187 Junior Poster

Try writing the problem out in steps first. You can use pseudo-code (a combination of written language and computer language).

Prompt for number of assignments - "numAssignments"

for each assignment {
    Prompt for score - "enteredScore"

    totalScore = totalScore + enteredScore
}

averageScore = ....

Now convert that into code.
How do you write a proper for loop in C++? Convert the pseudo-code to a C++ for loop.

example data:
Score 1: 92
Score 2: 85
Score 3: 95

Using what I have above.

numAssignments = 3

How many assignments do you need to prompt for scores?
How can you write that in a for loop? Write it out on paper plugging in the values.

cgeier 187 Junior Poster

Read more about classpath. classpath Documentation

From the documentation:

...Multiple path entries are separated by semi-colons....

The default class path is the current directory. Setting the CLASSPATH variable or using the -classpath command-line option overrides that default, so if you want to include the current directory in the search path, you must include "." in the new settings.

Classpath entries that are neither directories nor archives (.zip or .jar files) nor '' are ignored.

Also, I think that in your first post, the colon in -classpath should be a semi-colon

cgeier 187 Junior Poster

I discovered another solution that lets you avoid 8.3 filenames. Use double-quotes. But you need to escape them with a '\'.

#include <cstdlib>

int returnVal = 0;

//need to put quotes if dir or filename contains spaces
//need to escape quotes
returnVal = system("\"c:/batch scripts/startmp3.bat\"");

if (returnVal != 0)
{
    printf("An error occurred while running the command.  (%i)\n",returnVal);
}//if
else
{
    printf("Command executed successfully.\n",returnVal);
}//else

return returnVal;

Here is another resource that may be of use:
How to spawn console processes with redirected standard handles

vibhu mishra commented: its not showing any illegal command and system() returing 0, but the problem is that my mp3 file is not playing..... on cmd same bath file work good and play mp3 +0
cgeier 187 Junior Poster

The following works for me:

#include <cstdlib>

//use 8.3 filename and directory name format
//my file is in "c:\batch scripts\startmp3.bat"

//To get the 8.3 directory name:
//in cmd window run > dir "c:\" /x | find /i "batch scripts"


system("c:\\batchs~1\\startmp3.bat"); //make sure to escape '\'

//should also be able to use:
//system("c:/batchs~1/startmp3.bat");

See How Windows Generates 8.3 File Name from Long File Names

The important thing is to use 8.3 (DOS) filenames.

cgeier 187 Junior Poster

Because it's not a TimeSpan. Use DateTime.Now.TimeOfDay. That is if ts1 is of type TimeSpan.

cgeier 187 Junior Poster

Convert string to char array, then check each character to see if it is a digit using Character.isDigit(char c)

See isDigit Documentation

OR

Use regex, with the split function.

See Java regex Documentation

See an Example Here

cgeier 187 Junior Poster
  1. Use a timer. For an example, Click Here

  2. Create 3 sorting functions.

  3. Use a counter.

  4. There is no substitution for practice.

cgeier 187 Junior Poster

Updated code:
added int permutationCount = 1;, permutationCount += 1;, and printf ("%d", permutationCount);

    #define AsciiArraySize 52

    int i,j = 0;
    int permutationCount = 1; //keeps track of # of permutations
    char asciiArray[AsciiArraySize]; 

    int arrCount = 0;

    // insert upper case letters
    // i = ascii character code
    for (i=65; i <= 90; i++)
    {
        asciiArray[arrCount] = i;
        arrCount += 1; //increment counter
    }//for

    // insert lower case letters
    // i = ascii character code
    for (i=97; i <= 122; i++)
    {
        asciiArray[arrCount] = i;
        arrCount += 1; //increment counter
    }//for


    //permutations of length 1
    for (i=0; i < AsciiArraySize; i++)
    {
        printf("%c \n", asciiArray[i]);
        permutationCount += 1;
    }//for

    //permutations of length 2
    for (i=0; i < AsciiArraySize; i++)
    {
        //print contents of array
        for (j=0; j < AsciiArraySize; j++)
        {
            printf("%c%c \n", asciiArray[i],asciiArray[j]);
            permutationCount += 1;
        }//for
    }//for

    printf ("%d", permutationCount);

Now add the code for passwords that are 3-characters long, and then passwords that are 4-characters long.

cgeier 187 Junior Poster

Check out the documentation for the scanner class.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html

It will throw "NoSuchElementException" if no line was found. If you don't haven't learned about exception handling yet, I would use "hasNext".

int myInt = 0;
String myString = "";

Scanner in = new Scanner(System.in);
in.useDelimiter("\n");

if (in.hasNextInt()){
     //read in int value
     myInt = in.nextInt();
}//if
else if (in.hasNext()){
     //read in String value
     myString = in.next();
}//else if
cgeier 187 Junior Poster

Here's a possible solution. Not sure what you are trying to accomplish, but this sounds like it should do it. There are probably better options.

int i;
String myNumberAsString;
myNumberAsString = Integer.toString(i);

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html#toString(int)

Then you can use the String function "charAt".

int indexNumber;
char desiredDigit;
String myDigitStr;
int myDigitInt;

desiredDigit = myNumberAsString.charAt(indexNumber);
//optional: convert back to an int
//convert back to String first
myDigitStr = Character.toString(desiredNumber);
//then, convert String back to int
myDigitInt = Integer.parseInt(myDigitStr);

System.out.println(desiredDigit);
jen140 commented: Thanks =) +1
cgeier 187 Junior Poster

Change the following line from:

Scanner number = new Scanner ( System.in );

To:

static Scanner number = new Scanner ( System.in );

OR better yet, just move it inside of the main method:

public static void main(String[] args)
{
     Scanner number = new Scanner ( System.in ); 
     int firstValue;

     System.out.print( "Please enter time in hours:" );
     firstValue = number.nextInt();
}

See my some of my posts in the following article on how to do error checking with scanner:
http://www.daniweb.com/forums/post998852.html#post998852

Also see the following article about using "static":
http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html

Teethous commented: Super helper. +1
cgeier 187 Junior Poster

You almost got it. You just need to get rid of a bunch of the following statements:

randomNumber = ((int)(0+ Math.random()* 11));

It really should only exist in one place. You can get rid of the rest of them.

for(int counterTrials = 0; counterTrials < numberOfRolls; counterTrials++)          
{            
     randomNumber = ((int)(0+ Math.random()* 11));

     if (randomNumber == 1)                
     {                    
          counter1++;
     }             

     if (randomNumber == 2)                
     {                    
          counter2++;                 
     }    

      ....
}

Or better yet, change to "else-if" statements. There's no need to check 11 "if" statements each time. If you use "else if", it only checks until it finds the one that satisfies the expression.

for(int counterTrials = 0; counterTrials < numberOfRolls; counterTrials++)          
{            
     randomNumber = ((int)(0+ Math.random()* 11));

     if (randomNumber == 1)                
     {                    
          counter1++;
     }             

     else if (randomNumber == 2)                
     {                    
          counter2++;                 
     }    

     else if (randomNumber == 3)                
     {                    
          counter3++;                 
     }

      ....
}

I guess this could be considered a nested statement (obviously not a nested for loop though), because you could re-write it as:

for(int counterTrials = 0; counterTrials < numberOfRolls; counterTrials++)          
{            
     randomNumber = ((int)(0+ Math.random()* 11));

     if (randomNumber == 1)                
     {                    
          counter1++;
     }//if             

     else{         
          if (randomNumber == 2)                
          {           
               counter2++;
          }//if                 
          else 
          {
               if (randomNumber == 3)                
               {           
                    counter3++;
               }//if 

                  .....
          }//else
     }//else    

     
}
VernonDozier commented: Good posts on this thread. +28