public PhoneCall FixEmptyDates(PhoneCall thisCall) { //Fix DateMin Casting to SQL DateMin if (thisCall.SessionEndTime == DateTime.MinValue) { thisCall.SessionEndTime = SqlDateTime.MinValue.Value; } if (thisCall.ResponseTime == DateTime.MinValue) { thisCall.ResponseTime = SqlDateTime.MinValue.Value; } if (thisCall.AcDisputeResolvedOn == DateTime.MinValue) { thisCall.AcDisputeResolvedOn = SqlDateTime.MinValue.Value; } if (thisCall.AcInvoiceDate == DateTime.MinValue) { thisCall.AcInvoiceDate = SqlDateTime.MinValue.Value; } if (thisCall.UiAssignedOn == DateTime.MinValue) { thisCall.UiAssignedOn = SqlDateTime.MinValue.Value; } if (thisCall.UiMarkedOn == DateTime.MinValue) { thisCall.UiMarkedOn = SqlDateTime.MinValue.Value; } return(thisCall); }
public override byte[] ToBytes() { return(TLUtils.Combine( TLUtils.SignatureToBytes(Signature), PhoneCall.ToBytes(), Users.ToBytes())); }
static void TestStatePhoneCall() { var phoneCall = new PhoneCall("Lokesh"); phoneCall.Print(); phoneCall.Dialed("Prameela"); phoneCall.Print(); phoneCall.Connected(); phoneCall.Print(); phoneCall.SetVolume(2); phoneCall.Print(); phoneCall.Hold(); phoneCall.Print(); phoneCall.Mute(); phoneCall.Print(); phoneCall.Unmute(); phoneCall.Print(); phoneCall.Resume(); phoneCall.Print(); phoneCall.SetVolume(11); phoneCall.Print(); Console.WriteLine("Graph..."); Console.WriteLine(phoneCall.ToDotGraph()); Console.WriteLine("Press any key..."); Console.ReadKey(true); }
public void Extensions_Entity_ToStringAttributes() { var entity = new Contact { FirstName = "a", LastName = "b", }; AssertAreEqual("{0}[firstname]: a{1}{0}[lastname]: b", entity.ToStringAttributes()); var phoneCall = new PhoneCall { From = new List <ActivityParty> { new ActivityParty { PartyId = new EntityReference(entity.LogicalName, Guid.NewGuid()) { Name = "a" } }, new ActivityParty { PartyId = new EntityReference(entity.LogicalName, Guid.NewGuid()) { Name = "b" } } } }; AssertAreEqual("{0}[from]: {1}{0}{0}[0:partyid]: " + phoneCall.From.First().PartyId.GetNameId() + "{1}{0}{0}[1:partyid]: " + phoneCall.From.Skip(1).First().PartyId.GetNameId(), phoneCall.ToStringAttributes()); }
public override void ToStream(Stream output) { output.Write(TLUtils.SignatureToBytes(Signature)); PhoneCall.ToStream(output); Users.ToStream(output); }
static void Main(string[] args) { var phoneCall = new PhoneCall("MyFriend"); phoneCall.Print(); phoneCall.Dialed("Prameela"); phoneCall.Print(); phoneCall.Connected(); phoneCall.Print(); phoneCall.SetVolume(2); phoneCall.Print(); phoneCall.Hold(); phoneCall.Print(); phoneCall.Mute(); phoneCall.Print(); phoneCall.Unmute(); phoneCall.Print(); phoneCall.Resume(); phoneCall.Print(); phoneCall.SetVolume(11); phoneCall.Print(); Console.WriteLine(phoneCall.ToDotGraph()); Console.WriteLine("Press any key..."); Console.ReadKey(true); }
// Ends the call and saves the information to the database. private void btnEnd_Click_1(object sender, EventArgs e) { string duration = lblHours.Text + ":" + lblMinutes.Text + ":" + lblSeconds.Text; string[] arrayNotes = rtxNotes.Text.Split('\n'); string notes = ""; for (int i = 0; i < arrayNotes.Length; i++) { notes = notes + " " + arrayNotes[i]; } string reason = cmbReason.Items[cmbReason.SelectedIndex].ToString(); PhoneCall call = new PhoneCall(); if (cmbReason.SelectedIndex != 0) { timer.Stop(); call = new PhoneCall(0, duration, DateTime.Now, reason, notes, int.Parse(admin.AdministratorID.ToString())); call.AddCall(); this.Hide(); } else { MessageBox.Show("Please choose a reason for the call!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public async Task <ActionResult <PhoneCall> > PostPhoneCall(PhoneCall phoneCall) { _context.PhoneCall.Add(phoneCall); await _context.SaveChangesAsync(); return(CreatedAtAction("GetPhoneCall", new { id = phoneCall.PhoneCallId }, phoneCall)); }
public async Task <IActionResult> PutPhoneCall(long id, PhoneCall phoneCall) { if (id != phoneCall.PhoneCallId) { return(BadRequest()); } _context.Entry(phoneCall).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PhoneCallExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public static async void TestPhoneCall() { Console.WriteLine("Calling phone number via Twilio. It should ring out."); Utils.Logger.Info("Calling phone number via Twilio. It should ring out."); try { var call = new PhoneCall { FromNumber = Caller.Gyantal, ToNumber = PhoneCall.PhoneNumbers[Caller.Gyantal], Message = "This is a test phone call from Health Monitor.", NRepeatAll = 2 }; // skipped temporarily bool didTwilioAcceptedTheCommand = await call.MakeTheCallAsync(); if (didTwilioAcceptedTheCommand) { Utils.Logger.Debug("TestPhoneCall(): PhoneCall instruction was sent to Twilio."); } else { Utils.Logger.Error("TestPhoneCall(): PhoneCall instruction was NOT accepted by Twilio."); } } catch (Exception e) { Utils.Logger.Error(e, "TestPhoneCall(): Exception in TestPhoneCall()."); } }
public static PhoneCall RandomCall() { PhoneCall call = new PhoneCall(); call.DialogClip = ClipManager.RandomClip(); return(call); }
public void Run_WithPhoneCallOnSuccess_SavesPhoneCallAndIncrementsCallbackBookingQuotaNumberOfBookings() { var candidateId = Guid.NewGuid(); var scheduledAt = DateTime.UtcNow.AddDays(3); var phoneCall = new PhoneCall() { ScheduledAt = scheduledAt }; _candidate.PhoneCall = phoneCall; var quota = new CallbackBookingQuota() { StartAt = scheduledAt, NumberOfBookings = 5, Quota = 10 }; _mockContext.Setup(m => m.GetRetryCount(null)).Returns(0); _mockCrm.Setup(mock => mock.Save(It.IsAny <Candidate>())).Callback <BaseModel>(c => c.Id = candidateId); _mockCrm.Setup(mock => mock.GetCallbackBookingQuota(scheduledAt)).Returns(quota); _job.Run(_candidate.SerializeChangeTracked(), null); phoneCall.CandidateId = candidateId.ToString(); _mockCrm.Verify(mock => mock.Save(It.Is <PhoneCall>(p => IsMatch(phoneCall, p))), Times.Once); _mockCrm.Verify(mock => mock.Save(It.Is <CallbackBookingQuota>(q => IsMatch(quota, q))), Times.Once); quota.NumberOfBookings.Should().Be(6); _metrics.HangfireJobQueueDuration.WithLabels(new[] { "UpsertCandidateJob" }).Count.Should().Be(1); }
public void DoEvent() { if (PhoneCall != null) { PhoneCall.Invoke(); } }
public void RemovePhoneCall(int id) { PhoneCall PhoneCall = GetPhoneCall(id); context.PhoneCalls.Remove(PhoneCall); context.SaveChanges(); }
public void Should_create_phone_call_history_on_create_of_a_phonecall_with_its_details() { var ctx = new XrmFakedContext(); var contact = new Contact() { Id = Guid.NewGuid() }; var phoneCall = new PhoneCall() { Id = Guid.NewGuid(), RegardingObjectId = contact.ToEntityReference(), PhoneNumber = "+34666666666" }; ctx.ExecutePluginWithTarget <PhoneCallCreatePlugin>(phoneCall); var historyRecords = ctx.CreateQuery <ultra_phonecallhistory>().ToList(); Assert.Equal(1, historyRecords.Count); var historyRecord = historyRecords.First(); Assert.Equal(phoneCall.PhoneNumber, historyRecord.ultra_phonenumber); Assert.Equal(phoneCall.RegardingObjectId.Id, historyRecord.ultra_contactid.Id); Assert.Equal(historyRecord.Id, phoneCall.ultra_phonecallhistoryid.Id); }
public void CheckPhoneCallHistory() { string crmCon = ConfigurationManager.ConnectionStrings["crm"].ConnectionString; using (CrmServiceClient svc = new CrmServiceClient(crmCon)) { Contact c = new Contact(); c.FirstName = "Wael"; c.LastName = Guid.NewGuid().ToString(); c.MobilePhone = new Random().Next(100000000, 200000000).ToString(); c.Id = svc.Create(c); PhoneCall p = new PhoneCall(); p.RegardingObjectId = c.ToEntityReference(); p.PhoneNumber = c.MobilePhone; p.Id = svc.Create(p); using (var ctx = new XrmServiceContext(svc)) { var exists = (from ph in ctx.CreateQuery <ultra_phonecallhistory>() where ph.ultra_contactid.Id == c.Id where ph.ultra_phonenumber == c.MobilePhone select ph).FirstOrDefault() != null; Assert.IsTrue(exists); } } }
public void Shouldnt_create_a_duplicate_phone_call_history_record() { var ctx = new XrmFakedContext(); var contact = new Contact() { Id = Guid.NewGuid() }; var phoneCall = new PhoneCall() { Id = Guid.NewGuid(), RegardingObjectId = contact.ToEntityReference(), PhoneNumber = "+34666666666" }; var existingPhoneCallHistory = new ultra_phonecallhistory() { Id = Guid.NewGuid(), ultra_contactid = contact.ToEntityReference(), ultra_phonenumber = phoneCall.PhoneNumber }; ctx.Initialize(existingPhoneCallHistory); ctx.ExecutePluginWithTarget <PhoneCallCreatePlugin>(phoneCall); var historyRecords = ctx.CreateQuery <ultra_phonecallhistory>().ToList(); Assert.Equal(1, historyRecords.Count); }
private void delCurCall_Click(object sender, EventArgs e) { if (lvCalls.CheckedItems.Count > 0) { foreach (ListViewItem item in lvCalls.CheckedItems) { lvCalls.Items.Remove(item); var selectedCall = new PhoneCall() { From = (item.SubItems[0].Text == "" ? null: item.SubItems[0].Text), To = item.SubItems[1].Text, StartTime = DateTime.Parse(item.SubItems[2].Text), Direction = (CallDirection)Enum.Parse(typeof(CallDirection), item.SubItems[4].Text) }; var calls = phone1.UseComponent <Memory>().Get <PhoneCall>().ToList(); foreach (var call in calls) { if ((call as IEquatable <PhoneCall>).Equals(selectedCall)) { phone1.UseComponent <Memory>().Get <PhoneCall>().Remove(call); } } } } }
public void ClearLine() { _currCall = null; _outgoing.ClearTarget(); _incoming.ClearTarget(); Operator.FreePhoneLine(this); }
public void LocalCrmTests_NonPrimitiveDataTypesAreCloned() { var service = GetService(); var contact = new Contact(); contact.Id = service.Create(contact); var phoneCall = new PhoneCall(); phoneCall.Id = service.Create(phoneCall); SetActivityParty(phoneCall, PhoneCall.Fields.From, new ActivityParty { PartyId = contact.ToEntityReference() }); phoneCall.CreatedBy = contact.ToEntityReference(); service.Update(phoneCall); phoneCall.CreatedBy.Name = "Test"; Assert.AreEqual(1, service.GetFirst <PhoneCall>().From.Count()); var from = phoneCall.GetAttributeValue <EntityCollection>(PhoneCall.Fields.From); from.Entities.Clear(); Assert.IsNull(service.GetFirst <PhoneCall>().CreatedBy.Name); Assert.AreEqual(1, service.GetFirst <PhoneCall>().From.Count()); }
public int solution(String S) { String[] phoneCalls = S.Split((char)10); var PhoneCall_dict = new Dictionary <long, PhoneCall>(); // maxiumum duraction call PhoneCall maxDurationphoneCall = null; int totalPhoneBill = 0; foreach (var phoneCall in phoneCalls) { var phoneInfo = phoneCall.Split(','); var duration = phoneInfo[0].Trim(); var phone = phoneInfo[1].Trim(); var NumericPhone = ConvertPhoneToNumeric(phone); PhoneCall phoneObj = null; if (!PhoneCall_dict.ContainsKey(NumericPhone)) { phoneObj = new PhoneCall() { phoneNumber = NumericPhone, totalDuration = CalcDurationInSec(duration), totalBill = CalcBill(duration) }; PhoneCall_dict.Add(phoneObj.phoneNumber, phoneObj); } else { phoneObj = PhoneCall_dict[NumericPhone]; phoneObj.totalDuration += CalcDurationInSec(duration); phoneObj.totalBill += CalcBill(duration); } totalPhoneBill += CalcBill(duration); // Check for Tie cases if (maxDurationphoneCall == null) // First time { maxDurationphoneCall = phoneObj; } else if (maxDurationphoneCall.totalDuration <= phoneObj.totalDuration) { if (maxDurationphoneCall.totalDuration < phoneObj.totalDuration) { maxDurationphoneCall = phoneObj; } else { //check for smallest numbr maxDurationphoneCall = (maxDurationphoneCall.phoneNumber < phoneObj.phoneNumber) ? maxDurationphoneCall : phoneObj; } } } return(totalPhoneBill - maxDurationphoneCall.totalBill); }
// Callback method for refreshing call state for the phone call. private void RefreshPhoneCallState(object pCall) { PhoneCall call = (PhoneCall)pCall; call.Refresh(); //string sAdd = "Call Status: " + call.State + "\r\n"; //txtBody.Text += sAdd; // TODO: need to get the body to display updates... }
public void Execute(IServiceProvider serviceProvider) { ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); CrmServiceContext xrm = new CrmServiceContext(service); if (context.PostEntityImages.Contains("PostCall") && context.PostEntityImages["PostCall"] is Entity) { PhoneCall call = context.PostEntityImages["PostCall"].ToEntity <PhoneCall>(); if (call.StateCode is PhoneCallState.Completed) { try { //call.Description += $"\nPhone call was completed at {call.ActualEnd} \nDue date: {call.ScheduledEnd}"; bool CallInTime = (int)DateTime.Compare((DateTime)call.ScheduledEnd, (DateTime)call.ActualEnd) >= 0;//>=0 in time, <0 not in time CrmEarlyBound.Task task = xrm.TaskSet.Where(p => p.RegardingObjectId.Id == call.RegardingObjectId.Id).ToList().FirstOrDefault(); if (task.StateCode is TaskState.Completed) { bool TaskInTime = (int)DateTime.Compare((DateTime)task.ScheduledEnd, (DateTime)task.ActualEnd) >= 0; BL.ActivityInTime(CallInTime, TaskInTime, call.RegardingObjectId.Id, serviceProvider); } //BL.ActivityInTime(call, CallInTime, call.RegardingObjectId.Id, serviceProvider); //get account from call //EntityReference acc = (EntityReference)call.Attributes["regardingobjectid"]; //Entity accc = service.Retrieve(acc.LogicalName, acc.Id, new ColumnSet(true)); //Account account = (Account)accc; //ColumnSet columnSet = new ColumnSet(true); //Account account = (Account)service.Retrieve("account", acc.Id, columnSet); //Entity accEnt = (Entity)account; //IEnumerable<Task> relatedTasks = account.Account_Tasks; //Task related = (Task)relatedTasks.First<Task>(); /* * List<Task> relatedTasks = xrm.TaskSet.Where(c => c.RegardingObjectId.Id == account.Id).ToList(); * Task related = relatedTasks.First(); * //throw new InvalidPluginExecutionException(related == null ? "null" : "not null"); * if (related.StateCode is TaskState.Completed)//Value cannot be null. Parameter name: source * { * bool TaskInTime = (int)DateTime.Compare((DateTime)related.ScheduledEnd, (DateTime)related.ActualEnd) >= 0; * if (CallInTime && TaskInTime) * account.new_NewClientProccess = Account_new_NewClientProccess.Passedintime; * else * account.new_NewClientProccess = Account_new_NewClientProccess.Passednotintime; * service.Update(call); * service.Update(account); * } */ } catch (Exception ex) { throw new InvalidPluginExecutionException($"An error occurred in Call plug-in: {ex.Message}"); } } } }
public ConnectionResult ConnectCall(int receptorId) { if (gameController.currentGameState != GameState.PLAYING) { return(ConnectionResult.IS_VOID); } if (phoneCalls.Count(x => x.state == PhoneCallState.PENDING) > 0) { if (currentPhoneCall == null) { if (phoneCalls.Count(x => x.state == PhoneCallState.CONNECTED) > 2) { return(ConnectionResult.IS_VOID); } currentPhoneCall = phoneCalls.Take(phoneCallIndex).FirstOrDefault(x => x.state == PhoneCallState.PENDING && x.caller == receptorId); if (currentPhoneCall != null) { gameController.NotifyShowCaller(currentPhoneCall.caller); sfxController.PlayPlugIn(); return(ConnectionResult.IS_CALLER); } } else if (currentPhoneCall.receiver == receptorId) { currentPhoneCall.state = PhoneCallState.CONNECTED; stressController.EndCall(phoneCalls.IndexOf(currentPhoneCall)); gameController.CallCompleted(currentPhoneCall.caller, receptorId); currentPhoneCall = null; sfxController.PlayConnected(); return(ConnectionResult.IS_RECEIVER); } else { stressController.WrongConnection(); if (receptorId == currentPhoneCall.caller) { return(ConnectionResult.IS_SAME); } if (phoneCalls.Take(phoneCallIndex).Any(x => x.state == PhoneCallState.PENDING && x.caller == receptorId)) { return(ConnectionResult.IS_SAME); } gameController.WrongConnection(receptorId); sfxController.PlayError(); return(ConnectionResult.IS_WRONG); } } return(ConnectionResult.IS_VOID); }
public void EqualCallsTest() { PhoneCall call1 = new PhoneCall("123", true, cont1); PhoneCall call2 = new PhoneCall("123", true, cont1); bool res = call1.Equals(call2); Assert.IsTrue(res); }
/// <summary> /// Callback method for refreshing call state for the phone call. /// </summary> /// <param name="pCall">The PhoneCall object that contains the call state.</param> static void RefreshPhoneCallState(object pCall) { PhoneCall call = (PhoneCall)pCall; // Update the phone call state. This results in a GetPhoneCallInformation operation call to EWS. call.Refresh(); Console.WriteLine(DateTime.Now + " - Call Status: " + call.State); }
} // End Sub ListAllMails /// <summary> /// Finds the first email message and initiates an attempt to call a phone number and /// dictate the contents of the email message. This sample requires that Unified Messaging /// is enabled for the caller. /// </summary> /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param> public static void PlayEmailOnPhone(ExchangeService service) { /// <summary> /// Callback method for refreshing call state for the phone call. /// </summary> /// <param name="pCall">The PhoneCall object that contains the call state.</param> void RefreshPhoneCallState(object pCall) { PhoneCall phoneCall = (PhoneCall)pCall; // Update the phone call state. This results in a GetPhoneCallInformation operation call to EWS. phoneCall.Refresh(); System.Console.WriteLine(System.DateTime.Now + " - Call Status: " + phoneCall.State); } // End Sub RefreshPhoneCallState // Find the first email message in the Inbox folder. ItemView view = new ItemView(1); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); // Find the first email message in the Inbox. This results in a FindItem operation call to EWS. FindItemsResults <Item> results = service.FindItems(WellKnownFolderName.Inbox, view); try { string itemId = results.Items[0].Id.UniqueId; string dialstring = "4255551212"; // Initiate a call to dictate an email message over a phone call. // This results in a PlayOnPhone operation call to EWS. PhoneCall call = service.UnifiedMessaging.PlayOnPhone(itemId, dialstring); System.Console.WriteLine("Call Number: " + dialstring); System.Console.WriteLine(System.DateTime.Now + " - Call Status: " + call.State + "\n\r"); // Create a timer that will start immediately. Timer will call callback every 2 seconds. using (System.Threading.Timer timer = new System.Threading.Timer(RefreshPhoneCallState, call, 0, 2000)) { System.Console.WriteLine("PRESS ENTER TO END THE PHONE CALL AND CALL STATUS UPDATES"); System.Console.ReadLine(); // Disconnect the phone call if it is not already disconnected. if (call.State != PhoneCallState.Disconnected) { call.Disconnect(); } } // End Using timer System.Console.WriteLine("PRESS ENTER TO END CLOSE THIS WINDOW"); System.Console.ReadLine(); } catch (System.Exception ex) { System.Console.WriteLine(ex.Message); } } // End Sub PlayEmailOnPhone
private void frmCallHistory_Load(object sender, EventArgs e) { dgvCallHistory.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; dgvCallHistory.AutoResizeColumns(); bs.DataSource = PhoneCall.GetCalls(); dgvCallHistory.DataSource = bs.DataSource; }
/// <summary> /// Refreshes the state of this phone call. /// </summary> void Refresh() { PhoneCall phoneCall = service.UnifiedMessaging.GetPhoneCallInformation(this.id); this.state = phoneCall.State; this.connectionFailureCause = phoneCall.ConnectionFailureCause; this.sipResponseText = phoneCall.SIPResponseText; this.sipResponseCode = phoneCall.SIPResponseCode; }
: super() { EwsUtilities.Assert( service != null, "GetPhoneCallResponse.ctor", "service is null"); this.phoneCall = new PhoneCall(service); }
public static void Main() { Soldier giJoe = new Soldier(266143); PhoneCall aCall = new PhoneCall("212", "344-4188"); Console.WriteLine(giJoe.ToString()); giJoe.Reverse(); Console.WriteLine(giJoe.ToString()); giJoe.Reverse(); Console.WriteLine(giJoe.ToString()); Console.WriteLine(aCall.ToString()); aCall.Reverse(); Console.WriteLine(aCall.ToString()); }
/// <summary> /// This method creates any entity records that this sample requires. /// Create a queue instance. /// Create a phone call activity instance. /// Add phone call entity instance in to queue. /// Mark phone call entity instance status as completed. /// </summary> public void CreateRequiredRecords() { // Create a queue instance and set its property values. Queue newQueue = new Queue() { Name = "Example Queue", Description = "This is an example queue.", QueueViewType = new OptionSetValue((int)QueueQueueViewType.Private) }; _queueId = _serviceProxy.Create(newQueue); Console.WriteLine("Created {0}.", newQueue.Name); // Create a phone call activity instance. PhoneCall newPhoneCall = new PhoneCall { Description = "Example Phone Call" }; _phoneCallId = _serviceProxy.Create(newPhoneCall); Console.WriteLine("Created {0}.", newPhoneCall.Description); // Create a new instance of a queueitem and initialize its // properties. QueueItem item = new QueueItem { QueueId = new EntityReference(Queue.EntityLogicalName, _queueId), ObjectId = new EntityReference(PhoneCall.EntityLogicalName, _phoneCallId) }; // Create the queueitem on the server, which will associate // the phone call activity with the queue. _queueItemId = _serviceProxy.Create(item); Console.WriteLine("Added phone call entity instance to {0}", newQueue.Name); // Mark the phone call as completed. SetStateRequest setStatePhoneCall = new SetStateRequest { EntityMoniker = new EntityReference(PhoneCall.EntityLogicalName, _phoneCallId), State = new OptionSetValue((int)PhoneCallState.Completed), Status = new OptionSetValue(-1) }; _serviceProxy.Execute(setStatePhoneCall); Console.WriteLine("PhoneCall entity instance has been marked as completed."); return; }
/// <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 }
/// <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 DistributeCampaign() { Console.WriteLine("=== Creating and Distributing the Campaign ==="); // Create the campaign. var campaign = new Campaign { Name = "Sample Campaign" }; _originalCampaignId = _serviceProxy.Create(campaign); NotifyEntityCreated(Campaign.EntityLogicalName, _originalCampaignId); //<snippetDistributeCampaignFromMarketingList1> // Copy the campaign. var campaignCopyRequest = new CopyCampaignRequest { BaseCampaign = _originalCampaignId }; var copyCampaignResponse = (CopyCampaignResponse)_serviceProxy.Execute(campaignCopyRequest); _campaignId = copyCampaignResponse.CampaignCopyId; Console.WriteLine(" Copied the campaign to new campaign with GUID \r\n\t{{{0}}}", _campaignId); //</snippetDistributeCampaignFromMarketingList1> var activity = new CampaignActivity { Subject = "Sample phone call", ChannelTypeCode = new OptionSetValue((int)CampaignActivityChannelTypeCode.Phone), RegardingObjectId = new EntityReference( Campaign.EntityLogicalName, _campaignId) }; _campaignActivityId = _serviceProxy.Create(activity); NotifyEntityCreated(CampaignActivity.EntityLogicalName, _campaignActivityId); // Find the current user to determine who the owner of the activity should be. var whoAmI = new WhoAmIRequest(); var currentUser = (WhoAmIResponse)_serviceProxy.Execute(whoAmI); //<snippetDistributeCampaignFromMarketingList2> // Add the marketing list created earlier to the campaign. var addListToCampaignRequest = new AddItemCampaignRequest { CampaignId = _campaignId, EntityId = _copiedMarketingListId, EntityName = List.EntityLogicalName, }; _serviceProxy.Execute(addListToCampaignRequest); Console.WriteLine(" Added the marketing list to the campaign."); //</snippetDistributeCampaignFromMarketingList2> //<snippetDistributeCampaignFromMarketingList3> // Add the marketing list created earlier to the campaign activity. var addListToActivityRequest = new AddItemCampaignActivityRequest { CampaignActivityId = _campaignActivityId, ItemId = _copiedMarketingListId, EntityName = List.EntityLogicalName }; _serviceProxy.Execute(addListToActivityRequest); Console.WriteLine(" Added the marketing list to the campaign activity."); //</snippetDistributeCampaignFromMarketingList3> // Create the phone call to use for distribution. var phonecall = new PhoneCall { Subject = "Sample Phone Call" }; //<snippetDistributeCampaignFromMarketingList4> // Distribute and execute the campaign activity. // PostWorkflowEvent signals Microsoft Dynamics CRM to actually create the phone call activities. // Propagate also signals to Microsoft Dynamics CRM to create the phone call activities. // OwnershipOptions indicates whom the created activities should be assigned // to. var distributeRequest = new DistributeCampaignActivityRequest { Activity = phonecall, CampaignActivityId = _campaignActivityId, Owner = new EntityReference( SystemUser.EntityLogicalName, currentUser.UserId), OwnershipOptions = PropagationOwnershipOptions.Caller, PostWorkflowEvent = true, Propagate = true, SendEmail = false, }; var distributeResponse = (DistributeCampaignActivityResponse)_serviceProxy.Execute(distributeRequest); Console.WriteLine(" Distributed and executed the campaign activity to the marketing list."); //</snippetDistributeCampaignFromMarketingList4> //<snippetDistributeCampaignFromMarketingList5> // Retrieve the members that were distributed to. var retrieveMembersRequest = new RetrieveMembersBulkOperationRequest { BulkOperationId = distributeResponse.BulkOperationId, BulkOperationSource = (int)BulkOperationSource.CampaignActivity, EntitySource = (int)EntitySource.Contact, Query = new QueryExpression(Contact.EntityLogicalName) }; var retrieveMembersResponse = (RetrieveMembersBulkOperationResponse) _serviceProxy.Execute(retrieveMembersRequest); Console.WriteLine(" Contacts with the following GUIDs were distributed to:"); //</snippetDistributeCampaignFromMarketingList5> foreach (var member in retrieveMembersResponse.EntityCollection.Entities) { Console.WriteLine("\t{{{0}}}", member.Id); } }
/// <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; } }