/// <summary> /// This method creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Get the current user. WhoAmIRequest userRequest = new WhoAmIRequest(); WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest); _userId = userResponse.UserId; // Create the activity party for sending and receiving the fax. ActivityParty party = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId) }; // Create the fax object. Fax fax = new Fax { Subject = "Sample Fax", From = new ActivityParty[] { party }, To = new ActivityParty[] { party } }; _faxId = _serviceProxy.Create(fax); Console.WriteLine("Created a fax: '{0}'.", fax.Subject); }
/// <summary> /// This method creates any entity records that this sample requires. /// Create a new recurring appointment. /// </summary> public void CreateRequiredRecords() { // Create a contact Contact newContact = new Contact { FirstName = "Lisa", LastName = "Andrews", EMailAddress1 = "*****@*****.**" }; _contactId = _serviceProxy.Create(newContact); Console.WriteLine("Created contact: {0}.", newContact.FirstName + " " + newContact.LastName); // Create ab activity party ActivityParty requiredAttendee = new ActivityParty { PartyId = new EntityReference(Contact.EntityLogicalName, _contactId) }; // Create an appointment Appointment newAppointment = new Appointment { Subject = "Test Appointment", Description = "Test Appointment", ScheduledStart = DateTime.Now.AddHours(1), ScheduledEnd = DateTime.Now.AddHours(2), Location = "Office", RequiredAttendees = new ActivityParty[] { requiredAttendee } }; _appointmentId = _serviceProxy.Create(newAppointment); Console.WriteLine("Created {0}.", newAppointment.Subject); }
/** * <summary> * Creates the email that is going to be sent and returns its ID. * </summary> * <param name="fromQueue">ID of the queue the email is going to be sent from</param> * <param name="toQueue">ID of the queue the email is going to be sent to</param> * <param name="subject">the subject of the email </param> * <param name="cbgApplication">Cbg application - null for SIS check and populated for police check.</param> * */ public Guid CreateEmail(Guid fromQueue, Guid toQueue, string subject, EntityReference entityRef) { //creating activity party to set To field of the email address ActivityParty to = new ActivityParty() { PartyId = new EntityReference(Queue.EntityLogicalName, toQueue), }; //creating activity party to set From field of the email address ActivityParty from = new ActivityParty() { PartyId = new EntityReference(Queue.EntityLogicalName, fromQueue), }; // create the email to attach file to and send Email _emailToUpdate = new Email() { Id = Guid.NewGuid(), From = new ActivityParty[] { from }, To = new ActivityParty[] { to }, Subject = subject, }; if (entityRef != null) { _emailToUpdate.RegardingObjectId = entityRef; } Guid emailId = ElevatedService.Create(_emailToUpdate); return(emailId); }
/// <summary> /// This method called when user clicks item in a Grid /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void lvList_ItemClick(object sender, ItemClickEventArgs e) { // Obtain clicked item var item = e.ClickedItem as ViewData; EntityMetadataEx entityMetadataEx; if (!string.IsNullOrEmpty(item.ActivityTypeName)) //Activities { entityMetadataEx = CRMHelper.EntityMetadataExCollection. Where(x => x.EntityMetadata.LogicalName == item.ActivityTypeName).FirstOrDefault(); } else { entityMetadataEx = CRMGrid.cbLookFor.SelectedItem as EntityMetadataEx; } // If this is for Party if (formFieldData.FieldMetadata.AttributeType == AttributeTypeCode.PartyList) { // Create Collection to host multiple records EntityCollection newCollection = new EntityCollection(); // Store existing ActityParties newCollection.Entities.AddRange((formFieldData.FieldData as EntityCollection).Entities); // Create new ActivityParty ActivityParty recordToAdd = new ActivityParty(); recordToAdd.PartyId = new EntityReference(); recordToAdd.PartyId.Id = item.Id; recordToAdd.PartyId.LogicalName = (CRMGrid.cbLookFor.SelectedItem as EntityMetadataEx).EntityMetadata.LogicalName; recordToAdd.PartyId.Name = item.PrimaryFieldValue; // Then add to the list. newCollection.Entities.Add(recordToAdd); // Store it to FieldData formFieldData.FieldData = newCollection; // Assign the value to temporary data CRMHelper.temporaryData = formFieldData; } // If this is normal lookup else { // Generate new EntityReference EntityReference newReference = new EntityReference(); newReference.Id = item.Id; newReference.LogicalName = entityMetadataEx.EntityMetadata.LogicalName; newReference.Name = item.PrimaryFieldValue; // Assign new value to FieldData formFieldData.FieldData = newReference; // Assign the value to temporary data CRMHelper.temporaryData = formFieldData; } // Then Go back to original page if (Frame.CanGoBack) { Frame.GoBack(); } }
public bool CreateEmailFromTemplate(IContactModel contact, Incident incident, string registrationName, Template template) { try { _log.Info($"Creating email message from template {template.Title}..."); _contactId = contact.Id ?? Guid.Empty; // Create the 'From:' activity party for the email ActivityParty fromParty = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId) }; // Create the 'To:' activity party for the email ActivityParty toParty = new ActivityParty { PartyId = new EntityReference(Contact.EntityLogicalName, _contactId), AddressUsed = contact.Email }; _log.Info("Created activity parties."); // Create an e-mail message. Email email = new Email { To = new ActivityParty[] { toParty }, From = new ActivityParty[] { fromParty }, Subject = GetDataFromXml(template.Subject, "match"), Description = GetDataFromXml(template.Body, "match"), DirectionCode = true, RegardingObjectId = new EntityReference(Contact.EntityLogicalName, _contactId) }; _log.Info("Start modifying the email description with dynamic values..."); email.Description = email.Description.Replace("#LastName#", contact.LastName); email.Description = email.Description.Replace("#caseNumber#", incident.TicketNumber); email.Description = email.Description.Replace("#RegistrationName#", registrationName); Guid emailId = _service.Create(email); if (emailId == Guid.Empty) { _log.Error("Email not sent successfully"); return(false); } _log.Info($"Created email message with id {emailId} with the following information: " + $"Template {template.Title}, Subject {email.Subject}, Description {email.Description}"); return(true); //bool emailSent = SendEmailFromTemplate(email, template.Id); } catch (Exception ex) { _log.Error($"An error occurred during creating email. Exception: {ex.Message}"); return(false); } }
public Email SendEmail(Guid fromUser) { Email email = new Email(); email.TrackingToken = string.Empty; var fromParty = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, fromUser) }; ActivityParty[] emailTo = null; ActivityParty toParty = null; var teamid = GetUsersTeam(); if (teamid == null) { throw new ArgumentNullException("teamid is null"); } var teamGuids = GetTeamMembers(teamid.Value); if (teamGuids != null && teamGuids.Count > 0) { emailTo = new ActivityParty[teamGuids.Count]; for (int i = 0; i < teamGuids.Count; i++) { Guid userGuid = teamGuids[i]; toParty = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, userGuid) }; emailTo[i] = toParty; } } if (emailTo != null) { email.To = emailTo; } email.From = new ActivityParty[] { fromParty }; Guid getTamplateEmail = GetTamplateEmail(); var emailTemplate = GetEmailTemplateDescription(getTamplateEmail, fromUser); email.Subject = GenerateTemplateTitle(emailTemplate.Item2, _orginalFlightOccurrence); email.Description = GenerateTemplateBody(emailTemplate.Item1, _orginalFlightOccurrence); // email.Attributes.Add("RegardingObjectId".ToLower(), _target.ToEntityReference()); //= new Microsoft.Xrm.Client.CrmEntityReference(_target.LogicalName, _target.Id); //_target.ToEntityReference(); email.RegardingObjectId = _target.ToEntityReference(); Guid emailid = _service.Create(email); email.ActivityId = emailid; return(email); }
private bool SendEmail(IExtendedExecutionContext context, Entity account, Incident caseRecord) { context.Trace($"Attempting to retrieve case with title Email Change Request..."); // Get a system user to send the email (From: field) _userId = context.UserId; // Create the 'From:' activity party for the email ActivityParty fromParty = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId) }; // Create the 'To:' activity party for the email ActivityParty toParty = new ActivityParty { PartyId = new EntityReference(PluginXrm.Account.EntityLogicalName, _accountId), AddressUsed = account.GetAttributeValue <string>(Email) }; context.Trace("Created To and From activity parties."); // Create an email message entity Email email = new Email { To = new ActivityParty[] { toParty }, From = new ActivityParty[] { fromParty }, Subject = "Email change request confirmation", Description = $"Hello, {account.GetAttributeValue<string>(AccountName)}.{Environment.NewLine}" + $"We received your request to change your primary email address from " + $"{caseRecord.GetAttributeValue<string>(PreviousEmail)} to " + $"{caseRecord.GetAttributeValue<string>(NewEmail)}.{Environment.NewLine}" + @"Please <a href=""https://www.uopeople.edu/"">Click Here</a> to confirm your request", DirectionCode = true, RegardingObjectId = new EntityReference(Incident.EntityLogicalName, _caseId) }; _emailId = context.OrganizationService.Create(email); context.Trace($"Created {email.Subject} email with description: {email.Description}."); SendEmailRequest sendEmailRequest = new SendEmailRequest { EmailId = _emailId, TrackingToken = string.Empty, IssueSend = true }; SendEmailResponse sendEmailResponse = (SendEmailResponse)context.OrganizationService.Execute(sendEmailRequest); return(sendEmailResponse != null); }
public bool SendEmailToRegistrationScheduledTaskOwners(string currentScheduledTaskOwner, List <IRegistrationModel> registrations, List <IIssueModel> issues) { _log.Info($"Creating email message to Scheduled task owner {currentScheduledTaskOwner}..."); // Create the 'From:' activity party for the email ActivityParty fromParty = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId) }; // Create the 'To:' activity party for the email ActivityParty toParty = new ActivityParty { AddressUsed = currentScheduledTaskOwner }; _log.Info("Created To and From activity parties."); string description = BuildDescription(registrations, issues); // Create an email message entity Email email = new Email { To = new ActivityParty[] { toParty }, From = new ActivityParty[] { fromParty }, Subject = "Registration Update Summary", Description = description, DirectionCode = true }; Guid emailId = _service.Create(email); if (emailId == Guid.Empty) { _log.Error("Email not sent successfully"); return(false); } _log.Info($"Created email message with id {emailId} with the following information: " + $"Subject {email.Subject}, Description {email.Description}"); SendEmailRequest sendEmailRequest = new SendEmailRequest { EmailId = emailId, TrackingToken = string.Empty, IssueSend = true }; SendEmailResponse sendEmailResponse = (SendEmailResponse)_service.Execute(sendEmailRequest); return(sendEmailResponse != null); }
public void When_executing_a_linq_query_with_equals_between_2_activityparties_result_is_returned() { var fakedContext = new XrmFakedContext(); fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); var contactId = Guid.NewGuid(); var activityId = Guid.NewGuid(); var partyRecord = new ActivityParty() { Id = Guid.NewGuid(), ActivityId = new EntityReference(Email.EntityLogicalName, activityId), PartyId = new EntityReference(Contact.EntityLogicalName, contactId) }; fakedContext.Initialize(new List <Entity>() { new Email() { Id = activityId, ActivityId = activityId, Subject = "Test email" }, new ActivityPointer() { Id = Guid.NewGuid(), ActivityId = activityId }, partyRecord, new ActivityPointer() { Id = Guid.NewGuid() }, //To test also nulls new ActivityParty() { Id = Guid.NewGuid() } //To test also nulls }); var service = fakedContext.GetFakedOrganizationService(); using (XrmServiceContext ctx = new XrmServiceContext(service)) { var activities = (from pointer in ctx.CreateQuery <Email>() join party in ctx.CreateQuery <ActivityParty>() on pointer.ActivityId.Value equals party.ActivityId.Id // from party in ctx.CreateQuery<ActivityParty>() //on pointer.ActivityId.Value equals party.ActivityId.Id where party.PartyId.Id == contactId select pointer).ToList(); Assert.True(activities.Count == 1); } }
public void Execute(IServiceProvider serviceProvider) { //get user(CreatedBy), account, phone, creation date(CreatedOn) //Extract the tracing service for use in debugging sandboxed plug-ins. ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); // Obtain the execution context from the service provider. IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); if (context.PostEntityImages.Contains("Image") && context.PostEntityImages["Image"] is Entity) { Entity entity = ((Entity)context.PostEntityImages["Image"]).ToEntity <Account>(); Account postAccount = (Account)entity; //create phone call activity try { PhoneCall call = new PhoneCall(); call.Subject = "Call after creation an account"; call.ScheduledStart = DateTime.Now.AddDays(1); call.ScheduledEnd = DateTime.Now.AddDays(1); if (!string.IsNullOrEmpty(call.PhoneNumber)) { call.PhoneNumber = postAccount.Telephone1.ToString(); } ActivityParty from = new ActivityParty(); from.PartyId = new EntityReference("systemuser", context.UserId); ActivityParty to = new ActivityParty(); to.PartyId = new EntityReference("account", postAccount.Id); call.To = new ActivityParty[] { to }; call.From = new ActivityParty[] { from }; call.RegardingObjectId = new EntityReference("account", postAccount.Id); // Obtain the organization service reference. tracingService.Trace("Creating phone call activity."); service.Create(call); } catch (Exception ex) { throw new InvalidPluginExecutionException($"Plugin error: {ex.Message}"); } } }
private static void SetActivityParty(Entity entity, string fieldName, ActivityParty party) { var partyList = entity.GetAttributeValue <EntityCollection>(fieldName); if (partyList == null) { partyList = new EntityCollection(); entity[fieldName] = partyList; } else { partyList.Entities.Clear(); } partyList.Entities.Add(party); }
public void SendEmail(CodeActivityContext context, Dictionary <Guid, string> pmDetails, IWorkflowContext wfContext, IOrganizationService _service) { //From: From User //To: List of PM ActivityParty fromParty = new ActivityParty() { PartyId = new EntityReference("systemuser", FromUser.Get(context).Id) }; ActivityParty toParty = new ActivityParty() { PartyId = new EntityReference(ToUser.Get(context).LogicalName, ToUser.Get(context).Id) }; List <ActivityParty> ccActivityPartyList = new List <ActivityParty>(); foreach (var item in pmDetails) { ActivityParty ccParty = new ActivityParty { PartyId = new EntityReference(ToUser.Get(context).LogicalName, item.Key) }; ccActivityPartyList.Add(ccParty); } Email email = new Email { To = new ActivityParty[] { toParty }, From = new ActivityParty[] { fromParty }, Subject = Subject.Get(context), Description = "Dear User <br /> The timeframe to complete project task has elapsed.", DirectionCode = true, Cc = ccActivityPartyList, RegardingObjectId = new EntityReference("msdyn_project", wfContext.PrimaryEntityId), }; Guid _emailId = _service.Create(email); SendEmailRequest sendEmailreq = new SendEmailRequest { EmailId = _emailId, TrackingToken = "", IssueSend = true }; SendEmailResponse sendEmailresp = (SendEmailResponse)_service.Execute(sendEmailreq); }
private bool SendEmail(IExtendedExecutionContext context, Entity account, Incident latestCase) { // Get a system user to send the email (From: field) _userId = context.UserId; // Create the 'From:' activity party for the email ActivityParty fromParty = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId) }; // Create the 'To:' activity party for the email ActivityParty toParty = new ActivityParty { PartyId = new EntityReference(PluginXrm.Account.EntityLogicalName, _accountId), AddressUsed = account.GetAttributeValue <string>(Email) }; context.Trace("Created To and From activity parties."); // Create an email message entity Email email = new Email { To = new ActivityParty[] { toParty }, From = new ActivityParty[] { fromParty }, Subject = "Email successfully changed", Description = $"Hello, {account.GetAttributeValue<string>(AccountName)}.{Environment.NewLine}" + $"We are writing you to inform you that your primary email was successfully changed " + $"to {account.GetAttributeValue<string>(Email)}.{Environment.NewLine}" + $"Thank you for using our services!", DirectionCode = true, RegardingObjectId = new EntityReference(Incident.EntityLogicalName, latestCase.Id) }; _emailId = context.OrganizationService.Create(email); context.Trace($"Created {email.Subject} email with description: {email.Description}."); SendEmailRequest sendEmailRequest = new SendEmailRequest { EmailId = _emailId, TrackingToken = string.Empty, IssueSend = true }; SendEmailResponse sendEmailResponse = (SendEmailResponse)context.OrganizationService.Execute(sendEmailRequest); return(sendEmailResponse != null); }
/// <summary> /// This called when ActivityParty (which may have more than 1 item in a field) is touched. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void ActivityParty_Tapped(object sender, TappedRoutedEventArgs e) { // Cast item to ActivityParty ActivityParty ap = (e.OriginalSource as TextBlock).DataContext as ActivityParty; // Find EntityMetadata (usually its SystemUser) EntityMetadataEx entityMetadataEx = CRMHelper.EntityMetadataExCollection.Where(x => x.EntityMetadata.LogicalName == ap.PartyId.LogicalName).FirstOrDefault(); if (entityMetadataEx == null) { return; } // Pass data by using TemporaryData CRMHelper.temporaryData = new object[] { ap.PartyId.Id, entityMetadataEx }; Frame.Navigate(typeof(RecordDetailPage)); }
/// <summary> /// This method creates any entity records that this sample requires. /// </summary> public static void CreateRequiredRecords(CrmServiceClient service) { // Create a contact to send an email to (To: field) var emailContact = new Contact { FirstName = "Nancy", LastName = "Anderson", EMailAddress1 = "*****@*****.**" }; contactId = service.Create(emailContact); Console.WriteLine("Created a contact: {0}.", emailContact.FirstName + " " + emailContact.LastName); // Get a system user to send the email (From: field) var systemUserRequest = new WhoAmIRequest(); var systemUserResponse = (WhoAmIResponse)service.Execute(systemUserRequest); userId = systemUserResponse.UserId; // Create the 'From:' activity party for the email var fromParty = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, userId) }; // Create the 'To:' activity party for the email var toParty = new ActivityParty { PartyId = new EntityReference(Contact.EntityLogicalName, contactId) }; Console.WriteLine("Created activity parties."); // Create an e-mail message. var email = new Email { To = new ActivityParty[] { toParty }, From = new ActivityParty[] { fromParty }, Subject = "SDK Sample e-mail", Description = "SDK Sample for SendEmail Message.", DirectionCode = true }; emailId = service.Create(email); Console.WriteLine("Create {0}.", email.Subject); }
public static JObject ActivityPartyToJObject(ActivityParty activityParty, WebApiMetadata webApiMetadata) { var jObject = new JObject(); jObject["participationtypemask"] = (int)activityParty.ParticipationTypeMask; if (activityParty.TargetEntity != null) { jObject[$"partyid_{activityParty.TargetEntity.LogicalName}@odata.bind"] = EntityReferenceTostring(activityParty.TargetEntity, webApiMetadata); } foreach (KeyValuePair <string, object> attribute in activityParty.Attributes) { jObject.Add(attribute.Key, JValue.FromObject(attribute.Value)); } return(jObject); }
public Email SendEmail(Guid fromUser) { Email email = new Email(); email.TrackingToken = string.Empty; var fromParty = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, fromUser) }; ActivityParty[] emailTo = null; ActivityParty toParty = null; var teamid = GetUsersTeam(); if (teamid == null) throw new ArgumentNullException("teamid is null"); var teamGuids = GetTeamMembers(teamid.Value); if (teamGuids != null && teamGuids.Count > 0) { emailTo = new ActivityParty[teamGuids.Count]; for (int i = 0; i < teamGuids.Count; i++) { Guid userGuid = teamGuids[i]; toParty = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, userGuid) }; emailTo[i] = toParty; } } if (emailTo != null) email.To = emailTo; email.From = new ActivityParty[] { fromParty }; Guid getTamplateEmail = GetTamplateEmail(); var emailTemplate = GetEmailTemplateDescription(getTamplateEmail, fromUser); email.Subject = GenerateTemplateTitle(emailTemplate.Item2, _orginalFlightOccurrence); email.Description = GenerateTemplateBody(emailTemplate.Item1, _orginalFlightOccurrence); // email.Attributes.Add("RegardingObjectId".ToLower(), _target.ToEntityReference()); //= new Microsoft.Xrm.Client.CrmEntityReference(_target.LogicalName, _target.Id); //_target.ToEntityReference(); email.RegardingObjectId = _target.ToEntityReference(); Guid emailid = _service.Create(email); email.ActivityId = emailid; return email; }
public void Should_Not_Fail_On_Retrieving_Entity_With_Entity_Collection_Attributes() { var ctx = new XrmFakedContext(); var service = ctx.GetFakedOrganizationService(); var party = new ActivityParty { PartyId = new EntityReference("systemuser", Guid.NewGuid()) }; var email = new Email { Id = Guid.NewGuid(), To = new[] { party } }; service.Create(email); Assert.DoesNotThrow(() => service.Retrieve(email.LogicalName, email.Id, new ColumnSet(true))); }
private string CreateEmail(List <Entity> usersTo, Guid userFromId, Entity contact) { ActivityParty fromParty = new ActivityParty { PartyId = new EntityReference("systemuser", userFromId) }; List <ActivityParty> toParty = new List <ActivityParty>(); foreach (var user in usersTo) { toParty.Add(new ActivityParty { PartyId = new EntityReference(user.LogicalName, user.Id) }); } Email email = new Email { To = toParty, From = new ActivityParty[] { fromParty }, Description = string.Format("Contact Full Name: {0} \n Contact link: {1}", contact.GetAttributeValue <string>("fullname"), crmUrl + "/main.aspx?etn=contact&pagetype=entityrecord&id=%7B" + contact.Id.ToString().Replace("{", string.Empty).Replace("}", string.Empty) + "%7D"), DirectionCode = true, }; var emailId = _service.Create(email); CoppyContactAttachmentsToEmail(contact.Id, emailId); SendEmailRequest sendEmailreq = new SendEmailRequest { EmailId = emailId, TrackingToken = "", IssueSend = true }; SendEmailResponse sendEmailresp = (SendEmailResponse)_service.Execute(sendEmailreq); return(sendEmailresp.Subject); }
protected override void Execute(CodeActivityContext context) { //throw new NotImplementedException(); ITracingService tracingService = context.GetExtension <ITracingService>(); IWorkflowContext workflowContext = context.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = context.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId); CrmServiceContext xrm = new CrmServiceContext(service); try { ActivityParty from = new ActivityParty(); from.PartyId = new EntityReference("systemuser", workflowContext.UserId); //SystemUser to = xrm.SystemUserSet.Where(p => p.Id == UserInput.Get(context).Id).FirstOrDefault(); ActivityParty to = new ActivityParty(); to.PartyId = new EntityReference("systemuser", UserInput.Get(context).Id); Email email = new Email { From = new ActivityParty[] { from }, To = new ActivityParty[] { to }, Subject = "Test Workflow", Description = TextInput.Get(context), DirectionCode = true, ScheduledEnd = DateTime.Now.AddDays(1) }; Guid emailId = service.Create(email); SendEmailRequest sendEmail = new SendEmailRequest(); sendEmail.EmailId = emailId; sendEmail.TrackingToken = string.Empty; sendEmail.IssueSend = true; service.Execute(sendEmail); IsSuccess.Set(context, true); } catch (Exception ex) { //throw new InvalidPluginExecutionException($"An error occured in worlflow: {ex.Message}"); IsSuccess.Set(context, false); } }
private async System.Threading.Tasks.Task create_email_atvity() { Email email = new Email(); email.ToRecipients = "*****@*****.**"; //email.To= //email.From= email.Subject = (string)con["name"]; email.Description = "nazi nigger created this task"; emailid_ = (Guid)service.Create(email); ActivityParty activityparty = new ActivityParty(); SystemUser systemuser = new SystemUser(); EntityReference from = new EntityReference("systemuser", context.UserId); activityparty.PartyId = from; email.From = (System.Collections.Generic.IEnumerable <crm_ddl_namespace.ActivityParty>)activityparty; emailid_ = (Guid)service.Create(email); }
/// <summary> /// Main entry point for he business logic that the plug-in is to execute. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> protected override void ExecuteCrmPlugin(LocalPluginContext localContext) { IPluginExecutionContext context = localContext.PluginExecutionContext; IOrganizationService service = localContext.OrganizationService; Entity preEntity = (Entity)context.PreEntityImages["contactPreImage"]; Contact precontact = preEntity.ToEntity <Contact>(); Entity postEntity = (Entity)context.PostEntityImages["contactPostImage"]; Contact postContact = postEntity.ToEntity <Contact>(); if (precontact.di_IntialInvesmentFinal != postContact.di_IntialInvesmentFinal || precontact.di_interest_rate != postContact.di_interest_rate || precontact.di_InvestmentPeriod != postContact.di_InvestmentPeriod) { Entity entity = GetGlobalTemplate("Changes", service); Email email = new Email(); ActivityParty activityParty = new ActivityParty(); email.LogicalName = "email"; email.Subject = GetDataFromXml("match", entity.Attributes["subject"].ToString()); email.Subject = email.Subject.ToString().Replace("[subject]", "Changes Noticed on your account"); email.Description = GetDataFromXml("match", entity.Attributes["body"].ToString()); string urlToReplace = "<html><body><table border=1>" + "<tr><th>Field</th><th>Before</th><th>After</th>" + "</tr><tr><td>Initial Investment</td><td>" + Math.Round(precontact.di_IntialInvesmentFinal.GetValueOrDefault(0), 2) + "</td><td>" + Math.Round(postContact.di_IntialInvesmentFinal.GetValueOrDefault(0), 2) + "</td></tr><tr><td>Interest Rate</td><td>" + Math.Round(precontact.di_interest_rate.GetValueOrDefault(0), 2) + "</td><td>" + Math.Round(postContact.di_interest_rate.GetValueOrDefault(0), 2) + "</td></tr><tr><td>Investment Period</td><td>" + precontact.di_InvestmentPeriod + "</td><td>" + postContact.di_InvestmentPeriod + "</td></tr>" + "</table></body></html>"; email.Description = email.Description.ToString().Replace("[fullname]", postContact.FullName); email.Description = email.Description.ToString().Replace("[table]", urlToReplace); email.From = CreateActivityPartyList(postContact.OwnerId); email.To = CreateActivityPartyList(new EntityReference(Contact.EntityLogicalName, postContact.ContactId.Value)); email.RegardingObjectId = (new EntityReference(Contact.EntityLogicalName, postContact.ContactId.Value)); Guid emailCreated = service.Create(email); SendEmailRequest req = new SendEmailRequest(); req.EmailId = emailCreated; req.TrackingToken = string.Empty; req.IssueSend = true; SendEmailResponse res = (SendEmailResponse)service.Execute(req); } }
public void LocalCrmTests_Crud_ActivityPartyAutoCreation() { var service = GetService(); var contact = new Contact(); contact.Id = service.Create(contact); var account = new Account(); account.Id = service.Create(account); var party = new ActivityParty { PartyId = account.ToEntityReference() }; var parties = new EntityCollection { EntityName = account.LogicalName }; parties.Entities.Add(party); var phoneCall = new PhoneCall { [PhoneCall.Fields.To] = parties, RegardingObjectId = contact.ToEntityReference() }; service.Create(phoneCall); var qe = QueryExpressionFactory.Create <PhoneCall>(); var apLink = qe.AddLink <ActivityParty>(PhoneCall.Fields.ActivityId); apLink.Columns.AddColumn(ActivityParty.Fields.ParticipationTypeMask); //apLink.AddLink(account.LogicalName, ActivityParty.Fields.PartyId, Account.Fields.Id); var values = service.GetEntities(qe) .Select(p => p.GetAliasedEntity <ActivityParty>().ParticipationTypeMaskEnum) .ToList(); Assert.AreEqual(1, values.Count(m => m == ActivityParty_ParticipationTypeMask.ToRecipient), "The to activity party should have been created."); Assert.AreEqual(1, values.Count(m => m == ActivityParty_ParticipationTypeMask.Regarding), "The regarding activity party should have been created."); }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// activity party records are created and associated with an activity. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete /// all created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetWorkingWithActivityParties1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy); // Retrieve the Contact records that we created previously. List<Contact> contacts = (from c in orgContext.CreateQuery<Contact>() where c.Address1_City == "Sammamish" select new Contact { ContactId = c.ContactId, FirstName = c.FirstName, LastName = c.LastName }).ToList<Contact>(); Console.Write("Contacts retrieved, "); // Create an Activity Party record for each Contact. var activityParty1 = new ActivityParty { PartyId = new EntityReference(Contact.EntityLogicalName, contacts[0].ContactId.Value), }; var activityParty2 = new ActivityParty { PartyId = new EntityReference(Contact.EntityLogicalName, contacts[1].ContactId.Value), }; var activityParty3 = new ActivityParty { PartyId = new EntityReference(Contact.EntityLogicalName, contacts[2].ContactId.Value), }; Console.Write("ActivityParty instances created, "); // Create Letter Activity and set From and To fields to the // respective Activity Party entities. var letter = new Letter { RegardingObjectId = new EntityReference(Contact.EntityLogicalName, contacts[2].ContactId.Value), Subject = "Sample Letter Activity", ScheduledEnd = DateTime.Now + TimeSpan.FromDays(5), Description = @"Greetings, Mr. Andreshak, This is a sample letter activity as part of the Microsoft Dynamics CRM SDK. Sincerely, Mary Kay Andersen cc: Denise Smith", From = new ActivityParty[] { activityParty1 }, To = new ActivityParty[] { activityParty3, activityParty2 } }; orgContext.AddObject(letter); orgContext.SaveChanges(); Console.WriteLine("and Letter Activity created."); DeleteRequiredRecords(promptforDelete); } //</snippetWorkingWithActivityParties1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
public static void sendEmailFromTemplate(IOrganizationService organizationService, Contact contact, IPluginExecutionContext pluginExecutionContext, ITracingService tracingService, Money prevInvestment, Money newInvestment, double prevInterestRate, double newInterestRate, int?prevInvestmentPeriod, int?newInvestmentPeriod) { try { Guid templateId; ActivityParty fromParty = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, pluginExecutionContext.UserId) }; // Create the 'To:' activity party for the email ActivityParty toParty = new ActivityParty { PartyId = contact.ToEntityReference() }; string clientName = ""; if (contact.abc_IndividualClientName != null) { clientName = contact.abc_IndividualClientName; } if (contact.abc_CorporateClientName != null) { clientName = contact.abc_CorporateClientName; } Email email = new Email { To = new ActivityParty[] { toParty }, From = new ActivityParty[] { fromParty }, Subject = "Investment Update Notification", Description = HtlStringBody(clientName, (decimal)prevInvestment.Value, (int)prevInvestmentPeriod, prevInterestRate, (decimal)newInvestment.Value, (int)newInvestmentPeriod, newInterestRate), DirectionCode = true, }; email.Id = organizationService.Create(email); var queryBuildInTemplates = new QueryExpression { EntityName = Template.EntityLogicalName, ColumnSet = new ColumnSet(Template.Fields.TemplateId, Template.Fields.TemplateTypeCode), Criteria = new FilterExpression() }; queryBuildInTemplates.Criteria.AddCondition(Template.Fields.TemplateTypeCode, ConditionOperator.Equal, Contact.EntityLogicalName); EntityCollection templateEntityCollection = organizationService.RetrieveMultiple(queryBuildInTemplates); for (int i = 0; i < templateEntityCollection.TotalRecordCount; i++) { if (templateEntityCollection.Entities[1].Attributes[Template.Fields.Title].ToString().Trim() == "notificationemailtemplate") { templateId = (Guid)templateEntityCollection.Entities[0].Attributes[Template.Fields.TemplateId]; var emailUsingTemplateReq = new SendEmailFromTemplateRequest { Target = email, TemplateId = templateId, RegardingId = (Guid)contact.Id, RegardingType = Contact.EntityLogicalName }; //var emailUsingTemplateResp = (SendEmailFromTemplateResponse)organizationService.Execute(emailUsingTemplateReq); // email.Id = emailUsingTemplateResp.Id; if (!email.Id.Equals(Guid.Empty)) { } } else { throw new ArgumentException("Standard Email Templates are missing"); } } } catch (Exception) { throw; } }
/// <summary> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Book an appointment. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetBookAppointment1> // Get the current user information WhoAmIRequest userRequest = new WhoAmIRequest(); WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest); // Create the ActivityParty instance. ActivityParty party = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, userResponse.UserId) }; // Create the appointment instance. Appointment appointment = new Appointment { Subject = "Test Appointment", Description = "Test Appointment created using the BookRequest Message.", ScheduledStart = DateTime.Now.AddHours(1), ScheduledEnd = DateTime.Now.AddHours(2), Location = "Office", RequiredAttendees = new ActivityParty[] { party }, Organizer = new ActivityParty[] { party } }; // Use the Book request message. BookRequest book = new BookRequest { Target = appointment }; BookResponse booked = (BookResponse)_serviceProxy.Execute(book); _appointmentId = booked.ValidationResult.ActivityId; // Verify that the appointment has been scheduled. if (_appointmentId != Guid.Empty) { Console.WriteLine("Succesfully booked {0}.", appointment.Subject) ; } //</snippetBookAppointment1> DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region Create or Retrieve the necessary system users // Retrieve the ldapPath String ldapPath = String.Empty; // Retrieve the sales team - 1 sales manager and 2 sales representatives. _salesManagerId = SystemUserProvider.RetrieveSalesManager(_serviceProxy, ref ldapPath); _salesRepresentativeIds = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath); #endregion #region Create PhoneCall record and supporting account Account account = new Account { Name = "Margie's Travel", Address1_PostalCode = "99999" }; _accountId = (_serviceProxy.Create(account)); account.Id = _accountId; // Create Guids for PhoneCalls _phoneCallId = Guid.NewGuid(); _phoneCall2Id = Guid.NewGuid(); // Create ActivityPartys for the phone calls' "From" field. ActivityParty activityParty = new ActivityParty() { PartyId = account.ToEntityReference(), ActivityId = new EntityReference { Id = _phoneCallId, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9), }; ActivityParty activityPartyClosed = new ActivityParty() { PartyId = account.ToEntityReference(), ActivityId = new EntityReference { Id = _phoneCall2Id, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9) }; // Create an open phone call. PhoneCall phoneCall = new PhoneCall() { Id = _phoneCallId, Subject = "Sample Phone Call", DirectionCode = false, To = new ActivityParty[] { activityParty }, OwnerId = new EntityReference("systemuser", _salesRepresentativeIds[0]), ActualEnd = DateTime.Now }; _serviceProxy.Create(phoneCall); // Close the first phone call. SetStateRequest closePhoneCall = new SetStateRequest() { EntityMoniker = phoneCall.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(4) }; _serviceProxy.Execute(closePhoneCall); // Create a second phone call. phoneCall = new PhoneCall() { Id = _phoneCall2Id, Subject = "Sample Phone Call 2", DirectionCode = true, To = new ActivityParty[] { activityParty }, OwnerId = new EntityReference("systemuser", _salesRepresentativeIds[1]), ActualEnd = DateTime.Now }; _serviceProxy.Create(phoneCall); // Close the second phone call. closePhoneCall = new SetStateRequest() { EntityMoniker = phoneCall.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(4) }; _serviceProxy.Execute(closePhoneCall); #endregion }
[STAThread] // Added to support UX static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { #region Sample Code #region Set up SetUpSample(service); #endregion Set up #region Demonstrate // Get the current user information var userRequest = new WhoAmIRequest(); var userResponse = (WhoAmIResponse)service.Execute(userRequest); // Create the ActivityParty instance. var party = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, userResponse.UserId) }; // Create the appointment instance. var appointment = new Appointment { Subject = "Test Appointment", Description = "Test Appointment created using the BookRequest Message.", ScheduledStart = DateTime.Now.AddHours(1), ScheduledEnd = DateTime.Now.AddHours(2), Location = "Office", RequiredAttendees = new ActivityParty[] { party }, Organizer = new ActivityParty[] { party } }; // Use the Book request message. var book = new BookRequest { Target = appointment }; var booked = (BookResponse)service.Execute(book); _appointmentId = booked.ValidationResult.ActivityId; // Verify that the appointment has been scheduled. if (_appointmentId != Guid.Empty) { Console.WriteLine("Succesfully booked {0}.", appointment.Subject); } #region Clean up CleanUpSample(service); #endregion Clean up } #endregion Demonstrate #endregion Sample Code else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
private void SendEmail(List <ProxyToSendEmail> listInvoice, IOrganizationService service, byte whatDay) { var Agreements = getAgreements(); foreach (var item in Agreements) { Email mail = new Email(); mail.Subject = "Просьба согласовать КИЗ"; string link = string.Empty; var current = from p in listInvoice where Equals(p.agreementLaw, item) || Equals(p.agreementLog, item) || Equals(p.agreementFin, item) select p; if (current.Count() == 0) { continue; } foreach (var colection in current) { link += string.Format("<p class='MsoNormal'><i><u><span lang='RU' style='color:rgb(0,112,192)'>" + /*"<a href=https://ukraine.crm.softlinegroup.com/main.aspx?etc=invoice&extraqs=%3f_gridType%3d4212%26etc%3d4212%26id%3d%257b{0}" + * "%257d%26preloadcache%3d1406639059288%26rskey%3d307497509&histKey=417657088&newWindow=true&pagetype=entityrecord>{1}</a></span></u></i></p>",*/ "<a href=https://ukraine.crm.softlinegroup.com/main.aspx?etn=invoice&pagetype=entityrecord&id=%7b{0}%7d>{1}</a></span></u></i></p>", colection.recordId.ToString(), colection.Name.ToString()); } switch (whatDay) { case 0: mail.Description = string.Format(@"<div id=':3ua' class='Am Al editable LW-avf' hidefocus='true' aria-label='Текст' g_editable='true' role='textbox' contenteditable='true' tabindex='1' itacorner='6,7:1,1,0,0' style='direction: ltr; min-height: 236px;'> <p class='MsoNormal'><span lang='RU'>Уважаемый коллега, срок согласования КИЗ по счету(ам) истекает завтра. Просьба согласовать КИЗ.</span><o:p></o:p></p> <p class='MsoNormal'><i><u><span lang='RU' style='color: rgb(0, 112, 192);'>{0}</span></u></i></p> <br></div>", link.ToString()); break; case 1: mail.Description = string.Format(@"<div id=':3ua' class='Am Al editable LW-avf' hidefocus='true' aria-label='Текст' g_editable='true' role='textbox' contenteditable='true' tabindex='1' itacorner='6,7:1,1,0,0' style='direction: ltr; min-height: 236px;'> <p class='MsoNormal'><span lang='RU'>Уважаемый коллега, срок согласования КИЗ по счету(ам) истек. Просьба согласовать КИЗ.</span><o:p></o:p></p> <p class='MsoNormal'><i><u><span lang='RU' style='color: rgb(0, 112, 192);'>{0}</span></u></i></p> <br></div>", link.ToString()); break; } mail.DirectionCode = true; SystemUser user = (SystemUser)service.Retrieve(SystemUser.EntityLogicalName, item.Id, new ColumnSet("fullname", "internalemailaddress")); if (user.InternalEMailAddress == null) { continue; } var activityParty2 = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, new Guid("C49FE2C3-FB35-E511-80D7-005056820ECA")), }; mail.From = new[] { activityParty2 }; var activityParty1 = new ActivityParty { AddressUsed = user.InternalEMailAddress }; mail.To = new[] { activityParty1 }; Guid createdEmailId = service.Create(mail); var sendEmailreq = new SendEmailRequest { EmailId = createdEmailId, TrackingToken = "", IssueSend = true }; try { service.Execute(sendEmailreq); } catch (Exception) { } } }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// a phone call is created to a contact regarding a lead. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetWorkingWithRelatedAttributesforNto1Relationships1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); _service = (IOrganizationService)_serviceProxy; // Create a lead. Lead lead = new Lead() { CompanyName = "Litware, Inc." }; _leadId = _service.Create(lead); Console.Write("Lead created, "); // Create a contact. Contact contact = new Contact() { FirstName = "Dan", LastName = "Park", Address1_Line1 = "23 Market St.", Address1_City = "Sammamish", Address1_StateOrProvince = "MT", Address1_PostalCode = "99999", Telephone1 = "12345678", EMailAddress1 = "*****@*****.**" }; _contactId = _service.Create(contact); contact.ContactId = _contactId; Console.Write("contact created, "); // Create a blank phone call. PhoneCall phoneCall = new PhoneCall(); _phoneCallId = _service.Create(phoneCall); Console.Write("phone call created, "); // Create an ActivityParty for the phone call's "to" field. ActivityParty activityParty = new ActivityParty() { PartyId = new EntityReference { Id = _contactId, LogicalName = Contact.EntityLogicalName, }, ActivityId = new EntityReference { Id = _phoneCallId, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9) }; // Create a phone call and add the properties we are updating. PhoneCall updatePhoneCall = new PhoneCall() { Id = _phoneCallId, Subject = "Test Phone Call", RegardingObjectId = new EntityReference { Id = _leadId, LogicalName = Lead.EntityLogicalName }, To = new ActivityParty[] { activityParty } }; // Update the phone call. UpdateRequest updateRequest = new UpdateRequest() { Target = updatePhoneCall }; _service.Execute(updateRequest); Console.Write("phone call updated.\n"); DeleteRequiredRecords(promptforDelete); } //</snippetWorkingWithRelatedAttributesforNto1Relationships1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecutePostPostedFormUpdate(LocalPluginContext localContext) { if (localContext == null) { throw new ArgumentNullException("localContext"); } // TODO: Implement your custom Plug-in business logic. IPluginExecutionContext context = localContext.PluginExecutionContext; IOrganizationService service = localContext.OrganizationService; if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { if (context.PostEntityImages.Contains("PF2") && context.PostEntityImages["PF2"] is Entity) { Entity entityImage = (Entity)context.PostEntityImages["PF2"]; Entity entityTarget = (Entity)context.InputParameters["Target"]; //Entity entity2 = service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet(true)); if (entityImage.LogicalName == "cdi_postedform") { try { if (entityImage.Attributes.Contains("cdi_campaignid") && entityImage.Attributes.Contains("cdi_leadid") && entityImage.Attributes.Contains("cdi_formcaptureid")) { EntityReference entityCampaign = (EntityReference)entityImage.Attributes["cdi_campaignid"]; EntityReference entityLead = (EntityReference)entityImage.Attributes["cdi_leadid"]; EntityReference entityFormCapture = (EntityReference)entityImage.Attributes["cdi_formcaptureid"]; var campaignName = entityCampaign.Name; QueryExpression queryPostedField = new QueryExpression { EntityName = "cdi_postedfield" }; queryPostedField.Criteria.AddCondition("cdi_postedformid", ConditionOperator.Equal, entityImage.Id); queryPostedField.ColumnSet = new ColumnSet("cdi_value", "cdi_fieldid", "cdi_label"); EntityCollection returnPostedField = service.RetrieveMultiple(queryPostedField); if (entityCampaign.Name == "ITSD FC Inquiry" || entityCampaign.Name == "New Quest Website Inquiry") { var Link = String.Format("{0}/{1}/userdefined/edit.aspx?etc=4&id={2}", "https://qcrm.questinc.com:443", "", entityLead.Id); string firstName = " "; string lastName = " "; string emailAddress = " "; string country = " "; string company = " "; string model = " "; string type = " "; string phone = " "; string pageTitle = " "; string formUrl = " "; System.DateTime dateTime = new DateTime(); foreach (var element in returnPostedField.Entities) { switch (element.Attributes["cdi_fieldid"].ToString()) { case "first_name": firstName = (string)element.Attributes["cdi_value"]; break; case "last_name": lastName = (string)element.Attributes["cdi_value"]; break; case "email_address": emailAddress = (string)element.Attributes["cdi_value"]; break; case "country": country = (string)element.Attributes["cdi_value"]; break; case "company": company = (string)element.Attributes["cdi_value"]; break; case "specifics": model = (string)element.Attributes["cdi_value"]; break; case "hardware": type = (string)element.Attributes["cdi_value"]; break; case "phone": phone = (string)element.Attributes["cdi_value"]; break; case "new_pagetitle": pageTitle = (string)element.Attributes["cdi_value"]; break; case "new_formurl": formUrl = (string)element.Attributes["cdi_value"]; break; } } // DateTime dateTime = (entityImage.Attributes.Contains("createdon")) ? (DateTime)entityImage.Attributes["createdon"] : new System.DateTime(); //string url = (string)entityImage.Attributes["new_formurl"]; EntityCollection returnToUser = new EntityCollection(); Guid FromUserId; QueryExpression queryFromUser = new QueryExpression { EntityName = "systemuser" }; queryFromUser.Criteria.AddCondition("internalemailaddress", ConditionOperator.Equal, "*****@*****.**"); queryFromUser.ColumnSet = new ColumnSet("systemuserid"); EntityCollection returnFromUser = service.RetrieveMultiple(queryFromUser); if (entityCampaign.Name == "ITSD FC Inquiry") { QueryExpression queryToUser = new QueryExpression { EntityName = "systemuser" }; queryToUser.Criteria = new FilterExpression(); FilterExpression childFilter = queryToUser.Criteria.AddFilter(LogicalOperator.Or); //childFilter.AddCondition("internalemailaddress", ConditionOperator.Equal, "*****@*****.**"); //childFilter.AddCondition("internalemailaddress", ConditionOperator.Equal, "*****@*****.**"); childFilter.AddCondition("internalemailaddress", ConditionOperator.Equal, "*****@*****.**"); //childFilter.AddCondition("internalemailaddress", ConditionOperator.Equal, "*****@*****.**"); //childFilter.AddCondition("internalemailaddress", ConditionOperator.Equal, "*****@*****.**"); queryToUser.ColumnSet.AddColumn("systemuserid"); returnToUser = service.RetrieveMultiple(queryToUser); #region change campain adwords if (formUrl.Contains("AdWords")) { var Start = formUrl.IndexOf("AdWords", 0) + "AdWords".Length; var strSource = formUrl.Substring(Start, formUrl.Length - Start); QueryExpression queryCampaign = new QueryExpression { EntityName = "campaign" }; queryCampaign.Criteria.AddCondition("codename", ConditionOperator.Equal, strSource); queryCampaign.ColumnSet = new ColumnSet("codename", "campaignid", "name"); EntityCollection returnCampaign = service.RetrieveMultiple(queryCampaign); Guid key = (Guid)returnCampaign.Entities[0].Attributes["campaignid"]; campaignName = (string)returnCampaign.Entities[0].Attributes["name"]; entityTarget.Attributes["cdi_campaignid"] = new EntityReference("campaign", key); // service.Update(entityTarget); QueryExpression queryLead = new QueryExpression { EntityName = "lead" }; queryLead.Criteria.AddCondition("leadid", ConditionOperator.Equal, entityLead.Id); queryLead.ColumnSet = new ColumnSet("createdon", "subject"); EntityCollection returnLead = service.RetrieveMultiple(queryLead); dateTime = (DateTime)returnLead.Entities[0].Attributes["createdon"]; returnLead.Entities[0].Attributes["subject"] = returnCampaign.Entities[0].Attributes["name"].ToString() + " " + model + " - " + type; // service.Update(returnLead.Entities[0]); } #endregion } if (entityCampaign.Name == "New Quest Website Inquiry") { QueryExpression queryToUser = new QueryExpression { EntityName = "systemuser" }; queryToUser.Criteria = new FilterExpression(); FilterExpression childFilter = queryToUser.Criteria.AddFilter(LogicalOperator.Or); //childFilter.AddCondition("internalemailaddress", ConditionOperator.Equal, "*****@*****.**"); //childFilter.AddCondition("internalemailaddress", ConditionOperator.Equal, "*****@*****.**"); childFilter.AddCondition("internalemailaddress", ConditionOperator.Equal, "*****@*****.**"); //childFilter.AddCondition("internalemailaddress", ConditionOperator.Equal, "*****@*****.**"); //childFilter.AddCondition("internalemailaddress", ConditionOperator.Equal, "*****@*****.**"); queryToUser.ColumnSet.AddColumn("systemuserid"); returnToUser = service.RetrieveMultiple(queryToUser); } #region send email FromUserId = (Guid)returnFromUser.Entities[0].Attributes["systemuserid"]; // Create the 'From:' activity party for the email ActivityParty fromParty = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, FromUserId) }; var ToUserId = (Guid)returnToUser.Entities[0].Attributes["systemuserid"]; // Create the 'To:' activity party for the email ActivityParty toParty = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, ToUserId) }; //var CcUserId1 = (Guid)returnToUser.Entities[1].Attributes["systemuserid"]; //// Create the 'Cc1:' activity party for the email //ActivityParty ccParty1 = new ActivityParty //{ // PartyId = new EntityReference(SystemUser.EntityLogicalName, CcUserId1) //}; //var CcUserId2 = (Guid)returnToUser.Entities[2].Attributes["systemuserid"]; //// Create the 'cc2:' activity party for the email //ActivityParty ccParty2 = new ActivityParty //{ // PartyId = new EntityReference(SystemUser.EntityLogicalName, CcUserId2) //}; //var CcUserId3 = (Guid)returnToUser.Entities[3].Attributes["systemuserid"]; //// Create the 'Cc3:' activity party for the email //ActivityParty ccParty3 = new ActivityParty //{ // PartyId = new EntityReference(SystemUser.EntityLogicalName, CcUserId3) //}; //var CcUserId4 = (Guid)returnToUser.Entities[4].Attributes["systemuserid"]; //// Create the 'Cc4:' activity party for the email //ActivityParty ccParty4 = new ActivityParty //{ // PartyId = new EntityReference(SystemUser.EntityLogicalName, CcUserId4) //}; // Create an e-mail message. Email email = new Email { From = new ActivityParty[] { fromParty }, To = new ActivityParty[] { toParty }, // Cc = new ActivityParty[] { ccParty1, ccParty2, ccParty3, ccParty4 }, Subject = "Test New Lead Alert and New Request QUEST " + company + "�- Form Campaign: " + campaignName, DirectionCode = true, Description = "Lead Hyperlink to CRM:</br> <a>" + Link + "</a> </br> </br> Form Campaign: " + campaignName + "</br> </br> Company: " + company + "</br> Lead Name: " + firstName + " " + lastName + "</br>Email: " + emailAddress + "</br>Phone: " + phone + "</br>Country: " + country + "</br></br>Quest Web Page Where Form Was Submitted: </br>" + formUrl + "</br></br>Page Title: " + pageTitle + "</br>Lead's Web Comments and Requests: </br>" + model + "</br>" + dateTime + "</br>OPTION 1 - NEW LEAD" }; Guid _emailId = service.Create(email); SendEmailRequest sendEmailreq = new SendEmailRequest(); Microsoft.Crm.Sdk.Messages.SendEmailRequest req = new Microsoft.Crm.Sdk.Messages.SendEmailRequest(); req.EmailId = _emailId; req.TrackingToken = ""; req.IssueSend = true; // Finally Send the email message. SendEmailResponse res = (SendEmailResponse)service.Execute(req); // service.Delete(Email.EntityLogicalName, _emailId); #endregion } } } catch (FaultException ex) { throw new InvalidPluginExecutionException("this is a test", ex); } } } } }
/// <summary> /// Send an e-mail using a template. /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> /// </summary> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetSendEmailUsingTemplate1> // Create the 'From:' activity party for the email ActivityParty fromParty = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId) }; // Create the 'To:' activity party for the email ActivityParty toParty = new ActivityParty { PartyId = new EntityReference(Contact.EntityLogicalName, _contactId) }; Console.WriteLine("Created activity parties."); // Create an e-mail message. Email email = new Email { To = new ActivityParty[] { toParty }, From = new ActivityParty[] { fromParty }, Subject = "SDK Sample e-mail", Description = "SDK Sample for SendEmailFromTemplate Message.", DirectionCode = true }; //Create a query expression to get one of Email Template of type "contact" QueryExpression queryBuildInTemplates = new QueryExpression{ EntityName = "template", ColumnSet = new ColumnSet("templateid", "templatetypecode"), Criteria = new FilterExpression() }; queryBuildInTemplates.Criteria.AddCondition("templatetypecode", ConditionOperator.Equal, "contact"); EntityCollection templateEntityCollection = _serviceProxy.RetrieveMultiple(queryBuildInTemplates); if (templateEntityCollection.Entities.Count > 0) { _templateId = (Guid)templateEntityCollection.Entities[0].Attributes["templateid"]; } else { throw new ArgumentException("Standard Email Templates are missing"); } // Create the request SendEmailFromTemplateRequest emailUsingTemplateReq = new SendEmailFromTemplateRequest { Target = email, // Use a built-in Email Template of type "contact". TemplateId = _templateId, // The regarding Id is required, and must be of the same type as the Email Template. RegardingId = _contactId, RegardingType = Contact.EntityLogicalName }; SendEmailFromTemplateResponse emailUsingTemplateResp = (SendEmailFromTemplateResponse)_serviceProxy.Execute(emailUsingTemplateReq); // Verify that the e-mail has been created _emailId = emailUsingTemplateResp.Id; if (!_emailId.Equals(Guid.Empty)) { Console.WriteLine("Successfully sent an e-mail message using the template."); } //</snippetSendEmailUsingTemplate1> DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
private void SendEmail(List<EmailProxy> listData) { using (var orgContext = new OrganizationServiceContext(service)) { try { foreach (var item in listData) { Email unloadEmail = new Email(); var client = (Invoice)service.Retrieve(Invoice.EntityLogicalName, item.InvoiceId, new ColumnSet("customerid")); //Тема письма: «Уведомление о неотгруженном в срок заказе. //Сущность - invoice поле new_invoice_number, Сущность - invoice поле - customerid unloadEmail.Subject = string.Format("Уведомление о неотгруженном в срок заказе. {0} , {1}", item.NumberInvoice, client.CustomerId == null ? "" : client.CustomerId.Name); //Заказы по нижеуказанным данным не поступили в ожидаемый срок. //Сущность invoicedetail, Сущность invoicedetail поле new_sopplierid, Сущность invoicedetail поле new_sopplierid_invoice_supplier //Требуемые действия Логиста: //1) связаться с поставщиком для решения вопроса с поставкой //2) предоставить ответственному менеджеру информацию о причинах задержки и обновленной дате отгрузки заказа //Требуемые действия ответственного менеджера: //1) связаться с заказчиком, извиниться и сообщить о задержке заказа предоставив информацию о новых датах отгрузки //link ----<http://crm2011:5555/SoftlineInternationalLtd/userdefined/edit.aspx?etc=1091&id=%7b{0}%7d> string link = string.Format(/*@"<p class='MsoNormal'><i><u><span lang='RU' style='color:rgb(0,112,192)'>" +*/ @"<a href=http://crm2011:5555/SoftlineInternationalLtd/userdefined/edit.aspx?etc=1091&id=%7b{0}%7d>{1}</a></span></u></i></p>", item.InvoiceDetail.Id.ToString(), item.Product); unloadEmail.Description = string.Format(@"<div id=':1df' class='Am Al editable LW-avf' hidefocus='true' aria-label='Текст повідомлення' g_editable='true' role='textbox' contenteditable='true' tabindex='1' itacorner='6,7:1,1,0,0' style='direction: ltr; min-height: 240px;'><p class='MsoNormal' style='background-image: initial; background-repeat: initial;'><b><i><span style='color: black;'>Заказы по нижеуказанным данным не поступили в ожидаемый срок.</span></i></b></p> <p class='MsoNormal' style='background-image: initial; background-repeat: initial;'><span lang='EN-US' style='color: black;'>{0}, {1}</span><span lang='EN-US' style='color: black;'>, {2}</span></p> <p class='MsoNormal' style='background-image: initial; background-repeat: initial;'><b><i><span style='color: black;'>Требуемые действия Логиста: </span></i></b></p> <p style='background-image: initial; background-repeat: initial;'><span style='color: black;'>1)</span><span style='color: rgb(40, 40, 40);'> </span><span style='color: black;'>связаться с поставщиком для решения вопроса с поставкой</span><span style='color: rgb(40, 40, 40);'></span></p> <p style='background-image: initial; background-repeat: initial;'><span style='color: black;'>2)</span><span style='color: rgb(40, 40, 40);'> </span><span style='color: black;'>предоставить ответственному менеджеру информацию о причинах задержки и обновленной дате отгрузки заказа</span></p> <p class='MsoNormal' style='background-image: initial; background-repeat: initial;'><b><i><span style='color: black;'>Требуемые действия ответственного менеджера: </span></i></b><span style='color: rgb(40, 40, 40);'></span></p> <p style='background-image: initial; background-repeat: initial;'><span style='color: black;'>1)</span><span style='color: rgb(40, 40, 40);'> </span><span style='color: black;'>связаться с заказчиком, извиниться и сообщить о задержке заказа предоставив информацию о новых датах отгрузки</span><span style='color: rgb(40, 40, 40);'></span></p><p style='background-image: initial; background-repeat: initial;'><span style='color: rgb(40, 40, 40);'>Ссылка для перехода - {3}</span><span style='color: black;'><br></span></p></div>" , item.Product, item.InvoiceAccount == null ? "" : item.InvoiceAccount.Name, item.Number, link); unloadEmail.DirectionCode = true; SystemUser user = (SystemUser)service.Retrieve(SystemUser.EntityLogicalName, item.EntityOwner.Id, new ColumnSet("internalemailaddress")); if (user.InternalEMailAddress == null) { Log.AddLog(string.Format("Адрес Електроной почты отсутствует... ({0})", item.EntityOwner.Name)); continue; } var activity1 = new ActivityParty { AddressUsed = user.InternalEMailAddress }; var activity2 = new ActivityParty { AddressUsed = @"*****@*****.**" }; unloadEmail.To = new[] { activity1 }; unloadEmail.Cc = new[] { activity2 }; Guid createdEmailId = service.Create(unloadEmail); service.Update(new InvoiceDetail { Id = item.InvoiceDetail.Id, new_shipping = true }); var sendEmailreq = new SendEmailRequest { EmailId = createdEmailId, TrackingToken = "", IssueSend = true }; try { service.Execute(sendEmailreq); } catch (Exception ex) { Log.AddLog(ex.Message); } } } catch (Exception ex) { Log.AddLog(ex.Message); } } }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region Create or Retrieve the necessary system users // Retrieve a sales manager. _salesManagerId = SystemUserProvider.RetrieveMarketingManager(_serviceProxy); #endregion #region Create PhoneCall record and supporting account Account newAccount = new Account { Name = "Margie's Travel", Address1_PostalCode = "99999" }; _accountId = (_serviceProxy.Create(newAccount)); newAccount.Id = _accountId; // Create Guids for PhoneCalls _phoneCallId = Guid.NewGuid(); _phoneCall2Id = Guid.NewGuid(); // Create ActivityPartys for the phone calls' "From" field. ActivityParty activityParty = new ActivityParty() { PartyId = newAccount.ToEntityReference(), ActivityId = new EntityReference { Id = _phoneCallId, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9) }; ActivityParty activityPartyClosed = new ActivityParty() { PartyId = newAccount.ToEntityReference(), ActivityId = new EntityReference { Id = _phoneCall2Id, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9) }; // Create an open phone call. PhoneCall phoneCall = new PhoneCall() { Id = _phoneCallId, Subject = "Sample Phone Call", DirectionCode = false, To = new ActivityParty[] { activityParty } }; _serviceProxy.Create(phoneCall); // Create a second phone call to close phoneCall = new PhoneCall() { Id = _phoneCall2Id, Subject = "Sample Phone Call 2", DirectionCode = false, To = new ActivityParty[] { activityParty }, ActualEnd = DateTime.Now }; _serviceProxy.Create(phoneCall); // Close the second phone call. SetStateRequest closePhoneCall = new SetStateRequest() { EntityMoniker = phoneCall.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(4) }; _serviceProxy.Execute(closePhoneCall); #endregion }
private void SendEmail(List<ProxyToSendEmailExtended> listSales, IOrganizationService service, byte whatDay) { var Agreements = getAgreements(); foreach (var item in Agreements) { Email mail = new Email(); mail.Subject = "Просьба согласовать Договор либо внести комментарии"; string link = string.Empty; var current = from p in listSales where Equals(p.agreementLaw, item) || Equals(p.agreementLog, item) || Equals(p.agreementFin, item) || Equals(p.agreementAc, item) || Equals(p.agreementSd, item) select p; if (current.Count() == 0) continue; foreach (var colection in current) { link += string.Format("<p class='MsoNormal'><i><u><span lang='RU' style='color:rgb(0,112,192)'>" + /*"<a href=https://ukraine.crm.softlinegroup.com/main.aspx?etc=SalesOrder&extraqs=%3f_gridType%3d4212%26etc%3d4212%26id%3d%257b{0}" + "%257d%26preloadcache%3d1406639059288%26rskey%3d307497509&histKey=417657088&newWindow=true&pagetype=entityrecord>{1}</a></span></u></i></p>",*/ "<a href=https://ukraine.crm.softlinegroup.com/main.aspx?etn=SalesOrder&pagetype=entityrecord&id=%7b{0}%7d>{1}</a></span></u></i></p>", colection.recordId.ToString(), colection.Name.ToString()); } switch (whatDay) { case 0: mail.Description = string.Format(@"<div id=':3ua' class='Am Al editable LW-avf' hidefocus='true' aria-label='Текст' g_editable='true' role='textbox' contenteditable='true' tabindex='1' itacorner='6,7:1,1,0,0' style='direction: ltr; min-height: 236px;'> <p class='MsoNormal'><span lang='RU'>Уважаемый коллега, срок согласования договора(ов) истекает завтра. Просьба согласовать Договор либо внести комментарии.</span><o:p></o:p></p> <p class='MsoNormal'><i><u><span lang='RU' style='color: rgb(0, 112, 192);'>{0}</span></u></i></p> <br></div>", link.ToString()); break; case 1: mail.Description = string.Format(@"<div id=':3ua' class='Am Al editable LW-avf' hidefocus='true' aria-label='Текст' g_editable='true' role='textbox' contenteditable='true' tabindex='1' itacorner='6,7:1,1,0,0' style='direction: ltr; min-height: 236px;'> <p class='MsoNormal'><span lang='RU'>Уважаемый коллега, срок согласования договора(ов) истекает сегодня. Просьба согласовать Договор либо внести комментарии.</span><o:p></o:p></p> <p class='MsoNormal'><i><u><span lang='RU' style='color: rgb(0, 112, 192);'>{0}</span></u></i></p> <br></div>", link.ToString()); break; } mail.DirectionCode = true; SystemUser user = (SystemUser)service.Retrieve(SystemUser.EntityLogicalName, item.Id, new ColumnSet("fullname", "internalemailaddress")); if (user.InternalEMailAddress == null) continue; var activityParty1 = new ActivityParty { AddressUsed = user.InternalEMailAddress }; var activityParty2 = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, new Guid("C49FE2C3-FB35-E511-80D7-005056820ECA")), }; mail.From = new[] { activityParty2 }; mail.To = new[] { activityParty1 }; Guid createdEmailId = service.Create(mail); var sendEmailreq = new SendEmailRequest { EmailId = createdEmailId, TrackingToken = "", IssueSend = true }; try { service.Execute(sendEmailreq); } catch (Exception) { } } }
/// <summary> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Book an appointment. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); // Get the current user information WhoAmIRequest userRequest = new WhoAmIRequest(); WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest); // Create the ActivityParty instance. ActivityParty party = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, userResponse.UserId) }; // Create the appointment instance. Appointment appointment = new Appointment { Subject = "Test Appointment", Description = "Test Appointment created using the BookRequest Message.", ScheduledStart = DateTime.Now.AddHours(1), ScheduledEnd = DateTime.Now.AddHours(2), Location = "Office", RequiredAttendees = new ActivityParty[] { party }, Organizer = new ActivityParty[] { party } }; // Use the Book request message. BookRequest book = new BookRequest { Target = appointment }; BookResponse booked = (BookResponse)_serviceProxy.Execute(book); _appointmentId = booked.ValidationResult.ActivityId; // Verify that the appointment has been scheduled. if (_appointmentId != Guid.Empty) { Console.WriteLine("Succesfully booked {0}.", appointment.Subject); } DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// This method creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Create a contact to send an email to (To: field) Contact emailContact = new Contact { FirstName = "Nancy", LastName = "Anderson", EMailAddress1 = "*****@*****.**" }; _contactId = _serviceProxy.Create(emailContact); Console.WriteLine("Created a contact: {0}.", emailContact.FirstName + " " + emailContact.LastName); // Get a system user to send the email (From: field) WhoAmIRequest systemUserRequest = new WhoAmIRequest(); WhoAmIResponse systemUserResponse = (WhoAmIResponse)_serviceProxy.Execute(systemUserRequest); _userId = systemUserResponse.UserId; // Create the 'From:' activity party for the email ActivityParty fromParty = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId) }; // Create the 'To:' activity party for the email ActivityParty toParty = new ActivityParty { PartyId = new EntityReference(Contact.EntityLogicalName, _contactId) }; Console.WriteLine("Created activity parties."); // Create an e-mail message. Email email = new Email { To = new ActivityParty[] { toParty }, From = new ActivityParty[] { fromParty }, Subject = "SDK Sample e-mail", Description = "SDK Sample for SendEmail Message.", DirectionCode = true }; _emailId = _serviceProxy.Create(email); Console.WriteLine("Create {0}.", email.Subject); }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// a phone call is created to a contact regarding a lead. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetWorkingWithRelatedAttributesforNto1Relationships1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); _service = (IOrganizationService)_serviceProxy; // Create a lead. Lead lead = new Lead() { CompanyName = "Litware, Inc." }; _leadId = _service.Create(lead); Console.Write("Lead created, "); // Create a contact. Contact contact = new Contact() { FirstName = "Dan", LastName = "Park", Address1_Line1 = "23 Market St.", Address1_City = "Sammamish", Address1_StateOrProvince = "MT", Address1_PostalCode = "99999", Telephone1 = "12345678", EMailAddress1 = "*****@*****.**" }; _contactId = _service.Create(contact); contact.ContactId = _contactId; Console.Write("contact created, "); // Create a blank phone call. PhoneCall phoneCall = new PhoneCall(); _phoneCallId = _service.Create(phoneCall); Console.Write("phone call created, "); // Create an ActivityParty for the phone call's "to" field. ActivityParty activityParty = new ActivityParty() { PartyId = new EntityReference { Id = _contactId, LogicalName = Contact.EntityLogicalName, }, ActivityId = new EntityReference { Id = _phoneCallId, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9) }; // Create a phone call and add the properties we are updating. PhoneCall updatePhoneCall = new PhoneCall() { Id = _phoneCallId, Subject = "Test Phone Call", RegardingObjectId = new EntityReference { Id = _leadId, LogicalName = Lead.EntityLogicalName }, To = new ActivityParty[] { activityParty } }; // Update the phone call. UpdateRequest updateRequest = new UpdateRequest() { Target = updatePhoneCall }; _service.Execute(updateRequest); Console.Write("phone call updated.\n"); DeleteRequiredRecords(promptforDelete); } //</snippetWorkingWithRelatedAttributesforNto1Relationships1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
public void When_executing_a_linq_query_with_equals_between_2_activityparties_result_is_returned() { var fakedContext = new XrmFakedContext(); fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); var contactId = Guid.NewGuid(); var activityId = Guid.NewGuid(); var partyRecord = new ActivityParty() { Id = Guid.NewGuid(), ActivityId = new EntityReference(Email.EntityLogicalName, activityId), PartyId = new EntityReference(Contact.EntityLogicalName, contactId) }; fakedContext.Initialize(new List<Entity>() { new Email() { Id = activityId, ActivityId = activityId, Subject = "Test email"}, new ActivityPointer () { Id = Guid.NewGuid(), ActivityId = activityId }, partyRecord, new ActivityPointer() { Id = Guid.NewGuid()}, //To test also nulls new ActivityParty() { Id = Guid.NewGuid()} //To test also nulls }); var service = fakedContext.GetFakedOrganizationService(); using (XrmServiceContext ctx = new XrmServiceContext(service)) { var activities = (from pointer in ctx.CreateQuery<Email>() join party in ctx.CreateQuery<ActivityParty>() on pointer.ActivityId.Value equals party.ActivityId.Id // from party in ctx.CreateQuery<ActivityParty>() //on pointer.ActivityId.Value equals party.ActivityId.Id where party.PartyId.Id == contactId select pointer).ToList(); Assert.True(activities.Count == 1); } }