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 :

connexion au serveur exchange en C#


Sujet :

Windows Forms

  1. #1
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Octobre 2008
    Messages
    35
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 35
    Points : 34
    Points
    34
    Par défaut connexion au serveur exchange en C#
    Bonjour

    j'ai trouvé sur ce site un moyen de se connecter via ssl à exchange.

    Donc voilà le 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
    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
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
     
    using System;
    using System.IO;
    using System.Xml;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Authentication;
    using System.Text.RegularExpressions;
     
     
    namespace autreTestSSL
    {
        public class WebDAVRequest
        {        
            private static string server = "https://ip";
            private static string path = "/exchange";
            private static string username = "user";
            private static string password = "password";
            private CookieContainer authCookies = null;
     
     
            /// 
            /// Add code here to check the server certificate, if you think it’s necessary. Note that this
            /// will only be called once when the application is first started.
            /// 
     
            protected bool CheckCert(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                return true;
            }
     
            /// 
            /// Default WebDAVRequest constructor. Set the certificate callback here.
            /// 
     
            public WebDAVRequest()
            {
                ServicePointManager.ServerCertificateValidationCallback += CheckCert;
            }
     
     
            /// 
            /// Authenticate against the Exchange server and store the authorization cookie so we can use
            /// it for future WebDAV requests.
            /// 
     
            public void Authenticate()
            {
                string authURI = server + "/exchweb/bin/auth/owaauth.dll";
     
                // Create the web request body:
     
                string body = string.Format("destination={0}&username={1}&password={2}", server + path, username, password);
                byte[] bytes = Encoding.UTF8.GetBytes(body);
     
                // Create the web request:
     
                HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(authURI);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.CookieContainer = new CookieContainer();
                request.ContentLength = bytes.Length;
     
                // Create the web request content stream:
     
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Close();
                }
     
                // Get the response & store the authentication cookies:
     
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
     
                if (response.Cookies.Count < 2)
                    throw new AuthenticationException("Login failed. Is the login / password correct?");
     
                authCookies = new CookieContainer();
                foreach (Cookie myCookie in response.Cookies)
                {
                    //cookies.Add(myCookie);
                    authCookies.Add(myCookie);
                }
     
                response.Close();
            }
     
     
     
            /// 
            /// Find today’s appointments in the public folder calendar and print the results.
            /// 
     
            public void RunQuery()
            {
                string uri = server + path;
                HttpWebRequest request;
                WebResponse response;
                byte[] bytes;
     
                string start = DateTime.Today.ToString("yyyy/MM/dd");
                string end = DateTime.Today.ToString("yyyy/MM/dd");
     
                // Note that deep traversals don’t work on public folders. In other words, if you
                // need to dig deeper you’ll need to split your query into multiple requests.
     
                string format =
                    @"                       
                                SELECT
                                    ""urn:schemas:calendar:dtstart"", ""urn:schemas:calendar:dtend"",
                                    ""urn:schemas:httpmail:subject"", ""urn:schemas:calendar:organizer"",
                                    ""DAV:parentname""
                                FROM
                                    Scope(’SHALLOW TRAVERSAL OF ""{0}""‘)
                                WHERE
                                    NOT ""urn:schemas:calendar:instancetype"" = 1
                                    AND ""DAV:contentclass"" = ‘urn:content-classes:appointment’
                                    AND ""urn:schemas:calendar:dtstart"" > ‘{1}’
                                    AND ""urn:schemas:calendar:dtend"" < '{2}'
     
                        ";
     
                bytes = Encoding.UTF8.GetBytes(String.Format(format, uri, start, end));
     
                // Use the authorization cookies we stored in the authentication method.
     
                request = (HttpWebRequest)HttpWebRequest.Create(uri);
                request.CookieContainer = authCookies;
                request.Method = "SEARCH";
                request.ContentLength = bytes.Length;
                request.ContentType = "text/xml";
     
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
     
                response = (HttpWebResponse)request.GetResponse();
     
                using (Stream responseStream = response.GetResponseStream())
                {
                    // Parse the XML response to find the data we need.
     
                    XmlDocument document = new XmlDocument();
                    document.Load(responseStream);
     
                    XmlNodeList subjectNodes = document.GetElementsByTagName("e:subject");
                    XmlNodeList locationNodes = document.GetElementsByTagName("a:parentname");
                    XmlNodeList startTimeNodes = document.GetElementsByTagName("d:dtstart");
                    XmlNodeList endTimeNodes = document.GetElementsByTagName("d:dtend");
                    XmlNodeList organizerNodes = document.GetElementsByTagName("d:organizer");
     
                    for (int index = 0; index < subjectNodes.Count; index++)
                    {
                        string subject = subjectNodes[index].InnerText;
                        string organizer = organizerNodes[index].InnerText;
                        //string location = ParentName(locationNodes[index].InnerText);
                        DateTime startTime = DateTime.Parse(startTimeNodes[index].InnerText);
                        DateTime endTime = DateTime.Parse(endTimeNodes[index].InnerText);
     
                        // Use a regex to get just the user's first and last names. Note that
                        // some appointments may not have a valid user name.
     
                        string pattern = @"""(?.*?)""";
                        Regex regex = new Regex(pattern, RegexOptions.None);
                        Match matchedText = regex.Match(organizer);
     
                        if (matchedText.Success && matchedText.Groups["name"] != null)
                            organizer = matchedText.Groups["name"].Value;
     
                        // Print the results to the console.
     
                        Console.WriteLine("{0} - {1}: {2}", startTime.ToShortTimeString(), endTime.ToShortTimeString(), subject);
                      //  Console.WriteLine("{0} ({1})", location, organizer);
                        Console.WriteLine();
                    }
     
                }
     
                response.Close();
            }
     
     
            static void Main(string[] args)
            {
                try
                {
                    WebDAVRequest request = new WebDAVRequest();
                    request.Authenticate();
                    request.RunQuery();
                }
                catch (SecurityException e)
                {
                    Console.WriteLine("Security Exception");
                    Console.WriteLine("   Msg: " + e.Message);
                    Console.WriteLine("   Note: The application may not be trusted if run from a network share.");
                }
                catch (AuthenticationException e)
                {
                    Console.WriteLine("Authentication Exception, are you using a valid login?");
                    Console.WriteLine("   Msg: " + e.Message);
                    Console.WriteLine("   Note: You must use a valid login / password for authentication.");
                }
                catch (WebException e)
                {
                    Console.WriteLine("Web Exception");
                    Console.WriteLine("   Status: " + e.Status);
                    Console.WriteLine("   Reponse: " + e.Response);
                    Console.WriteLine("   Msg: " + e.Message);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unknown Exception");
                    Console.WriteLine("   Msg: " + e.Message);
                }
            }
     
        }
    }
    Quelqu'un pourrait-il le tester sur son serveur exchange?
    Peut-être en implémentant CheckCert() ?
    Car moi il me renvoie:
    erreur (401) non autorisé.
    Alors que le user et pwd sont exactes...


    Merci de votre aide

  2. #2
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Octobre 2008
    Messages
    35
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 35
    Points : 34
    Points
    34
    Par défaut
    après debug il arrive ici:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Puis plus rien ... :s

    Je ne comprends pas, en théorie ça devrait fonctionner...

    j'ai corrigé un peu le code et retiré des commentaires, ce qui donne:
    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
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
     
    using System;
    using System.IO;
    using System.Xml;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Authentication;
    using System.Text.RegularExpressions;
    using System.Security;
     
    namespace DowntownSoftwareHouse.ExchangeExample
    {
        public class WebDAVRequest
        {
            private static string server = "https://ip";
            private static string path = "/exchange/boite/Inbox";
            private static string username = "user";
            private static string password = "pwd";
            private CookieContainer authCookies = null;
     
     
     
            /// 
            /// Add code here to check the server certificate, if you think it’s necessary. Note that this
            /// will only be called once when the application is first started.
            /// 
     
            protected bool CheckCert(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                return true;
            }
     
            /// 
            /// Default WebDAVRequest constructor. Set the certificate callback here.
            /// 
     
            public WebDAVRequest()
            {
                ServicePointManager.ServerCertificateValidationCallback += CheckCert;
            }
     
     
            /// 
            /// Authenticate against the Exchange server and store the authorization cookie so we can use
            /// it for future WebDAV requests.
            /// 
     
            public void Authenticate()
            {
                string authURI = server + "/exchweb/bin/auth/owaauth.dll";
     
                // Create the web request body:
     
                string body = string.Format("destination={0}&username={1}&password={2}", server + path, username, password);
                byte[] bytes = Encoding.UTF8.GetBytes(body);
                Console.WriteLine("body " + body);
                // Create the web request:
     
                HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(authURI);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.CookieContainer = new CookieContainer();
                request.ContentLength = bytes.Length;
     
                Console.WriteLine("create web response");
                // Create the web request content stream:
     
                using (Stream stream = request.GetRequestStream())
                {                
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Close();                
                }
     
     
     
                // Get the response & store the authentication cookies:
                Console.WriteLine("Web response quasi prete: " + request);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Console.WriteLine("Web response recue ");
                if (response.Cookies.Count < 2)
                    throw new AuthenticationException("Login failed. Is the login / password correct?");
     
     
                CookieContainer Cookies = new CookieContainer();
     
                foreach (Cookie myCookie in response.Cookies)
                {
     
                    Cookies.Add(myCookie);
                }
     
                response.Close();
     
            }
     
     
            /// 
            /// Find today’s appointments in the public folder calendar and print the results.
            /// 
     
            public void RunQuery()
            {
                string uri = server + path;
                HttpWebRequest request;
                WebResponse response;
                byte[] bytes;
     
                string start = DateTime.Today.ToString("yyyy/MM/dd");
                string end = DateTime.Today.ToString("yyyy/MM/dd");
     
                // Note that deep traversals don’t work on public folders. In other words, if you
                // need to dig deeper you’ll need to split your query into multiple requests.
     
                string format =
                    @"
     
     
                                SELECT
                                    ""urn:schemas:calendar:dtstart"", ""urn:schemas:calendar:dtend"",
                                    ""urn:schemas:httpmail:subject"", ""urn:schemas:calendar:organizer"",
                                    ""DAV:parentname""
                                FROM
                                    Scope(’SHALLOW TRAVERSAL OF ""{0}""‘)
                                WHERE
                                    NOT ""urn:schemas:calendar:instancetype"" = 1
                                    AND ""DAV:contentclass"" = ‘urn:content-classes:appointment’
                                    AND ""urn:schemas:calendar:dtstart"" > ‘{1}’
                                    AND ""urn:schemas:calendar:dtend"" < '{2}'
     
                        ";
     
                bytes = Encoding.UTF8.GetBytes(String.Format(format, uri, start, end));
     
                // Use the authorization cookies we stored in the authentication method.
     
                request = (HttpWebRequest)HttpWebRequest.Create(uri);
                request.CookieContainer = authCookies;
                request.Method = "SEARCH";
                request.ContentLength = bytes.Length;
                request.ContentType = "text/xml";
     
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
     
                response = (HttpWebResponse)request.GetResponse();
     
                using (Stream responseStream = response.GetResponseStream())
                {
                    // Parse the XML response to find the data we need.                
                    XmlDocument document = new XmlDocument();
                    document.Load(responseStream);
     
                    XmlNodeList subjectNodes = document.GetElementsByTagName("e:subject");
                    XmlNodeList locationNodes = document.GetElementsByTagName("a:parentname");
                    XmlNodeList startTimeNodes = document.GetElementsByTagName("d:dtstart");
                    XmlNodeList endTimeNodes = document.GetElementsByTagName("d:dtend");
                    XmlNodeList organizerNodes = document.GetElementsByTagName("d:organizer");
     
                    for (int index = 0; index < subjectNodes.Count; index++)
                    {
                        string subject = subjectNodes[index].InnerText;
                        string organizer = organizerNodes[index].InnerText;
                        string location = ParentName(locationNodes[index].InnerText);
                        DateTime startTime = DateTime.Parse(startTimeNodes[index].InnerText);
                        DateTime endTime = DateTime.Parse(endTimeNodes[index].InnerText);
     
                        // Use a regex to get just the user's first and last names. Note that
                        // some appointments may not have a valid user name.
     
                        string pattern = @"""(?.*?)""";
                        Regex regex = new Regex(pattern, RegexOptions.None);
                        Match matchedText = regex.Match(organizer);
     
                        if (matchedText.Success && matchedText.Groups["name"] != null)
                            organizer = matchedText.Groups["name"].Value;
     
                        // Print the results to the console.
     
                        Console.WriteLine("{0} - {1}: {2}", startTime.ToShortTimeString(), endTime.ToShortTimeString(), subject);
                        Console.WriteLine("{0} ({1})", location, organizer);
                        Console.WriteLine();
                    }
     
                }
     
                response.Close();
            }
     
            private string ParentName(string p)
            {
                throw new NotImplementedException();
            }
     
     
     
     
            static void Main(string[] args)
            {
                try
                {
                    WebDAVRequest request = new WebDAVRequest();                
                    request.Authenticate();              
                    request.RunQuery();
                }
                catch (SecurityException e)
                {
                    Console.WriteLine("Security Exception");
                    Console.WriteLine("   Msg: " + e.Message);
                    Console.WriteLine("   Note: The application may not be trusted if run from a network share.");
                }
                catch (AuthenticationException e)
                {
                    Console.WriteLine("Authentication Exception, are you using a valid login?");
                    Console.WriteLine("   Msg: " + e.Message);
                    Console.WriteLine("   Note: You must use a valid login / password for authentication.");
                }
                catch (WebException e)
                {
                    Console.WriteLine("Web Exception");
                    Console.WriteLine("   Status: " + e.Status);
                    Console.WriteLine("   Reponse: " + e.Response);
                    Console.WriteLine("   Msg: " + e.Message);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unknown Exception");
                    Console.WriteLine("   Msg: " + e.Message);
                }
            }
        }
    }

  3. #3
    Membre du Club
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Mai 2002
    Messages
    49
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 51
    Localisation : Belgique

    Informations professionnelles :
    Activité : Consultant informatique

    Informations forums :
    Inscription : Mai 2002
    Messages : 49
    Points : 55
    Points
    55
    Par défaut
    Bonjour,
    je rencontre le même problème.

    Configuration :
    Client (WinXP , VS 2008)
    Serveur (Win 2k3, Exchange 2007)

    Je pense qu'il s'agit d'un problème de nommage du chemin à adresser.
    Mais lequel ?

  4. #4
    Membre du Club
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Mai 2002
    Messages
    49
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 51
    Localisation : Belgique

    Informations professionnelles :
    Activité : Consultant informatique

    Informations forums :
    Inscription : Mai 2002
    Messages : 49
    Points : 55
    Points
    55
    Par défaut
    Bonjour,
    j'ai abandonné la méthode WebDAV pour aller vers les Web Services (Exchange Web Services).

    La connexion, l'identification et l'insertion de messages se passent pour ma part sans problèmes.

    Je suis entrain d'explorer les possibilités de l'Exchange Web Service Managed API 1.0.

    Je reviendrai indiquer les résultats de mes efforts et pourquoi pas donner quelques informations complémentaires.

  5. #5
    Membre à l'essai
    Profil pro
    Inscrit en
    Septembre 2009
    Messages
    19
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2009
    Messages : 19
    Points : 23
    Points
    23
    Par défaut Precision pour la connection à Exchange
    Je viens de me connecter à Exchange et je voudrai préciser un petit detail sur la connexion.

    Il faut importer le WebService https://<mon_serveur>/EWS/Services.wsdl
    et fournir au connecteur ExchangeServiceBinding l'URL https://<mon_serveur>/EWS/Exchange.asmx

    Sinon on a des erreurs 405 comme décrit ici (Là où j'ai trouvé la solution).

    http://www.mombu.com/microsoft/excha...d-1050514.html

  6. #6
    Futur Membre du Club
    Profil pro
    Inscrit en
    Juillet 2009
    Messages
    5
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2009
    Messages : 5
    Points : 6
    Points
    6
    Par défaut
    L'utilisation des web services (Exchange Web Service aka EWS) est devenu LA solution conseillée par Microsoft (le support Webdav ayant été arrété avec la version 2010 d'Exchange server)

    Pour s'initier à l'API permettant d'utiliser EWS (envoi d'email, récupération d'email avec critères..) ou découvrir quelques fonctionnalités tel que la gestion des propriétés personnalisées sur les emails, ca se passe ici:

    http://www.thomasdupuis.com/portfoli...hange-ews-api/

    Bon coding!

Discussions similaires

  1. VB6- Connexion à un serveur exchange
    Par Asdorve dans le forum VB 6 et antérieur
    Réponses: 2
    Dernier message: 18/11/2014, 14h00
  2. Réponses: 0
    Dernier message: 31/07/2014, 12h26
  3. [Exchange 2010] Connexion impossible entre Outlook et Serveur Exchange. (banal, mais)
    Par Kuma25 dans le forum Exchange Server
    Réponses: 5
    Dernier message: 11/03/2013, 10h18
  4. Problème de connexion à un serveur SMTP MS Exchange
    Par GillesN dans le forum Réseau
    Réponses: 0
    Dernier message: 24/02/2009, 19h13
  5. Script de connexion sur un serveur Exchange
    Par Scarface698 dans le forum Windows
    Réponses: 0
    Dernier message: 29/12/2008, 11h29

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