IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

Barre de progression et MVC


Sujet :

C#

  1. #1
    Membre expert
    Profil pro
    Dév
    Inscrit en
    Juin 2007
    Messages
    1 160
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations professionnelles :
    Activité : Dév

    Informations forums :
    Inscription : Juin 2007
    Messages : 1 160
    Points : 3 691
    Points
    3 691
    Par défaut Barre de progression et MVC
    Bonjour,

    J'essaie de respecter le MVC et je voudrais mettre un barre de progression. En fait, j'ouvre tous les fichiers d'un répertoire et fais des traitements dessus (environ 10 000). Mais comment faire dans ce cas pour revenir dans la forme principale pour remettre à jour l'affichage durant le traitement qui se fait dans la couche model?

    Merci.

  2. #2
    Membre habitué
    Profil pro
    Inscrit en
    Août 2009
    Messages
    147
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2009
    Messages : 147
    Points : 174
    Points
    174
    Par défaut
    Regarde du coté du backgroundWorker, tu devrais trouver des exemples sur le net.

  3. #3
    Membre expert
    Profil pro
    Dév
    Inscrit en
    Juin 2007
    Messages
    1 160
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations professionnelles :
    Activité : Dév

    Informations forums :
    Inscription : Juin 2007
    Messages : 1 160
    Points : 3 691
    Points
    3 691
    Par défaut
    Je sais comment utiliser le BackGroundWorker mais je ne vois pas comment placer le traitement dans le DoWork.

    Actuellement mon code est de la manière suivante :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    //Code de la vue
    public partial class MainForm : Form
        {
            private Controleur controleur;
            private XmlDocument xmlDoc;
            private XmlNode node;
            string applicationName;
            public MainForm()
            {
                InitializeComponent();
                controleur = new Controleur();
     
                xmlDoc = new XmlDocument();
                // Path of exe
                // The first element of the array is the path of the exe
                string exePath = Environment.GetCommandLineArgs()[0];
                // Directory of the exe
                string exeDir = System.IO.Path.GetDirectoryName(exePath);
                applicationName = exeDir + "\\" + "Repetabilite SCG.exe.config";
                xmlDoc.Load(applicationName);
                node = xmlDoc.SelectSingleNode("configuration/appSettings/add[@key='directory1']");
                this.txtBoxDir1.Text = node.Attributes[1].Value;
                node = xmlDoc.SelectSingleNode("configuration/appSettings/add[@key='directory2']");
                this.txtBoxDir2.Text = node.Attributes[1].Value;
                node = xmlDoc.SelectSingleNode("configuration/appSettings/add[@key='outputFile']");
                this.txtBoxFile.Text = node.Attributes[1].Value;
     
            }
     
            private void SaveInfoConfigFile()
            {
                node = xmlDoc.SelectSingleNode("configuration/appSettings/add[@key='directory1']");
                node.Attributes[1].Value = this.txtBoxDir1.Text;
                node = xmlDoc.SelectSingleNode("configuration/appSettings/add[@key='directory2']");
                node.Attributes[1].Value = this.txtBoxDir2.Text;
                node = xmlDoc.SelectSingleNode("configuration/appSettings/add[@key='outputFile']");
                node.Attributes[1].Value = this.txtBoxFile.Text;
                xmlDoc.Save(applicationName);
                ConfigurationManager.RefreshSection("appSettings");
            }
            private void ControlDirPath(TextBox txtBoxDir)
            {
                folderBrowserDialog.Description = "Choisissez votre répertoire";
                if (folderBrowserDialog.ShowDialog(this) == DialogResult.OK)
                {
                    if (controleur.ControlDirectoryPath(folderBrowserDialog.SelectedPath))
                        txtBoxDir.Text = folderBrowserDialog.SelectedPath;
                    else
                    {
                        MessageBox.Show(this,
                        "Vous aves choisi " + folderBrowserDialog.SelectedPath + ", ce répertoire est incorrect.",
                        "Repertoire",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                    }
     
                }
            }
     
            private void folderButton1_Click(object sender, EventArgs e)
            {
                ControlDirPath(txtBoxDir1);
            }
     
            private void folderButton2_Click(object sender, EventArgs e)
            {
                ControlDirPath(txtBoxDir2);
            }
     
            private void buttonOK_Click(object sender, EventArgs e)
            {
                controleur.Dir1 = this.txtBoxDir1.Text;
                controleur.Dir2 = this.txtBoxDir2.Text;
                if (!String.IsNullOrEmpty(controleur.FileName))
                {
                    SaveInfoConfigFile();
                    controleur.ComparisonFiles();
                }
                else
                {
                    MessageBox.Show("Renseignez le nom du fichier à créer.");
                }
            }
     
     
            private void fileButton_Click(object sender, EventArgs e)
            {
                // Sauvegarde du document
                saveFileDialog1.Title = "Sauvegarde";
                saveFileDialog1.DefaultExt = "txt";
                saveFileDialog1.Filter = "fichiers textes (*.xls)|*.xls|Tous les fichiers (*.*)|*.*";
                saveFileDialog1.FilterIndex = 1;
                // Ouverture boite de dialogue Enregistrer
                if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    controleur.FileName = saveFileDialog1.FileName;
                    this.txtBoxFile.Text = saveFileDialog1.FileName;
                }
            }
        }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    //Code du controleur
    public class Controleur
        {
            #region Attributes
            private List<String> fileList1 = new List<string>();
            private string fileName;
            private List<String> fileList2 = new List<string>();
     
            private String dir1;
            private string dir2;
     
            #endregion
            #region Properties
            /// <summary>
            /// Get or Set a System.String that represents the first directory
            /// </summary>
            public String Dir1
            {
                get { return dir1; }
                set { dir1 = value; }
            }
            /// <summary>
            /// Get or Set a System.String that represents the output file
            /// </summary>
            public string FileName
            {
                get { return fileName; }
                set
                {
                    if (!string.Equals(value.Substring(value.Length - 4, 4), ".xls")) value += ".xls";
                    fileName = value;
                }
            }
            /// <summary>
            /// Get or Set a System.String that represents the second directory
            /// </summary>
            public string Dir2
            {
                get { return dir2; }
                set { dir2 = value; }
            }
            /// <summary>
            /// Get or Set the file list 1
            /// </summary>
            public List<String> FileList1
            {
                get { return fileList1; }
            }
            /// <summary>
            /// Get or Set the file list 1
            /// </summary>
            public List<String> FileList2
            {
                get { return fileList2; }
            }
            #endregion
            #region Constructor
            /// <summary>
            /// Constructor
            /// </summary>
            public Controleur()
            {
     
            }
            #endregion
     
            #region Public methods
            /// <summary>
            /// Control the path of a directory
            /// </summary>
            /// <param name="directoryPath">A System.String that represents the path of a directory</param>
            /// <returns>A System.Boolean that represents the existing of a path</returns>
            public bool ControlDirectoryPath(string directoryPath)
            {
                return System.IO.Directory.Exists(directoryPath);
            }
            /// <summary>
            /// Launch the comparison between 2 directories
            /// </summary>
            public void ComparisonFiles()
            {
                LoadFiles(dir1, fileList1);
                LoadFiles(dir2, fileList2);
                FileReader fileReader = new FileReader(dir1, dir2);
                fileReader.Treatment(fileList1, fileList2);
                string[] array = new string[fileReader.Res.Count];
                fileReader.Res.CopyTo(array, 0);
                object[,] rawData = new object[array.Length, 5];//array for xls copy
     
                for (int i = 0; i < array.Length; i++)
                {
                    string[] tmp = array[i].Split(' ');
                    rawData[i, 0] = tmp[0];
                    rawData[i, 1] = tmp[1];
                    rawData[i, 2] = tmp[2];
                    rawData[i, 3] = tmp[3];
                    rawData[i, 4] = tmp[4];
                }
     
                TraitementExcel.ExcelWriter xls= new ExcelWriter();
                xls.Open(this.fileName);
     
                //Copy to a xls file
                string range = String.Format("A2:E{0}", array.Length + 1);
                xls.CopyArray(rawData, range);
     
                //Libération ressources
                fileReader.ClearRes();
                fileList1.Clear();
                FileList2.Clear();
            }
     
            #endregion
     
            #region Private methods
            private void LoadFiles(string directory, List<string> list)
            {
                string[] files;
                // pour avoir les noms des fichiers .s et sous-répertoires. A modifier si les fichiers peuvent avoir d'autres extensions
                files = Directory.GetFiles(directory, "*.s*", SearchOption.AllDirectories);
                //list.ad(files);
                list.AddRange(files);
            }
     
            #endregion
        }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    //Code model
    public class FileReader
        {
            public struct ResultatComparaison
            {
                public double min;
                public double max;
                public double average;
                public double standardDeviation;
            }
     
            private string dir1;
            private string dir2;
            private Collection<String> res = new Collection<string>();
            /// <summary>
            /// Get the result dictionnary
            /// </summary>
            public Collection<String> Res
            {
                get { return res; }
            }
            /// <summary>
            /// Constructor
            /// </summary>
            public FileReader(string d1, string d2)
            {
                dir1 = d1;
                dir2 = d2;
            }
     
            /// <summary>
            /// Read a text file
            /// </summary>
            /// <param name="nomFichier">A System.String that represents the file name</param>
            private void FichierTexte(string nomFichier, List<String> fileList2)
            {
                StreamReader sr = null;
                StreamReader sr2 = null;
                string line;
                string line2;
                string fileNameWithoutPath = System.IO.Path.GetFileName(nomFichier);
                try
                {
                    //A modifier dépendant du nom des fichiers
                    if (File.Exists(System.IO.Path.Combine(dir2, fileNameWithoutPath)) && fileList2.Contains(System.IO.Path.Combine(dir2, fileNameWithoutPath)))
                    {
                        // Ouverture des fichiers
                        sr2 = new StreamReader(System.IO.Path.Combine(dir2, fileNameWithoutPath));
                        sr = new StreamReader(nomFichier);
     
                        //traitement première ligne
                        line2 = sr2.ReadLine().Trim();
                        line = sr.ReadLine().Trim();
     
                        //header of file treatment
                        string[] header = line.Split(' ');
                        string[] header2 = line2.Split(' ');
                        Collection<Double> val = new Collection<double>(); ;
                        if (string.Equals(header[0], header2[0]) && string.Equals(header2[1], header[1]))
                        {
                            int lineCount = 1;
                            while (line != null)
                            {
                                line = sr.ReadLine();
                                line2 = sr2.ReadLine();
     
                                if (!String.IsNullOrEmpty(line))
                                {
                                    line = line.Trim();
                                    line2 = line2.Trim();
                                    //treatment of lines
                                    string[] valTmp = line.Split(' ');
                                    string[] valTmp2 = line2.Split(' ');
                                    string[] values = ResizeArray(valTmp);
                                    string[] values2 = ResizeArray(valTmp2);                                
                                    for (int i = 0; i < values.Length; i++)
                                    {
                                        double v;
                                        double v2;
                                        double.TryParse(values[i], System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out v);
                                        double.TryParse(values2[i], System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out v2);
                                        double f = Math.Abs(v - v2);
                                        val.Add(f);
                                    }
                                    lineCount++;
                                }
                            }
                            double[] array = new double[val.Count];
                            val.CopyTo(array, 0);
                            ResultatComparaison r;
                            r.average = AverageFromDoubleArray(array);
                            r.max = Maximum(val);
                            r.min = Minimum(val);
                            r.standardDeviation = StandardDeviation(val, r.average);
                            val.Clear();
                            res.Add(fileNameWithoutPath.Replace(" ", "") + " " + 
                                r.min.ToString("0.0000000000") + " " +
                                r.max.ToString("0.0000000000") + " " +
                                r.average.ToString("0.0000000000") + " " +
                                r.standardDeviation.ToString("0.0000000000"));
                        }
                    }                
                }
                finally
                {
                    // Fermeture streamreader
                    if (sr != null) sr.Close();
                    if (sr2 != null) sr2.Close();
                }
            }
     
            private string[] ResizeArray(string[] array)
            {
                List<string> tmp = new List<string>(array.Length);
                for (int i = 0; i < array.Length; i++)
                {
                    if (!string.IsNullOrEmpty(array[i])) tmp.Add(array[i]);
                }
                string[] res = new string[tmp.Count];
                tmp.CopyTo(res);
                tmp.Clear();
                return res;
            }
     
            #region Math
            private double StandardDeviation(Collection<double> doubleList, double average)
            {
                double sumOfDerivation = 0;
                foreach (double value in doubleList)
                {
                    sumOfDerivation += (value) * (value);
                }
                double sumOfDerivationAverage = sumOfDerivation / doubleList.Count;
                return Math.Sqrt(sumOfDerivationAverage - (average * average));
            }
     
            private double Maximum(Collection<double> val)
            {
                //calculation of max, min, avg and sd
                double max = double.MinValue;
                foreach (double d in val)
                {
                    if (d > max) max = d;
                }
                return max;
            }
     
            private double Minimum(Collection<double> val)
            {
                //calculation of max, min, avg and sd
                double min = double.MaxValue;
                foreach (double d in val)
                {
                    if (d < min) min = d;
                }
                return min;
            }
            /// <summary>
            /// Calculate the average of all elements in a double array.
            /// </summary>
            /// <param name="dblArray">The double array to get the 
            /// average from.</param>
            /// <returns>The average of the double array</returns>
            private double AverageFromDoubleArray(double[] dblArray)
            {
                double dblResult = 0;
                foreach (double dblValue in dblArray)
                    dblResult += dblValue;
                return dblResult / dblArray.Length;
            }
            #endregion
     
            public void Treatment(List<String> fileList1, List<String> fileList2)
            {
                foreach (string fileName in fileList1)
                {
                    FichierTexte(fileName, fileList2);
                }
            }
            /// <summary>
            /// Clear result dictionnary
            /// </summary>
            public void ClearRes()
            {
                this.res.Clear();
            }
     
        }
    C'est surtout la partie fileReader.Treatment(fileList1, fileList2); qui prend du temps. La seule solution que j'ai trouvé c'est de mettre un gif de chargement mais ce n'est pas très précis. Donc si j'utilise le backgroundworker, comment je renvois des données de la méthode Treatment sur la form principale?

  4. #4
    Membre habitué
    Profil pro
    Inscrit en
    Août 2009
    Messages
    147
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2009
    Messages : 147
    Points : 174
    Points
    174
    Par défaut
    Il y a pour cela la méthode reportProgress. Tu t'abonnes à l'évenement progressChanged du backgroundWorker et tu incrémentes la valeur de ta progressBar dans la fonction On_ProgressChanged.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Pattern MVC et barre de progression
    Par Tiberizz dans le forum Interfaces Graphiques en Java
    Réponses: 7
    Dernier message: 05/12/2006, 18h44
  2. [VB.NET] Pb avec le bouton Annuler d'1 barre de progression
    Par dada1982 dans le forum Windows Forms
    Réponses: 3
    Dernier message: 30/06/2004, 09h56
  3. Réponses: 12
    Dernier message: 27/05/2004, 00h13
  4. [DEBUTANT] Barre de progression
    Par pupupu dans le forum MFC
    Réponses: 4
    Dernier message: 18/01/2004, 16h47
  5. [web] Barre de Progression ASCII
    Par Red Bull dans le forum Web
    Réponses: 13
    Dernier message: 05/06/2003, 12h56

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo