1 2 3 4 5  ... Previous Next 

VS 2008: Extension Methods


Visual Basic 2008 adds a new features called extension methods.   These allow you to add a method, or function to a type.  For this example we will add an IsGuid function to strings.  All extension methods must be placed in a module.  The function or method must be marked as an extension and the first argument is the type the method extends.

Imports System.Runtime.CompilerServices
Imports System.Text.RegularExpressions

Module Module1

    Sub Main()
        Dim g As String = "82ee4145-632c-42a1-83b9-57ec163eaa17"
        Dim g1 As String = "82ee4145-632c-42a1-83b9-57ec163ea17"

        Console.WriteLine(g & IIf(g.IsGuid, " is ", " is not ") & "a valid guid")
        Console.WriteLine(g1 & IIf(g1.IsGuid, " is ", " is not ") & "a valid guid")
    End Sub

End Module

Public Module MyExtensions

    <Extension()> _
    Public Function IsGuid(ByVal s As String) As Boolean
        Dim regGuid As New Regex("^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled)
        Return regGuid.IsMatch(s)
    End Function
End Module




Making a REST service with VB and WCF


REST which stands for Representational State Transfer is a way of sending data over the Internet without an additional message layer.  Standard web services use soap for there message header.  In this example we will create a service that uses the northwind database to send a  list of the products for a category.

 

Lets start by create a new VB web application. In that web application add a Ado.Net Entities data model.  In that class add the northwind database's product class.

 

image

 

Now add a service named Service1 to the web application.  Lets start by modify the web.config for the service to support rest.  First remove the ServiceBehavior section and add a endpointBehaviors section for webHttp.  In the endpoint we have to change the binding to webHttpBinding and the behaviorConfiguration to the webBehavior we created.

 

    <system.serviceModel>
        <behaviors>
      <endpointBehaviors>
        <behavior name="webBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="True"></serviceHostingEnvironment>
        <services>
            <service name="RestTest.Service1">
                <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" bindingConfiguration="" contract="RestTest.IService1">
                </endpoint>
            </service>
        </services>
    </system.serviceModel>

 

When we added the service we got 2 items the wcf service and an interface for the service.  Before we go any further we need to add a reference to system.servicebehavior.web  

 

In the Interface we need to define the how the categoryId is passed to the service.  In this example it expects product/categoryID in the url for the service

 

Imports System.ServiceModel
Imports System.ServiceModel.Web

<ServiceContract()> _
Public Interface IService1

    <OperationContract()> _
    <WebGet(UriTemplate:="Product/{categoryID}", ResponseFormat:=WebMessageFormat.Xml, BodyStyle:=WebMessageBodyStyle.Bare)> _
    Function GetProducts(ByVal categoryId As String) As List(Of Products)

End Interface

 

In the service we need to set the AspNetCompatibilityMode and write some code to return the products

 

Imports System.ServiceModel.Activation

<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Service1
    Implements IService1

    Public Function GetProducts(ByVal categoryId As String) As System.Collections.Generic.List(Of Products) Implements IService1.GetProducts
        Dim dc As New NorthwindEntities
        Dim q = From p In dc.Products Select p Where p.CategoryID = CInt(categoryId)
        Return q.ToList
    End Function
End Class

 

To call the service you would use a url like http://localhost:2050/Service1.svc/Product/7

 

you will get an xml file like this returned

 

 

image



Getting Windows Mobile Device ID


I got email today asking me how to get the device ID from a pocket pc with vb

 

Imports System.Text

Public Class Form1

    <System.Runtime.InteropServices.DllImport("coredll.dll")> _
Private Shared Function GetDeviceUniqueID(ByVal appdata As Byte(), ByVal cbApplictionData As Integer, ByVal dwDeviceIDVersion As Integer, ByVal deviceIDOuput As Byte(), ByRef pcbDeviceIDOutput As Integer) As Integer
    End Function

    Private Function GetDeviceId(ByVal appData As String) As Byte()

        Dim appDataBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(appData)
        Dim outputSize As Integer = 20
        Dim output(19) As Byte

        Dim result As Integer = GetDeviceUniqueID(appDataBytes, appDataBytes.Length, 1, output, outputSize)

        Return output

    End Function

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim sbId As New StringBuilder

        Dim bID() As Byte = GetDeviceId("MyAppName")

        For Each b In bID
            sbId.Append(String.Format("{0:x2}", b))
        Next

        Debug.WriteLine(sbId.ToString)
    End Sub
End Class

 

References

 

http://www.peterfoot.net/GetDeviceUniqueIDForVB.aspx

http://msdn.microsoft.com/en-us/library/ms893522.aspx




Report Viewer control and dataset


1.- I created a Sql Server 2005 database in the App_Code of my Web App. In it, I build two tables named ‘Encabs´ (‘Headers’ in

English I suppose) and ‘ Detalle’

The ‘Encabs’ table has colums that will be used in text boxes of the Header and the Bottom of the Report, like :

- Folio, date, user, total, sending warehouse, receiving warehouse, Total amount expressed in alphabetical letters etc..

The ‘Detalle’ table has colums that will be included in a table control (of the Report Items Toolbar) that will show the details of the

Report, like Article Code, Description, Unit Cost, Series numbers, quantity and (I don´t know how to say in english :

Pedimento Aduanal)

. These will be used just to create a xsd schema. Really they won´t be used directly in the program. It´s just that when you create

the xsd file, it´s mandatory (I think) to use them for configuration purposes. In fact, the program will use a couple of tables

created at runtime individualized with the 3 first characters of the User code that connected to the Web App. In this way I solved the

problema that could occur if two or more users use the Report at the same time. (Remember ?). For example : ‘Encabs_ken’ or

‘Encabs_mig’ and “Detalle_ken” or “Detalle_usr”

2.- Then I created the xsd file ( I named it ‘Traspasos.xsd’. My Web App is about traspassing merchandise between warehouses

In the company. Some of them very far from Mexico City, like Los Cabos B. Calif.). I´m pretty sure you know how to do it.

clip_image002

3- You create the Report Definition Fle (.rdlc) . I´m using a Report Viewer in Local Mode. We don´t need a huge level of impression.

clip_image004

4.- Using code, I fill the two mentioned tables with the data I need. (At Runtime)

5.- Using Code also, in the Web page that contains the Report Viewer Control, I managed to replace the data sources for it.

I saw the code in a Web Portal but sadly, I don´t remember the URL, so I send you my own code, which I developed upon what

I saw in that Portal. (In fact, the code was in C#)

Imports Microsoft.Reporting.WebForms

Imports System.Data

Imports System.Data.SqlClient

Partial Class Reporte

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Dim strXsd As String, strXsDet As String

strXsd = CType(Session("strxsd"), String)

strXsDet = CType(Session("strxsdet"), String)

RV1.ProcessingMode = ProcessingMode.Local

Dim LocalReport = RV1.LocalReport

LocalReport.reportPath = "C:\WebSite_Traspasos\Report.rdlc"

Dim Encabs_Set As New DataSet

Dim Detalle_Set As New DataSet

Dim Cn As New SqlConnection

Cn.ConnectionString = "Data Source=MALTAMIRANO\SQLEXPRESS;Initial Catalog=C:\WEBSITE_TRASPASOS\APP_DATA\TRASP_WORK.MDF;Integrated Security=True"

Cn.Open()

Dim Comando As New SqlCommand("SELECT * FROM " + strXsd, Cn)

Dim Adapter As New SqlDataAdapter

Adapter.SelectCommand = Comando

Adapter.Fill(Encabs_Set, strXsd)

Dim ds As New ReportDataSource

ds.Name = "Traspasos_Encabs"

ds.Value = Encabs_Set.Tables(strXsd)

LocalReport.datasources.add(ds)

'

Dim Comanda As New SqlCommand("SELECT * FROM " + strXsDet, Cn)

Dim Adaptador As New SqlDataAdapter

Adaptador.SelectCommand = Comanda

Adaptador.Fill(Detalle_Set, strXsDet)

Dim det As New ReportDataSource

det.Name = "Traspasos_Detalle"

det.Value = Detalle_Set.Tables(strXsDet)

LocalReport.datasources.add(det)

Cn.Close()

End Sub

Explanations :

StrXsd is the variable which holds the name of the table with the information for the ‘Encabs’ table

StrXdet has the infomation for the ‘Detalle’ table.

RV1 is the Instance of the Report Viewer Control. In the next lines of code, the program creates a New couple of Data Sets and

Somehow manages to set the replace the original datasources of the Report for the newly created. I´m very aware I don´t need to

Explain anything to you. Besides, I did almost identcally to what I saw. Someday I´ll analize it deeper.

I think the code :

Dim det As New ReportDataSource

det.Name = "Traspasos_Detalle" ‘ You can see these names in the xsd schema

det.Value = Detalle_Set.Tables(strXsDet)

LocalReport.datasources.add(det)

Is what really makes the miracle.


Submitted by Miguel Altamirano




Validating Data entered in a DataRepeater control


In this example I will show how to validate the data entered into a datarepeater control. For this example I am added the northwind SQL compact edition database to the project and created a typed dataset for the products table.  So from the toolbox drop a datarepeater on the form.  Inside the datarepeater drag the ProductName, UnitPrice, and Units in stock fields. Your form should look something like

 

image

 

Now in the drawitem event for the datarepeater we can add a handler to validating event.

Private Sub DataRepeater1_DrawItem(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.PowerPacks.DataRepeaterItemEventArgs) Handles DataRepeater1.DrawItem
    Dim currItem As DataRowView = DirectCast(ProductsBindingSource.Item(e.DataRepeaterItem.ItemIndex), DataRowView)
    Dim txt As TextBox = DirectCast(e.DataRepeaterItem.Controls("Unit_PriceTextBox"), TextBox)
    AddHandler txt.Validating, AddressOf TextBox_Validating
End Sub

Private Sub TextBox_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs)
    Dim dec As Decimal
    If Not Decimal.TryParse(DirectCast(sender, TextBox).Text, dec) Then
        MessageBox.Show("Please enter a valid number")
        e.Cancel = True
    End If
End Sub

 

The complete code

 

Public Class Form1

    Private Sub ProductsBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProductsBindingNavigatorSaveItem.Click
        Me.Validate()
        Me.ProductsBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.NorthwindDataSet)

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'NorthwindDataSet.Products' table. You can move, or remove it, as needed.
        Me.ProductsTableAdapter.Fill(Me.NorthwindDataSet.Products)

    End Sub

    Private Sub DataRepeater1_DrawItem(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.PowerPacks.DataRepeaterItemEventArgs) Handles DataRepeater1.DrawItem
        Dim currItem As DataRowView = DirectCast(ProductsBindingSource.Item(e.DataRepeaterItem.ItemIndex), DataRowView)
        Dim txt As TextBox = DirectCast(e.DataRepeaterItem.Controls("Unit_PriceTextBox"), TextBox)
        AddHandler txt.Validating, AddressOf TextBox_Validating
    End Sub

    Private Sub TextBox_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs)
        Dim dec As Decimal
        If Not Decimal.TryParse(DirectCast(sender, TextBox).Text, dec) Then
            MessageBox.Show("Please enter a valid number")
            e.Cancel = True
        End If
    End Sub
End Class




1 2 3 4 5  ... Previous Next