Code d'application de l'outil Annotation Research Tool (exemple d'application EDM)

L'application EDM (Modèle de données d'entité) Annotation Research Tool est implémentée à l'aide d'un Windows Form et des contrôles de la boîte à outils Visual Studio.

Un contrôle WebBrowser est utilisé pour afficher les références Web. Différentes zones de texte permettent aux utilisateurs d'entrer des données qui deviennent des annotations et des informations de contact. Les chaînes d'URL assignées à la propriété Locator des instances Reference sont obtenues à partir de l'objet document de la page affichée dans le WebBrowser lors de la création des instances de la classe ReferenceDescriptor. Les gestionnaires d'événements effectuent tout le travail en réponse à l'entrée de l'utilisateur. Pour un affichage de l'interface utilisateur, voir Outil Annotation and Research Collaboration Tool (exemple d'application EDM).

Fichier Exe.Config et chaîne de connexion

Le fichier exe.config suivant contient la chaîne de connexion et les informations de configuration d'une base de données SQL Server ou SQL Server Compact 3.5. L'espace de noms System.Data.EntityClient qui contient les classes utilisées par la connexion et les métadonnées est également référencé.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="ResearchCollaborationData"
         connectionString="metadata=.;
             provider=System.Data.SqlClient;
             provider connection string='server=servername;
             database=ResearchCollaborationData;
             integrated security=true;
             multipleactiveresultsets=true'"
         providerName="System.Data.EntityClient"/>
  </connectionStrings>
</configuration>
NoteRemarque

Cette chaîne de connexion affecte la valeur true à plusieurs jeux de résultats actifs, comme le requiert l'appel à la méthode Load sur des associations lorsqu'un autre lecteur de données est déjà ouvert sur la même connexion.

Initialisation de la connexion au stockage

Avec le fichier exe.config précédent dans la portée de l'exécutable et une référence à System.Data.Entity.dll dans le projet, une ligne de code est suffisante pour ouvrir une connexion aux données utilisées par cette application.

    ResearchCollaborationData researchCollaborationData =
                                    new ResearchCollaborationData();

Tous les gestionnaires d'événements qui permettent à cette application d'interroger ou de mettre à jour les données utilisent cette initialisation. L'instruction suivante permet de fermer la connexion :

    researchCollaborationData.Connection.Close();

Création d'un descripteur de référence

Le code suivant crée une instance de la classe ReferenceDescriptor et l'enregistre sur le support de stockage. La séquence détermine si la page dans la fenêtre du WebBrowser existe déjà en tant qu'objet Reference. Si ce n'est pas le cas, une nouvelle instance de Reference est créée avec le ReferenceDescriptor. Si le Reference ne se trouve pas déjà dans le stockage, il est ajouté par le biais d'un appel à AddToReference : researchCollaborationData.AddToReferecne(newReference). Le ReferenceDescriptor est ajouté au stockage par le biais d'un appel à researchCollaborationData.AddToReferenceDescriptor(newReferenceDescriptor).

ReferenceDescriptor est également ajouté à la collection représentée par la propriété de navigation du Reference appelée RefDescriptors: newReference.RefDescriptors.Add(newReferenceDescriptor).

L'application n'implémente pas de méthode pour créer une instance Reference sans ReferenceDescriptor associé.

        private void buttonCreateRefDescriptor_Click(
            object sender, EventArgs e)
        {
            ResearchCollaborationData researchCollaborationData = null;
            try
            {
                using (researchCollaborationData =
                    new ResearchCollaborationData())
                {
                    ObjectParameter param = new ObjectParameter(
                        "p", webBrowser1.Document.Url.ToString());

                    if (!researchCollaborationData.Reference.Where(
                        "it.Locator = @p", param).Any())
                    {
                        Reference newReference = new Reference();
                        newReference.ReferenceID = Guid.NewGuid(); 
                        newReference.Locator = webBrowser1.Document.Url.ToString();

                        researchCollaborationData.AddToReference(newReference);

                        ReferenceDescriptor newReferenceDescriptor =
                             new ReferenceDescriptor();
                        newReferenceDescriptor.DescriptorID = Guid.NewGuid();

                        newReferenceDescriptor.Keyword = 
                            textBoxKeyWord.Text;

                        newReferenceDescriptor.Annotation = 
                            textBoxAnnotationResults.Text;

                        researchCollaborationData.AddToReferenceDescriptor(newReferenceDescriptor);

                        newReference.RefDescriptors.Add(
                            newReferenceDescriptor);
                    }
                    else
                    {
                        Reference reference = 
                            researchCollaborationData.Reference.Where(
                            "it.Locator = @p", param).First();

                        ReferenceDescriptor newReferenceDescriptor = 
                            new ReferenceDescriptor();
                        newReferenceDescriptor.DescriptorID = Guid.NewGuid();

                        newReferenceDescriptor.Keyword = 
                            textBoxKeyWord.Text;

                        newReferenceDescriptor.Annotation = 
                            textBoxAnnotationResults.Text;
                        researchCollaborationData.AddToReferenceDescriptor(newReferenceDescriptor);

                        reference.RefDescriptors.Add(
                            newReferenceDescriptor);
                    }

                    researchCollaborationData.SaveChanges();
                    

                    researchCollaborationData.Connection.Close();
                }
            }
            catch(Exception exception)
            {
                MessageBox.Show(exception.ToString());
                researchCollaborationData.Connection.Close();
            }
        }

Création d'une instance ContactPerson

Créer une instance ContactPerson puis l'associer à un Reference suit la même procédure que créer un ReferenceDescriptor et l'associer à un Reference. Quatre options de code sont possibles selon qu'il existe déjà un ContactPerson et/ou un Reference. Dans le cas précédent de création d'un ReferenceDescriptor, une nouvelle instance de descripteur est toujours créée. Le processus d'association d'un ContactPerson à un Reference détermine si une instance de ContactPerson représente déjà ce contact.

Un ReferenceDescriptor est associé à un seul Reference, alors qu'un ContactPerson peut être associé à de nombreux References. Pour plus d'informations sur l'implémentation du Association plusieurs-à-plusieurs qui prend en charge cette relation, voir Schémas de l'outil Annotation Research Tool (exemple d'application EDM).

Les quatre chemins de code dans le gestionnaire d'événements suivant connectent les instances de l'entité ContactPerson aux instances de l'entité Reference. La première option crée un ContactPerson et un Reference. Le nouveau ContactPerson et le nouveau Reference sont ajoutés au stockage à l'aide de AddToContactPerson et de AddToReference. Comme il s'agit d'une association plusieurs-à-plusieurs, une nouvelle entité de lien doit également être instanciée et ses propriétés de navigation initialisées pour connecter des instances de ContactPerson et Reference.

                    ContactPersonReference newLink = 
                        new ContactPersonReference();
                    newLink.ContactPersonRefID = Guid.NewGuid();

                    newLink.RelatedContact = newContact;
                    newLink.RelatedReference = newReference;

Cette séquence de code instancie l'entité de lien nommée ContactPersonReference. Les propriétés de navigation de l'entité de lien représentent les deux terminaisons de l'association : RelatedContact et RelatedReference. Celles-ci sont affectées des nouvelles instances de ContactPerson et Reference créées dans ce chemin de code. Dans d'autres cas, dans lesquels ContactPerson et/ou Reference existent déjà, les assignations utilisent des instances existantes localisées par des requêtes d'objet.

La nouvelle entité de lien est ajoutée au support de stockage et toutes les nouvelles instances d'entités sont enregistrées dans le code suivant.

        researchCollaborationData.AddToContactPersonReference(newLink);
        researchCollaborationData.SaveChanges();

Deux des quatre chemins de code possibles sont présentés dans la séquence suivante. Pour consulter l'intégralité des gestionnaires d'événements, voir la méthode : private void buttonCreateRefPerson_Click(object sender, EventArgs e) dans le code de tous les gestionnaires d'événements à la fin de cette rubrique.

                    ObjectParameter paramContact = 
                        new ObjectParameter("p", textBoxEmail.Text);

                    if (!researchCollaborationData.ContactPerson.Where(
                        "it.Email = @p", paramContact).Any())
                    {
                        ObjectParameter paramReference = 
                            new ObjectParameter("p", 
                            webBrowser1.Document.Url.ToString());

                        if (!researchCollaborationData.Reference.Where(
                            "it.Locator = @p", paramReference).Any())
                        {
                            // Neither contact nor reference exist.
                            ContactPerson newContact = new ContactPerson();
                            newContact.ContactPersonID = Guid.NewGuid(); 
                            newContact.LastName = textBoxLastName.Text;
                            newContact.FirstName = textBoxFirstName.Text; 
                            newContact.Email = textBoxEmail.Text;

                            newContact.Title = 
                                textBoxTitlePosition.Text;

                            researchCollaborationData.AddToContactPerson(newContact);

                            Reference newReference = new Reference();
                            newReference.ReferenceID = Guid.NewGuid(); 
                            newReference.Locator = webBrowser1.Document.Url.ToString();

                            researchCollaborationData.AddToReference(newReference);

                            ContactPersonReference newLink = 
                                new ContactPersonReference();
                            newLink.ContactPersonRefID = Guid.NewGuid();

                            newLink.RelatedContact = newContact;
                            newLink.RelatedReference = newReference;
                            researchCollaborationData.AddToContactPersonReference(newLink);
                        }

                        else
                        {
                            // Reference exists but contact doesn't.
                            Reference reference = 
                                researchCollaborationData.Reference.
                                Where("it.Locator = @p", 
                                paramReference).First();

                            ContactPerson newContact = new ContactPerson();
                            newContact.ContactPersonID = Guid.NewGuid(); 
                            newContact.LastName = textBoxLastName.Text;
                            newContact.FirstName = textBoxFirstName.Text; 
                            newContact.Email = textBoxEmail.Text;

                            newContact.Title = 
                                textBoxTitlePosition.Text;

                            researchCollaborationData.AddToContactPerson(newContact);

                            ContactPersonReference newLink = new ContactPersonReference();
                            newLink.ContactPersonRefID = Guid.NewGuid();
                            newLink.RelatedContact = newContact;
                            newLink.RelatedReference = reference;
                            researchCollaborationData.AddToContactPersonReference(newLink);

                        }
                    }

Rechercher des références à l'aide de descripteurs de référence

Les instances de l'entité ReferenceDescriptor sont des annotations qui permettent de décrire et rechercher des ressources Web afin qu'il ne soit pas nécessaire de répéter ni de cataloguer la recherche à un autre endroit. Chaque ReferenceDescriptor représente une seule annotation. Si de nombreuses instances de ReferenceDescriptor peuvent décrire une page Web, chaque instance ne peut être associée qu'à une seule page.

Les références Web sont annotées en ajoutant des instances ReferenceDescriptor tel que décrit dans les segments de code précédents. La recherche des propriétés Annotation et Keyword des instances ReferenceDescriptor fournit un moyen de déplacer des pages Reference utiles. Le gestionnaire d'événements suivant est occupé lorsque l'utilisateur entre des mots clés ou une expression de recherche dans la zone de texte et qu'il clique sur le bouton Find.

        private void buttonSearch_Click(object sender, EventArgs e)
        {
            ResearchCollaborationData researchCollaborationData = null;
            try
            {
                using (researchCollaborationData = 
                    new ResearchCollaborationData())
                {
                    // Make a list of keywords to search for in annotatations.
                    List<string> keywords = new List<string>();
                    int i = 0;
                    int j = 0;
                    while (i < textBoxSearch.Text.Length)
                    {
                        j = textBoxSearch.Text.IndexOf(" ", i);
                        if (-1 == j) j = textBoxSearch.Text.Length;

                        keywords.Add(
                             textBoxSearch.Text.Substring(i, j - i));

                        i = ++j;
                    }

                    textBoxAnnotationResults.Text = "Results:";
                    foreach (string keyword in keywords)
                    {
                        // Create ObjectParameter from each keyword.
                        ObjectParameter paramKeyword = 
                            new ObjectParameter(
                            "p", "%" + keyword + "%");

                        ObjectQuery<ReferenceDescriptor> 
                            descriptorQuery = 
                            researchCollaborationData.
                            ReferenceDescriptor.Where(
                            "it.Annotation LIKE @p OR it.Keyword LIKE @p",
                            paramKeyword);

                        foreach (ReferenceDescriptor refDescriptor
                                                  in descriptorQuery)
                        {

                            textBoxAnnotationResults.Text = 
                                textBoxAnnotationResults.Text + "\n" +
                                refDescriptor.Keyword + "\n" + 
                                refDescriptor.Annotation;

                           refDescriptor.ReferenceReference.Load();

                            Reference reference = refDescriptor.Reference;

                            textBoxAnnotationResults.Text = 
                                textBoxAnnotationResults.Text + "\n" +
                                reference.Locator + "\n";

                            foreach (ContactPersonReference contactPersRef in
                                researchCollaborationData.ContactPersonReference)
                            {
                                contactPersRef.RelatedReferenceReference.Load();
                                if (contactPersRef.RelatedReferenceReference.Value.Equals(
                                    reference))
                                {
                                    contactPersRef.RelatedContactReference.Load();

                                    textBoxAnnotationResults.Text =
                                    textBoxAnnotationResults.Text +
                                    "\n" +
                                    "Relevant Contact:";

                                    textBoxAnnotationResults.Text =
                                        textBoxAnnotationResults.Text +
                                        "\n" +
                                        contactPersRef.
                                        RelatedContact.FirstName + " " +
                                        contactPersRef.RelatedContact.
                                        LastName +
                                        " Title: " + contactPersRef.
                                        RelatedContact.Title + " Email: "
                                        + contactPersRef.RelatedContact.
                                        Email
                                        + "\n";
                                }
                            }                            
                        }                        
                    }
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }
            
        }

Ce code est composé de deux séquences de base : une pour créer un List<T> de chaînes recherchées et une autre pour rechercher un texte correspondant dans les propriétés Keyword et Annotation des instances de ReferenceDescriptor.

La création de la liste de chaînes recherchées s'effectue en analysant le texte d'entrée. La requête est un objet ObjectQuery paramétré, utilisé dans une boucle, qui insère chaque chaîne recherchée dans la requête et la compare aux textes assignés aux propriétés Keyword et Annotation des instances de ReferenceDescriptor sur le support de stockage. Les classes ObjectParameter et ObjectQuery sont instanciées dans le segment de code suivant.

               // Create ObjectParameter from each keyword.
               ObjectParameter paramKeyword = 
                    new ObjectParameter(
                    "p", "%" + keyword + "%");

                ObjectQuery<ReferenceDescriptor> 
                     descriptorQuery = 
                     researchCollaborationData.
                     ReferenceDescriptor.Where(
                     "it.Annotation LIKE @p OR it.Keyword LIKE @p",
                     paramKeyword);

Chaque ReferenceDescriptor retourné par le ObjectQuery entre dans une boucle qui charge le Reference associé à l'aide de son NavigationProperty et du Association conçu à cette fin. Le segment de code suivant charge le Reference, lit sa propriété Locator et affiche l'URL du Reference sous forme de lien dans la zone de texte des résultats.

                           refDescriptor.ReferenceReference.Load();

                            Reference reference = refDescriptor.Reference;

                            textBoxAnnotationResults.Text = 
                                textBoxAnnotationResults.Text + "\n" +
                                reference.Locator + "\n";

Enfin, la méthode recherche et affiche les informations concernant les contacts liés au Reference. Une méthode statique du LinkTable_ReferenceAssociation permet de localiser les entités de table de liens associées au Reference. Des instances de ContactPersonReference, les entités de table de liens qui contiennent le Reference, entrent dans une boucle qui charge et affiche les propriétés du ContactPerson associé. Les propriétés FirstName, LastName, Title et Email sont affichées associées aux textes ReferenceAnnotation et Locator trouvés par le code précédent.

                            foreach (ContactPersonReference contactPersRef in
                                researchCollaborationData.ContactPersonReference)
                            {
                                contactPersRef.RelatedReferenceReference.Load();
                                if (contactPersRef.RelatedReferenceReference.Equals(
                                    reference))
                                {
                                    contactPersRef.RelatedContactReference.Load();

                                    textBoxAnnotationResults.Text =
                                    textBoxAnnotationResults.Text +
                                    "\n" +
                                    "Relevant Contact:";

                                    textBoxAnnotationResults.Text =
                                        textBoxAnnotationResults.Text +
                                        "\n" +
                                        contactPersRef.
                                        RelatedContact.FirstName + " " +
                                        contactPersRef.RelatedContact.
                                        LastName +
                                        " Title: " + contactPersRef.
                                        RelatedContact.Title + " Email: "
                                        + contactPersRef.RelatedContact.
                                        Email
                                        + "\n";
                                }
                            }  

Rechercher des références associées aux contacts

Il est possible de rechercher des instances de Reference associées aux instances ContactPerson à l'aide de l'entité de table de liens et des associations du segment de code précédent. Les utilisateurs de cette application peuvent rechercher des pages de référence à partir d'un contact en renseignant les zones de texte LastName et/ou Email et en cliquant sur le bouton intitulé Find Ref/Person. De nouvelles instances de l'objet ObjectParameter sont créées à partir des textes LastName et Email. Les paramètres sont utilisés par un objet ObjectQuery pour rechercher une personne ayant le même nom ou la même adresse de messagerie. La méthode Any de l'objet ObjectQuery permet de tester si cette requête a obtenu des résultats.

Si une instance de ContactPerson possédant un même nom ou une même adresse de messagerie est trouvée, les informations de contact sont affichées avec les documents Reference associés. La recherche des documents associés s'effectue, comme dans la méthode précédente, à l'aide de l'entité de lien ContactPersonReference et de ses propriétés de navigation.

        private void buttonFindRefPerson_Click(object sender, EventArgs e)
        {
            ResearchCollaborationData researchCollaborationData = null;
            try
            {
                using (researchCollaborationData = 
                    new ResearchCollaborationData())
                {
                    // Use parameters from LastName and 
                    // Email text boxes in search.
                    ObjectParameter emailParam = new ObjectParameter(
                        "email", textBoxEmail.Text);
                    ObjectParameter nameParam = new ObjectParameter(
                        "name", textBoxLastName.Text);
                    ObjectParameter[] objParams = { emailParam, 
                        nameParam };
                    
                    ObjectQuery<ContactPerson> query = 
                        researchCollaborationData.ContactPerson.Where(
                        "it.Email = @email OR it.LastName = @name", 
                        objParams );

                    if (query.Any())
                    {
                        textBoxAnnotationResults.Text = 
                            "Contact and associated reference documents:\n";

                        ContactPerson person = null;
                        query.FirstOrDefault(out person);

                        // Display contact information and 
                        // related references.
                        textBoxAnnotationResults.Text = 
                            textBoxAnnotationResults.Text +
                            person.FirstName + " " + person.LastName +
                            " Title: " + person.Title +
                            " Email address: " + person.Email;

                        ObjectParameter contactParam = 
                            new ObjectParameter("p", 
                            person.ContactPersonID);

                        foreach (ContactPersonReference contactReference
                            in researchCollaborationData.
                            ContactPersonReference.Where(
                            "it.RelatedContact.ContactPersonID = @p",
                            contactParam))
                        {
                            contactReference.RelatedReferenceReference.
                                Load();

                            textBoxAnnotationResults.Text = 
                                textBoxAnnotationResults.Text + "\n" +
                                contactReference.RelatedReference.Locator;
                        }
                    }                                        
                }
            }

            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }

        }

Code de tous les gestionnaires d'événements de l'application

Le code suivant contient tous les gestionnaires d'événements utilisés pour initialiser l'objet EntityConnection et rechercher et mettre à jour des données basées sur Research Collaboration Data Model.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.Common;
using System.Data.Objects;
using System.Linq;
using ResearchCollaborationDataModel;

namespace ResearchCollaboration
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();

            try
            {
                webBrowser1.Navigate(
                    "http://www.live.com/?searchonly=true");               

            }

            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

        private void buttonNavigate_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate(textBoxUri.Text);
        }

        private void buttonCreateRefDescriptor_Click(
            object sender, EventArgs e)
        {
            ResearchCollaborationData researchCollaborationData = null;
            try
            {
                using (researchCollaborationData =
                    new ResearchCollaborationData())
                {
                    ObjectParameter param = new ObjectParameter(
                        "p", webBrowser1.Document.Url.ToString());

                    if (!researchCollaborationData.Reference.Where(
                        "it.Locator = @p", param).Any())
                    {
                        Reference newReference = new Reference();
                        newReference.ReferenceID = Guid.NewGuid(); 
                        newReference.Locator = webBrowser1.Document.Url.ToString();

                        researchCollaborationData.AddToReference(newReference);

                        ReferenceDescriptor newReferenceDescriptor =
                             new ReferenceDescriptor();
                        newReferenceDescriptor.DescriptorID = Guid.NewGuid();

                        newReferenceDescriptor.Keyword = 
                            textBoxKeyWord.Text;

                        newReferenceDescriptor.Annotation = 
                            textBoxAnnotationResults.Text;

                        researchCollaborationData.AddToReferenceDescriptor(newReferenceDescriptor);

                        newReference.RefDescriptors.Add(
                            newReferenceDescriptor);
                    }
                    else
                    {
                        Reference reference = 
                            researchCollaborationData.Reference.Where(
                            "it.Locator = @p", param).First();

                        ReferenceDescriptor newReferenceDescriptor = 
                            new ReferenceDescriptor();
                        newReferenceDescriptor.DescriptorID = Guid.NewGuid();

                        newReferenceDescriptor.Keyword = 
                            textBoxKeyWord.Text;

                        newReferenceDescriptor.Annotation = 
                            textBoxAnnotationResults.Text;
                        researchCollaborationData.AddToReferenceDescriptor(newReferenceDescriptor);

                        reference.RefDescriptors.Add(
                            newReferenceDescriptor);
                    }

                    researchCollaborationData.SaveChanges();
                    

                    researchCollaborationData.Connection.Close();
                }
            }
            catch(Exception exception)
            {
                MessageBox.Show(exception.ToString());
                researchCollaborationData.Connection.Close();
            }
        }

 
        private void buttonSearch_Click(object sender, EventArgs e)
        {
            ResearchCollaborationData researchCollaborationData = null;
            try
            {
                using (researchCollaborationData = 
                    new ResearchCollaborationData())
                {
                    // Make a list of keywords to search for in annotatations.
                    List<string> keywords = new List<string>();
                    int i = 0;
                    int j = 0;
                    while (i < textBoxSearch.Text.Length)
                    {
                        j = textBoxSearch.Text.IndexOf(" ", i);
                        if (-1 == j) j = textBoxSearch.Text.Length;

                        keywords.Add(
                             textBoxSearch.Text.Substring(i, j - i));

                        i = ++j;
                    }

                    textBoxAnnotationResults.Text = "Results:";
                    foreach (string keyword in keywords)
                    {
                        // Create ObjectParameter from each keyword.
                        ObjectParameter paramKeyword = 
                            new ObjectParameter(
                            "p", "%" + keyword + "%");

                        ObjectQuery<ReferenceDescriptor> 
                            descriptorQuery = 
                            researchCollaborationData.
                            ReferenceDescriptor.Where(
                            "it.Annotation LIKE @p OR it.Keyword LIKE @p",
                            paramKeyword);

                        foreach (ReferenceDescriptor refDescriptor
                                                  in descriptorQuery)
                        {

                            textBoxAnnotationResults.Text = 
                                textBoxAnnotationResults.Text + "\n" +
                                refDescriptor.Keyword + "\n" + 
                                refDescriptor.Annotation;

                           refDescriptor.ReferenceReference.Load();

                            Reference reference = refDescriptor.Reference;

                            textBoxAnnotationResults.Text = 
                                textBoxAnnotationResults.Text + "\n" +
                                reference.Locator + "\n";

                            foreach (ContactPersonReference contactPersRef in
                                researchCollaborationData.ContactPersonReference)
                            {
                                contactPersRef.RelatedReferenceReference.Load();
                                if (contactPersRef.RelatedReferenceReference.Equals(
                                    reference))
                                {
                                    contactPersRef.RelatedContactReference.Load();

                                    textBoxAnnotationResults.Text =
                                    textBoxAnnotationResults.Text +
                                    "\n" +
                                    "Relevant Contact:";

                                    textBoxAnnotationResults.Text =
                                        textBoxAnnotationResults.Text +
                                        "\n" +
                                        contactPersRef.
                                        RelatedContact.FirstName + " " +
                                        contactPersRef.RelatedContact.
                                        LastName +
                                        " Title: " + contactPersRef.
                                        RelatedContact.Title + " Email: "
                                        + contactPersRef.RelatedContact.
                                        Email
                                        + "\n";
                                }
                            }                            
                        }                        
                    }
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }
            
        }

        
        private void buttonCreateRefPerson_Click(object sender, 
            EventArgs e)
        {
            ResearchCollaborationData researchCollaborationData = null;
            try
            {
                using (researchCollaborationData = 
                    new ResearchCollaborationData())
                {
                    // There are four possible cases depending 
                    // whether contact and reference exist.

                    ObjectParameter paramContact = 
                        new ObjectParameter("p", textBoxEmail.Text);

                    if (!researchCollaborationData.ContactPerson.Where(
                        "it.Email = @p", paramContact).Any())
                    {
                        ObjectParameter paramReference = 
                            new ObjectParameter("p", 
                            webBrowser1.Document.Url.ToString());

                        if (!researchCollaborationData.Reference.Where(
                            "it.Locator = @p", paramReference).Any())
                        {
                            // Neither contact nor reference exist.
                            ContactPerson newContact = new ContactPerson();
                            newContact.ContactPersonID = Guid.NewGuid(); 
                            newContact.LastName = textBoxLastName.Text;
                            newContact.FirstName = textBoxFirstName.Text; 
                            newContact.Email = textBoxEmail.Text;

                            newContact.Title = 
                                textBoxTitlePosition.Text;

                            researchCollaborationData.AddToContactPerson(newContact);

                            Reference newReference = new Reference();
                            newReference.ReferenceID = Guid.NewGuid(); 
                            newReference.Locator = webBrowser1.Document.Url.ToString();

                            researchCollaborationData.AddToReference(newReference);

                            ContactPersonReference newLink = 
                                new ContactPersonReference();
                            newLink.ContactPersonRefID = Guid.NewGuid();

                            newLink.RelatedContact = newContact;
                            newLink.RelatedReference = newReference;
                            researchCollaborationData.AddToContactPersonReference(newLink);
                        }

                        else
                        {
                            // Reference exists but contact doesn't.
                            Reference reference = 
                                researchCollaborationData.Reference.
                                Where("it.Locator = @p", 
                                paramReference).First();

                            ContactPerson newContact = new ContactPerson();
                            newContact.ContactPersonID = Guid.NewGuid(); 
                            newContact.LastName = textBoxLastName.Text;
                            newContact.FirstName = textBoxFirstName.Text; 
                            newContact.Email = textBoxEmail.Text;

                            newContact.Title = 
                                textBoxTitlePosition.Text;

                            researchCollaborationData.AddToContactPerson(newContact);

                            ContactPersonReference newLink = new ContactPersonReference();
                            newLink.ContactPersonRefID = Guid.NewGuid();
                            newLink.RelatedContact = newContact;
                            newLink.RelatedReference = reference;
                            researchCollaborationData.AddToContactPersonReference(newLink);

                        }
                    }

                    else
                    {
                        // Contact exists but reference doesn't.
                        ObjectParameter paramReference = 
                            new ObjectParameter("p", 
                            webBrowser1.Document.Url.ToString());

                        if (!researchCollaborationData.Reference.Where(
                            "it.Locator = @p", paramReference).Any())
                        {
                            ContactPerson contact = 
                                researchCollaborationData.ContactPerson.
                                Where("it.Email = @p", 
                                paramContact).First();

                            Reference newReference = new Reference();
                            newReference.ReferenceID = Guid.NewGuid(); 
                            newReference.Locator = webBrowser1.Document.Url.ToString();

                            researchCollaborationData.AddToReference(newReference);

                            ContactPersonReference newLink = new ContactPersonReference();
                            newLink.ContactPersonRefID = Guid.NewGuid();

                            newLink.RelatedContact = contact;
                            newLink.RelatedReference = newReference;
                            researchCollaborationData.AddToContactPersonReference(newLink);

                        }

                        else
                        {
                            // Contact and reference both exist.
                            Reference reference = 
                                researchCollaborationData.Reference.
                                Where("it.Locator = @p", 
                                paramReference).First();

                            ContactPerson contact = 
                                researchCollaborationData.
                                ContactPerson.Where("it.Email = @p", 
                                paramContact).First();
                            
                            ContactPersonReference newLink = new ContactPersonReference();
                            newLink.ContactPersonRefID = Guid.NewGuid();
                            newLink.RelatedContact = contact;
                            newLink.RelatedReference = reference;
                            researchCollaborationData.AddToContactPersonReference(newLink);

                        }
                        
                    }

                    researchCollaborationData.SaveChanges();

                    researchCollaborationData.Connection.Close();
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }

        }
        
        private void buttonFindRefPerson_Click(object sender, EventArgs e)
        {
            ResearchCollaborationData researchCollaborationData = null;
            try
            {
                using (researchCollaborationData = 
                    new ResearchCollaborationData())
                {
                    // Use parameters from LastName and 
                    // Email text boxes in search.
                    ObjectParameter emailParam = new ObjectParameter(
                        "email", textBoxEmail.Text);
                    ObjectParameter nameParam = new ObjectParameter(
                        "name", textBoxLastName.Text);
                    ObjectParameter[] objParams = { emailParam, 
                        nameParam };
                    
                    ObjectQuery<ContactPerson> query = 
                        researchCollaborationData.ContactPerson.Where(
                        "it.Email = @email OR it.LastName = @name", 
                        objParams );

                    if (query.Any())
                    {
                        textBoxAnnotationResults.Text = 
                            "Contact and associated reference documents:\n";

                        ContactPerson person = null;
                        query.FirstOrDefault(out person);

                        // Display contact information and 
                        // related references.
                        textBoxAnnotationResults.Text = 
                            textBoxAnnotationResults.Text +
                            person.FirstName + " " + person.LastName +
                            " Title: " + person.Title +
                            " Email address: " + person.Email;

                        ObjectParameter contactParam = 
                            new ObjectParameter("p", 
                            person.ContactPersonID);

                        foreach (ContactPersonReference contactReference
                            in researchCollaborationData.
                            ContactPersonReference.Where(
                            "it.RelatedContact.ContactPersonID = @p",
                            contactParam))
                        {
                            contactReference.RelatedReferenceReference.
                                Load();

                            textBoxAnnotationResults.Text = 
                                textBoxAnnotationResults.Text + "\n" +
                                contactReference.RelatedReference.Locator;
                        }
                    }                                        
                }
            }

            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }

        }

        private void textBoxUri_PreviewKeyDown(object sender, 
            PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode.Equals(Keys.Return))
                buttonNavigate_Click(this, System.EventArgs.Empty);
        }

        private void textBoxSearch_PreviewKeyDown(object sender, 
            PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode.Equals(Keys.Return))
                buttonSearch_Click(this, null);
        }

        private void textBoxAnnotationResults_LinkClicked(object sender, 
            LinkClickedEventArgs e)
        {
            // Display the Locator URL in Web browser.
            webBrowser1.Navigate(e.LinkText);
        }

        private void webBrowser1_DocumentCompleted(object sender, 
            WebBrowserDocumentCompletedEventArgs e)
        {
            textBoxUri.Text = webBrowser1.Document.Url.ToString();
        }

        private void textBoxEmail_MouseDoubleClick(object sender, 
            MouseEventArgs e)
        {
            ResearchCollaborationData researchCollaborationData = null;
            try
            {
                researchCollaborationData = 
                    new ResearchCollaborationData();

                textBoxAnnotationResults.Text = 
                    "Contacts and related references:";

                // Find and display all contacts and 
                // their related references.
                foreach (ContactPerson person in 
                    researchCollaborationData.ContactPerson)
                {
                    textBoxAnnotationResults.Text = 
                        textBoxAnnotationResults.Text + "\n\n" +
                        person.FirstName + " " + person.LastName + 
                        " Title: " + person.Title +
                        " Email address: " + person.Email;

                    ObjectParameter contactParam = new ObjectParameter(
                        "p", person.ContactPersonID);

                    foreach (ContactPersonReference contactReference in 
                        researchCollaborationData.ContactPersonReference.
                        Where("it.RelatedContact.ContactPersonID = @p",
                        contactParam))
                    {
                        contactReference.RelatedReferenceReference.Load();
                        textBoxAnnotationResults.Text = 
                            textBoxAnnotationResults.Text + 
                            "\n" + 
                            contactReference.RelatedReference.Locator;
                    }

                }     

            }

            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }

        }

        private void textBoxSearch_MouseDoubleClick(object sender,
            EventArgs e)
        {
            ResearchCollaborationData researchCollaborationData = null;
            try
            {
                researchCollaborationData = 
                    new ResearchCollaborationData();

                textBoxAnnotationResults.Text = 
                    "All references and related contacts:\n";

                foreach (ReferenceDescriptor refDescriptor in 
                    researchCollaborationData.ReferenceDescriptor)
                {

                    textBoxAnnotationResults.Text = 
                        textBoxAnnotationResults.Text + "\n" +
                        refDescriptor.Keyword + "\n" + 
                        refDescriptor.Annotation;
                    
                    refDescriptor.ReferenceReference.Load();

                    Reference reference = refDescriptor.Reference;

                    textBoxAnnotationResults.Text = 
                        textBoxAnnotationResults.Text + "\n" +
                        reference.Locator + "\n";

                    foreach (ContactPersonReference contactPersonRef in 
                        researchCollaborationData.ContactPersonReference)
                    {
                        if(contactPersonRef.Equals(reference))
                        {
                            contactPersonRef.RelatedContactReference.Load();

                            textBoxAnnotationResults.Text = 
                            textBoxAnnotationResults.Text + "\n" +
                            "Relevant Contact:";

                            textBoxAnnotationResults.Text = 
                            textBoxAnnotationResults.Text + "\n" +
                            contactPersonRef.RelatedContact.FirstName + " " + 
                            contactPersonRef.RelatedContact.LastName + " Title: " + 
                            contactPersonRef.RelatedContact.Title + " Email: " +
                            contactPersonRef.RelatedContact.Email + "\n";
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }

        }
        
    }
}

Voir aussi

Concepts

Outil Annotation and Research Collaboration Tool (exemple d'application EDM)
Schémas de l'outil Annotation Research Tool (exemple d'application EDM)