Data Cogs Information Technology

posts - 131, comments - 251, trackbacks - 36

General

Search This Site

Powered by Google

Brisbane

Locations of visitors to this page

Information

Archives

Images

Blogs

CV etc.

Links For Me

Some answers to student questions from the ASP.NET course I am teaching this week

1.  Writing out to a text file_______________________________________________

Dim cn As New SqlConnection("Server=(local);Database=Northwind;Trusted_Connection=true")
Dim cmd As New SqlCommand("select * from customers where customerid = 'alfki'", cn)
Dim dr As SqlDataReader
cn.Open()
dr = cmd.ExecuteReader()
Dim fileName As String
fileName = "C:\inetpub\wwwroot\Demos\Export\" & DateTime.Now.ToString("ddMMyyyyHHmmss") & ".txt"
Dim sw As New StreamWriter(fileName, False)

While dr.Read
     Dim i As Integer
    
For i = 0 To dr.FieldCount - 1
          sw.WriteLine(dr(i))
     Next
End While

sw.Close()
cn.Close()

File.Copy(fileName, \\Brisbane\c$\test.txt)

2.  Simple Web Server Control________________________________________________

Imports System.ComponentModel
Imports System.Web.UI
Imports System.Web.UI.WebControls

Public Class DatePicker
    Inherits System.Web.UI.WebControls.WebControl

    'First declare the Child Controls required in the Control
    Dim ddDay As New DropDownList()
    Dim ddMonth As New DropDownList()
    Dim ddYear As New DropDownList()

    Property CalDate() As Date
        Get
            EnsureChildControls()
            Dim dt As Date = DateSerial(ddYear.SelectedItem.Value, ddMonth.SelectedItem.Value, ddDay.SelectedItem.Value)
            Return dt
        End Get

        Set(ByVal Value As Date)
            EnsureChildControls()
            ddDay.SelectedIndex = _
                ddDay.Items.IndexOf(ddDay.Items.FindByValue(Value.Day.ToString()))
            ddMonth.SelectedIndex = _
                ddMonth.Items.IndexOf(ddMonth.Items.FindByValue(Value.Month.ToString()))
            ddYear.SelectedIndex = _
                ddYear.Items.IndexOf(ddYear.Items.FindByValue(Value.Year.ToString()))
        End Set
    End Property

    Protected Overrides Sub CreateChildControls()
        ddDay.ID = "ddDay"
        Dim i As Integer
        For i = 1 To 31
            ddDay.Items.Add(New ListItem(i, i))
        Next

        ddMonth.ID = "ddMonth"
        For i = 1 To 12
            Dim d As Date
            d = DateSerial(Date.Now.Year, i, 1)
            ddMonth.Items.Add(New ListItem(d.ToString("MMM"), i))
        Next

        ddYear.ID = "ddYear"
        For i = Date.Now.Year To Date.Now.Year + 10
            ddYear.Items.Add(New ListItem(i, i))
        Next

        Controls.Add(ddDay)
        Controls.Add(ddMonth)
        Controls.Add(ddYear)
    End Sub
End Class

3.  Listing Available Printers____________________________________________

Dim printerName As String
For Each printerName In pd.PrinterSettings.InstalledPrinters
      lstPrinters.Items.Add(printerName)
Next

4.  Printing a Text File________________________________________________


Dim WithEvents pd As New Printing.PrintDocument()
Dim fileToPrint As StreamReader

Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Dim printPath As String = "C:\inetpub\wwwroot\Demos\Export\Export.txt"
        fileToPrint = New StreamReader(printPath)
        printFont = New System.Drawing.Font("Arial", 10)
        pd.PrinterSettings.PrinterName = "Canon LBP-1000PS"
        pd.Print()
        fileToPrint.Close()
End Sub

Private Sub pd_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles pd.PrintPage
        Dim yPos As Double = 0
        Dim count As Integer = 0
        Dim leftMargin As Double = e.MarginBounds.Left
        Dim topMargin As Double = e.MarginBounds.Top
        Dim line As String
        Dim linesPerPage As Double = e.MarginBounds.Height / printFont.GetHeight(e.Graphics)

        Do While count < linesPerPage
            line = fileToPrint.ReadLine()
            If line Is Nothing Then
                Exit Do
            End If
            yPos = topMargin + count * printFont.GetHeight(e.Graphics)
            e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, New StringFormat())
            count += 1
        Loop

        If Not line Is Nothing Then
            e.HasMorePages = True
        End If

End Sub

4.  Routing a file_________________________________________________

Dim strRequest As String = TextBox1.Text
        '-- if something was passed to the file querystring 

        'get absolute path of the file   
        ' Dim path As String = Server.MapPath(strRequest)
        Dim path As String = TextBox1.Text
        'get file object as FileInfo   
        Dim file As System.IO.FileInfo = New System.IO.FileInfo(path)
        '-- if the file exists on the server   
        If file.Exists Then
            'set appropriate headers    
            Response.Clear()
            Response.AddHeader("Content-Disposition", "attachment; filename=" & file.Name)
            Response.AddHeader("Content-Length", file.Length.ToString())
            Response.ContentType = "application/octet-stream"
            Response.WriteFile(file.FullName)
            Response.End()
            'if file does not exist   
        Else
            Response.Write("This file does not exist.")
        End If

5.  Cache Dependency________________________________________________

Put this code in the global.asax:

 Shared _cache As System.Web.Caching.Cache

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        _cache = HttpContext.Current.Cache
        LoadFile(Nothing, Nothing, 0)
    End Sub

    Shared Sub LoadFile(ByVal key As String, ByVal value As Object, ByVal reason As CacheItemRemovedReason)
        Dim ds As New DataSet()
      
        ds.ReadXml("c:\inetpub\wwwroot\demos\pubs.xml")
        _cache.Insert("pubslist", _
                ds, _
                New CacheDependency("c:\inetpub\wwwroot\demos\pubs.xml"), _
                Cache.NoAbsoluteExpiration, _
                Cache.NoSlidingExpiration, _
                CacheItemPriority.Default, _
                New CacheItemRemovedCallback(AddressOf LoadFile))
    End Sub

Put this code in any page that accesses the cached item (in this case a dataset)

Dim ds As New DataSet()
ds = Cache("pubslist")

DataGrid1.DataSource = ds
DataGrid1.DataBind()

posted on Tuesday, February 01, 2005 1:04 PM

Feedback

No comments posted yet.

Post Comment

Title  
Name  
Url
Comment   
Protected by Clearscreen.SharpHIPEnter the code you see: