News



Locations of visitors to this page

January 2008 Entries

Send e-mail with attachment from database image column (sql server 2k5)


Soooo...I needed to get files out of my SQL Server table (which has the files in an image column) and attach them to an email to send out.  I honestly thought this would be a no-brainer but turned out it was pretty finicky.  Anyway...the code to so is below just in case anyone is wondering.

    Function SendEmail()

        'Get your data (filename, content type, image column) from the db

        Dim dt As DataTable = GetYourStuff()

 

        If dt.Rows.Count <= 0 Then Return Nothing

 

        Dim msg As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()

        msg.Subject = "Sample Message"

        msg.To.Add(New System.Net.Mail.MailAddress("Receiver@yourDomain.com"))

        Dim fromadx As New System.Net.Mail.MailAddress("Sender@yourDomain.com", "Sender Name")

        msg.From = fromadx

        msg.IsBodyHtml = False

        msg.Body = "Sample body..."

 

        Dim strMem As System.IO.MemoryStream = New System.IO.MemoryStream(CType(dt.Rows(0)("ImageColumn"), Byte()))

        Dim strWriter As System.IO.StreamWriter = New System.IO.StreamWriter(strMem)

        strWriter.Flush()

 

        'this is very important..wont work without it

        strMem.Position = 0

 

        'Filename and content type are hardcoded here, but I assume you get them from GetYourStuff() above

        Dim attachment As System.Net.Mail.Attachment = New System.Net.Mail.Attachment(strMem, "myFile.txt", "text/plain")

        msg.Attachments.Add(attachment)

        Dim smtpClient As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings.Item("smtpserver"), 25)

        smtpClient.Send(msg)

    End Function

posted @ Thursday, January 31, 2008 4:44 PM | Feedback (0) | Filed Under [ VB.NET ]


Alternatives to FindControl()?


Alright, as much as I try to avoid using FindControl() sometimes I need to get a control by its ID.  I came across what seems like a good idea here : http://www.thescripts.com/forum/thread269592.html

It's in C#, but here is the VB.NET adaptation...

  549     Private Sub BuildControlHashTable()

  550         Dim cName As String = String.Empty

  551         For i As Int16 = 0 To Me.Controls.Count - 1

  552             cName = Me.Controls(i).ID

  553             If Not (cName Is Nothing) Then

  554                 cntrlHashTbl.Add(cName, Me.Controls(i))

  555             End If

  556         Next

  557     End Sub

  558     Private Function GetControlByName(ByVal cntrlName As String) As Control

  559         Return CType(Me.cntrlHashTbl(cntrlName), Control)

  560     End Function


Good idea? Bad idea? Thoughts?


posted @ Thursday, January 24, 2008 12:55 PM | Feedback (1) | Filed Under [ Developing & Best Practices VB.NET ]