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

Windows Forms Discussion :

probleme avec un brackgroundWorker (BGW)


Sujet :

Windows Forms

  1. #1
    Membre actif
    Profil pro
    Inscrit en
    Janvier 2004
    Messages
    614
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2004
    Messages : 614
    Points : 299
    Points
    299
    Par défaut probleme avec un brackgroundWorker (BGW)
    Bonjour,
    après avoir ouvert un premier post sur le sujet je rencontre parfois un problème lors de l'execution de mon BGW.
    la valeur de ma variable globale sPath (qui est le chemin utiliser pour attacher un doc lorsque j'envoie un mail) et pas VU dans ma fonction d'envoi de mail)

    je souhaite que le BGW traite la creation d'un .doc et également la conversion en PDF
    pour cela j'ai codé ceci :
    1) envoi d'email sur l'event click (dans cette fonction est appelé mon BGW):

    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
    private void SendMailClient(string Caller)
            {
                try
                {
                    
                    FileInfo fi;
                    string sFileToAttach = string.Empty;
                    openFileDialog1.Multiselect = false;
                    openFileDialog1.CheckFileExists = true;
                    openFileDialog1.CheckPathExists = true;
                    String sSource = string.Empty;
    
                    Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
                    Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
                    Microsoft.Office.Interop.Outlook.Recipient oRecip;//= (Microsoft.Office.Interop.Outlook.Recipient)oMsg.Recipients.Add(tBoxMailClient.Text);
                    Microsoft.Office.Interop.Outlook.Attachment oAttach;
    
                    openFileDialog1.Filter = "All files (*.*)|*.*|Documents files (*.doc)|*.doc|Images files (*.jpg)|*.jpg|PDF files (*.pdf)|*.pdf";
    
                    if ((tBoxMailClient.Text.Length > 1) && (tBoxMailClient.Text.Contains("@")) && (tBoxMailClient.Text.Contains(".")) || (Caller == "Mailing"))
                    {
                        if (Caller != "Mailing")
                        {
                            KillPDF();
                            BGW_PDF.RunWorkerAsync();                   
    
                        }
                        else if ((Caller == "Mailing") && (CBAttachementC.Checked == true))
                        {
                            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                            {
                                fi = new System.IO.FileInfo(openFileDialog1.FileName);
                                if (fi.Name.Length > 0)
                                {
                                    sFileToAttach = fi.FullName;
                                }
                                Environment.CurrentDirectory = sPathOrg;
                            }
                        }
    
                        if (Caller != "Mailing")
                        {
                            oRecip = (Microsoft.Office.Interop.Outlook.Recipient)oMsg.Recipients.Add(tBoxMailClient.Text);
                            oRecip.Resolve();
                        }
                        else
                        {
                            oMsg.BCC = sMailing.Substring(1);
                        }
    
                        //Set the basic properties.
                        oMsg.Subject = "[EURO MEDIA]";
                        oMsg.Body = tboxMailMsg.Text;
    
                        if (Caller != "Mailing")
                        {
                            sSource = sPathPDF;
                            String sDisplayName = "MyFirstAttachment";
                            int iPosition = (int)oMsg.Body.Length + 1;
                            int iAttachType = (int)Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue;
                            oAttach = oMsg.Attachments.Add(sSource, iAttachType, iPosition, sDisplayName);
    
                        }
                        else if ((Caller == "Mailing") && (CBAttachementC.Checked == true) && (sFileToAttach != string.Empty))
                        {
                            sSource = sFileToAttach;
                            String sDisplayName = "MyFirstAttachment";
                            int iPosition = (int)oMsg.Body.Length + 1;
                            int iAttachType = (int)Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue;
                            oAttach = oMsg.Attachments.Add(sSource, iAttachType, iPosition, sDisplayName);
                        }
                        // oMsg.Display(true);  //modal
                        oMsg.Save();
                        (oMsg as Microsoft.Office.Interop.Outlook._MailItem).Send();
    
                        oRecip = null;
                        oAttach = null;
                        oMsg = null;
                        oApp = null;
                        if (Caller != "Mailing")
                            File.Delete(sPath);
                    }
                    else
                    {
                        MessageBox.Show("Veuillez saisir un format d'email correct", "Erreur de Format", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception e1)
                {
                    MessageBox.Show("Exception caught: " + e1);
                }   
            }

    Voici ce que contient la methode DoWork de mon BGW:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    private void BGW_PDF_DoWork(object sender, DoWorkEventArgs e)
           {   
               CreateDoc(iTypeDoc, false);
               ExportToPDF();
     
           }

    2) creation du .doc a partir des infos de ma form:

    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
    public void CreateDoc(int NumRelance, bool IsVisible) 
                
            {
                string sPathSaveFacture = string.Empty;
                
                    Microsoft.Office.Interop.Word.Application msWord = new Microsoft.Office.Interop.Word.Application();
                     msWord.Visible = false;
                    object missing = System.Reflection.Missing.Value;
                    object fileName = string.Empty;
                    sPathSaveFacture = Environment.CurrentDirectory + "\\Content\\" + DateTime.Now.Year.ToString();
                    
    
                    fileName = @sPathSaveFacture + "\\" +"Facture_" + tBoxFacture.Text + "_" + tBoxRaisonSocialeClient.Text + "_" + sDateFile + ".doc";
                    sNomDocSansExtension = "Facture_" + tBoxFacture.Text + "_" + tBoxRaisonSocialeClient.Text + "_" + sDateFile;
                    sPathPDF = @sPathSaveFacture + "\\" + "Facture_" + tBoxFacture.Text + "_" + tBoxRaisonSocialeClient.Text + "_" + sDateFile + ".pdf";
    
    
                    Microsoft.Office.Interop.Word.Document nvDoc;
                    if (File.Exists((string)fileName))
                    {
                        // ouvrir le document existant
                        nvDoc = msWord.Documents.Open(ref fileName, ref missing, ref missing,
                                    ref missing, ref missing, ref missing,
                                    ref missing, ref missing, ref missing,
                                    ref missing, ref missing, ref missing,
                                    ref missing, ref missing, ref missing,
                                    ref missing);
    
                        try
                        {
                       //     nvDoc.Unprotect(ref pwd);
                        }
                        catch {}
                    }
                    else
                    {
    
                        // Choisir le template
                        object templateName = "";
    
                       templateName = Environment.CurrentDirectory + "\\Content\\"+sModelCourierTypeFacture;break; //FactureEMV3.dot"; break;
    
                        // Créer le document
                        nvDoc = msWord.Documents.Add(ref templateName, ref missing, ref missing, ref missing);
                    }
    
                    object field = "NumFacture";
                    nvDoc.FormFields.get_Item(ref field).Result = tBoxFacture.Text;
    
                    field = "Raison_Social";
                    nvDoc.FormFields.get_Item(ref field).Result = tBoxRaisonSocialeClient.Text;
    
                    field = "Adresse";
                    nvDoc.FormFields.get_Item(ref field).Result = tBoxAdresseClient.Text;
    
                    field = "CP";
                    nvDoc.FormFields.get_Item(ref field).Result = tBoxCPClient.Text;
    
                    field = "Ville";
                    nvDoc.FormFields.get_Item(ref field).Result = tBoxVille.Text;
    
    
                    object noReset = true;
                    object useIRM = true;
                    object enforce = true;
    
                    // Sauver le document
                    nvDoc.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing,
                                ref missing, ref missing, ref missing, ref missing, ref missing,
                                ref missing, ref missing, ref missing, ref missing, ref missing,
                                ref missing);
                    
                    //sPath est utilisé pour l'attachement au mail
                    sPath = fileName.ToString();
    
                   // nvDoc.PrintPreview();
                    
                        (nvDoc as Microsoft.Office.Interop.Word._Document).Close(ref missing, ref missing, ref missing);
                        (msWord as Microsoft.Office.Interop.Word._Application).Quit(ref missing, ref missing, ref missing);
            }
    3 : Convertion du doc en PDF

    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
     
     private void ExportToPDF()
            {
                PrintDocument prtdoc = new PrintDocument();
                DefPrinter = prtdoc.PrinterSettings.PrinterName;
     
                //CreateDoc(iTypeDoc, false);
     
                string fname, DefaultPrinter;
                string fi2 = string.Empty;
                PDFCreator.clsPDFCreatorOptions opt;
                pErr = new PDFCreator.clsPDFCreatorError();
     
                _PDFCreator = new PDFCreator.clsPDFCreator();
                _PDFCreator.eError += new PDFCreator.__clsPDFCreator_eErrorEventHandler(_PDFCreator_eError);
                _PDFCreator.eReady += new PDFCreator.__clsPDFCreator_eReadyEventHandler(_PDFCreator_eReady);
     
                string parameters = "/NoProcessingAtStartup";
     
                if (!_PDFCreator.cStart(parameters, false))
                {
                    MessageBox.Show("Status: Error[" + pErr.Number + "]: " + pErr.Description);
                }
                else
                    fi2 = sPath;
     
                fname = sNomDocSansExtension;
     
                if (!_PDFCreator.cIsPrintable(sPath))
                {
                    MessageBox.Show("File '" + sPath + "' is not printable!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                opt = _PDFCreator.cOptions;
                opt.UseAutosave = 1;
                opt.UseAutosaveDirectory = 1;
                opt.AutosaveDirectory = Environment.CurrentDirectory + "\\Content\\" + DateTime.Now.Year.ToString(); //fi.DirectoryName;
                opt.AutosaveFormat = 0;
     
                opt.AutosaveFilename = fname;
                _PDFCreator.cOptions = opt;
                _PDFCreator.cClearCache();
                DefaultPrinter = _PDFCreator.cDefaultPrinter;
                _PDFCreator.cDefaultPrinter = "PDFCreator";
                _PDFCreator.cPrintFile(sPath);
     
                ReadyState = false;
                _PDFCreator.cPrinterStop = false;
                timer2.Interval = maxTime * 1000;
                timer2.Enabled = true;
                while (!ReadyState && timer2.Enabled)
                {
                    Application.DoEvents();
                }
                timer2.Enabled = false;
                if (!ReadyState)
                {
                    MessageBox.Show("Creating printer test page as pdf.\n\r\n\r" +
                        "An error is occured: Time is up!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                _PDFCreator.cPrinterStop = true;
                _PDFCreator.cDefaultPrinter = DefaultPrinter;
                ClosePDF();
     
            }

  2. #2
    Membre actif
    Profil pro
    Inscrit en
    Janvier 2004
    Messages
    614
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2004
    Messages : 614
    Points : 299
    Points
    299
    Par défaut
    personne ne vient a mon secours...

  3. #3
    Rédacteur
    Avatar de Greybird
    Inscrit en
    Juin 2002
    Messages
    673
    Détails du profil
    Informations forums :
    Inscription : Juin 2002
    Messages : 673
    Points : 1 271
    Points
    1 271
    Par défaut
    Bon on n'a pas tout ton code, mais il me semble que ton code n'utilise pas le BGW correctement. Je en vois nulle part où tu attends que la tâche soit terminée (tu as un event pour ça sur le BGW). Si tu demande la valeur sPath avant que le thread d'arrière plan ne l'ait positionnée, forcément que tu ne la retrouves pas... Et forcément, certaines fois ça marche et d'autre pas, suivant le temps que met le PDF à se créer, et le temps que met le reste du code à avancer.

    Enfin, utiliser une variable globale me parait foireux.

    Je ferais :
    CreateDoc retourne le path sous forme de string
    ExportToPDF prend en paramètre le path du fichier
    fournir le path dans la valeur de retour du thread d'arrière plan. (DoWorkEventArgs.Result)
    tout le code que tu ne peux exécuter qu'une fois le fichier pdf créé => dans le gestionnaire d'événement BackgroundWorker.RunWorkerCompleted, où tu récupère le chemin du fichier créé.

  4. #4
    Membre actif
    Profil pro
    Inscrit en
    Janvier 2004
    Messages
    614
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2004
    Messages : 614
    Points : 299
    Points
    299
    Par défaut
    c'est ce que je n'arrive pas a faire. d'attendre que createDoc est fini pour lancer ExportTOPDF.
    Le code qui te manque doit etre ca :

    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
     private void BGW_PDF_DoWork(object sender, DoWorkEventArgs e)
            {
                CreateDoc(iTypeDoc, false);
                ExportToPDF();
            }
    //----------------------------
    private void BGW_PDF_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {
     
            }
    //----------------------------
            private void BGW_PDF_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                if (e.Error != null)
                    toolStripStatusLabel1.Text = "Erreur lors de la tentative de creation du PDF";
                else if (e.Cancelled)
                    toolStripStatusLabel1.Text = "Creation du PDF annulé";
                else
                    toolStripStatusLabel1.Text = "Creation du PDF avec succes";
            }
    Dans quelle methode dois je faire patienter mon thread?
    merci de ta reponse.
    Edit: je ne comprends pas pourquoi lorsque je met un point d'arret sur la methode DoWork ca passe jamais dessus???

  5. #5
    Rédacteur
    Avatar de Greybird
    Inscrit en
    Juin 2002
    Messages
    673
    Détails du profil
    Informations forums :
    Inscription : Juin 2002
    Messages : 673
    Points : 1 271
    Points
    1 271
    Par défaut
    Tu ne fais pas patienter ton thread principal.

    Ton thread principal lance le BGW puis fait tout ce qu'il peut faire sans le fichier pdf, et c'est tout, pas d'attente, juste la fin de la méthode.

    Dans le BGW_PDF_RunWorkerCompleted, il finit ses traitements, vu qu'il a maintenant le pdf disponible.

    J'en profite pour mentionner que iTypeDoc devrait également être passé en argument du RunWorkerAsync, plutôt que d'être en global, et récupéré via DoEventArgs.Argument

  6. #6
    Membre actif
    Profil pro
    Inscrit en
    Janvier 2004
    Messages
    614
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2004
    Messages : 614
    Points : 299
    Points
    299
    Par défaut
    je reviens car il se passe des choses bizares parfois..
    comme je l'ai dit dans mon post precedent avec un point d'arret sur DoWork il n'y avait aucun arret. j'ai donc recreer la fonction et la il s'arrete.
    J'ai modifié mon code comme cela :
    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
     
     //sending mail to the client with attached document
            private void btnSendMailClient_Click(object sender, EventArgs e)
            {
                //SendMailClient("ClassicalMail");
                KillPDF();
                BGW_PDF.RunWorkerAsync();
            }
     
    private void BGW_PDF_DoWork(object sender, DoWorkEventArgs e)
            {
                CreateDoc(iTypeDoc, false);
                e.Result = sPathPDF;
                ExportToPDF();
                SendMailClient("ClassicalMail");
            }
    et la ca a l'air de marcher.
    j'avoue que je ne sais pas ce que l'instruction :
    fait exactement....
    mais ca a l'air de marcher
    Toutes les remarques sont les bienvenues pour optimiser, aider a comprendre!!
    merci

  7. #7
    Rédacteur
    Avatar de Greybird
    Inscrit en
    Juin 2002
    Messages
    673
    Détails du profil
    Informations forums :
    Inscription : Juin 2002
    Messages : 673
    Points : 1 271
    Points
    1 271
    Par défaut
    Je pensais que tu voulais juste générer le pdf en arrière plan.

    Forcément, si tu veux tout faire en arrière plan c'est plus simple.

    e.Result ca te permet de récupérer un résultat de traitement dans l'évenement Completed.

    e.Argument dans le DoWork, ca te permet de récupérer l'argument que tu as passé à RunWorkerAsync.

    Je te conseille sincèrement d'aller lire la doc du BackgroundWorker sur MSDN pour comprendre comment ça marche.

  8. #8
    Membre actif
    Profil pro
    Inscrit en
    Janvier 2004
    Messages
    614
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2004
    Messages : 614
    Points : 299
    Points
    299
    Par défaut
    oui je souhaitais faire en fait tout la gestion d'envoi de mail en arriere plan.
    je t'avoue que j'ai lu la doc sur MSDN ainsi que le tutorial mais c'est pas tout a fait clair..
    je vais m'y pencher plus sérieusement.
    Merci de tes explications en tout cas.

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

Discussions similaires

  1. Probleme avec la copie des surfaces
    Par Black_Daimond dans le forum DirectX
    Réponses: 3
    Dernier message: 09/01/2003, 10h33
  2. Problèmes avec le filtrage des ip
    Par berry dans le forum Réseau
    Réponses: 9
    Dernier message: 30/12/2002, 07h51
  3. probleme avec la touche F10
    Par b.grellee dans le forum Langage
    Réponses: 2
    Dernier message: 15/09/2002, 22h04
  4. Probleme avec fseek
    Par Bjorn dans le forum C
    Réponses: 5
    Dernier message: 04/08/2002, 07h17
  5. [Kylix] probleme avec un imagelist
    Par NicoLinux dans le forum EDI
    Réponses: 4
    Dernier message: 08/06/2002, 23h06

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