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 :

Création de mon premier service windows C#


Sujet :

C#

  1. #1
    Membre actif
    Profil pro
    Inscrit en
    Juin 2006
    Messages
    661
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Juin 2006
    Messages : 661
    Points : 244
    Points
    244
    Par défaut Création de mon premier service windows C#
    Bonjour,

    J'ai une application qui va lire les fichiers .docs dans un répertoire pour ensuite les transformer dans un autre répertoire en PDF à l'aide de PDFCrreator avec un composant COM .

    ça fonctionne bien en WinForm.

    J'ai essayé d’adapter mon code WinForm en Windows service.

    Mais j'obtiens une erreur:

    Le service sur ordinateur local a démarré et s'est ensuite arrêté. Certains services s'arrêtent automatiquement s'ils ne sont utilisés par d'autres services ou programmes.

    Voici mon code:

    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
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Linq;
    using System.ServiceProcess;
    using System.Text;
    using System.IO;
    using System.Windows.Forms;
    using System.Configuration;
     
    namespace WindowsServiceDocToPdf
    {
        public partial class Service1 : ServiceBase
        {
            private const int maxTime = 20;
     
            private PDFCreator.clsPDFCreator _PDFCreator;
            private PDFCreator.clsPDFCreatorError pErr;
     
            private bool ReadyState;
     
            public Service1()
            {
                InitializeComponent();
            }
     
            protected override void OnStart(string[] args)
            {
     
                string parameters;
                MessageBox.Show ("Status: Program is started.");
     
                string sourcePath = ConfigurationManager.AppSettings["source"];
                string targetPath = ConfigurationManager.AppSettings["target"];
     
                pErr = new PDFCreator.clsPDFCreatorError();
     
                _PDFCreator = new PDFCreator.clsPDFCreator();
                _PDFCreator.eError += new PDFCreator.__clsPDFCreator_eErrorEventHandler(_PDFCreator_eError);
                _PDFCreator.eReady += new PDFCreator.__clsPDFCreator_eReadyEventHandler(_PDFCreator_eReady);
     
                parameters = "/NoProcessingAtStartup";
     
                if (!_PDFCreator.cStart(parameters, false))
                {
                    MessageBox.Show("Status: Error[" + pErr.Number + "]: " + pErr.Description);
                }
     
                // récupérer les fichiers du dossier source
                string[] fileNames = Directory.GetFiles(sourcePath, "*.doc*");
                //MessageBox.Show(Convert.ToString(fileNames.Count()));
     
                for (int i = 0; i < (fileNames.Count()); i++)
                {
                    string fname, DefaultPrinter;
                    FileInfo fi;
                    PDFCreator.clsPDFCreatorOptions opt;
     
                    fi = new FileInfo(fileNames[i]);
                    if (fi.Name.Length > 0)
                    {
                        if (fi.Name.IndexOf(".") > 1)
                        {
                            fname = fi.Name.Substring(0, fi.Name.IndexOf("."));
                        }
                        else
                        {
                            fname = fi.Name;
                        }
     
                        opt = _PDFCreator.cOptions;
                        opt.UseAutosave = 1;
                        opt.UseAutosaveDirectory = 1;
                        opt.AutosaveDirectory = targetPath;
                        opt.AutosaveFormat = 0;
                        opt.AutosaveFilename = fname;
                        _PDFCreator.cOptions = opt;
                        _PDFCreator.cClearCache();
                        DefaultPrinter = _PDFCreator.cDefaultPrinter;
                        _PDFCreator.cDefaultPrinter = "PDFCreator";
                        _PDFCreator.cPrintFile(fi.FullName);
                        ReadyState = false;
                        _PDFCreator.cPrinterStop = false;
                        timer1.Interval = maxTime * 1000;
                        timer1.Enabled = true;
                        while (!ReadyState && timer1.Enabled)
                        {
                            Application.DoEvents();
                        }
                        timer1.Enabled = false;
     
                        _PDFCreator.cPrinterStop = true;
                        _PDFCreator.cDefaultPrinter = DefaultPrinter;
                    }
                }
     
            }
            private void _PDFCreator_eReady()
            {
                _PDFCreator.cPrinterStop = true;
                ReadyState = true;
            }
     
            private void _PDFCreator_eError()
            {
                pErr = _PDFCreator.cError;
            }
     
            private void timer1_Tick(object sender, System.EventArgs e)
            {
                timer1.Enabled = false;
            }
     
            protected override void OnStop()
            {
                _PDFCreator.cClose();
                while (_PDFCreator.cProgramIsRunning)
                {
                    System.Threading.Thread.Sleep(100);
                }
                _PDFCreator = null;
                pErr = null;
     
                System.Diagnostics.Process.Start("taskkill", "/F /IM [taskname].exe");
            }
        }
    }
    Je tiens à préciser que c'est mon premier service

    D'avance merci

  2. #2
    Expert confirmé Avatar de DonQuiche
    Inscrit en
    Septembre 2010
    Messages
    2 741
    Détails du profil
    Informations forums :
    Inscription : Septembre 2010
    Messages : 2 741
    Points : 5 485
    Points
    5 485
    Par défaut
    Bonjour, c'est vraisemblablement dû à une exception non-gérée, contrairement à ce que laisse entendre le message d'erreur.

  3. #3
    Membre actif
    Profil pro
    Inscrit en
    Juin 2006
    Messages
    661
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Juin 2006
    Messages : 661
    Points : 244
    Points
    244
    Par défaut
    Pour le moment je n'ai que ça comme doc: http://msdn.microsoft.com/fr-fr/libr...v=vs.110).aspx

    J'ai rajouté un try catch

    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
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Linq;
    using System.ServiceProcess;
    using System.Text;
    using System.IO;
    using System.Windows.Forms;
    using System.Configuration;
     
    namespace WindowsServiceDocToPdf
    {
        public partial class Service1 : ServiceBase
        {
            private const int maxTime = 20;
     
            private PDFCreator.clsPDFCreator _PDFCreator;
            private PDFCreator.clsPDFCreatorError pErr;
     
            private bool ReadyState;
     
            public Service1()
            {
                InitializeComponent();
                //Ajouter une fonctionnalité de journal des événements personnalisé
                if (!System.Diagnostics.EventLog.SourceExists("MySource"))
                {
                    System.Diagnostics.EventLog.CreateEventSource(
                        "MySource", "MyNewLog");
                }
                eventLog1.Source = "MySource";
                eventLog1.Log = "MyNewLog";
            }
     
            protected override void OnStart(string[] args)
            {
     
                try
                {
                    eventLog1.WriteEntry("In OnStart");
                    MessageBox.Show("test");
                    string parameters;
                    MessageBox.Show("Status: Program is started.");
     
                    string sourcePath = ConfigurationManager.AppSettings["source"];
                    string targetPath = ConfigurationManager.AppSettings["target"];
     
                    pErr = new PDFCreator.clsPDFCreatorError();
     
                    _PDFCreator = new PDFCreator.clsPDFCreator();
                    _PDFCreator.eError += new PDFCreator.__clsPDFCreator_eErrorEventHandler(_PDFCreator_eError);
                    _PDFCreator.eReady += new PDFCreator.__clsPDFCreator_eReadyEventHandler(_PDFCreator_eReady);
     
                    parameters = "/NoProcessingAtStartup";
     
                    if (!_PDFCreator.cStart(parameters, false))
                    {
                        MessageBox.Show("Status: Error[" + pErr.Number + "]: " + pErr.Description);
                    }
     
                    // récupérer les fichiers du dossier source
                    string[] fileNames = Directory.GetFiles(sourcePath, "*.doc*");
                    //MessageBox.Show(Convert.ToString(fileNames.Count()));
     
                    for (int i = 0; i < (fileNames.Count()); i++)
                    {
                        string fname, DefaultPrinter;
                        FileInfo fi;
                        PDFCreator.clsPDFCreatorOptions opt;
     
                        fi = new FileInfo(fileNames[i]);
                        if (fi.Name.Length > 0)
                        {
                            if (fi.Name.IndexOf(".") > 1)
                            {
                                fname = fi.Name.Substring(0, fi.Name.IndexOf("."));
                            }
                            else
                            {
                                fname = fi.Name;
                            }
     
                            opt = _PDFCreator.cOptions;
                            opt.UseAutosave = 1;
                            opt.UseAutosaveDirectory = 1;
                            opt.AutosaveDirectory = targetPath;
                            opt.AutosaveFormat = 0;
                            opt.AutosaveFilename = fname;
                            _PDFCreator.cOptions = opt;
                            _PDFCreator.cClearCache();
                            DefaultPrinter = _PDFCreator.cDefaultPrinter;
                            _PDFCreator.cDefaultPrinter = "PDFCreator";
                            _PDFCreator.cPrintFile(fi.FullName);
                            ReadyState = false;
                            _PDFCreator.cPrinterStop = false;
                            timer1.Interval = maxTime * 1000;
                            timer1.Enabled = true;
                            while (!ReadyState && timer1.Enabled)
                            {
                                Application.DoEvents();
                            }
                            timer1.Enabled = false;
     
                            _PDFCreator.cPrinterStop = true;
                            _PDFCreator.cDefaultPrinter = DefaultPrinter;
                        }
                    }
     
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
     
     
     
            }
            private void _PDFCreator_eReady()
            {
                _PDFCreator.cPrinterStop = true;
                ReadyState = true;
            }
     
            private void _PDFCreator_eError()
            {
                pErr = _PDFCreator.cError;
            }
     
            private void timer1_Tick(object sender, System.EventArgs e)
            {
                timer1.Enabled = false;
            }
     
            protected override void OnStop()
            {
     
                eventLog1.WriteEntry("In onStop.");
                _PDFCreator.cClose();
                while (_PDFCreator.cProgramIsRunning)
                {
                    System.Threading.Thread.Sleep(100);
                }
                _PDFCreator = null;
                pErr = null;
     
                System.Diagnostics.Process.Start("taskkill", "/F /IM [taskname].exe");
            }
        }
    }
    J'ai toujours le même problème

  4. #4
    Expert éminent sénior Avatar de Pol63
    Homme Profil pro
    .NET / SQL SERVER
    Inscrit en
    Avril 2007
    Messages
    14 154
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : .NET / SQL SERVER

    Informations forums :
    Inscription : Avril 2007
    Messages : 14 154
    Points : 25 072
    Points
    25 072
    Par défaut
    de ce que j'en sais sur les services windows :

    il y a peu de temps pour la méthode OnStart
    si on dépasse le temps imparti le service arrête de démarrer

    ensuite si à un instant T il n'y a aucun thread le service s'arrête

    le principe est donc dans OnStart de démarrer un thread qui boucle en While True avec un Thread.Sleep pour ne pas prendre trop de ressources
    et dans ce while voir s'il y a quelques chose à faire
    concernant le sleep, ca dépend de l'importance du traitement, si tu es pressé 10 ms peuvent convenir (voir moins), si tu as le temps tu peux mettre quelques secondes
    au passage sur OnStop on peut mettre un booléen qui est vérifié dans la boucle pour sortir (là aussi le temps laissé à l'arrêt est court, donc avec un sleep de 2 secondes ca ne conviendra pas, mais bon le thread sera interrompu par la demande d'arrêt)
    Cours complets, tutos et autres FAQ ici : C# - VB.NET

  5. #5
    Membre actif
    Profil pro
    Inscrit en
    Juin 2006
    Messages
    661
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Juin 2006
    Messages : 661
    Points : 244
    Points
    244
    Par défaut
    Merci Pol63, aurais tu un exemple stp

    Merci

  6. #6
    Expert éminent sénior Avatar de Pol63
    Homme Profil pro
    .NET / SQL SERVER
    Inscrit en
    Avril 2007
    Messages
    14 154
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : .NET / SQL SERVER

    Informations forums :
    Inscription : Avril 2007
    Messages : 14 154
    Points : 25 072
    Points
    25 072
    Par défaut
    en vb.net alors

    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
     
    protected override SubOnStart(args as string())
      dim th as new system.threading.thread(addressof traitement)
      th.start
    end sub
     
    private sub traitement
       while true
           if exists some files then
              traitementfichier
           end if
           system.threading.thread.sleep(100)
       end while
    end sub
     
    private sub traitementfichier
       'boucle pour traiter les fichiers
    end sub
    (il exite des convertisseurs vers c# si ce n'est pas explicite)
    Cours complets, tutos et autres FAQ ici : C# - VB.NET

  7. #7
    Inactif  

    Homme Profil pro
    Ingénieur test de performance
    Inscrit en
    Décembre 2003
    Messages
    1 986
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 49
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Ingénieur test de performance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2003
    Messages : 1 986
    Points : 2 605
    Points
    2 605
    Par défaut
    Bonjour.

    Citation Envoyé par jacko842 Voir le message
    ça fonctionne bien en WinForm.

    J'ai essayé d’adapter mon code WinForm en Windows service.

    Mais j'obtiens une erreur:

    Le service sur ordinateur local a démarré et s'est ensuite arrêté. Certains services s'arrêtent automatiquement s'ils ne sont utilisés par d'autres services ou programmes.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    MessageBox.Show ("Status: Program is started.");
    Le problème c'est qu'un service ne peut pas afficher d'IHM (Form ou MessageBox). Le service doit certainement s'arrêter à la première demande d'affichage d'une MessageBox. Il faut utiliser les logs dédiés aux services.

    Pour qu'un service affiche une Form ou une MessageBox, il faut faire de la bidouille que je n'ai jamais testée.

    Le service peut se lancer avant l'ouverture de session et il sera donc déjà impossible d'afficher une IHM. La bidouille doit consister à attendre qu'une session soit ouverture avec en plus le lancement d'une application externe plus communication réseau ou messages windows. Je ne suis pas certain.

    Mais ce qui est certain, c'est qu'un service windows n'est pas du tout designé pour de l'IHM :

    http://msdn.microsoft.com/en-us/libr...(v=vs.85).aspx


    Pour résumer, enlever toutes les MessageBox du service.

  8. #8
    Membre actif
    Profil pro
    Inscrit en
    Juin 2006
    Messages
    661
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Juin 2006
    Messages : 661
    Points : 244
    Points
    244
    Par défaut
    Merci pour vos informations

    Pour les MessageBox j'en ai pas vraiment besoin.

    j'ai suivi les conseils de Pol63:

    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
    189
    190
    191
    192
    193
    194
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Configuration;
    using System.Data;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.ServiceProcess;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;
    using System.Configuration.Install;
     
    namespace ServiceDocPdf
    {
     
        [RunInstaller(true)]
        public class ServiceInstall : Installer
        {
            public ServiceInstall()
                : base()
            {
                // On définit le compte sous lequel le service sera lancé (compte Système)
                ServiceProcessInstaller process = new ServiceProcessInstaller();
                process.Account = ServiceAccount.LocalSystem;
     
                // On définit le mode de lancement (Manuel), le nom du service et sa description
                ServiceInstaller service = new ServiceInstaller();
                service.StartType = ServiceStartMode.Manual;
                service.ServiceName = "Developpez";
                service.DisplayName = "Developpez";
                service.Description = "Service de test pour DVP";
     
                // On ajoute les installeurs à la collection (l'ordre n'a pas d'importance) 
                Installers.Add(service);
                Installers.Add(process);
            }
     
            private System.Windows.Forms.Timer timer1;
            private IContainer components;
     
            private void InitializeComponent()
            {
                this.components = new System.ComponentModel.Container();
                this.timer1 = new System.Windows.Forms.Timer(this.components);
                // 
                // timer1
                // 
                this.timer1.Interval = 10;
     
            }
        }
     
        public partial class Service : ServiceBase
        {
            private const int maxTime = 20;
     
            private PDFCreator.clsPDFCreator _PDFCreator;
            private PDFCreator.clsPDFCreatorError pErr;
     
            private bool ReadyState;
            public Service()
            {
                // Permet de définir le mode de lancement du service
                ServiceInstaller si = new ServiceInstaller();
                si.StartType = ServiceStartMode.Manual;
                si.DisplayName = "Developpez";
                si.Description = "Service de test pour DVP";
                si.ServiceName = "Developpez";
                InitializeComponent();
            }
     
            protected override void OnStart(string[] args)
            {
                System.Threading.Thread th = new System.Threading.Thread(traitement);
                th.Start();
            }
     
            protected override void OnStop()
            {
            }
     
            private void traitement()
                        {
                 while (true)
                 {
                     Thread.Sleep(10);
                     traitementFichier();
                 }
            }
            private void traitementFichier()
            {
                string sourcePath = ConfigurationManager.AppSettings["source"];
                string targetPath = ConfigurationManager.AppSettings["target"];
     
                pErr = new PDFCreator.clsPDFCreatorError();
     
                _PDFCreator = new PDFCreator.clsPDFCreator();
                _PDFCreator.eError += new PDFCreator.__clsPDFCreator_eErrorEventHandler(_PDFCreator_eError);
                _PDFCreator.eReady += new PDFCreator.__clsPDFCreator_eReadyEventHandler(_PDFCreator_eReady);
     
                // récupérer les fichiers du dossier source
                string[] fileNames = Directory.GetFiles(sourcePath, "*.doc*");
                //MessageBox.Show(Convert.ToString(fileNames.Count()));
     
     
     
                for (int i = 0; i < (fileNames.Count()); i++)
                {
                    string fname, DefaultPrinter;
                    FileInfo fi;
                    PDFCreator.clsPDFCreatorOptions opt;
     
                    fi = new FileInfo(fileNames[i]);
                    if (fi.Name.Length > 0)
                    {
                        if (fi.Name.IndexOf(".") > 1)
                        {
                            fname = fi.Name.Substring(0, fi.Name.IndexOf("."));
                        }
                        else
                        {
                            fname = fi.Name;
                        }
     
                        opt = _PDFCreator.cOptions;
                        opt.UseAutosave = 1;
                        opt.UseAutosaveDirectory = 1;
                        opt.AutosaveDirectory = targetPath;
                        opt.AutosaveFormat = 0;
                        opt.AutosaveFilename = fname;
                        _PDFCreator.cOptions = opt;
                        _PDFCreator.cClearCache();
                        DefaultPrinter = _PDFCreator.cDefaultPrinter;
                        _PDFCreator.cDefaultPrinter = "PDFCreator";
                        _PDFCreator.cPrintFile(fi.FullName);
                        ReadyState = false;
                        _PDFCreator.cPrinterStop = false;
                        timer1.Interval = maxTime * 1000;
                        timer1.Enabled = true;
                        while (!ReadyState && timer1.Enabled)
                        {
                            Application.DoEvents();
                        }
                        timer1.Enabled = false;
     
                        if (File.Exists(@"C:\temp\test.txt"))
                        {
                            StreamWriter sw = new StreamWriter(@"C:\temp\test.txt");
                            sw.WriteLine(targetPath);
                            sw.Close();
                        }
                        else
                        {
                            TextWriter file = File.CreateText(@"C:\temp\test.txt");
                            file.WriteLine(targetPath);
                            file.Close();
                        }
     
                        _PDFCreator.cPrinterStop = true;
                        _PDFCreator.cDefaultPrinter = DefaultPrinter;
                    }
                }
                _PDFCreator.cClose();
                _PDFCreator = null;
                pErr = null;
                Process.Start("taskkill /f /im PDFCreator.exe");
                this.Dispose();
                Application.ExitThread();
                Application.Exit();
                Environment.Exit(0);
     
     
            }
                private void _PDFCreator_eReady()
            {
                _PDFCreator.cPrinterStop = true;
                ReadyState = true;
            }
     
            private void _PDFCreator_eError()
            {
                pErr = _PDFCreator.cError;
            }
     
            private void timer1_Tick(object sender, System.EventArgs e)
            {
                timer1.Enabled = false;
            }
        }
     
        }
    J'ai l'impression de parcourir tout le code mais pdfcreator ne se lance pas !!

    Je pense que c'est la ligne là qui pose problème.

    Qu'en pensez vous ??

    Et que me conseillez vous ?

    Bizarrement c'est quand je fais stop le service que cette ligne ci est exécutée
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    sw.WriteLine(targetPath);
    Comment puis déboguer le service ?



    Merci

  9. #9
    Expert éminent sénior Avatar de Pol63
    Homme Profil pro
    .NET / SQL SERVER
    Inscrit en
    Avril 2007
    Messages
    14 154
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : .NET / SQL SERVER

    Informations forums :
    Inscription : Avril 2007
    Messages : 14 154
    Points : 25 072
    Points
    25 072
    Par défaut
    quelques lignes de code qui ne vont pas


    "Application.DoEvents"
    ca devrait être interdit

    "timer1.Enabled = false"
    à priori tu ne t'en sers pas, mais certains timers ne fonctionnent pas dans les services

    "this.Dispose();
    Application.ExitThread();
    Application.Exit();
    Environment.Exit(0);"


    le minimum pour débugger c'est de mettre des try catch ... et après tu peux enregistrer les détails de l'erreur dans un fichier

    sinon tu dois pouvoir attacher vs à un processus pour le débugger
    Cours complets, tutos et autres FAQ ici : C# - VB.NET

  10. #10
    Inactif  

    Homme Profil pro
    Ingénieur test de performance
    Inscrit en
    Décembre 2003
    Messages
    1 986
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 49
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Ingénieur test de performance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2003
    Messages : 1 986
    Points : 2 605
    Points
    2 605
    Par défaut
    Bonjour.

    Voici un code qui je pense est plus proche de la manière dont doit fonctionner un service. Je n'ai pas la librairie Pdf, donc il y aura certainement des ajustements.

    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
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Configuration;
    using System.Data;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.ServiceProcess;
    using System.Text;
    using System.Threading;
    using System.Configuration.Install;
     
    namespace ServiceDocPdf
    {
     
        [RunInstaller(true)]
        public class ServiceInstall : Installer
        {
            public ServiceInstall()
                : base()
            {
                // On définit le compte sous lequel le service sera lancé (compte Système)
                ServiceProcessInstaller process = new ServiceProcessInstaller();
                process.Account = ServiceAccount.LocalSystem;
     
                // On définit le mode de lancement (Manuel), le nom du service et sa description
                ServiceInstaller service = new ServiceInstaller();
                service.StartType = ServiceStartMode.Manual;
                service.ServiceName = "Developpez";
                service.DisplayName = "Developpez";
                service.Description = "Service de test pour DVP";
     
                // On ajoute les installeurs à la collection (l'ordre n'a pas d'importance) 
                Installers.Add(service);
                Installers.Add(process);
            }
        }
     
        public partial class Service : ServiceBase
        {
            //private const int maxTime = 20;
     
            //private PDFCreator.clsPDFCreator _PDFCreator;
            //private PDFCreator.clsPDFCreatorError pErr;
     
            private bool bRetry = true;
            private bool bStop = false;
     
            // Certainement redondant avec pErr, mais je ne connais pas la lib Pdf.
            private bool bPdfError = false;
            private bool ReadyState;
     
            public Service()
            {
                // Permet de définir le mode de lancement du service
                ServiceInstaller si = new ServiceInstaller();
                si.StartType = ServiceStartMode.Manual;
                si.DisplayName = "Developpez";
                si.Description = "Service de test pour DVP";
                si.ServiceName = "Developpez";
            }
     
            protected override void OnStart(string[] args)
            {
                // On attend 2 minutes que l'OS soit complètement opérationnel.
                // C'est complètement arbitraire... cela ne gère pas tous les cas de figure.
                System.Threading.Thread.Sleep(120000);
     
                while (bRetry)
                {
                    bRetry = traitementFichier();
     
                    // Autant ne pas brutaliser le système, 1 seconde d'attente
                    // si l'on est pas pressé...
                    System.Threading.Thread.Sleep(1000);
                }
            }
     
            protected override void OnStop()
            {
                // On arrête le service.
                bRetry = false;
                bStop = true;
            }
     
            private bool traitementFichier()
            {
                string sourcePath = ConfigurationManager.AppSettings["source"];
                string targetPath = ConfigurationManager.AppSettings["target"];
     
                //pErr = new PDFCreator.clsPDFCreatorError();
     
                try
                {
     
                    PDFCreator.clsPDFCreator _PDFCreator = new PDFCreator.clsPDFCreator();
                    _PDFCreator.eError += new PDFCreator.__clsPDFCreator_eErrorEventHandler(_PDFCreator_eError);
                    _PDFCreator.eReady += new PDFCreator.__clsPDFCreator_eReadyEventHandler(_PDFCreator_eReady);
     
                    // récupérer les fichiers du dossier source
                    string[] fileNames = Directory.GetFiles(sourcePath, "*.doc*");
                    //MessageBox.Show(Convert.ToString(fileNames.Count()));
     
                    for (int i = 0; i < (fileNames.Count()); i++)
                    {
                        string fname, DefaultPrinter;
                        FileInfo fi;
                        PDFCreator.clsPDFCreatorOptions opt;
     
                        fi = new FileInfo(fileNames[i]);
                        if (fi.Name.Length > 0)
                        {
                            if (fi.Name.IndexOf(".") > 1)
                            {
                                fname = fi.Name.Substring(0, fi.Name.IndexOf("."));
                            }
                            else
                            {
                                fname = fi.Name;
                            }
     
                            opt = _PDFCreator.cOptions;
                            opt.UseAutosave = 1;
                            opt.UseAutosaveDirectory = 1;
                            opt.AutosaveDirectory = targetPath;
                            opt.AutosaveFormat = 0;
                            opt.AutosaveFilename = fname;
                            _PDFCreator.cOptions = opt;
                            _PDFCreator.cClearCache();
                            DefaultPrinter = _PDFCreator.cDefaultPrinter;
                            _PDFCreator.cDefaultPrinter = "PDFCreator";
                            _PDFCreator.cPrintFile(fi.FullName);
                            //ReadyState = false;
                            _PDFCreator.cPrinterStop = false;
                            //timer1.Interval = maxTime * 1000;
                            //timer1.Enabled = true;
     
                            while (!ReadyState && !bStop && !bPdfError)
                            {
                                System.Threading.Thread.Sleep(100);
                            }
     
                            //timer1.Enabled = false;
     
                            if (ReadyState && !bStop && !bPdfError)
                            {
     
                                if (File.Exists(@"C:\temp\test.txt"))
                                {
                                    StreamWriter sw = new StreamWriter(@"C:\temp\test.txt");
                                    sw.WriteLine(targetPath);
                                    sw.Close();
                                }
                                else
                                {
                                    TextWriter file = File.CreateText(@"C:\temp\test.txt");
                                    file.WriteLine(targetPath);
                                    file.Close();
                                }
     
                                _PDFCreator.cPrinterStop = true;
                                _PDFCreator.cDefaultPrinter = DefaultPrinter;
                                bRetry = false;
                            }
                        }
                    }
                }
                catch (Exception) { }
     
                // Obligatoire sinon fuite de mémoire...
                _PDFCreator.eError -= new PDFCreator.__clsPDFCreator_eErrorEventHandler(_PDFCreator_eError);
                _PDFCreator.eReady -= new PDFCreator.__clsPDFCreator_eReadyEventHandler(_PDFCreator_eReady);
     
                _PDFCreator.cClose();
                _PDFCreator = null;
                //pErr = null;
                Process.Start("taskkill /f /im PDFCreator.exe");
                //this.Dispose();
                //Application.ExitThread();
                //Application.Exit();
                //Environment.Exit(0);
     
                return bRetry;
            }
     
            private void _PDFCreator_eReady()
            {
                //_PDFCreator.cPrinterStop = true;
                ReadyState = true;
            }
     
            private void _PDFCreator_eError()
            {
                //pErr = _PDFCreator.cError;
                bPdfError = true;
            }
        }
     
    }
    Pour débugger un service :

    http://msdn.microsoft.com/en-us/libr...(v=vs.85).aspx

    ou bien faire du tracing :

    http://msdn.microsoft.com/en-us/libr...(v=vs.85).aspx

  11. #11
    Membre actif
    Profil pro
    Inscrit en
    Juin 2006
    Messages
    661
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Juin 2006
    Messages : 661
    Points : 244
    Points
    244
    Par défaut
    Merci de ton aide moldavi, mais quand j'essai de démarrer le service, j'ai un message d'erreur:

    Erreur 1053 le service n'a pas répondu assez vite à la demande de lancement ou de contrôle
    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
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Configuration;
    using System.Data;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.ServiceProcess;
    using System.Text;
    using System.Threading;
    using System.Configuration.Install;
     
    namespace ServiceDocPdf
    {
     
        [RunInstaller(true)]
        public class ServiceInstall : Installer
        {
            public ServiceInstall()
                : base()
            {
                // On définit le compte sous lequel le service sera lancé (compte Système)
                ServiceProcessInstaller process = new ServiceProcessInstaller();
                process.Account = ServiceAccount.LocalSystem;
     
                // On définit le mode de lancement (Manuel), le nom du service et sa description
                ServiceInstaller service = new ServiceInstaller();
                service.StartType = ServiceStartMode.Manual;
                service.ServiceName = "Developpez";
                service.DisplayName = "Developpez";
                service.Description = "Service de test pour DVP";
     
                // On ajoute les installeurs à la collection (l'ordre n'a pas d'importance) 
                Installers.Add(service);
                Installers.Add(process);
            }
        }
     
        public partial class Service : ServiceBase
        {
            //private const int maxTime = 20;
     
            //private PDFCreator.clsPDFCreator _PDFCreator;
            //private PDFCreator.clsPDFCreatorError pErr;
     
            private bool bRetry = true;
            private bool bStop = false;
     
            // Certainement redondant avec pErr, mais je ne connais pas la lib Pdf.
            private bool bPdfError = false;
            private bool ReadyState;
     
            public Service()
            {
                // Permet de définir le mode de lancement du service
                ServiceInstaller si = new ServiceInstaller();
                si.StartType = ServiceStartMode.Manual;
                si.DisplayName = "Developpez";
                si.Description = "Service de test pour DVP";
                si.ServiceName = "Developpez";
            }
     
            protected override void OnStart(string[] args)
            {
                // On attend 2 minutes que l'OS soit complètement opérationnel.
                // C'est complètement arbitraire... cela ne gère pas tous les cas de figure.
                System.Threading.Thread.Sleep(120000);
     
                while (bRetry)
                {
                    bRetry = traitementFichier();
     
                    // Autant ne pas brutaliser le système, 1 seconde d'attente
                    // si l'on est pas pressé...
                    System.Threading.Thread.Sleep(1000);
                }
            }
     
            protected override void OnStop()
            {
                // On arrête le service.
                bRetry = false;
                bStop = true;
            }
     
            private bool traitementFichier()
            {
                string sourcePath = ConfigurationManager.AppSettings["source"];
                string targetPath = ConfigurationManager.AppSettings["target"];
     
                //pErr = new PDFCreator.clsPDFCreatorError();
     
               // try
               // {
     
                    PDFCreator.clsPDFCreator _PDFCreator = new PDFCreator.clsPDFCreator();
                    _PDFCreator.eError += new PDFCreator.__clsPDFCreator_eErrorEventHandler(_PDFCreator_eError);
                    _PDFCreator.eReady += new PDFCreator.__clsPDFCreator_eReadyEventHandler(_PDFCreator_eReady);
     
                    // récupérer les fichiers du dossier source
                    string[] fileNames = Directory.GetFiles(sourcePath, "*.doc*");
                    //MessageBox.Show(Convert.ToString(fileNames.Count()));
     
                    for (int i = 0; i < (fileNames.Count()); i++)
                    {
                        string fname, DefaultPrinter;
                        FileInfo fi;
                        PDFCreator.clsPDFCreatorOptions opt;
     
                        fi = new FileInfo(fileNames[i]);
                        if (fi.Name.Length > 0)
                        {
                            if (fi.Name.IndexOf(".") > 1)
                            {
                                fname = fi.Name.Substring(0, fi.Name.IndexOf("."));
                            }
                            else
                            {
                                fname = fi.Name;
                            }
     
                            opt = _PDFCreator.cOptions;
                            opt.UseAutosave = 1;
                            opt.UseAutosaveDirectory = 1;
                            opt.AutosaveDirectory = targetPath;
                            opt.AutosaveFormat = 0;
                            opt.AutosaveFilename = fname;
                            _PDFCreator.cOptions = opt;
                            _PDFCreator.cClearCache();
                            DefaultPrinter = _PDFCreator.cDefaultPrinter;
                            _PDFCreator.cDefaultPrinter = "PDFCreator";
                            _PDFCreator.cPrintFile(fi.FullName);
                            //ReadyState = false;
                            _PDFCreator.cPrinterStop = false;
                            //timer1.Interval = maxTime * 1000;
                            //timer1.Enabled = true;
     
                            while (!ReadyState && !bStop && !bPdfError)
                            {
                                System.Threading.Thread.Sleep(100);
                            }
     
                            //timer1.Enabled = false;
     
                            if (ReadyState && !bStop && !bPdfError)
                            {
     
                                if (File.Exists(@"C:\temp\test.txt"))
                                {
                                    StreamWriter sw = new StreamWriter(@"C:\temp\test.txt");
                                    sw.WriteLine(targetPath);
                                    sw.Close();
                                }
                                else
                                {
                                    TextWriter file = File.CreateText(@"C:\temp\test.txt");
                                    file.WriteLine(targetPath);
                                    file.Close();
                                }
     
                                _PDFCreator.cPrinterStop = true;
                                _PDFCreator.cDefaultPrinter = DefaultPrinter;
                                bRetry = false;
                            }
                        }
                    }
                //}
               // catch (Exception) { }
     
                // Obligatoire sinon fuite de mémoire...
                _PDFCreator.eError -= new PDFCreator.__clsPDFCreator_eErrorEventHandler(_PDFCreator_eError);
                _PDFCreator.eReady -= new PDFCreator.__clsPDFCreator_eReadyEventHandler(_PDFCreator_eReady);
     
                _PDFCreator.cClose();
                _PDFCreator = null;
                //pErr = null;
                Process.Start("taskkill /f /im PDFCreator.exe");
                //this.Dispose();
                //Application.ExitThread();
                //Application.Exit();
                //Environment.Exit(0);
     
                return bRetry;
            }
     
            private void _PDFCreator_eReady()
            {
                //_PDFCreator.cPrinterStop = true;
                ReadyState = true;
            }
     
            private void _PDFCreator_eError()
            {
                //pErr = _PDFCreator.cError;
                bPdfError = true;
            }
        }
     
    }

  12. #12
    Expert éminent sénior Avatar de Pol63
    Homme Profil pro
    .NET / SQL SERVER
    Inscrit en
    Avril 2007
    Messages
    14 154
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : .NET / SQL SERVER

    Informations forums :
    Inscription : Avril 2007
    Messages : 14 154
    Points : 25 072
    Points
    25 072
    Par défaut
    oublie ce qu'a dit moldavi ca ne peut pas fonctionner
    à la place tu peux relire ma réponse en post #4 et comprendre ce que j'ai dis pour l'appliquer
    Cours complets, tutos et autres FAQ ici : C# - VB.NET

  13. #13
    Inactif  

    Homme Profil pro
    Ingénieur test de performance
    Inscrit en
    Décembre 2003
    Messages
    1 986
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 49
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Ingénieur test de performance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2003
    Messages : 1 986
    Points : 2 605
    Points
    2 605
    Par défaut
    Bonjour.

    Citation Envoyé par jacko842 Voir le message
    Merci de ton aide moldavi, mais quand j'essai de démarrer le service, j'ai un message d'erreur:
    Oui, la méthode OnStart nécessite certainement un retour. Il faut préserver la création d'un thread à l'intérieur de cette méthode, comme tu l'avais fait dans ton code.

    Dès que possible je te fournis un code minimal pour un service.

  14. #14
    Membre actif
    Profil pro
    Inscrit en
    Juin 2006
    Messages
    661
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Juin 2006
    Messages : 661
    Points : 244
    Points
    244
    Par défaut
    merci moldavi parce-que là je patauge

  15. #15
    Expert éminent sénior Avatar de Pol63
    Homme Profil pro
    .NET / SQL SERVER
    Inscrit en
    Avril 2007
    Messages
    14 154
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : .NET / SQL SERVER

    Informations forums :
    Inscription : Avril 2007
    Messages : 14 154
    Points : 25 072
    Points
    25 072
    Par défaut
    ca tourne un peu en rond, j'ai fournit un code fonctionnel il y a 10 jours ...
    Cours complets, tutos et autres FAQ ici : C# - VB.NET

Discussions similaires

  1. Mon premier service Windows avec timer
    Par OmegA_MRS dans le forum Services Windows
    Réponses: 7
    Dernier message: 20/02/2012, 11h56
  2. [C#] Création de mon premier projet.
    Par ThGraf dans le forum Windows Forms
    Réponses: 1
    Dernier message: 17/02/2011, 17h21
  3. Mon premier Service Windows
    Par BOSSANT dans le forum Services Windows
    Réponses: 3
    Dernier message: 05/02/2011, 12h51
  4. Création de mon premier service web
    Par hugo7 dans le forum Services Web
    Réponses: 2
    Dernier message: 28/10/2010, 13h08
  5. Création de mon premier trigger : Argh !
    Par zevince dans le forum PostgreSQL
    Réponses: 8
    Dernier message: 07/04/2006, 12h03

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