Код приложения средства для заметок и исследований (образец приложения модели EDM)
Приложение Annotation Research Tool модели Entity Data Model (EDM) реализовано с использованием формы Windows Forms и элементов управления из области элементов Visual Studio.
Элемент управления WebBrowser используется для отображения веб-ссылок. Различные текстовые поля позволяют пользователям вводить сведения, которые станут заметками или контактной информацией. Строки URL-адресов, назначаемые свойству Locator экземпляров Reference, получаются от объекта документа страницы, отображенной в WebBrowser при создании экземпляров класса ReferenceDescriptor. После ввода данных пользователями всю работу выполняют обработчики событий. Интерфейс пользователя см. в Средство Annotation and Research Collaboration Tool (образец приложения модели EDM).
Исполняемый файл конфигурации и строка соединения
В следующем исполняемом файле конфигурации содержится строка соединения и сведения о конфигурации базы данных SQL Server или SQL Server Compact 3.5. Также имеются ссылки на пространство имен System.Data.EntityClient, которое содержит классы, используемые соединением и метаданными.
<?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>
![]() |
---|
Эта строка соединения устанавливает для параметра режима MARS значение |
Инициализация соединения с хранилищем
Одной строки кода достаточно, чтобы соединиться с данными, используемым этим приложением, когда в проекте предыдущий исполняемый файл конфигурации находится в области действия исполняемого объекта и имеется ссылка на файл System.Data.Entity.dll.
ResearchCollaborationData researchCollaborationData =
new ResearchCollaborationData();
Эта инициализация используется всеми обработчиками событий, которые это приложение задействует, чтобы запрашивать или обновлять данные. Соединение разрывается при помощи следующей инструкции:
researchCollaborationData.Connection.Close();
Создание дескриптора ссылки
Следующий код создает экземпляр класса ReferenceDescriptor и сохраняет его в хранилище. Эта последовательность определяет, существует ли уже страница в окне WebBrowser как объект Reference. Если нет, то создается новый экземпляр сущности Reference с дескриптором ссылки ReferenceDescriptor. Если сущность Reference еще не находится в хранилище, она добавляется туда при помощи вызова метода AddToReference: researchCollaborationData.AddToReferecne(newReference)
. Сущность ReferenceDescriptor добавляется в хранилище при помощи вызова researchCollaborationData.AddToReferenceDescriptor(newReferenceDescriptor)
.
Сущность ReferenceDescriptor также добавляется в коллекцию, представленную свойством навигации сущности Reference под названием RefDescriptors: newReference.RefDescriptors.Add(newReferenceDescriptor)
.
Для создания экземпляра сущности Reference приложение не использует метод без связанной с ним сущности ReferenceDescriptor.
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();
}
}
Создание экземпляра ContactPerson
Для создания нового экземпляра сущности ContactPerson и ассоциирования его с сущностью Reference используется такая же процедура, как для создания экземпляра сущности ReferenceDescriptor и его ассоциирования с сущностью Reference. Можно использовать четыре варианта кода в зависимости от того, существует ли уже только сущность ContactPerson или еще и сущность Reference. В первом случае при создании экземпляра сущности ReferenceDescriptor всегда создается новый экземпляр дескриптора. В процессе ассоциирования сущности ContactPerson с сущностью Reference определяется, представляет ли уже экземпляр сущности ContactPerson это контактное лицо.
Сущность ReferenceDescriptor ассоциируется только с одной сущностью Reference, тогда как экземпляр сущности ContactPerson можно ассоциировать с несколькими сущностями References. Дополнительные сведения об ассоциациях Association типа «многие ко многим», поддерживающих эту связь, см. в разделе Схемы программы Annotation Research Tool (образец приложения модели EDM).
Все четыре кодовых пути в следующем обработчике событий связывают экземпляры сущности ContactPerson с экземплярами сущности Reference. При использовании первого варианта создается новый экземпляр сущности ContactPerson и новая сущность Reference. Новый экземпляр сущности ContactPerson и новая сущность Reference добавляются в хранилище при помощи методов AddToContactPerson и AddToReference. Поскольку это ассоциация типа «многие ко многим», сущность новой ссылки также должна быть создана в виде экземпляра, а ее свойства навигации инициализированы, чтобы подключить экземпляры сущностей ContactPerson и Reference.
ContactPersonReference newLink =
new ContactPersonReference();
newLink.ContactPersonRefID = Guid.NewGuid();
newLink.RelatedContact = newContact;
newLink.RelatedReference = newReference;
Этот код создает экземпляр сущности ссылки ContactPersonReference. Сущность ссылки имеет свойства навигации, представляющие два следующих элемента ассоциации: RelatedContact и RelatedReference. Это назначенные новые экземпляры сущностей ContactPerson и Reference, созданные в этом кодовом пути. В других случаях, когда одна из двух сущностей — ContactPerson либо Reference — или обе уже существуют, назначения используют существующие экземпляры, обнаруженные запросами к объектам.
Новая сущность ссылки добавляется в хранилище, а все экземпляры этой сущности сохраняются в следующем коде.
researchCollaborationData.AddToContactPersonReference(newLink);
researchCollaborationData.SaveChanges();
В следующей последовательности продемонстрированы два из четырех возможных кодовых пути. Полный обработчик события см. в методе private void buttonCreateRefPerson_Click(object sender, EventArgs e)
в полном коде обработчиков события в конце этого раздела..
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);
}
}
Использование дескрипторов ссылок для поиска ссылок
Экземпляры сущности ReferenceDescriptor являются заметками, которые используются, чтобы описывать и находить веб-ресурсы, чтобы поиск не нужно было проводить повторно или каталогизировать где-то еще. Каждый экземпляр сущности ReferenceDescriptor является одной заметкой. Веб-страницу можно описать при помощи нескольких экземпляров сущности ReferenceDescriptor, однако каждый экземпляр может быть ассоциирован только с одной страницей.
Заметки к веб-ссылкам создаются путем добавления экземпляров сущности ReferenceDescriptor, как описано в предыдущих сегментах кода. Поиск свойств Annotation и Keyword экземпляров сущности ReferenceDescriptor является средством перемещения полезных страниц сущности Reference. Когда пользователь вводит ключевые слова или поисковую фразу в текстовое поле поиска и нажимает кнопку 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());
}
}
Этот код состоит из двух базовых последовательностей: одной для создания списка строк поиска List<T>, а другой, чтобы запрашивать совпадающий текст в свойствах Keyword и Annotation экземпляров сущности ReferenceDescriptor.
Список строк поиска создается путем синтаксического анализа входного текста. Запрос является параметризированным методом ObjectQuery, используемым в цикле, в котором каждая строка поиска вставляется в запрос и сравнивается с текстом, назначенным свойствам Keyword и Annotation экземпляров сущности ReferenceDescriptor в хранилище. Экземпляры классов ObjectParameter и ObjectQuery создаются в следующем сегменте кода.
// 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);
Каждый экземпляр сущности ReferenceDescriptor, возвращаемый запросом ObjectQuery, попадает в цикл, который загружает связанный экземпляр сущности Reference при помощи предназначенных для этого свойства навигации NavigationProperty и ассоциации Association данного экземпляра. Следующий сегмент кода загружает экземпляр сущности Reference, читает ее свойство Locator и отображает URL-адрес сущности Reference в виде ссылки в итоговом текстовом поле.
refDescriptor.ReferenceReference.Load();
Reference reference = refDescriptor.Reference;
textBoxAnnotationResults.Text =
textBoxAnnotationResults.Text + "\n" +
reference.Locator + "\n";
И наконец, метод находит и отображает сведения о контактных лицах, связанных с сущностью Reference. Статический метод объекта LinkTable_ReferenceAssociation используется для обнаружения сущностей таблицы ссылок, ассоциированных с сущностью Reference. Экземпляры сущности ContactPersonReference, сущности таблицы ссылок, которые содержат сущность Reference, попадают в цикл, который загружает и отображает свойства связанной сущности ContactPerson. Свойства FirstName, LastName, Title и Email отображаются вместе с текстом ReferenceAnnotation и Locator, найденным предыдущим кодом.
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";
}
}
Поиск ссылок, ассоциированных с контактными лицами
Экземпляры сущности Reference, связанные с экземплярами сущности ContactPerson, можно находить при помощи той же сущности таблицы ссылок и ассоциаций, использованной в предыдущем сегменте кода. Пользователи этого приложения могут находить ссылки на страницы от контактных лиц, введя текст в текстовые поля LastName или Email и нажав кнопку Find Ref/Person. Будут созданы новые экземпляры ObjectParameter из текста LastName и Email. Эти параметры используются методом ObjectQuery, чтобы искать человека с совпадающей фамилией или адресом электронной почты. Метод Any объекта ObjectQuery используется для проверки наличия результатов этого запроса.
Если найден экземпляр сущности ContactPerson с совпадающей фамилией или адресом электронной почты, контактные сведения отображаются с ассоциированными документами Reference. Как и в предыдущем методе, соответствующие документы находятся при помощи сущности ContactPersonReference и ее свойств навигации.
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());
}
}
Полный код обработчика события приложения
Следующий код содержит все обработчики событий, используемые для инициализации объекта EntityConnection, а также поиска и обновления данных, которые построены по модели данных совместной работы для исследований.
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());
}
}
}
}
См. также
Основные понятия
Средство Annotation and Research Collaboration Tool (образец приложения модели EDM)
Схемы программы Annotation Research Tool (образец приложения модели EDM)