コード例 #1
0
        private List <QuizQuestionDto> MapJsonToQuizQuestions(JToken jArray)
        {
            List <QuizQuestionDto> questionDtoList = new List <QuizQuestionDto>();

            foreach (var token in jArray)
            {
                var questionDto = new QuizQuestionDto();

                var categoryString   = token.Value <string>("category");
                var typeString       = token.Value <string>("type");
                var difficultyString = token.Value <string>("difficulty");
                var wrongAnswers     = (token["incorrect_answers"] as JArray).ToObject <List <string> >();

                questionDto.Question         = HttpUtility.HtmlDecode(token.Value <string>("question"));
                questionDto.CorrectAnswer    = HttpUtility.HtmlDecode(token.Value <string>("correct_answer"));
                questionDto.IncorrectAnswers = wrongAnswers.Select(str => HttpUtility.HtmlDecode(str)).ToList();

                questionDto.Category   = EnumExtensionMethods.GetEnumValueFromDescription <Categories>(categoryString);
                questionDto.Type       = EnumExtensionMethods.GetEnumValueFromDescription <QuestionTypes>(typeString);
                questionDto.Difficulty = EnumExtensionMethods.GetEnumValueFromDescription <Difficulties>(difficultyString);

                questionDtoList.Add(questionDto);
            }

            return(questionDtoList);
        }
コード例 #2
0
        public FinalizeOrderDTO GetDataForFinalizeOrder(Guid userId)
        {
            var user  = this.context.Users.Include(x => x.CartItems).SingleOrDefault(x => x.Id == userId);
            var items = new List <Item>();

            user.CartItems.ForEach(x =>
            {
                items.Add(this.context.Items.SingleOrDefault(i => i.Id == x.ItemId));
            });

            int priceSum = 0;

            items.ForEach(x =>
            {
                priceSum += (x.DiscountedPrice != null ? x.DiscountedPrice.Value : x.OriginalPrice) * user.CartItems.Single(y => y.ItemId == x.Id).Quantity;
            });

            var dto = new FinalizeOrderDTO()
            {
                BillingData    = new UserBillingDataDTO(user),
                PaymentMethods = new List <string>()
                {
                    EnumExtensionMethods.GetDescription(PaymentMethod.AdvancePayment),
                    EnumExtensionMethods.GetDescription(PaymentMethod.OnlineCreditCard),
                    EnumExtensionMethods.GetDescription(PaymentMethod.WhenDelivered)
                },
                PriceSum = priceSum
            };

            return(dto);
        }
コード例 #3
0
        public async Task <IActionResult> OnPostNextAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }
            var wizardEvent = HttpContext.Session.GetJson <RideEvent>("WizardEvent");

            wizardEvent.MaxSignup     = EventWizard2.MaxSignup;
            wizardEvent.MaxSignUpType = EnumExtensionMethods.GetValueFromDescription <MaxSignUpType>(Input.SelectedMaxSignUpType);
            wizardEvent.Status        = EnumExtensionMethods.GetValueFromDescription <Status>(Input.SelectedStatus);
            HttpContext.Session.SetJson("WizardEvent", null);
            _context.RideEvent.Add(wizardEvent);
            foreach (var user in Input.SelectedUser)
            {
                // finds single selected user in list by full name
                // will change this so it searches by id instead
                var selectedUser = await _context.Users
                                   .AsNoTracking()
                                   .FirstOrDefaultAsync(m => m.FullName == user);

                RideLeaderAssignment RideLeaderAssignment = new RideLeaderAssignment
                {
                    InTandemUserID = selectedUser.Id,
                    RideEventID    = wizardEvent.ID
                };
                _context.RideLeaderAssignment.Add(RideLeaderAssignment);
            }
            await _context.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }
コード例 #4
0
ファイル: ItemService.cs プロジェクト: Wolvarr/WebShop
        public ItemFullViewDTO GetItemById(Guid id)
        {
            var similarItems = new List <ItemHeader>();

            var returnDto = new ItemFullViewDTO(this.context.Items
                                                .Include(x => x.Ratings)
                                                .Include(x => x.Comments).ThenInclude(c => c.User)
                                                .SingleOrDefault(x => x.Id == id));

            var temp = this.context.Items.Where(x => x.Category == EnumExtensionMethods.GetValueFromDescription <Category>(returnDto.Category)).Include(x => x.Ratings).Include(x => x.Comments).ToList();

            temp.ForEach(x =>
            {
                if (x.Id != id)
                {
                    similarItems.Add(new ItemHeader(x));
                }
            });

            returnDto.SimilarItems = new PagedResult <ItemHeader>
            {
                AllResultsCount = similarItems.Count <= 3 ? similarItems.Count : 3,
                Results         = similarItems.Count <= 3 ? similarItems : similarItems.Take(3).ToList(),
                PageNumber      = 0,
                PageSize        = 1
            };

            return(returnDto);
        }
コード例 #5
0
ファイル: ItemHeader.cs プロジェクト: Wolvarr/WebShop
 public ItemHeader(Item item)
 {
     this.Id               = item.Id.ToString();
     this.Name             = item.Name;
     this.Available        = item.Available;
     this.PicturePath      = item.PicturePath;
     this.OriginalPrice    = item.OriginalPrice;
     this.DiscountedPrice  = item.DiscountedPrice;
     this.AverageRating    = item.Ratings.Any() ? Convert.ToInt32(item.Ratings.Average(x => x.Value)) : 0;
     this.Manufacturer     = item.Manufacturer;
     this.ShortDescription = item.ShortDescription;
     this.Description      = item.Description;
     this.GamingFlag       = item.GamingFlag;
     this.IsUsed           = item.IsUsed;
     this.HasRGB           = item.HasRGB;
     this.Category         = EnumExtensionMethods.GetDescription(item.Category);
     if (item is Motherboard)
     {
         this.CpuSocket = (item as Motherboard).Socket;
     }
     if (item is Cpu)
     {
         this.CpuSocket = (item as Cpu).Socket;
     }
 }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var settings   = DependencyService.Get <IAppSettings>();
            var Controller = EnumExtensionMethods.GetEnumDescription(UserRole.Controller);
            var Admin      = EnumExtensionMethods.GetEnumDescription(UserRole.Admin);
            var SiteAdmin  = EnumExtensionMethods.GetEnumDescription(UserRole.SiteAdmin);


            ComplaintModel complaint = (ComplaintModel)value;

            if (complaint.ComplainStatus == (int)ComplaintStatusEnum.Pending || complaint.ComplainStatus == (int)ComplaintStatusEnum.Rejected)
            {
                if ((settings.UserRole.Equals(Controller) || settings.UserRole.Equals(Admin) || settings.UserRole.Equals(SiteAdmin)) && complaint.CreatedBy.Equals(settings.UserId))
                {
                    return(true);
                }
                else
                {
                    if (!settings.UserRole.Equals(Controller) || settings.UserRole.Equals(Admin) || settings.UserRole.Equals(SiteAdmin))
                    {
                        return(true);
                    }
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
コード例 #7
0
 public static IEnumerable <EnumResponseModel> GetEnums <T>()
 {
     return((Enum.GetValues(typeof(T)).Cast <T>().Select(
                 enu => new EnumResponseModel()
     {
         Name = enu.ToString(), Id = enu.To <int>(), Description = EnumExtensionMethods.GetEnumDescription <T>(enu.To <int>())
     })).ToList());
 }
コード例 #8
0
        public void CreateOrder(CreateOrderDTO orderDto)
        {
            var items = new List <OrderItem>();
            var user  = this.context.Users.Include(x => x.CartItems).SingleOrDefault(x => x.Id == orderDto.UserId);

            user.CartItems.ForEach(x =>
            {
                items.Add(new OrderItem()
                {
                    ItemId = x.ItemId
                });
            });

            if (orderDto.BillingAddres.Country == null)
            {
                orderDto.BillingAddres.Country = orderDto.ShippingAddres.Country;
            }

            if (orderDto.BillingAddres.ZipCode == null)
            {
                orderDto.BillingAddres.ZipCode = orderDto.ShippingAddres.ZipCode;
            }

            if (orderDto.BillingAddres.Street == null)
            {
                orderDto.BillingAddres.Street = orderDto.ShippingAddres.Street;
            }

            if (orderDto.BillingAddres.HouseNumberAndDoor == null)
            {
                orderDto.BillingAddres.HouseNumberAndDoor = orderDto.ShippingAddres.HouseNumberAndDoor;
            }

            var order = new Order()
            {
                UserId          = orderDto.UserId,
                OrderStatus     = Dal.Enums.OrderStatus.New,
                PaymentMethod   = EnumExtensionMethods.GetValueFromDescription <PaymentMethod>(orderDto.PaymentMethod),
                Items           = items,
                BillingAddress  = orderDto.BillingAddres,
                ShippingAddress = orderDto.ShippingAddres,
                OrderDate       = DateTime.Now,
                DeliveryDate    = null,
                Comment         = orderDto.Comment
            };

            this.context.Orders.Add(order);
            this.context.SaveChanges();

            order.Items.ForEach(x => x.OrderId = order.Id);
            user.CartItems.ForEach(x =>
            {
                context.UserCartItems.Remove(x);
            });
            this.context.SaveChanges();
        }
コード例 #9
0
        public bool IsSiteAdmin()
        {
            var Admin = EnumExtensionMethods.GetEnumDescription(UserRole.SiteAdmin);

            if (_settings.UserRole.Equals(Admin))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #10
0
        /// <summary>
        /// Gets the value of an enumeration option.
        /// </summary>
        /// <param name="enumerationType">The type of the enumeration.</param>
        /// <param name="value">The value to get from the enumeration.</param>
        /// <returns>The value of the option on the enumeration.</returns>
        public static object GetEnumerationValue(Type enumerationType, string value)
        {
            ExceptionUtilities.CheckArgumentNotNull(enumerationType, "enumerationType");
            ExceptionUtilities.CheckStringArgumentIsNotNullOrEmpty(value, "value");

            foreach (var enumValue in EnumExtensionMethods.GetValues(enumerationType))
            {
                if (enumValue.ToString() == value)
                {
                    return(enumValue);
                }
            }

            throw new ArgumentException(String.Format("Failed to find value '{0}' in enum type '{1}", value, enumerationType.Name));
        }
コード例 #11
0
        public bool IsController()
        {
            var Controller = EnumExtensionMethods.GetEnumDescription(UserRole.Controller);
            var Volunteer  = EnumExtensionMethods.GetEnumDescription(UserRole.Volunteer);
            var Admin      = EnumExtensionMethods.GetEnumDescription(UserRole.Admin);
            var SiteAdmin  = EnumExtensionMethods.GetEnumDescription(UserRole.SiteAdmin);

            if (_settings.UserRole.Equals(Controller) || _settings.UserRole.Equals(Admin) || _settings.UserRole.Equals(SiteAdmin))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #12
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var settings   = DependencyService.Get <IAppSettings>();
            var Controller = EnumExtensionMethods.GetEnumDescription(UserRole.Controller);
            var Admin      = EnumExtensionMethods.GetEnumDescription(UserRole.Admin);
            var SiteAdmin  = EnumExtensionMethods.GetEnumDescription(UserRole.SiteAdmin);

            ComplaintModel status = (ComplaintModel)value;

            if ((settings.UserRole.Equals(Controller) || settings.UserRole.Equals(Admin) || settings.UserRole.Equals(SiteAdmin)) && status.ComplainStatus != (int)ComplaintStatusEnum.Registered && status.IsEmailSend == false)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        } // OnGet

        public IActionResult OnPost()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }
            var wizardEvent = HttpContext.Session.GetJson <RideEvent>("WizardEvent");

            wizardEvent.EventName   = EventWizard1.EventName;
            wizardEvent.EventDate   = EventWizard1.EventDate;
            wizardEvent.Description = EventWizard1.Description;
            wizardEvent.Location    = EventWizard1.Location;
            wizardEvent.Distance    = EventWizard1.Distance;
            wizardEvent.EventType   = EnumExtensionMethods.GetValueFromDescription <EventType>(Input.SelectedEventType);
            HttpContext.Session.SetJson("WizardEvent", wizardEvent);


            return(RedirectToPage("./EventWizard2"));
        } //OnPost
コード例 #14
0
        /// <summary>
        /// Converts attribute value to value for Target Path for FeedMappingAnnotation
        /// </summary>
        /// <param name="attributeValue">attribute value to get the target path value from</param>
        /// <param name="feedMappingAnnotation">Feed Mapping Annotation</param>
        /// <returns>Target Path Value</returns>
        private string HandleTargetPath(string attributeValue, PropertyMappingAnnotation feedMappingAnnotation)
        {
            // The goal here is to return the Target Path Value expected by the test annotation. It uses the same values as
            // SyndicationItemProperty enumeration found in the Microsoft.OData.Service.Common.

            // if the attribute value in one of the Atom mapping we need to strip the "Syndication" from the beginning and parse it as enum.
            // if not it will be a custom property
            string value = attributeValue.Replace(ODataConstants.EpmAttributePrefix, null);

            Astoria.Contracts.SyndicationItemProperty targetValue;
            if (EnumExtensionMethods.TryParse <Astoria.Contracts.SyndicationItemProperty>(value, false, out targetValue))
            {
                feedMappingAnnotation.SyndicationItemProperty = targetValue;
                return(value);
            }
            else
            {
                feedMappingAnnotation.SyndicationItemProperty = Astoria.Contracts.SyndicationItemProperty.CustomProperty;
                return(attributeValue);
            }
        }
コード例 #15
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var settings   = DependencyService.Get <IAppSettings>();
            var Controller = EnumExtensionMethods.GetEnumDescription(UserRole.Controller);
            var Volunteer  = EnumExtensionMethods.GetEnumDescription(UserRole.Volunteer);
            var Admin      = EnumExtensionMethods.GetEnumDescription(UserRole.Admin);

            switch ((int)value)
            {
            case (int)ComplaintStatusEnum.Registered:
            {
                return(false);
            }

            case (int)ComplaintStatusEnum.Rejected:
            {
                return(true);
            }

            case (int)ComplaintStatusEnum.Verified:
            {
                if (settings.UserRole.Equals(Controller) || settings.UserRole.Equals(Admin))
                {
                    return(false);
                }
                return("Register");
            }

            case (int)ComplaintStatusEnum.Pending:
            default:

            {
                return(true);
            }
            }
        }
        public async Task SetComplaintOverviewData()
        {
            try
            {
                List <LowsModel> listLows = new List <LowsModel>();
                listLows = await _complaintService.GetAllLows(_settings.UserId, _settings.UserCityId);

                RejectTextArea    = ComplaintModelObj.CommentForRejection;
                Complaint         = _complaintService.GetNonComplaint();
                IsBusy            = true;
                ComplaintModelObj = await _complaintService.GetNonComplaintModel();

                var Controller = EnumExtensionMethods.GetEnumDescription(UserRole.Controller);
                var Admin      = EnumExtensionMethods.GetEnumDescription(UserRole.Admin);

                if (ComplaintModelObj != null)
                {
                    if (!string.IsNullOrEmpty(ComplaintModelObj.LowsId))
                    {
                        List <int> SplitLows = new List <int>();
                        SplitLows = ComplaintModelObj.LowsId.Split(',')?.Select(Int32.Parse).ToList();
                        int i = 1;
                        foreach (var item in listLows)
                        {
                            if (SplitLows.AnyExtended())
                            {
                                if (SplitLows.Contains(item.ExternalId))
                                {
                                    item.LowsTitile = item.LowsTitile;
                                    item.NumberText = Convert.ToString(i);
                                    LowsList.Add(item);
                                    i++;
                                }
                            }
                        }
                    }

                    ComplaintImagesDTOs = new ObservableCollection <ComplaintImagesDTO>();
                    if (!string.IsNullOrEmpty(ComplaintModelObj.Files))
                    {
                        List <string> SplitFilePaths = new List <string>();

                        SplitFilePaths = ComplaintModelObj.Files.Split(',')?.ToList();
                        if (SplitFilePaths.AnyExtended())
                        {
                            foreach (var item in SplitFilePaths)
                            {
                                ComplaintImagesDTOs.Add(new ComplaintImagesDTO()
                                {
                                    ComplaintId = 0,
                                    FileType    = "Image",
                                    FileImage   = item
                                });
                            }
                            CheckHashFile();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
コード例 #17
0
        public void CollectionWriterStatesTest()
        {
            var testCases = new CollectionWriterStatesTestDescriptor[]
            {
                new CollectionWriterStatesTestDescriptor {
                    DebugDescription = "Start",
                    Setup            = null,
                    ExpectedResults  = new Dictionary <CollectionWriterAction, string> {
                        { CollectionWriterAction.Start, null },
                        { CollectionWriterAction.Item, "Cannot transition from state 'Start' to state 'Item'. The only valid actions in state 'Start' are to write the collection or to write nothing at all." },
                        { CollectionWriterAction.End, "ODataCollectionWriter.WriteEnd was called in an invalid state ('Start'); WriteEnd is only supported in states 'Start', 'Collection', and 'Item'." },
                        { CollectionWriterAction.Error, null },
                    }
                },
                new CollectionWriterStatesTestDescriptor {
                    DebugDescription = "Collection",
                    Setup            = (mw, w, s) => {
                        w.WriteStart(new ODataCollectionStart {
                            Name = "foo"
                        });
                    },
                    ExpectedResults = new Dictionary <CollectionWriterAction, string> {
                        { CollectionWriterAction.Start, "Cannot transition from state 'Collection' to state 'Collection'. The only valid actions in state 'Collection' are to write an item or to write the end of the collection." },
                        { CollectionWriterAction.Item, null },
                        { CollectionWriterAction.End, null },
                        { CollectionWriterAction.Error, null },
                    }
                },
                new CollectionWriterStatesTestDescriptor {
                    DebugDescription = "Item",
                    Setup            = (mw, w, s) => {
                        w.WriteStart(new ODataCollectionStart {
                            Name = "foo"
                        });
                        w.WriteItem(42);
                    },
                    ExpectedResults = new Dictionary <CollectionWriterAction, string> {
                        { CollectionWriterAction.Start, "Cannot transition from state 'Item' to state 'Collection'. The only valid actions in state 'Item' are to write an item or the end of the collection." },
                        { CollectionWriterAction.Item, null },
                        { CollectionWriterAction.End, null },
                        { CollectionWriterAction.Error, null },
                    }
                },
                new CollectionWriterStatesTestDescriptor {
                    DebugDescription = "Completed",
                    Setup            = (mw, w, s) => {
                        w.WriteStart(new ODataCollectionStart {
                            Name = "foo"
                        });
                        w.WriteEnd();
                    },
                    ExpectedResults = new Dictionary <CollectionWriterAction, string> {
                        { CollectionWriterAction.Start, "Cannot transition from state 'Completed' to state 'Collection'. Nothing further can be written once the writer has completed." },
                        { CollectionWriterAction.Item, "Cannot transition from state 'Completed' to state 'Item'. Nothing further can be written once the writer has completed." },
                        { CollectionWriterAction.End, "ODataCollectionWriter.WriteEnd was called in an invalid state ('Completed'); WriteEnd is only supported in states 'Start', 'Collection', and 'Item'." },
                        { CollectionWriterAction.Error, "Cannot transition from state 'Completed' to state 'Error'. Nothing further can be written once the writer has completed." },
                    }
                },
                new CollectionWriterStatesTestDescriptor {
                    DebugDescription = "ODataExceptionThrown",
                    Setup            = (mw, w, s) => {
                        TestExceptionUtils.RunCatching(() => w.WriteItem(42));
                    },
                    ExpectedResults = new Dictionary <CollectionWriterAction, string> {
                        { CollectionWriterAction.Start, "Cannot transition from state 'Error' to state 'Collection'. Nothing can be written once the writer entered the error state." },
                        { CollectionWriterAction.Item, "Cannot transition from state 'Error' to state 'Item'. Nothing can be written once the writer entered the error state." },
                        { CollectionWriterAction.End, "ODataCollectionWriter.WriteEnd was called in an invalid state ('Error'); WriteEnd is only supported in states 'Start', 'Collection', and 'Item'." },
                        { CollectionWriterAction.Error, null },
                    }
                },
                new CollectionWriterStatesTestDescriptor {
                    DebugDescription = "FatalExceptionThrown",
                    Setup            = (mw, w, s) => {
                        // In JSON we can make the stream fail
                        s.FailNextCall = true;
                        w.WriteStart(new ODataCollectionStart {
                            Name = "foo"
                        });
                        TestExceptionUtils.RunCatching(() => w.Flush());
                    },
                    ExpectedResults = new Dictionary <CollectionWriterAction, string> {
                        { CollectionWriterAction.Start, "Cannot transition from state 'Error' to state 'Collection'. Nothing can be written once the writer entered the error state." },
                        { CollectionWriterAction.Item, "Cannot transition from state 'Error' to state 'Item'. Nothing can be written once the writer entered the error state." },
                        { CollectionWriterAction.End, "ODataCollectionWriter.WriteEnd was called in an invalid state ('Error'); WriteEnd is only supported in states 'Start', 'Collection', and 'Item'." },
                        { CollectionWriterAction.Error, null },
                    },
                    // There's no simple way to make the writer go into a fatal exception state with XmlWriter underneath.
                    // XmlWriter will move to an Error state if anything goes wrong with it, and thus we can't write into it anymore.
                    // As a result for example the in-stream error case for this one can't work as it should.
                    SkipForConfiguration = (tc) => tc.Format != ODataFormat.Json
                },
                new CollectionWriterStatesTestDescriptor {
                    DebugDescription = "Error",
                    Setup            = (mw, w, s) => {
                        mw.WriteError(new ODataError(), false);
                    },
                    ExpectedResults = new Dictionary <CollectionWriterAction, string> {
                        { CollectionWriterAction.Start, "Cannot transition from state 'Error' to state 'Collection'. Nothing can be written once the writer entered the error state." },
                        { CollectionWriterAction.Item, "Cannot transition from state 'Error' to state 'Item'. Nothing can be written once the writer entered the error state." },
                        { CollectionWriterAction.End, "ODataCollectionWriter.WriteEnd was called in an invalid state ('Error'); WriteEnd is only supported in states 'Start', 'Collection', and 'Item'." },
                        { CollectionWriterAction.Error, "The WriteError method or the WriteErrorAsync method on the ODataMessageWriter has already been called to write an error payload. Only a single error payload can be written with each ODataMessageWriter instance." },
                    }
                },
            };

            //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                EnumExtensionMethods.GetValues <CollectionWriterAction>().Cast <CollectionWriterAction>(),
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => false),
                (testCase, writerAction, testConfiguration) =>
            {
                using (TestStream stream = new TestStream())
                {
                    if (testCase.SkipForConfiguration != null && testCase.SkipForConfiguration(testConfiguration))
                    {
                        return;
                    }

                    // We purposely don't use the using pattern around the messageWriter here. Disposing the message writer will
                    // fail here because the writer is not left in a valid state.
                    var messageWriter            = TestWriterUtils.CreateMessageWriter(stream, testConfiguration, this.Assert);
                    ODataCollectionWriter writer = messageWriter.CreateODataCollectionWriter();
                    if (testCase.Setup != null)
                    {
                        testCase.Setup(messageWriter, writer, stream);
                    }

                    string expectedException = testCase.ExpectedResults[writerAction];

                    this.Assert.ExpectedException <ODataException>(
                        () => InvokeCollectionWriterAction(messageWriter, writer, writerAction),
                        expectedException);
                }
            });
        }
コード例 #18
0
ファイル: ItemFullViewDTO.cs プロジェクト: Wolvarr/WebShop
        public SpecificProperties(Item item)
        {
            if (item is Case)
            {
                Case pcCase = item as Case;
                this.BuiltInFanNumber     = pcCase.BuiltInFanNumber;
                this.SupportedMotherboard = EnumExtensionMethods.GetDescription(pcCase.SupportedMotherboard);
                this.Height    = pcCase.Height;
                this.Width     = pcCase.Width;
                this.Depth     = pcCase.Depth;
                this.HDDNumber = pcCase.HDDNumber;
            }

            if (item is Cpu)
            {
                Cpu cpu = item as Cpu;
                this.ProcessorFamily = cpu.ProcessorFamily;
                this.Technology      = cpu.Technology;
                this.CoreNumber      = cpu.CoreNumber;
                this.ThreadNumber    = cpu.ThreadNumber;
                this.Socket          = Socket;
                this.BaseClock       = cpu.BaseClock;
                this.TDP             = cpu.TDP;
            }

            if (item is GraphicsCard)
            {
                GraphicsCard gpu = item as GraphicsCard;
                this.BuiltInMemory         = gpu.BuiltInMemory;
                this.MemoryClock           = gpu.MemoryClock;
                this.BandWidth             = gpu.BandWidth;
                this.CoolerType            = gpu.CoolerType;
                this.MemoryType            = MemoryType;
                this.PowerSupplyConnection = gpu.PowerSupplyConnection;
                this.BaseClock             = gpu.BaseClock;
                this.TDP = gpu.TDP;
            }

            if (item is HardDrive)
            {
                HardDrive drive = item as HardDrive;
                this.Size        = drive.Size;
                this.ReadSpeed   = drive.ReadSpeed;
                this.WriteSpeed  = drive.WriteSpeed;
                this.Weight      = drive.Weight;
                this.DriveSocket = drive.Socket;
            }

            if (item is Memory)
            {
                Memory mem = item as Memory;
                this.BaseClock = mem.BaseClock;
                this.Capacity  = mem.Capacity;
                this.MemoryTypeForMmoryCard = mem.MemoryType;
                this.Timing = mem.Timing;
                this.Kit    = mem.Kit;
            }

            if (item is Motherboard)
            {
                Motherboard board = item as Motherboard;
                this.Type    = board.Type;
                this.Chipset = board.Chipset;
                this.CpuSocketForMotherboard = board.Socket;
                this.SupportedMemoryType     = board.SupportedMemoryType;
                this.SupportedMemorySpeed    = board.SupportedMemorySpeed;
                this.MemorySocketNumber      = board.MemorySocketNumber;
            }

            if (item is PowerSupply)
            {
                PowerSupply psu = item as PowerSupply;
                this.ATXConnector        = psu.ATXConnector;
                this.MolexConnector      = psu.MolexConnector;
                this.SixPinConnector     = psu.SixPinConnector;
                this.SixPlusTwoConnector = psu.SixPlusTwoConnector;
                this.Efficiency          = psu.Efficiency;
                this.IsModular           = psu.IsModular;
            }
            if (item is CompletPC)
            {
                CompletPC pc = item as CompletPC;
                this.Case        = pc.Case;
                this.Motherboard = pc.Motherboard;
                this.Cpu         = pc.Cpu;
                this.Gpu         = pc.Gpu;
                this.Memories    = pc.Memories;
                this.Drives      = pc.Drives;
                this.PowerSupply = pc.PowerSupply;
            }
        }
コード例 #19
0
 public IActionResult GetTenderStatuses()
 {
     return(Ok(EnumExtensionMethods.GetValues <TenderStatus>()));
 }
コード例 #20
0
ファイル: ItemService.cs プロジェクト: Wolvarr/WebShop
        public PagedResult <ItemHeader> GetAllItems(ItemSpecification specification = null)
        {
            if (specification == null)
            {
                specification = new ItemSpecification();
            }

            if (specification.PageSize < 0)
            {
                specification.PageSize = null;
            }
            if (specification.PageNumber < 0)
            {
                specification.PageNumber = null;
            }

            IQueryable <Item> query = this.context.Items
                                      .Include(x => x.Ratings);

            if (!string.IsNullOrWhiteSpace(specification.ComplexFilter))
            {
                query = query.Where(x => x.Name.Contains(specification.ComplexFilter) ||
                                    x.Manufacturer.Contains(specification.ComplexFilter) ||
                                    x.ShortDescription.Contains(specification.ComplexFilter));
            }

            if (!string.IsNullOrWhiteSpace(specification.Name))
            {
                query = query.Where(x => x.Name.Contains(specification.Name));
            }

            if (specification.SelectedCategories.Any())
            {
                var selectedCategoriesEnum = new List <Category>();
                specification.SelectedCategories.ForEach(x =>
                {
                    selectedCategoriesEnum.Add(EnumExtensionMethods.GetValueFromDescription <Category>(x));
                });
                query = query.Where(x => selectedCategoriesEnum.Contains(x.Category));
            }

            if (specification.SelectedManufacturers.Any())
            {
                query = query.Where(x => specification.SelectedManufacturers.Contains(x.Manufacturer));
            }

            if (specification.HasRGB.HasValue)
            {
                query = query.Where(x => x.HasRGB == specification.HasRGB);
            }

            if (specification.IsNewArrival.HasValue)
            {
                query = query.Where(x => x.DateSinceInStore > DateTime.Now.AddDays(-30));
            }

            if (specification.IsDiscounted.HasValue)
            {
                query = query.Where(x => x.DiscountedPrice != null && x.DiscountedPrice < x.OriginalPrice);
            }

            if (specification.IsGaming.HasValue)
            {
                query = query.Where(x => x.GamingFlag == specification.IsGaming);
            }

            if (specification.IsUsed.HasValue)
            {
                query = query.Where(x => x.IsUsed == specification.IsUsed);
            }

            if (specification.MinPrice != null)
            {
                query = query.Where(x => (x.DiscountedPrice ?? x.OriginalPrice) >= specification.MinPrice);
            }

            if (specification.MaxPrice != null)
            {
                query = query.Where(x => (x.DiscountedPrice ?? x.OriginalPrice) <= specification.MaxPrice);
            }

            if (specification.MinRating != null)
            {
                query = query.Where(x => (x.Ratings.Any() ? Convert.ToInt32(x.Ratings.Average(y => y.Value)) : 0) >= specification.MinRating);
            }

            if (specification.MaxRating != null)
            {
                query = query.Where(x => (x.Ratings.Any() ? Convert.ToInt32(x.Ratings.Average(y => y.Value)) : 0) <= specification.MaxRating);
            }

            //order
            switch (specification.Order)
            {
            case ItemSpecification.ItemOrder.PriceAscending:
                query = query.OrderBy(x => x.DiscountedPrice ?? x.OriginalPrice);
                break;

            case ItemSpecification.ItemOrder.PriceDescending:
                query = query.OrderByDescending(x => x.DiscountedPrice ?? x.OriginalPrice);
                break;

            case ItemSpecification.ItemOrder.RatingAscending:
                query = query.OrderBy(x => (x.Ratings.Any() ? Convert.ToInt32(x.Ratings.Average(y => y.Value)) : 0));
                break;

            case ItemSpecification.ItemOrder.RatingDescending:
                query = query.OrderByDescending(x => (x.Ratings.Any() ? Convert.ToInt32(x.Ratings.Average(y => y.Value)) : 0));
                break;
            }

            int?allResultsCount = null;

            if ((specification.PageSize ?? 0) != 0)
            {
                specification.PageNumber ??= 0;
                allResultsCount = query.Count();
                query           = query
                                  .Skip(specification.PageNumber.Value * specification.PageSize.Value)
                                  .Take(specification.PageSize.Value);
            }

            int totalMaxPrice, totalMinPrice;
            var maxDiscounted = context.Items.Max(x => x.DiscountedPrice);
            var maxOriginal   = context.Items.Max(x => x.OriginalPrice);
            var minDiscounted = context.Items.Min(x => x.DiscountedPrice);
            var minOriginal   = context.Items.Min(x => x.OriginalPrice);

            if (maxDiscounted != null)
            {
                totalMaxPrice = maxOriginal > maxDiscounted ? maxOriginal : maxDiscounted.Value;
                totalMinPrice = maxOriginal > maxDiscounted ? minOriginal : minDiscounted.Value;
            }
            else
            {
                totalMaxPrice = maxOriginal;
                totalMinPrice = minOriginal;
            }

            return(new PagedResult <ItemHeader>
            {
                AllResultsCount = allResultsCount,
                Results = query.ToList().Select(ItemHeaderSelectorFunc.Value),
                Categories = context.Items.Select(x => EnumExtensionMethods.GetDescription(x.Category)).Distinct().ToList(),
                Manufacturers = context.Items.Select(x => x.Manufacturer).Distinct().ToList(),
                TotalMaxPrice = totalMaxPrice,
                TotalMinPrice = totalMinPrice,
                PageNumber = specification.PageNumber,
                PageSize = specification.PageSize,
                Specification = specification,
            });
        }
コード例 #21
0
ファイル: ItemService.cs プロジェクト: Wolvarr/WebShop
        public void CreateItem(CreateItemDTO item)
        {
            switch (EnumExtensionMethods.GetValueFromDescription <Category>(item.Category))
            {
            case Category.Cpu:
            {
                var cpu = new Cpu()
                {
                    Name             = item.Name,
                    Category         = Category.Cpu,
                    Available        = 20,
                    PicturePath      = item.PicturePath,
                    OriginalPrice    = item.OriginalPrice,
                    DiscountedPrice  = item.DiscountedPrice,
                    Manufacturer     = item.Manufacturer,
                    ShortDescription = item.ShortDescription,
                    Description      = item.Description,
                    Warranty         = item.Warranty,
                    GamingFlag       = item.GamingFlag,
                    IsUsed           = item.IsUsed,
                    HasRGB           = item.HasRGB,
                    DateSinceInStore = DateTime.Now,

                    BaseClock       = item.BaseClock.Value,
                    TDP             = item.TDP.Value,
                    ProcessorFamily = item.ProcessorFamily,
                    Technology      = item.Technology == null ? 0 : item.Technology.Value,
                    CoreNumber      = item.CoreNumber == null ? 0 : item.CoreNumber.Value,
                    ThreadNumber    = item.ThreadNumber == null ? 0 : item.ThreadNumber.Value,
                    Socket          = item.Socket
                };

                this.context.Items.Add(cpu);
                break;
            }

            case Category.Case:
            {
                var pcCase = new Case()
                {
                    Name             = item.Name,
                    Category         = Category.Cpu,
                    Available        = 20,
                    PicturePath      = item.PicturePath,
                    OriginalPrice    = item.OriginalPrice,
                    DiscountedPrice  = item.DiscountedPrice,
                    Manufacturer     = item.Manufacturer,
                    ShortDescription = item.ShortDescription,
                    Description      = item.Description,
                    Warranty         = item.Warranty,
                    GamingFlag       = item.GamingFlag,
                    IsUsed           = item.IsUsed,
                    HasRGB           = item.HasRGB,
                    DateSinceInStore = DateTime.Now,

                    BuiltInFanNumber     = item.BuiltInFanNumber == null ? 0 : item.BuiltInFanNumber.Value,
                    SupportedMotherboard = item.SupportedMotherboard,
                    Height    = item.Height == null ? 0 : item.Height.Value,
                    Width     = item.Width == null ? 0 : item.Width.Value,
                    Depth     = item.Depth == null ? 0 : item.Depth.Value,
                    HDDNumber = item.HDDNumber == null ? 0 : item.HDDNumber.Value,
                };

                this.context.Items.Add(pcCase);
                break;
            }
                //TODO: case for all types
            }
            context.SaveChanges();
        }
コード例 #22
0
        public void BatchWriterStatesTest()
        {
            var testCases = new BatchWriterStatesTestDescriptor[]
            {
                // Start
                new BatchWriterStatesTestDescriptor {
                    Setup           = null,
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, null },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromStart") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromStart") },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteChangeSetWithoutActiveChangeSet") },
                        { BatchWriterAction.Operation, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromStart") },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },

                // BatchStarted
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        return(null);
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromBatchStarted") },
                        { BatchWriterAction.EndBatch, null },
                        { BatchWriterAction.StartChangeset, null },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteChangeSetWithoutActiveChangeSet") },
                        { BatchWriterAction.Operation, null },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },

                // ChangeSetStarted
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        w.WriteStartChangeset();
                        return(null);
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromChangeSetStarted") },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteBatchWithActiveChangeSet") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotStartChangeSetWithActiveChangeSet") },
                        { BatchWriterAction.EndChangeset, null },
                        { BatchWriterAction.Operation, null },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = false
                },

                // OperationCreated - Read
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        if (tc.IsRequest)
                        {
                            return(new BatchWriterStatesTestSetupResult {
                                Message = w.CreateOperationRequestMessage("GET", new Uri("http://odata.org"))
                            });
                        }
                        else
                        {
                            return(new BatchWriterStatesTestSetupResult {
                                Message = w.CreateOperationResponseMessage()
                            });
                        }
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationCreated") },
                        { BatchWriterAction.EndBatch, null },
                        { BatchWriterAction.StartChangeset, null },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteChangeSetWithoutActiveChangeSet") },
                        { BatchWriterAction.Operation, null },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },

                // OperationStreamRequested - Read
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        if (tc.IsRequest)
                        {
                            return(GetOperationStream(w.CreateOperationRequestMessage("GET", new Uri("http://odata.org")), tc));
                        }
                        else
                        {
                            return(GetOperationStream(w.CreateOperationResponseMessage(), tc));
                        }
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.Operation, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.GetOperationStream, ODataExpectedExceptions.ODataException("ODataBatchOperationMessage_VerifyNotCompleted") },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },

                // OperationStreamDisposed - Read
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        BatchWriterStatesTestSetupResult result;
                        if (tc.IsRequest)
                        {
                            result = GetOperationStream(w.CreateOperationRequestMessage("GET", new Uri("http://odata.org")), tc);
                        }
                        else
                        {
                            result = GetOperationStream(w.CreateOperationResponseMessage(), tc);
                        }

                        result.MessageStream.Dispose();
                        return(result);
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamDisposed") },
                        { BatchWriterAction.EndBatch, null },
                        { BatchWriterAction.StartChangeset, null },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteChangeSetWithoutActiveChangeSet") },
                        { BatchWriterAction.Operation, null },
                        { BatchWriterAction.GetOperationStream, ODataExpectedExceptions.ODataException("ODataBatchOperationMessage_VerifyNotCompleted") },
                        // Calling IDisposable.Dispose  should not throw.
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },

                // OperationCreated - Update
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        w.WriteStartChangeset();
                        if (tc.IsRequest)
                        {
                            return(new BatchWriterStatesTestSetupResult {
                                Message = w.CreateOperationRequestMessage("POST", new Uri("http://odata.org"), "1")
                            });
                        }
                        else
                        {
                            return(new BatchWriterStatesTestSetupResult {
                                Message = w.CreateOperationResponseMessage()
                            });
                        }
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationCreated") },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteBatchWithActiveChangeSet") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotStartChangeSetWithActiveChangeSet") },
                        { BatchWriterAction.EndChangeset, null },
                        { BatchWriterAction.Operation, null },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = false
                },

                // OperationStreamRequested - Update
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        w.WriteStartChangeset();
                        if (tc.IsRequest)
                        {
                            return(GetOperationStream(w.CreateOperationRequestMessage("POST", new Uri("http://odata.org"), "2"), tc));
                        }
                        else
                        {
                            return(GetOperationStream(w.CreateOperationResponseMessage(), tc));
                        }
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.Operation, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.GetOperationStream, ODataExpectedExceptions.ODataException("ODataBatchOperationMessage_VerifyNotCompleted") },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = false
                },

                // OperationStreamDisposed - Update
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        w.WriteStartChangeset();
                        BatchWriterStatesTestSetupResult result;
                        if (tc.IsRequest)
                        {
                            result = GetOperationStream(w.CreateOperationRequestMessage("POST", new Uri("http://odata.org"), "3"), tc);
                        }
                        else
                        {
                            result = GetOperationStream(w.CreateOperationResponseMessage(), tc);
                        }

                        result.MessageStream.Dispose();
                        return(result);
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamDisposed") },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteBatchWithActiveChangeSet") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotStartChangeSetWithActiveChangeSet") },
                        { BatchWriterAction.EndChangeset, null },
                        { BatchWriterAction.Operation, null },
                        { BatchWriterAction.GetOperationStream, ODataExpectedExceptions.ODataException("ODataBatchOperationMessage_VerifyNotCompleted") },
                        // Calling IDisposable.Dispose  should not throw.
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = false
                },

                // ChangeSetCompleted
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        w.WriteStartChangeset();
                        w.WriteEndChangeset();
                        return(null);
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromChangeSetCompleted") },
                        { BatchWriterAction.EndBatch, null },
                        { BatchWriterAction.StartChangeset, null },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteChangeSetWithoutActiveChangeSet") },
                        { BatchWriterAction.Operation, null },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },

                // BatchCompleted
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        w.WriteEndBatch();
                        return(null);
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromBatchCompleted") },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromBatchCompleted") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromBatchCompleted") },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteChangeSetWithoutActiveChangeSet") },
                        { BatchWriterAction.Operation, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromBatchCompleted") },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },

                // FatalExceptionThrown
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        s.FailNextCall = true;
                        w.WriteStartBatch();
                        if (tc.IsRequest)
                        {
                            w.CreateOperationRequestMessage("GET", new Uri("http://odata.org"));
                        }
                        else
                        {
                            w.CreateOperationResponseMessage();
                        }
                        TestExceptionUtils.RunCatching(() => w.Flush());
                        return(null);
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "BatchStarted") },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "BatchCompleted") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "ChangeSetStarted") },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteChangeSetWithoutActiveChangeSet") },
                        { BatchWriterAction.Operation, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "OperationCreated") },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                EnumExtensionMethods.GetValues <BatchWriterAction>().Cast <BatchWriterAction>(),
                this.WriterTestConfigurationProvider.DefaultFormatConfigurations,
                (testCase, writerAction, testConfiguration) =>
            {
                using (TestStream stream = new TestStream())
                {
                    // We purposely don't use the using pattern around the messageWriter here. Disposing the message writer will
                    // fail here because the writer is not left in a valid state.
                    var messageWriter = TestWriterUtils.CreateMessageWriter(stream, testConfiguration, this.Assert);
                    ODataBatchWriterTestWrapper writer           = messageWriter.CreateODataBatchWriter();
                    BatchWriterStatesTestSetupResult setupResult = null;
                    if (testCase.Setup != null)
                    {
                        setupResult = testCase.Setup(writer, stream, testConfiguration);
                    }

                    ExpectedException expectedException = testCase.ExpectedResults[writerAction];

                    TestExceptionUtils.ExpectedException(
                        this.Assert,
                        () => InvokeBatchWriterAction(writer, writerAction, testConfiguration, testCase.ReadOperationReady, setupResult),
                        expectedException,
                        this.ExceptionVerifier);
                }
            });
        }
コード例 #23
0
        private void WriterStatesTestImplementation(bool feedWriter)
        {
            var testCases = new WriterStatesTestDescriptor[]
            {
                // Start
                new WriterStatesTestDescriptor {
                    Setup           = null,
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, feedWriter ? ODataExpectedExceptions.ODataException("ODataWriterCore_CannotWriteTopLevelResourceWithResourceSetWriter") : (ExpectedException)null },
                        { WriterAction.StartFeed, feedWriter ? (ExpectedException)null : ODataExpectedExceptions.ODataException("ODataWriterCore_CannotWriteTopLevelResourceSetWithResourceWriter") },
                        { WriterAction.StartLink, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromStart", "Start", "NavigationLink") },
                        { WriterAction.End, ODataExpectedExceptions.ODataException("ODataWriterCore_WriteEndCalledInInvalidState", "Start") },
                        { WriterAction.Error, null },
                    }
                },

                // Entry
                new WriterStatesTestDescriptor {
                    Setup = (mw, w, s) => {
                        if (feedWriter)
                        {
                            w.WriteStart(ObjectModelUtils.CreateDefaultFeed());
                        }
                        w.WriteStart(ObjectModelUtils.CreateDefaultEntry());
                    },
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromResource", "Entry", "Entry") },
                        { WriterAction.StartFeed, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromResource", "Entry", "Feed") },
                        { WriterAction.StartLink, null },
                        { WriterAction.End, null },
                        { WriterAction.Error, null },
                    }
                },

                // Feed
                new WriterStatesTestDescriptor {
                    Setup = (mw, w, s) => {
                        if (feedWriter)
                        {
                            w.WriteStart(ObjectModelUtils.CreateDefaultFeed());
                        }
                        else
                        {
                            w.WriteStart(ObjectModelUtils.CreateDefaultEntry()); w.WriteStart(ObjectModelUtils.CreateDefaultCollectionLink()); w.WriteStart(ObjectModelUtils.CreateDefaultFeed());
                        }
                    },
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, null },
                        { WriterAction.StartFeed, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromResourceSet", "Feed", "Feed") },
                        { WriterAction.StartLink, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromResourceSet", "Feed", "NavigationLink") },
                        { WriterAction.End, null },
                        { WriterAction.Error, null },
                    }
                },

                // Link - single
                new WriterStatesTestDescriptor {
                    Setup = (mw, w, s) => {
                        if (feedWriter)
                        {
                            w.WriteStart(ObjectModelUtils.CreateDefaultFeed());
                        }
                        w.WriteStart(ObjectModelUtils.CreateDefaultEntry());
                        w.WriteStart(new ODataNestedResourceInfo {
                            Name = ObjectModelUtils.DefaultLinkName, Url = ObjectModelUtils.DefaultLinkUrl, IsCollection = false
                        });
                    },
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, null },
                        { WriterAction.StartFeed, ODataExpectedExceptions.ODataException("WriterValidationUtils_ExpandedLinkIsCollectionFalseWithResourceSetContent", "http://odata.org/link") },
                        { WriterAction.StartLink, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidStateTransition", "NavigationLink", "NavigationLink") },
                        { WriterAction.End, null },
                        { WriterAction.Error, null },
                    },
                    SkipForTestConfiguration = tc => tc.IsRequest
                },

                // Link - collection
                new WriterStatesTestDescriptor {
                    Setup = (mw, w, s) => {
                        if (feedWriter)
                        {
                            w.WriteStart(ObjectModelUtils.CreateDefaultFeed());
                        }
                        w.WriteStart(ObjectModelUtils.CreateDefaultEntry());
                        w.WriteStart(ObjectModelUtils.CreateDefaultCollectionLink());
                    },
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, ODataExpectedExceptions.ODataException("WriterValidationUtils_ExpandedLinkIsCollectionTrueWithResourceContent", "http://odata.org/link") },
                        { WriterAction.StartFeed, null },
                        { WriterAction.StartLink, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidStateTransition", "NavigationLink", "NavigationLink") },
                        { WriterAction.End, null },
                        { WriterAction.Error, null },
                    },
                    SkipForTestConfiguration = tc => tc.IsRequest
                },

                // Expanded link - there's no way to get to the expanded link state alone since the writer will always
                //   immediately transition to either entry or feed state instead.

                // Completed
                new WriterStatesTestDescriptor {
                    Setup = (mw, w, s) => {
                        if (feedWriter)
                        {
                            w.WriteStart(ObjectModelUtils.CreateDefaultFeed()); w.WriteEnd();
                        }
                        else
                        {
                            w.WriteStart(ObjectModelUtils.CreateDefaultEntry()); w.WriteEnd();
                        }
                    },
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromCompleted", "Completed", "Entry") },
                        { WriterAction.StartFeed, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromCompleted", "Completed", "Feed") },
                        { WriterAction.StartLink, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromCompleted", "Completed", "NavigationLink") },
                        { WriterAction.End, ODataExpectedExceptions.ODataException("ODataWriterCore_WriteEndCalledInInvalidState", "Completed") },
                        { WriterAction.Error, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromCompleted", "Completed", "Error") },
                    }
                },

                // ODataExceptionThrown
                new WriterStatesTestDescriptor {
                    Setup = (mw, w, s) => {
                        TestExceptionUtils.RunCatching(() => w.WriteStart(ObjectModelUtils.CreateDefaultCollectionLink()));
                    },
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "Entry") },
                        { WriterAction.StartFeed, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "Feed") },
                        { WriterAction.StartLink, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "NavigationLink") },
                        { WriterAction.End, ODataExpectedExceptions.ODataException("ODataWriterCore_WriteEndCalledInInvalidState", "Error") },
                        { WriterAction.Error, null },
                    },
                    SkipForTestConfiguration = tc => tc.IsRequest,
                },

                // Error
                new WriterStatesTestDescriptor {
                    Setup = (mw, w, s) => {
                        mw.WriteError(new ODataError(), false);
                    },
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "Entry") },
                        { WriterAction.StartFeed, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "Feed") },
                        { WriterAction.StartLink, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "NavigationLink") },
                        { WriterAction.End, ODataExpectedExceptions.ODataException("ODataWriterCore_WriteEndCalledInInvalidState", "Error") },
                        { WriterAction.Error, ODataExpectedExceptions.ODataException("ODataMessageWriter_WriteErrorAlreadyCalled") },
                    },
                    SkipForTestConfiguration = tc => tc.IsRequest,
                },
            };

            ExpectedException errorNotAllowedException = ODataExpectedExceptions.ODataException("ODataMessageWriter_ErrorPayloadInRequest");

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                EnumExtensionMethods.GetValues <WriterAction>().Cast <WriterAction>(),
                this.WriterTestConfigurationProvider.AtomFormatConfigurations,
                (testCase, writerAction, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                if (testCase.SkipForTestConfiguration != null && testCase.SkipForTestConfiguration(testConfiguration))
                {
                    return;
                }

                ExpectedException expectedExceptionOnError;
                if (testCase.ExpectedResults.TryGetValue(WriterAction.Error, out expectedExceptionOnError))
                {
                    if (testConfiguration.IsRequest)
                    {
                        testCase = new WriterStatesTestDescriptor(testCase);
                        testCase.ExpectedResults[WriterAction.Error] = errorNotAllowedException;
                    }
                }

                using (TestStream stream = new TestStream())
                {
                    // We purposely don't use the using pattern around the messageWriter here. Disposing the message writer will
                    // fail here because the writer is not left in a valid state.
                    var messageWriter  = TestWriterUtils.CreateMessageWriter(stream, testConfiguration, this.Assert);
                    ODataWriter writer = messageWriter.CreateODataWriter(feedWriter);

                    TestExceptionUtils.ExpectedException(
                        this.Assert,
                        () =>
                    {
                        if (testCase.Setup != null)
                        {
                            testCase.Setup(messageWriter, writer, stream);
                        }
                        this.InvokeWriterAction(messageWriter, writer, writerAction);
                    },
                        testCase.ExpectedResults[writerAction],
                        this.ExceptionVerifier);
                }
            });
        }
コード例 #24
0
 public IActionResult GetPlacingWays()
 {
     return(Ok(EnumExtensionMethods.GetValues <PlacingWay>()));
 }
コード例 #25
0
        } // OnGetAsync

        public async Task <IActionResult> OnPostAsync(int?id)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }
            List <InTandemUser> SelectedInTandemUsers = new List <InTandemUser> {
            };

            foreach (var user in Input.SelectedUsers)
            {
                SelectedInTandemUsers.Add(_context.Users
                                          .FirstOrDefault(u => u.FullName == user));
            }


            RideEvent RideEventToUpdate = await _context.RideEvent
                                          .Include(r => r.RideLeaderAssignments)
                                          .ThenInclude(r => r.InTandemUser)
                                          .FirstOrDefaultAsync(m => m.ID == id);


            // takes list of names of ride leaders selected and adds them to a list of ride leader assignments
            var assignedLeaders = RideEventToUpdate.RideLeaderAssignments
                                  .Select(u => u.InTandemUser)
                                  .ToList();

            foreach (var leaderToBeAssigned in SelectedInTandemUsers)
            {
                // if the leader is not already assigned to the ride, assign them to the ride
                if (!assignedLeaders.Any(u => u.FullName.Equals(leaderToBeAssigned.FullName)))
                {
                    var NewLeaderAdded = new RideLeaderAssignment
                    {
                        InTandemUser   = leaderToBeAssigned,
                        InTandemUserID = leaderToBeAssigned.Id
                    };
                    RideEventToUpdate.RideLeaderAssignments.Add(NewLeaderAdded);
                }
            }
            // to indicate ride leader needs to be deleted, compare both lists
            // if the length of selected users is less than the number of assigned leaders
            // find which one is not in the selected users list and delete that assignment
            foreach (var assignedLeader in assignedLeaders)
            {
                // if a user is in the assignedUsers list but not in the selectedUsers list
                // remove the ride leader assignment containing that user
                if (!SelectedInTandemUsers.Any(u => u.FullName.Equals(assignedLeader.FullName)))
                {
                    RideLeaderAssignment RideLeaderAssignmentToBeRemoved = RideEventToUpdate.RideLeaderAssignments
                                                                           .SingleOrDefault(u => u.InTandemUser.FullName.Equals(assignedLeader.FullName));

                    RideEventToUpdate.RideLeaderAssignments.Remove(RideLeaderAssignmentToBeRemoved);
                }
            }


            RideEvent.Status        = EnumExtensionMethods.GetValueFromDescription <Status>(Input.SelectedStatus);
            RideEvent.EventType     = EnumExtensionMethods.GetValueFromDescription <EventType>(Input.SelectedEventType);
            RideEvent.MaxSignUpType = EnumExtensionMethods.GetValueFromDescription <MaxSignUpType>(Input.SelectedMaxSignUpType);
            // default entity tracking does not include navigation properties

            if (RideEventToUpdate == null)
            {
                return(NotFound());
            }
            // TruUpdateModelAsync is used to prevent overposting
            if (await TryUpdateModelAsync <RideEvent>(
                    RideEventToUpdate,
                    "RideEvent",
                    i => i.EventName, i => i.EventDate,
                    i => i.EventType, i => i.Description,
                    i => i.Location, i => i.Distance,
                    i => i.RideLeaderAssignments,
                    i => i.MaxSignup, i => i.Status
                    ))
            {
                _context.Update(RideEventToUpdate);
                await _context.SaveChangesAsync();

                return(RedirectToPage("./Index"));
            }

            return(RedirectToPage("./Index"));
        } // OnPostAsync
コード例 #26
0
        public void ContentTypeHeaderParsingTest()
        {
            IEnumerable <ContentTypeTestCase> testCases = new ContentTypeTestCase[]
            {
                #region Atom test cases
                new ContentTypeTestCase
                {
                    // only reading an entry or feed should succeed
                    ContentType    = "application/atom+xml;type=feed",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    // only reading an entry or feed should succeed
                    ContentType    = "application/atom+xml;type=entry",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    // reading a feed, an entry, and metadata should succeed
                    ContentType    = "application/atom+xml",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    // reading a property, an entity reference link, entity reference links, a collection, a service document, and an error should succeed
                    ContentType    = "application/xml",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    // reading a property, an entity reference link, entity reference links, and a collection should succeed
                    ContentType    = "text/xml",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    // reading a service document should succeed
                    ContentType    = "application/atomsvc+xml",
                    ExpectedFormat = ODataFormat.Atom,
                },
                #endregion Atom test cases

                #region RawValue test cases
                new ContentTypeTestCase
                {
                    // only reading a raw value will succeed
                    ContentType    = "text/plain",
                    ExpectedFormat = ODataFormat.RawValue,
                    ShouldSucceedForPayloadKind = pk =>
                                                  pk == ODataPayloadKind.Value ||
                                                  pk == ODataPayloadKind.BinaryValue,
                },
                new ContentTypeTestCase
                {
                    // only reading a raw value or binary value will succeed; raw values can be read as binary values when the content type is application/octet-stream
                    ContentType    = "application/octet-stream",
                    ExpectedFormat = ODataFormat.RawValue,
                    ShouldSucceedForPayloadKind = pk =>
                                                  pk == ODataPayloadKind.Value ||
                                                  pk == ODataPayloadKind.BinaryValue,
                },
                new ContentTypeTestCase
                {
                    // only raw value / binary value will succeed
                    ContentType    = "multipart/mixed",
                    ExpectedFormat = ODataFormat.RawValue,
                    ShouldSucceedForPayloadKind = pk => false,
                },
                new ContentTypeTestCase
                {
                    // Test for: MimeType allows 0x7F character, but ContentType parsing doesn't
                    ContentType    = "application/" + 0x7F,
                    ExpectedFormat = ODataFormat.RawValue,
                    ShouldSucceedForPayloadKind = pk => false,
                },

                #endregion RawValue test cases

                #region JSON Lite test cases
                new ContentTypeTestCase
                {
                    // only batch and raw value will fail (batch payload kind tested separately in BatchContentTypeHeaderParsingTest)
                    ContentType    = ApplicationJsonODataLight,
                    ExpectedFormat = ODataFormat.Json,
                    ShouldSucceedForPayloadKind = pk =>
                                                  pk != ODataPayloadKind.Value &&
                                                  pk != ODataPayloadKind.BinaryValue,
                },
                new ContentTypeTestCase
                {
                    // only batch and raw value will fail (batch payload kind tested separately in BatchContentTypeHeaderParsingTest)
                    ContentType    = ApplicationJsonODataLightStreaming,
                    ExpectedFormat = ODataFormat.Json,
                    ShouldSucceedForPayloadKind = pk =>
                                                  pk != ODataPayloadKind.Value &&
                                                  pk != ODataPayloadKind.BinaryValue,
                },
                new ContentTypeTestCase
                {
                    // only batch and raw value will fail (batch payload kind tested separately in BatchContentTypeHeaderParsingTest)
                    ContentType    = ApplicationJsonODataLightNonStreaming,
                    ExpectedFormat = ODataFormat.Json,
                    ShouldSucceedForPayloadKind = pk =>
                                                  pk != ODataPayloadKind.Value &&
                                                  pk != ODataPayloadKind.BinaryValue,
                },
                #endregion JSON Lite test cases

                #region Error test cases
                new ContentTypeTestCase
                {
                    // unsupported content type; everything will fail
                    ContentType = "application/foo",
                    ShouldSucceedForPayloadKind = pk => false,
                },
                new ContentTypeTestCase
                {
                    // unsupported content type with parameters; everything will fail
                    ContentType = "abc/pqr;a=b;c=d",
                    ShouldSucceedForPayloadKind = pk => false,
                },
                new ContentTypeTestCase
                {
                    // "image/jpeg" is not supported, even for raw values.
                    ContentType = "image/jpeg",
                    ShouldSucceedForPayloadKind = pk => false,
                },
                #endregion Error test cases

                #region Content Type is null or empty
                new ContentTypeTestCase
                {
                    // null content type and zero content length should be default to Json if the payload kind is not binary value or value.
                    ContentType    = null,
                    ContentLength  = 0,
                    ExpectedFormat = ODataFormat.Json,
                    ShouldSucceedForPayloadKind = pk => true,
                    ShouldIgnoreTest            = pk => pk == ODataPayloadKind.BinaryValue || pk == ODataPayloadKind.Value
                },
                new ContentTypeTestCase
                {
                    // null content type and zero content length should be default to RawValue if the payload kind is binary value or value.
                    ContentType    = null,
                    ContentLength  = 0,
                    ExpectedFormat = ODataFormat.RawValue,
                    ShouldSucceedForPayloadKind = pk => true,
                    ShouldIgnoreTest            = pk => pk != ODataPayloadKind.Value
                },
                #endregion
            };

            string[] parameters = new string[]
            {
                "foo=bar",
                "foo1=bar1;foo2=bar2"
            };

            testCases = testCases.Concat(testCases.Where(tc => tc.ContentType != null).SelectMany(tc => parameters.Select(p => new ContentTypeTestCase(tc)
            {
                ContentType = tc.ContentType + ";" + p
            })));

            int oDataPayloadKindCount = EnumExtensionMethods.GetValues <ODataPayloadKind>().Length;

            this.Assert.AreEqual(oDataPayloadKindCount, TestReaderUtils.ODataPayloadKinds.Length, "The number of payload kind have changed, please update this test.");

            IEdmModel model = Microsoft.Test.OData.Utils.Metadata.TestModels.BuildTestModel();

            // We don't support batch payloads here; we test those separately in BatchContentTypeHeaderParsingTest
            IEnumerable <ODataPayloadKind> payloadKinds =
                TestReaderUtils.ODataPayloadKinds.Where(k => k != ODataPayloadKind.Batch && k != ODataPayloadKind.Unsupported);

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                payloadKinds,
                this.ReaderTestConfigurationProvider.AllFormatConfigurations,
                (testCase, payloadKind, testConfiguration) =>
            {
                testConfiguration = new ReaderTestConfiguration(testConfiguration);
                testConfiguration.MessageReaderSettings.EnableAtom = false;
                if (IgnoreTestCase(payloadKind, testConfiguration))
                {
                    return;
                }

                if (testCase.ShouldIgnoreTest != null && testCase.ShouldIgnoreTest(payloadKind))
                {
                    return;
                }

                string supportedMediaTypes;

                if (payloadKind == ODataPayloadKind.Value || payloadKind == ODataPayloadKind.BinaryValue)
                {
                    supportedMediaTypes = TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.Value) + ", " + TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.BinaryValue);
                }
                else
                {
                    supportedMediaTypes = TestMediaTypeUtils.GetSupportedMediaTypes(payloadKind, /*includeAppJson*/ true);
                }

                ExpectedException expectedException = testCase.ExpectedException == null
                         ? testCase.ShouldSucceedForPayloadKind != null && testCase.ShouldSucceedForPayloadKind(payloadKind)
                             ? null
                             : ODataExpectedExceptions.ODataContentTypeException("MediaTypeUtils_CannotDetermineFormatFromContentType", supportedMediaTypes, testCase.ContentType ?? "")
                         : testCase.ExpectedException;

                // Make sure to run success test cases only in configurations that will work.
                if (expectedException == null &&
                    testConfiguration.Format != null &&
                    testCase.ExpectedFormat != testConfiguration.Format)
                {
                    return;
                }

                ODataPayloadElement payloadElement = CreatePayloadElement(model, payloadKind, testConfiguration);

                // When we write a value with a content type different than 'text/plain', we will read it as binary.
                // Likewise, when we write a binary value with a 'text/plain' content type, we will read it as a string.
                Func <ReaderTestConfiguration, ODataPayloadElement> expectedResultElementFunc = null;
                if (payloadKind == ODataPayloadKind.Value && testCase.ContentType != null && !testCase.ContentType.StartsWith("text/plain"))
                {
                    expectedResultElementFunc = (testConfig) => ConvertToBinaryPayloadElement(payloadElement);
                }
                else if (payloadKind == ODataPayloadKind.BinaryValue && testCase.ContentType != null && testCase.ContentType.StartsWith("text/plain"))
                {
                    expectedResultElementFunc = (testConfig) => ConvertToStringPayloadElement(payloadElement);
                }

                ODataFormat expectedFormat = testCase.ExpectedFormat;

                ReaderContentTypeTestDescriptor testDescriptor = new ReaderContentTypeTestDescriptor(this.Settings)
                {
                    PayloadElement = payloadElement,
                    ExpectedResultPayloadElement = expectedResultElementFunc,
                    PayloadEdmModel   = model,
                    ExpectedFormat    = expectedFormat,
                    ContentType       = testCase.ContentType,
                    ExpectedException = expectedException
                };

                testDescriptor.RunTest(testConfiguration);
                testConfiguration.MessageReaderSettings.EnableAtom = true;
            });
        }