Friday, June 22, 2007

Using Cross Control Thread in .Net 2.0

This article discuss about the using of Thread in .Net 2.0. In the previous framework (.Net 1.1), it is easy to create a thread cross between control or class. But we can not use the same method for .Net 2.0. We should use a callback that delegate enables asynchronous calls to cross thread control.

First step, we define the thread.

'define thread for translation
Private threadTranslation As System.Threading.Thread

Second step, we call a ThreadTranslation function to start the process.

'create a process thread, then start translation
If IsNothing(threadTranslation) OrElse Not threadTranslation.IsAlive Then
threadTranslation = New System.Threading.Thread(AddressOf ThreadTranslation)
threadTranslation.Start()
End If

The first and second step are same with the .Net 1.1. procedures.

The next third step is different, we add a delegate function as a callback. The public function will invoke the callback function if the caller from different thread.

' This delegate enables asynchronous calls to cross thread control
Delegate Function GetDictionaryTextCallback() As String

Public Function GetDictionaryText() As String
Dim strText As String = ""
Try
' InvokeRequired required compares the thread ID of the
' calling thread to the thread ID of the creating thread.
' If these threads are different, it returns true.
If txtDictionary.InvokeRequired Then
Dim d As New GetDictionaryTextCallback(AddressOf GetDictionaryText)
strText = Me.Invoke(d, New Object() {})
Else
strText = txtDictionary.Text
End If
Return strText
Catch ex As Exception
Throw ex
End Try
End Function

The ThreadTranslation function will call GetDictionaryText function from different thread. The GetDictionaryText will invoke the callback function.
The result will be successfully written into textbox in the different thread.

I use this method in my Bahasa Professional project.

Friday, February 17, 2006

How to check Internet Connection using .Net

In this article I want to describe how to check Internet Connection using .Net.
We use an API function to check the connection; InternetGetConnectionState.

The function source code is described below:

Private Declare Function InternetGetConnectedState Lib "wininet.dll" (ByRef lpdwFlags As Int32, _
ByVal dwReserved As Int32) As Boolean

Public Function IsConnectionAvailable() As Boolean
Dim lngFlags As Long
Try
'Return True if connection is available
IsConnectionAvailable = InternetGetConnectedState(lngFlags, 0)
Catch ex As Exception
Throw ex
End Try
End Function

Sunday, February 12, 2006

WebDAV for .Net Sample Application

This is a sample to send email using WebDAV protocol:

'define public variables
Private strUsername As String
Private strPassword As String
Private strAddress As String
Private strServer As String
Private strDomain As String
Private strMailboxURI As String

Public Sub SendEmail(ByVal strTo As String, ByVal strSubject As String, ByVal strBody As String)

'Variables.
Dim PUTRequest As System.Net.HttpWebRequest
Dim PUTResponse As System.Net.HttpWebResponse
Dim MOVERequest As System.Net.HttpWebRequest
Dim MOVEResponse As System.Net.HttpWebResponse
Dim strMailboxURI As String
Dim strSubURI As String
Dim strTempURI As String
Dim PUTRequestStream As System.IO.Stream
Dim bytes() As Byte
Try
' Build the mailbox URI.
strMailboxURI = "http://" & strServer & "/exchange/" & strAddress
' Build the submission URI for the message. If Secure
' Sockets Layer (SSL) is set up on the server, use
' "https://" instead of "http://".
strSubURI = strMailboxURI & "/##DavMailSubmissionURI##/"
' Build the temporary URI for the message. If SSL is set
' up on the server, use "https://" instead of "http://".
strTempURI = strMailboxURI & "/drafts/" & strSubject & ".eml"
' Construct the RFC 822 formatted body of the PUT request.
' Note: If the From: header is included here,
' the MOVE method request will return a
' 403 (Forbidden) status. The From address will
' be generated by the Exchange server.
strBody = "To: " & strTo & vbNewLine & _
"Subject: " & strSubject & vbNewLine & _
"Date: " & System.DateTime.Now & _
"X-Mailer: test mailer" & vbNewLine & _
"MIME-Version: 1.0" & vbNewLine & _
"Content-Type: text/plain;" & vbNewLine & _
"Charset = ""iso-8859-1""" & vbNewLine & _
"Content-Transfer-Encoding: 7bit" & vbNewLine & _
vbNewLine & strBody
' Create the PUT HttpWebRequest object.
PUTRequest = CType(System.Net.WebRequest.Create(strTempURI), _
System.Net.HttpWebRequest)
' Create a new CredentialCache object and fill it with the network
' credentials required to access the server.
' Add the network credentials to the request.
Dim myCredential As System.Net.NetworkCredential = New System.Net.NetworkCredential(strUsername, strPassword, strDomain)
PUTRequest.Credentials = myCredential
' Specify the PUT method.
PUTRequest.Method = "PUT"
' Encode the body using UTF-8.
bytes = System.Text.Encoding.UTF8.GetBytes(strBody)
' Set the content header length. This must be
' done before writing data to the request stream.
PUTRequest.ContentLength = bytes.Length
' Get a reference to the request stream.
PUTRequestStream = PUTRequest.GetRequestStream()
' Write the message body to the request stream.
PUTRequestStream.Write(bytes, 0, bytes.Length)
' Close the Stream object to release the connection
' for further use.
PUTRequestStream.Close()
' Set the Content-Type header to the RFC 822 message format.
PUTRequest.ContentType = "message/rfc822"
' PUT the message in the Drafts folder of the
' sender's mailbox.
PUTResponse = CType(PUTRequest.GetResponse(), System.Net.HttpWebResponse)
'Console.WriteLine("Message successfully PUT to " & strTempURI)
' Create the MOVE HttpWebRequest object.
MOVERequest = CType(System.Net.WebRequest.Create(strTempURI), _
System.Net.HttpWebRequest)
' Add the network credentials to the request.
MOVERequest.Credentials = myCredential
' Specify the MOVE method.
MOVERequest.Method = "MOVE"
' Set the Destination header to the
' mail submission URI.
MOVERequest.Headers.Add("Destination", strSubURI)
' Send the message by moving it from the Drafts folder of the
' sender's mailbox to the mail submission URI.
MOVEResponse = CType(MOVERequest.GetResponse(), System.Net.HttpWebResponse)
'Console.WriteLine("Message successfully sent to " & strTo)
' Clean up.
PUTResponse.Close()
MOVEResponse.Close()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try

End Sub

Saturday, February 11, 2006

Sending Email in .Net using WebDAV

Items in the Exchange store can be accessed remotely by using the WebDAV protocol, defined in RFC 2518. This protocol extends the HTTP 1.1 protocol, defined by RFC 2616, to provide additional methods and capabilities. It provides a means to access both the contents of an item and an extensible set of associated properties. Some of the methods defined by the protocol are the MOVE Method, the COPY Method, the DELETE Method, and the MKCOL Method. The encoding format used to transfer item properties across the network is XML, defined in the World Wide Web Consortium (W3C) Recommendation REC-xml-20001006.
When a URL in the Exchange store is entered in a Web browser, an XML formatted WebDAV protocol request is created and sent to the Microsoft® Exchange Server computer. When the server receives the request, it verifies the credentials of the client and automatically parses the XML for the requested data. The server then builds an XML WebDAV protocol response containing the appropriate properties and their values and sends the response back to the client. If the Web browser is able to parse XML, an XSL style sheet can be applied to the XML response and the data will be displayed in the browser. If the Web browser cannot parse XML, the information is displayed in HTML.

The following illustration shows how a client browser interacts with the Exchange store using WebDAV.


Microsoft Internet Explorer 5 and later provide the Microsoft XML (MSXML) Component Object Model (COM) component, a powerful XML parser and set of related tools. The XMLHTTPRequest COM class integrates with MSXML COM objects to simplify the management of client-side HTTP protocol requests and responses that contain XML bodies.

The transformational capabilities of the MSXML component can easily cast the response XML data into HTML, which can then be displayed by the browser.

Friday, February 10, 2006

CDO.Net Sample Application

This is a sample for Sending Email using CDO.Net. Don't forget to add the reference to Microsoft CDO for Exchange Library.

'set constants
Public Const cdoLow = 0
Public Const cdoNormal = 1
Public Const cdoHigh = 2
Public Const cdoSendUsingPort = 2
Public Const cdoSendUsingExchange = 3
Public Const cdoImportance = "urn:schemas:httpmail:importance"
Public Const cdoSendUsingMethod = _
"http://schemas.microsoft.com/cdo/ configuration/sendusing"
Public Const cdoSMTPServer = _
"http://schemas.microsoft.com/cdo/ configuration/smtpserver"
Public Const cdoSMTPServerPort = _
"http://schemas.microsoft.com/cdo/ configuration/smtpserverport"
Public Const cdoSMTPConnectionTimeout = _
"http://schemas.microsoft.com/cdo/ configuration/smtpconnectiontimeout"
Public Const cdoSMTPAuthenticate = _
"http://schemas.microsoft.com/cdo/ configuration/smtpauthenticate"
Public Const cdoBasic = 1
Public Const cdoSendUserName = _
"http://schemas.microsoft.com/cdo/ configuration/sendusername"
Public Const cdoSendPassword = _
"http://schemas.microsoft.com/cdo/ configuration/sendpassword"


Dim objConfig As CDO.Configuration
Dim oFields As ADODB.Fields
Dim oField As ADODB.Field
Dim objMessage As CDO.Message


'---------------- SETUP CONNECTION --------------
'Setup configuration to connect to Exchange Server using SMTP
objConfig = New CDO.Configuration
oFields = objConfig.Fields
' Set config fields we care about
oField = oFields(cdoSendUsingMethod)
oField.Value = cdoSendUsingPort
'Change to read web.config SmptServer section
oField = oFields(cdoSMTPServer)
oField.Value = ConfigurationSettings.AppSettings("EmailServer")
'set SMTP port
oField = oFields(cdoSMTPServerPort)
oField.Value = 25
'set connection timeout
oField = oFields(cdoSMTPConnectionTimeout)
oField.Value = ConfigurationSettings.AppSettings("ConnectionTimeOut")
'set smtp autenthication
oField = oFields(cdoSMTPAuthenticate)
oField.Value = cdoBasic
'set username
oField = oFields(cdoSendUserName)
oField.Value = ConfigurationSettings.AppSettings("DomainName") & "\" & strUserId
'set password
oField = oFields(cdoSendPassword)
oField.Value = strPassword
oFields.Update()


'-------------- CREATE CDO Message Object -----------
objMessage = CreateObject("CDO.Message")
objMessage.Configuration = objConfig


'set the sender
objMessage.From = strEmail


'set destination
objMessage.To = strEmailTo

'set carbon copy
objMessage.CC = strEmailCC


'set blank carbon copy
objMessage.BCC = strEmailBCC


'set the subject
objMessage.Subject = strSubject


'set the message body
objMessage.TextBody = strBody


'add attachment
objMessage.AddAttachment(strFilePath)


'set the message importance
objMessage.Fields(cdoImportance).Value = cdoHigh

'save the message
objMessage.Fields.Update()


'send the message
objMessage.Send()

Sending Email in .Net using CDO

Collaboration Data Objects (CDO) is a server-side collaborative component that is used in conjunction with Microsoft® ActiveX® Data Objects (ADO) 2.5 and Active Directory® Service Interfaces (ADSI). You can use CDO to create Web collaboration solutions based on the Exchange store and Microsoft Active Directory® service in Microsoft Windows® server operating systems. Whereas OLE DB, ADO, and ADSI provide the fundamental data access mechanisms to the Exchange store and Active Directory, CDO provides extended collaborative functionality that includes the creation and management of the following:

  • Folders and non-folder items
  • Messages
  • Appointments
  • Meeting request messages and responses (accept, accept tentative, decline)
  • Contacts
  • Mailboxes, recipients, and the Exchange store folder hierarchies and settings
  • Exchange store event-driven workflows that manage process-driven application

In Microsoft Exchange Server 2003, CDO is available only on the same computer (or cluster) as Exchange Server 2003 itself. In addition, CDO can access data only in a local Exchange Server 2003 public store or mailbox store. It cannot directly access data residing in different Exchange Server 2003 stores.

Note The CDO for Exchange Management (CDOEXM) component of CDO can be used from remote servers. You can install CDOEXM along with the Exchange Server 2003 Administration tools.