<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Catalyst Development &#187; SocketTips</title>
	<atom:link href="http://blog.catalyst.com/archives/category/sockettips/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.catalyst.com</link>
	<description>Applications, Components and Libraries For Software Developers</description>
	<lastBuildDate>Fri, 18 Nov 2011 21:34:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>Remote Command Execution</title>
		<link>http://blog.catalyst.com/archives/36</link>
		<comments>http://blog.catalyst.com/archives/36#comments</comments>
		<pubDate>Wed, 12 Aug 2009 20:50:22 +0000</pubDate>
		<dc:creator>Catalyst</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[SocketTips]]></category>
		<category><![CDATA[Visual Basic]]></category>

		<guid isPermaLink="false">http://blog.catalyst.com/?p=36</guid>
		<description><![CDATA[When people think of the Secure Shell (SSH) protocol, interactive terminal sessions and secure file transfers are typically what to come to mind. In addition to these common functions, SSH also supports securely executing a command on a remote host and returning the output of that command back to the local system. The SSH component [...]]]></description>
			<content:encoded><![CDATA[<p>When people think of the Secure Shell (SSH) protocol, interactive terminal sessions and secure file transfers are typically what to come to mind. In addition to these common functions, SSH also supports securely executing a command on a remote host and returning the output of that command back to the local system. The SSH component that is included with the SocketTools Secure Editions enables you to take advantage of this functionality through a single method call named Execute.<span id="more-36"></span></p>
<p>For example, in Visual Basic the code could look like this:</p>
<pre>
  SecureShell.HostName = "remote.server.net"
  SecureShell.UserName = "username"
  SecureShell.Password = "password"

  Dim strResult = SecureShell.Execute("/bin/ps -ef")
  If strResult.Length = 0 And SecureShell.LastError > 0 Then
      MessageBox.Show(SecureShell.LastErrorString)
      Exit Sub
  End If

  TextBox1.Text = strResult
</pre>
<p>In this example, the typical property values are set for the SSH server domain name or IP address, the user name and password required to authenticate the session. The Execute method is then called, providing the command to execute as a parameter, and the output from the command will be returned to a string value. In this case, we&#8217;re connecting to a UNIX based system and listing all of the running processes using the /bin/ps command.</p>
<p>If an error occurs, then the return value will be an empty string and the LastError property will be set to a value which identifies the error condition. In this case, we simply display a message box that shows a human-readable description of the last error code and then exit the subroutine.</p>
<p>As with an interactive terminal session, the entire operation is encrypted over the network, including the command that is sent and the output that it returns. For this reason, using SSH is preferred over the old rexec protocol which would send both the user credentials and the command as plain text. If you&#8217;re currently using the Remote Command class in your applications, it&#8217;s recommended that you consider rewriting your code to use the SSH component as a secure alternative.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.catalyst.com/archives/36/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>InternetServer Class For SocketTools .NET</title>
		<link>http://blog.catalyst.com/archives/32</link>
		<comments>http://blog.catalyst.com/archives/32#comments</comments>
		<pubDate>Wed, 18 Feb 2009 17:44:15 +0000</pubDate>
		<dc:creator>Catalyst</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[SocketTips]]></category>
		<category><![CDATA[SocketTools]]></category>

		<guid isPermaLink="false">http://blog.catalyst.com/archives/32</guid>
		<description><![CDATA[The SocketTools 6.0 .NET Edition introduced the new InternetServer class that was designed to simplify the implementation of a TCP/IP server application. With only a few lines of code, you can create the framework for a multi-threaded server that is completely event driven. You only need to create event handlers and then write your server [...]]]></description>
			<content:encoded><![CDATA[<p>The SocketTools 6.0 .NET Edition introduced the new InternetServer class that was designed to simplify the implementation of a TCP/IP server application. With only a few lines of code, you can create the framework for a multi-threaded server that is completely event driven. You only need to create event handlers and then write your server code to respond to those network events.<span id="more-32"></span></p>
<p>Although the class makes developing server applications significantly easier, there are a few important things to keep in mind when using this class:</p>
<p>Although the code that you&#8217;ll write will look like typical single-threaded code that responds to events, it&#8217;s actually a multi-threaded application, with each client session isolated in its own thread. When network events are raised, they are being raised within the context of the thread that&#8217;s generated them. For example, this means that when the OnRead event fires, it&#8217;s not firing within the thread that created that instance of the InternetServer class (e.g.: the main UI thread). Any code that you have inside that event handler is executing in the context of the thread that&#8217;s managing that specific client session.</p>
<p>Because network events are being raised in the context of the client session threads, this means you cannot update user interface controls directly from within the event handlers. .NET does not allow one thread to modify a control that was created in another thread (usually the main UI thread). This is an absolute rule, and if you break it, your program is either going to hang or throw an exception. If you want to change any property values or call methods in a control, you need to create a delegate and marshal the call to the UI thread to using the Invoke method. Both the VB.NET and C# examples show how to do this; in the example, it&#8217;s used to update a ListBox control. Frequently updating the user interface from within an event handler can have a very negative impact on the overall performance of your program. Marshalling calls across threads to those UI controls is an expensive operation, and while you&#8217;re doing it, you&#8217;re not servicing network events like OnRead. You should keep it to a minimum, only updating the UI when absolutely necessary.</p>
<p>Another important consideration is that you should never modify shared objects without first synchronizing access to that object. In VB.NET it&#8217;s typically done using the SyncLock statement; in C# it&#8217;s done using the lock statement. The VB.NET and C# examples show to do this using a shared instance of a Hashtable class which is used to keep track of the number of bytes echoed by the server. While our lower-level API provides thread-safe queuing functions (InetServerEnqueue, InetServerDequeue, etc.) this doesn&#8217;t exist in the .NET class, largely because it would be redundant. If you want to use a queue, then you use the .NET Queue class, but the same rule applies; make sure that you synchronize access to the queue. While the InternetServer class does have Lock and Unlock methods, you should never use it for general purpose synchronization in your program. Calling the Lock method will cause every single client thread to block, and so while using Lock and Unlock would seem to be the easiest approach, it&#8217;s not a good idea for performance reasons.</p>
<p>The InternetServer class provides two general forms of many methods which are used to exchange data with the clients, ones which requires a handle to the client socket, and ones that do not. It&#8217;s not required that you specify a client handle if your code is inside an event handler (or in a function that&#8217;s being called by an event handler); the class knows which client raised the event and calls to Read and Write will work with that client (referred to as the &#8220;current client&#8221; in the documentation). However, if you want to exchange data with a client outside of an event handler, or with a client other than the current client, then you must specify a handle. Also, certain properties only return meaningful results from within an event handler. For example, the ClientAddress property (which returns the IP address of the client) should only be referenced from within an event handler such as OnConnect. The documentation notes when a property or method should only be used inside an event handler.</p>
<p>Finally, while it is possible to exchange data in an event handler with a client other than the one that generated the event, it&#8217;s not recommended. This is a case where you should use the Lock method to ensure that you&#8217;re the only thread that is attempting to read or write on that socket at the time. Two threads that attempt to read or write data on the same socket has undefined results; there&#8217;s no guarantee which thread would &#8220;get there first&#8221;, and the end result can be really unpredictable behavior by your program. One way to think about this is to think of your server program as a house, with each client connection being a room inside that house. You can do pretty much anything you want inside your own room (from within the event handler code that you write). However, if you want to go into another room and start rearranging the furniture, you need to make sure that every other thread is locked out while you do that. When you&#8217;re done and back in your own room, then you unlock the server and continue on.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.catalyst.com/archives/32/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>File Transfer Verification</title>
		<link>http://blog.catalyst.com/archives/31</link>
		<comments>http://blog.catalyst.com/archives/31#comments</comments>
		<pubDate>Thu, 22 Jan 2009 22:19:33 +0000</pubDate>
		<dc:creator>Catalyst</dc:creator>
				<category><![CDATA[SocketTips]]></category>
		<category><![CDATA[SocketTools]]></category>

		<guid isPermaLink="false">http://blog.catalyst.com/archives/31</guid>
		<description><![CDATA[SocketTools 6.0 introduced some new functionality as part of the existing file transfer API and components that enables applications to verify that the contents of a file on the local system are the same as a file on the server. This can be used to either ensure that a file was uploaded correctly, or to [...]]]></description>
			<content:encoded><![CDATA[<p>SocketTools 6.0 introduced some new functionality as part of the existing file transfer API and components that enables applications to verify that the contents of a file on the local system are the same as a file on the server. This can be used to either ensure that a file was uploaded correctly, or to check whether or not a file should be downloaded. For example, an application could check to see if the contents of a local file were the same as a remote file the user has requested to download, and if they match, the application knows it&#8217;s not necessary to download the file again.<span id="more-31"></span></p>
<p>The file verification is performed using one of several methods, depending on what features the server supports. There are three general options available when performing file verifications using FTP: an MD5 hash, a CRC-32 checksum or a file size comparison. If the server supports the XMD5 command, then this is used to generate an MD5 hash and compare it against the local file; if the hash value matches, then the contents of the file are identical. If the server doesn&#8217;t support this feature, a CRC-32 checksum can be generated in a similar fashion using the XCRC command to determine if the file contents are the same. If the FTP server doesn&#8217;t support either MD5 or CRC-32, then a simple file size comparison can be performed.</p>
<p>By default, SocketTools will give preference to the MD5 hash, falling back to a CRC-32 checksum. If neither feature is supported by the server, then it will compare file sizes. Naturally, a file size comparison is the least reliable, so developers can specify if they only wish to use the MD5 and/or CRC-32 methods to determine if the file contents match.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.catalyst.com/archives/31/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Managing Message Stores</title>
		<link>http://blog.catalyst.com/archives/30</link>
		<comments>http://blog.catalyst.com/archives/30#comments</comments>
		<pubDate>Mon, 03 Nov 2008 18:16:33 +0000</pubDate>
		<dc:creator>Catalyst</dc:creator>
				<category><![CDATA[SocketTips]]></category>
		<category><![CDATA[SocketTools]]></category>

		<guid isPermaLink="false">http://blog.catalyst.com/archives/30</guid>
		<description><![CDATA[One of the new features in SocketTools 6.0 is the Message Store API which is designed to make it simple to store and manage email messages on the local system. For developers who use the POP3, IMAP4 and NNTP components to retrieve messages, the storage API enables those messages to be easily stored in a [...]]]></description>
			<content:encoded><![CDATA[<p>One of the new features in SocketTools 6.0 is the Message Store API which is designed to make it simple to store and manage email messages on the local system. For developers who use the POP3, IMAP4 and NNTP components to retrieve messages, the storage API enables those messages to be easily stored in a single file, rather than storing them individually in separate text files. The actual message store format is similar to the standard UNIX mbox format, and the API can actually be used to open mailboxes that were created on a UNIX or Linux system.<span id="more-30"></span></p>
<p>Using the storage API is very simple, with methods that create or open an existing storage file, store new messages, retrieve old messages and search for specific messages. For example, you can search the message store for all emails that have a certain subject or were sent by a particular individual. The API itself is independent of the various email protocol components, and can be interfaced with any of them to provide local storage capability for the email messages that you&#8217;re processing.</p>
<p>The SocketTools Library Edition includes the message store API as part of the MIME API, with new functions such as MimeOpenMessageStore and MimeFindStoredMessage. The SocketTools Visual Edition includes the new functionality as part of the current MailMessage control, while the SocketTools .NET Edition includes it as part of the SocketTools.MailMessage assembly.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.catalyst.com/archives/30/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Prioritizing File Transfers</title>
		<link>http://blog.catalyst.com/archives/17</link>
		<comments>http://blog.catalyst.com/archives/17#comments</comments>
		<pubDate>Wed, 18 Jul 2007 23:12:34 +0000</pubDate>
		<dc:creator>Catalyst</dc:creator>
				<category><![CDATA[SocketTips]]></category>
		<category><![CDATA[SocketTools]]></category>

		<guid isPermaLink="false">http://blog.catalyst.com/archives/17</guid>
		<description><![CDATA[One typical requirement for many applications today is the ability to transfer files between the local system and a remote server, and the File Transfer Protocol (FTP) and Hyptertext Transfer Protocol (HTTP) are the two most commonly used Internet protocols for this purpose. SocketTools has components that support both of these protocols, making it a [...]]]></description>
			<content:encoded><![CDATA[<p>One typical requirement for many applications today is the ability to transfer files between the local system and a remote server, and the File Transfer Protocol (FTP) and Hyptertext Transfer Protocol (HTTP) are the two most commonly used Internet protocols for this purpose. SocketTools has components that support both of these protocols, making it a simple task to integrate this functionality into your own software.<br />
<span id="more-17"></span></p>
<p>Not all applications have the same needs when it comes to the resource and bandwidth utilization on the local system. In some cases, developers want the data transferred as quickly as possible, regardless of how much network bandwidth they consume. Other programs are designed to run in the background or as a service and need to use very little bandwidth and system resources.</p>
<p>One of the new features in SocketTools 5.0 is the ability to specify transfer priorities. This determines how system resources and network bandwidth should be allocated for the transfer. For the libraries, the transfer priority is set by calling the <a title="FtpSetPriority" href="http://www.catalyst.com/support/help/sockettools/library/html/ftp/library/ftpsetpriority.html" target="_blank">FtpSetPriority</a> or <a title="HttpSetPriority" href="http://www.catalyst.com/support/help/sockettools/library/html/http/library/httpsetpriority.html" target="_blank">HttpSetPriority</a> functions. For the .NET classes and ActiveX controls, you can set the Priority property. There are five priority levels which control the transfer rate:</p>
<blockquote><p><strong>Normal Priority</strong><br />
This is the default priority, and is designed to provide a balance between the file transfer rate and the system resources allocated for the transfer. In most cases, this is the appropriate priority for an interactive user application. At this priority, the transfer won&#8217;t interfere with other applications running on the system, either in terms of CPU utilization or network bandwidth.</p>
<p><strong>Background Priority</strong><br />
This priority specifies that the transfer is taking place in the background and should be given a very low priority. At this priority level the CPU utilization is minimal and very little network bandwidth is consumed. The trade-off is that the transfer will take much longer to complete. This priority should be used if low resource utilization is required, and the amount of time to complete the transfer is not important. This priority is not recommended for interactive applications where the user must wait for the transfer to complete.</p>
<p><strong>Low Priority</strong><br />
This priority specifies that the transfer should use less memory and reduce the network bandwidth utilization. It is not as restrictive as a background priority transfer, and is generally recommended for applications that are performing multiple, simultaneous transfers. This will minimize the impact on other applications that are running on the system.</p>
<p><strong>High Priority</strong><br />
This priority specifies that additional system resources should be allocated for the transfer, and there should be no limitations on network bandwidth utilization. High priority transfers typically require more memory, have increased CPU utilization and consume more network bandwidth. Interactive programs that require the transfer to complete quickly can use this priority to increase the overall transfer rate.</p>
<p><strong>Critical Priority</strong><br />
This priority specifies that the transfer must complete as quickly as possible, without regard for system resource allocation or network bandwidth. With critical priority transfers, no events are generated and Windows messages will not be processed. It is important to note that if you specify this priority level in the main UI thread of an application, it can effectively cause the program to appear to be non-responsive to the user. Use of this priority can also negatively impact the performance of other applications running on the system, both in terms of CPU utilization and the amount of network bandwidth that is consumed during the transfer.</p></blockquote>
<p>The ability to specify a priority gives your application additional flexibility and control over the transfer process. For more information about setting transfer priorities, you can refer to the technical reference documentation that is included with your copy of SocketTools.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.catalyst.com/archives/17/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SocketTools and PowerShell</title>
		<link>http://blog.catalyst.com/archives/16</link>
		<comments>http://blog.catalyst.com/archives/16#comments</comments>
		<pubDate>Thu, 14 Jun 2007 22:59:21 +0000</pubDate>
		<dc:creator>Catalyst</dc:creator>
				<category><![CDATA[SocketTips]]></category>
		<category><![CDATA[SocketTools]]></category>

		<guid isPermaLink="false">http://blog.catalyst.com/archives/16</guid>
		<description><![CDATA[PowerShell is Microsoft&#8217;s new command line shell and scripting development environment for the Windows platforms. It primarily serves as both a replacement for the classic command line (cmd.exe) and as an administrative tool that integrates much of the functionality that was previously found in other tools like Windows Scripting Host (WSH) and the Network Shell [...]]]></description>
			<content:encoded><![CDATA[<p>PowerShell is Microsoft&#8217;s new command line shell and scripting development environment for the Windows platforms. It primarily serves as both a replacement for the classic command line (cmd.exe) and as an administrative tool that integrates much of the functionality that was previously found in other tools like Windows Scripting Host (WSH) and the Network Shell (netsh). PowerShell was released in November 2006, and is available as a <a href="http://www.microsoft.com/windowsserver2003/technologies/management/powershell/download.mspx" target="_blank">free download</a> for Windows XP, Windows Server 2003 and Windows Vista. Microsoft has announced that it will also be included as part of Windows Server 2008. In this article, we&#8217;ll talk about how you can use SocketToolsÂ withÂ PowerShell.<br />
<span id="more-16"></span></p>
<p>The PowerShell scripting language is similar to C# and provides many of the typical statements in a scripting language (conditional statements, looping control, switch statements and so on) as well as support for regular expressions, array slicing and hash tables. It also supports scoping, allowing you to declare variables to be global or local scope. In addition to many of its features, PowerShell can also make use of .NET assemblies, enabling you to take advantage of the expansive .NET Framework in your own scripts. This opens a lot of possibilities, both for the typical administrative tasks one could perform, but also allows developers to use PowerShell as a test-harness and prototyping tool for their own projects.</p>
<p>With the SocketTools .NET Edition, you can create scripts using the same classes that you use when building your applications. If you are already familiar with SocketTools, then there is virtually no learning curve aside from some minor syntactical differences. Note that even if you&#8217;re not familiar with C#, you&#8217;ll find the PowerShell scripting language easy to work with. A great book to help you get started is &#8220;<a href="http://www.amazon.com/Windows-PowerShell-Action-Bruce-Payette/dp/1932394907" target="_blank">Windows PowerShell In Action</a>&#8221; by Bruce Payette, and something that every aspiring PowerShell user should have on their bookshelf.</p>
<p><strong>Getting Started</strong><br />
To demonstrate how to use SocketTools with PowerShell, the first step is to install PowerShell and the <a href="http://www.catalyst.com/products/sockettools/standard/dotnet/index.html" target="_blank">SocketTools .NET Edition</a> on your local system. If you don&#8217;t already have a copy of the SocketTools .NET Edition, you can download and install it with a free evaluation license. Once you have everything installed, fire up your copy of PowerShell.</p>
<p>To use one of the SocketTools assemblies, you need to load it. This can be done using the LoadFile method in the System.Reflection.Assembly class. Simply pass the full file name of the assembly as its argument. The SocketTools assemblies are found in the following folder:</p>
<blockquote><p><tt>C:\Program Files\Common Files\Catalyst Shared\Assemblies\v5.0\v2.0.50727</tt></p></blockquote>
<p>So let&#8217;s say that you want to use the FTP class to download a file to the local system. You would enter the following (note thatÂ PS> is the PowerShell prompt and should not be entered):</p>
<p><tt>PS> <strong>[System.Reflection.Assembly]::LoadFile("C:\Program Files\Common Files\Catalyst Shared\Assemblies\v5.0\v2.0.50727\SocketTools.FtpClient.dll")</strong></tt></p>
<p>If you&#8217;ve entered the path correctly, you&#8217;ll get a message that shows the version and location of the assembly that&#8217;s been loaded. The next step is to create an instance of the <a href="http://www.catalyst.com/support/help/sockettools/dotnet/html/dotnet/htmlhelp/sockettools.ftpclient.html" target="_blank">SocketTools.FtpClient</a> class:</p>
<p><tt>PS> <strong>$FtpClient = New-Object SocketTools.FtpClient</strong></tt></p>
<p><strong>Using the SocketTools Class</strong><br />
The $FtpClient variable now references an instance of the SocketTools.FtpClient class. With that done, you now have access to all of the various properties and methods. To see a list of the current property values, you can simply enter:</p>
<p><tt>PS> <strong>$FtpClient</strong></tt></p>
<p>To download a file, you can use the GetFile method. For example, you could enter:</p>
<p><tt>PS> <strong>$FtpClient.GetFile("c:\rfc959.txt", "ftp://ftp.ietf.org/rfc/rfc959.txt;type=a")</strong></tt></p>
<p>The first argument is the name of the file on the local system, and the second argument is the FTP URL that specifies the remote location of the file (the &#8220;type a&#8221; at the end is part of the FTP URL syntax that specifies the file is an ASCII text file).</p>
<p>An important point to keep in mind is that whenever you specify a path to a method in a .NET class (whether in SocketTools or some other class) you should always specify a full path. This is important because PowerShell keeps track of its current working directory independently of what the assembly considers to be the current working directory. To avoid any possible confusion, it&#8217;s always best to be explicit, otherwise you can get some unexpected results.</p>
<p>You&#8217;ve downloaded a file and stored it on the local system, but what if you want to manipulate the contents of the file in memory, instead of writing it to disk? Instead of using the GetFile method, use the GetData method instead. It accepts two arguments, the URL of the file that you want to download, and a buffer to store the contents of the file in. To do this, first we need to create a string variable that will contain the file data when the method returns:</p>
<p><tt>PS> <strong>$buffer = ""</strong></tt></p>
<p>This is important because the second argument to the GetData method must be passed by reference. To do this, the variable must already exist and the [ref] attribute must be specified for the parameter. Here&#8217;s an example:</p>
<p><tt>PS> <strong>$FtpClient.GetData("ftp://ftp.ietf.org/rfc/rfc959.txt;type=a", [ref] $buffer)</strong></tt></p>
<p>When the GetData method returns, the $buffer variable will contain the contents of the file and you can manipulate it as you would any string type.</p>
<p><strong>More Information</strong><br />
Hopefully will give you an idea of how you can use SocketTools with PowerShell as a means to accomplish administrative tasks, as well as help you with your development projects. Here&#8217;s some more links to help you get started:</p>
<ul>
<li><a href="http://www.microsoft.com/windowsserver2003/technologies/management/powershell/download.mspx" target="_blank">Windows PowerShell Download</a></li>
<li><a href="http://www.microsoft.com/downloads/details.aspx?familyid=df8ed469-9007-401c-85e7-46649a32d0e0&#038;displaylang=en&#038;tm" target="_blank">Windows PowerShell Quick Reference</a></li>
<li><a href="http://msdn2.microsoft.com/en-us/library/ms714674.aspx" target="_blank">Windows PowerShell Programmer&#8217;s Guide</a></li>
<li><a href="http://channel9.msdn.com/wiki/default.aspx/Channel9.WindowsPowerShellQuickStart" target="_blank">PowerShell Quick Start</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.catalyst.com/archives/16/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SocketTips Revisited</title>
		<link>http://blog.catalyst.com/archives/15</link>
		<comments>http://blog.catalyst.com/archives/15#comments</comments>
		<pubDate>Wed, 30 May 2007 01:05:08 +0000</pubDate>
		<dc:creator>Catalyst</dc:creator>
				<category><![CDATA[SocketTips]]></category>

		<guid isPermaLink="false">http://blog.catalyst.com/archives/15</guid>
		<description><![CDATA[A number of years ago, we published a newsletter called SocketTips which provided general programming tips, how-toâ€™s and code snippets to help developers make the most of SocketTools in their applications. Weâ€™re going to pick up where we left off, and start with covering some of the new features and functionality that was introduced in [...]]]></description>
			<content:encoded><![CDATA[<p>A number of years ago, we published a newsletter called SocketTips which provided general programming tips, how-toâ€™s and code snippets to help developers make the most of SocketTools in their applications. Weâ€™re going to pick up where we left off, and start with covering some of the new features and functionality that was introduced in SocketTools 5.0. Each of these articles will be categorized as SocketTips, so theyâ€™ll be easy to search and reference in the future. If anyone has any ideas about articles they would like to see written, please let us know. For the first tip, weâ€™ll talk about how to simplify your code using URLs with the FTP and HTTP components.<br />
<span id="more-15"></span></p>
<p><strong>Coding Shortcuts Using URLs</strong><br />
For those of you using the SocketTools .NET Edition or Visual Edition, the typical sequence of method calls requires that you establish a connection using the Connect method, then perform the action that you want to take (for example, calling the GetFile method to download a file) and then terminating the connection by calling the Disconnect method.</p>
<p>For the File Transfer and Hypertext Transfer components, weâ€™ve added the ability to use URLs without requiring that you explicitly establish a connection to the server first. New code can be written to take advantage of this feature, but existing code will continue to work as it always has.</p>
<p><strong>Visual Basic Example</strong><br />
For example, hereâ€™s some Visual Basic code (using a Visual Edition component) that connects to our web server and downloads the index file, storing it on the local system:</p>
<p><tt>Dim strHostName As String = "www.catalyst.com"<br />
Dim strRemoteFile As String = "/index.html"<br />
Dim strLocalFile As String = "c:\index.html"<br />
Dim nError As Integer</tt></p>
<p><tt>nError = HttpClient1.Connect(strHostName, 80)<br />
If nError = 0 Then<br />
Â Â Â Â nError = HttpClient1.GetFile(strLocalFile, strRemoteFile)<br />
End If</tt></p>
<p><tt>If nError > 0 Then<br />
Â Â Â Â MsgBox(HttpClient1.LastErrorString, MsgBoxStyle.Exclamation)<br />
Â Â Â Â Exit Sub<br />
End If</tt></p>
<p><tt>HttpClient1.Disconnect()</tt></p>
<p>With SocketTools 5.0, that code can be reduced to the following:</p>
<p><tt>Dim strLocalFile As String = "c:\index.html"<br />
Dim strRemoteFile As String = "http://www.catalyst.com/index.html"<br />
Dim nError As Integer</tt></p>
<p><tt>nError = HttpClient1.GetFile(strLocalFile, strRemoteFile)<br />
If nError > 0 Then<br />
Â Â Â Â MsgBox(HttpClient1.LastErrorString, MsgBoxStyle.Exclamation)<br />
Â Â Â Â Exit Sub<br />
End If</tt></p>
<p>By providing a complete URL as the remote file that you want to download, you can omit the explicit calls to the Connect and Disconnect methods, and have the component automatically manage the connection for you. This applies to the GetFile and PutFile methods, as well as methods such as GetData, PutData, PostData and so on. This also applies to the same methods that are available in the SocketTools .NET Edition.</p>
<p><strong>C/C++Â Example</strong><br />
For developers who are using the SocketTools Library Edition, thereâ€™s some shortcuts available to you as well. The FtpDownloadFile, FtpUploadFile, HttpDownloadFile and HttpUploadFile functions are high-level â€œwrapper functionsâ€ around the API that enable you to upload and download files in a single function call. For example:</p>
<p><tt>LPCTSTR lpszLocalFile = _T("c:\\index.html");<br />
LPCTSTR lpszRemoteFile = _T("http://www.catalyst.com/index.html");<br />
BOOL bResult;</tt></p>
<p><tt>bResult = HttpDownloadFile(lpszLocalFile,<br />
Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â  lpszRemoteFile,<br />
Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â  Â Â Â HTTP_TIMEOUT,<br />
Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â  Â Â Â Â HTTP_OPTION_DEFAULT,<br />
Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â  Â Â Â Â NULL, NULL, 0);</tt></p>
<p><tt>if (bResult == FALSE)<br />
{<br />
Â Â Â Â DWORD dwError = HttpGetLastError();<br />
Â Â Â Â _tcprintf(_T("Unable to download file, error %08lX\n"), dwError);<br />
}</tt></p>
<p>There still are some cases where you want to explicitly connect to the server. If youâ€™re going to perform multiple file transfers, itâ€™s more efficient to call the Connect method, call GetFile or PutFIle for each file, and then Disconnect. When you use URLs, then a connection will be established for each file thatâ€™s being transferred. By explicitly connecting to the server, you have more direct control over the â€œlifetimeâ€ of the client session. However, for single operations (downloading one file at a time, or posting data to a script on a web server) the ability to use URLs can simplify and reduce the amount of code that you need to write.</p>
<p>Â </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.catalyst.com/archives/15/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

