Locations of visitors to this page


Onteora Software - Ken Tucker's Blog

Onteora Software

Ken Tucker's Blog

About the author

Author Name is someone.
E-mail me Send mail

Recent posts

Recent comments

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Asp.Net Routing

 

New to the .Net Framework 3.5 SP 1 is the System.Web.Routing namespace.  The classes in the routing namespace allow you to use urls that do not map to a web page.

 

 

For this example I created a new web application.  To start off with lets add a reference to the system.web.routing and system.web.abstractions.  Open up the web.config file and lets add the UrlRoutingModule to the httpmodules section

 

        <httpModules>
            <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </httpModules>

 

Next we need to add a WebFormRouteHandler class which will be our route handler.

 

Imports System.Web.Routing
Imports System.Web.Compilation

Public Class WebFormRouteHandler
    Implements IRouteHandler

    Private _Path As String
    Public Property Path() As String
        Get
            Return _Path
        End Get
        Set(ByVal value As String)
            _Path = value
        End Set
    End Property

    Public Sub New(ByVal p As String)
        Path = p
    End Sub

    Public Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler Implements System.Web.Routing.IRouteHandler.GetHttpHandler
        For Each value In requestContext.RouteData.Values
            requestContext.HttpContext.Items(value.Key) = value.Value
        Next
        If Not String.IsNullOrEmpty(Path) Then
            Return TryCast(BuildManager.CreateInstanceFromVirtualPath(Path, GetType(Page)), IHttpHandler)
        Else
            Return Nothing
        End If

    End Function
End Class

 

Finally we have to add global.asax so we can start the routing when the web site starts up

 

 

Imports System.Web.SessionState
Imports System.Web.Routing

Public Class Global_asax
    Inherits System.Web.HttpApplication

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the application is started.
        Dim userHandler As New WebFormRouteHandler("~/user.aspx")
        With RouteTable.Routes

            ' pattern of the url to match
            .Add(New Route("user/{user}", userHandler))
        End With
    End Sub

    Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the session is started
    End Sub

    Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires at the beginning of each request
    End Sub

    Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires upon attempting to authenticate the use
    End Sub

    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when an error occurs
    End Sub

    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the session ends
    End Sub

    Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the application ends
    End Sub

End Class

 

Finally we need 2 web pages

 

Default.aspx

 

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="RoutingTest._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>ASP.NET System.Web.Routing with WebForms sample</h1>
    <div><a href="user/ken">User test</a></div>
    </div>
    </form>
</body>
</html>

 

user.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="User.aspx.vb" Inherits="RoutingTest.User" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
            <h1>
            Users</h1>
        <div>
            User:
            <%=Context.Items("user")%></div>
        <hr />
        <div>
            Change the user in the URL.</div>
        <div>
            The WebFormRouteHandler adds the matched values to the HTTPContext.Items collection
            (exists for lifetime of request only).</div>
    </div>
    </form>
</body>
</html>

 

Hope this helps

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by Ken Tucker on Monday, August 18, 2008 1:41 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Publishing a VB Silverlight 2 Beta 2 app which uses a WCF service

I created a Silverlight 2 beta 2 app which uses a WCF Silverlight service which worked fine localy but did call the service when I published it to my web host.  After playing around with the different settings I finally came across an entry in the Silverlight Forums by sladapter with a solution. 

 

http://silverlight.net/forums/t/19021.aspx 

 

So lets create a simple Silverlight 2 App to demo how to do this.  I created a silverlight app with a web application project.   I prefer web applications to web sites but a web site will work the same.  

 

Add a WCF Silverlight- enabled service named  service1 to the web application. 

 

This is the code I am using for the service

 

Imports System.ServiceModel
Imports System.ServiceModel.Activation

<ServiceContract(Namespace:="")> _
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Service1

    <OperationContract()> _
    Public Function SayHello() As String
        ' Add your operation implementation here
        Return "Hello World"
    End Function
End Class

 

Lets add a TextBlock to the Page.xaml to display our message.

 

<UserControl x:Class="SilverlightApplication2.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
            <TextBlock x:Name="txt">Loading..</TextBlock>
    </Grid>
</UserControl>

 

Now run the app.  Once that is done we can add a service reference to our silverlight app.  Press the arrow on the Discover button and select services in the solution.  You should windup with something like this.

 

image

 

In the silverlight app open up the file ServiceReferences.ClientConfig

 

<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_Service1" maxBufferSize="65536"
                    maxReceivedMessageSize="65536">
                    <security mode="None" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:1205/Service1.svc" binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_Service1" contract="ServiceReference1.Service1"
                name="BasicHttpBinding_Service1" />
        </client>
    </system.serviceModel>
</configuration>

 

In the endpoint address change the contract to include the project name.

 

<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_Service1" maxBufferSize="65536"
                    maxReceivedMessageSize="65536">
                    <security mode="None" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:1205/Service1.svc" binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_Service1" contract="SilverlightApplication2.ServiceReference1.Service1"
                name="BasicHttpBinding_Service1" />
        </client>
    </system.serviceModel>
</configuration>

 

Now lets add some code to call the service. Page.Xaml.VB

 

Partial Public Class Page
    Inherits UserControl
    Dim current As String

    Public Sub New()
        InitializeComponent()
    End Sub

    Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        Dim ws As New ServiceReference1.Service1Client
        AddHandler ws.SayHelloCompleted, AddressOf HelloComplete
        ws.SayHelloAsync()
    End Sub

    Private Sub HelloComplete(ByVal sender As Object, ByVal e As ServiceReference1.SayHelloCompletedEventArgs)
        txt.Text = e.Result
    End Sub

End Class

 

Now if we run the app you should see Hello World but when published you will only see loading.   So lets change how we create the service so that this will work once deployed.  Basically we tell the service to use the current web address.

 

Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
    Dim address = New Uri(Application.Current.Host.Source, "../Service1.svc")

    Dim ws As New ServiceReference1.Service1Client("BasicHttpBinding_Service1", address.AbsoluteUri)
    AddHandler ws.SayHelloCompleted, AddressOf HelloComplete
    ws.SayHelloAsync()
End Sub

 

Hope this helps

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Silverlight | VB
Posted by Ken Tucker on Tuesday, July 15, 2008 1:54 PM
Permalink | Comments (0) | Post RSSRSS comment feed

The INETA Community Champion Award

INETA Rewards those Active in the User Group Community

An XBox or MSDN Subscription to the 10 Most Active Contributors in the User Group Community each quarter.
How?  By doing what you are doing already, you stand to win:
a) Valuable Prizes: An MSDN Subscription.  And, if you already have one, you can choose an XBox instead.

XBox
MSDN Professional Subscription

XBox
MSDN Subscription

b) The Fame and Prestige of having an award to hang on your wall that shows that INETA recognizes your contributions to the User Group Community.

Champion Award

c) Official Recognition on the INETA Website  for one year.
All of your peers will be able to see that you stand out above the crowd. If the opportunity presents itself for you to show your dedication to the User Group Community in a public way, there is no better way than to show off your name highlighted on the website of a highly respected organization like INETA.
d) A Badge for your website showing that you are a Community Champion.
When folks visit your website, blog or any other place where you publicly post your work, they will see that you are a Community Champion.
Oooohhhh. Recognition by INETA? Valuable Prizes? An award to hang on my wall? A Badge?  How can I participate?

Well, I am glad that you asked.

INETA has long been known for it's support of User Groups and this year, there are a number of great new programs supporting the User Group Community.  The Community Champs program is one of them.  INETA wants to recognize individuals who are demonstrating their involvement in the User Group community.  The program is aimed at rewarding those that are the most active with the prizes and award mentioned above.  It is INETA's way of recognizing the ones that really bring the community together.  So, in short, if you are the kind of person who helps to run user group meetings, codecamps, or helps out in any number of other ways, you should let INETA know the kind of activities that you are involved in.  If you are very active, you may be recognized by INETA in a very public and spectacular way for the activities that you currently do to help the user group community.

INETA and Community-Credit are making it happen.

Community Credit has been helping to recognize fellow developers for the past number of years for their accomplishments and INETA has been the mainstay of User Groups for many years, so it is no surprise that the two would be working together to make this great program possible.  Best of all, the contributions that you record will also count toward Community Credit prizes, so you may even have a chance to be rewarded with a Geeky, Community Credit prize as an added bonus.

How do I submit my contributions?

Visit the INETA website and go to the Champions section, sign in and let INETA know what you are doing by recording your contributions.  The current quarterly period counts for contributions during period of  June 30th, 2007 to June 30th, 2008.  The final submissions can be made until July 14th.  Keep in mind that the end of this current quarter is coming up pretty soon, so if you have been very active over the last year, be sure to enter them soon so that you don't miss this great opportunity.

What are the benefits of participating?

If you are an individual who is always contributing to the User Group Community, you do it because you like it.  You don't do it because you expect to be rewarded.  At the same time, if you just happen to be rewarded and recognized then that makes it that much better.  Imagine playing on an XBox that you received as a thanks for all of your hard work.  It makes the games just a little bit more fun.  Using your MSDN subscription that you "earned" makes the tools just a little bit better and seeing the award hanging on your wall is a reminder to you and your colleagues just how committed you are.

Can anybody participate?

Unfortunately, the current period (being our first) is for participants in North America only.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: User Group
Posted by Ken Tucker on Tuesday, July 01, 2008 12:34 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Linq 2 entities and XML

When using Linq 2 Sql with Linq to Xml in VB you could write code like this to generate xml

 

Dim db As New NorthwindDataContext
 

Dim xmlLinq2Sql = <root><%= From emp In db.Employees _
                            Select <Employee id=<%= emp.EmployeeID %>><%= emp.FirstName & " " & emp.LastName %>
                                   </Employee> %>
                  </root>

 

Which will generate xml  like this

<root>
  <Employee id="1">Nancy Davolio</Employee>
  <Employee id="2">Andrew Fuller</Employee>
  <Employee id="3">Janet Leverling</Employee>
  <Employee id="4">Margaret Peacock</Employee>
  <Employee id="5">Steven Buchanan</Employee>
  <Employee id="6">Michael Suyama</Employee>
  <Employee id="7">Robert King</Employee>
  <Employee id="8">Laura Callahan</Employee>
  <Employee id="9">Anne Dodsworth</Employee>
</root>

 

The entity framework requires a more explicit format for the query

 

Dim entDB As New NorthwindModel.NorthwindEntities

Dim xmlLinq2Entities = <root><%= From ent In entDB.Employees.AsEnumerable _
                                 Select <Employee id=<%= ent.EmployeeID %>><%= ent.FirstName & " " & ent.LastName %>
                                        </Employee> %>
                       </root>

 

 

Hope this helps

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by Ken Tucker on Monday, June 30, 2008 12:58 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Silverlight 2 Beta 2 VB only bug

           I have been playing around trying to use a wcf service with a vb silverlight 2 beta 2 app and kept getting a InvalidOperationException when trying to call the wcf service (of course it works fine in c#). 

Tim Anderson's blog correctly shows all you have to do is give the contract a fully qualified namespace to fix the issue.   

http://www.itwriting.com/blog/?p=666

  

So in a nut shell vb generates this in ServiceReferences.ClientConfig

         <client>            <endpoint address="http://localhost:1735/Service1.svc" binding="basicHttpBinding"                bindingConfiguration="BasicHttpBinding_IService11" contract="ServiceReference1.IService1"                name="BasicHttpBinding_IService1" />

        </client>

When it should be

         <client>            <endpoint address="http://localhost:1735/Service1.svc" binding="basicHttpBinding"                bindingConfiguration="BasicHttpBinding_IService11" contract="VBSqlData.ServiceReference1.IService1"                name="BasicHttpBinding_IService1" />        </client>

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by Ken Tucker on Sunday, June 15, 2008 11:17 PM
Permalink | Comments (0) | Post RSSRSS comment feed

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

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: VB
Posted by ken tucker on Wednesday, May 07, 2008 5:34 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Sql Server for Developers Space Coast .Net Meeting

When Wednesday June 11, 2008 @ 6:30PM

Want to know what you need to do to keep your DBA happy and make your application run really fast? Wondering if stored procedures are really faster than dynamic sql? Need some good guidelines for adding indexes? We'll spend an hour talking about performance in this very interactive presentation.

Andy Warren of End to End Training will be speaking.

Register if you plan to attend this event

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by Ken Tucker on Tuesday, April 29, 2008 3:06 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Space Coast .Net Silverlight 2.0 Meeting

When: Wednesday May 21, 2008 @ 6:30 PM

Where: Space Coast Credit Union corp headquarters 

 

Silverlight 2 includes a cross-platform, cross-browser version of the .NET Framework, and enables a rich .NET development platform that runs in the browser.  Developers can write Silverlight applications using any .NET language (including VB, C#, JavaScript, IronPython and IronRuby).  We will ship Visual Studio 2008 and Expression Studio tool support that enables great developer / designer workflow and integration when building Silverlight applications.

 

Jeff Barnes of Microsoft will be presenting


There will be pizza and magazines available at this meeting. There will be a raffle for a Office 2007 pro at the end of the meeting.


Register if you plan to attend this event

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: User Group
Posted by Ken Tucker on Tuesday, April 29, 2008 3:03 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Regular Expression Help

I got an regualr expression question today from one of my friends.  Basically she was using a regular expression  to validate a number was 4 or 6 digits long but the expression she was using ^\d{4,6}$ would validate numbers 5 digits long.  Lets look at this regular expression ^ means starts with. The \d means number and the {4,6} means 4 to 6 digits long.  The $ means ends with. The answer is to use a regular express with an or (the | means or)

Dim regNum As New Regex("^\d{4}$|^\d{6}$")

Debug.Print(regNum.IsMatch("1234").ToString)

Debug.Print(regNum.IsMatch(
"12345").ToString)

Debug.Print(regNum.IsMatch("123456").ToString)

Output

True

False

True

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: VB | regex
Posted by Ken Tucker on Monday, April 28, 2008 1:13 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Print to PDF

The .Net framework provides a print document class for printing.  There are times that it would be nice to redirect what you are printing to a pdf.   In this example we are going to use the Sharp Pdf lib version 1.3.1 to print to a pdf. 

The sharp pdf lib allows you to add an image to a page in a pdf.  To make it possible to print to a pdf we are going to create a new print controller class which creates a bitmap and has the print document draw the page on the bitmap.  Then it adds the bitmap as a pdf page.  Once the document is done printing it saves the pdf to disk. 

 

http://sharppdf.sourceforge.net/

Update this Project is now available on CodePlex

http://www.codeplex.com/Print2Pdf

 

Imports sharpPDF

Public Class PdfPrintController
    Inherits Printing.PrintController
    Dim pdf As pdfDocument
    Dim bm As Image

    Private _Author As String = "Unknown"

    Public Property Author() As String
        Get
            Return _Author
        End Get
        Set(ByVal value As String)
            _Author = value
        End Set
    End Property

    Private _FileName As String = "Printed.pdf"
    Public Property FileName() As String
        Get
            Return _FileName
        End Get
        Set(ByVal value As String)
            _FileName = value
        End Set
    End Property

    Private _Title As String = "Unknown"
    Public Property Title() As String
        Get
            Return _Title
        End Get
        Set(ByVal value As String)
            _Title = value
        End Set
    End Property

    Public Overrides ReadOnly Property IsPreview() As Boolean
        Get
            Return True
        End Get
    End Property

    Public Overrides Function OnStartPage(ByVal document As System.Drawing.Printing.PrintDocument, ByVal e As System.Drawing.Printing.PrintPageEventArgs) As System.Drawing.Graphics
        bm = New Bitmap(e.PageBounds.Width, e.PageBounds.Height)
        Dim g As Graphics = Graphics.FromImage(bm)
        g.Clear(Color.White)
        Return g
    End Function

    Public Overrides Sub OnStartPrint(ByVal document As System.Drawing.Printing.PrintDocument, ByVal e As System.Drawing.Printing.PrintEventArgs)
        pdf = New pdfDocument(Title, Author)
        MyBase.OnStartPrint(document, e)
    End Sub

    Public Overrides Sub OnEndPage(ByVal document As System.Drawing.Printing.PrintDocument, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
        Dim p As pdfPage = pdf.addPage(e.PageBounds.Height, e.PageBounds.Width)
        p.addImage(bm, 0, 0)
        MyBase.OnEndPage(document, e)
    End Sub

    Public Overrides Sub OnEndPrint(ByVal document As System.Drawing.Printing.PrintDocument, ByVal e As System.Drawing.Printing.PrintEventArgs)
        pdf.createPDF(FileName)
        MyBase.OnEndPrint(document, e)
    End Sub

End Class

Here is a sample which creates a pdf of the Northwind product list.

Imports System.Data.SqlClient

Public Class Form1
    Public WithEvents p As New Printing.PrintDocument
    Dim iRecord As Integer = 0
    Dim fntPrice As New Font("Arial", 12)
    Dim ds As New DataSet

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim strConn As String
        Dim conn As SqlConnection
        Dim da As SqlDataAdapter

        strConn = "Server = .\SQLEXPRESS;"
        strConn &= "Database = Northwind; Integrated Security = SSPI;"
        conn = New SqlConnection(strConn)
        da = New SqlDataAdapter("Select ProductName, UnitPrice From Products", conn)
        da.Fill(ds, "Products")

        DataGridView1.DataSource = ds.Tables("Products")
    End Sub

    Private Sub p_BeginPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles p.BeginPrint
        iRecord = 0
    End Sub

    Private Sub p_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles p.PrintPage
        Dim g As Graphics = e.Graphics
        Dim iPageHeight As Integer = e.PageBounds.Height
        Dim iPageWidth As Integer = e.PageBounds.Width
        Dim iFntHeight As Integer = CInt(g.MeasureString("Test", fntPrice).Height)
        Dim iLinesPerPage As Integer = iPageHeight \ iFntHeight - 15
        Dim yPos As Integer = 0
        Dim iTop As Integer
        Dim iMax As Integer = ds.Tables("Products").Rows.Count
        Dim strDescription As String
        Dim x As Integer
        Dim xPos As Integer
        Dim strPrice As String
        Dim fntTitle As Font = New Font("Microsoft Sans Serf", 14)
        Dim iCount As Integer = ds.Tables("Products").Rows.Count
        Dim strDate As String = Trim(Now.ToLongDateString)
        Dim sf As New StringFormat
        sf.Alignment = StringAlignment.Far

        xPos = CInt(iPageWidth - g.MeasureString("Price List", fntTitle).Width) \ 2
        g.DrawString("Price List", fntTitle, Brushes.Black, xPos, 10)
        yPos = 10 + CInt(g.MeasureString("Price List", fntTitle).Height)

        xPos = CInt(iPageWidth - g.MeasureString(strDate, fntPrice).Width) \ 2
        g.DrawString(strDate, fntPrice, Brushes.Black, xPos, yPos)
        yPos += 2 * iFntHeight
        g.DrawString("Product", fntPrice, Brushes.Black, 50, yPos)

        g.DrawString("Price", fntPrice, Brushes.Black, _
                New Rectangle(430, yPos, 100, 2 * iFntHeight), sf)

        yPos += iFntHeight
        g.DrawLine(Pens.Black, 0, yPos, iPageWidth, yPos)

        e.HasMorePages = True
        iTop = yPos

        For x = 0 To iLinesPerPage
            If iRecord < imax Then
                With ds.Tables("Products").Rows(iRecord)
                    strDescription = .Item("ProductName").ToString
                    strPrice = Convert.ToDecimal(.Item("UnitPrice")).ToString("c")
                End With
                Dim rName As New Rectangle(5, yPos, 400, iFntHeight)
                Dim rPrice As New Rectangle(430, yPos, 100, iFntHeight)

                g.DrawString(strDescription, fntPrice, Brushes.Black, rName)
                g.DrawString(strPrice, fntPrice, Brushes.Black, rPrice, sf)
            Else
                e.HasMorePages = False
            End If
            yPos += iFntHeight
            iRecord += 1
        Next
        fntTitle.Dispose()
        If e.HasMorePages = False Then iRecord = 0
    End Sub

    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Dim pc As New PdfPrintController
        pc.Title = "Test Pdf"
        pc.Author = "Ken Tucker"
        pc.FileName = "Test.pdf"
        p.PrintController = pc
        p.Print()
    End Sub
End Class



kick it on DotNetKicks.com

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: pdf | VB
Posted by Ken Tucker on Friday, April 04, 2008 2:07 PM
Permalink | Comments (0) | Post RSSRSS comment feed