vbdotnet.it

Tricks & tips, workaround, forum and ideas with .Net

About the author

Enrico Rossini è il gestore di questo blog.
E-mail me Send mail

Recent posts

Recent comments

Contributi

Best 6 ~ 6 users ~ 6 comments

Info legali

Le opinioni espresse in questo blog sono strettamente personali e ogni persona è responsabile dei commenti che inserisce. I marchi citati sono delle rispettive aziende.

© Copyright 2010

Advertising


Directory del programma

Ciao, questo è un semplice tricks. Molto spesso accade che si vuole sapere in quale directory gira il nostro programma. COn questa semplice riga lo si sa.

Private myFileName As String = System.Reflection.Assembly.GetExecutingAssembly().Location
myFileName = myFileName.Substring(0, myFileName.LastIndexOf("\"))

Attenzione. La funzione System.Reflection.Assembly.GetExecutingAssembly().Location restituisce anche il nome del file eseguibile. Per questo è stato necessario aggiungere la riga sottostante. Buon lavoro.

Be the first to rate this post

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

Posted by enrico on Tuesday, July 28, 2009 12:46 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Invio email con framework 3.5

Con il .NET framework 3.5 è stato introdotto un nuovo namespace Mail per l’invio delle email: questo namespace può essere aggiunto ai nostri programmi con la seguenti riga di codice:

Imports System.Net.Mail

L’invio dell’email può presentare qualche problema poiché non si trovano molti esempi su come inviare ad esempio degli allegati o ricevere una conferma di lettura. Nell’esempio che segue cercherò di rispondere a questi problemi.

Si supponga di avere un form con i seguenti textbox: txtTo per inserire l’email a cui spedire, txtSubject per inserire l’oggetto del messaggio, txtMessage per il corpo del messaggio e un listbox di nome lstAttachment per visualizzare l’elenco degli allegati. Un bottone per l’invio ed un checkbox per voler spedire il messaggio come HTML.

Dim objSmtpMail As System.Net.Mail.SmtpClient       ' variabile generale per l'invio dell'email
Dim Attachment As System.Net.Mail.Attachment        ' variabile per salvare gli allegati
Dim Mailmsg As New System.Net.Mail.MailMessage()    ' variabile per creare il corpo del messaggio
 
Private _displayname As String = ""                 ' variabile che contiene il nome dell'email da visualizzare
Private _from As String = ""                        ' variabile con l'indirizzo email da cui spedire
Private _smtpserver As String = ""                  ' variabile contenente l'indirizzo del server mail
 
Public Sub SendEmail()
   ' imposta le proprietà del server
   objSmtpMail = New System.Net.Mail.SmtpClient(_smtpserver)
 
   ' definisce il mittente 
   ' (primo parametro l'indirizzo email, secondo il nome che deve apparire all'utente che riceve l'email)
   Mailmsg.From = New System.Net.Mail.MailAddress(_from, _displayname)
 
   ' per specificare indirizzi multipli separare uno dall'altro con il ;
   Mailmsg.To.Add(New System.Net.Mail.MailAddress(Me.txtTo.Text.Trim))
 
   ' specifica formato
   If Me.tsbHTML.Checked = True Then
      ' spedisce l'email in formato HTML
      Mailmsg.IsBodyHtml = True
   Else
      Mailmsg.IsBodyHtml = False
   End If
 
   ' aggiunge degli header all'email che consentono di ricevere la conferma di lettura
   Mailmsg.Headers.Add("Reply-To", Mailmsg.From.Address)
   Mailmsg.Headers.Add("Disposition-Notification-To", Mailmsg.From.Address)
   Mailmsg.Headers.Add("Return-Receipt-To", Mailmsg.From.Address)
 
   ' aggiunge il testo
   Mailmsg.Subject = txtSubject.Text
   Mailmsg.Body = txtMessage.Text
 
   ' aggiunte gli allegati
   For Counter = 0 To lstAttachment.Items.Count - 1
      Attachment = New System.Net.Mail.Attachment(lstAttachment.Items(Counter))
      Mailmsg.Attachments.Add(Attachment)
   Next
 
   ' spedisce effettivamente l'email
   objSmtpMail.Send(Mailmsg)
End Sub

Spero vi sia utile. Ciao!

Be the first to rate this post

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

Posted by enrico on Tuesday, July 21, 2009 12:03 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Leggere un file Microsoft Excel 97/2003 o 2007

La funzione che presento oggi consente di importare un foglio di Microsoft Excel in un dataset nelle versioni 97, 2003 e 2007.

 

   1: ''' <summary>
   2: ''' Reads the data from excel.
   3: ''' </summary>
   4: ''' <param name="excelfilename">The excelfilename.</param>
   5: ''' <returns></returns>
   6: Function ReadDataFromExcel(ByVal excelfilename As String) As DataSet
   7:     Dim ds As New DataSet
   8:     Dim da As OleDbDataAdapter
   9:     Dim conn As OleDbConnection
  10:  
  11:     Try
  12:         If System.IO.Path.GetExtension(excelfilename) = ".xls" Then
  13:             conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & excelfilename & "; Extended Properties=Excel 8.0;")
  14:         ElseIf System.IO.Path.GetExtension(excelfilename) = ".xlsx" Then
  15:             conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & excelfilename & "; Extended Properties=Excel 8.0;")
  16:         End If
  17:  
  18:         da = New OleDbDataAdapter("SELECT * FROM [Foglio1$]", conn)
  19:  
  20:         conn.Open()
  21:         da.Fill(ds)
  22:     Catch ex As Exception
  23:         MsgBox(ex.Message)
  24:     Finally
  25:         If conn.State = ConnectionState.Open Then
  26:             conn.Close()
  27:         End If
  28:     End Try
  29:     ReadDataFromExcel = ds
  30: End Function

Buon lavoro e ricordatevi il nostro forum!

Be the first to rate this post

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

Posted by enrico on Tuesday, April 07, 2009 7:32 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Generazione di un nome di file temporaneo

Alle volte può essere necessario generate un file con un nome temporaneo. Per poter inventare un nome, esiste una funzione del namespace System.IO che fa al caso nostro.

Dim sTempFileName As String = System.IO.Path.GetRandomFileName

Ciao, a presto!

Currently rated 4.0 by 1 people

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

Posted by enrico on Friday, January 09, 2009 11:39 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Come conoscere l'ID della scheda madre?

Questa funzione consente di conoscere l’identificativo del processore montato sul PC. Per poter eseguire correttamente questa funzione è necessario importare il namespace System.Management

   1:  Imports System.Management
   2:   
   3:  Public Function GetMotherBoardID() As String
   4:     Dim strMotherBoardID As String = String.Empty
   5:     Dim query As New SelectQuery("Win32_BaseBoard")
   6:     Dim search As New ManagementObjectSearcher(query)
   7:   
   8:     For Each info As ManagementObject In search.Get()
   9:        strMotherBoardID = info("SerialNumber").ToString()
  10:     Next
  11:   
  12:     Return strMotherBoardID
  13:  End Function

È possibile modificare questa funzione e trovare altre informazioni sul sistema.

Currently rated 5.0 by 1 people

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

Posted by enrico on Sunday, December 28, 2008 10:57 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Come conoscere l'ID del processore?

Questa funzione consente di conoscere l’identificativo del processore montato sul PC. Per poter eseguire correttamente questa funzione è necessario importare il namespace System.Management

   1:  Imports System.Management
   2:   
   3:  Public Function GetProcessorId() As String
   4:     Dim strProcessorId As String = String.Empty
   5:     Dim query As New SelectQuery("Win32_processor")
   6:     Dim search As New ManagementObjectSearcher(query)
   7:   
   8:     For Each info As ManagementObject In search.Get()
   9:        strProcessorId = info("processorId").ToString()
  10:     Next
  11:   
  12:     Return strProcessorId
  13:  End Function

Questa funzione può essere modificata per conoscere altre informazioni sulla macchina.

Currently rated 5.0 by 1 people

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

Posted by enrico on Sunday, December 28, 2008 10:54 PM
Permalink | Comments (0) | Post RSSRSS comment feed

SQL: convert date in string

Come riuscire a convertire direttamente da SQL un valore datetime in una stringa nel formato voluto? Attraverso questo semplice comando e con la lista seguente è possibile scegliere il tipo di formato data che si vuole.

   1:  CONVERT(varchar, CampoData, 103) AS Valore

Tabella di conversioe

Senza il secolo (aa) Con il secolo (aaaa) Standard Input/Output

-

0 o 100

Valore predefinito

mes gg aaaa hh:miAM (o PM)

1

101

U.S.

mm/gg/aaaa

2

102

ANSI

aa.mm.gg

3

103

Inglese Regno Unito/Francese

gg/mm/aaaa

4

104

Tedesco

gg.mm.aa

5

105

Italiano

gg-mm-aa

6

106

-

gg mes aa

7

107

-

Mes gg, aa

8

108

-

hh:mi:ss

-

9 o 109

Valore predefinito + millisecondi

mes gg aaaa hh:mi:ss:mmmAM (o PM)

10

110

USA

mm-gg-aa

11

111

Giapponese

aa/mm/gg

12

112

ISO

aammgg

aaaammgg

-

13 o 113

Valore predefinito Europa + millisecondi

gg mes aaaa hh:mi:ss:mmm(24h)

14

114

-

hh:mi:ss:mmm(24h)

-

20 o 120

ODBC canonico

aaaa-mm-gg hh:mi:ss(24h)

-

21 o 121

ODBC canonico (con millisecondi)

aaaa-mm-gg hh:mi:ss.mmm(24h)

-

126

ISO8601

aaaa-mm-ggThh:mi:ss.mmm (senza spazi)

-

127

ISO8601 con fuso orario Z.

aaaa-mm-ggThh:mi:ss.mmmZ

(senza spazi)

-

130

Hijri

gg mes aaaa hh:mi:ss:mmmAM

-

131

Hijri

gg/mm/aa hh:mi:ss:mmmAM

 

Currently rated 5.0 by 1 people

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

Posted by enrico on Tuesday, November 11, 2008 5:22 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Eseguire un "group by" su un datatable con sommatoria

Ho ormai perso diverse ore per trovare un sistema per eseguire un "group by" o simili su un datatable questo perché ho estratto una query dal database con diverse righe doppie e non posso eseguire un raggruppamento direttamente sul database (ad esempio ho fatto delle union nello script SQL).

Attraverso questo codice riesco a creare un datatable raggruppando in un'unica riga le righe che hanno più righe su un campo A sommando i valori numerici B. dt è il datatable di partenza con ad esempio i dati ottenuti con una query sul database.

   1:  Dim dtAgg As DataTable = dt.Clone
   2:  dtAgg.PrimaryKey = New DataColumn() {dtAgg.Columns("A")}
   3:   
   4:  For I As Integer = 0 To dt.Rows.Count - 1
   5:     Dim dr As DataRow = dtAgg.Rows.Find(dt.Rows(I).Item("A"))
   6:     If IsNothing(dr) Then
   7:        dr = dtAgg.NewRow()
   8:        dr.Item("A") = dt.Rows(I).Item("A")
   9:        dr.Item("B") = dt.Rows(I).Item("B")
  10:        dtAgg.Rows.Add(dr)
  11:     Else
  12:        dr.Item("B") += dt.Rows(I).Item("B")
  13:     End If
  14:  Next

Ovviamente la personalizzazione del codice ti permetterà di risolvere problemi più complessi.

Currently rated 5.0 by 2 people

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

Posted by enrico on Monday, September 29, 2008 2:15 AM
Permalink | Comments (0) | Post RSSRSS comment feed