in

DotNetSide

Dot Net South Italy Developers User Group

Tips

VB.net

  • DataObjectAttribute e ObjectDataSource

    Autore: Mario Ferrante

    L’attributo DataObject rende più facile la ricerca delle classi che si vogliono legare ad un controllo DataBound durante la configurazione dell’ObjectDataSource.
    Quando si utilizza l’ObjectDataSource, la prima cosa che devo fare è scegliere l’oggetto Business da utilizzare per recuperare o gestire i dati e per legarli ad un controllo DataBound:

    Purtroppo se chiedo al wizard dell’ObjectDataSource di mostrarmi solo i “Data Components” (come in figura), la maggior parte delle volte il risultato che ottengo è un menù a discesa vuoto.
    Dunque non rimane che levare la spunta a “Show only data components” e cercare l’oggetto Business che mi interessa tra tutti quelli a cui è referenziata la mia applicazione, come si vede nella figura successiva.

     

    Poco male nel caso di piccole applicazioni, ma nel caso di applicazioni molto grandi o che comunque referenziano molti assemblies il problema diventa un po’ più serio.
    Ed è qui che viene in aiuto l’attributo DataObjectAttribute o semplicemente DataObject. Questo attributo può essere usato a livello di classe, ma anche a livello dei singoli metodi.

    L’Attributo DataObject a livello di classe
    Supponiamo che nella mia applicazione ho una classe che mi gestisce il CRUD (Create Retrieve Update e Delete) di News a cui aggiungo, a livello di classe, l’attributo DataObject:

     

     

    Imports System.ComponentModel Namespace Mario.DotNetSide <DataObject()> _ Public Class NewsManager 'Implementazione della Classe End Class End Namespace

     

    Il risultato sarà:

    Il costruttore dell’attributo DataObject accetta anche un parametro di tipo System.Boolean, se False dichiaro esplicitamente all’Object Data Source di non considerare quella classe come Data Component.
    L’Attributo DataObject a livello di metodo

    Abbiamo usato questo attributo a livello di Classe, ma lo posso utilizzare anche a livello di metodi per definire quali di essi devono essere utilizzati per selezionare i dati, quali per inserire un record, cancellarlo o modificarlo:

     

    <DataObject()> _ Public Class NewsManager <DataObjectMethod(DataObjectMethodType.Select, True)> _ Public Function GetNews() As NewsCollection End Function <DataObjectMethod(DataObjectMethodType.Insert, True)> _ Public Function AddNews(ByVal item As News) As Integer End Function End Class

    I valori dell’enumerazione DataObjectMethodType sono autoesplicativi:

    • Delete
    • Fill
    • Insert
    • Select
    • Update

    Il secondo parametro booleano passato all’attributo (True in questo caso) indica all Object Data Source se considerare (True) o meno (False) quel metodo per una determinata funzione (ad esempio di Select).
    In .Net gli attributi hanno una fondamentale importanza, essi contribuiscono a fornire tutte quelle informazioni che costituiscono i MetaData di un’assembly. Inoltre possono influenzare il comportamento di un oggetto sia a run-time sia (come in questo caso) a design-time.

  • Convertire HTML in Testo

    Autore: Stefano De Mattia

    Quella che segue è una funzione che converte una stringa HTML in una di testo semplice.

    Sono necessari i seguenti Imports:

    Imports System.Text
    Imports System.Text.RegularExpressions

    Il codice della funzione:

    ''' <summary>
    '
    '' Funzione che converte una stringa HTML in una di testo semplice
    '
    '' </summary>
    '
    '' <param name="html">Stringa da convertire</param>
    '
    '' <returns>Stinga semplice</returns>
    '
    '' <remarks></remarks>
    Function Html2Text(ByVal html As String) As String
    ' pattern per la rimozione dei tag HTML
    Dim pattern As String = "\<[^\>]*\>"
    Dim re As New Regex(pattern, RegexOptions.IgnoreCase)

    'qui posso modificare la formattazione sui
    'tag che mi interessano, prima di eliminarli ad esempio
    'html = html.Replace("<p>", vbCrLf)
    'html = html.Replace("<\p>", vbCrLf & vbCrLf)
    'html = html.Replace("&nbsp;", " ")
    html = html.Replace("<br />", vbCrLf)

    'applico l'espressione regolare,
    'sostituendo i caratteri speciali con la stringa vuota
    html = re.Replace(html, String.Empty)

    Return html

    End Function
    Posted Oct 31 2006, 11:53 AM by VitoA with 2 comment(s)
    Filed under: ,
  • Leggere il sorgente di una pagina html

    Autore: Vito Arconzo

    Ecco una funzione che restituisce il codice HTML di una pagina web.
     

    1        Function GetHtmlPageSource(ByVal url As String, _
    2                Optional ByVal username As String = Nothing, _
    3                Optional ByVal password As String = Nothing) As String
    4            Dim st As System.IO.Stream
    5            Dim sr As System.IO.StreamReader
    6    
    7            Try
    8                ' invia una Web request
    9                Dim req As System.Net.WebRequest = System.Net.WebRequest.Create(url)
    10   
    11               ' se sono specificati username/password usa le credenziali
    12               If Not username Is Nothing AndAlso Not password Is Nothing Then
    13                   req.Credentials = New System.Net.NetworkCredential(username, password)
    14               End If
    15   
    16               ' ricava la risposta e legge lo stream coi risultati
    17               Dim resp As System.Net.WebResponse = req.GetResponse
    18               st = resp.GetResponseStream
    19               sr = New System.IO.StreamReader(st)
    20   
    21               Return sr.ReadToEnd
    22           Catch ex As Exception
    23               Return ""
    24           Finally
    25               sr.Close()
    26               st.Close()
    27           End Try
    28       End Function
    
     
    Posted Jun 30 2006, 11:55 AM by VitoA with no comments
    Filed under:
  • Verificare se un anno è bisestile

    Autore: Vito Arconzo

    Spesso è necessario conoscere se un anno sia bisestile.
    Con VB.NET è molto semplice in quanto, il problema, è stato risolto alla fonte: è fornito un opportuno metodo, IsLeapYear, che accetta in input un valore intero (l'anno) e restituisce un valore booleano (True = bisestile, False = non bisestile).

    Per provare questa funzione, creare una form, aggiungere due TextBox di nome rispettivamente TextBox1 e TextBox2 ed un pulsante e infine, nell'evento Click del pulsante inserire il seguente codice:

     
    1      If TextBox1.Text = "" Then
    2 TextBox2.Text = "anno non indicato"
    3 Else
    4 If
    (DateTime.IsLeapYear(Integer.Parse(TextBox1.Text)) = True) Then
    5 TextBox2.Text = "Anno " & TextBox1.Text & " bisestile."
    6 Else
    7 TextBox2.Text = "Anno " & TextBox1.Text & " NON bisestile."
    8 End If
    9 End If

     
    Posted Jun 22 2006, 11:28 AM by VitoA with no comments
    Filed under:
  • Verificare se l'applicazione è già in esecuzione

    Autore: Fabio Cozzolino

    Verificare se l'applicazione è già in esecuzione

    Spesso mi viene chiesto: come posso fare per verificare se il mio programma è già in esecuzione?

    Una possibile soluzione è l'utilizzo della classe Mutex del namespace System.Threading. Mutex verifica che in esecuzione esista un unico thread in base al nome passato come parametro stringa.

    Un esempio in Visual Basic .NET:

    1    Private Shared m As Mutex
    2
    3 Private Shared Sub Main()
    4 Dim first As Boolean
    5
    6 m = New Mutex(true, Application.ProductName, first)
    7 if (first) then
    8 Application.Run(new MainForm())
    9 m.ReleaseMutex()
    10 else
    11 MessageBox.Show("Applicazione già in esecuzione")
    12 end if
    13 End Sub
     
    Posted Jun 21 2006, 10:16 AM by VitoA with no comments
    Filed under:
  • Invertire una stringa

    Autore: Vito Arconzo

    Questa funzione restituisce la stringa passata come parametro invertita.

    1    Public Function ReverseString(ByVal stringToReverse As String) As String
    2 ' dichiarazione variabili

    3 Dim s As String = ""
    4 Dim lunghezza As Integer = 0
    5 If stringToReverse = "" Then
    6 ' se stringa vuota restituiscila
    7 s = ""
    8 Else
    9 ' altrimenti esegui l'inversione della stringa
    10 lunghezza = stringToReverse.Length
    11 For i As Integer = (lunghezza - 1) To 0 Step -1
    12 s = String.Concat(s, stringToReverse.Substring(i, 1))
    13 Next
    14 End If
    15 Return
    (s)
    16 End Function
     
    Posted Jun 09 2006, 09:55 AM by VitoA with 1 comment(s)
    Filed under:
  • Utilizzo ANSI Jolly in SQL

    Autore: Vito Arconzo

    Se siamo abituati ad utilizzare caratteri jolly ANSI (* e ?), questa funzione converte il caratteri jolly SQL (% e _), quindi, in ANSI.

        Public Function AnsiJolly(ByVal Value As String) As String
            If (Value Is Nothing) Then
                Return String.Empty
            End If

            Value = Value.Replace("*", "%")
            Return Value.Replace("?", "_")
        End Function

    Posted Jun 03 2006, 09:49 AM by VitoA with 3 comment(s)
    Filed under:
  • Convertire una stringa in una DataTable

    Autore: Vito Arconzo

    Questa utilissima funzione permette la conversione di una stringa contenente valori separati da un carattere in  DataTable.

        Public Function StringToTable(ByVal value As String, ByVal delimiter As Char) As DataTable
            Dim table As DataTable = New DataTable
            table.Rows.Clear()
            table.Columns.Clear()
            table.Columns.Add("Value", GetType(String))

            If ((Not value Is Nothing) AndAlso (value.Length > 0)) Then
                Dim text1 As String
                For Each text1 In value.Split(New Char() {delimiter})
                    Dim objArray1 As Object() = New Object() {text1}
                    table.Rows.Add(objArray1)
                Next
            End If

            table.AcceptChanges()
            table = Nothing
            Return table
        End Function

    Posted Jun 03 2006, 01:35 AM by VitoA with 3 comment(s)
    Filed under:
Powered by Community Server (Commercial Edition), by Telligent Systems