Friday, April 27, 2012


 'Set Automatic Serail
            Dim dt As DataTable
            dt = DB.GetData("SELECT SUBSTR(orders.odr_code FROM 1 FOR 6) `date`,SUBSTR(orders.odr_code FROM 8 FOR 2) `serial` FROM orders ORDER BY SUBSTR(orders.odr_code FROM 1 FOR 6) desc,SUBSTR(orders.odr_code FROM 8 FOR 2) desc LIMIT 1")

            Dim serial As String

            If dt.Rows.Count > 0 Then
                If dt.Rows(0).Item(0) = Year & Month & Day Then
                    serial = Format(dt.Rows(0).Item(1) + 1, "00")
                    order_id = Year & Month & Day & "-" & serial

                Else
                    order_id = Year & Month & Day & "-01"
                End If
            Else
                order_id = Year & Month & Day & "-01"
            End If



' Command.ExecuteScalar()
 
Public Sub CreateMySqlCommand(myScalarQuery As String, myConnection As SqlConnection)
    Dim myCommand As New SqlCommand(myScalarQuery, myConnection)
    myCommand.Connection.Open()
    myCommand.ExecuteScalar()
    myConnection.Close()
End Sub
 
' Command.ExecuteReader()
 
Public Sub CreateMySqlDataReader(mySelectQuery As String, _
myConnectionString As String)
    Dim myConnection As New SqlConnection(myConnectionString)
    Dim myCommand As New SqlCommand(mySelectQuery, myConnection)
    myCommand.Connection.Open()
    Dim myReader As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
    While myReader.Read()
        Console.WriteLine(myReader.GetString(0))
    End While
    myReader.Close()
    myConnection.Close()
 End Sub
 
' Command.ExecuteNonQuery()
 
Public Sub CreateMySqlCommand(myQuery As String, myConnection As SqlConnection)
    Dim myCommand As New SqlCommand(myQuery, myConnection)
    myCommand.Connection.Open()
    myCommand.ExecuteNonQuery()
    myConnection.Close()
End Sub

Thursday, April 26, 2012

Declaration and Access Control

Array Fundamentals
Arrays are used to represent fixed number of elements of the same type. The following are legal syntax for declaring one-dimensional arrays.int anArray[];
int[] anArray;
int []anArray;

It is important to note that the size of the array is not included in the declaration. Memory is allocated for an array using the new operator as shown below. 
anArray = new int[10]; 
The declaration and memory allocation may be combined together as shown below. 
int anArray[] = new int[10]; 
The elements of the array are implicitly initialized to default values based on array types (0 for integral types, null for objects etc.). This is true for both local arrays as well as arrays which are data members. In this respect arrays are different from normal variables. Variable defined inside a method are not implicitly initialized, where as array elements are implicitly initialized.
Array Initializations
Arrays are initialized using the syntax below 
int intArray[] = {1,2,3,4}; The length operator can be used to access the number of elements in an array (for example - intArray.length).
Multidimensional Arrays
The following are legal examples of declaration of a two dimensional array. 
int[] arr[];
int[][] arr;
int arr[][];
int []arr[];
When creating multi-dimensional arrays the initial index must be created before a later index. The following examples are legal.
int arr[][] = new int[5][5];
int arr[][] = new int[5][];

The following example will not compile;
int arr[][] = new int[][5];
Class Fundamentals
A class defines a new type and contains methods and variables. The example below illustrates a simple class.

class City {
   String name;      // member variable  
   String getName()    // member method
   {
      return name;
   }
   public static void main(String arg[]) {
   }
}

Method overloading
JavaTM technology allows two methods to have the same name as long as they have different signatures. The signature of a method consists of name of the method, and count and type of arguments of the method. Thus as long as the argument types of two methods are different, they may be over-loaded (have the same name).


Class constructors
Constructors are member methods that have same name as the class name. The constructor is invoked using the new operator when a class is created. If a class does not have any constructors then Java language compiler provides an implicit default constructor. The implicit default constructor does not have any arguments and is of the type - 
class_name() { }If a class defines one or more constructors, an implicit constructor is not provided. The example below gives a compilation error. 


class Test {
   int temp;
   Test(int x) {
      temp = x;
   }
   public static void main() {
      Test t = new Test(); /* This would generate a 
      compilation error, as there is no constructor 
      without any arguments. */
   }
}
Access Control In Java


 As you know, encapsulation links data with the code that manipulates it. However, encapsulation provides another important attribute: access control. Through encapsulation, you can control what parts of a program can access the members of a class. By controlling access, you can prevent misuse. For example, allowing access to data only through a well-defined set of methods, you can prevent the misuse of that data. Thus, when correctly implemented, a class creates a “black box” which may be used, but the inner workings of which are not open to tampering. However, the classes that were presented earlier do not completely meet this goal. For example, consider the Stack class shown at the end of the Recursion article. While it is true that the methods push() and pop() do provide a controlled interface to the stack, this interface is not enforced. That is, it is possible for another part of the program to bypass these methods and access the stack directly. Of course, in the wrong hands, this could lead to trouble. In this section you will be introduced to the mechanism by which you can precisely control access to the various members of a class.
             The access specifier that modifies its declaration determines how a member can be accessed. Java supplies a rich set of access specifiers. Some aspects of access control are related mostly to inheritance or packages. (A package is, essentially, a grouping of classes.) These parts of java’s access control mechanism will be discussed later. Here, let’s begin by examining access control as it applies to a single class. Once you understand the fundamentals of access control, the rest will be easy.
             Java’s access specifiers are public, private, and protected.  Java also defines a default access level. protected applies only when inheritance is involved. The other access specifiers are described next.
             Let’s begin by defining public and private. When a member of a class is modified by the public specifier, then that member can be accessed by any other code in your program. When a member of a class is specified as private, then that member can only be accessed by other members of its class. Now you can understand why main() has always been preceded by the public specifier. It is called by code that is outside the program that is, by the java run-time system. When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package.
             In the classes developed so far, all members of a class have used the default access mode, which is essentially public. However, this is not what you will typically want to be the case. Usually, you will want to restrict access to the data members of a class allowing access only through methods. Also, there will be times when you will want to define methods, which are private to a class.
             An access specifier precedes the rest of a member’s type specification. That is, it must begin a member’s declaration statement. Here is an example:
                public int i;
        private double j;
        private int myMethod(int a, char b) {//…
To understand the effects of public and private access, consider the following program:
class Test {
     int a;
     public int b;
     private int c;
      void setc(int i) {
          c = i;
     }
     int getc() {
          return c;
     }
}
class AccessTest {
     public static void main(String args[]) {
          Test ob = new Test ();
          ob.a = 10;
          ob.b = 20;
          ob.setc(100);
          System.out.println(“a, b, and c: “ + ob.a + ”  “ + ob.b+ “  “+ ob.getc());
     }
}
            As you can see, inside the Test class, a uses default access, which for this example is the same as specifying public. b is explicitly specified as public. Member c is given private access. This means that it cannot be accessed by code outside of its class. So, inside the AccessTest class, c cannot be used directly. It must be accessed through its public methods: setc() and getc(). If you were to remove the comment symbol from the beginning of the following line;
            ob.c = 100;
then you would not be able to compile this program because of the access violation.
            To see how access control can be applied to a more practical example, consider the following improved version of the Stack class shown at the end of the article Recursion.
class Stack {
     private int stck[] = new int [10];
     private int tos;
Stack() {
     tos = -1;
}
void push(int item) {
     if( tos==9)
          System.out.println(“Stack is full.”);
     else
          stck[++tos] = item;
}
int pop() {
     if(tos <0) {
          System.out.println(“Stack underflow.”);
          Return 0;
     }
     else
         return stck[tos--];
     }
}
As you can see, now both stck, which holds the stack, and tos, which is the index of the top of the stack, are specified as private. This means that they cannot be accessed or altered except through push() and pop(). Making tos private, for example, prevents other parts of your program from inadvertently setting it to a value that is beyond the end of the stck array.         

Wednesday, April 25, 2012

Sending with VB.NET

Option Explicit On 

Imports System.Net.Sockets

Imports System.IO

Imports System.Text

Public Class ClsSMTP
    Private Enum SMTP_STATE
        MAIL_CONNECT
        MAIL_HELO
        MAIL_FROM
        MAIL_RCPTTO
        MAIL_DATA
        MAIL_DOT
        MAIL_QUIT
    End Enum

    Private Structure EMAIL
        Dim Name As String
        Dim Address As String
    End Structure

    Private Structure SMTP
        Dim HOST As String
        Dim Port As Integer
        Dim Sender As EMAIL
        Dim Recipient As EMAIL
        Dim ReplyTo As EMAIL
        Dim Subject As String
        Dim message As String
        Dim AttachmentFile As String
        Dim AttachmentData As String
        Dim EncodedFile As String
    End Structure

    Private strSMTPError As String

    Private SMTPData As SMTP
    Private SMTPState As SMTP_State

    Public Property HOST() As String
        Get
            Return SMTPData.HOST
        End Get
        Set(ByVal Value As String)
            SMTPData.HOST = Value
        End Set
    End Property

    Public Property Port() As Integer
        Get
            Return SMTPData.Port
        End Get
        Set(ByVal Value As Integer)
            SMTPData.Port = Value
        End Set
    End Property

    Public Property SenderName() As String
        Get
            Return SMTPData.Sender.Name
        End Get
        Set(ByVal Value As String)
            SMTPData.Sender.Name = Value
        End Set
    End Property

    Public Property SenderAddress() As String
        Get
            Return SMTPData.Sender.Address
        End Get
        Set(ByVal Value As String)
            SMTPData.Sender.Address = Value
        End Set
    End Property

    Public Property RecipientName() As String
        Get
            Return SMTPData.Recipient.Name
        End Get
        Set(ByVal Value As String)
            SMTPData.Recipient.Name = Value
        End Set
    End Property

    Public Property RecipientAddress() As String
        Get
            Return SMTPData.Recipient.Address
        End Get
        Set(ByVal Value As String)
            SMTPData.Recipient.Address = Value
        End Set
    End Property

    Public Property ReplyToName() As String
        Get
            Return SMTPData.ReplyTo.Name
        End Get
        Set(ByVal Value As String)
            SMTPData.ReplyTo.Name = Value
        End Set
    End Property

    Public Property ReplyToAddress() As String
        Get
            Return SMTPData.ReplyTo.Address
        End Get
        Set(ByVal Value As String)
            SMTPData.ReplyTo.Address = Value
        End Set
    End Property

    Public Property Subject() As String
        Get
            Return SMTPData.Subject
        End Get
        Set(ByVal Value As String)
            SMTPData.Subject = Value
        End Set
    End Property

    Public Property Message() As String
        Get
            Return SMTPData.message
        End Get
        Set(ByVal Value As String)
            SMTPData.message = Value
        End Set
    End Property

    Public Property AttachmentFile() As String
        Get
            Return SMTPData.AttachmentFile
        End Get
        Set(ByVal Value As String)
            SMTPData.AttachmentFile = Value
            SMTPData.EncodedFile = UUEncodeFile(SMTPData.AttachmentFile)
            SMTPData.AttachmentData = SMTPData.AttachmentData & SMTPData.EncodedFile & vbCrLf
        End Set
    End Property

    Public Property AttachmentData() As String
        Get
            Return SMTPData.AttachmentData
        End Get
        Set(ByVal Value As String)
            SMTPData.AttachmentData = Value
        End Set
    End Property

    Public ReadOnly Property SMTPError() As String
        Get
            Return strSMTPError
        End Get
    End Property

    Public Sub SendMessage()
        On Error GoTo ProcErr
        Dim strServerResponse As String
        Dim strResponseCode As String
        Dim strDataToSend As String

        Dim varLines() As String
        Dim varLine As String
        Dim strMessage As String
        Dim Count As Long
        Dim StartPoint As Long

        Dim ObjTCP As New TcpClient()
        Dim ObjOutboundData As Stream
        Dim ObjInboundData As StreamReader
        Dim DataArray() As Byte
        SMTPState = SMTP_STATE.MAIL_CONNECT

        'check data
        Select Case True
            Case InStr(1, SMTPData.Sender.Address, "@") = 0
                SMTPData.Sender.Address = SMTPData.Sender.Address & "@" & SMTPData.HOST
            Case InStr(1, SMTPData.Recipient.Address, "@") = 0
                SMTPData.Recipient.Address = SMTPData.Recipient.Address & "@" & SMTPData.HOST
        End Select

        'Call CWinSock.Connect(SMTPData.HOST, SMTPData.Port)
        ObjTCP.Connect(SMTPData.HOST, SMTPData.Port)
        ObjInboundData = New StreamReader(ObjTCP.GetStream, Encoding.ASCII)

        Do While (Not SMTPState = SMTP_STATE.MAIL_QUIT)
            strServerResponse = ObjInboundData.ReadLine

            strResponseCode = Left(strServerResponse, 3)
            If strServerResponse <> "" Then
                If strResponseCode = "250" Or strResponseCode = "220" Or strResponseCode = "354" Then
                    Select Case SMTPState
                        Case SMTP_STATE.MAIL_CONNECT
                            SMTPState = SMTP_STATE.MAIL_HELO
                            strDataToSend = Trim$(SMTPData.Sender.Address)
                            strDataToSend = Left$(strDataToSend, InStr(1, strDataToSend, "@") - 1)

                            strDataToSend = "HELO " & strDataToSend & vbCrLf

                            DataArray = Encoding.ASCII.GetBytes(strDataToSend.ToCharArray())
                            ObjOutboundData = ObjTCP.GetStream
                            ObjOutboundData.Write(DataArray, 0, strDataToSend.Length)

                        Case SMTP_STATE.MAIL_HELO
                            SMTPState = SMTP_STATE.MAIL_FROM
                            strDataToSend = "MAIL FROM:" & Trim$(SMTPData.Sender.Address) & vbCrLf

                            DataArray = Encoding.ASCII.GetBytes(strDataToSend.ToCharArray())
                            ObjOutboundData = ObjTCP.GetStream
                            ObjOutboundData.Write(DataArray, 0, strDataToSend.Length)

                        Case SMTP_STATE.MAIL_FROM
                            SMTPState = SMTP_STATE.MAIL_RCPTTO
                            strDataToSend = "RCPT TO:" & Trim$(SMTPData.Recipient.Address) & vbCrLf

                            DataArray = Encoding.ASCII.GetBytes(strDataToSend.ToCharArray())
                            ObjOutboundData = ObjTCP.GetStream
                            ObjOutboundData.Write(DataArray, 0, strDataToSend.Length)

                        Case SMTP_STATE.MAIL_RCPTTO
                            SMTPState = SMTP_STATE.MAIL_DATA
                            strDataToSend = "DATA" & vbCrLf

                            DataArray = Encoding.ASCII.GetBytes(strDataToSend.ToCharArray())
                            ObjOutboundData = ObjTCP.GetStream
                            ObjOutboundData.Write(DataArray, 0, strDataToSend.Length)

                        Case SMTP_STATE.MAIL_DATA
                            SMTPState = SMTP_STATE.MAIL_DOT

                            strDataToSend = "From:" & SMTPData.Sender.Name & " <" & SMTPData.Sender.Address & ">" & vbCrLf

                            DataArray = Encoding.ASCII.GetBytes(strDataToSend.ToCharArray())
                            ObjOutboundData = ObjTCP.GetStream
                            ObjOutboundData.Write(DataArray, 0, strDataToSend.Length)

                            strDataToSend = "To:" & SMTPData.Recipient.Name & " <" & SMTPData.Recipient.Address & ">" & vbCrLf

                            DataArray = Encoding.ASCII.GetBytes(strDataToSend.ToCharArray())
                            ObjOutboundData.Write(DataArray, 0, strDataToSend.Length)


                            If Len(SMTPData.ReplyTo.Address) > 0 Then
                                strDataToSend = "Subject:" & SMTPData.Subject & vbCrLf & vbCrLf

                                DataArray = Encoding.ASCII.GetBytes(strDataToSend.ToCharArray())
                                ObjOutboundData.Write(DataArray, 0, strDataToSend.Length)

                                strDataToSend = "Reply-To:" & SMTPData.ReplyTo.Name & " <" & SMTPData.ReplyTo.Address & ">" & vbCrLf & vbCrLf

                                DataArray = Encoding.ASCII.GetBytes(strDataToSend.ToCharArray())
                                ObjOutboundData.Write(DataArray, 0, strDataToSend.Length)

                            Else
                                strDataToSend = "Subject:" & SMTPData.Subject & vbCrLf & vbCrLf

                                DataArray = Encoding.ASCII.GetBytes(strDataToSend.ToCharArray())
                                ObjOutboundData.Write(DataArray, 0, strDataToSend.Length)
                            End If

                            If Len(SMTPData.AttachmentData) <> 0 Then
                                strMessage = SMTPData.message & vbCrLf & vbCrLf & SMTPData.AttachmentData
                            Else
                                strMessage = SMTPData.message & vbCrLf & vbCrLf
                            End If
                            varLines = Split(strMessage, vbCrLf)
                            strMessage = ""
                            For Each varLine In varLines
                                strDataToSend = varLine & vbCrLf
                                DataArray = Encoding.ASCII.GetBytes(strDataToSend.ToCharArray())
                                ObjOutboundData.Write(DataArray, 0, strDataToSend.Length)
                            Next
                            strDataToSend = "." & vbCrLf
                            DataArray = Encoding.ASCII.GetBytes(strDataToSend.ToCharArray())
                            ObjOutboundData.Write(DataArray, 0, strDataToSend.Length)
                        Case SMTP_STATE.MAIL_DOT
                            SMTPState = SMTP_STATE.MAIL_QUIT
                            strDataToSend = "QUIT" & vbCrLf

                            DataArray = Encoding.ASCII.GetBytes(strDataToSend.ToCharArray())
                            ObjOutboundData = ObjTCP.GetStream
                            ObjOutboundData.Write(DataArray, 0, strDataToSend.Length)

                        Case SMTP_STATE.MAIL_QUIT
                            ObjTCP.Close()
                    End Select
                Else
                    ObjTCP.Close()
                    If Not SMTPState = SMTP_STATE.MAIL_QUIT Then
                        strSMTPError = "SMTP Error: " & strServerResponse
                    End If
                End If
            Else
            End If
        Loop
        ObjTCP.Close()

ProcExit:
        Exit Sub
ProcErr:
        Err.Raise(Err.Number, TypeName(Me) & ".SendMessage", Err.Source & " -> " & vbCrLf & Err.Description & vbCrLf)
        GoTo ProcExit
    End Sub

    Public Function UUEncodeFile(ByVal strFilePath As String) As String
        'On Error GoTo ProcErr

        Dim ObjFile As New StreamReader(strFilePath)
        Dim Buffer() As Char
        Dim FileIndex As Integer

        Dim intFile As Integer 'file handler
        Dim intTempFile As Integer 'temp file
        Dim lFileSize As Long 'size of the file
        Dim strFileName As String 'name of the file
        Dim strFileData As String 'file data chunk
        Dim lEncodedLines As Long 'number of encoded lines
        Dim strTempLine As String 'temporary string
        Dim I As Long 'loop counter
        Dim j As Integer 'loop counter
        Dim strResult As String

        'Get file name
        strFileName = Mid$(strFilePath, InStrRev(strFilePath, "\") + 1)
        'Insert first marker: "begin 664 ..."
        strResult = "begin 664 " + strFileName + vbLf
        'Get file size
        lFileSize = FileLen(strFilePath)
        lEncodedLines = lFileSize \ 45 + 1
        'Prepare buffer to retrieve data from the file by 45 symbols chunks
        strFileData = Space(45)
        intFile = FreeFile()

        ' Open strFilePath For Binary As intFile
        For I = 1 To lEncodedLines
            'Read file data by 45-bytes cnunks
            If I = lEncodedLines Then
                'Last line of encoded data often is not equal to 45, therefore we need to change size of the buffer
                strFileData = Space(lFileSize Mod 45)
            End If
            'Retrieve data chunk from file to the buffer
            ReDim Buffer(strFileData.Length - 1)
            ObjFile.ReadBlock(Buffer, FileIndex, strFileData.Length)
            strFileData = CStr(Buffer)

            'Get intFile, , strFileData

            'Add first symbol to encoded string that informs about quantity of symbols in encoded string.
            'More often "M" symbol is used.
            strTempLine = Chr(Len(strFileData) + 32)
            If I = lEncodedLines And (Len(strFileData) Mod 3) Then
                'If the last line is processed and length of source data is not a number divisible by 3, add one or two blankspace symbols
                strFileData = strFileData + Space(3 - (Len(strFileData) Mod 3))
            End If
            For j = 1 To Len(strFileData) Step 3
                'Breake each 3 (8-bits) bytes to 4 (6-bits) bytes
                '1 byte
                strTempLine = strTempLine + Chr(Asc(Mid(strFileData, j, 1)) \ 4 + 32)
                '2 byte
                strTempLine = strTempLine + Chr((Asc(Mid(strFileData, j, 1)) Mod 4) * 16 + Asc(Mid(strFileData, j + 1, 1)) \ 16 + 32)
                '3 byte
                strTempLine = strTempLine + Chr((Asc(Mid(strFileData, j + 1, 1)) Mod 16) * 4 + Asc(Mid(strFileData, j + 2, 1)) \ 64 + 32)
                '4 byte
                strTempLine = strTempLine + Chr(Asc(Mid(strFileData, j + 2, 1)) Mod 64 + 32)
            Next j
            'replace " " with "`"
            strTempLine = Replace(strTempLine, " ", "`")
            'add encoded line to result buffer
            strResult = strResult + strTempLine + vbLf
            'reset line buffer
            strTempLine = ""
        Next I
        ObjFile.Close()

        'Close(intFile)

        'add the end marker
        strResult = strResult & "`" & vbLf + "end" + vbLf
        'asign return value
        UUEncodeFile = strResult

ProcExit:
        Exit Function
ProcErr:
        Err.Raise(Err.Number, "MUUEncode.UUEncodeFile", Err.Source & " -> " & vbCrLf & Err.Description & vbCrLf)
        GoTo ProcExit

    End Function

End Class