public virtual async Task Run(SearchProductResponse parameter, Func <SearchProductResponse, Task> next) { if (parameter == null) { throw new ArgumentNullException(nameof(parameter)); } var query = parameter.Query; if (query == null) { throw new OperationCanceledException("Query must be set"); } var responseGroup = EnumUtility.SafeParse(query.GetResponseGroup(), ExpProductResponseGroup.None); // If promotion evaluation requested if (responseGroup.HasFlag(ExpProductResponseGroup.LoadPrices)) { var promoEvalContext = new PromotionEvaluationContext { Currency = query.CurrencyCode, StoreId = query.StoreId, Language = query.CultureName, CustomerId = query.UserId }; await _pipeline.Execute(promoEvalContext); //Evaluate promotions promoEvalContext.PromoEntries = parameter.Results.Select(x => _mapper.Map <ProductPromoEntry>(x, options => { options.Items["all_currencies"] = parameter.AllStoreCurrencies; options.Items["currency"] = parameter.Currency; })).ToList(); var promotionResults = await _marketingEvaluator.EvaluatePromotionAsync(promoEvalContext); var promoRewards = promotionResults.Rewards.OfType <CatalogItemAmountReward>().ToArray(); if (promoRewards.Any()) { parameter.Results.Apply(x => x.ApplyRewards(promoRewards)); } } await next(parameter); }
private RequestBodyBuilder PopulateRequestParameters(KnowledgebaseCategoryRequest knowledgebaseCategoryRequest, RequestTypes requestType) { knowledgebaseCategoryRequest.EnsureValidData(requestType); var parameters = new RequestBodyBuilder(); parameters.AppendRequestDataNonEmptyString("title", knowledgebaseCategoryRequest.Title); if (knowledgebaseCategoryRequest.CategoryType.HasValue) { parameters.AppendRequestData("categorytype", EnumUtility.ToApiString(knowledgebaseCategoryRequest.CategoryType.Value)); } if (knowledgebaseCategoryRequest.ParentCategoryId.HasValue) { parameters.AppendRequestData("parentcategoryid", knowledgebaseCategoryRequest.ParentCategoryId.Value); } if (knowledgebaseCategoryRequest.DisplayOrder.HasValue) { parameters.AppendRequestDataNonNegativeInt("displayorder", knowledgebaseCategoryRequest.DisplayOrder.Value); } if (knowledgebaseCategoryRequest.ArticleSortOrder.HasValue) { parameters.AppendRequestData("articlesortorder", EnumUtility.ToApiString(knowledgebaseCategoryRequest.ArticleSortOrder.Value)); } parameters.AppendRequestDataBool("allowcomments", knowledgebaseCategoryRequest.AllowComments); parameters.AppendRequestDataBool("allowrating", knowledgebaseCategoryRequest.AllowRating); parameters.AppendRequestDataBool("ispublished", knowledgebaseCategoryRequest.IsPublished); parameters.AppendRequestDataBool("uservisibilitycustom", knowledgebaseCategoryRequest.UserVisibilityCustom); parameters.AppendRequestDataArrayCommaSeparated("usergroupidlist", knowledgebaseCategoryRequest.UserGroupIdList); parameters.AppendRequestDataBool("staffvisibilitycustom", knowledgebaseCategoryRequest.StaffVisibilityCustom); parameters.AppendRequestDataArrayCommaSeparated("staffgroupidlist", knowledgebaseCategoryRequest.StaffGroupIdList); if (requestType == RequestTypes.Create && knowledgebaseCategoryRequest.StaffId.HasValue) { parameters.AppendRequestDataNonNegativeInt("staffid", knowledgebaseCategoryRequest.StaffId.Value); } return(parameters); }
public static User ToUser(this dto.ApplicationUser userDto) { var result = new User() { Email = userDto.Email, Id = userDto.Id, ContactId = userDto.MemberId, PhoneNumber = userDto.PhoneNumber, UserName = userDto.UserName, StoreId = userDto.StoreId, IsRegisteredUser = true, IsAdministrator = userDto.IsAdministrator ?? false, Permissions = userDto.Permissions, AccessFailedCount = userDto.AccessFailedCount ?? 0, LockoutEnabled = userDto.LockoutEnabled ?? false, EmailConfirmed = userDto.EmailConfirmed ?? false, LockoutEndDateUtc = userDto.LockoutEndDateUtc, PasswordHash = userDto.PasswordHash, SecurityStamp = userDto.SecurityStamp, UserState = EnumUtility.SafeParse(userDto.UserState, AccountState.Approved), UserType = userDto.UserType, TwoFactorEnabled = userDto.TwoFactorEnabled ?? false, PhoneNumberConfirmed = userDto.PhoneNumberConfirmed ?? false, }; if (!userDto.Roles.IsNullOrEmpty()) { result.Roles = userDto.Roles.Select(x => new Role { Id = x.Id, Name = x.Name }); } if (!userDto.Logins.IsNullOrEmpty()) { result.ExternalLogins = userDto.Logins.Select(x => new ExternalUserLoginInfo { LoginProvider = x.LoginProvider, ProviderKey = x.ProviderKey }).ToList(); } return(result); }
public IEnumerable <ResourceScanInformation> List() { var resources = StreamResources(); return(resources .Select(res => new ResourceScanInformation() { ResourceType = EnumUtility.ParseLiteral <ResourceType>(res.Name.LocalName).Value, ResourceUri = fullUrl(res), Canonical = getPrimitiveValueElement(res, "url"), ValueSetSystem = getValueSetSystem(res), UniqueIds = getUniqueIds(res), ConceptMapSource = getCmSources(res), ConceptMapTarget = getCmTargets(res), Origin = _origin, })); }
/// <summary> /// Creates an Error response based on the passed-in localized /// Message and Property. /// </summary> /// <typeparam name="TStatusCode">Type of the StatusCode property /// in the ApiError object.</typeparam> /// <param name="message">Localized Message describing the error. /// </param> /// <param name="property">Name of the invalid property, null if /// the payload is null.</param> /// <returns>Error response based on the passed-in localized /// Message and Property.</returns> protected ApiError <TStatusCode> Error <TStatusCode>( string message, string property) where TStatusCode : struct, IConvertible { var statusCode = property == null ? ApiStatusCode.BadRequest.ToString() : string.Format(CultureInfo.InvariantCulture, ApiStatusCode.Format.GetDescription(), property); var apiError = new ApiError <TStatusCode> { Message = LocalizeString(message), StatusCode = EnumUtility.GetValueFromDescription <TStatusCode>(statusCode) }; Logger.LogWarning(apiError.Message); return(apiError); }
public static Inventory ToInventory(this inventoryDto.InventoryInfo inventoryDto) { var result = new Inventory { AllowBackorder = inventoryDto.AllowBackorder, AllowPreorder = inventoryDto.AllowPreorder, BackorderAvailabilityDate = inventoryDto.BackorderAvailabilityDate, FulfillmentCenterId = inventoryDto.FulfillmentCenterId, InStockQuantity = inventoryDto.InStockQuantity, PreorderAvailabilityDate = inventoryDto.PreorderAvailabilityDate, ProductId = inventoryDto.ProductId, ReservedQuantity = inventoryDto.ReservedQuantity, Status = EnumUtility.SafeParse(inventoryDto.Status, InventoryStatus.Disabled) }; return(result); }
public virtual PaymentPlan ToModel(PaymentPlan paymentPlan) { if (paymentPlan == null) { throw new ArgumentNullException(nameof(paymentPlan)); } paymentPlan.Id = Id; paymentPlan.CreatedBy = CreatedBy; paymentPlan.CreatedDate = CreatedDate; paymentPlan.ModifiedBy = ModifiedBy; paymentPlan.ModifiedDate = ModifiedDate; paymentPlan.IntervalCount = IntervalCount; paymentPlan.TrialPeriodDays = TrialPeriodDays; paymentPlan.Interval = EnumUtility.SafeParse(Interval, PaymentInterval.Months); return(paymentPlan); }
public void GetEnumEntriesTest() { var entries = EnumUtility.GetEnumEntries(typeof(Gender), true); Assert.AreEqual(2, entries.Length); Assert.AreEqual("Male", entries[0].Name); Assert.AreEqual("Female", entries[1].Name); entries = EnumUtility.GetEnumEntries(typeof(Nullable <Gender>), true, null, "<Unknown>"); Assert.AreEqual(3, entries.Length); Assert.AreEqual("", entries[0].Name); Assert.AreEqual(null, entries[0].Value); Assert.AreEqual("<Unknown>", entries[0].Description); Assert.AreEqual("Male", entries[1].Name); Assert.AreEqual("Female", entries[2].Name); }
public virtual OperationLog ToModel(OperationLog operation) { if (operation == null) { throw new ArgumentNullException(nameof(operation)); } operation.CreatedBy = CreatedBy; operation.CreatedDate = CreatedDate; operation.Detail = Detail; operation.Id = Id; operation.ModifiedBy = ModifiedBy; operation.ModifiedDate = ModifiedDate; operation.ObjectId = ObjectId; operation.ObjectType = ObjectType; operation.OperationType = EnumUtility.SafeParse(OperationType, EntryState.Unchanged); return(operation); }
private static string TransformType(CitationType type) { return(type switch { CitationType.ArticleMagazine => "article-magazine", CitationType.ArticleNewspaper => "article-newspaper", CitationType.ArticleJournal => "article-journal", CitationType.EntryDictionary => "entry-dictionary", CitationType.EntryEncyclopedia => "entry-encyclopedia", CitationType.LegalCase => "legal_case", CitationType.MotionPicture => "motion_picture", CitationType.MusicalScore => "musical_score", CitationType.PaperConference => "paper-conference", CitationType.PostWeblog => "post-webblog", CitationType.PersonalCommunication => "personal_communication", CitationType.ReviewBook => "review-book", _ => EnumUtility.GetName(type)?.ToLowerInvariant() ?? string.Empty });
internal static FhirVersion GetFhirVersion(Type fhirType) { var modelInfoType = fhirType.Assembly.GetTypes() .Where(t => t.Name.Equals("ModelInfo")) .FirstOrDefault(); var version = modelInfoType .GetProperty("Version", BindingFlags.Static | BindingFlags.Public) .GetValue(null) as string; FhirVersion?fhirVersion = default; if (SemanticVersion.TryParse(version, out SemanticVersion semanticVersion)) { fhirVersion = EnumUtility.ParseLiteral <FhirVersion>($"{semanticVersion.Major}.{semanticVersion.Minor}"); } return(fhirVersion ?? FhirVersion.None); }
public virtual void ReduceDetails(string responseGroup) { var orderResponseGroup = EnumUtility.SafeParseFlags(responseGroup, CustomerOrderResponseGroup.Full); if (!orderResponseGroup.HasFlag(CustomerOrderResponseGroup.WithDiscounts)) { Discounts = null; } if (!orderResponseGroup.HasFlag(CustomerOrderResponseGroup.WithPrices)) { Price = 0m; PriceWithTax = 0m; DiscountAmount = 0m; DiscountAmountWithTax = 0m; TaxTotal = 0m; TaxPercentRate = 0m; } }
private static List <Provider> SetProvidersFromReader(SqlDataReader reader) { var providerList = new List <Provider>(); if (reader.HasRows) { while (reader.Read()) { providerList.Add(new Provider { npi = reader["NPI"].ToString(), name = new ProviderName { first = reader["FIRSTNAME"].ToString(), middle = reader["MIDDLENAME"].ToString(), last = reader["LASTNAME"].ToString(), suffix = String.IsNullOrEmpty(reader["SUFFIX"].ToString()) ? null : reader["Suffix"].ToString() }, address = new Address { address = reader["LINE1"].ToString(), address_2 = reader["LINE2"].ToString(), city = reader["CITY"].ToString(), state = reader["STATE"].ToString(), zip = reader["ZIP"].ToString() }, specialty = new List <string> { EnumUtility.Convert( (DentalProviderSpecialty)Enum.Parse(typeof(DentalProviderSpecialty), reader["PROVIDERSPECIALTY"].ToString())) }, phone = reader["PHONENUMBER"].ToString(), networks = reader["NETWORK"].ToString(), network_type = reader["NETWORKTYPE"].ToString(), import_type = reader["IMPORTTYPE"].ToString(), accepting = Boolean.Parse(reader["NEWPATIENTS"].ToString()), last_updated_on = DateTime.Today.ToString("yyyy-MM-dd") }); } } return(providerList); }
public virtual void LoadContent(string content, IDictionary <string, IEnumerable <string> > metaInfoMap) { foreach (var setting in metaInfoMap) { var settingValue = setting.Value.FirstOrDefault(); switch (setting.Key.ToLower()) { case "permalink": this.Permalink = settingValue; break; case "title": this.Title = settingValue; break; case "author": this.Author = settingValue; break; case "published": this.PublicationStatus = EnumUtility.SafeParse <ContentPublicationStatus>(settingValue, ContentPublicationStatus.Draft); break; case "tags": this.Tags = setting.Value.ToList(); break; case "layout": this.Layout = settingValue; break; } } Content = content; if (Title == null) { Title = Name; } }
/// <summary> /// Get all columns /// </summary> /// <returns>All columns</returns> public override IEnumerable <ModelBase> GetAllColumns() { var columns = new List <ModelBase> { new GridField { field = "SegmentNumberString", title = SegmentCodesResx.SegmentNumber, attributes = FinderConstant.CssClassGridColumn10, headerAttributes = FinderConstant.CssClassGridColumn10, PresentationList = EnumUtility.GetItemsList <SegmentNumber>() }, new GridField { field = "SegmentCode", title = SegmentCodesResx.SegmentCode, attributes = FinderConstant.CssClassGridColumn10, headerAttributes = FinderConstant.CssClassGridColumn10, dataType = FinderConstant.DataTypeString, customAttributes = new Dictionary <string, string> { { FinderConstant.CustomAttributeMaximumLength, "24" }, { "class", FinderConstant.CssClassTxtUpper }, { FinderConstant.CustomAtrributeFormatTextBox, FinderConstant.AlphaNumeric } } }, new GridField { field = "Description", title = SegmentCodesResx.Description, attributes = FinderConstant.CssClassGridColumn10, headerAttributes = FinderConstant.CssClassGridColumn10, dataType = FinderConstant.DataTypeString, customAttributes = new Dictionary <string, string> { { FinderConstant.CustomAttributeMaximumLength, "60" } } } }; return(columns.AsEnumerable()); }
private static RequestBodyBuilder PopulateRequestParameters(DepartmentRequest dept, RequestTypes requestType) { dept.EnsureValidData(requestType); RequestBodyBuilder parameters = new RequestBodyBuilder(); if (!String.IsNullOrEmpty(dept.Title)) { parameters.AppendRequestData("title", dept.Title); } parameters.AppendRequestData("type", EnumUtility.ToApiString(dept.Type)); if (requestType == RequestTypes.Create) { parameters.AppendRequestData("module", EnumUtility.ToApiString(dept.Module)); } if (dept.DisplayOrder > 0) { parameters.AppendRequestData("displayorder", dept.DisplayOrder); } if (dept.ParentDepartmentId > 0) { parameters.AppendRequestData("parentdepartmentid", dept.ParentDepartmentId); } if (dept.UserVisibilityCustom) { parameters.AppendRequestData("uservisibilitycustom", 1); } else { parameters.AppendRequestData("uservisibilitycustom", 0); } if (dept.UserGroups != null && dept.UserGroups.Count > 0) { parameters.AppendRequestDataArray <int>("usergroupid[]", dept.UserGroups); } return(parameters); }
public void Delete(int id, int quantidadeEsperada) { BaseResultModel result = null; PaginatedMongoModel <ListaEmpresaMongoModel> listResult = null; "Quando solicitado editar empresa com id {0}" .x(async() => { var user = await service.MongoService.GetMongoObjectByParentId <PessoaMongoModel>(1); if (user == null) { result = new BaseResultModel { IsValid = false, StatusCode = 404, Message = "Profile não encontrado" }; } else { var model = await service.MongoService.GetMongoObjectByParentId <EmpresaClienteMongoModel>(id); result = await service.DeleteEmpresaBindingModel(new DeleteBindingModel { Id = model.Id }); } }); "Então o result deve ser válido e o objeto deve ter sido excluído" .x(() => { Assert.NotNull(result); Assert.Equal(result.IsValid, true); }); "Quando novamente solicitado obter todas as empresas" .x(async() => { var model = new PaginatedRequestCommand { Page = 1, Take = 1000, Type = EnumUtility.GetEnumText(GetTypes.Paged) }; listResult = await service.GetAll <ListaEmpresaMongoModel>(container, model); }); "Então a quantidade de empresas deve ser {1}" .x(() => { Assert.Equal(listResult.Items.Count(), quantidadeEsperada); Reset(true); }); }
public virtual Address ToModel(Address address) { address.CountryCode = CountryCode; address.CountryName = CountryName; address.PostalCode = PostalCode; address.RegionId = RegionId; address.RegionName = RegionName; address.City = City; address.Name = Name; address.Email = Email; address.FirstName = FirstName; address.LastName = LastName; address.Line1 = Line1; address.Line2 = Line2; address.Key = Id; address.Phone = DaytimePhoneNumber; address.AddressType = EnumUtility.SafeParse(Type, AddressType.BillingAndShipping); return(address); }
public AdventurerModel GenerateUnique() { GameObject newAdventurer = new GameObject(); AdventurerModel adventurerScript = newAdventurer.AddComponent <AdventurerModel> (); AdventurerData adventurerData = dataBase.GetRandomAdventurer(); adventurerScript._unitName = adventurerData.name; adventurerScript._unitDescription = adventurerData.description; adventurerScript.rarity = EnumUtility.StringToRarity(adventurerData.rarity); adventurerScript.totalHealth = adventurerData.max_health; adventurerScript.dexterity = adventurerData.dex_mod; adventurerScript.strength = adventurerData.str_mod; adventurerScript.wisdom = adventurerData.wis_mod; adventurerScript.attack_damage = adventurerData.attackDamage; newAdventurer.name = adventurerScript._unitName + ", " + adventurerScript._unitDescription; return(adventurerScript); }
public static Payment TowebModel(this VirtoCommerceCartModuleWebModelPayment payment) { var webModel = new Payment(); var currency = new Currency(EnumUtility.SafeParse(payment.Currency, CurrencyCodes.USD)); webModel.InjectFrom(payment); webModel.Amount = new Money(payment.Amount ?? 0, currency.Code); if (payment.BillingAddress != null) { webModel.BillingAddress = payment.BillingAddress.ToWebModel(); } webModel.Currency = currency; return(webModel); }
public static PaymentIn ToCoreModel(this PaymentInEntity entity) { if (entity == null) { throw new ArgumentNullException("entity"); } var retVal = new PaymentIn(); retVal.InjectFrom(entity); retVal.Currency = (CurrencyCodes)Enum.Parse(typeof(CurrencyCodes), entity.Currency); retVal.PaymentStatus = EnumUtility.SafeParse <PaymentStatus>(entity.Status, PaymentStatus.Custom); if (entity.Addresses != null && entity.Addresses.Any()) { retVal.BillingAddress = entity.Addresses.First().ToCoreModel(); } return(retVal); }
private void Parse(NameValueCollection queryString) { Keyword = queryString.Get("q"); //TODO move this code to Parse or Converter method // tags=name1:value1,value2,value3;name2:value1,value2,value3 SearchInChildren = Convert.ToBoolean(queryString.Get("deep_search") ?? SearchInChildren.ToString()); ResponseGroup = EnumUtility.SafeParse(queryString.Get("resp_group"), CatalogSearchResponseGroup.WithProducts | CatalogSearchResponseGroup.WithCategories | CatalogSearchResponseGroup.WithProperties | CatalogSearchResponseGroup.WithOutlines); SortBy = queryString.Get("sort_by"); Terms = (queryString.GetValues("terms") ?? new string[0]) .SelectMany(s => s.Split(';')) .Select(s => s.Split(':')) .Where(a => a.Length == 2) .SelectMany(a => a[1].Split(',').Select(v => new Term { Name = a[0], Value = v })) .ToArray(); VendorId = queryString.Get("vendor"); VendorIds = (queryString.GetValues("vendors") ?? new string[0]); }
public override void Execute() { Validate(); var state = State as UserStudingPlansStatisticsEventState; //学习中的计划状态,指:未开始,学习中的状态 var status = EnumUtility.GetEnumValues(typeof(UserStudyPlanStatus)).ToList(); //排除已学习完成的 status.Remove((int)UserStudyPlanStatus.COMPLETE); status.TrimExcess(); //学员 学习计划数量 int count = UserStudyPlanAccessor.GetPlansCount(state.UserId, status); //更新仓储数据 UserStudyAccessor.UpdateStudyPlans(state.UserId, count); }
public CategoryEntity[] GetCategoriesByIds(string[] categoriesIds, string respGroup = null) { if (categoriesIds == null) { throw new ArgumentNullException(nameof(categoriesIds)); } if (!categoriesIds.Any()) { return(new CategoryEntity[] { }); } var categoryRespGroup = EnumUtility.SafeParse(respGroup, CategoryResponseGroup.Full); if (categoryRespGroup.HasFlag(CategoryResponseGroup.WithOutlines)) { categoryRespGroup |= CategoryResponseGroup.WithLinks | CategoryResponseGroup.WithParents; } var result = Categories.Where(x => categoriesIds.Contains(x.Id)).ToArray(); if (categoryRespGroup.HasFlag(CategoryResponseGroup.WithLinks)) { var incommingLinks = CategoryLinks.Where(x => categoriesIds.Contains(x.TargetCategoryId)).ToArray(); var outgoingLinks = CategoryLinks.Where(x => categoriesIds.Contains(x.SourceCategoryId)).ToArray(); } if (categoryRespGroup.HasFlag(CategoryResponseGroup.WithImages)) { var images = Images.Where(x => categoriesIds.Contains(x.CategoryId)).ToArray(); } //Load all properties meta information and information for inheritance if (categoryRespGroup.HasFlag(CategoryResponseGroup.WithProperties)) { //Load category property values by separate query var propertyValues = PropertyValues.Where(x => categoriesIds.Contains(x.CategoryId)).ToArray(); var categoryPropertiesIds = Properties.Where(x => categoriesIds.Contains(x.CategoryId)).Select(x => x.Id).ToArray(); var categoryProperties = GetPropertiesByIds(categoryPropertiesIds); } return(result); }
public virtual async Task <CustomerOrder[]> GetByIdsAsync(string[] orderIds, string responseGroup = null) { var cacheKey = CacheKey.With(GetType(), nameof(GetByIdsAsync), string.Join("-", orderIds), responseGroup); return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) => { var retVal = new List <CustomerOrder>(); var orderResponseGroup = EnumUtility.SafeParseFlags(responseGroup, CustomerOrderResponseGroup.Full); using (var repository = _repositoryFactory()) { repository.DisableChangesTracking(); //It is so important to generate change tokens for all ids even for not existing objects to prevent an issue //with caching of empty results for non - existing objects that have the infinitive lifetime in the cache //and future unavailability to create objects with these ids. cacheEntry.AddExpirationToken(OrderCacheRegion.CreateChangeToken(orderIds)); var orderEntities = await repository.GetCustomerOrdersByIdsAsync(orderIds, responseGroup); foreach (var orderEntity in orderEntities) { var customerOrder = AbstractTypeFactory <CustomerOrder> .TryCreateInstance(); if (customerOrder != null) { customerOrder = orderEntity.ToModel(customerOrder) as CustomerOrder; //Calculate totals only for full responseGroup if (orderResponseGroup == CustomerOrderResponseGroup.Full) { _totalsCalculator.CalculateTotals(customerOrder); } await LoadOrderDependenciesAsync(customerOrder); customerOrder.ReduceDetails(responseGroup); retVal.Add(customerOrder); } } } return retVal.ToArray(); })); }
/// <summary> /// Query instruction /// </summary> public IncludeInstruction(String queryInstruction) { var parsed = queryInstruction.Split(':'); if (parsed.Length != 2) { var localizationService = ApplicationServiceContext.Current.GetService <ILocalizationService>(); var tracer = Tracer.GetTracer(typeof(ResourceHandlerBase <TFhirResource, TModel>)); tracer.TraceError($"{queryInstruction} is not a valid include instruction"); throw new ArgumentOutOfRangeException(localizationService.FormatString("error.type.InvalidDataException.userMessage", new { param = "include instruction" })); } this.Type = EnumUtility.ParseLiteral <ResourceType>(parsed[0]).Value; this.JoinPath = parsed[1]; }
public static T Offset <T>(this T @this, int offset) where T : struct, Enum { // needs newer .net to get 'unsafe' /*var index = Unsafe.As<T, int>(ref @this) + offset; * if (index < 0 || index >= EnumUtility.GetCount<T>()) * throw new ArgumentOutOfRangeException(nameof(offset)); * return Unsafe.As<int, T>(ref index);*/ var index = (int)(object)@this + offset; if (index < 0 || index >= EnumUtility.GetCount <T>()) { throw new ArgumentOutOfRangeException(nameof(offset)); } // ReSharper disable once PossibleInvalidCastException return((T)(object)index); }
/// <summary> /// Writes a shapefile header to the given stream; /// </summary> /// <param name="file">The binary writer to use.</param> public void Write(BigEndianBinaryWriter file) { if (file == null) { throw new ArgumentNullException("file"); } if (_fileLength == -1) { throw new InvalidOperationException("The header properties need to be set before writing the header record."); } var pos = 0; file.WriteIntBE(_fileCode); pos += 4; for (var i = 0; i < 5; i++) { file.WriteIntBE(0); //Skip unused part of header pos += 4; } file.WriteIntBE(_fileLength); pos += 4; file.Write(_version); pos += 4; var format = EnumUtility.Format(typeof(ShapeGeometryType), _shapeType, "d"); file.Write(int.Parse(format)); pos += 4; // Write the bounding box file.Write(_bounds.MinX); file.Write(_bounds.MinY); file.Write(_bounds.MaxX); file.Write(_bounds.MaxY); pos += 8 * 4; // Skip remaining unused bytes for (int i = 0; i < 4; i++) { file.Write(0.0); // Skip unused part of header pos += 8; } }
public static coreModel.PaymentIn ToCoreModel(this webModel.PaymentIn payment) { var retVal = new coreModel.PaymentIn(); retVal.InjectFrom(payment); retVal.PaymentStatus = EnumUtility.SafeParse <PaymentStatus>(payment.Status, PaymentStatus.Custom); retVal.Currency = payment.Currency; if (payment.DynamicProperties != null) { retVal.DynamicProperties = payment.DynamicProperties; } return(retVal); }
public ActionResult <SampleDataImportPushNotification> ImportSampleData([FromQuery] string url = null) { lock (_lockObject) { var sampleDataState = EnumUtility.SafeParse(_settingsManager.GetValue(PlatformConstants.Settings.Setup.SampleDataState.Name, SampleDataState.Undefined.ToString()), SampleDataState.Undefined); if (sampleDataState == SampleDataState.Undefined && Uri.IsWellFormedUriString(url, UriKind.Absolute)) { _settingsManager.SetValue(PlatformConstants.Settings.Setup.SampleDataState.Name, SampleDataState.Processing); var pushNotification = new SampleDataImportPushNotification(User.Identity.Name); _pushNotifier.Send(pushNotification); var jobId = BackgroundJob.Enqueue(() => SampleDataImportBackgroundAsync(new Uri(url), Path.GetFullPath(_platformOptions.LocalUploadFolderPath), pushNotification, JobCancellationToken.Null, null)); pushNotification.JobId = jobId; return(Ok(pushNotification)); } } return(Ok()); }