[VB.NET] Quick Refference Syntax


Description
      Here's quick refference syntax that i already use , and it's always update.

How To

IF - ELSE
if <exp> then
     'to do here
else
     'to do here
end if
example :
if i = true then
     msgbox "yes"
else
     msgbox "no"
end if


FOR - NEXT
for <var initialize> <condition>
     'to do here
next <var initialize>
example :
for i = 1 to 5
     msgbox(i)
next i


WHILE
while <expression>
     'to do here
end while
example :
while i = 5
     msgbox "yes"
end while


DO-WHILE-LOOP
do
     'to do here
loop while <expression>
example
do
     msgbox "yes"
loop while i = 5


SELECT - CASE
select <expression>
case <expression>
      'to do here
case default
      ' if not match any case
end select
example
select number
case "1"
      msgbox " yes"
case default
      msgbox "no"
end select


*get path current application
My.Application.Info.DirectoryPath & "\SQLServer.udl"

*playing sound
Imports System.Media.SoundPlayer
Dim Sound As New System.Media.SoundPlayer()
Sound.SoundLocation = My.Application.Info.DirectoryPath & "\Sound\tick.wav"
Sound.Load()
Sound.Play()

*format string (add some string), for example i want format string like this "000005" (convert from int)
.ToString().PadLeft(5, "0")

*get datetime now , with custom format
DateTime.Now.ToString("MM/dd/yyyy")

*set variable constant
Public Const IP_DB_SQLSERVER As String = "1x.xx.xx.xx"

*remove space
trim("this is space") 'the result : "thisisspace"

*Escape string
 Uri.EscapeDataString("string")

*Set Regional Setting to standart - it's affect date time
Imports System.Threading
Imports System.Globalization
    Public Sub regionalSetting()
        ' Sets the culture to US (en-US)
        Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
        ' Sets the UI culture to US (en-US)
        Thread.CurrentThread.CurrentUICulture = New CultureInfo("en-US")
    End Sub

*Set oracle Language (Datetime) - it's affect date time in Oracle Database
Imports Microsoft.Win32
Public Sub oraNLSLangReg()
        Dim regKey As RegistryKey
        Dim backupVal As String

        'reading
        regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\ORACLE\KEY_OraClient10g_home1", False)

        If regKey.GetValue("NLS_LANG") = "AMERICAN_AMERICA.WE8ISO8859P1" Then
            'no need for edit
        Else
            ' need for setting but backup first
            backupVal = regKey.GetValue("NLS_LANG")
            regKey.Close()
            regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\ORACLE\KEY_OraClient10g_home1", True)
            regKey.SetValue("BACKUP_NLS_LANG", backupVal)
            regKey.SetValue("NLS_LANG", "AMERICAN_AMERICA.WE8ISO8859P1")
            regKey.Close()
        End If
    End Sub

Note : if you have any quick refference that you think is important , just comment below .... i will add in this article, thank you.

[VB.NET] Transparent Form


Description
      Learn how to make form into transparent without make another object transparent, it's different from opaque that make transparent all object.

How To
1. first make the background color of the form into white color (color.white)

2. On Event Load Form , write this code :
        TransparencyKey = Color.White
        BackColor = Color.White

3. Done , you form is transparent and you can add control object over it but don't give the background of control object into white color because it will become transparant too (white = transparant) so use a color other than white.

4. to bring form background you can use "picture box" and set property "Background Image Layout" into "center", why "picture box" ? because "picture box" support transparent color from file format like GIF and PNG. so you can make border of your form not always rectangle, it's based your imagination :)

5. set position of your "picture box" into behind by right click of  "picture box" , and click "Send to Back"

6. please comment if you having difficult or another idea :).

[INFO-ANDROID] Create Appointment on android

-


Description
-        create appintment on android , in this article i use OS Android Jelly Bean and the target user (attendant) use microsoft exchange server (outlook). already test and it's work.


-How To
 -     to make appointment and send to attendant most of people think this feature is default come from email application, but they wrong (haha first i look like that too ) , when i need this feature i didn't find it. it's make me feel dizzy and headache. now i've find it and i will share to everyone who need :).

-     if you see the word of "appointment" in email  , you will think when the date !! , that's our KEY !! in smartphone you can find the date in CALENDAR, now open your Calendar from smartphone, in this case i using android.



calendar in android (click to enlarge)


-      After you open the calendar, click on the cell of table, and open the menu it will appear many options, then select "New Event", look picture below if you don't understand.

 calendar in android (click to enlarge)


-     After that, Setting the event by fill the event name , location , when the appointments will be held , and look on the guest row , fill that with an email of the target (attendant) of course you can fill that more than one. after that you can click done.



-     when you finish by click "Done", the calendar send email to target attendant. in this step you success make an appointment. you can see , broadcast email to the guest or edit the appointment you made before by click cell of table in calendar that already fill by the event appointment. when you click it will appear like below

the appointment that you created


-     and last don't forget to always setting "Sync Calendar" on email settings.

    Sync Calendar


-That's all , Create Appointment on android.

[Database][SQLServer] Backup - Full Database


Description
         Performing Backup - Full database in SQLServer .

How To.
1. Open SQLServer Management Studio
2. After you connect database , select database (highlight) that you want to backup.
3. Right click the database and select Tasks > Backup (see the picture below)


Right click on database

4. it will open a new form with many setting , here's the step :
      - Step-1 : look on the left corner , on page menu select "General"
      - Step-2 : Make sure you select right DB
      - Step-3 : Select backup type FULL
      - Step-4 : Give The sets of name (it will appear during restore database)
      - Step-5 : Set the expired to zero / 0 , it means "never expired"
      - Step-6 : Remove Current Save Path (by default the path is in current directory SQLServer).
      - Step-7 : Add new save path , don't forget add extention .BAK on the filename.
      - Step-8 : look again on the left corner , on page menu select "Options"

    for fast understanding you can see picture below


 Backup Option - General (SQLServer)

5. On page "Options" , look on the box picture below , the settings depend what you need.
    - Append to existing backup database , it usually use by the first time backup the database , if you have an existing database with same name, the data won't overwrite but will add.
    - Overwrite all exiting backup sets , it will overwrite all of data include all structure. the old data that overwrite will be lost.

   
 Backup Option - Options (SQLServer)


that's all , backup database - full on SQLServer


[Database][SQLServer] Cannot call methods on void type.


Description
     Null cannot call method, it usually typo from user.


How To
     Just fixed the query, example typo query maybe like this :

     NULL.ALIAS.FIELD

    Just Fixed to : NULL , ALIAS.FIELD

    no DOT Character  in front of NULL.

[INFO-EMAIL] Setting email on mobile Device

Description
      Setting email on your mobile device , most work on all OS (because the setting is same average)., this setting is only 3 popular domain : Yahoo , Google , Outlook / Hotmail (Exchange Server)

How to

Here's the setting

yahoo.com (IMAP)
-----------------------------------------------
username : 'your account
password : *****
pop3 server : pop.mail.yahoo.com
port : 995
security : SSL/TLS


Gmail.com (IMAP)
-----------------------------------------------
username : 'your account
password : *****
pop3 server : imap.gmail.com
port : 995
security : SSL/TLS


Hotmail / Outlook (Exchange Server)
-----------------------------------------------
domain\username : xxx@outlook.com
password : *****
Server : blu402-m.hotmail.com
checklist : use SSL and Accept all certificate
client certificate : none
port : 443

Now the question , which is the best of 3 email above ??
i personally choose Outlook , why ? because it support exchange activesync.
activesync provide notification as soon as possible when email has been arrived. so the respons very fast.
for more information about exchange activesync you learn on wiki.
but i have 3 account above haha :D.

if you want to register you can go here :
Mail.Yahoo.com
Mail.Google.com
Outlook.com

[Oauth] Full Source Class Twitter VB.NET

Before copy paste , read this explanation first Click HERE
To use this class , Read this 
VB.NET 2010

'copy paste start here
Imports System.Security.Cryptography
Imports System.Text
Imports System.Net
Imports System.IO
Imports System.IO.Compression
Imports System.Windows.Forms

Public Class TwitterLib

    Private Api_Response_Header As WebHeaderCollection
    Private Base_Format As String
    Private Method() As String = {"GET", "POST"}
    Public chooseMethod As Integer = "0" 'User select 0(GET) or 1(POST)
    Private oauth_signKey As String
    Private oauth_baseString As String
    Public oauth_consumer_key As String
    Public oauth_consumer_secret As String
    Private oauth_nonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString())) & "AbCdEfKg" '32 bit string
    Public oauth_resource_url As String
    Private oauth_signature As String
    Public oauth_signature_method As String = "HMAC-SHA1"
    Private oauth_timestamp As String = (DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds
    Public oauth_token As String
    Public oauth_token_secret As String
    Public oauth_version As String = "1.0"
    Public oauth_host As String = "api.twitter.com"
    Public count = "15"
    Private workType() As String = {"Retrieval", "PostStatus"}
    Public chooseWorkType As Integer = 0 'User select 0(Retrieval) or 1(PostStatus)
    Public updateStatus As String = " "
    Public limitation As String
    Public rate_limit As String
    Public utc_reset As String
    Private _chars(,) As String = {{"%", "%25"}, {"$", "%24"}, {"&", "%26"}, {"+", "%2B"}, {",", "%2C"}, {"/", "%2F"}, {":", "%3A"}, {";", "%3B"}, {"=", "%3D"}, {"?", "%3F"}, {"@", "%40"}, {" ", "%20"}, {"\", "%22"}, {"<", "%3C"}, {">", "%3E"}, {"#", "%23"}, {"{", "%7B"}, {"}", "%7D"}, {"|", "%7C"}, {"\", "%5C"}, {"^", "%5E"}, {"~", "%7E"}, {"[", "%5B"}, {"]", "%5D"}, {"'", "%60"}}



    Private Function Create_baseString(ByVal oauth_consumer_key As String, ByVal oauth_nonce As String, ByVal oauth_signature_method As String, ByVal oauth_timestamp As String, ByVal oauth_token As String, ByVal oauth_version As String) As String
        Dim baseString As String
        Try
            Select Case workType(chooseWorkType)
                Case "Retrieval"
                    Base_Format = "count={6}&oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}"
                    baseString = String.Format(Base_Format,
                    oauth_consumer_key,
                    oauth_nonce,
                    oauth_signature_method,
                    oauth_timestamp,
                    oauth_token,
                    oauth_version,
                    count
                    )
                    Return String.Concat(Method(chooseMethod) & "&", Uri.EscapeDataString(oauth_resource_url), "&", Uri.EscapeDataString(baseString))
                Case "PostStatus"
                    Base_Format = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}"
                    baseString = String.Format(Base_Format,
                    oauth_consumer_key,
                    oauth_nonce,
                    oauth_signature_method,
                    oauth_timestamp,
                    oauth_token,
                    oauth_version,
                    Uri.EscapeDataString(updateStatus)
                    )
                    Return String.Concat(Method(chooseMethod) & "&", Uri.EscapeDataString(oauth_resource_url), "&", Uri.EscapeDataString(baseString))
                Case Else
                    MessageBox.Show("Some parameter wrong or not complete please check your syntax !! (Er.Code : x01)")
                    Return "zero"
            End Select

        Catch ex As Exception
            Return "error occured when creating basestring"
        End Try
    End Function

    Private Function Create_signKey(ByVal oauth_consumer_secret As String, ByVal oauth_token_secret As String) As String
        Try
            Return Uri.EscapeDataString(oauth_consumer_secret) & "&" & Uri.EscapeDataString(oauth_token_secret)
        Catch ex As Exception
            Return "error occured when creating signkey"
        End Try
    End Function

    Private Function Create_Signature(ByVal oauth_signKey As String, ByVal oauth_baseString As String) As String
        Try
            Dim encryption
            encryption = New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(oauth_signKey))
            Using (encryption)
                Return Uri.EscapeDataString(Convert.ToBase64String(encryption.ComputeHash(ASCIIEncoding.ASCII.GetBytes(oauth_baseString))))
            End Using
        Catch ex As Exception
            Return "error occured when creating signature"
        End Try
    End Function

    Private Sub generateParameter(ByRef oauth_baseString As String, ByRef oauth_signKey As String, ByRef oauth_signature As String)
        Try
            oauth_baseString = Create_baseString(oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, oauth_version)
            oauth_signKey = Create_signKey(oauth_consumer_secret, oauth_token_secret)
            oauth_signature = Create_Signature(oauth_signKey, oauth_baseString)
        Catch ex As Exception
        End Try
    End Sub

    Public Function EncodeText(ByVal url As String) As String
        For i As Integer = 0 To _chars.GetUpperBound(0) - 1
            url = url.Replace(_chars(i, 0), _chars(i, 1))
        Next i
        Return (url)
    End Function

    'Public Function Connect_Api_Twitter(ByVal oauth_resource_url As String, ByVal oauth_consumer_key As String, ByVal oauth_nonce As String, ByVal oauth_signature As String, ByVal oauth_signature_method As String, ByVal oauth_timestamp As String, ByVal oauth_token As String, ByVal oauth_version As String, ByRef Api_Response_Header As Object) As String
    Public Function Connect_Api_Twitter() As String
        Dim json As String
        Dim reader As StreamReader
        Dim myHttpWebResponse As HttpWebResponse
        Dim myHttpWebRequest As HttpWebRequest
        Dim myWebHeaderCollection As WebHeaderCollection
        Dim responseStream As Stream

        updateStatus = updateStatus.Replace("!", "")

        Try
            'Generate All Parameter
            generateParameter(oauth_baseString, oauth_signKey, oauth_signature)

            Select Case workType(chooseWorkType)
                Case "Retrieval"
                    myHttpWebRequest = CType(WebRequest.Create(oauth_resource_url & "?count=" & count), HttpWebRequest)
                Case "PostStatus"
                    myHttpWebRequest = CType(WebRequest.Create(oauth_resource_url & "?status=" & EncodeText(updateStatus)), HttpWebRequest)
                Case Else
                    myHttpWebRequest = CType(WebRequest.Create(oauth_resource_url & "?count=" & count), HttpWebRequest)
            End Select

            myWebHeaderCollection = myHttpWebRequest.Headers
            myHttpWebRequest.Method = Method(chooseMethod)
            myHttpWebRequest.Host = oauth_host
            'myHttpWebRequest.UserAgent = "Personal Application Learner"
            myWebHeaderCollection.Add("Authorization: OAuth oauth_consumer_key=""" & oauth_consumer_key & """, oauth_nonce=""" & oauth_nonce & """, oauth_signature=""" & oauth_signature & """, oauth_signature_method=""" & oauth_signature_method & """, oauth_timestamp=""" & oauth_timestamp & """, oauth_token=""" & oauth_token & """, oauth_version=""" & oauth_version & """")
            myWebHeaderCollection.Add("Accept-Encoding:gzip")
            myHttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)

            responseStream = myHttpWebResponse.GetResponseStream()
            If (myHttpWebResponse.ContentEncoding.ToLower().Contains("gzip")) Then
                responseStream = New GZipStream(responseStream, CompressionMode.Decompress)
            ElseIf (myHttpWebResponse.ContentEncoding.ToLower().Contains("deflate")) Then
                responseStream = New DeflateStream(responseStream, CompressionMode.Decompress)
            End If
            reader = New StreamReader(responseStream, Encoding.Default)
            json = reader.ReadToEnd()
            Api_Response_Header = myHttpWebResponse.Headers

            'Return Json and Header
            If workType(chooseWorkType) = "PostStatus" Then
                'if using for post twitter then no response header from server
            Else
                limitation = Api_Response_Header.GetValues(14)(0)
                rate_limit = Api_Response_Header.GetValues(15)(0)
                utc_reset = Api_Response_Header.GetValues(16)(0)
            End If

            Return json
        Catch ex As Exception
            MessageBox.Show("Error Occured, please check your connection or parameter")
            json = "Error Occured please check the connection or parameter !!"
            Return "error"
        End Try

    End Function
End Class

[Oauth] Introduction oauth and how to use

Deskripsi
        Learn about Oauth ver.1.1

on wiki :
OAuth is an open standard for authorization. OAuth provides client applications a 'secure delegated access' to server resources on behalf of a resource owner. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials. Designed specifically to work with Hypertext Transfer Protocol (HTTP), OAuth essentially allows access tokens to be issued to third-party clients by an authorization server, with the approval of the resource owner, or end-user. The client then uses the access token to access the protected resources hosted by the resource server. OAuth is commonly used as a way for web surfers to log into third party web sites using their Google, Facebook or Twitter accounts, without worrying about their access credentials being compromised.

for developers , we need 4 key that provide by the vendor for example twitter :

here's the key, if you don't know how to create it just google -_-a  : 
- consumer key
- consumer secret
- access token  *by default status readonly , you must change to 'write' if you want to tweet

- access token secret *by default status readonly  , you must change to 'write' if you want to tweet
note : this 4 key must be kept secret from the user and only the developer knows.

Step 1
you must know the resource URL of the vendor (for the example twitter), from twitter API we get sample resource URL like this :
- For data retrieval
GET statuses/mentions_timeline
GET statuses/user_timeline 
GET statuses/home_timeline
GET statuses/retweets_of_me

- For posting tweets
POST statuses/update

Step 2
create oauth_BaseString
oauth_BaseString consist of 3 part : method, resource_url and basestring

here's explanation
method : GET / POST
resource_url :  https://api.twitter.com/1.1/statuses/user_timeline.json
base string :
   -base string part :
         - oauth_consumer_key // dynamic
         - oauth_nonce // dynamic
         - oauth_signature_method = HMAC-SHA1
         - oauth_timestamp // dynamic
         - oauth_token  // dynamic
         - oauth_version= // dynamic
 
      - Here's the example base string :
"oauth_consumer_key=xxx&oauth_nonce=9c3f7ae6df9649a77c34ac588e4b6372&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1380789372&oauth_token=yyy&oauth_version=1.0"

you must thinking where i get oauth_nononce and  oauth_timestamp right ?

oauth_nononce is Random 64-bit, unsigned number encoded as an ASCII string in decimal format. you can create it by generate datetime and convert into base64 , the total string must 32 digit, if less you add manually.

oauth_timestamp is an Integer representing the time the request is sent. The timestamp should be expressed in number of seconds after January 1, 1970.

after basestring created , oauth_BaseString need basestring converted into a format escape character
 because it send from url (headers).


step 3
create oauth_signKey
oauth_signKey consist of 2 part : oauth_consumer_secret and oauth_token_secret

here's the explanation :
- oauth_consumer_secret : This key is usually obtained from vendors , don't worry :)
- oauth_token_secret : This key is usually obtained from vendors , don't worry :)

you must combine the 2 key and add '&' between two key , and escape string character that each key.
here the example key :
oauth_signKey = "4hpFcExUrg1V6vCSYMAhg&t2SwVdDenSSaTjRiPo0PGy5ytSZjAe5lXsHTmUiFI6U"

here's the rugged code example from vb.net
Uri.EscapeDataString(oauth_consumer_secret) & "&" & Uri.EscapeDataString(oauth_token_secret) 


step 4
create oauth_signature
if you don't have oauth_BaseString , go back step_2
to create signature you must have oauth_BaseString that encrypted using HMAC-SHA1 , then converted into 64Base string and last escape string character.

here's the rugged code example from vb.net
Private Function Create_Signature(ByVal oauth_signKey As String, ByVal oauth_baseString As String) As String
        Try
            Dim encryption
            encryption = New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(oauth_signKey))
            Using (encryption)
                Return Uri.EscapeDataString(Convert.ToBase64String(encryption.ComputeHash(ASCIIEncoding.ASCII.GetBytes(oauth_baseString))))
            End Using
        Catch ex As Exception
            Return "error occured when creating signature"
        End Try
    End Function


that's all step we need to Authorized in oauth.
Authorization oauth (for example twitter) need some key here's the format :

Authorization: OAuth oauth_consumer_key="xxx", oauth_nonce="yyy",oauth_signature="zzz", oauth_signature_method="abc", oauth_timestamp="12456623", oauth_token="abc", oauth_version="1.0".
*note : length of value is dynamic not same as above.

so for authorization , you need :
Keyword : Authorization: OAuth
1. oauth_consumer_key
2. oauth_nonce
3. oauth_signature
4. oauth_signature_method
5. oauth_timestamp
6. oauth_token
7. oauth_version
and place it into webheader , i will give example full source of my class for twitterLib in vb.net , i hope you can learn it fast and translate it into any programming language :).

here's the full source oauth twitterLib class VB.NET

[INFO-ANDROID] Display Automatically Image on Default Application Email Android ?


Question
       i want to always load picture in default application email android , is there possible or any settings ?

The Answer 
      NO , the reason is security issue but you can always load picture per Sender. to set autoload image per sender, open your email (incoming email / inbox then find the email that the content have an image). below target sender or (to: xxx ) you see an option "show pictures" klik that and appear new option "always show pictures from this sender" and klik that again (annoying right ?).

the effect , email came from that sender will be automatically load picture (only that sender), so if you have many trust email you must do this manually.

yes it's very very annoying but your smartphone safe from threat like malware which can steal your information.


[VB.NET] Insert Icon before text in Button


Description
    Add icon on button to beautify the look of button in vb.net.

How To
1. Import resource , we need image with resolution 64px x 64px and extention (PNG / ICO) because it support transparent.
to import:
    * Project > Properties > select RESOURCE > Add Resource > Add Existing File and select the image.

2. After success import , we change the property the button. find property "Text Image Relation" and set "Image Before Text"

3. now setup the image size on the button, we need event form_load to do this, look code below :

'---- start here----
Dim btnImageIco As New Bitmap(New Bitmap(My.Resources.myimage), 16, 16)

commandButton1.Image = btnImageIco
commandButton1.ImageAlign = ContentAlignment.MiddleCenter
'---- end ------

explanation :
* 16 , 16 => size image in pixel , you can change it
* ContentAlignment.MiddleCenter => image and text is center with relation "Image Before Text" look step 2

if you have trouble with align you can make change with just lengthen the size of button.