cgeier 187 Junior Poster

Try this:

Public Function filterDataSet(ByVal ds As DataSet) As DataView

    Dim dv As DataView = New DataView()

    dv = ds.Tables(0).DefaultView
    dv.RowFilter = "startDate > #1/30/2008# and endDate < #1/30/2010#"

    Return dv
End Function

Usage:

dgTranslog.DataSource  = Nothing
dgTranslog.DataSource = filterDataSet(dsGet)

Could replace:

dv = ds.Tables(0).DefaultView

With:

dv = ds.Tables(tblTranslog).DefaultView

The following may need to be changed:

"startDate > #1/30/2008# and endDate < #1/30/2010#"

and the format of the date may depend on your computer locale settings.

The above is untested.

Code adapted from:

DataView RowFilter with multiple conditions

DataView RowFilter Syntax

cgeier 187 Junior Poster

Search for DataView and DataView.RowFilter

cgeier 187 Junior Poster

Above, in "updateFilterDict", change from:

whereClause = "WHERE " + kvp.Value;

To:

whereClause = kvp.Value;
cgeier 187 Junior Poster

The following is an easy way to accomplish it.

Add the following:

Dictionary<string, string> filterDict = new Dictionary<string, string>();

private string whereClause = string.Empty;

Then call the following everytime "TextChanged" (for any TextBox) occurs:

Version 1:

This version assumes that all of the column data types are string data types (such as varchar, nvarchar, etc..)

private void updateFilterDict(string keyName, string value)
{
    string newDictValue = string.Empty;

    //value to store in dictionary
    newDictValue = keyName + " LIKE " + "'%" + value + "%'";

    //check if dictionary already 
    //contains the key
    if (filterDict.ContainsKey(keyName))
    {
        //if value is null or empty
        //remove key. Otherwise, update
        //key.
        if (String.IsNullOrEmpty(value))
        {
            filterDict.Remove(keyName);
        }//if
        else
        {
            filterDict[keyName] = newDictValue; 
        }//else
    }//if
    else
    {
        //add key to dictionary
        filterDict.Add(keyName, newDictValue);
    }//else

    int filterCount = 0;
    foreach (KeyValuePair<string,string> kvp in filterDict)
    {
        if (filterCount > 0)
        {
            whereClause += " AND " + kvp.Value;
        }//if
        else
        {
            whereClause = "WHERE " + kvp.Value;
        }//else

        filterCount += 1;
    }//foreach

    //ToDo: Update DataGridView results here
    Console.WriteLine("whereClause: " + whereClause);

}//updateFilterDict

Version 2:

This version allows one to specify different search behavior for different filters / data types. It is for demonstration purposes. It is a good idea to maintain consistency for a data type. If when a user enters a string value (ex: "12") and the results returned "contains" the value (ex:"12") in one filter, it is a good idea to do similarly in the other filters (when possible).

private void updateFilterDict(string keyName, …
cgeier 187 Junior Poster

Change the name using the properties for the control. Right-click the control, and select "Properties". Look for "(Name)". Change the name there.

cgeier 187 Junior Poster

Use the code from your other post that uses the DataTable. Set the DataTable as the datasource for the DataGridView. A DataSet can hold multiple data tables.

cgeier 187 Junior Poster

If you aren't updating any data, you can use "ExecuteScalar" or "ExecuteReader".

ExecuteScalar returns a single value. It can be used when you only need to get a single column from a single row.

ExecuteReader returns rows in a DataReader. It can be used to retrieve data from multiple columns and multiple rows.

You don't need to retrieve the password from the database, but rather send the password that the user submitted and see if it matches the one in the database. You really shouldn't store clear text passwords though. You should encrypt it before storing it in the database. Then encrypt the password that the user submitted, and see if it matches the encrypted password in the database.

checkPassword:

Public Function checkPassword(ByVal username As String, ByVal password As String) As Boolean

    Dim totalRows As Integer = 0
    Dim passwordVerified As Boolean = False

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

            sqlText = "SELECT COUNT(*) FROM " + usersTbl + " "
            sqlText += "WHERE username = @username and password = @password"

            'open connection
            cn.Open()

            Using cmd As New iDB2Command(sqlText, cn)

                'add username parameter
                cmd.Parameters.AddWithValue("@username", username)

                'add password parameter
                cmd.Parameters.AddWithValue("@password", password)

                'execute the command
                'ExecuteScalar returns a single value / single column
                totalRows = Convert.ToInt32(cmd.ExecuteScalar())

                If totalRows >= 1 Then
                    passwordVerified = True
                End If

            End Using
        End Using

    Catch ex As iDB2Exception
        Throw New Exception("Error (checkPassword): " + ex.Message)

    Catch ex As Exception
        Throw New Exception("Error (checkPassword): " + ex.Message)

    End Try

    Return …
cgeier 187 Junior Poster

How many lines of code? Did you overstate your abilities during your interview? You may find it beneficial to shadow one (or more) of the users of the product--to get the end user experience. Aside from that, if you want to prove yourself, you will likely need to spend time at work as well as personal time to figure it all out.

cgeier 187 Junior Poster

Create, Execute and delete Macro in excel using C#

There is also a VB .NET version in the post.

To add Microsoft.Vbe.Interop reference:

  • Project
  • Add Reference
  • .NET
  • Microsoft.Vbe.Interop

To add Microsoft.Office.Interop.Excel reference:
* Project
* Add Reference
* .NET
* Microsoft.Office.Interop.Excel

You must explicitly enable access to the Microsoft Office Visual Basic for Applications project system before you can create or open a Visual Studio Tools for the Microsoft Office System project

cgeier 187 Junior Poster

In the second example it will skip the rest of the else if statements when it has found a satisfying condition. In your first example every if statement will be evaluated. In your short example it doesn't make much difference. The difference is noticed in a loop with many iterations or if you have many if statements or if your if statements must perform more complex (time consuming) evaluations. Of course this all depends on the frequency of a satisfying condition being found. The greatest benefit will result in the second example if you order the statements from most likely to occur to least likely to occur.

ddanbe commented: Great answer! +15
cgeier 187 Junior Poster

First of all, your code doesn't compile. You're missing the following:

Dim clients As New Hashtable

In Server, try the following:

Sub Recieved(ByVal Message As String, ByVal Client As ConnectedClient)
    Dim msg() As String = Message.Split(split)
    Select Case msg(0)
        ' switch case on server return
        Case "Login"
            clients.Add(Client, Client.Name)
            ListBox1.Items.Add("Connected - " & Client.Name & vbNewLine)
            '' //// Trying to update here //// ''
            '' //// ''
            '' //// ''
            '' //// ''
    End Select
End Sub

Note: "received" is spelled this way, not "recieved".

Also, in Server you have:

Dim Port As Integer = 5440

And in Client, you have:

Dim IP As String = "localhost", Port As Integer = 5504

The server is listening on a different port than the client is using.

In client, add code to exit if the client can't connect. Otherwise, the client will keep trying to connect and error messages will keep popping up.

Add the following (to Client):

Dim attemptCount As Integer = 0
Dim maxConnectAttempts As Integer = 4

Then, in Client, add the following code:

attemptCount += 1

If attemptCount < maxConnectAttempts Then
    Connect()
Else
    'close form
    Me.Dispose()
End If

Connect will look like the following:

Sub Connect()
    Try
        t.Connect(IP, Port)
        If t.Connected Then
            t.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Read, Nothing)
            SendData("Login" & split)
        End If
    Catch ex As Exception
        attemptCount += 1

        MsgBox(ex.Message & " (" & attemptCount & ")")

        If attemptCount < maxConnectAttempts Then …
cgeier 187 Junior Poster

The following has been tested in Excel 2010:

Add a reference to Microsoft Excel xx.x Object Library

  • Project
  • Add Reference
  • COM
  • Microsoft Excel 14.0 Object Library

Create a new module named "Module1.vb".

Module1.vb:

Imports Excel = Microsoft.Office.Interop.Excel

Module Module1

    Public Enum ColumnVisibility
        Hide
        Show
    End Enum


    Public Sub setColumnVisibility(ByVal filename As String, ByVal visibility As ColumnVisibility)

        Dim xlApp As Excel.Application = New Excel.Application
        Dim xlWb As Excel.Workbook
        Dim xlPreviousActiveSheet As Excel.Worksheet
        Dim xlSheet As Excel.Worksheet
        Dim xlRng As Excel.Range

        'start Excel and get Application object
        xlApp = CreateObject("Excel.Application")

        'change to False if you don't
        'want Excel to be visible
        xlApp.Visible = True

        'open workbook
        xlWb = xlApp.Workbooks.Open(filename)

        'get previously active sheet
        'so we can make it the active sheet
        'again before we close the file
        xlPreviousActiveSheet = xlWb.ActiveSheet

        For i As Integer = 1 To xlWb.Sheets.Count

            xlSheet = xlApp.Sheets(i)

            'activate current sheet
            'needed for "Select"
            xlSheet.Activate()

            'get range of sheet
            xlRng = xlSheet.Cells()

            'Console.WriteLine("Total Rows: " & xlRng.Rows.Count)
            'Console.WriteLine("Total Columns: " & xlRng.Columns.Count)

            'select range
            xlSheet.Range(xlSheet.Cells(1, 10), xlSheet.Cells(xlRng.Rows.Count, xlRng.Columns.Count)).Select()

            If visibility = ColumnVisibility.Show Then
                'show columns in range
                xlApp.Selection.EntireColumn.Hidden = False
            Else
                'hide columns in range
                xlApp.Selection.EntireColumn.Hidden = True
            End If

            'undo selection
            xlApp.CutCopyMode = Excel.XlCutCopyMode.xlCopy
            xlSheet.Range("A1").Select()
        Next

        'make previous active sheet
        'the active sheet again
        'before we close the file
        xlPreviousActiveSheet.Activate()

        'close and save changes
        xlWb.Close(SaveChanges:=True)

        'quit Excel
        xlApp.Quit()

    End Sub

End Module  

Usage:

setColumnVisibility("C:\Temp\Book1.xlsx", ColumnVisibility.Hide)

Or

setColumnVisibility("C:\Temp\Book1.xlsx", ColumnVisibility.Show)

Resources:

VB.NET Excel

How to select cells/ranges by using …

cgeier 187 Junior Poster

I made a couple of changes to "ClsDB2", so I'm re-attaching it. Also attached below is the verion in VB .NET. Both are untested.

VB .NET version: ModuleDB2.zip

C# version: ClsDB2.zip

cgeier 187 Junior Poster

Below I've attached a C# version of the code so you can see how to do it in C#. The code is untested though, because I don't have a database to test it on.

I made the class static, so to use it, use <class name>.<method name>

ex: ClsDB2.doTasks()

Note: Change the namespace name to the name of the namespace for your project.

cgeier 187 Junior Poster

Also, when you are searching for information, do a general search rather than searching for info on DB2. You will get more results.

Example:

DB2: iDB2DataAdapter

Try searching for:

  • OleDbDataAdapter
  • SqlDataAdapter

DB2: iDB2Command

Try searching for:
SqlCommand
OleDbCommand

Basically, replace "iDB2" with "OleDb" or "Sql".

Here is some code I've adapted from this post.

doTasks:

Private Sub doTasks()
    Try
        Dim err As Exception = Nothing
        Dim dt As DataTable = Nothing

        'get data and put into a DataTable
        'if an exception occurs, it is 
        'returned in "err"
        dt = getData(err)

        If err IsNot Nothing Then
            MessageBox.Show("Error: " & err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            If dt IsNot Nothing Then
                showData(dt)
            Else
                MessageBox.Show("DataTable is Nothing.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        End If
    Catch ex As Exception
        MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub

getData:

Private Function getData(ByRef err As Exception) As DataTable

    Dim retDataTable As New DataTable

    Try

        Using cn As New iDB2Connection(str)


            Dim sqlText As String = String.Empty
            sqlText = "SELECT username, fullname "
            sqlText += "FROM expusers"

            Try
                ' Open Connection
                cn.Open()
                Using cmd As New iDB2Command(sqlText, cn)
                    Dim dA As New iDB2DataAdapter(sqlText, cn)
                    Try
                        dA.Fill(retDataTable)
                    Catch ex1 As iDB2Exception
                        Throw New Exception("Error in dataAdapter. " + ex1.Message)
                    Catch ex1 As Exception
                        Throw New Exception("Error in dataAdapter. " + ex1.Message)
                    End Try
                End Using
            Catch ex2 As iDB2Exception
                Throw New Exception("Error in connection. " + ex2.Message)
            Catch ex2 As Exception
                Throw New Exception("Error in connection. " + ex2.Message) …
cgeier 187 Junior Poster

You may find more help if you switch to C#. C# seems to be more popular and more examples seem to be available. See my post here on how to use a dataset and tableadapter. It is for C#, but the steps are similar.

cgeier 187 Junior Poster

See the following post:

TableAdapter and Unicode?

cgeier 187 Junior Poster

First of all, you want to make sure that the DocumentCompleted event is only firing once.

Determine a web page is done loading in WebBrowser (CSWebBrowserLoadComplete)

"...In the case of a page with no frames, the DocumentComplete event is fired once after
everything is done. In case of multiple frames, the DocumentComplete event gets fired
multiple times..."

cgeier 187 Junior Poster

Yes. You need to have an "electronic" version of a dictionary that contains valid words. This electronic version can be a text file. Additionally, new words are added to dictionaries from time to time, so you may need to update your file from time to time.

cgeier 187 Junior Poster

See the other post on how to use parameters. I am not able to test it on DB2, but I believe that the driver follows the same syntax rules as other database drivers.

cgeier 187 Junior Poster

Try the following:

Dim param1 As New iDB2Parameter
param1.ParameterName = "@username"
param1.iDB2DbType = iDB2DbType.iDB2VarChar
param1.Value = txtUsername.Text

cmdUpdate.Parameters.Add(param1)

Dim param2 As New iDB2Parameter
param2.ParameterName = "@loginDate"
param2.iDB2DbType = iDB2DbType.iDB2Date
param2.Value = DateTime.Now.ToString("d")

cmdUpdate.Parameters.Add(param2)

Dim param3 As New iDB2Parameter
param3.ParameterName = "@loginTime"
param3.iDB2DbType = iDB2DbType.iDB2Time
param3.Value = DateTime.Now.ToString("T")

cmdUpdate.Parameters.Add(param3)

Or in lines 15-17 you could try the following:

cmdUpdate.Parameters.Add("@username", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters.Add("@loginDate", iDB2DbType.iDB2Date)
cmdUpdate.Parameters.Add("@loginTime", iDB2DbType.iDB2Time)

add the "@" sign.

Also in lines 19-21:

cmdUpdate.Parameters("@username").Value = txtUsername.Text
cmdUpdate.Parameters("@loginDate").Value = Now.ToString("d")
cmdUpdate.Parameters("@loginTime").Value = Now.ToString("T")

The above code is untested.

cgeier 187 Junior Poster

How did you create the columns? In VS or using code?

cgeier 187 Junior Poster

What is the data type of the column?

cgeier 187 Junior Poster

Question 1: How do you know "dog" is a word?

Question 2: If you didn't know if "dog" was a word or not, how would you find out?

cgeier 187 Junior Poster

Use a variable to sum the totals as you add them to listview2. Then after the for loop add a series of '-' (dashes) in each column of a new row. Then add one more row with the total of the totals. I'll leave the implementation to you.

cgeier 187 Junior Poster

For duration, you see the following:

<meta itemprop="duration" content="PT2M13S">

It appears that “PT” marks the start of the time part of the value. "M" is for minute(s). "S" is for seconds.

So in the above: 2 minutes and 13 seconds

AnooooPower commented: ty! +1
cgeier 187 Junior Poster

You could use WebClient or HttpWebRequest to get the URL source. Then look for the desired info.

Add the following Imports statements:

  • Imports System.IO
  • Imports System.Net

Version 1 (using WebClient):
getUrlSource:

Public Function getUrlSource() As String
    Dim urlSource As String = String.Empty
    Dim client As New System.Net.WebClient

    Try
        'create request to web server (url)
        urlSource = client.DownloadString(_url)
    Finally
        If Not client Is Nothing Then
            client.Dispose()
        End If
    End Try

    Return urlSource
End Function

Version 2 (using HttpWebRequest):
getUrlSource:

Public Function getUrlSource() As String
    Dim errMsg As String = String.Empty
    Dim urlSource As String = String.Empty
    Dim request As System.Net.HttpWebRequest = Nothing
    Dim response As System.Net.HttpWebResponse = Nothing
    Dim sr As System.IO.StreamReader = Nothing

    Try
        'create request to web server (url)
        request = HttpWebRequest.Create(_url)

        'set value for AutoRedirect
        request.AllowAutoRedirect = True

        'receives response from request sent to 
        'web server
        response = request.GetResponse()

        If Not response.StatusCode = HttpStatusCode.OK Then
            errMsg = "Response status code: " & response.StatusCode
            MessageBox.Show(errMsg, "Error - Response", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return errMsg
        End If

        'get encoding
        Dim encoding = System.Text.Encoding.GetEncoding(response.CharacterSet)

        'use StreamReader to read urlSource
        sr = New StreamReader(response.GetResponseStream(), encoding)
        urlSource = sr.ReadToEnd()

    Finally
        'close StreamReader
        If Not sr Is Nothing Then
            sr.Close()
        End If
    End Try

    Return urlSource
End Function

Then get the information from the html source code:

First I create a class to hold the desired data. I will call it "YTInfo.vb"

YTInfo.vb

Public Class YTnfo
    Public Property Author As String
    Public Property ChannelId As String
    Public Property Description As …
AnooooPower commented: thank you very much for this, well detailed! +0
cgeier 187 Junior Poster

Here is another version that uses List--just to show another way to do it.

Version 4 (using List):

We will use our custom class "CarInfo".

CarInfo.vb

Public Class CarInfo
    Public Property name As String
    Public Property total As Integer
End Class

readData:

Private Sub readData()

    Dim cars As New List(Of CarInfo)

    'total # of columns
    Dim totalColumns As Integer = 5

    Dim fileDataArr() As String = File.ReadAllLines(_filename)

    ListView1.Items.Clear()

    For Each line As String In fileDataArr

        'skip any blank lines
        If Not String.IsNullOrEmpty(line) Then
            Dim flds() As String = line.Split(vbTab)

            If flds.Count = totalColumns Then
                Dim entryDate As String = flds(0)
                Dim placano As String = flds(1)
                Dim car As String = flds(2)
                Dim workDone As Integer = flds(3)
                Dim status As String = flds(4)

                ListView1.Items.Add(New ListViewItem({entryDate, placano, car, workDone, status}))

                Dim carExists As Boolean = False
                Dim carIndex As Integer = 0

                'check if car exists in cars array
                If (cars.Count > 0) Then
                    For i As Integer = 0 To cars.Count - 1
                        If cars(i).name = car Then
                            carExists = True
                            carIndex = i
                        End If
                        Next
                End If


                'if car exists in List
                'add value to existing value.
                'Otherwise, add car
                If carExists = True Then
                    cars(carIndex).total += workDone
                Else

                    Dim myCarInfo As New CarInfo
                    myCarInfo.name = car
                    myCarInfo.total = workDone

                    cars.Add(myCarInfo)
                End If
            Else
                MessageBox.Show("Invalid data found in file. Found " & flds.Count & " columns. Expecting " & totalColumns & ". Skipping.", "Invalid Data Found", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            End If
        End If
    Next

    'clear …
cgeier 187 Junior Poster

If your teacher asked you to use an array, it is probably better to not use a Dictionary.

Dictionary<TKey, TValue> Class

Represents a collection of keys and values.

It exists in the System.Collections.Generic namespace.

cgeier 187 Junior Poster

Here are 3 different versions.

  • Version 1 uses the dictionary above, mentioned by Reverend Jim.
  • Version 2 uses two arrays.
  • Version 3 uses an array of a class.

Note: Uses a ListView as mentioned by tinsaafl

Controls on form:

  • Button named writeBtn
  • Button named readBtn
  • CheckBox named CheckBox1
  • DateTimePicker named DateTimePicker1
  • NumericUpDown named NumericUpDown1
  • Panel named Panel1
  • RadioButton named RadioButton1
  • RadioButton named RadioButton2
  • RadioButton named RadioButton3
  • ListBox named ListBox1
  • ListView named ListView1
  • ListView named ListView2

Note: Place RadioButtion1, RadioButton2, and RadioButton3 on Panel1.

I have declared the filename a private variable so that it is not hard coded multiple times throughout the program.

Private _filename As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\data.txt"

Form1_Load:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    ListBox1.Items.Add("Mercedes")
    ListBox1.Items.Add("Citroen")
    ListBox1.Items.Add("BMW")
    ListBox1.Items.Add("Opel")
    ListBox1.Items.Add("Renault")


    'set View to Details
    ListView1.View = View.Details
    ListView1.Columns.Add("Date", 80, HorizontalAlignment.Left)
    ListView1.Columns.Add("Placano", 60, HorizontalAlignment.Left)
    ListView1.Columns.Add("Car", 60, HorizontalAlignment.Left)
    ListView1.Columns.Add("Work Done", 80, HorizontalAlignment.Left)
    ListView1.Columns.Add("Status", 60, HorizontalAlignment.Left)

    'set View to Details
    ListView2.View = View.Details
    ListView2.Columns.Add("Car", 60, HorizontalAlignment.Left)
    ListView2.Columns.Add("Total", 60, HorizontalAlignment.Left)
End Sub

writeBtn_Click:

Private Sub writeBtn_Click(sender As Object, e As EventArgs) Handles writeBtn.Click
    writeData()
End Sub

readBtn_Click:

Private Sub readBtn_Click(sender As Object, e As EventArgs) Handles readBtn.Click
    readData()
End Sub

writeData:

Private Sub writeData

        Dim tableArr()

        Dim tableArrfull As Boolean

        If Not tableArrfull Then
            ReDim tableArr(0)
            tableArrfull = True
        Else

            ReDim Preserve tableArr(UBound(tableArr) + 1)

        End If

        Dim date_short As String
        date_short = Format(DateTimePicker1.Value, "dd/MM/yyyy")

        Dim placano As String

        If CheckBox1.Checked = True Then …
cgeier 187 Junior Poster

I haven't tested this, but it looks like it might be what you are trying to do:

Programmatically forwarding email message with inline images

cgeier 187 Junior Poster

In my previous post, in the connection string, "Port" should only be in there once.

cgeier 187 Junior Poster

See the post from deceptikon for:

System.Environment.SpecialFolder Enumeration

UserProfile:

"...The user's profile folder. Applications should not create files or folders at this level; they should put their data under the locations referred to by ApplicationData. Added in the .NET Framework 4..."

Any of these should work:

'ApplicationData:
'The directory that serves as a common repository for 
'application-specific data for the current roaming user.
'A roaming user works on more than one computer on a network. 
'A roaming user's profile is kept on a server on the network 
'and is loaded onto a system when the user logs on.

Dim applicationData As String = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Dim appDataEnvVar As String = System.Environment.GetEnvironmentVariable("APPDATA")

'CommonApplicationData:
'The directory that serves as a common repository for 
'application-specific data that is used by all users.
Dim commonApplicationData As String = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
Dim allUsersProfileEnvVar As String = System.Environment.GetEnvironmentVariable("ALLUSERSPROFILE")

'LocalApplicationData:
'The directory that serves as a common repository for 
'application-specific data that is used by the current, 
'non-roaming user.
Dim localApplicationData As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)

'MyDocuments:
'The My Documents folder.
'This member is equivalent to Personal.
Dim myDocuments As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Dim personal As String = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal)


Console.WriteLine("ApplicationData: " & applicationData)
Console.WriteLine("appDataEnvVar: " & appDataEnvVar)

Console.WriteLine("CommonApplicationData: " & commonApplicationData)
Console.WriteLine("allUsersProfileEnvVar: " & allUsersProfileEnvVar)

Console.WriteLine("LocalApplicationData: " & localApplicationData)
Console.WriteLine("MyDocuments: " & myDocuments)
Console.WriteLine("Personal: " & personal)

Note: Choose the most appropriate one.

For Win 7 (if "C:" is your system drive):

  • ApplicationData should be: "C:\Users\<username>\AppData\Roaming"
  • CommonApplicationData should be "C:\ProgramData"
  • LocalApplicationData should be "C:\Users\<username>\AppData\Local
  • MyDocuments should …
cgeier 187 Junior Poster

Creating and Using a Database

"...The USE statement is special in another way, too: it must be given on a single line..."

Connection Strings
"...The port 3306 is the default MySql port..."

Try the following:

In "saveImage":

Change line #5 to:

string myConnectionString = "Server = " + server + "; Port = 3306; Database=" + dbName + "; Uid = " + user + "; Port = 3306; Pwd = " + password + ";";

Change line #10 to:

MySqlCommand myCommand = new MySqlCommand(updateTableCommand, myConnection);

Or you can use the following:

Ensure you have a reference to "MySql.Data":

  • Select "Project"
  • Select "Reference"
  • Click ".NET" tab
  • Select "MySql.Data"

Add using statement:

  • using MySql.Data.MySqlClient

Connection String:

private string connectStr = "Server = " + server + "; Port = 3306; Database=dbName; Uid = " + user + "; Port = 3306; Pwd = " + password + ";";

updateUserImage:

public static string updateUserImage(string currentUser, byte[] userImage, string tblName)
{    
    string status = string.Empty;
    string errMsg = string.Empty;

    try
    {
        using (MySqlConnection cn = new MySqlConnection(connectStr))
        {
            string sqlText = string.Empty;

            sqlText = "Update [" + tblName + "]";
            sqlText += "SET UserImage = @userImage ";
            sqlText += "where Username = @currentUser";

            //open connection to db
            cn.Open();

            using (MySqlCommand sqlCmd = new MySqlCommand(sqlText, cn))
            {

                sqlCmd.Parameters.AddWithValue("@currentUser", currentUser);
                sqlCmd.Parameters.AddWithValue("@userImage", userImage);

                //MySqlParameter paramName1 = new MySqlParameter();
                //paramName1.ParameterName = "@userImage";
                //paramName1.MySqlDbType = MySqlDbType.VarBinary;
                //paramName1.Value = userImage;
                //sqlCmd.Parameters.Add(paramName1);

                //execute
                sqlCmd.ExecuteNonQuery();
            }//using SqlCommand
        }//using …
cgeier 187 Junior Poster

Are you trying to send this to a form you created in VB .NET or to a window in another program?

Also, you can edit a post after you sign out and sign back in. However, there is a 30 min cutoff. After 30 mins you are no longer able to edit a post. If you don't press the refresh button on your browser after clicking "Save Changes", and edit the post again, the previous update is lost. Also, you need to refresh your browser to update the posting time.

cgeier 187 Junior Poster

SendKeys.Send Method

"Caution: If your application is intended for international use with a variety of keyboards, the use of Send could yield unpredictable results and should be avoided."

cgeier 187 Junior Poster

Use one of the following directories to store your data:

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

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

Dim appDataDir As String = Environment.GetEnvironmentVariable("APPDATA")

If you don't need to run your program on XP, you can use:

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

I've updated the code. See the notes inside the files (inside FtpDownload.zip) for more details.

Resources:

using ftp to download a file

FtpWebRequest Download File

Downloading Files Using FTPWebRequest

FtpWebRequest Class

System.Net.FtpWebRequest class behaves differently in .Net Framework 4 vs .Net Framework 3.5

Files attached below (in .zip file):

cgeier 187 Junior Poster

The following should work:

    Private _filenamePattern As String = ".*(?<filename>\d{4}-\d{2}-\d{2}-\d{4}.txt.tgz).*"

    Private _ftpRequest As FtpWebRequest = Nothing

    Private _downloadDirectory As String = String.Empty
    Private _ftpUrl As String = String.Empty
    Private _password As String = "user@name.com"
    Private _username As String = "anonymous"

        'Enum
    Private Enum FtpMethod
        ListFiles = 0
        Download = 1
    End Enum

        Private Function getNewestFilename(ByVal directoryData As String) As String

        Dim output As String = String.Empty
        Dim lastFilename As String = String.Empty
        Dim newestFilename As String = String.Empty

        'create new instance of RegEx
        Dim myRegex As New Regex(_filenamePattern)

        'create new instance of Match
        Dim myMatch As Match = myRegex.Match(directoryData)

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

            'get groups
            Dim myGroups As GroupCollection = myMatch.Groups

            'For Each groupName As String In myRegex.GetGroupNames
            'output += String.Format("Group: '{0}' Value: {1}", groupName, myGroups(groupName).Value)
            'output += System.Environment.NewLine
            'Next

            'Console.WriteLine(output)

            lastFilename = myGroups("filename").Value

            If Not String.IsNullOrEmpty(newestFilename) Then
                If lastFilename > newestFilename Then
                    newestFilename = lastFilename
                End If
            Else
                newestFilename = myGroups("filename").Value
            End If

            'Console.WriteLine("lastFilename: " + lastFilename + " newestFilename: " + newestFilename)


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

        If String.IsNullOrEmpty(newestFilename) Then
            newestFilename = "No matches found for specified pattern."
        End If

        Return newestFilename
    End Function

        Private Function CreateFtpWebRequest(ByVal ftpUrl As String, ByVal username As String, ByVal password As String, ByVal ftpMethod As FtpMethod, ByVal keepAlive As Boolean) As Stream

        'defined as Private
        '_ftpRequest = DirectCast(WebRequest.Create(New Uri(ftpUrl)), FtpWebRequest)
        _ftpRequest = WebRequest.Create(New Uri(ftpUrl))

        'either download the file or
        'list the files in the directory
        If ftpMethod = 0 Then …
cgeier 187 Junior Poster

I don't understand why you would have to "modify the regex everytime". From the data you provided, the last filename is the newest filename. So you just have to get the last filename. If the filenames could be listed in a different order then what you need to do is search through the list of files and determine which one is the newest.

The following code will find the newest filename given the filename format that you have provided:

    Public Function extractData(ByVal myData As String) As String

        Dim output As String = String.Empty
        Dim lastFilename As String = String.Empty
        Dim newestFilename As String = String.Empty

        'Dim pattern As String = "[-rwx]{10}\s+\d\s+\d\s+\d\s+\d+\s+(?<monthName>[A-Z][a-z]+)\s+(?<monthNumber>\d+)\s+(?<timeOfDay>\d{2}:\d{2})\s+(?<filenameDateYear>\d{4})-(?<filenameDateMonth>\d{2})-(?<filenameDateDay>\d{2})-(?<filenameTimePart>\d{4}).txt.tgz.*"
        'Dim pattern As String = "[-rwx]{10}\s+\d\s+\d\s+\d\s+\d+\s+(?<monthName>[A-Z][a-z]+)\s+(?<monthNumber>\d+)\s+(?<timeOfDay>\d{2}:\d{2})\s+(?<filename>\d{4}-\d{2}-\d{2}-\d{4}.txt.tgz).*"
        'Dim pattern As String = ".*(?<monthName>[A-Z][a-z]+)\s+(?<monthNumber>\d+)\s+(?<timeOfDay>\d{2}:\d{2})\s+(?<filename>\d{4}-\d{2}-\d{2}-\d{4}.txt.tgz).*"

        Dim pattern As String = ".*(?<filename>\d{4}-\d{2}-\d{2}-\d{4}.txt.tgz).*"

        'create new instance of RegEx
        Dim myRegex As New Regex(pattern)

        'create new instance of Match
        Dim myMatch As Match = myRegex.Match(myData)

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

            'get groups
            Dim myGroups As GroupCollection = myMatch.Groups

            'For Each groupName As String In myRegex.GetGroupNames
            'output += String.Format("Group: '{0}' Value: {1}", groupName, myGroups(groupName).Value)
            'output += System.Environment.NewLine
            'Next

            'Console.WriteLine(output)

            lastFilename = myGroups("filename").Value

            If Not String.IsNullOrEmpty(newestFilename) Then
                If lastFilename > newestFilename Then
                    newestFilename = lastFilename
                End If
            Else
                newestFilename = myGroups("filename").Value
            End If

            'Console.WriteLine("lastFilename: " + lastFilename + " newestFilename: " + newestFilename)


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

        Return newestFilename
    End Function

Usage:

Dim lastFilename as String = extractData(myData)

Example usage:

cgeier 187 Junior Poster

I have a post here that shows using ADODB. It is on page 1. See "Version 4 (using ADODB and OleDbDataAdapter)" It is for DB2 Express, but just change the connection string and it should work.

For additional connection strings see:
Connection Strings

cgeier 187 Junior Poster

Try one of the following:

Version 1:

Dim pattern As String = "[-rwx]{10}\s+\d\s+\d\s+\d\s+\d+\s+(?<monthName>[A-Z][a-z]+)\s+(?<monthNumber>\d+)\s+(?<timeOfDay>\d{2}:\d{2})\s+(?<filename>\d{4}-\d{2}-\d{2}-\d{4}.txt.tgz).*"

Version 2:

Dim pattern As String = "[-rwx]{10}\s+\d\s+\d\s+\d\s+\d+\s+(?<monthName>[A-Z][a-z]+)\s+(?<monthNumber>\d+)\s+(?<timeOfDay>\d{2}:\d{2})\s+(?<filenameDatePart>\d{4}-\d{2}-\d{2})-(?<filenameTimePart>\d{4}).txt.tgz.*"

Version 3:

Dim pattern As String = "[-rwx]{10}\s+\d\s+\d\s+\d\s+\d+\s+(?<monthName>[A-Z][a-z]+)\s+(?<monthNumber>\d+)\s+(?<timeOfDay>\d{2}:\d{2})\s+(?<filenameDateYear>\d{4})-(?<filenameDateMonth>\d{2})-(?<filenameDateDay>\d{2})-(?<filenameTimePart>\d{4}).txt.tgz.*"

Group names are "monthName", "monthNumber", "timeOfDay", etc...:

Console.WriteLine("monthName: '" + myMatch.Groups("monthName").Value + "'")

or

For Each g As Group In myGroups
    Console.WriteLine(g.Value)
Next
cgeier 187 Junior Poster

If you have foreign keys, the order in which you drop the tables is important. If you are re-creating the tables exactly the same, it isn't necessary to drop the tables, only to delete the data.

cgeier 187 Junior Poster

Please post the value of "result" after line #15 is executed.

cgeier 187 Junior Poster

Please show your table relationships.

cgeier 187 Junior Poster

There is some code in this post that uses regex. It demonstrates usage of regex in VB .NET.

cgeier 187 Junior Poster

What kind of database are you using?

cgeier 187 Junior Poster

The code above is not for Exchange.

These may be of use:

Programmatically Accessing Outlook Contacts Via Exchange Web Services

How do I access my Outlook contacts from my web application?

I don't have access to an Exchange server to test the code.

cgeier 187 Junior Poster

You will also need to change the protection level of "FirstName", "LastName", and "EmailAddress" (in person).

Otherwise the following line will throw a compiler error:

mailing.Bcc.Add(person.EmailAddress);

Accessibility Levels (C# Reference)

Members of: class

Default member accessibility: private

cgeier 187 Junior Poster

Personalize the message. In emailText replace the word "user" with each person's first name. Use String.Replace