public async Task QuerySchedules_ToQueryString_Start_IsCorrect() { Uri requestUri = null; var httpClient = new HttpClient(new MockedHttpMessageHandler((request) => { requestUri = request.RequestUri; return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.NoContent))); })); var crmClient = FakeCrmWebApiClient.Create(httpClient); var crmRequest = new QueryScheduleRequest() { Start = new DateTime(2019, 02, 25, 0, 0, 0, DateTimeKind.Utc), }; await crmClient.ExecuteAsync(crmRequest); var value = QueryHelpers.ParseQuery(requestUri.Query) .GetValueOrDefault("@Start").ToString(); value.Should().NotBeNullOrEmpty(); value.Should().Be(crmRequest.Start.ToString("yyyy-MM-ddTHH:mm:ssZ")); }
public async Task QuerySchedules_ToQueryString_ResourceId_IsCorrect() { Uri requestUri = null; var httpClient = new HttpClient(new MockedHttpMessageHandler((request) => { requestUri = request.RequestUri; return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.NoContent))); })); var crmClient = FakeCrmWebApiClient.Create(httpClient); // Create var crmRequest = new QueryScheduleRequest() { ResourceId = SetupBase.EntityId }; await crmClient.ExecuteAsync(crmRequest); // Test var value = QueryHelpers.ParseQuery(requestUri.Query).GetValueOrDefault("@ResourceId").ToString(); value.Should().NotBeNullOrEmpty(); value.Should().Be($"{SetupBase.EntityId}"); }
public async Task QuerySchedules_ToQueryString_When_One_TimeCodes_IsCorrect() { Uri requestUri = null; var httpClient = new HttpClient(new MockedHttpMessageHandler((request) => { requestUri = request.RequestUri; return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.NoContent))); })); var crmClient = FakeCrmWebApiClient.Create(httpClient); var crmRequest = new QueryScheduleRequest() { TimeCodes = new[] { TimeCode.Filter } }; await crmClient.ExecuteAsync(crmRequest); // Test var value = QueryHelpers.ParseQuery(requestUri.Query).GetValueOrDefault("@TimeCodes").ToString(); value.Should().NotBeNullOrEmpty(); value.Should().Be($"[\"{(int) TimeCode.Filter}\"]"); }
public void QuerySchedules_ToQueryString_When_Empty_TimeCodes_IsCorrect() { var request = new QueryScheduleRequest(); var queryString = request.QueryString(); var queryParams = queryString.Split("?").Last(); var value = QueryHelpers.ParseQuery(queryParams).GetValueOrDefault("@TimeCodes").ToString(); value.Should().NotBeNullOrEmpty(); value.Should().Be("[]"); }
/// <summary> /// Search the specified resource for an available time block that matches the specified parameters. /// <para> /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.queryschedulerequest(v=crm.8).aspx /// </para> /// </summary> /// <param name="resourceId">Resource Id</param> /// <param name="start">Start of the time slot.</param> /// <param name="end">End of the time slot.</param> /// <param name="timecode"> /// <see cref="TimeCode"/> /// </param> /// <returns><see cref="QueryScheduleResponse"/></returns> public QueryScheduleResponse GetWorkingHours(Guid resourceId, DateTime start, DateTime end, TimeCode timecode) { ExceptionThrow.IfGuidEmpty(resourceId, "resourceId"); QueryScheduleRequest request = new QueryScheduleRequest() { ResourceId = resourceId, Start = start, End = end, TimeCodes = new TimeCode[] { timecode } }; return((QueryScheduleResponse)this.OrganizationService.Execute(request)); }
public async Task Execute_QuerySchedule_When_Resource_Is_CurrentUser_Then_ResultOk() { var request = new QueryScheduleRequest() { ResourceId = CrmClient.GetMyCrmUserId(), Start = System.DateTime.Now.Date, End = System.DateTime.Now.Date.AddDays(1).AddSeconds(-1), TimeCodes = new TimeCode[] { TimeCode.Available } }; var response = await CrmClient.ExecuteAsync <QueryScheduleResponse>(request); response.TimeInfos.Should().NotBeNull(); response.TimeInfos.Should().NotBeEmpty(); }
public void QuerySchedules_ToQueryString_End_IsCorrect() { var request = new QueryScheduleRequest() { End = new DateTime(2019, 02, 25, 0, 0, 0, DateTimeKind.Local), }; var queryString = request.QueryString(); var queryParams = queryString.Split("?").Last(); var value = QueryHelpers.ParseQuery(queryParams).GetValueOrDefault("@End").ToString(); value.Should().NotBeNullOrEmpty(); value.Should().Be(request.End.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")); }
public void QuerySchedules_ToQueryString_When_Multiple_TimeCodes_IsCorrect() { var request = new QueryScheduleRequest() { TimeCodes = new[] { TimeCode.Filter, TimeCode.Available, TimeCode.Busy } }; var queryString = request.QueryString(); var queryParams = queryString.Split("?").Last(); var value = QueryHelpers.ParseQuery(queryParams).GetValueOrDefault("@TimeCodes").ToString(); value.Should().NotBeNullOrEmpty(); value.Should().Be($"[\"3\",\"0\",\"1\"]"); }
public void QuerySchedules_ToQueryString_ResourceId_IsCorrect() { var request = new QueryScheduleRequest() { ResourceId = SetupBase.EntityId }; var queryString = request.QueryString(); var queryParams = queryString.Split("?").Last(); var value = QueryHelpers.ParseQuery(queryParams).GetValueOrDefault("@ResourceId").ToString(); value.Should().NotBeNullOrEmpty(); value.Should().Be($"{SetupBase.EntityId}"); }
/// <summary> /// Create and configure the organization service proxy. /// Retrieve the working hours of the current user. /// 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 = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetQueryWorkingHoursOfUser1> // Get the current user's information. WhoAmIRequest userRequest = new WhoAmIRequest(); WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest); // Retrieve the working hours of the current user. QueryScheduleRequest scheduleRequest = new QueryScheduleRequest { ResourceId = userResponse.UserId, Start = DateTime.Now, End = DateTime.Today.AddDays(7), TimeCodes = new TimeCode[] { TimeCode.Available } }; QueryScheduleResponse scheduleResponse = (QueryScheduleResponse)_serviceProxy.Execute(scheduleRequest); // Verify if some data is returned for the availability of the current user if (scheduleResponse.TimeInfos.Length > 0) { Console.WriteLine("Successfully queried the working hours of the current user."); } //</snippetQueryWorkingHoursOfUser1> } } // 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; } }
[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 // Get the current user's information. WhoAmIRequest userRequest = new WhoAmIRequest(); WhoAmIResponse userResponse = (WhoAmIResponse)service.Execute(userRequest); // Retrieve the working hours of the current user. QueryScheduleRequest scheduleRequest = new QueryScheduleRequest { ResourceId = userResponse.UserId, Start = DateTime.Now, End = DateTime.Today.AddDays(7), TimeCodes = new TimeCode[] { TimeCode.Available } }; QueryScheduleResponse scheduleResponse = (QueryScheduleResponse)service.Execute(scheduleRequest); // Verify if some data is returned for the availability of the current user if (scheduleResponse.TimeInfos.Length > 0) { Console.WriteLine("Successfully queried the working hours of the current user."); } } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse"; 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; } } } #endregion Demonstrate catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
public async Task <List <AppointmentTimeSlot> > getRescheduleVisitDates(string userId, DateTime currentBookDate, string workOrderId, DateTime startDate, DateTime endDate) { List <AppointmentTimeSlot> listObj = new List <AppointmentTimeSlot>(); Configuration configuration = new Configuration(); SoapEntityRepository repo = SoapEntityRepository.GetService(); if (string.IsNullOrEmpty(userId)) { throw new ValidationException("Resource not booked for this visit."); } if (!string.IsNullOrEmpty(workOrderId)) { QueryExpression query = new QueryExpression(xrm.msdyn_workorder.EntityLogicalName); query.Criteria.AddCondition("msdyn_workorderid", ConditionOperator.Equal, new Guid(workOrderId)); query.ColumnSet = new ColumnSet("mzk_visitstatus", "mzk_actualvisitstartdatetime", "mzk_numberoftimerescheduled"); LinkEntity link1 = new LinkEntity(xrm.msdyn_workorder.EntityLogicalName, xrm.mzk_prescription.EntityLogicalName, "mzk_prescription", "mzk_prescriptionid", JoinOperator.LeftOuter) { Columns = new ColumnSet("mzk_prescriptionstatus"), EntityAlias = "Prescription" }; LinkEntity link2 = new LinkEntity(xrm.mzk_prescription.EntityLogicalName, xrm.Opportunity.EntityLogicalName, "mzk_referral", "opportunityid", JoinOperator.LeftOuter) { Columns = new ColumnSet("mzk_status"), EntityAlias = "Referral" }; LinkEntity link3 = new LinkEntity(xrm.msdyn_workorder.EntityLogicalName, xrm.msdyn_workordertype.EntityLogicalName, "msdyn_workordertype", "msdyn_workordertypeid", JoinOperator.LeftOuter) { Columns = new ColumnSet("mzk_canberescheduledbythepatient"), EntityAlias = "WorkOrderType" }; link1.LinkEntities.Add(link2); query.LinkEntities.Add(link1); query.LinkEntities.Add(link3); EntityCollection entitycollection = repo.GetEntityCollection(query); configuration = configuration.getConfiguration(); foreach (Entity entity in entitycollection.Entities) { if (entity.Attributes.Contains("WorkOrderType.mzk_canberescheduledbythepatient")) { if (entity.GetAttributeValue <AliasedValue>("WorkOrderType.mzk_canberescheduledbythepatient").Value.Equals(false)) { QueryExpression bu_query = new QueryExpression(xrm.BusinessUnit.EntityLogicalName); bu_query.Criteria.AddCondition("parentbusinessunitid", ConditionOperator.Null); bu_query.ColumnSet = new ColumnSet("mzk_contactcentrenumber", "mzk_facility", "name"); bu_query.TopCount = 1; EntityCollection entityCollection = repo.GetEntityCollection(bu_query); if (entityCollection.Entities.Count > 0) { if (entityCollection.Entities[0].Attributes.Contains("mzk_contactcentrenumber") && entityCollection.Entities[0].Attributes.Contains("name")) { throw new ValidationException("This type of treatment/appointment cannot be re-scheduled using the app. Please call " + entityCollection.Entities[0]["name"] + " on " + entityCollection.Entities[0]["mzk_contactcentrenumber"].ToString() + " to discuss your treatment options."); } else { throw new ValidationException("This type of treatment/appointment cannot be re-scheduled using the app."); } } else { throw new ValidationException("This type of treatment/appointment cannot be re-scheduled using the app."); } } } if (entity.Attributes.Contains("mzk_visitstatus")) { if (entity["mzk_visitstatus"].Equals(new OptionSetValue(275380002))) { throw new ValidationException("Visit cannot be rescheduled as it is already delivered"); } if (entity["mzk_visitstatus"].Equals(new OptionSetValue(275380000))) { if (entity.Attributes.Contains("mzk_proposedvisitdatetime")) { DateTime visitDate = (DateTime)entity["mzk_proposedvisitdatetime"]; int days = (int)(visitDate - DateTime.Now).TotalDays; if (configuration.numberOfDays > 0) { if (days < configuration.numberOfDays) { throw new ValidationException("Visit can only be rescheduled " + configuration.numberOfDays.ToString() + " days prior to your delivery date."); } } } } if (entity["mzk_visitstatus"].Equals(new OptionSetValue(275380001))) { if (entity.Attributes.Contains("mzk_scheduledstartdatetime")) { DateTime visitDate = (DateTime)entity["mzk_scheduledstartdatetime"]; int days = (int)(visitDate - DateTime.Now).TotalDays; if (configuration.numberOfDays > 0) { if (days < configuration.numberOfDays) { throw new ValidationException("Visit can only be rescheduled " + configuration.numberOfDays.ToString() + " days prior to your delivery date."); } } } } } if (entity.Attributes.Contains("mzk_numberoftimerescheduled")) { int timesRescheduled = entity.GetAttributeValue <int>("mzk_numberoftimerescheduled"); if (timesRescheduled >= configuration.rescheduleDaysAllowed) { throw new ValidationException("You cannot reschedule more than " + configuration.rescheduleDaysAllowed.ToString() + " times"); } } if (entity.Attributes.Contains("Referral.mzk_status")) { if (entity.GetAttributeValue <AliasedValue>("Referral.mzk_status").Value.Equals(new OptionSetValue(275380008))) { throw new ValidationException("Visit cannot be rescheduled as referral is marked finished"); } } if (entity.Attributes.Contains("Prescription.mzk_prescriptionstatus")) { if (entity.GetAttributeValue <AliasedValue>("Prescription.mzk_prescriptionstatus").Value.Equals(new OptionSetValue(275380002))) { throw new ValidationException("Visit cannot be rescheduled as prescription is on hold"); } } if (entity.Attributes.Contains("Prescription.mzk_prescriptionstatus")) { if (entity.GetAttributeValue <AliasedValue>("Prescription.mzk_prescriptionstatus").Value.Equals(new OptionSetValue(100000000))) { throw new ValidationException("Visit cannot be rescheduled as prescription is expired"); } } } } QueryScheduleRequest scheduleRequest = new QueryScheduleRequest { ResourceId = new Guid(userId), Start = startDate, End = endDate, TimeCodes = new TimeCode[] { TimeCode.Available } }; QueryScheduleResponse scheduleResponse = (QueryScheduleResponse)repo.Execute(scheduleRequest); if (scheduleResponse != null) { foreach (var item in scheduleResponse.TimeInfos) { AppointmentTimeSlot modelObj = new AppointmentTimeSlot(); modelObj.StartDate = item.Start.Value; modelObj.EndDate = item.End.Value; listObj.Add(modelObj); } } return(listObj); }
public IEnumerable<TimeInfo> GetSchedule(Guid resourceId, DateTime start, DateTime end) { var req = new QueryScheduleRequest { End = end, Start = start, ResourceId = resourceId, TimeCodes = new[] {TimeCode.Available} }; var response = (QueryScheduleResponse) Execute(req); return response.TimeInfos; }
/// <summary> /// Create and configure the organization service proxy. /// Retrieve the working hours of the current user. /// 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(); //<snippetQueryWorkingHoursOfUser1> // Get the current user's information. WhoAmIRequest userRequest = new WhoAmIRequest(); WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest); // Retrieve the working hours of the current user. QueryScheduleRequest scheduleRequest = new QueryScheduleRequest { ResourceId = userResponse.UserId, Start = DateTime.Now, End = DateTime.Today.AddDays(7), TimeCodes = new TimeCode[] { TimeCode.Available } }; QueryScheduleResponse scheduleResponse = (QueryScheduleResponse)_serviceProxy.Execute(scheduleRequest); // Verify if some data is returned for the availability of the current user if (scheduleResponse.TimeInfos.Length > 0) { Console.WriteLine("Successfully queried the working hours of the current user."); } //</snippetQueryWorkingHoursOfUser1> } } // 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; } }