public DtoOrder AddResponse(int orderId, int drugStoreId, DtoSkuReply skuReplay) { try { EnsureArg.IsGt(orderId, 0, nameof(orderId)); } catch (Exception ex) { throw new BadRequest(ex); } var order = OrderQueries.GetOrder(orderId); var drugstore = StoreDomain.Get(drugStoreId); if (order.Responses != null) { order.Responses = new List <DtoOrderResponse>(); var response = new DtoOrderResponse() { DrugStore = drugstore, Accepted = false }; OrderQueries.CreateResponse(ref response, orderId); order.Responses.Add(response); } return(CheckOrder(order)); }
public List <DtoOrder> GetAvailableOrders(int storeId) { try { EnsureArg.IsGt(storeId, 0, nameof(storeId)); } catch (Exception ex) { throw new BadRequest(ex); } var response = CacheManager.GetHashs <DtoOrder>(CacheKey.StoreOrders, storeId.ToString()); var removeItem = new List <string>(); foreach (var item in response) { var relativeTimespace = item.Value.RequestedOn - DateTime.Now; if (relativeTimespace > TimeSpan.FromMinutes(ORDER_RESPONSE_EXPIRATION_TIME)) { CacheManager.DeleteHash(CacheKey.StoreOrders, storeId.ToString(), item.Key); removeItem.Add(item.Key); } } var result = response.Where(i => !removeItem.Contains(i.Key)).Select(i => i.Value).ToList(); var ordered = OrderQueries.GetOrderIn(result.Select(i => i.Id).ToList()).OrderBy(i => i.RequestedOn); return(ordered.Select(i => CheckOrder(i)).ToList()); }
public DtoOrder AddSku(int orderId, DtoSku skuRequest) { try { EnsureArg.IsNotNull(skuRequest, nameof(skuRequest)); EnsureArg.IsGt(orderId, 0, nameof(orderId)); } catch (Exception ex) { throw new BadRequest(ex); } var skus = OrderQueries.GetRequestedSkus(orderId); var dbsku = skus.Where(i => i.Id == skuRequest.Id).FirstOrDefault(); DtoOrder dtoOrder = null; if (dbsku == null) { dtoOrder = OrderQueries.AddSku(orderId, skuRequest.Id, skuRequest.Quantity.Value); } else { dtoOrder = OrderQueries.UpdateSku(orderId, dbsku.OrderSkuId.Value, skuRequest.Quantity.Value); } return(CheckOrder(dtoOrder)); }
public DtoOrder MakeOrderRequest(int orderId) { try { EnsureArg.IsGt(orderId, 0, nameof(orderId)); } catch (Exception ex) { throw new BadRequest(ex); } var order = OrderQueries.GetOrder(orderId); order.RequestedOn = DateTime.Now; OrderQueries.Update(ref order); var stores = StoreDomain.GetNearStore(order.AddressToShip); order.RequestedStores = stores; foreach (var store in stores) { OrderQueries.SetStoreOnOrder(order.Id, store.Id); CacheManager.SetHash(CacheKey.StoreOrders, store.Id.ToString(), order.Id.ToString(), order); } return(CheckOrder(order)); }
/// <summary> /// Given a list of <see cref="SearchParameterInfo"/> calculates a hash using the /// <see cref="SearchParameterInfo.Url"/>, <see cref="SearchParameterInfo.Type"/>, /// <see cref="SearchParameterInfo.Expression"/>, <see cref="SearchParameterInfo.TargetResourceTypes"/>, and /// <see cref="SearchParameterInfo.BaseResourceTypes"/>, /// values of each component. The same collection of search parameter infos (irrespective of their order in the input) /// will return the same hash. /// </summary> /// <param name="searchParamaterInfos">A list of <see cref="SearchParameterInfo" /></param> /// <returns>A hash based on the search parameter uri and last updated value.</returns> public static string CalculateSearchParameterHash(IEnumerable <SearchParameterInfo> searchParamaterInfos) { EnsureArg.IsNotNull(searchParamaterInfos, nameof(searchParamaterInfos)); EnsureArg.IsGt(searchParamaterInfos.Count(), 0, nameof(searchParamaterInfos)); StringBuilder sb = new StringBuilder(); foreach (SearchParameterInfo searchParamInfo in searchParamaterInfos.OrderBy(x => x.Url.ToString())) { sb.Append(searchParamInfo.Url.ToString()); sb.Append(searchParamInfo.Type.ToString()); sb.Append(searchParamInfo.Expression); if (searchParamInfo.TargetResourceTypes != null && searchParamInfo.TargetResourceTypes.Any()) { sb.Append(string.Join(null, searchParamInfo.TargetResourceTypes.OrderBy(s => s))); } if (searchParamInfo.BaseResourceTypes != null && searchParamInfo.BaseResourceTypes.Any()) { sb.Append(string.Join(null, searchParamInfo.BaseResourceTypes.OrderBy(s => s))); } } string hash = sb.ToString().ComputeHash(); return(hash); }
public Perft(int depth, Action <string, ulong> callback, ICollection <PerftPosition> positions = null) { EnsureArg.IsGt(depth, 0, nameof(depth)); _positions = positions == null ? new List <PerftPosition>() : positions.ToList(); _perftLimit = depth; _callback = callback; }
/// <summary> /// Find the K nearest neighbors. /// O(K logN) /// </summary> /// <param name="startingLocation"></param> /// <param name="maxDistance"></param> /// <param name="maxResults"></param> /// <returns></returns> public async Task <IEnumerable <LocationWithDistanceFromStartingPoint> > GetNearestLocations(StartingLocation startingLocation, int maxDistance, int maxResults) { EnsureArg.IsNotNull(startingLocation, nameof(startingLocation)); EnsureArg.IsGte(maxDistance, 0, nameof(maxDistance)); EnsureArg.IsGt(maxResults, 0, nameof(maxResults)); var startLoc = new Location(startingLocation.Latitude, startingLocation.Longitude); var nearestNeighbors = _locationsKdTree.GetNearestRadialNeighbors( startingLocation.Latitude, startingLocation.Longitude, maxDistance); var res = nearestNeighbors .Select(t => { var loc = new Location(t.Item2, t.Item1[0], t.Item1[1]); return(new LocationWithDistanceFromStartingPoint(loc, loc.CalculateDistance(startLoc))); }) .Where(l => l.DistanceFromStartingPoint <= maxDistance) .OrderBy(l => l.DistanceFromStartingPoint) .Take(maxResults) .ToList(); return(await Task.FromResult(res)); }
public override async Task <IReadOnlyList <WatermarkRange> > GetInstanceBatchesAsync( int batchSize, int batchCount, IndexStatus indexStatus, long?maxWatermark = null, CancellationToken cancellationToken = default) { EnsureArg.IsGt(batchSize, 0, nameof(batchSize)); EnsureArg.IsGt(batchCount, 0, nameof(batchCount)); using SqlConnectionWrapper sqlConnectionWrapper = await SqlConnectionWrapperFactory.ObtainSqlConnectionWrapperAsync(cancellationToken); using SqlCommandWrapper sqlCommandWrapper = sqlConnectionWrapper.CreateSqlCommand(); VLatest.GetInstanceBatches.PopulateCommand(sqlCommandWrapper, batchSize, batchCount, (byte)indexStatus, maxWatermark); try { var batches = new List <WatermarkRange>(); using SqlDataReader reader = await sqlCommandWrapper.ExecuteReaderAsync(cancellationToken); while (await reader.ReadAsync(cancellationToken)) { batches.Add(new WatermarkRange(reader.GetInt64(0), reader.GetInt64(1))); } return(batches); } catch (SqlException ex) { throw new DataStoreException(ex); } }
public ExportJobRecord( Uri requestUri, ExportJobType exportType, string exportFormat, string resourceType, IList <ExportJobFilter> filters, string hash, uint rollingFileSizeInMB, IReadOnlyCollection <KeyValuePair <string, string> > requestorClaims = null, PartialDateTime since = null, string groupId = null, string storageAccountConnectionHash = null, string storageAccountUri = null, string anonymizationConfigurationLocation = null, string anonymizationConfigurationFileETag = null, uint maximumNumberOfResourcesPerQuery = 100, uint numberOfPagesPerCommit = 10, string storageAccountContainerName = null, int schemaVersion = 2) { EnsureArg.IsNotNull(requestUri, nameof(requestUri)); EnsureArg.IsNotNullOrWhiteSpace(hash, nameof(hash)); EnsureArg.IsNotNullOrWhiteSpace(exportFormat, nameof(exportFormat)); EnsureArg.IsGt(schemaVersion, 0, nameof(schemaVersion)); Hash = hash; RequestUri = requestUri; ExportType = exportType; ExportFormat = exportFormat; ResourceType = resourceType; Filters = filters; RequestorClaims = requestorClaims; Since = since; GroupId = groupId; StorageAccountConnectionHash = storageAccountConnectionHash; StorageAccountUri = storageAccountUri; MaximumNumberOfResourcesPerQuery = maximumNumberOfResourcesPerQuery; NumberOfPagesPerCommit = numberOfPagesPerCommit; RollingFileSizeInMB = rollingFileSizeInMB; AnonymizationConfigurationLocation = anonymizationConfigurationLocation; AnonymizationConfigurationFileETag = anonymizationConfigurationFileETag; // Default values SchemaVersion = schemaVersion; Id = Guid.NewGuid().ToString(); Status = OperationStatus.Queued; QueuedTime = Clock.UtcNow; if (string.IsNullOrWhiteSpace(storageAccountContainerName)) { StorageAccountContainerName = Id; } else { StorageAccountContainerName = storageAccountContainerName; } }
private Company(string name, int numberOfEmployees) { EnsureArg.IsNotNull(name); EnsureArg.IsGt(numberOfEmployees, 0); this.Name = name; this.NumberOfEmployees = numberOfEmployees; }
private Subscription(EmployeesRange employeesRange, decimal price) { EnsureArg.IsNotNull(employeesRange); EnsureArg.IsGt(price, 0); EmployeesRange = employeesRange; Price = price; }
private EmployeesRange(int inferiorLimit, int superiorLimit) { EnsureArg.IsGt(inferiorLimit, 0); EnsureArg.IsGt(superiorLimit, 0); InferiorLimit = inferiorLimit; SuperiorLimit = superiorLimit; }
/// <summary> /// Limit the number of the returned documents to the specified number. /// </summary> /// <param name="value"></param> /// <returns></returns> public virtual FindParametersConfigurator Limit(int value) { EnsureArg.IsGt(value, 0, nameof(value)); Parameters.Limit = value; return(this); }
/// <summary> /// Initialise une nouvelle instance de la classes <see cref="VariableLengthStringGenerator"/> /// </summary> /// <param name="rnd">Le générateur aléatoire</param> public VariableLengthStringGenerator(IRandomNumber rnd, int maxLength, bool unicode) : base(rnd) { EnsureArg.IsGt(maxLength, 0, nameof(maxLength)); this.maximumlength = maxLength; this.isUnicode = unicode; }
public void IsGt_When_value_is_gt_than_limit_It_should_not_throw() { var spec = When_value_is_gt_than_limit(); ShouldNotThrow( () => Ensure.That(spec.Value, ParamName).IsGt(spec.Limit), () => EnsureArg.IsGt(spec.Value, spec.Limit, ParamName)); }
public void IsGt_When_value_is_lt_than_limit_It_throws_ArgumentException() { var spec = When_value_is_lt_than_limit(); AssertIsGtScenario(spec.Value, spec.Limit, () => Ensure.That(spec.Value, ParamName).IsGt(spec.Limit), () => EnsureArg.IsGt(spec.Value, spec.Limit, ParamName)); }
private static void Validate(AgreementRequest request) { Ensure.Guid.IsNotEmpty(request.Id, nameof(request.Id)); EnsureArg.IsGt(request.Amount, 0, nameof(request.Amount)); Ensure.Enum.IsDefined(request.BaseRateCode, nameof(request.BaseRateCode)); EnsureArg.IsGt(request.Duration, 0, nameof(request.Duration)); EnsureArg.IsGt(request.Margin, 0, nameof(request.Margin)); Ensure.Guid.IsNotEmpty(request.CustomerId, nameof(request.CustomerId)); }
/// <summary> /// Starts the rest-service on the provided port. /// </summary> /// <param name="port">Port that the service should bind onto.</param> /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="port"/> is out of bounds.</exception> /// <inheritdoc /> public void Listen(int port) { EnsureArg.IsGt(port, IPEndPoint.MinPort, nameof(port)); EnsureArg.IsLt(port, IPEndPoint.MaxPort, nameof(port)); owinInstance = WebApp.Start(new StartOptions { Port = port }, Startup); }
/// <summary> /// Copies all the data from one stream into another, using the given /// buffer for transferring data. Note that the current contents of /// the buffer is ignored, so the buffer needn't be cleared beforehand. /// </summary> public static long CopyTo(this Stream input, Stream output, byte[] buffer) { EnsureArg.IsNotNull(buffer, nameof(buffer)); EnsureArg.IsNotNull(input, nameof(input)); EnsureArg.IsNotNull(output, nameof(output)); EnsureArg.IsGt(buffer.Length, 0, optsFn: options => options.WithMessage("Buffer has length of 0.")); return(CopyToImpl(input, output, buffer).Sum()); }
public void IsGt_When_value_is_gt_than_limit_It_returns_passed_value() { var spec = When_value_is_gt_than_limit(); var returnedValue = Ensure.That(spec.Value, ParamName).IsGt(spec.Limit); AssertReturnedAsExpected(returnedValue, spec.Value); Action a = () => EnsureArg.IsGt(spec.Value, spec.Limit, ParamName); a.ShouldNotThrow(); }
public override async Task <IReadOnlyList <ExtendedQueryTagStoreEntry> > AddExtendedQueryTagsAsync( IReadOnlyCollection <AddExtendedQueryTagEntry> extendedQueryTagEntries, int maxAllowedCount, bool ready = false, CancellationToken cancellationToken = default) { EnsureArg.IsNotNull(extendedQueryTagEntries, nameof(extendedQueryTagEntries)); EnsureArg.IsGt(maxAllowedCount, 0, nameof(maxAllowedCount)); using SqlConnectionWrapper sqlConnectionWrapper = await ConnectionWrapperFactory.ObtainSqlConnectionWrapperAsync(cancellationToken); using SqlCommandWrapper sqlCommandWrapper = sqlConnectionWrapper.CreateSqlCommand(); IEnumerable <AddExtendedQueryTagsInputTableTypeV1Row> rows = extendedQueryTagEntries.Select(ToAddExtendedQueryTagsInputTableTypeV1Row); VLatest.AddExtendedQueryTags.PopulateCommand(sqlCommandWrapper, maxAllowedCount, ready, new VLatest.AddExtendedQueryTagsTableValuedParameters(rows)); try { var results = new List <ExtendedQueryTagStoreEntry>(); using SqlDataReader reader = await sqlCommandWrapper.ExecuteReaderAsync(cancellationToken); while (await reader.ReadAsync(cancellationToken)) { (int tagKey, string tagPath, string tagVR, string tagPrivateCreator, int tagLevel, int tagStatus, byte queryStatus, int errorCount) = reader.ReadRow( VLatest.ExtendedQueryTag.TagKey, VLatest.ExtendedQueryTag.TagPath, VLatest.ExtendedQueryTag.TagVR, VLatest.ExtendedQueryTag.TagPrivateCreator, VLatest.ExtendedQueryTag.TagLevel, VLatest.ExtendedQueryTag.TagStatus, VLatest.ExtendedQueryTag.QueryStatus, VLatest.ExtendedQueryTag.ErrorCount); results.Add(new ExtendedQueryTagStoreEntry(tagKey, tagPath, tagVR, tagPrivateCreator, (QueryTagLevel)tagLevel, (ExtendedQueryTagStatus)tagStatus, (QueryStatus)queryStatus, errorCount)); } return(results); } catch (SqlException ex) { throw ex.Number switch { SqlErrorCodes.Conflict => ex.State == 1 ? new ExtendedQueryTagsExceedsMaxAllowedCountException(maxAllowedCount) : new ExtendedQueryTagsAlreadyExistsException(), _ => new DataStoreException(ex), }; } }
public List <UserLocation> GetCurrentLocationForAllUsersByAreaCoordinates(AreaCoordinates area) { EnsureArg.IsNotNull(area, nameof(area)); EnsureArg.IsGt(area.LongitudeMin, -180, nameof(area.LongitudeMin)); EnsureArg.IsLt(area.LongitudeMin, 180, nameof(area.LongitudeMin)); EnsureArg.IsGt(area.LongitudeMax, -180, nameof(area.LongitudeMax)); EnsureArg.IsLt(area.LongitudeMax, 180, nameof(area.LongitudeMax)); EnsureArg.IsGt(area.LatitudeMin, -180, nameof(area.LatitudeMin)); EnsureArg.IsLt(area.LatitudeMin, 180, nameof(area.LatitudeMin)); EnsureArg.IsGt(area.LatitudeMax, -180, nameof(area.LatitudeMax)); EnsureArg.IsLt(area.LatitudeMax, 180, nameof(area.LatitudeMax)); return(CurrentLocationOfUsersInArea); }
public string GenerateHashCode(string valueToHash, int range = 256) { EnsureArg.IsGt(range, 0, nameof(range)); EnsureArg.IsNotNull(valueToHash, nameof(valueToHash)); int h = 0; foreach (char c in valueToHash.ToCharArray()) { h = unchecked ((31 * h) + c); } return((Math.Abs(h) % range).ToString(CultureInfo.InvariantCulture)); }
public UserLocation GetCurrentLocationForUser(int userId) { EnsureArg.IsGt(userId, 0, nameof(userId)); // get most recent location from store return(new UserLocation { UserId = userId, Longitude = 12.34, Latitude = -23.45, Area = "Here", RecordedAt = DateTime.Now.AddMinutes(-5) }); }
public bool SetCurrentLocation(UserLocation userLocation) { EnsureArg.IsGt(userLocation.UserId, 0, nameof(userLocation.UserId)); EnsureArg.IsGt(userLocation.Longitude, -180, nameof(userLocation.Longitude)); EnsureArg.IsLt(userLocation.Longitude, 180, nameof(userLocation.Longitude)); EnsureArg.IsGt(userLocation.Latitude, -90, nameof(userLocation.Latitude)); EnsureArg.IsLt(userLocation.Latitude, 90, nameof(userLocation.Latitude)); EnsureArg.IsNotNullOrWhiteSpace(userLocation.Area, nameof(userLocation.Area)); userLocation.RecordedAt = DateTime.Now; // add to store return(true); }
public MeasurementEventNormalizationService( ITelemetryLogger log, IContentTemplate contentTemplate, Data.IConverter <EventData, JToken> converter, IExceptionTelemetryProcessor exceptionTelemetryProcessor, int maxParallelism, int asyncCollectorBatchSize = 200) { _log = EnsureArg.IsNotNull(log, nameof(log)); _contentTemplate = EnsureArg.IsNotNull(contentTemplate, nameof(contentTemplate)); _converter = EnsureArg.IsNotNull(converter, nameof(converter)); _exceptionTelemetryProcessor = EnsureArg.IsNotNull(exceptionTelemetryProcessor, nameof(exceptionTelemetryProcessor)); _maxParallelism = maxParallelism; _asyncCollectorBatchSize = EnsureArg.IsGt(asyncCollectorBatchSize, 0, nameof(asyncCollectorBatchSize)); }
/// <summary> /// Reads the given stream up to the end, returning the data as a byte /// array, using the given buffer for transferring data. Note that the /// current contents of the buffer is ignored, so the buffer needn't /// be cleared beforehand. /// </summary> public static byte[] ReadFully(this Stream input, byte[] buffer) { EnsureArg.IsNotNull(buffer, nameof(buffer)); EnsureArg.IsNotNull(input, nameof(input)); EnsureArg.IsGt(buffer.Length, 0, optsFn: options => options.WithMessage("Buffer has length of 0.")); using (var stream = new MemoryStream()) { input.CopyTo(stream, buffer); return(stream.Length == stream.GetBuffer().Length ? stream.GetBuffer() : stream.ToArray()); } }
public DtoAddress GetAddressInfo(double latitude, double longitude) { try { EnsureArg.IsGt(latitude, 0, nameof(latitude)); EnsureArg.IsGt(longitude, 0, nameof(longitude)); } catch (Exception ex) { throw new BadRequest(ex); } return(GeocodeApi.GetAddress(latitude, longitude)); }
public List <DtoAddress> RemoveAddress(int id, string clientToken) { try { EnsureArg.IsGt(id, 0, nameof(id)); EnsureArg.IsNotNullOrEmpty(clientToken, nameof(clientToken)); } catch (Exception ex) { throw new BadRequest(ex); } ClientQueries.DeleteAddress(clientToken, id); return(ClientQueries.GetAllAddress(clientToken)); }
/// <summary> /// Given a list of <see cref="ResourceSearchParameterStatus"/> calculates a hash using the /// <see cref="ResourceSearchParameterStatus.Uri"/> and <see cref="ResourceSearchParameterStatus.LastUpdated"/> /// values of each component. The same collection of search parameter status (irrespective of their order in the input) /// will return the same hash. /// </summary> /// <param name="resourceSearchParameterStatus">A list of <see cref="ResourceSearchParameterStatus" /></param> /// <returns>A hash based on the search parameter uri and last updated value.</returns> public static string CalculateSearchParameterHash(IEnumerable <ResourceSearchParameterStatus> resourceSearchParameterStatus) { EnsureArg.IsNotNull(resourceSearchParameterStatus, nameof(resourceSearchParameterStatus)); EnsureArg.IsGt(resourceSearchParameterStatus.Count(), 0, nameof(resourceSearchParameterStatus)); StringBuilder sb = new StringBuilder(); foreach (ResourceSearchParameterStatus searchParameterStatus in resourceSearchParameterStatus.OrderBy(x => x.Uri.ToString())) { sb.Append(searchParameterStatus.Uri.ToString()); sb.Append(searchParameterStatus.LastUpdated.ToString()); } string hash = sb.ToString().ComputeHash(); return(hash); }