XGuarden
Messages postés259Date d'inscriptiondimanche 14 juillet 2002StatutMembreDernière intervention17 août 2012
-
8 nov. 2006 à 04:23
narfix
Messages postés3Date d'inscriptionlundi 19 juin 2006StatutMembreDerniè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 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)
'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
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.
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
narfix
Messages postés3Date d'inscriptionlundi 19 juin 2006StatutMembreDerniè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.
drikce06
Messages postés2236Date d'inscriptionlundi 29 mai 2006StatutMembreDernière intervention29 mai 200810 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.
drikce06
Messages postés2236Date d'inscriptionlundi 29 mai 2006StatutMembreDernière intervention29 mai 200810 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
drikce06
Messages postés2236Date d'inscriptionlundi 29 mai 2006StatutMembreDernière intervention29 mai 200810 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!