Tuesday, October 18, 2011

Tuesday 10/18/11

protected void gvwCustomers_SelectedIndexChanged(object sender, EventArgs e)
{
StringBuilder info = new StringBuilder();
info.AppendFormat("You are viewing record {0} of {1} (SelectedIndex)
", gvwCustomers.SelectedIndex.ToString(), gvwCustomers.Rows.Count.ToString());
info.AppendFormat("You are viewing record {0} of {1} (DataKeys)
", gvwCustomers.SelectedIndex.ToString(), gvwCustomers.DataKeys.Count);
info.AppendFormat("You are viewing page {0} of {1} (PageCount)
", gvwCustomers.PageIndex.ToString(), gvwCustomers.PageCount.ToString());

info.AppendFormat("

Using SelectedRow, Email Address= {0}
", gvwCustomers.SelectedRow.Cells[4].Text);

info.Append("Using SelectedDataKey
");

for (int i = 0; i < gvwCustomers.DataKeyNames.Length; i++)
{
info.AppendFormat("{0} : {1}
", gvwCustomers.DataKeyNames[i], gvwCustomers.SelectedDataKey.Values[i]);
}
info.AppendFormat("Selected Value: {0}", gvwCustomers.SelectedValue.ToString());

lblInfo.Text = info.ToString();
}



Imports System
Imports System.Data
Imports System.Threading
Imports System.Data.SqlClient

Namespace Apress.VisualBasicRecipes.Chapter08
Public Class Recipe08_09
'a method to handle asynchronous completion using callbacks
Public Shared Sub CallBackHandler(ByVal result As IAsyncResult)
'obtain a reference to the SqlCommand used to initiate the asynchronous operation
Using cmd As SqlCommand = TryCast(result.AsyncState, SqlCommand)
'obtain the result of the stored procedure.
Using reader As SqlDataReader = cmd.EndExecuteReader(result)
'display the results of the stored procedure to the console.
'to ensure the program is thread safe, SyncLock is used to stop
'more than one thread from accessing the console at the same time.
SyncLock Console.Out
Console.WriteLine("Bill of Materials:")
Console.WriteLine("ID \t DESCRIPTION \t QUANTITY \t LISTPRICE")
While reader.Read
'display the record details
Console.WriteLine("{0} {1} {2} {3}", reader("ComponentID"), reader("ComponentDesc"), reader("TotalQuantity"), reader("ListPrice"))
End While
End SyncLock
End Using
End Using

End Sub

Public Shared Sub Main()
'create a new SqlConnection object
Using con As New SqlConnection
'configure teh SqlConnection object's connection string
'you must specify Asynchronous Processing=True to support
'asynchronous operations over the connection
con.ConnectionString = "Data Source=Alfred-PC\SQLExpress; Database=AdventureWorks; Integrated Security=SSPI;Asynchronous Processing=True;"
'create and configure a new command to run a stored procedure
Using cmd As SqlCommand = con.CreateCommand

cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "uspGetBillOfMaterials"

'create the required SqlParameter objects
cmd.Parameters.Add("@StartProductID", SqlDbType.Int).Value = 771
cmd.Parameters.Add("@CheckDate", SqlDbType.DateTime).Value = DateTime.Parse("07/10/2000")

'open the database connection and execute the command
'asynchronously. Pass the reference to the SqlCommand used to initiate the asynchronous operation
con.Open()
cmd.BeginExecuteReader(AddressOf CallBackHandler, cmd)
End Using
'continue with other processing
For count As Integer = 1 To 10
SyncLock Console.Out
Console.WriteLine("{0} : Continue processing...", DateTime.Now.ToString("HH:mm:ss.ffff"))
End SyncLock
Thread.Sleep(500)
Next

'close the database connection
con.Close()

End Using

End Sub
End Class

End Namespace


Imports System
Imports System.Net.NetworkInformation

Namespace Apress.VisualBasicRecipes.Chapter11
Public Class Recipe11_01

Public Shared Sub Main()

'only proceed if there is a network available
If NetworkInterface.GetIsNetworkAvailable Then
'get the set of all NetworkInterface objects for the local machine
Dim interfaces As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces
'iterate through the interfaces and display information
For Each ni As NetworkInterface In interfaces
'report basic interface information
Console.WriteLine("Interface Name: {0}", ni.Name)
Console.WriteLine("Description: {0}", ni.Description)
Console.WriteLine("ID: {0}", ni.Id)
Console.WriteLine("Type: {0}", ni.NetworkInterfaceType)
Console.WriteLine("Speed: {0}", ni.Speed)
Console.WriteLine("Status: {0}", ni.OperationalStatus)

'report physical address
Console.WriteLine("Physical Address: {0}", ni.GetPhysicalAddress().ToString)

'report network statistics for the interface
Console.WriteLine("Bytes Sent: {0}", ni.GetIPv4Statistics().BytesSent)
Console.WriteLine("Bytes Received: {0}", ni.GetIPv4Statistics.BytesReceived)

'report IP configuration
Console.WriteLine("IP Addresses:")
For Each addr As UnicastIPAddressInformation In ni.GetIPProperties.UnicastAddresses
Console.WriteLine(" - {0} (lease expires {1})", addr.Address, DateTime.Now.AddSeconds(addr.DhcpLeaseLifetime))
Next
Console.WriteLine(Environment.NewLine)
Next
Else
Console.WriteLine("No network available")
End If
End Sub
End Class
End Namespace


Imports System
Imports System.IO
Imports System.Net
Imports System.Text.RegularExpressions

Namespace Apress.VisualBasicRecipes.Chapter11
Public Class Recipe11_03

Public Shared Sub Main()


'specify the URI of the resource to parse
Dim remoteUri As String = "http://www.msdn.com"

'create a webclient to perform the download
Dim client As New WebClient

Console.WriteLine("Downloading {0}", remoteUri)

'perform the donload getting the resource as a string
Dim str As String = client.DownloadString(remoteUri)

'use a regular expression to extract all fully qualified URIs that refer to GIF files
Dim matches As MatchCollection = Regex.Matches(str, "http\S+[^-,;:?]\.gif")

'try to download each referenced GIF file
For Each expMatch As Match In matches
For Each grp As Group In expMatch.Groups
'determine the local filename
Dim downloadedFile As String = grp.Value.Substring(grp.Value.LastIndexOf("/") + 1)
Try
'download and store the file
Console.WriteLine("Donlowading {0} to file {1}", grp.Value, downloadedFile)
client.DownloadFile(New Uri(grp.Value), downloadedFile)
Catch ex As Exception
Console.WriteLine("Failed to download {0}", grp.Value)
End Try
Next
Next

End Sub

End Class
End Namespace


Imports System
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Threading

Namespace Apress.VisualBasicRecipes.Chapter11
Public Class Recipe11_05

'configure the maximum number of requests that can be handled concurrently
Private Shared maxRequestHandlers As Integer = 5

'an integer used to assign each HTTP request handler a unique identifier
Private Shared requestHandlerID As Integer = 0

'the HttpListener is the class that provides all the capabilities to receive and process HTTP requests
Private Shared listener As HttpListener

Public Shared Sub Main()
'quit gracefully if this feature is not supported
If Not HttpListener.IsSupported Then
Console.WriteLine("You must be running this example on Windows XP SP2, Windows Server 2003, or higher to create an HttpListener.")
Exit Sub
End If

'create the HttpListener
listener = New HttpListener
'configure the URI prefixes that will map to the HttpListener
listener.Prefixes.Add("http://localhost:19080/VisualBasicRecipes/")
listener.Prefixes.Add("http://localhost:20000/Recipe11-05/")

'Start the HttpListener before listening for incoming requests.
Console.WriteLine("Starting HTTP Server")
listener.Start()
Console.WriteLine("HTTP Server started")
Console.WriteLine(Environment.NewLine)

'create a number of asynchronous request handlers up to the configurable maximum
'give each a unique identifier
For count As Integer = 1 To maxRequestHandlers
listener.BeginGetContext(AddressOf RequestHandler, "RequestHandler_" & Interlocked.Increment(requestHandlerID))
Next

'wait for the user to stop the HttpListener
Console.WriteLine("Press Enter to stop the HTTP Server.")
Console.ReadLine()

'stop accepting new requests
listener.Stop()

'Terminate the HttpListener without procesing current requests
listener.Abort()
End Sub

'a method to asynchronously process individual requests and send responses
Private Shared Sub RequestHandler(ByVal result As IAsyncResult)
Console.WriteLine("{0}: Activated.", result.AsyncState)
Try
'obtain the HttpListenerContext for the new request
Dim context As HttpListenerContext = listener.EndGetContext(result)

Console.WriteLine("{0}: Processing HTTP Request from {1} ({2}).", result.AsyncState, context.Request.UserHostName, context.Request.RemoteEndPoint)

'Build the response using a StreamWriter feeding the Response.OutputStream
Dim sw As New StreamWriter(context.Response.OutputStream, Encoding.UTF8)
sw.WriteLine("")
sw.WriteLine("")
sw.WriteLine("title>Visual Basic Recipes")
sw.WriteLine("")
sw.WriteLine("")
sw.WriteLine("Recipe 11-05: " & result.AsyncState)
sw.WriteLine("")
sw.WriteLine("")
sw.Flush()

'configure th response
context.Response.ContentType = "text/html"
context.Response.ContentEncoding = Encoding.UTF8

'close the response to send it to the client
context.Response.Close()

Console.WriteLine("{0}: Sent HTTP response.", result.AsyncState)

Catch ex As ObjectDisposedException
Console.WriteLine("{0}: HttpListener disposed--shutting down.", result.AsyncState)
Finally
'start another handler unless the HttpListener is closing.
If listener.IsListening Then
Console.WriteLine("{0}: Creating new request handler.", result.AsyncState)
listener.BeginGetContext(AddressOf RequestHandler, "RequestHandler_" & Interlocked.Increment(requestHandlerID))
End If

End Try
End Sub
End Class
End Namespace

No comments: