Login    
 
 
 
 
Text/HTML
  
You are here :: Blogs Saturday, May 19, 2012

Search
Note: This uses the internal blog search engine. The Google search engine is also available at the top of the page.
  
Disclaimer

Please review the site disclaimer before downloading or using content found on this site

  
Categories
  
DEVSHED Blog
As always, I welcome your comments!
Author: Steve Gray Created: 4/12/2009 1:46 PM RssIcon
Tricks and Tips on VB.NET
By Steve Gray on 5/26/2011 12:44 PM

When you create a web site in ASP.NET the form tag is included for you. This issue is magnified if you use master pages (who doesn’t?).

The issue is that the code that you get from PayPal has a <form> tag in it, and you can’t nest form tags. So your code doesn’t post correctly when the user clicks ‘Buy Now’.

Here’s a real easy way around that. There are two ways you can do this, as a link from the <HTML> code, or as a Response.Redirect from the code behind. The link will be less work, but also less flexible.

From the HTML, code something like this:

  1. <a href="https://www.paypal.com/cgi-bin/webscr
  2.   ?cmd=_xclick&business=YOUR-PAYPAL-EMAIL-HERE
  3.   &item_name=Widget
  4.   &amount=29.00
  5.   &undefined_quantity=1
  6.   &currency_code=USD">
  7. <img src="http://www.paypal.com/en_US/i/btn/x-click-but23.gif"
  8.   border="0" alt="Buy Now Using PayPal" />
  9. </a>

If you’ll compare the above to the code that you got from PayPal, you’ll see that we converted the <input> tags to be parameters in the query string.

From the code behind it looks like this:

  1. Protected Sub btnSubscribeYear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubscribeYear.Click
  2.     Dim dblAmount As Double
  3.     dblAmount = Me.txtAmount.text
  4.  
  5.     https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&amount=" & dblAmount & "&hosted_button_id=3IMNOTREAL3E3
  6. End Sub

 

Here’s a list of all the arguments (not guaranteed to be complete or correct, you’ll want to check with PayPal for complete information)

Argument                Description
business                Email address associated with seller's PayPal account
quantity                Quantity of items being sold
undefined_quantity      Allows user to edit quantity
item_name               Name of item
item_number             Optional item number
amount                  Price of each item (without currency symbol)
undefined_amount        Allows user to edit the amount (good for donations)
shipping                Price of shipping
currency_code           Code for type of currency (Default appears to be USD)
first_name              Customer's first name
last_name               Customer's last name
address1                Customer's first address line
address2                Customer's second address line
city                    Customer's city
state                   Customer's state
zip                     Customer's zip code
email                   Customer's email address
night_phone_a           Customers telephone area code
night_phone_b           Customers telephone prefix
night_phone_c           Remainder of customer's telephone number

By Steve Gray on 5/24/2011 1:42 PM

This piece of code will show how to serialize a DataTable to a string, where it can be saved to disk, and then how to read that string back into a DataTable again. Actually, we’ll have to use a DataSet to read the string (in XML format) back in, if you use a DataTable you’ll get:

DataTable does not support schema inference from Xml

Oddly, the DataSet works just fine

There are code comments for each line below, you should not have any trouble with it.

  1. Imports System.IO
  2. Imports System.Xml
  3.  
  4. Module Module1
  5.  
  6.     Sub Main()
  7.         'declare a datatable and populate it with data. Here, we call a
  8.         'subroutine that loads invoices from a text file.
  9.         Dim oDT As DataTable = getAPInvoices("Data.txt")
  10.  
  11.         'declare a stringWriter and an XmlTextWriter
  12.         Dim sw As New StringWriter
  13.         Dim tw As New XmlTextWriter(sw)
  14.         'give the table a name. This name will become the name of each row in the XML file
  15.         oDT.TableName = "invoice"
  16.  
  17.         'make the XML pretty
  18.         tw.Formatting = Formatting.Indented
  19.  
  20.         'write to the XmlTextWriter/StringWriter
  21.         oDT.WriteXml(tw)
  22.  
  23.         'view the results
  24.         MsgBox(sw.ToString)
  25.  
  26.         'declare a new DataSet. Note that we're not using a DataTable... you'll get
  27.         'an error if you do:
  28.         'DataTable does not support schema inference from Xml
  29.         Dim oDSNew As New DataSet
  30.  
  31.         'declare a StringReader, populate it with our XML String
  32.         Dim sr As New StringReader(sw.ToString)
  33.  
  34.         'read in the XML into our DataSet
  35.         oDSNew.ReadXml(sr)
  36.  
  37.         'loop through it to prove it worked.
  38.         For Each oRow As DataRow In oDSNew.Tables(0).Rows
  39.             Console.WriteLine(oRow("vchnumwk"))
  40.         Next
  41.     End Sub
By Steve Gray on 5/23/2011 12:43 PM

This piece of code shows how to embed an image into an email using the System.Net.Mail namespace

  1. Try
  2.     Dim strServer As String = strMailServer
  3.  
  4.     Dim mail As New System.Net.Mail.MailMessage(strFrom, strTo)
  5.  
  6.     For Each cc In strCC.Split(";")
  7.         If cc > "" Then
  8.             mail.CC.Add(cc)
  9.         End If
  10.     Next
  11.  
  12.     For Each bcc As String In strBCC.Split(";")
  13.         If bcc > "" Then
  14.             mail.Bcc.Add(bcc)
  15.         End If
  16.     Next
  17.  
  18.     Dim htmlView As Net.Mail.AlternateView = Net.Mail.AlternateView.CreateAlternateViewFromString("Here is the image... <img src=cid:myImage>", Nothing, "text/html")
  19.  
  20.     Dim oImage As New Net.Mail.LinkedResource(strFilename)
  21.     oImage.ContentId = "myImage"
  22.     htmlView.LinkedResources.Add(oImage)
  23.  
  24.     mail.Subject = strSubject
  25.     mail.Body = strBody
  26.     mail.Priority = intPriority
  27.     mail.AlternateViews.Add(htmlView)
  28.  
  29.     Dim serv As New System.Net.Mail.SmtpClient(strServer)
  30.  
  31.     serv.Send(mail)
  32.  
  33. Catch ex As Exception
  34.     Throw New Exception(ex.Message)
  35. End Try
By Steve Gray on 3/22/2011 5:55 PM

Recently I needed to concatenate two strings and form a URI. I had the base stored in the site config; then we needed to add the page onto that. I wanted to be sure that I didn’t have errors if the user added or didn’t add ‘/’ to the URI in the config so I started with Path.combine. <smiles> That worked (sort of) but it used the wrong ‘/’ and it generated an error.

Enter URI.TriCreate. According to the documentation this would do the trick. But the documentation didn’t have any examples; and I couldn’t figure out the syntax. How bad is the documentation if you read all the way through it and still don’t have a clue?

At any rate, I searched on line for a while and put it all together. Here are code sample for the three overloads.

A few definitions so that you don’t have the same issues that I did:

  • URI: Uniform Resource Identifier. A string of characters used to identify a name or a resource on the Internet.
  • UriKind: URIs can be Absolute or Relative. “www.devshed.us” is Absolute. “/links.aspx” is relative.

 

 

Code Snippet
  1. Module Module1
  2.  
  3.     Sub Main()
  4.         TryCreate1()
  5.         TryCreate2()
  6.         TryCreate3()
  7.     End Sub
  8.  
  9.     Sub TryCreate1()
  10.         'demonstrates Uri.TriCreate(Uri,String,Uri)
  11.         Dim UriIn As Uri = New Uri("http://devshed.us/")
  12.         Dim strPage As String = "/links.aspx"
  13.         Dim UriOut As Uri = Nothing
  14.  
  15.         If Uri.TryCreate(UriIn, strPage, UriOut) Then
  16.             Debug.Print(UriOut.ToString)
  17.         Else
  18.             Throw New Exception("Invalid URI")
  19.         End If
  20.     End Sub
  21.     Sub TryCreate2()
  22.         'demonstrates Uri.TriCreate(String,Urikind, Uri)
  23.         'this form doesn't create anything. It just tells us if the URI that we're passing
  24.         'in the first parameter is Relative or Absolute. Or valid at in any form
  25.  
  26.         'test to see if this string is a valid URI
  27.         Dim strUrl As String = "http://devshed.us/"
  28.  
  29.         'placeholder for our output
  30.         Dim UriOut As Uri = Nothing
  31.  
  32.         'see if our input qualifies as an Absolute URI
  33.         If Uri.TryCreate(strUrl, UriKind.Absolute, UriOut) Then
  34.             'yes
  35.             Debug.Print(UriOut.ToString & " is absolute")
  36.         Else
  37.             'no
  38.             Debug.Print(strUrl & " is not absolute")
  39.         End If
  40.  
  41.         'see if our input qualifies as a Relative URI
  42.         If Uri.TryCreate(strUrl, UriKind.Relative, UriOut) Then
  43.             'yes
  44.             Debug.Print(UriOut.ToString & " is Relative")
  45.         Else
  46.             'no
  47.             Debug.Print(strUrl & " is not Relative")
  48.         End If
  49.  
  50.         'same as above, but this time with a string that is Relative
  51.         strUrl = "/index.aspx"
  52.         If Uri.TryCreate(strUrl, UriKind.Absolute, UriOut) Then
  53.             Debug.Print(UriOut.ToString & " is absolute")
  54.         Else
  55.             Debug.Print(strUrl & " is not absolute")
  56.         End If
  57.  
  58.         If Uri.TryCreate(strUrl, UriKind.Relative, UriOut) Then
  59.             Debug.Print(UriOut.ToString & " is Relative")
  60.         Else
  61.             Debug.Print(strUrl & " is not Relative")
  62.         End If
  63.     End Sub
  64.     Sub TryCreate3()
  65.         'demonstrates Uri.TriCreate(Uri,Uri,Uri)
  66.         'concatonates the first two URIs into the third
  67.  
  68.         'get a base uri
  69.         Dim BaseUri As Uri = New Uri("http://devshed.us/")
  70.  
  71.         'note that we have to specify the urikind
  72.         Dim RelativeUri As New Uri("/links.aspx", UriKind.Relative)
  73.  
  74.         'placeholder for the return val
  75.         Dim UriOut As Uri = Nothing
  76.  
  77.         'add the two together
  78.         If Uri.TryCreate(BaseUri, RelativeUri, UriOut) Then
  79.             Debug.Print(UriOut.ToString)
  80.         Else
  81.             Throw New Exception("Invalid URI")
  82.         End If
  83.  
  84.     End Sub
  85.  
  86. End Module
By Steve Gray on 3/15/2011 8:08 AM

I spend most of my day in either SMSS or Visual Studio (currently 2010), and there are a couple of small changes that I’m fond of making. It’s not a big deal, but I really like VS to close the quote marks for me in the HTML editor, it makes typing slightly faster. And, I like the tabs on the tab well to be all the same size. It’s slightly easier to close a bunch of them quickly, you don’t have to move the cursor, you can just click.

But, I hate to spend the time to look for these options in Tools > Options, there are so many options. So I thought I’d blog the options and have them on hand the next time I need to set them.

In order to get the ‘tabs’ feature, you’ll want to install the Productivity Power Pack

(click to enlarge)

image

Here is the ‘tab’ settings

image

By Steve Gray on 2/21/2011 3:40 PM

This is a short example on how to create a DataTable dynamically, assign a primary key to it, and then how to update it

You can search a data table with or without a primary key, but if you don’t use the key you’ll get back an array of rows; in this case the single row is really what we need.

This code is very useful for submitting samples to vendors, you don’t have to fake data connections.

There is no error checking, this is just template code.

Code Snippet
  1. Function GetDataTable() As DataTable
  2.     Dim oDT As New DataTable
  3.     Dim oKeys(0) As DataColumn
  4.     'create a data table to use as our input source
  5.  
  6.     'create columns
  7.     Dim oCol As DataColumn = New DataColumn("order", System.Type.GetType("System.String"))
  8.     oDT.Columns.Add(oCol)
  9.     oKeys(0) = oCol
  10.     oDT.Columns.Add(New DataColumn("salesperson", System.Type.GetType("System.String")))
  11.     oDT.Columns.Add(New DataColumn("amount", System.Type.GetType("System.Double")))
  12.     oDT.PrimaryKey = oKeys
  13.  
  14.     'create the rows
  15.     oDT.Rows.Add("ORD00100", "Bob@test.com", 1.23)
  16.     oDT.Rows.Add("ORD00102", "Bob@test.com", 3.23)
  17.     oDT.Rows.Add("ORD00104", "Sam@test.com", 2.23)
  18.     oDT.Rows.Add("ORD00105", "Sam@test.com", 4.23)
  19.  
  20.     Return oDT
  21.  
  22. End Function
  23.  
  24. Sub updateDataTable(ByVal strOrder As String, ByVal dblAmount As Double)
  25.     Dim oRow As DataRow
  26.  
  27.     '"order" is our primary key. Search the primary key for strOrder
  28.     oRow = oDT.Rows.Find(strOrder)
  29.  
  30.     'in the row found, set the Amount column
  31.     oRow("amount") = dblAmount
  32.  
  33.     'save
  34.     oDT.AcceptChanges()
  35.  
  36. End Sub
By Steve Gray on 12/17/2010 11:19 AM

Every time I add the DAAB to an application, I struggle a little with which .dlls to add to my project.

So, here it a walk through to get you (and me) started.

 

Download and install the Enterprise Library 5.0 objects. Choose the larger install, the second one.

Create a project, and set a reference to these dlls:

Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.ServiceLocation.dll

That should do it.

By Steve Gray on 12/9/2010 4:16 PM

This is the class that I use to abstract the Enterprise Library DAAB. There are other classes, found here

 
Code Snippet
  1. Imports Microsoft.VisualBasic
  2. Imports System.Data.SqlClient
  3. Imports System.Data
  4. Imports Microsoft.Practices.EnterpriseLibrary.Data
  5. Imports Microsoft.Practices.EnterpriseLibrary.Data.Sql
  6. Imports System.Configuration
  7.  
  8. Public Class storedProcedure
  9.     Dim _storedProcName As String
  10.     Dim _db As String
  11.     Public commandParameters As System.Collections.Generic.List(Of commandParameter)
  12.     Public CommandTimeout As Int16
  13.     Dim cs As New Dictionary(Of String, String)
  14.  
  15.     Sub New(ByVal StoredProcName As String, ByVal db As String)
  16.         _storedProcName = StoredProcName
  17.         _db = db.ToUpper
  18.         commandParameters = New System.Collections.Generic.List(Of commandParameter)
  19.  
  20.         cs.Add("NGB01", "Data Source=ngb-sql-05;User Id=4pennyapp;Password=app4me;Initial Catalog=NGB01")
  21.         cs.Add("ELSTN", "Data Source=ngb-sql-05;User Id=4pennyapp;Password=app4me;Initial Catalog=ELSTN")
  22.         cs.Add("NGBOED", "Data Source=ngb-sql-05;User Id=4pennyapp;Password=app4me;Initial Catalog=NGBOED")
  23.         cs.Add("STONE", "Data Source=ngb-sql-05;User Id=4pennyapp;Password=app4me;Initial Catalog=STONE")
  24.         cs.Add("INTRANET2", "Data Source=ngb-sql-05;User Id=4pennyapp;Password=app4me;Initial Catalog=Intranet2")
  25.         cs.Add("TWO", "Data Source=vmGP11;User Id=4pennyapp;Password=app4me;Initial Catalog=TWO")
  26.     End Sub
  27.  
  28.     Function execute(ByVal timeout As Int32, ByRef cps As System.Collections.Generic.List(Of commandParameter)) As Int32
  29.         Dim strError As String = ""
  30.         Try
  31.  
  32.             Dim aParams As SqlParameter() = Nothing
  33.             Dim a As Int16 = 0
  34.  
  35.             Dim db As Database
  36.             db = New SqlDatabase(cs(_db))
  37.  
  38.             Dim dbCommand As Common.DbCommand = db.GetStoredProcCommand(_storedProcName)
  39.  
  40.             If timeout > 0 Then
  41.                 dbCommand.CommandTimeout = timeout
  42.             End If
  43.  
  44.             For Each cp As commandParameter In commandParameters
  45.                 Select Case cp.ParamDirection
  46.                     Case ParameterDirection.Input
  47.                         db.AddInParameter(dbCommand, cp.ParamName, cp.ParamType, cp.ParamValue)
  48.                     Case ParameterDirection.InputOutput
  49.                         'not handled
  50.                     Case ParameterDirection.Output
  51.                         db.AddOutParameter(dbCommand, cp.ParamName, cp.ParamType, cp.ParamSize)
  52.                     Case ParameterDirection.ReturnValue
  53.                         'not handled
  54.                 End Select
  55.             Next
  56.             db.AddParameter(dbCommand, "@ReturnValue", DbType.Int32, ParameterDirection.ReturnValue, String.Empty, System.Data.DataRowVersion.Default, 0)
  57.  
  58.             db.ExecuteNonQuery(dbCommand)
  59.             For Each cp As commandParameter In commandParameters
  60.                 cp.ParamValue = db.GetParameterValue(dbCommand, cp.ParamName)
  61.             Next
  62.  
  63.             Dim rcp As commandParameter
  64.             rcp = New commandParameter("@Return_Value", 0, DbType.Int16)
  65.             rcp.ParamValue = db.GetParameterValue(dbCommand, "@ReturnValue")
  66.             commandParameters.Add(rcp)
  67.  
  68.             cps = commandParameters
  69.             Return rcp.ParamValue
  70.         Catch ex As Exception
  71.             strError = "query: " & _storedProcName & "<BR>"
  72.             For Each cp As commandParameter In commandParameters
  73.                 strError += "params: " & cp.ParamName & " = " & cp.ParamValue.ToString & "<br>"
  74.             Next
  75.  
  76.             ex.Source = strError
  77.             Throw ex
  78.  
  79.         End Try
  80.  
  81.     End Function
  82.     Function execute() As Int32
  83.         Dim intTimeout As Int32 = -1
  84.         Dim cp As New System.Collections.Generic.List(Of commandParameter)
  85.         Return execute(intTimeout, cp)
  86.     End Function
  87.     Function execute(ByRef cp As System.Collections.Generic.List(Of commandParameter)) As Int32
  88.         Dim intTimeout As Int32 = -1
  89.         Return execute(intTimeout, cp)
  90.     End Function
  91.  
  92.     Function executeScalar() As Object
  93.         Dim strError As String = ""
  94.         Try
  95.  
  96.             Dim aParams As SqlParameter() = Nothing
  97.             Dim a As Int16 = 0
  98.             Dim db As Database '= DatabaseFactory.CreateDatabase(_db)
  99.             db = New SqlDatabase(cs(_db))
  100.             Dim dbCommand As Common.DbCommand = db.GetStoredProcCommand(_storedProcName)
  101.             For Each cp As commandParameter In commandParameters
  102.                 db.AddInParameter(dbCommand, cp.ParamName, cp.ParamType, cp.ParamValue)
  103.             Next
  104.  
  105.             Return db.ExecuteScalar(dbCommand)
  106.         Catch ex As Exception
  107.             strError = "query: " & _storedProcName & "<BR>"
  108.             For Each cp As commandParameter In commandParameters
  109.                 strError += "params: " & cp.ParamName & " = " & cp.ParamValue.ToString & "<br>"
  110.             Next
  111.             strError += ex.Message
  112.             Throw New Exception(strError)
  113.  
  114.         End Try
  115.  
  116.         executeScalar = Nothing
  117.     End Function
  118.     Function getReader(ByVal timeout As Int32) As SqlDataReader
  119.         Dim strError As String = ""
  120.         Try
  121.  
  122.             Dim aParams As SqlParameter() = Nothing
  123.             Dim a As Int16 = 0
  124.             Dim db As Database '= DatabaseFactory.CreateDatabase(_db)
  125.             db = New SqlDatabase(cs(_db))
  126.             Dim dbCommand As Common.DbCommand = db.GetStoredProcCommand(_storedProcName)
  127.             If timeout > 0 Then
  128.                 dbCommand.CommandTimeout = timeout
  129.             End If
  130.             For Each cp As commandParameter In commandParameters
  131.                 db.AddInParameter(dbCommand, cp.ParamName, cp.ParamType, cp.ParamValue)
  132.             Next
  133.  
  134.             Return db.ExecuteReader(dbCommand)
  135.         Catch ex As Exception
  136.             strError = "query: " & _storedProcName & "<BR>"
  137.             For Each cp As commandParameter In commandParameters
  138.                 strError += "params: " & cp.ParamName & " = " & cp.ParamValue.ToString & "<br>"
  139.             Next
  140.  
  141.             ex.Source = strError
  142.             Throw ex
  143.  
  144.         End Try
  145.         getReader = Nothing
  146.  
  147.     End Function
  148.     Function getReader() As SqlDataReader
  149.         getReader = getReader(-1)
  150.  
  151.     End Function
  152.     Function getTable() As DataTable
  153.         getTable = getTable(-1)
  154.     End Function
  155.  
  156.     Function getTable(ByVal timeout As Int32) As DataTable
  157.         Dim strError As String = ""
  158.         Try
  159.  
  160.             Dim aParams As SqlParameter() = Nothing
  161.             Dim a As Int16 = 0
  162.  
  163.             Dim db As Database
  164.             db = New SqlDatabase(cs(_db))
  165.  
  166.             Dim dbCommand As Common.DbCommand = db.GetStoredProcCommand(_storedProcName)
  167.  
  168.             'set the command timeout
  169.             If timeout > 0 Then
  170.                 dbCommand.CommandTimeout = timeout
  171.             End If
  172.  
  173.             For Each cp As commandParameter In commandParameters
  174.                 db.AddInParameter(dbCommand, cp.ParamName, cp.ParamType, cp.ParamValue)
  175.             Next
  176.  
  177.             Return db.ExecuteDataSet(dbCommand).Tables(0)
  178.         Catch ex As Exception
  179.             strError = "query: " & _storedProcName & "<BR>"
  180.             For Each cp As commandParameter In commandParameters
  181.                 If Not cp.ParamValue Is Nothing Then
  182.                     strError += "params: " & cp.ParamName & " = " & cp.ParamValue.ToString & "<br>"
  183.                 Else
  184.                     strError += "params: " & cp.ParamName & " = Nothing<br>"
  185.                 End If
  186.             Next
  187.  
  188.             ex.Source = strError
  189.             Throw ex
  190.         End Try
  191.         getTable = Nothing
  192.  
  193.     End Function
  194.  
  195. End Class
By Steve Gray on 9/23/2010 9:52 AM

I’m testing a product called SmartXLS, here’s my first stab at a class to use it’s properties

 

Imports SmartXLS
Imports System.IO

Public Class SmartXLS
    Dim wb As New WorkBook
    ''' <remarks>zero based</remarks>
    Public Columns As Int16
    ''' <remarks>zero based</remarks>
    Public Rows As Int16

    ''' <summary>
    ''' Creates a new instance of the SmartXML class
    ''' </summary>
    ''' <param name="strFileName">Excel FileName, includes the fill path</param>
    ''' <remarks></remarks>
    Sub New(ByVal strFileName As String)
        Dim strExt As String = Path.GetExtension(strFileName)

        Select Case strExt.ToUpper
            Case ".XLS"
                wb.read(strFileName)
            Case ".XLSX"
                wb.readXLSX(strFileName)
            Case Else
                Throw New Exception("Invalid file name")
        End Select

        Columns = wb.LastCol
        Rows = wb.LastRow

    End Sub

    ''' <summary>
    ''' To Read an Excel File and return a Generic List of the column headers
    ''' </summary>
    ''' <returns>A Generic List of String values</returns>
    Public Function GetExcelColumnHeaders() As List(Of String)
        Dim oColumnHeaders As New List(Of String)
        Dim Dt As New DataTable()

        Try

            Dim i As Int32
            For i = 0 To Columns
                oColumnHeaders.Add(wb.getFormattedText(0, i))
            Next

            Return oColumnHeaders
        Catch ex As Exception
            Throw ex
        End Try

    End Function

    ''' <summary>
    ''' To Read an Excel File and Get a DataTable with its values
    ''' </summary>
    ''' <returns>A DataTable with Excel Values</returns>
    ''' <remarks></remarks>
    Public Function GetExcelAsDataTable() As DataTable

        Dim Dt As New DataTable()

        Dim c As Integer = 0
        Dim r As Integer = 0

        'add the correct number of columns to our datatable
        For c = 0 To Columns
            Dt.Columns.Add(GetExcelColumnHeaders(c))
        Next

        'skip the first row
        For r = 1 To Rows
            Dim dr As DataRow = Dt.NewRow

            For c = 0 To Columns
                dr(c) = (wb.getFormattedText(r, c))
            Next
            Dt.Rows.Add(dr)

        Next

        Return Dt
    End Function

End Class

By Steve Gray on 9/23/2010 9:02 AM

I ran across a technique that I’ve not used before (you learn something new every day, don’t you?) that I want to document here. It involves decorating a class so that the methods and properties show up in VB when you call the class.

Basically, you just add comments above the methods like this:

    ''' <summary>
    ''' Creates a new instance of the ExcelHelper class
    ''' </summary>
    ''' <param name="strfile">Excel File as Stream</param>
    Public Sub New(ByVal strFile As String)
        myWorkbook = SpreadsheetDocument.Open(strFile, False)
        workbookpart = myWorkbook.WorkbookPart
        worksheetPart = workbookpart.WorksheetParts.FirstOrDefault()
        stringTablePart = workbookpart.SharedStringTablePart
        columns = GetExcelColumns()
    End Sub

 

And when you call the class, you can see the documentation:

SNAGHTMLdc89093

 

Nice, right?

The following XML comment tags are officially supported in VB.NET: c,code, example, exception, include, list, para, param, paramref, permission, remarks, returns, see, seealso, summary and typeparam.

c: This tag is used to denote code, so it can be used to identify sample code associated with a particular entity within the source code. Note that the tag can only be used to represent a single line of code or to denote that some of the text on a line should be marked up as code. Example: <c>Dim MyObject As MyType</c>

code: This tag is used to denote more than one line of code, so it can be used to identify longer areas of sample code.

example: This tag may be used to describe an example of using a particular method or class. It is possible to include code samples within the example tag by making use of either the c or code tags.

exception: The exception tag allows a method's exception handling to be documented. The cref attribute allows the namespace of the exception handler to be included. Example: <exception cref="System.Exception" >Throws an exception if the customer is not found.</exception>

include: This tag allows documentation to be imported from an external XML file rather than being stored within the source code itself. As such it may be useful if the documentation is written by people other than the software developers (e.g. technical writers).

list: This tag allows bulleted or numbered lists or tables to be added to XML comments.

para: This tag indicates that the text within the tags should be formatted within a paragraph. As such it can be used to format text within other tags such as summary or returns. Example: <para>This is a paragraph</para>

param: The param tag is used to document a method's arguments. The tag's name attribute specifies the name of the argument to which the tag refers. The tag is also used by Visual Studio's Intellisense system to show a description of a method's arguments. It is also used by the Visual Studio Object Browser. Example: <param name="FileName" >The filename of the file to be loaded.</param>

paramref: This tag can be used to refer to a method's argument elsewhere within the method's XML comments. The tag's name attribute specifies the name of the argument to which the tag refers. Note that the param tag is actually used to describe the parameter. Example: Use the <paramref name="FileName"/> argument to specify which filename is loaded.

permission: The permission tag can be used to describe any special permissions a specific object needs. The object to which the permission refers is included as the cref attribute. Example: Class needs to write to the file system, ensure user has appropriate access.

summary: The summary tag describes a method or class, so it is the most important tag. As well as being used in a project's documentation, the tag is also used by Visual Studio's Intellisense system to show a description of the method or class being referenced. It is also used by the Visual Studio Object Browser.

remarks: The remarks tag can be used to supply additional information about a method or class, supplementing the details given in the summary tag. As with the summary tag, this tag is also used by Visual Studio's Intellisense system and the Visual Studio Object Browser.

returns: Describes the return value of a method. Example: <returns>True if user has permission to access the resource, otherwise False.</returns>

see: The see tag is used to reference other entities (such as classes) in the project. The see tag is intended for use within other tags such as the summary tag. Example: <seealso cref="System.Configuration"/>

seealso: The seealso tag resembles the see tag and has identical syntax, except that the text is intended to be used to create a separate seealso section for the entity's documentation.

typeparam: Typeparam is used in an identical way to param, except that it is used to document a type associated with a generic class or function.

value: Value is only used when documenting a property, and is used to describe the value assigned to that. The comment is not required for properties that are marked as read only. Example: <value>Sets the employee's salary</value>

As always, I welcome your comments!
  
 
 
Home | Products | Blogs | Contact Us | Links | God's Plan
Privacy Statement | Terms Of Use
 
Copyright 2011 by Devshed.us