Comment puis-je améliorer mon code?

Résolu
XGuarden Messages postés 259 Date d'inscription dimanche 14 juillet 2002 Statut Membre Dernière intervention 17 août 2012 - 8 nov. 2006 à 04:23
narfix Messages postés 3 Date d'inscription lundi 19 juin 2006 Statut Membre Dernière intervention 8 novembre 2006 - 8 nov. 2006 à 14:28
Bonjour, je suis en trein de créer un énorme template pour vbfrance comme stateur de projet.
Je crois que sa va etre utile.

Mais je désire coder en respectant le plus haut niveau de normalisation et de standardisation posible.

Voici une parti du code, merci de me dire si vous trouver des améliorations posibles.
Chose importante.
-Standart
-Maniere de nommer variable
-vitesse d'exécution
-Beauté du code
-Toujours utiliser la maniere corecte de faire une chose(ne pas faire de code non réfléchit)

Merci à l'avance, ce projet me permet d'améliorer grandement ma technique de programmation.

CODE:

Imports System.IO
Imports System.Threading
Public Class MainForm
    Private crpSample As SampleCrypto
    Private formHasLoaded As Boolean
    Private strCurrentKeyFile As String
    Private strRijndaelSaltIVFile As String
    Private strSourcePath As String
    Private txtContent As New TextBox

 

    ''' <summary>
    ''' This routine handles the "Load" button click event.
    ''' </summary>

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Select Case Mid(DirectCast(sender, Button).ToString, 36)

            'Case btnPanelAjout.Text
            '    btnPanelSupprimer.Enabled = False
            '    activepanel = "ajout"
            '    PanelAjout.BringToFront()

            Case btnValider.Text

            Case Else
                MsgBox("Un bouton on géré a été cliqué")

        End Select

    End Sub

    Private Sub Click_AjouterCompte(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnValider.Click

        Try
            ' Vérifier que les informations entrées sont valide.
            VérifierInformations()
            ' Obtenir la liste des droits.
            Dim droits As String = infodroits()
            SBP_info.Text = Nothing

            Select Case btnValider.Text

                Case "Ajouter"
                    Dim listViewItemX As New ListViewItem(New String() {txtTitre.Text, txtlogin.Text, mtxtPassword.Text, droits, txtCommentaire.Text})
                    ListView1.Items.AddRange(New ListViewItem() {listViewItemX})

                Case "Modifier"

                    With ListView1.FocusedItem
                        .SubItems(0).Text = txtTitre.Text
                        .SubItems(1).Text = txtlogin.Text
                        .SubItems(2).Text = mtxtPassword.Text
                        .SubItems(3).Text = droits
                        .SubItems(4).Text = txtCommentaire.Text
                    End With

                Case Else
                    Throw New Exception("La propriété text de btnValider n'est pas valide")

            End Select

            ' Retourner à l'Affichage de la liste des accès.
            TabControl1.SelectedIndex = 0

        Catch exp As Exception
            MsgBox(exp.Message)

            Try

                For Each mycontrol As Control In TableLayoutPanelInfo.Controls
                    mycontrol.BackColor = SystemColors.Window
                Next mycontrol

            Catch subexp As Exception
                MsgBox(subexp.Message)
            End Try

        End Try
    End Sub

    Private Sub Click_SupprimerCompte(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSupprimer.Click
        If ListView1.Focused = True Then
            ListView1.FocusedItem.Remove()
        Else
            MsgBox("Selectionner d'habord un compte")
        End If
    End Sub

    Private Function decrypter() As Boolean
        Try
            If IsValid() Then
                With crpSample
                    .SaltIVFile = strCurrentKeyFile
                    .Password = TSlblPassword.Text
                End With

                crpSample.SourceFileName = strSourcePath

                crpSample.DecryptFile()

                txtContent.Text = My.Computer.FileSystem.ReadAllText(strSourcePath)
            Else
                Return False
            End If

            Return True

        Catch expCrypto As Security.Cryptography.CryptographicException
            MsgBox("The file could not be decrypted. Make sure you entered " & _
                "the correct password. " & vbCrLf & "This error can also be caused by changing " & _
                "crypto type between encryption and decryption.", _
                MsgBoxStyle.Critical, Me.Text)
            Return False
        End Try
    End Function

    ''' <summary>
    ''' This routine handles the "Encrypt" and "Decrypt" button click events.
    ''' </summary>
    Private Sub emcrypter()

        Try
            If IsValid() Then
                With crpSample
                    .SaltIVFile = strCurrentKeyFile
                    .Password = TSlblPassword.Text
                End With

                crpSample.SourceFileName = strSourcePath

                crpSample.EncryptFile()

                txtContent.Text = My.Computer.FileSystem.ReadAllText(strSourcePath)
            End If

        Catch expCrypto As Security.Cryptography.CryptographicException
            MsgBox("The file could not be decrypted. Make sure you entered " & _
                "the correct password. " & vbCrLf & "This error can also be caused by changing " & _
                "crypto type between encryption and decryption.", _
                MsgBoxStyle.Critical, Me.Text)
        Catch exp As Exception
            MsgBox(exp.Message, MsgBoxStyle.Critical, Me.Text)
        End Try
    End Sub

    ''' <summary>
    ''' This routine handles the Form's Load event, setting up the sample.
    ''' </summary>
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' Set the default crypto type.
        crpSample = New SampleCrypto("Rijndael")

        ' Set the path to save the key file to the Solution root folder by stripping
        ' "bin" from the current directory.
        Dim currentDirectory As String = My.Application.Info.DirectoryPath

        ' Initialize paths for both types of key files.
        strRijndaelSaltIVFile = currentDirectory & "RijndaelSaltIV.dat"

        ' Set the current key file path to the key for default crypto type.
        strCurrentKeyFile = strRijndaelSaltIVFile

        formHasLoaded = True
    End Sub

    ''' <summary>
    ''' This routine validates all data entry.
    ''' </summary>
    Private Function IsValid() As Boolean
        If Not PasswordIsValid() Then
            Return False
        End If

        If Len(strSourcePath) = 0 Then
            MsgBox("Vous devez d'habord charger un doccument valide!", MsgBoxStyle.Exclamation, Me.Text)
            Return False
        End If

        Return True
    End Function

    ''' <summary>
    ''' This routine validates the password.
    ''' </summary>
    Private Function PasswordIsValid() As Boolean
        If Not System.Text.RegularExpressions.Regex.IsMatch(txtPassword.Text, "^\s*(\w){8}\s*$") Then
            MsgBox("Vous devex entrer un mot de passe contenant de 8 caracteres constituer de nombre " & _
                "et/ou de lettre.", MsgBoxStyle.Exclamation, Me.Text)
            Return False
        End If

        Return True
    End Function

    Private Overloads Sub ChargementUtilisateurs(ByRef MyListView As ListView, ByRef MyTextBox As TextBox)

        MyTextBox.Text = "Valide" & vbCrLf

        For ligne As Integer = 0 To MyListView.Items.Count - 1
            With MyListView.Items.Item(ligne)
                MyTextBox.Text += String.Join("/", New String() {.SubItems(0).Text(), .SubItems(1).Text(), .SubItems(2).Text(), .SubItems(3).Text(), .SubItems(4).Text()}) & vbCrLf
            End With
        Next

        MyTextBox.Text.Remove(MyTextBox.Text.Length - 3)
        MyListView.Items.Clear()
    End Sub

    Private Overloads Sub ChargementUtilisateurs(ByRef MyTextBox As TextBox, ByRef MyListView As ListView)

        ' Enleverles éléments déja présent.
        MyListView.Items.Clear()

        'Comment faire pour que la boucle ne fasse pas la premiere ligne ou bien
        'Comment effacer la premiere ligne de MyTextBox
        For Each Line As String In MyTextBox.Lines
            MyListView.Items.Add(New ListViewItem(Split(Line, "/")))
        Next

        MyTextBox.Clear()
    End Sub

#Region "Procédure with Handles Click_ModifierCompte()"

    ' Handles ListView1.MouseDoubleClick.
    Private Sub Click_ModifierCompte(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseDoubleClick

        ' Sélectionner la page de modification.
        TabControl1.SelectedIndex = 1

        ' Charger les informations du formulaire.
        With ListView1.FocusedItem
            txtTitre.Text = .SubItems(0).Text
            txtlogin.Text = .SubItems(1).Text
            mtxtPassword.Text = .SubItems(2).Text
            mtxtCPassword.Text = .SubItems(2).Text
            infodroits() = .SubItems(3).Text.ToCharArray
            txtCommentaire.Text = .SubItems(4).Text
        End With

        ' Modifier le texte du bouton de validation.
        btnValider.Text = "Modifier"

    End Sub

#End Region ' Chargement des informations du compte à modifier.

#Region "Procédure with Handles EffacerInformations() "

    ' Handles: TabControl1.SelectedIndexChanged.
    Private Sub EffacerInformations(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        If TabControl1.SelectedIndex = 0 Then
            txtTitre.Text = Nothing
            txtlogin.Text = Nothing
            mtxtPassword.Text = Nothing
            mtxtCPassword.Text = Nothing
            txtCommentaire.Text = Nothing

            ChkPG.Checked = False
            ChkPR.Checked = False
            ChkPD.Checked = False

            ChkDL.Checked = False
            ChkDE.Checked = False
            ChkDM.Checked = False
            ChkDS.Checked = False
        ElseIf TabControl1.SelectedIndex = 1 Then
            btnValider.Text = "Ajouter"
        End If
    End Sub

#End Region ' Effacer les informations du formulaire de d'ajouts et modifications.

#Region "Propriété infodroits()          "

    ' Appelant(Get/Set): btnValider.Click / ListView1.MouseDoubleClick.
    Private Property infodroits() As String
        Get
            Dim droits As String = Nothing
            droits +IIf(ChkPG.Checked True, "G", "_").ToString            droits +IIf(ChkPR.Checked True, "R", "_").ToString            droits +IIf(ChkDL.Checked True, "L", "_").ToString            droits +IIf(ChkDE.Checked True, "E", "_").ToString            droits +IIf(ChkDM.Checked True, "M", "_").ToString            droits +IIf(ChkDS.Checked True, "S", "_").ToString            droits +IIf(ChkPD.Checked True, "D", "_").ToString

            If droits = "_______" Then
                Throw New Exception("Aucun privilège ou droit sélectionner")
            End If

            Return droits
        End Get
        Set(ByVal strDroits As String)
            Dim droits() As Char = strDroits.ToCharArray
            Dim validchar() As Char = "GRLEMSD".ToCharArray

            Try
                ChkPG.Checked CBool(IIf(droits(0) validchar(0), True, False))                ChkPR.Checked CBool(IIf(droits(1) validchar(1), True, False))                ChkDL.Checked CBool(IIf(droits(2) validchar(2), True, False))                ChkDE.Checked CBool(IIf(droits(3) validchar(3), True, False))                ChkDM.Checked CBool(IIf(droits(4) validchar(4), True, False))                ChkDS.Checked CBool(IIf(droits(5) validchar(5), True, False))                ChkPD.Checked CBool(IIf(droits(6) validchar(6), True, False))

                For i As Integer = 0 To 6
                    If droits(i) <> "_" AndAlso droits(i) <> validchar(i) Then
                        SBP_info.Text = "Une donnée non conforme a été trouvé dans le format des droits de cette utilisateur"
                        Exit For
                    End If
                Next

            Catch Exp As Exception
                Throw New Exception(Exp.Message)

            End Try

        End Set
    End Property

#End Region ' Obtenir et définir la propriété des droits.

#Region "Procédure VérifierInformations()"

    ' Appelant: btnValider.Click.
    Private Sub VérifierInformations()

        If Len(txtTitre.Text) = 0 Then
            txtTitre.BackColor = Color.Red
            Throw New Exception("Vous devez entrer un titre valide")
        End If

        For i As Integer = 0 To ListView1.Items.Count - 1
            If ListView1.Items(i).Text = txtTitre.Text AndAlso ListView1.FocusedItem.Index <> i Then
                Throw New Exception("Imposible d'ajouter un utilisateur déja existant")
            End If
        Next

        If Len(txtlogin.Text) = 0 Then
            txtlogin.BackColor = Color.Red
            Throw New Exception("Vous devez entrer un login valide")
        End If

        If Len(mtxtPassword.Text) = 0 Then
            mtxtPassword.BackColor = Color.Red
            Throw New Exception("Vous devez entrer un mot de passe")
        End If

        If mtxtPassword.Text <> mtxtCPassword.Text Then
            mtxtPassword.BackColor = Color.Red
            mtxtCPassword.BackColor = Color.Red
            Throw New Exception("Mot de passe incorecte")
        End If

    End Sub

#End Region ' Vérifier les informations entrées.

    Private Sub ToolStripButtonSauvegarder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonSauvegarder.Click
        With odlgSelectFile
            .InitialDirectory = "C:"
            ' The file could be of any type. The Filter is restricted to psw Format
            ' files only for demonstration purposes.
            If Len(txtPassword.Text) = 0 Then
                .Filter = "Password format (*.psw)|*.psw"
            Else
                .Filter = "Encrypted Password format (*.epw)|*.epw"
            End If

            .FilterIndex = 1

            ' The OpenFileDialog control only has an Open button, not an OK button.
            ' However, there is no DialogResult.Open enum so use DialogResult.OK.
            If .ShowDialog() = Windows.Forms.DialogResult.OK Then
                Try
                    txtContent.Text = _
                       My.Computer.FileSystem.ReadAllText((.FileName))
                    strSourcePath = .FileName

                    Select Case Len(txtPassword.Text)

                        Case 8
                            If decrypter() = True Then
                                ChargementUtilisateurs(txtContent, ListView1)
                            End If

                        Case 0
                            ChargementUtilisateurs(txtContent, ListView1)

                        Case Else
                            Throw New Exception("Format de fichier invalide")

                    End Select

                Catch exp As ArgumentException
                    MsgBox(exp.Message, MsgBoxStyle.Critical)
                End Try
            End If
        End With

    End Sub

    Private Sub ToolStripButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton2.Click
        Try
            If PasswordIsValid() Then
                crpSample.Password = txtPassword.Text
            Else
                Exit Sub
            End If

            If crpSample.CreateSaltIVFile(strCurrentKeyFile) Then
                MsgBox("Salt and IV successfully generated and saved to a .dat " & vbCrLf & _
                    "file in the Visual Studio .NET Solution root folder.", _
                    MsgBoxStyle.Information, Me.Text)
            End If

            ChargementUtilisateurs(ListView1, txtContent)
            emcrypter()

        Catch exp As Exception
            MsgBox(exp.Message, MsgBoxStyle.Critical, Me.Text)
        End Try
    End Sub

End Class

7 réponses

NHenry Messages postés 15113 Date d'inscription vendredi 14 mars 2003 Statut Modérateur Dernière intervention 22 avril 2024 159
8 nov. 2006 à 12:47
Bonjour

En ce qui me concerne, les variables locales commencent par un "l", les attributs par un "m" et les attributs shared pas "ms".


Sinon, pour la remarque de Drikce06, je le suis completement, préfère (c'est la convention que j'utilise) :

Cmd pour les boutons

Txt pour les Textbox

Pict Picturebox

LV ListView

TV TreeView

Cmb ComboBox

Lst Liste

T Timers

...


Par exemple CmdOK, c'est un bouton de validation

TxtPassWd, c'est une textbox pour un mdp.

Il est plus facile de batiser quelqu'un que de la convertir. (surtout en programmation)
NHenry (VB6, VBA excel, VB.NET, C++, C#.Net)

<fon></fon>
3
narfix Messages postés 3 Date d'inscription lundi 19 juin 2006 Statut Membre Dernière intervention 8 novembre 2006
8 nov. 2006 à 14:28
Pour info / référence, la notation hongroise : http://fr.wikipedia.org/wiki/Notation_hongroise
(La page anglaise correspondante est beaucoup plus fournie.)
Il est rare de voir ces règles appliquées à 100% partout.
3
drikce06 Messages postés 2236 Date d'inscription lundi 29 mai 2006 Statut Membre Dernière intervention 29 mai 2008 10
8 nov. 2006 à 10:26
Salut, j'ai parcourus ton code rapidement et comme c'est juste une petite remarque sur le code du style "beauté du code" je pense qu'il serai bien de nommer tes controles de maniere à ce qu'on sache ce qu'ils font lors de la lecture des évènements par exemple button4_click! Voilà juste ça pour moi sinon le code est assez claire à lecture.

 Drikce 06
0
XGuarden Messages postés 259 Date d'inscription dimanche 14 juillet 2002 Statut Membre Dernière intervention 17 août 2012
8 nov. 2006 à 13:13
A tu un lien qui fait la liste des conventions?
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
drikce06 Messages postés 2236 Date d'inscription lundi 29 mai 2006 Statut Membre Dernière intervention 29 mai 2008 10
8 nov. 2006 à 13:26
Il n'y a pas vraiment de convention chaque programmeur à sa convention ! Généralement pour les controles c'est comme l'a dit Nhenry. Pour les Variables:
String StrNomVariable
Single SngNomVariable
Double DblNomVariable
Integer IntNomVariable....etc

 Drikce 06
0
NHenry Messages postés 15113 Date d'inscription vendredi 14 mars 2003 Statut Modérateur Dernière intervention 22 avril 2024 159
8 nov. 2006 à 13:27
Bonjour

Non désolé.


Regarde les sources des leaders de VBFrance (et des autres sites, les conventions sont souent les même).


Tu y trouvera souvent des mises en page et des conventions similaires.

Il est plus facile de batiser quelqu'un que de la convertir. (surtout en programmation)
NHenry (VB6, VBA excel, VB.NET, C++, C#.Net)

<fon></fon>
0
drikce06 Messages postés 2236 Date d'inscription lundi 29 mai 2006 Statut Membre Dernière intervention 29 mai 2008 10
8 nov. 2006 à 13:47
Ce que je veux dire c'est qu'il n'y a pas vraiment de règles de programmation, ceux sont les programmeurs qui entre eux ont pris la même façon de programmer mais celle-ci peut changer de l'un à l'autre. Il y a déjà eu d'autre topic la-dessus sans réponse précise juste les habitudes des uns et des autres!

 Drikce 06
0
Rejoignez-nous