cgeier 187 Junior Poster

What's the data type of the column in your database?

cgeier 187 Junior Poster

Subtitle Editor 3.3.15 Changelog
Installer version, .NET 2-3.5, 32-bit (will run on win 64-bit too, but needs 32-bit codecs/VLC)

cgeier 187 Junior Poster

Btw, that's the answer I gave you in my second post.

cgeier 187 Junior Poster

It appears that you are creating a new instance of Form2 which is why your data is not updated. What do you consider a "Preview". A copy of the form that can be modified? Or an image of the form that one can look at? If you are looking to provide an image, look up "screen capture" and/or "window capture". If you want to use a new instance of your form, look at the tutorial on form to form communication. You could create your other instance of Form2 (previewFrm2) : Private previewFrm2 as New Form2. Change the "Modifiers" on Form2 to public. When you receive the data updates on the main form, you can set the values on previewFrm2 to the same values (previewFrm2.TextBox1.Text = "new text value")

cgeier 187 Junior Poster

I think that you don't understand the difference between sub, function, module, and class.

Here's a basic description:

A "Function" is basically a "Sub" that returns a value.

Functions and Subs (as well as other things) are contained within Classes and/or Modules.

cgeier 187 Junior Poster

You haven't posted any code so it's difficult to know exactly what you are doing. Using WebBrowser1.Navigate("http://www.yourUrl", True) will open the url in a browser (IE) window. While using WebBrowser1.Navigate("http://www.yourUrl", False) or WebBrowser1.Navigate("http://www.yourUrl") will open it in your WebBrowser control (ex: WebBrowser1)

cgeier 187 Junior Poster

Have you checked the value of "intDays" after you call "getDaysOut(intDays)"?

You have the following:
Private Sub getDaysOut(intDays As Integer)

it should be:
Private Sub getDaysOut(ByRef intDays As Integer)

If you don't include "ByRef", the default is to pass the parameter "ByVal".

An alternative is:

    Private Function getDaysOut() As Integer
        Dim intDays As Integer = 0

        Console.Write("How many days did the customer have the DVD? ")

        If Int32.TryParse(Console.ReadLine(), intDays) Then
            getDaysOut = intDays
        Else
            getDaysOut = 0
        End If

    End Function

Usage:

Dim intDays As Integer = 0
intDays = getDaysOut()

        ...

Resource:
How to: Force an Argument to Be Passed by Value (Visual Basic)

...When you pass a variable by reference, you must use the ByRef keyword to specify this mechanism.

The default in Visual Basic is to pass arguments by value...

cgeier 187 Junior Poster

If you right-click the file and "Send To" => "Compressed (Zipped) Folder", you can attach it.

cgeier 187 Junior Poster

You can do the following:
Add Imports System.Text.RegularExpressions

Create a class named "VideoInfo.vb".

VideoInfo.vb:

Public Class VideoInfo
    Public Property videoNumber As String
    Public Property name As String

    Public Sub New()

    End Sub

    Public Sub New(ByVal videoNumber As String, ByVal name As String)
        Me.videoNumber = videoNumber
        Me.name = name
    End Sub

End Class

We will use the above class inside the following function.

    Private Function extractData(ByVal myData As String) As List(Of VideoInfo)

        'create new list for video info
        Dim videoInfoList As New List(Of VideoInfo)

        'pattern that we want to find
        'use named groups
        Dim pattern As String = "/video(?<vidNumber>[0-9]+)/[0-9]?/(?<vidName>[A-Za-z0-9]+)"

        'look for a match
        Dim myMatch As Match = Regex.Match(myData, pattern)

        'keep looking for matches until no more are found
        While myMatch.Success

            'get groups
            Dim myGroups As GroupCollection = myMatch.Groups

            'store extracted info in an instance of VideoInfo
            Dim myVideoInfo As New VideoInfo
            myVideoInfo.videoNumber = myMatch.Groups("vidNumber").Value
            myVideoInfo.name = myMatch.Groups("vidName").Value

            'add video info to the list
            videoInfoList.Add(myVideoInfo)

            'get next match
            myMatch = myMatch.NextMatch()
        End While

        Return videoInfoList
    End Function

To use it:

        Dim myData As String = String.Empty
        Dim myVideoInfo As List(Of VideoInfo)
        Dim output As String = String.Empty

        myData += "<p><a href=""/video7419004/0/CoD4"">CoD4</a></p>"
        myData += "<p><a href=""/video7419005/0/CoD5"">CoD5</a></p>"
        myData += "<p><a href=""/video7419006/0/CoD6"">CoD6</a></p>"

        myVideoInfo = extractData(myData)


        For Each video In myVideoInfo
            output += "video: " & video.videoNumber & " " & video.name
            output += System.Environment.NewLine
        Next

        'display for testing purposes
        MessageBox.Show(output)

Resources:

Regex: Named Capturing Groups in .NET

Regular Expressions in C# …

cgeier 187 Junior Poster

You can use XMLSerializer. To hold the data from the XML file, I use two classes. I will call them "UserListInfo.cs" and "UserInfo.cs"--you can name them anything you want (it is possible to specify that the element name is different from the class name).

UserInfo.cs:

  • Add using System.Xml.Serialization;

    [XmlRootAttribute(ElementName="user")]
    public class UserInfo
    {
        public string userid { get; set; }
        public string username { get; set; }
        public string password { get; set; }
        public string email { get; set; }
    
    }//class
    

Note: ElementName="user" specifies that the element name is "user", not "UserInfo". The default is to use the class name unless otherwise specified.

UserListInfo.cs:

  • Add using System.Xml.Serialization;

    [XmlRootAttribute(ElementName = "usersList")]
    public class UserListInfo
    {
        //Element
        [XmlElement()]
        public List<UserInfo> user = new List<UserInfo>();
    
    }//class
    

Note: ElementName="usersList" specifies that the element name is "usersList", not "UserListInfo".

To read the data:

Version 1 (uses BufferedStream):

private void deserializeFromXml(string filename)
{
    //create new instance of UserListInfo
    UserListInfo myUserListInfo = new UserListInfo();

    using (FileStream fs = File.Open(filename,FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        using (BufferedStream bs = new BufferedStream(fs))
        {
            using (StreamReader sr = new StreamReader(bs))
            {

                //create new instance of XmlSerializer
                XmlSerializer deserializer = new XmlSerializer(myUserListInfo.GetType());
                myUserListInfo = (UserListInfo)deserializer.Deserialize(sr);
                sr.Close();
                bs.Close();
                fs.Close();
            }//using
         }//using
     }//using

     string output = string.Empty;
     for (int i = 0; i < myUserListInfo.user.Count; i++)
     {
         output += myUserListInfo.user[i].userid;
         output += " " + myUserListInfo.user[i].password;
         output += System.Environment.NewLine;
     }//for

    //print out the data for testing purposes
    MessageBox.Show(output);
}//deserializeFromXml

Version 2:

private void deserializeFromXml(string filename) …
cgeier 187 Junior Poster

What are you using to view the initial web page?

cgeier 187 Junior Poster

See above where it says: usage of the attached file.

cgeier 187 Junior Poster
cgeier 187 Junior Poster

Can read data into a DataTable, manipulate it, then save it back to the file.

How to read a CSV file into a .NET DataTable

cgeier 187 Junior Poster

Your connection string is incorrect.

Should be:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Video Rental System\DvDSystem1.accdb"

Also add the following:

Catch ex As OleDB.OleDbException

Access Connection String

cgeier 187 Junior Poster

You haven't set txttotal.Text = "" or txttotal.Text = Nothingin "txtamount_TextChanged" or "txtquantity_TextChanged" if txtamount or txtquantity is null or empty.

cgeier 187 Junior Poster

The following seems to work:

Create a new project:

  • Click "File" (in menu)
  • Select "New Project"
  • Double-click "Visual C#" to expand
  • Click "Web"
  • Select "ASP .NET Web Application"
  • Enter a name, and click "OK"

Open Solution Explorer:

  • Click "View" (in menu)
  • Select "Solution Explorer"

Add a DataSet to the project:

  • Click "Project" (in menu)
  • Select "Add New Item"
  • Under "Installed Templates" (left side), under "Visual C#", Click "Data"
  • Select "DataSet"
  • Click "Add"
  • Click "View" (in menu)
  • Select "ToolBox"
  • Double-click "TableAdapter"
  • Select an existing connection (or click "New Connection" and fill out the form)
  • Click Next
  • Click Next
  • Leave "Use SQL Statements" radio button checked. Click "Next"
  • Click "QueryBuilder"
  • Select "Language" table
  • Click "Add"
  • Click "Close"
  • Check "LanguageID", "LanguageName", and "MotherTongueLanguageName" checkboxes
  • Click "OK"
  • Click "Next"
  • Click "Finish"

Add a web page to display our data:

  • Click "Project" (in menu)
  • Select "Add new item"
  • Under "Installed Templates" (left side), under "Visual C#", Click "Web"
  • Select "Web Form"
  • For name enter: "DisplayLanguageInfo.aspx"
  • Click "Add"
  • In the "DisplayLanguageInfo.aspx" source code (source tab), replace:

    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
    

With the following:

    <form id="form1" runat="server">
        <p>
        <asp:GridView ID="GridView1" runat="server" CssClass="DataWebControlStyle">
           <HeaderStyle CssClass="HeaderStyle" />
           <AlternatingRowStyle CssClass="AlternatingRowStyle" />
        </asp:GridView>
        &nbsp;
        </p>
    </form>

In "Solution Explorer":

  • Right-click "AddLanguageInfo.aspx"
  • Select "View Code" (this will show "DisplayLanguageInfo.aspx.cs")

Replace:

protected void Page_Load(object sender, EventArgs e)
{

}

With the following:

protected void Page_Load(object sender, EventArgs e)
{
    DataSet1TableAdapters.LanguageTableAdapter languageAdapter = new DataSet1TableAdapters.LanguageTableAdapter();
    GridView1.DataSource = languageAdapter.GetData();
    GridView1.DataBind(); …
cgeier 187 Junior Poster

This may be of use:
Globalization Step-by-Step

cgeier 187 Junior Poster

Are you using the DataSet designer? If so, check the parameters by doing the following:

Open Solution Explorer:

  • View
  • Solution Explorer
  • Click your dataset name (ex: DataSet1.xsd)

In Dataset Designer:

  • Right-click your table adapter (ex: LanguageTableAdapter) and select "Properties"

    a25c038267f13cf044f669cf48c69dda

  • Double-click "InsertCommand" to expand it
    426c071dbbde77656142295985e996a5

  • Click "..." on the right side of "Parameters"
  • Select "@MotherTongueLanguageName"

    353d7e6a1fb0797d1270d9d96d94c275

  • Ensure "DbType" is "String" (not AnsiString)

  • Ensure "ProviderType" is "NVarChar" (not VarChar)

Repeat for "UpdateCommand" (both @MotherTongueLanguageName and @Original_MotherTongueLanguageName)

cgeier 187 Junior Poster

The following is untested (and has the username and password replaced by an asterisk):

    Private Function call_hitung_denda_function(ByVal idPinjam As Decimal, ByVal tgl As String) As Integer
        Dim denda As Integer
        Dim con As New OleDbConnection

        Try


            con.ConnectionString = "provider=msdaora; data source=xe; user id=*; password=*;"
            con.Open()

            'Dim cmd As OleDbCommand = New OleDbCommand("<package name>.hitung_denda", con)

            Dim cmd As OleDbCommand = New OleDbCommand("hitung_denda", con)
            cmd.CommandType = CommandType.StoredProcedure

            'Dim returnval As New OleDbParameter("retval", OleDbType.Decimal, 100, ParameterDirection.ReturnValue, True, 0, 0, "denda", DataRowVersion.Current, "")

            Dim returnval As New OleDbParameter()
            returnval.ParameterName = "returnval"
            returnval.OleDbType = OleDbType.Decimal
            returnval.Direction = ParameterDirection.ReturnValue

            cmd.Parameters.Add(returnval)

            cmd.Parameters.Add("idPinjam", OleDbType.Decimal, 5).Value = idPinjam
            cmd.Parameters.Add("tgl", OleDbType.VarChar, 40).Value = tgl

            'execute cmd
            'returns number of rows affected
            cmd.ExecuteNonQuery()

            'returns the first column in the first row
            'of the result set
            'cmd.ExecuteScalar()


            'denda = cmd.Parameters("returnval").Value
            denda = returnval.Value

            Label8.Text = CStr(denda)


        Catch ex As OleDb.OleDbException
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
        Finally
            'close connection 
            If con.State = ConnectionState.Open Then
                con.Close()
            End If

            'dispose connection
            con.Dispose()
        End Try

        Return denda

    End Function

Resources:
Note: Some of the code is adapted from C#.

Click Here

Click Here

Click Here

Click Here

Parameterized Queries (Oracle, SQLServer, OleDb)

cgeier 187 Junior Poster

First of all, I've found the following related to the provider "MSDAORA" (Microsoft OLE DB Provider for Oracle):

Microsoft OLE DB Provider for Oracle

"...This feature will be removed in a future version of Windows. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Instead, use Oracle’s OLE DB provider..."

Also, you create a parameter "returnvalue" but never "add" it to "cmd": cmd.Parameters.Add(returnval). Additionally, you don't have any code that would execute the command.

cgeier 187 Junior Poster

checked (C# Reference)

"...By default, an expression that contains only constant values causes a compiler error if the expression produces a value that is outside the range of the destination type. If the expression contains one or more non-constant values, the compiler does not detect the overflow..."

"...By default, these non-constant expressions are not checked for overflow at run time..."

...Overflow checking can be enabled by compiler options, environment configuration, or use of the checked keyword..."

public static long Factor(int number)
{
    long result = 1;

    try
    {
        //enables overflow checking
        checked
        {
            for (int x = 1; x <= number; x++)
            {

                result *= x;

            }//for
        }//checked

    }//try
    catch (OverflowException ex)
    {
        //Console.WriteLine("Error: " + ex.Message);
        throw new OverflowException();
    }//catch

    return result;
}//Factor

20! = 2,432,902,008,176,640,000
21! = 51,090,942,171,709,440,000

Max long: 9,223,372,036,854,775,807

Or in scientific (exponential) notation:

20! = 2.432902008176640E+18
21! = 51.090942171709440E+18

Max long: 9.223372036854775807E+18

*Note: I put all numbers above in E+18 for easier comparision.

Using 'long' data type:
21! will throw an OverflowException
providing that you have enabled overflow checking.

Other resources:
Arithmetic Overflow Checking using checked/unchecked

cgeier 187 Junior Poster

This can happen with improper usage of backgroundworker. You can use properties and/or constructors to pass data to your class.

I'm confused. Can you post your code. Or portions of your code that include the relavent information.

cgeier 187 Junior Poster

Try adding "N" in front of the unicode data:

TRUNCATE TABLE [dbo].[Language]
SET NOCOUNT ON
INSERT INTO [Language] VALUES ('English',N'English') -- 1
INSERT INTO [Language] VALUES ('French',N'Français') -- 2
INSERT INTO [Language] VALUES ('Spanish',N'Español') -- 3
Insert Into [Language] Values ('Russian', N'русский')
SET NOCOUNT OFF
GO

SQL Server multi language data support

"...When dealing with Unicode string constants in SQL Server you must precede all Unicode strings with a capital letter N, as documented in the SQL Server Books Online topic "Using Unicode Data". The "N" prefix stands for National Language in the SQL-92 standard, and must be uppercase. If you do not prefix a Unicode string constant with N, SQL Server will convert it to the non-Unicode code page of the current database before it uses the string..."

nchar and nvarchar (Transact-SQL)

Using Unicode Data
Unicode constants are specified with a leading N: N'A Unicode string'.

The following is listed for older versions of SQL Server:

You must precede all Unicode strings with a prefix N ...

"...Any time you pass Unicode data to SQL Server you must prefix the Unicode string with N..."

cgeier 187 Junior Poster
cgeier 187 Junior Poster

Sorry, I'm not going to debug your whole program for you. Place "MessageBox.Show()" and/or "Console.WriteLine()" statements throughout your code to help you find out what is executing and what is not.

ex:

MessageBox.Show("Before if 1")
Console.WriteLine("Before if 1")
    ...
MessageBox.Show("Inside if 1")
Console.WriteLine("Inside if 1")
    ...

MessageBox.Show("After if 1")
Console.WriteLine("After if 1")

    ...
cgeier 187 Junior Poster

Try changing:

Private allInventory As New Inventory

To:

 Private allInventory As New List(Of Inventory)

Add allInventory.Add(objInventory) here:

           ...

'Display data in text boxes.
DisplayInput(objInventory)

'--------------------------
' Add objInventory to list
'--------------------------
allInventory.Add(objInventory)

'Display inventory number in list box.
lstInventory.Items.Add(objInventory.InventoryNumber)

           ...

Change:

For Each InventoryNumber In allInventory
    lstInventory.Items.Add(InventoryNumber)
Next

To:

For Each item As Inventory In allInventory
    lstInventory.Items.Add(item.InventoryNumber)
Next

Change:

objInventory = CType(allInventory.Item(InventoryNumber), Inventory)

To:

 objInventory = allInventory(lstInventory.SelectedIndex)

There is an error in your constructor in "Inventory.vb".

decCost = String.Empty

"decCost" is declared as the following:

Private decCost As Decimal

decCost should be a Decimal value.

The same problem exists with "decretailPrice". Additionally, "IntqtyOnHand" is an Integer, not a String.

cgeier 187 Junior Poster

You haven't fixed your original problem. In your first post you do the following (line 34):

Dim stringrecord As String

The next time you reference "stringrecord" is in line 60:

stringfield =stringrecord .Split(",")

"stringrecord" is null because it hasn't been set to any value.

It should be:

stringfield =strline.Split(",")

Additionally, in lines 63-65, numrecord should be countnum

'now i will store into listproduct
listproduct(countnum).nameproduct = stringfield(0)
listproduct(countnum).catalogcode = stringfield(1)
listproduct(countnum).wholesade = stringfield(2)
listproduct(countnum).saleprice = stringfield(3)

Comment out your "Try-Catch" statements and you will be able to see where your code is throwing errors (in the debugger).

cgeier 187 Junior Poster

Is your Win 8.1 32-bit or 64-bit? What version of Outlook (year and 32-bit or 64-bit)?

Developing Outlook 2010 Solutions for 32-Bit and 64-Bit Systems

cgeier 187 Junior Poster

I think that you left out some "details".

In menu:

  • Click "File"
  • Select "Add"

OR

In solution explorer:

  • Right-click "Solution"

The remaining steps are the same for either:

  • Select "Add"
  • Select "New Project"
  • Double-click "Other Project Types" (to expand it)
  • Double-click "Setup and Deployment" (to expand it)
  • Click "Visual Studio Installer" (to select it)
  • Click "Setup Wizard" (to select it)
  • Click "Next"
  • Click "Next"
  • Check "Primary output from <project name>" checkbox
  • Click "Next"
  • Click "Next"
  • Click "Finish"

After opening the project, try the following:

Open Solution Explorer:
* Click "View" in the menu bar
* Select "Solution Explorer"

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

The following will show how to hide/show a menu based on user rights/permissions using a database that uses the structure in my post(s) above. There are most likely other ways of doing this, but the way I decided to do it was by making use of recursion. I use Dictionary and List in the process.

Ensure that you have SQLExpress or mySQL installed.

In this example, I use a database named "UserApp". So, create a new database named "UserApp". And create the file structure as previously described. Do not enter the sample data yet as I have made some slight modifications that will eliminate the need for some of the data. I require that only the youngest ToolStripMenuItem be entered in the database. It will be assumed that a user will also need access to all of the menus ancestors (parents).

Create a form named "Form1.vb" and add the following to it:

  • Add a ComboBox named "ComboBox1" to the form.
  • Add a Button named "Button1" to the form.
  • Add a StatusStrip named "StatusStrip1" to the form. Then add a StatusLabel named ToolStripStatusLabel1" to "StatusStrip1".
  • Add a MenuStrip named "MenuStrip1" to the form. Then create the following structure in MenuStrip1:

File menu:

  • File => Backup
  • File => Exit

Tools menu:

  • Tools => Accounting
  • Tools => Employee => EmployeeSubMenu1
  • Tools => Employee => EmployeeSubMenu2
  • Tools => Order Entry
  • Tools => Refresh

Create a module named "AppPermissionsModule.vb".

For SQLExpress, add the following Imports statement: Imports System.Data.SqlClient

For mySQL, ensure …

cgeier 187 Junior Poster

No one has any idea what you are talking about when you say "Everything points to c:\Program Files(x86)\Default Company Name". Provide some code.

cgeier 187 Junior Poster

My previous post was incorrect. Don't add Namespace My to "resultex". Change line #23 in "MyApplication" to:

Me.MainForm = My.Forms.resultex

The format is: Me.MainForm = My.Forms.<your form name to start>

cgeier 187 Junior Poster

You might try moving value.Dispose(); inside the closing bracket of the using statement:

using (Graphics graphicsHandle = Graphics.FromImage(TempImage))
{
                          ...

    if (value != null)
    {
        value.Dispose();
    }//if
}//end using
cgeier 187 Junior Poster

...it could be related to using a "using" statement.

using Statement (C# Reference)

File and Font are examples of managed types that access unmanaged resources (in this case file handles and device contexts). There are many other kinds of unmanaged resources and class library types that encapsulate them. All such types must implement the IDisposable interface.

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.

Image.Dispose
Calling the Dispose method allows the resources used by this Image to be reallocated for other purposes.

Call Dispose when you are finished using the Image. The Dispose method leaves the Image in an unusable state. After calling Dispose, you must release all references to the Image so the garbage collector can reclaim the memory that the Image was occupying. For more information, see Cleaning Up Unmanaged Resources and Implementing a Dispose Method.

Always call Dispose before you release your last reference to the Image. Otherwise, the resources …

cgeier 187 Junior Poster

It may be related to how garbage collection is occuring.

See the following post:

Does garbage collection run during debug

The following post may also be of use:
How to debug .net Garbage Collection
It contains some additional links.

Garbage Collection

cgeier 187 Junior Poster

I believe that your overall memory issues are probably due to the manner in which you use locking. The rest of your code would need to be examined. Unfortunately, I'm not familiar with locking in C#.

cgeier 187 Junior Poster
cgeier 187 Junior Poster

Using methods in System.IO.
Add using System.IO;

System.IO Namespace

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

I would say because class "resultex" is missing Namespace My which happens to be referenced in line #23 in "MyApplication" (Me.MainForm = My.Forms.MainForm). See line #11 & #27 in "MyApplication" for the placement (the position it should be in within "resultex").

cgeier 187 Junior Poster

You may consider storing the MenuStrip (ToolStripMenuItem) variable names in the database.

ex:

  • FileToolStripMenuItem
  • BackupToolStripMenuItem
  • ExitToolStripMenuItem
  • ToolsToolStripMenuItem
  • AccountingToolStripMenuItem
  • EmployeeToolStripMenuItem

The database structure will stay the same. The sample data in two of the tables will change as follows:

AppPermission:
b075cfdfecee5186895c9eb94dad07e6

AppGroupPermission:

f19d4eb425ff047e3501a85993319c8e

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

The following will replace "<address>" with the text contained in RichTextBox1 and save the document as a .pdf file. The original file will be unmodified:

        'use early binding
        Dim objWordApp As Word.Application = Nothing

        Try

            objWordApp = New Word.Application

            'Open an existing document.
            objWordApp.Documents.Open("C:\Temp\Sample.docx")


            'copy data to clipboard
            RichTextBox1.SelectAll()
            RichTextBox1.Copy()

            'find <address>
            objWordApp.Selection.Find.Execute("<address>")

            'copy richtext from clipboard
            objWordApp.Selection.PasteSpecial(DataType:=Word.WdPasteDataType.wdPasteRTF)

            'clear the clipboard
            Clipboard.Clear()

            'save as PDF
            objWordApp.ActiveDocument.SaveAs2("C:\Temp\Sample.pdf", Word.WdSaveFormat.wdFormatPDF)

            'Close the document.
            objWordApp.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges)

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally

            'quit Word
            If Not IsNothing(objWordApp) Then
                objWordApp.Quit()
                objWordApp = Nothing
            End If

        End Try

Note: You will need to be using a version of Word that allows a file to be save as ".pdf".

Resources:
How do I convert Word files to PDF programmatically

2007 Microsoft Office System Update: Redistributable Primary Interop Assemblies

Microsoft Office 2010: Primary Interop Assemblies Redistributable

How to open new file formats in earlier versions of Microsoft Office

Microsoft Office Compatibility Pack for Word, Excel, and PowerPoint File Formats

"...By installing the Compatibility Pack in addition to Microsoft Office 2000, Office XP, or Office 2003, you will be able to open, edit, and save files using the file formats in newer versions of Word, Excel, and PowerPoint . The Compatibility Pack can also be used in conjunction with the Microsoft Office Word Viewer 2003, Excel Viewer 2003, and PowerPoint Viewer 2003 to view files saved in these new formats..."

Microsoft Office Compatibility Pack Service …

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: