|
![]() |
#1 |
Чайный пьяница
|
Цитата:
Сообщение от CCNP|Leonid
![]() Добрый день, уже 2 день не получается.
Вот что получилось. Ткните носом в ошибки плз. X++: using System; using System.Collections.Generic; using System.Text; using Microsoft.Crm.Sdk; using Microsoft.Crm.SdkTypeProxy; using Microsoft.Crm.Sdk.Query; namespace LeadConversionPlugin { public class ContactCreationHandler : IPlugin { #region IPlugin Members public void Execute(IPluginExecutionContext context) { if (context.MessageName == MessageName.Create && context.InputParameters.Contains("Target") && context.InputParameters["Target"] is DynamicEntity) { DynamicEntity entity = (DynamicEntity)context.InputParameters["Target"]; //Проверяем является ли значение контактом if (entity.Name != EntityName.contact.ToString()) return; // Проверяем есть ли у контакта связь с интересом if (!entity.Properties.Contains("originatingleadid")) return; //Получаем Guid интереса Guid leadid = ((Lookup)entity["originatingleadid"]).Value; //получаем Guid контакта Guid contactid = (Guid)context.OutputParameters["Id"]; ICrmService crmservice = context.CreateCrmService(true); //Just build the query which will be used to retrieve //all child annotations (notes and attachements) //QueryByAttribute query = new QueryByAttribute(); //query.ColumnSet = new AllColumns(); //query.EntityName = EntityName.annotation.ToString(); //query.Attributes = new string[] { "objectid" }; //query.Values = new object[] { leadid }; QueryExpression relationshipCheckQuery = new QueryExpression(); relationshipCheckQuery.EntityName = "new_project"; relationshipCheckQuery.ColumnSet = new ColumnSet(new string[] { "new_projectid" }); // // // Code Create Moniker for first Entity: Contact Moniker Moniker1 = new Moniker(); Moniker1.Id = contactid; Moniker1.Name = EntityName.contact.ToString(); // Code Create Moniker for second Entity: New_CustomEntity Moniker Moniker2 = new Moniker(); Moniker2.Id = leadid; Moniker2.Name = EntityName.new_project.ToString(); string strManyToManyRelationshipName = "new_new_project_contactId"; RetrieveMultipleRequest request = new RetrieveMultipleRequest(); request.Query = query; request.ReturnDynamicEntities = false; RetrieveMultipleResponse response = (RetrieveMultipleResponse)crmservice.Execute(request);}} public bool AssociateManyToManyEntityRecords(Moniker Moniker1, Moniker Moniker2, string strEntityRelationshipName){ try { // Create an AssociateEntities request. AssociateEntitiesRequest request = new AssociateEntitiesRequest(); // Set the ID of Moniker1 to the ID of the lead. request.Moniker1 = Moniker1; // Set the ID of Moniker2 to the ID of the contact. request.Moniker2 = Moniker2; // Set the relationship name to associate on. request.RelationshipName = strEntityRelationshipName; // Execute the request. service.Execute(request); return true; } catch (SoapException ex) { return false; } } } #endregion IPlugin Members } Код: using System; using System.Collections.Generic; using System.Text; using Microsoft.Crm.Sdk; using Microsoft.Crm.SdkTypeProxy; using Microsoft.Crm.Sdk.Query; using System.Web.Services.Protocols; namespace LeadConversionPlugin { public class ContactCreationHandler : IPlugin { #region IPlugin Members public void Execute(IPluginExecutionContext context) { if (context.MessageName == MessageName.Create && context.InputParameters.Contains("Target") && context.InputParameters["Target"] is DynamicEntity) { DynamicEntity entity = (DynamicEntity)context.InputParameters["Target"]; //Проверяем является ли значение контактом if (entity.Name != EntityName.contact.ToString()) return; // Проверяем есть ли у контакта связь с интересом if (!entity.Properties.Contains("originatingleadid")) return; //Получаем Guid интереса Guid leadid = ((Lookup)entity["originatingleadid"]).Value; //получаем Guid контакта Guid contactid = (Guid)context.OutputParameters["Id"]; ICrmService crmservice = context.CreateCrmService(true); QueryExpression relationshipCheckQuery = new QueryExpression(); relationshipCheckQuery.EntityName = "new_project"; relationshipCheckQuery.ColumnSet = new ColumnSet(new string[] { "new_projectid" }); LinkEntity link = relationshipCheckQuery.AddLink("<название связи N:N между проектом и лидом>", "new_projectid", "new_projectid"); link.LinkCriteria.AddCondition("leadid", ConditionOperator.Equal, leadid); RetrieveMultipleRequest request = new RetrieveMultipleRequest(); request.Query = relationshipCheckQuery; request.ReturnDynamicEntities = true; List<BusinessEntity> list = ((RetrieveMultipleResponse)crmservice.Execute(request)).BusinessEntityCollection.BusinessEntities; foreach (DynamicEntity de in list) { AssociateEntitiesRequest assrequest = new AssociateEntitiesRequest(); assrequest.Moniker1 = new Moniker("contact", contactid); assrequest.Moniker2 = new Moniker("new_project", ((Key)de["new_projectid"]).Value); assrequest.RelationshipName = "<название связи N:N между проектом и контактом>"; crmservice.Execute(assrequest); } } } } #endregion IPlugin Members }
__________________
Эмо разработчик, сначала пишу код, потом плачу над его несовершенством. Подписывайтесь на мой блог, twitter и YouTube канал. Пользуйтесь моим Ultimate Workflow Toolkit |
|
![]() |
#2 |
sys*#**#**#**#**#*
|
Добрый вечер.
А на какое событие вещать плагин? |
|
![]() |
#3 |
Чайный пьяница
|
Создание контакта. Message - Create, Primary Entity - contact.
__________________
Эмо разработчик, сначала пишу код, потом плачу над его несовершенством. Подписывайтесь на мой блог, twitter и YouTube канал. Пользуйтесь моим Ultimate Workflow Toolkit |
|
![]() |
#4 |
sys*#**#**#**#**#*
|
Добрый вечер. Ускоренными темпами осваиваю шарп и начинаю кодить легкие вещи для CRM. Однако работа одного из отделов очень затруднена уже неделю. Поэтому, друзья, я продолжу Вас вырезано цензурой п.4.1 правил форума своими проблемами.
X++: using System; using System.Collections.Generic; using System.Text; using Microsoft.Crm.Sdk; using Microsoft.Crm.SdkTypeProxy; using Microsoft.Crm.Sdk.Query; using System.Web.Services.Protocols; namespace LeadConversionPlugin { public class ContactCreationHandler : IPlugin { #region IPlugin Members public void Execute(IPluginExecutionContext context) { if (context.MessageName == MessageName.Create && context.InputParameters.Contains("Target") && context.InputParameters["Target"] is DynamicEntity) { DynamicEntity entity = (DynamicEntity)context.InputParameters["Target"]; //Проверяем является ли значение контактом if (entity.Name != EntityName.contact.ToString()) return; // Проверяем есть ли у контакта связь с интересом if (!entity.Properties.Contains("originatingleadid")) return; //Получаем Guid интереса Guid leadid = ((Lookup)entity["originatingleadid"]).Value; //получаем Guid контакта Guid contactid = (Guid)context.OutputParameters["Id"]; ICrmService crmservice = context.CreateCrmService(true); //Параметры ссылки QueryExpression relationshipCheckQuery = new QueryExpression(); relationshipCheckQuery.EntityName = "new_project"; //Получаем ID проекта relationshipCheckQuery.ColumnSet = new ColumnSet(new string[] { "new_projectid" });//new_project это название поля на форме интереса, у обьекта new_project ключ new_projectid //Устанавливаем ссылку где //new_new_project_lead n:1 связи между Интересом и проектом //new_projectid название атрибута в источнике, a new_project на форме интереса. LinkEntity link = relationshipCheckQuery.AddLink("new_new_project_lead", "new_project", "new_projectid"); link.LinkCriteria.AddCondition("leadid", ConditionOperator.Equal, leadid); RetrieveMultipleRequest request = new RetrieveMultipleRequest(); request.Query = relationshipCheckQuery; request.ReturnDynamicEntities = true; List<BusinessEntity> list = ((RetrieveMultipleResponse)crmservice.Execute(request)).BusinessEntityCollection.BusinessEntities; foreach (DynamicEntity de in list) { AssociateEntitiesRequest assrequest = new AssociateEntitiesRequest(); assrequest.Moniker1 = new Moniker("contact", contactid); assrequest.Moniker2 = new Moniker("new_project", ((Key)de["new_projectid"]).Value); assrequest.RelationshipName = "new_new_project_contactBase"; crmservice.Execute(assrequest); } } } } #endregion IPlugin Members } И вдобавок Саня, бывший программист вырезано цензурой п.4.1 правил форума все что делал, сейчас никаких исходников, вообще ничего нет оказывается. ps. Если кому что по сетям помочь, сервер под тесты предоставить не вопрос - обращайтесь. Последний раз редактировалось a33ik; 22.11.2010 в 23:56. |
|
![]() |
#5 |
Чайный пьяница
|
Скриншоты регистрации плагинов приложите, пожалуйста и перепроверьте, что имя связи именно "new_new_project_contactBase" (потому что мне кажется, что это название таблицы-связки, а не связи).
__________________
Эмо разработчик, сначала пишу код, потом плачу над его несовершенством. Подписывайтесь на мой блог, twitter и YouTube канал. Пользуйтесь моим Ultimate Workflow Toolkit Последний раз редактировалось a33ik; 23.11.2010 в 02:02. |
|
![]() |
#6 |
sys*#**#**#**#**#*
|
Перепроверил, действительно это было имя таблички связи N:N в базе, исправил, однако симптомы те же. Ничего не происходит. Cкриншот PluginRegistration во вложении.
Последний раз редактировалось CCNP|Leonid; 23.11.2010 в 18:45. |
|
![]() |
#7 |
sys*#**#**#**#**#*
|
Возник такой вопрос, вот этим кодом получается мы получаем id проекта привязанного к интересу посредством запроса к базе на выборку значения поля new_project
X++: //Параметры ссылки QueryExpression relationshipCheckQuery = new QueryExpression(); relationshipCheckQuery.EntityName = "new_project"; //Получаем ID проекта relationshipCheckQuery.ColumnSet = new ColumnSet(new string[] { "new_projectid" });//new_project это название поля на форме интереса, у обьекта new_project ключ new_projectid |
|
Теги |
бизнес-партнер, интересы, контакт, связанные сущности, связь n:n, связи |
|
|