Fonction getContactExchange()

Résolu
Dedel209 Messages postés 29 Date d'inscription samedi 31 janvier 2009 Statut Membre Dernière intervention 14 août 2014 - 11 oct. 2013 à 10:06
Dedel209 Messages postés 29 Date d'inscription samedi 31 janvier 2009 Statut Membre Dernière intervention 14 août 2014 - 7 déc. 2013 à 13:16
Bonjour à tous,

voici mon code dans ma classe getAllContactExchange.cs
Je voudrais appeler la fonction getContactsExchange() lorsque je clique sur un bouton et que le résultat s'affiche dans un combobx. Seulement je ne sais pas le type de retour que je dois donner à ma fonction.

La modification ne doit pas être longue. Est ce que quelqu'un pourrait me donner une solution SVP?

Merci d'avance

class getAllContactsExchange
    {
        public List<Contact> getContactsExchange()
        {
            /*================================================================================================================================================*/
            /*==========================================================================VALIDATION CERTIFICAT=================================================*/
            /*================================================================================================================================================*/
            ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
            {
                // Si le certificat est un certificat valide, signée, retourner vrai
                if (errors == System.Net.Security.SslPolicyErrors.None)
                {
                    return true;
                }
                // Si erreur dans la chaine de certificat, Affiche chaque erreur pour déterminer la cause
                if ((errors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
                {
                    if (chain != null && chain.ChainStatus != null)
                    {
                        foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
                        {
                            if ((certificate.Subject == certificate.Issuer) &&
                               (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
                            {
                                // Self-signed certificates with an untrusted root are valid.
                                continue;
                            }
                            else
                            {
                                if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
                                {
                                    // If there are any other errors in the certificate chain, the certificate is invalid,
                                    // so the method returns false.
                                    return false;
                                }
                            }
                        }
                    }
                    //Lorsque le traitement atteint cette ligne, les seules erreurs dans la chaîne de certificats sont
                    //erreurs de racine non pour les certificats auto-signés. Ces certificats sont valables pour les installations de Exchange Server par défaut, de sorte return true.
                    return true;
                }
                else
                {
                    // Autres choix, return false.
                    return false;
                }
            };
            ExchangeService _service = new ExchangeService(ExchangeVersion.Exchange2010);
            _service.Credentials = new WebCredentials("user", "password");
            _service.Url = new Uri("https://mail.domain.be/ews/exchange.asmx");
            
            //Contact mailbox
            ContactsFolder contactsfolder = ContactsFolder.Bind(_service, WellKnownFolderName.Contacts);

            // Set the number of items to the number of items in the Contacts folder or 50, whichever is smaller.
            int numItems = contactsfolder.TotalCount < int.MaxValue ? contactsfolder.TotalCount : int.MaxValue;

            // Instantiate the item view with the number of items to retrieve from the Contacts folder.
            ItemView view = new ItemView(numItems);

            // To keep the request smaller, request only the display name property.
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName);

            // Retrieve the items in the Contacts folder that have the properties that you selected.
            FindItemsResults<Item> contactItems = _service.FindItems(WellKnownFolderName.Contacts, view);

            // Display the list of contacts. 
            foreach (Item item in contactItems)
            {

                if (item is Contact)
                {
                    Contact contact = item as Contact;
                    //comboBox1.Items.Add(contact.DisplayName);
                }
            }
        }
}



--

2 réponses

nagaD.scar Messages postés 4272 Date d'inscription samedi 8 septembre 2007 Statut Membre Dernière intervention 4 janvier 2023 17
11 oct. 2013 à 11:15
salut.

Tu peux gérer l'évenement "onClick", le plus simple étant, dans vs, de double cliquer dessus.
Tu auras par exemple :

private void button1_Click(object sender, EventArgs e)
{
    List<string> maList = getContactsExchange();
    foreach(string s un maList) 
    {
         maCombo.items.Add(s);
    }
}


"maCombo" étant le nom de ta combobox cible.

naga
0
Dedel209 Messages postés 29 Date d'inscription samedi 31 janvier 2009 Statut Membre Dernière intervention 14 août 2014
11 oct. 2013 à 14:59
Merci pour votre réponse mais je ne sais pas quoi mettre dans ma classe getAllContactsExchange.cs comme RETURN.

Je fais appel à cette classe en cliquant sur un bouton pour remplir ma combobox comme vous l'avez compris.

Ma classe getAllContactsExchange est développé dans mon premier post.

Donc pour le moment j'ai ceci :

private void button1_Click(object sender, EventArgs e)
{
    getAllContactsExchange getContact = new getAllContactsExchange();
    List<string> maList = getContact.getContactsExchange();
    foreach(string s un maList) 
    {
         maCombo.items.Add(s);
    }
} 




--
0
nagaD.scar Messages postés 4272 Date d'inscription samedi 8 septembre 2007 Statut Membre Dernière intervention 4 janvier 2023 17
11 oct. 2013 à 15:20
arf autant pour moi je n'avais pas vu "public List<Contact>".

Sinon je pense que tu t'emmêles un peu : tu as en effet une classe "getAllContactsExchange" mais une classe n'est pas une fonction et donc ne renvois pas de valeurs (Au mieux tu as la possibilitée de surcharger la méthode ToString mais on en reparlera, je veux pas t'embrouiller) , par contre la fonction "getContactsExchange" de la classe renvoi un résultat.

Je pense donc que tu souhaite que ta combo box affiche ta liste de Contact ? si c'est le cas, pourrais tu me montrer la classe Contact ? (ou au moins les paramètres qui la compose ? ).

Le code que je t'ai fourni est inexacte car (ma faute, j'ai lu trop vite), j''avais lu List<string> au lieu de List<Contact>. C'est à dire que la fonction sera plutôt du genre :

getAllContactsExchange getContact = new getAllContactsExchange();
    List<Contact> maList = getContact.getContactsExchange();
    foreach(Contact o in maList) 
    {
         //--ici nous ajouterons ton contact à la combo
    }



(ce qui me fait penser que c'est 'in' et non 'un' (faute de frappe, désolé)).


Ce qu'il me manque est la composition de ta classe 'Contact', ainsi que les valeurs que tu souhaites afficher dans ta combo.

naga
0
Dedel209 Messages postés 29 Date d'inscription samedi 31 janvier 2009 Statut Membre Dernière intervention 14 août 2014
11 oct. 2013 à 15:28
J'ai mis List<Contact> au dessus par erreur. Je ne sais pas vraiment quoi mettre.

Voici le code ma classe contact qui est en réalité générée par Exchange Web Services :

namespace Microsoft.Exchange.WebServices.Data
{
    // Résumé :
    //     Represents a contact. Properties available on contacts are defined in the
    //     ContactSchema class.
    [Attachable]
    [ServiceObjectDefinition("Contact")]
    public class Contact : Item
    {
        // Résumé :
        //     Initializes an unsaved local instance of Microsoft.Exchange.WebServices.Data.Contact.
        //     To bind to an existing contact, use Contact.Bind() instead.
        //
        // Paramètres :
        //   service:
        //     The ExchangeService object to which the contact will be bound.
        public Contact(ExchangeService service);

        // Résumé :
        //     Gets the Alias from the directory
        public string Alias { get; }
        //
        // Résumé :
        //     Gets or sets the contact's assistant name.
        public string AssistantName { get; set; }
        //
        // Résumé :
        //     Gets or sets the birthday of the contact.
        public DateTime? Birthday { get; set; }
        //
        // Résumé :
        //     Gets or sets the business home page of the contact.
        public string BusinessHomePage { get; set; }
        //
        // Résumé :
        //     Gets or sets a list of children for the contact.
        public StringList Children { get; set; }
        //
        // Résumé :
        //     Gets or sets a list of companies for the contact.
        public StringList Companies { get; set; }
        //
        // Résumé :
        //     Gets or sets the compnay name of the contact.
        public string CompanyName { get; set; }
        //
        // Résumé :
        //     Gets the complete name of the contact.
        public CompleteName CompleteName { get; }
        //
        // Résumé :
        //     Gets the source of the contact.
        public ContactSource? ContactSource { get; }
        //
        // Résumé :
        //     Gets or sets the department of the contact.
        public string Department { get; set; }
        //
        // Résumé :
        //     Gets the DirectoryID as Guid or DN string
        public string DirectoryId { get; }
        //
        // Résumé :
        //     Gets the Photo from the directory
        public byte[] DirectoryPhoto { get; }
        //
        // Résumé :
        //     Get the direct reports mailbox information
        public EmailAddressCollection DirectReports { get; }
        //
        // Résumé :
        //     Gets or sets the display name of the contact.
        public string DisplayName { get; set; }
        //
        // Résumé :
        //     Gets an indexed list of e-mail addresses for the contact. For example, to
        //     set the first e-mail address, use the following syntax: EmailAddresses[EmailAddressKey.EmailAddress1]
        //     = "john.doe@contoso.com"
        public EmailAddressDictionary EmailAddresses { get; }
        //
        // Résumé :
        //     Gets or set the name under which this contact is filed as. FileAs can be
        //     manually set or can be automatically calculated based on the value of the
        //     FileAsMapping property.
        public string FileAs { get; set; }
        //
        // Résumé :
        //     Gets or sets a value indicating how the FileAs property should be automatically
        //     calculated.
        public FileAsMapping FileAsMapping { get; set; }
        //
        // Résumé :
        //     Gets or sets the generation of the contact.
        public string Generation { get; set; }
        //
        // Résumé :
        //     Gets or sets the given name of the contact.
        public string GivenName { get; set; }
        //
        // Résumé :
        //     Gets a value indicating whether this contact has a picture associated with
        //     it.
        public bool HasPicture { get; }
        //
        // Résumé :
        //     Gets an indexed list of Instant Messaging addresses for the contact. For
        //     example, to set the first IM address, use the following syntax: ImAddresses[ImAddressKey.ImAddress1]
        //     = "john.doe@contoso.com"
        public ImAddressDictionary ImAddresses { get; }
        //
        // Résumé :
        //     Gets or sets the initials of the contact.
        public string Initials { get; set; }
        //
        // Résumé :
        //     Gets or sets the contact's job title.
        public string JobTitle { get; set; }
        //
        // Résumé :
        //     Gets or sets the name of the contact's manager.
        public string Manager { get; set; }
        //
        // Résumé :
        //     Gets the manager mailbox information
        public EmailAddress ManagerMailbox { get; }
        //
        // Résumé :
        //     Gets or sets the initials of the contact.
        public string MiddleName { get; set; }
        //
        // Résumé :
        //     Gets or sets the mileage for the contact.
        public string Mileage { get; set; }
        //
        // Résumé :
        //     Gets the MSExchange certificate from the directory
        public byte[][] MSExchangeCertificate { get; }
        //
        // Résumé :
        //     Gets or sets the middle name of the contact.
        public string NickName { get; set; }
        //
        // Résumé :
        //     Get the Notes from the directory
        public string Notes { get; }
        //
        // Résumé :
        //     Gets or sets the location of the contact's office.
        public string OfficeLocation { get; set; }
        //
        // Résumé :
        //     Gets an indexed list of phone numbers for the contact. For example, to set
        //     the home phone number, use the following syntax: PhoneNumbers[PhoneNumberKey.HomePhone]
        //     = "phone number"
        public PhoneNumberDictionary PhoneNumbers { get; }
        //
        // Résumé :
        //     Gets the phonetic first name from the directory
        public string PhoneticFirstName { get; }
        //
        // Résumé :
        //     Gets the full phonetic name from the directory
        public string PhoneticFullName { get; }
        //
        // Résumé :
        //     Gets the phonetic last name from the directory
        public string PhoneticLastName { get; }
        //
        // Résumé :
        //     Gets an indexed list of physical addresses for the contact. For example,
        //     to set the business address, use the following syntax: PhysicalAddresses[PhysicalAddressKey.Business]
        //     = new PhysicalAddressEntry()
        public PhysicalAddressDictionary PhysicalAddresses { get; }
        //
        // Résumé :
        //     Gets or sets the index of the contact's postal address. When set, PostalAddressIndex
        //     refers to an entry in the PhysicalAddresses indexed list.
        public PhysicalAddressIndex? PostalAddressIndex { get; set; }
        //
        // Résumé :
        //     Gets or sets the contact's profession.
        public string Profession { get; set; }
        //
        // Résumé :
        //     Gets or sets the name of the contact's spouse.
        public string SpouseName { get; set; }
        //
        // Résumé :
        //     Gets or sets the surname of the contact.
        public string Surname { get; set; }
        //
        // Résumé :
        //     Gets the User SMIME certificate from the directory
        public byte[][] UserSMIMECertificate { get; }
        //
        // Résumé :
        //     Gets or sets the date of the contact's wedding anniversary.
        public DateTime? WeddingAnniversary { get; set; }

        // Résumé :
        //     Binds to an existing contact and loads its first class properties.  Calling
        //     this method results in a call to EWS.
        //
        // Paramètres :
        //   service:
        //     The service to use to bind to the contact.
        //
        //   id:
        //     The Id of the contact to bind to.
        //
        // Retourne :
        //     A Contact instance representing the contact corresponding to the specified
        //     Id.
        public static Contact Bind(ExchangeService service, ItemId id);
        //
        // Résumé :
        //     Binds to an existing contact and loads the specified set of properties. 
        //     Calling this method results in a call to EWS.
        //
        // Paramètres :
        //   service:
        //     The service to use to bind to the contact.
        //
        //   id:
        //     The Id of the contact to bind to.
        //
        //   propertySet:
        //     The set of properties to load.
        //
        // Retourne :
        //     A Contact instance representing the contact corresponding to the specified
        //     Id.
        public static Contact Bind(ExchangeService service, ItemId id, PropertySet propertySet);
        //
        // Résumé :
        //     Retrieves the file attachment that holds the contact's picture.
        //
        // Retourne :
        //     The file attachment that holds the contact's picture.
        public FileAttachment GetContactPictureAttachment();
        //
        // Résumé :
        //     Removes the contact's picture.
        public void RemoveContactPicture();
        //
        // Résumé :
        //     Sets the contact's picture using the specified byte array.
        //
        // Paramètres :
        //   content:
        //     The bytes making up the picture.
        public void SetContactPicture(byte[] content);
        //
        // Résumé :
        //     Sets the contact's picture using the specified stream.
        //
        // Paramètres :
        //   contentStream:
        //     The stream containing the picture.
        public void SetContactPicture(Stream contentStream);
        //
        // Résumé :
        //     Sets the contact's picture using the specified file.
        //
        // Paramètres :
        //   fileName:
        //     The name of the file that contains the picture.
        public void SetContactPicture(string fileName);
    }
}
0
nagaD.scar Messages postés 4272 Date d'inscription samedi 8 septembre 2007 Statut Membre Dernière intervention 4 janvier 2023 17
11 oct. 2013 à 15:36
ok je crois que j'ai pigé ce que tu voudrais. à la fin de ta fonction , tu as :

 // Display the list of contacts. 
            foreach (Item item in contactItems)
            {

                if (item is Contact)
                {
                    Contact contact = item as Contact;
                    //comboBox1.Items.Add(contact.DisplayName);
                }
            }


édite de cette manière :
List<string>liste_Renvoye = new List<string>();
 // Display the list of contacts. 
            foreach (Item item in contactItems)
            {

                if (item is Contact)
                {
                    Contact contact = item as Contact;
                    liste_Renvoye .Add(contact.DisplayName);
                }
            }

return liste_Renvoye ;


en changeant la valeur renvoyée par ta fonction par List<string>.

Ensuite, pour le code de ton bouton, mets :
getAllContactsExchange getContact = new getAllContactsExchange();
    List<Contact> maList = getContact.getContactsExchange();
    foreach(Contact o in maList) 
    {
        maCombo.items.Add(s);
    }


de cette manière ta comboBox contiendra tous les "displayName" de tes contacts.

Ensuite ce qui me gène, ce sont ces return de booléen dans ta fonction , ca risque de te générer des erreurs (dans le cas contraire tu risque d'avoir des exception à la génération). Donc en attendant, change les "return true" et "return false" par des "return new List<string>". On verra ensuite pour corriger ça ;)
0
Dedel209 Messages postés 29 Date d'inscription samedi 31 janvier 2009 Statut Membre Dernière intervention 14 août 2014
Modifié par Dedel209 le 11/10/2013 à 15:49
Je viens d'essayer et ça fonctionne parfaitement.

CODE CLASSE getAllContactsExchange.cs

class getAllContactsExchange
    {
        public List<string> getContactsExchange()
        {
            ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
            {
                // Si le certificat est un certificat valide, signée, retourner vrai
                if (errors == System.Net.Security.SslPolicyErrors.None)
                {
                    return true;
                }
                // Si erreur dans la chaine de certificat, Affiche chaque erreur pour déterminer la cause
                if ((errors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
                {
                    if (chain != null && chain.ChainStatus != null)
                    {
                        foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
                        {
                            if ((certificate.Subject == certificate.Issuer) &&
                               (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
                            {
                                // Self-signed certificates with an untrusted root are valid.
                                continue;
                            }
                            else
                            {
                                if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
                                {
                                    // If there are any other errors in the certificate chain, the certificate is invalid,
                                    // so the method returns false.
                                    return false;
                                }
                            }
                        }
                    }
                    //Lorsque le traitement atteint cette ligne, les seules erreurs dans la chaîne de certificats sont
                    //erreurs de racine non pour les certificats auto-signés. Ces certificats sont valables pour les installations de Exchange Server par défaut, de sorte return true.
                    return true;
                }
                else




            ExchangeService _service = new ExchangeService(ExchangeVersion.Exchange2010);
            _service.Credentials = new WebCredentials("username", "password");
            _service.Url = new Uri("https://mail.domain.be/ews/exchange.asmx");


            //Contact mailbox
            ContactsFolder contactsfolder = ContactsFolder.Bind(_service, WellKnownFolderName.Contacts);

            // Set the number of items to the number of items in the Contacts folder or 50, whichever is smaller.
            int numItems = contactsfolder.TotalCount < int.MaxValue ? contactsfolder.TotalCount : int.MaxValue;

            // Instantiate the item view with the number of items to retrieve from the Contacts folder.
            ItemView view = new ItemView(numItems);

            // To keep the request smaller, request only the display name property.
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName);

            // Retrieve the items in the Contacts folder that have the properties that you selected.
            FindItemsResults<Item> contactItems = _service.FindItems(WellKnownFolderName.Contacts, view);

            List<string> list_Renvoye = new List<string>();
            // Display the list of contacts. 
            foreach (Item item in contactItems)
            {

                if (item is Contact)
                {
                    Contact contact = item as Contact;
                    list_Renvoye.Add(contact.DisplayName);
                    //comboBox1.Items.Add("" + contact.DisplayName + "" + contact.PhoneNumbers);
                }

            }

            return list_Renvoye;
        }
    }


CODE POUR MON BOUTON:
getAllContactsExchange getContact = new getAllContactsExchange();
            List<string> myList = getContact.getContactsExchange();
            foreach (string s in myList)
            {
                comboBoxClientExchange.Items.Add(s);
            }
0
nagaD.scar Messages postés 4272 Date d'inscription samedi 8 septembre 2007 Statut Membre Dernière intervention 4 janvier 2023 17
11 oct. 2013 à 15:56
ok niquel, et je viens de regarder vis à vis des return true/false, il appartiennent au delegate et donc ne risquent pas de te générer d'exceptions =)

Bonne continuation.
naga

PS : si c'est ok pour toi, mets le sujet en résolu ;)
0
Rejoignez-nous