Exemple #1
1
        public static int GetCurrentPeriodId(IList<Period> periods)
        {
            int currentMonth = DateTime.Now.Month;

            switch (currentMonth)
            {
                case 1:
                case 2:
                case 3:
                    return periods.Single(p => p.NumberGym == 3).Id;
                case 4:
                case 5:
                case 6:
                    return periods.Single(p => p.NumberGym == 4).Id;
                case 7:
                case 8:
                case 9:
                    return periods.Single(p => p.NumberGym == 1).Id;
                case 10:
                case 11:
                case 12:
                    return periods.Single(p => p.NumberGym == 2).Id;
                default:
                    return 0;
            }
        }
        public virtual VoucherInformation GetPrimeCredit(IList<VoucherInformation> vouchers)
        {
            int numberOfCredit = vouchers.Count(v => v.voucher.documentType == DocumentTypeEnum.Cr);

            if (numberOfCredit == 1)
            {
                return vouchers.Single(v => v.voucher.documentType == DocumentTypeEnum.Cr);
            }
            else if (numberOfCredit > 1)
            {
                var creditVouchers = vouchers.Where(v => v.voucher.documentType == DocumentTypeEnum.Cr);

                if (creditVouchers.Any(v => !string.IsNullOrEmpty(v.GetExtraAuxDom())))
                {
                    return creditVouchers.Last(v => !string.IsNullOrEmpty(v.GetExtraAuxDom()));
                }
                else if (creditVouchers.Any(v => !string.IsNullOrEmpty(v.GetAuxDom())))
                {
                    return creditVouchers.Last(v => !string.IsNullOrEmpty(v.GetAuxDom()));
                }
                else
                {
                    return creditVouchers.Last();
                }
            }

            return null;
        }
Exemple #3
1
        public static IList<IJigsawPiece> ScramblePieces(IList<IJigsawPiece> pieces, int rows, int cols)
        {
            var random = new Random();
            var temp = new List<KeyValuePair<int, int>>();
            foreach (JigsawPieceBase originPiece in pieces)
            {
                int row = random.Next(0, rows);
                int col = random.Next(0, cols);

                while (temp.Exists(t => (t.Key == row) && (t.Value == col)))
                {
                    row = random.Next(0, rows);
                    col = random.Next(0, cols);
                }
                temp.Add(new KeyValuePair<int, int>(row, col));
                IJigsawPiece targetPiece = pieces.Single(p => p.OriginRow == row && p.OriginColumn == col);

                //swap positions
                var tempPoint = new Point(originPiece.Position.X, originPiece.Position.Y);
                originPiece.Position = new Point(targetPiece.Position.X, targetPiece.Position.Y);
                targetPiece.Position = tempPoint;

                //Swap column and row numbers
                int targetColumn = targetPiece.CurrentColumn;
                int targetRow = targetPiece.CurrentRow;
                targetPiece.CurrentColumn = originPiece.CurrentColumn;
                targetPiece.CurrentRow = originPiece.CurrentRow;
                originPiece.CurrentColumn = targetColumn;
                originPiece.CurrentRow = targetRow;
            }
            return pieces;
        }
Exemple #4
1
        public static Geopoint GetCentralGeopoint(IList<Geopoint> geoPoints)
        {
            if (geoPoints.Count == 1)
            {
                return geoPoints.Single();
            }

            double x = 0;
            double y = 0;
            double z = 0;

            foreach (var geopoint in geoPoints)
            {
                var latitude = geopoint.Position.Latitude * Math.PI / 180;
                var longitude = geopoint.Position.Longitude * Math.PI / 180;

                x += Math.Cos(latitude) * Math.Cos(longitude);
                y += Math.Cos(latitude) * Math.Sin(longitude);
                z += Math.Sin(latitude);
            }

            var total = geoPoints.Count;

            x = x / total;
            y = y / total;
            z = z / total;

            var centralLongitude = Math.Atan2(y, x);
            var centralSquareRoot = Math.Sqrt(x * x + y * y);
            var centralLatitude = Math.Atan2(z, centralSquareRoot);

            return new Geopoint(new BasicGeoposition { Latitude = centralLatitude * 180 / Math.PI, Longitude = centralLongitude * 180 / Math.PI });
        }
        private string GetJobDependencies(Job current, string result, IList<Job> jobs)
        {
            if (result.Contains(current.Name))
                return "";
            if (string.IsNullOrEmpty(current.DependencyName))
                return current.Name;

            ThrowIfCircularDependencyFound(current);

            return GetJobDependencies(jobs.Single(x => x.Name == current.DependencyName), result, jobs) + current.Name;
        }
 private static IEnumerable<PlayerGameweekPerformance> RetrievePlayerPerformances(IEnumerable<int> playerIds, int gameweek, IList<Player> upToDatePlayers)
 {
     foreach (var playerId in playerIds)
     {
         int id = playerId;
         var upToDatePlayer = upToDatePlayers.Single(x => x.Id == id);
         var gameweekFixtures =
             upToDatePlayer.PastFixtures.Where(x => x.GameWeek == gameweek);
         yield return PerformanceMappingHelper.CreatePlayerPerformanceFromFixtures(upToDatePlayer.Id, upToDatePlayer.Name, upToDatePlayer.Position, gameweekFixtures);
     }
 }
 private void AddRecursive(IList<NavigationNode> navigationNodes, NavigationNode toAdd)
 {
     if (navigationNodes.Contains(toAdd))
     {
         foreach (var node in toAdd.Children)
         {
             AddRecursive(navigationNodes.Single(x => x.Name == toAdd.Name).Children, node);
         }
     }
     else
         navigationNodes.Add(toAdd);
 }
        /// <summary>
        /// Verifies that the resulting java model matches our expectations.
        /// </summary>
        private void VerifyJavaModel(
            IList<JavaClass> expectedModel,
            IList<JavaClass> actualModel)
        {
            Assert.Equal(expectedModel.Count, actualModel.Count);

            foreach (var actualJavaClass in actualModel)
            {
                var expectedJavaClass = expectedModel
                    .Single(c => c.Type == actualJavaClass.Type);

                VerifyJavaClass(expectedJavaClass, actualJavaClass);
            }
        }
Exemple #9
1
        public HangmanGame(string solution)
        {
            Answer = solution;
            Id = Guid.NewGuid();

            _alphabet = "abcdefghijklmnopqrstuvwxyz ".ToArray()
                .Select(letter => new Tile { Letter = letter.ToString() })
                .ToArray();

            _alphabet.Single(t => t.Letter == " ").State = TileState.Hit;

            _solution = solution.ToArray()
                .Select(letter => _alphabet.FirstOrDefault(t => t.Letter == letter.ToString()))
                .ToArray();
        }
        private void SyncRoles(IList<RoleCheckbox> checkboxes, IList<RoleNames> roles)
        {
            var selectedRoles = new List<RoleNames>();
            foreach (var role in Database.Session.Query<RoleNames>())
            {
                var checkbox = checkboxes.Single(c => c.Id == role.Id);
                checkbox.Role = role.Role;

                if (checkbox.IsChecked)
                    selectedRoles.Add(role);
            }
            foreach (var toAdd in selectedRoles.Where(t => !roles.Contains(t)))
                roles.Add(toAdd);

            foreach (var toRemove in roles.Where(t => !selectedRoles.Contains(t)).ToList())
                roles.Remove(toRemove);
        }
        public Team AdjustTeamToGameweek(Team team, IList<Player> allUpToDatePlayers, int gameweek)
        {
            if (team == null) throw new ArgumentNullException("team");
            if (gameweek < 1 || gameweek > 38) throw new ArgumentException("gameweek");
            if (allUpToDatePlayers == null) throw new ArgumentNullException("allUpToDatePlayers");

            _logger.Log(Tag.Adjusting, string.Concat("Adjusting team to gameweek ", gameweek));

            var updatedTeam = new Team();

            foreach (var playerInTeam in team.Players)
            {
                //find player that is up to date to adjust
                Player inTeam = playerInTeam;

                var playerToAdjust = allUpToDatePlayers.Single(x => x.Id == inTeam.Id);

                //bring them back to the current gameweek
                var adjustedPlayer = AdjustPlayer(playerToAdjust, gameweek);

                if(adjustedPlayer.NowCost != playerInTeam.NowCost)
                {
                    _logger.Log(Tag.Adjusting, string.Format("{0} value has {1} from {2} to {3}", playerInTeam.Name, adjustedPlayer.NowCost > playerInTeam.NowCost ? "increased" : "decreased", playerInTeam.NowCost.ToMoney(), adjustedPlayer.NowCost.ToMoney()));
                }

                //now copy over anything that is special about a player being in your team

                //todo: check this is correct when we find out property for purchase cost
                adjustedPlayer.OriginalCost = playerInTeam.OriginalCost;

                updatedTeam.Players.Add(adjustedPlayer);
            }

            //now switch over captains
            updatedTeam.Captain = updatedTeam.Players.Single(p => p.Id == team.Captain.Id);
            updatedTeam.ViceCaptain = updatedTeam.Players.Single(p => p.Id == team.ViceCaptain.Id);

            return updatedTeam;
        }
Exemple #12
1
        public RoomViewModel(MainViewModel mainViewModel, Room room, IList<User> users)
            : base(true)
        {
            Description = room;
              MainViewModel = mainViewModel;
              Messages = new ObservableCollection<MessageViewModel>();
              allInRoom = new UserViewModel(new User("Все в комнате", Color.Black), this);
              messageIds = new HashSet<long>();
              Users = new ObservableCollection<UserViewModel>(users == null
            ? Enumerable.Empty<UserViewModel>()
            : room.Users.Select(user => new UserViewModel(users.Single(u => u.Equals(user)), this)));

              SendMessageCommand = new Command(SendMessage, Obj => ClientModel.Client != null);
              PastReturnCommand = new Command(PastReturn);
              AddFileCommand = new Command(AddFile, Obj => ClientModel.Client != null);
              InviteInRoomCommand = new Command(InviteInRoom, Obj => ClientModel.Client != null);
              KickFromRoomCommand = new Command(KickFromRoom, Obj => ClientModel.Client != null);
              ClearSelectedMessageCommand = new Command(ClearSelectedMessage, Obj => ClientModel.Client != null);

              MainViewModel.AllUsers.CollectionChanged += AllUsersCollectionChanged;
              NotifierContext.ReceiveMessage += ClientReceiveMessage;
              NotifierContext.RoomRefreshed += ClientRoomRefreshed;
        }
Exemple #13
1
        public static void Sync(IList<RoleCheckBox> checkBoxes, IList<Role> userRoles)
        {
            var selectedRoles = new List<Role>();

            foreach (var role in Database.Session.Query<Role>())
            {
                var checkBox = checkBoxes.Single(c => c.Id == role.Id);

                checkBox.Name = role.Name;

                if (checkBox.IsChecked)
                    selectedRoles.Add(role);
            }

            foreach (var roleToAdd in selectedRoles.Where(sr => !userRoles.Contains(sr)))
            {
                userRoles.Add(roleToAdd);
            }

            foreach (var roleToRemove in userRoles.Where(cr => !selectedRoles.Contains(cr)).ToList())
            {
                userRoles.Remove(roleToRemove);
            }
        }
        public virtual void UpdateFromSeriesEditor(IList<Series> editedSeries)
        {
            var allSeries = GetAllSeries();

            foreach(var series in allSeries)
            {
                //Only update parameters that can be changed in MassEdit
                var edited = editedSeries.Single(s => s.SeriesId == series.SeriesId);
                series.QualityProfileId = edited.QualityProfileId;
                series.Monitored = edited.Monitored;
                series.SeasonFolder = edited.SeasonFolder;
                series.BacklogSetting = edited.BacklogSetting;
                series.Path = edited.Path;
            }

            _database.UpdateMany(allSeries);
        }
        public async Task<IList<DiagnosisResultDTO>> Process(IList<FuzzySymptomDTO> symptomes)
        {
            var symptomIds = symptomes.Select(s => s.SymptomId).ToArray();

            var diagnosesRepo = _unitOfWork.RepositoryAsync<Diagnosis>();
            var diagnosis = diagnosesRepo.Query(d => d.Symptoms.Any(s => symptomIds.Any(id => id == s.SymptomId))).Select().Distinct().OrderBy(d => d.Id).ToList();
            var diagnosesIds = diagnosis.Select(d => d.Id).ToArray();

            var IS = await InitFuzzyEngineDiagnosis(symptomIds, diagnosesIds);

            var symptomRepo = _unitOfWork.RepositoryAsync<Symptom>();
            var symptoms = await symptomRepo.Queryable().Where(s => symptomIds.Any(sId => sId == s.Id)).ToListAsync();
            foreach(var s in symptoms)
            {
                var fuzzySymptom = symptomes.Single(fs => fs.SymptomId == s.Id);
                var fuzzy = fuzzySymptom.FuzzySet != null ? fuzzySymptom.FuzzySet : SymptomFuzzySet.Common;
                var average = (fuzzy.RightLimit + fuzzy.LeftLimit) / 2;
                try
                {
                    IS.SetInput(s.Name, average);
                }
                catch(Exception exc)
                {

                }
            }

            var result = new List<DiagnosisResultDTO>();

            var evaluate = IS.Evaluate("Diagnosis");

            var i = 0;
            foreach (var diagnoses in diagnosis)
            {
                i++;

                var predel = new Tuple<int, int>(i > 1 ? (i - 1) * 100 : -1, i * 100);

                if(predel.Item1 <= (int)evaluate && predel.Item2 >= (int)evaluate)
                {
                    result.Add(new DiagnosisResultDTO
                    {
                        DiagnosisId = diagnoses.Id,
                        DiagnosisName = diagnoses.DisplayName,
                        Coefficient = 100//TODO:
                    });
                    break;
                }
                //try
                //{
                //    result.Add(new DiagnosisResultDTO {
                //        DiagnosisId = diagnoses.Id,
                //        DiagnosisName = diagnoses.DisplayName,
                //        Coefficient = IS.Evaluate(diagnoses.Name)
                //    });
                //}
                //catch(Exception exc)
                //{

                //}
            }

            return result;
        }
 /// <summary>
 /// Get job
 /// </summary>
 /// <param name="requestId">Unique identifier for a job</param>
 /// <returns>Job or null if not found</returns>
 public async Task <IJobQueue> GetJobAsync(Guid requestId)
 {
     return(await Task.Run(() => jobs.Single(x => x.RequestId == requestId)));
 }
        protected static IEnumerable<CodeActionOperation> VerifyInputsAndGetOperations(int index, IList<CodeAction> actions)
        {
            Assert.NotNull(actions);
            if (actions.Count == 1)
            {
                var suppressionAction = actions.Single() as SuppressionCodeAction;
                if (suppressionAction != null)
                {
                    actions = suppressionAction.NestedActions.ToList();
                }
            }

            Assert.InRange(index, 0, actions.Count - 1);

            var action = actions[index];
            return action.GetOperationsAsync(CancellationToken.None).Result;
        }
Exemple #18
0
 private Expression MakeIfExpression(Expression recursiveCount, IList <Expression> input)
 {
     return(Expression.IfThen(Expression.GreaterThanOrEqual(recursiveCount, Expression.Constant(0)),
                              input.Count > 1 ? Expression.Block(input) : input.Single()));
 }
Exemple #19
0
            public Reign.Unit ToUnit(IList<UnitData> data)
            {
                var uData = data.Single(u => u.ID == _id);

                return new Reign.Unit(uData, _rank, _exp, _obCount) {
                    Acted = _acted
                };
            }
 public Task <Order> GetOrderByIdAsync(string id)
 {
     return(Task.FromResult(_orders.Single(_ => _.Id == id)));
 }
 private void CheckFieldValues(int size, int[][] expectedValues, IList<Field> fieldList)
 {
     for (int i = 0; i < size; i++)
     {
         for (int j = 0; j < size; j++)
         {
             fieldList.Single(f => f.Row == i && f.Column == j).Value.Should().Be(expectedValues[i][j], string.Format("{0}/{1}", i, j));
         }
     }
 }
Exemple #22
0
 public T Get(int id)
 {
     return(Data.Single(l => (int)l.GetType().GetRuntimeProperty("Id").GetValue(l) == id));
 }
Exemple #23
0
 private static void AssertHasResultType(string testName, TestResultType result)
 {
     FinishedTests.ShouldContain(x => x.Name == testName);
     FinishedTests.Single(x => x.Name == testName).ResultType.ShouldEqual(result);
 }
Exemple #24
0
 public Task <Customer> GetCustomerAsync(int id)
 {
     return(Task.FromResult(_customers.Single(c => Equals(c.Id, id))));
 }
Exemple #25
0
        private static void LoginUserMethod(ElectionDbContext context, WebserviceRawCommunication webservice)
        {
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine("----- Login to system -------------------------------------------------------");
            LoginCredentials loginCredentials = GetCredentialsFromConsole();
            User             user             = new Domain.Models.User(loginCredentials, context, webservice);
            LoginValidation  loginValidation  = user.Login();

            if (loginValidation.Error)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                foreach (var error in loginValidation.LoginErrors)
                {
                    Console.WriteLine($"- Error: {LoginErrorDescription.GetDescription(error)}");
                }
            }

            if (loginValidation.Warning)
            {
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                foreach (var warning in loginValidation.LoginWarnings)
                {
                    Console.WriteLine($"- Warning: {LoginWarningDescription.GetDescription(warning)}");
                }
            }

            if (!loginValidation.Error)
            {
                if (user.Logged)
                {
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine($"- User logged : {user.FirstName} / {user.LastName} / {user.Pesel}");

                    if (!loginValidation.LoginWarnings.Contains(LoginWarning.UserAlreadyVoted) &&
                        !loginValidation.LoginWarnings.Contains(LoginWarning.UserIsDisallowedToVote))
                    {
                        IList <Candidate> candidates = context.Candidates.ToList();
                        IList <Party>     parties    = context.Parties.ToList();
                        Console.ForegroundColor = ConsoleColor.Magenta;
                        for (int i = 0; i < candidates.Count; i++)
                        {
                            Console.WriteLine(
                                $"{i + 1}] {candidates[i].Name} / {parties.Single(x => x.PartyId == candidates[i].PartyId).Name}");
                        }

                        int[] parsedChoice;
                        do
                        {
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.Write("Please enter you candidate (or candidates) no [eg. \"1,5,10\"]: ");
                            Console.ForegroundColor = ConsoleColor.White;
                            string candidatesRead = Console.ReadLine();
                            parsedChoice = ChoiceParser.Parse(candidatesRead, candidates.Count);
                            if (parsedChoice == null)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine($"- Error: Illegal characters in your response");
                            }
                        } while (parsedChoice == null);

                        Console.ForegroundColor = ConsoleColor.Yellow;

                        for (int i = candidates.Count; i > 0; i--)
                        {
                            if (!parsedChoice.Any(x => x == i))
                            {
                                candidates.RemoveAt(i - 1);
                            }
                        }

                        Console.ForegroundColor = ConsoleColor.DarkGray;
                        if (candidates.Count == 0)
                        {
                            Console.WriteLine($"You voted to nobody");
                        }

                        foreach (var c in candidates)
                        {
                            Console.WriteLine(
                                $"You voted to {c.Name} / {parties.Single(x => x.PartyId == c.PartyId).Name}");
                        }

                        user.Vote(candidates);
                    }

                    // Get Vote statistics
                    VoteStatistics(context);

                    user.Logout();
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("- User logout");
                }
            }
        }
 public static TestCase FindTestcase(string qualifiedTestname, IList <TestCase> testCasesRun)
 {
     return(testCasesRun.Single(tc => tc.FullyQualifiedName == qualifiedTestname));
 }
        private static void InitAccounts()
        {
            Accounts = new List<Account>
            {
               
                new PremiumAccount()
                {
                    Id = 1,
                    Name = "Name1",
                    AccountInfo = new AccountInfo()
                    {
                        NickName = "NickName1"
                    },
                    Address = new GlobalAddress()
                    {
                        City = "Redmond",
                        Street = "1 Microsoft Way",
                        CountryCode="US"
                    },
                    Tags = new Tags(),
                    Since=new DateTimeOffset(new DateTime(2014,5,22),TimeSpan.FromHours(8)),
                },
                new Account()
                {
                    Id = 2,
                    Name = "Name2",
                    AccountInfo = new AccountInfo()
                    {
                        NickName = "NickName2"
                    },
                    Address =  new Address()
                    {
                        City = "Shanghai",
                        Street = "Zixing Road"
                    },
                    Tags = new Tags()
                },
                new Account()
                {
                    Id = 3,
                    Name = "Name3",
                    AccountInfo = new AccountInfo()
                    {
                        NickName = "NickName3"
                        
                    },
                    Address = new Address()
                    {
                        City = "Beijing",
                        Street = "Danling Street"
                    },
                    Tags = new Tags()
                }
            };

            Account account = Accounts.Single(a => a.Id == 1);
            account.DynamicProperties["OwnerAlias"] = "jinfutan";
            account.DynamicProperties["OwnerGender"] = Gender.Female;
            account.DynamicProperties["IsValid"] = true;
            account.DynamicProperties["ShipAddresses"] = new List<Address>(){
                new Address
                {
                    City = "Beijing",
                    Street = "Danling Street"
                },
                new Address
                {
                    City="Shanghai",
                    Street="Zixing",
                }
            };

            Accounts[0].AccountInfo.DynamicProperties["Age"] = 10;

            Accounts[0].AccountInfo.DynamicProperties["Gender"] = Gender.Male;

            Accounts[0].AccountInfo.DynamicProperties["Subs"] = new string[] { "Xbox", "Windows", "Office" };

            Accounts[0].Address.DynamicProperties["Country"] = "US";
            Accounts[0].Tags.DynamicProperties["Tag1"] = "Value 1";
            Accounts[0].Tags.DynamicProperties["Tag2"] = "Value 2";

            Accounts[1].AccountInfo.DynamicProperties["Age"] = 20;

            Accounts[1].AccountInfo.DynamicProperties["Gender"] = Gender.Female;

            Accounts[1].AccountInfo.DynamicProperties["Subs"] = new string[] { "Xbox", "Windows" };

            Accounts[1].Address.DynamicProperties["Country"] = "China";
            Accounts[1].Tags.DynamicProperties["Tag1"] = "abc";

            Accounts[2].AccountInfo.DynamicProperties["Age"] = 30;

            Accounts[2].AccountInfo.DynamicProperties["Gender"] = Gender.Female;

            Accounts[2].AccountInfo.DynamicProperties["Subs"] = new string[] { "Windows", "Office" };

            Accounts[2].Address.DynamicProperties["Country"] = "China";
        }
Exemple #28
0
        private void ImportPurchaseOrders()
        {
            DataModel.Model.PurchaseOrder purchaseOrder = _purchaseOrderRepository
                                                          .Query()
                                                          .OrderByDescending(x => x.DateOriginated)
                                                          .FirstOrDefault(x => x.POStatusCategory == (sbyte)DataType.POStatusCategory.Ordered);

            if (purchaseOrder == null)
            {
                return;
            }

            IList <DataModel.Model.Produce> produces = _produceRepository.Query().ToList();

            IEnumerable <IEnumerable <KeyValuePair <string, string> > > csvContents = CsvHepler.GetCsvData(tbPath.Text);
            IEnumerable <KeyValuePair <byte, string> > procedureUnits = CommonHelper.Enumerate <DataType.ProduceUnit>();

            csvContents.ForEach(x =>
            {
                DataModel.Model.POItem poItem = new DataModel.Model.POItem();
                foreach (var y in x)
                {
                    if (!string.IsNullOrEmpty(y.Value))
                    {
                        DataType.PurchaseOrderField purchaseOrderField =
                            (DataType.PurchaseOrderField)Enum.Parse(typeof(DataType.PurchaseOrderField), y.Key);
                        switch (purchaseOrderField)
                        {
                        case DataType.PurchaseOrderField.ProduceNo:
                            DataModel.Model.Produce produce = produces
                                                              .Single(c => y.Value.Equals(c.ProduceNo, StringComparison.CurrentCultureIgnoreCase));
                            poItem.ProduceId = produce.ProduceId;
                            poItem.Produce   = produce;
                            continue;

                        case DataType.PurchaseOrderField.PriceOrdered:
                            poItem.PriceOrdered = float.Parse(y.Value);
                            continue;

                        case DataType.PurchaseOrderField.PriceReceived:
                            poItem.PriceReceived = float.Parse(y.Value);
                            continue;

                        case DataType.PurchaseOrderField.QuantityOrdered:
                            poItem.QuantityOrdered = float.Parse(y.Value);
                            continue;

                        case DataType.PurchaseOrderField.QuantityReceived:
                            poItem.QuantityReceived = float.Parse(y.Value);
                            continue;

                        default:
                            continue;
                        }
                    }
                }
                poItem.POStatusCategory  = (sbyte)DataType.POItemStatusCategory.Dispatched;
                poItem.CreatedBy         = "admin";
                poItem.CreatedOn         = DateTime.Now;
                poItem.LastModifiedBy    = "admin";
                poItem.LastModifiedOn    = DateTime.Now;
                poItem.RowVersion        = DateTime.Now;
                poItem.Produce.Quantity += poItem.QuantityReceived ?? 0;
                poItem.Produce.Producelogs.Add(new Producelog
                {
                    ChangedBy   = ResourcesHelper.CurrentUser.Name,
                    DateChanged = DateTime.Now,
                    NewValue    = string.Format(ResourcesHelper.PurchaseOrderImporterFormat,
                                                purchaseOrder.PurchaseOrderNo,
                                                (poItem.QuantityReceived ?? 0).ToString("F2"),
                                                (poItem.PriceReceived ?? 0).ToString("F2"),
                                                poItem.Produce.Quantity.ToString("F2"))
                });
                poItem.Produce.LastOrderDate = DateTime.Now;

                purchaseOrder.POItems.Add(poItem);
            });
            purchaseOrder.POStatusCategory = (sbyte)DataType.POStatusCategory.Completed;
            purchaseOrder.TotalAmount      = purchaseOrder.POItems.Sum(x => x.PriceReceived * x.QuantityReceived);
            purchaseOrder.GrandTotal       = (purchaseOrder.TotalAmount ?? 0) + (purchaseOrder.TotalOther ?? 0)
                                             + (purchaseOrder.TotalShipping ?? 0) + (purchaseOrder.TotalTax ?? 0);
            _purchaseOrderRepository.Update(purchaseOrder);
            _unitOfWork.Commit();

            System.Windows.MessageBox.Show("订单导入成功!", Properties.Resources.SystemName,
                                           MessageBoxButton.OK, MessageBoxImage.Information);
            Close();
        }
        /// <summary>
        /// Generates SriptSharp files
        /// </summary>
        /// <param name="entries">List of jQueryUI entries.</param>
        public void Render(IList<Entry> entries)
        {
            if (entries == null) {
                return;
            }

            DirectoryInfo destination = new DirectoryInfo(DestinationPath);
            if (destination.Exists) {
                destination.Delete(true);
            }

            foreach (Entry entry in entries) {
                Messages.WriteLine("Generating " + Path.Combine(DestinationPath, Utils.PascalCase(entry.Name)));

                Entry baseEntry = null;
                if (!string.IsNullOrEmpty(entry.Type)) {
                    // find the base entry
                    baseEntry = entries.SingleOrDefault(e => e.Name.ToLowerInvariant() == entry.Type.ToLowerInvariant());
                }

                RenderEntry(entry, baseEntry);
            }

            Messages.WriteLine("Generating jQueryUI base files.");
            RenderEventHandler();
            RenderBox();
            RenderSize();
            RenderEffectExtensionMethods(entries.Where(e => e.Category == "effects" && e.Name != "effect"));
            RenderInteractionOrWidgetExtensionMethods("Interaction", entries.Where(e => e.Category == "interactions"));
            RenderInteractionOrWidgetExtensionMethods("Widget", entries.Where(e => e.Category == "widgets" && e.Name != "widget"));
            RenderPositionExtensionMethods(entries.Single(e => e.Name == "position"));
        }
Exemple #30
0
        private void ProcessBatch([NotNull] IList <UnitOfWork> batch)
        {
            if (this._singleItemMethod != null && batch.Count == 1)
            {
                UnitOfWork item = batch.Single();

                TInput itemInput = item.Input;
                TaskCompletionSource <TOutput> tcs = item.TaskCompletionSource;

                // Task.Run b/c it's possible that the Func<Task> throws on run rather than on await if they aren't async
                Task <TOutput> task = Task.Run(
                    // TODO: Take cancellationToken? not of super importance since BatchExecutor usage advice is to live for the whole process
                    () => this._singleItemMethod(itemInput),
                    this.cts.Token);

                ConnectTaskToTaskCompletionSource(task, tcs, this.cts.Token);
            }
            else
            {
                // A batch or single-item is disabled (so handled as a batch)

                List <TInput> allInputs = batch
                                          .Select(item => item.Input)
                                          .ToList();

                // Task.Run b/c it's possible that the Func<Task> throws on run rather than on await if they aren't async
                Task <IList <TOutput> > task = Task.Run(
                    () => this._batchedItemsMethod(allInputs),
                    this.cts.Token);

                // Orphaned, observed on tcs's
                Task orphan = task.ContinueWith(
                    t =>
                {
                    switch (t.Status)
                    {
                    case TaskStatus.Canceled:
                        foreach (TaskCompletionSource <TOutput> tcs in batch.Select(item => item.TaskCompletionSource))
                        {
                            tcs.SetCanceled();
                        }

                        break;

                    case TaskStatus.RanToCompletion:
                        IList <TOutput> results = t.Result;

                        Dictionary <TInput, TaskCompletionSource <TOutput> > inputToTcsDictionary = batch
                                                                                                    .ToDictionary(
                            item => item.Input,
                            item => item.TaskCompletionSource /* TODO: contract of _outputToInputMatchFunction -- use ReferenceEquals dictionary */);

                        Dictionary <TInput, TaskCompletionSource <TOutput> > unhandledItems = batch
                                                                                              .ToDictionary(
                            item => item.Input,
                            item => item.TaskCompletionSource /* TODO: contract of _outputToInputMatchFunction -- use ReferenceEquals dictionary */);
                        try
                        {
                            for (var index = 0; index < results.Count; index++)
                            {
                                TOutput result          = results[index];
                                TInput resultIsForInput = this._ouputToInputMatchFunction(allInputs, index, result);

                                if (inputToTcsDictionary.ContainsKey(resultIsForInput))
                                {
                                    TaskCompletionSource <TOutput> tcs = inputToTcsDictionary[resultIsForInput];

                                    tcs.SetResult(result);

                                    // Remove so the exception logic doesn't set exception on this item
                                    unhandledItems.Remove(resultIsForInput);
                                }
                            }

                            // Some outputs did not have matches in the inputs
                            if (unhandledItems.Any())
                            {
                                foreach (TaskCompletionSource <TOutput> tcs in unhandledItems.Values)
                                {
                                    tcs.SetException(
                                        new InvalidOperationException(
                                            "A result was processed for the batched inputs, but no result item was matched to this input item."));
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            foreach (TaskCompletionSource <TOutput> tcs in unhandledItems.Values)
                            {
                                tcs.SetException(
                                    new InvalidOperationException(
                                        "OuputToInputMatchFunction threw, meaning we cannot properly match the outputs back to the inputs!",
                                        e));
                            }
                        }

                        break;

                    case TaskStatus.Faulted:
                        foreach (TaskCompletionSource <TOutput> tcs in batch.Select(item => item.TaskCompletionSource))
                        {
                            tcs.SetException(task.Exception);
                        }

                        break;

                    default:
                        // Pipe the exception back to somewhere we will observe it
                        foreach (TaskCompletionSource <TOutput> tcs in batch.Select(item => item.TaskCompletionSource))
                        {
                            tcs.SetException(new InvalidOperationException("Invalid continuation call."));
                        }

                        break;
                    }
                },
                    this.cts.Token);
            }
        }
Exemple #31
0
        /*
         导入结构:
         * 总目录-|
         *        -供应商-|
         *                -图片文件夹
         *                -产品数据.xls
         *
         * 结果目录:
         *  总目录-
         *        --合格数据
         *        --不合格数据
         *               --供应商
         *                   --没有产品信息的图片
         *                   --没有图片的产品.xls
         */
        /// <summary>
        /// 将结果保存到磁盘:
        /// </summary>
        /// <param name="productHasImages"></param>
        public void HandlerCheckResult(string supplierName, IList<Product> productHasImages, IList<Product> productNotHasImages,
            IList<Product> productsExistedInDb,
            IList<FileInfo> imagesHasProduct, IList<FileInfo> imagesNotHasProduct,
            string outputFolder)
        {
            DirectoryInfo dirRoot = new DirectoryInfo(outputFolder);
            DataExport transfer = new DataExport();
            DataSet ds = new DataSet();
            //如果没有合格数据 则不需要创建
            if (productHasImages.Count > 0)
            {
                DirectoryInfo dirQuanlified = IOHelper.EnsureDirectory(outputFolder + "合格数据\\");
                DirectoryInfo dirSupplierQuanlified = IOHelper.EnsureDirectory(dirQuanlified.FullName + supplierName + "\\");
                DirectoryInfo dirSupplierQuanlifiedImages = IOHelper.EnsureDirectory(dirSupplierQuanlified.FullName + supplierName + "\\");
                foreach (Product product in productHasImages)
                {
                    try
                    {
                        FileInfo imageFile = imagesHasProduct.Single(x => StringHelper.ReplaceSpace(Path.GetFileNameWithoutExtension(x.Name))
                          .Equals(StringHelper.ReplaceSpace(product.ModelNumber), StringComparison.OrdinalIgnoreCase));
                        File.Copy(imageFile.FullName, dirSupplierQuanlified.FullName + supplierName + "\\" + imageFile.Name, true);

                    }
                    catch (Exception ex)
                    {
                        throw new Exception("图片复制出错:" + dirSupplierQuanlified.FullName + "---" + product.ModelNumber + "---" + ex.Message);
                    }
                }

                DataTable dtProductsHasImage = ObjectConvertor.ToDataTable<Product>(productHasImages);
                ds.Clear();
                ds.Tables.Add(dtProductsHasImage);
                transfer.DataToExport = ds;
                transfer.SaveWorkBook(dirSupplierQuanlified.FullName + "\\" + supplierName + ".xls");
            }

            //没有图片的产品
            string dirPathNotQuanlified = outputFolder + "不合格数据\\";
            string dirPathSupplierNotQuanlified = dirPathNotQuanlified + supplierName + "\\";
            if (productNotHasImages.Count > 0)
            {
                DirectoryInfo dirSupplierNotQuanlified = IOHelper.EnsureDirectory(dirPathSupplierNotQuanlified);
                DataTable dtProductsNotHasImage = ObjectConvertor.ToDataTable<Product>(productNotHasImages);
                ds.Clear();
                ds.Tables.Add(dtProductsNotHasImage);
                transfer.DataToExport = ds;
                transfer.SaveWorkBook(dirSupplierNotQuanlified + "没有图片的数据_" + supplierName + ".xls");

            }
            //没有产品的图片
            if (imagesNotHasProduct.Count > 0)
            {

                string dirPathSupplierNotQuanlifiedImages = dirPathSupplierNotQuanlified + "多余图片_" + supplierName + "\\";
                DirectoryInfo dirSupplierNotQuanlifiedImages = IOHelper.EnsureDirectory(dirPathSupplierNotQuanlifiedImages);
               foreach (FileInfo file in imagesNotHasProduct)
                {
                    file.CopyTo(dirSupplierNotQuanlifiedImages + file.Name, true);
                }
            }
            //多余的图片

            //重复数据
            if (productsExistedInDb.Count > 0)
            {
                string dirPathSupplierRepeated = dirPathSupplierNotQuanlified + "数据库内已存在的数据_" + supplierName + "\\";
                DirectoryInfo dirSupplierRepeated = IOHelper.EnsureDirectory(dirPathSupplierRepeated);

                DataTable dtProductsRepeated = ObjectConvertor.ToDataTable<Product>(productsExistedInDb);
                ds.Clear();
                ds.Tables.Add(dtProductsRepeated);
                transfer.DataToExport = ds;
                transfer.SaveWorkBook( dirSupplierRepeated.FullName+"\\" + supplierName + ".xls");
            }
        }
        /// <summary>
        /// Try to resolve a function from the given inputs.
        /// </summary>
        /// <param name="identifier">The identifier of the function that we're trying to find</param>
        /// <param name="parameterNames">the names of the parameters to search for.</param>
        /// <param name="bindingType">the type of the previous segment</param>
        /// <param name="model">the model to use to look up the operation import</param>
        /// <param name="matchingOperation">The single matching function found.</param>
        /// <param name="resolver">Resolver to be used.</param>
        /// <returns>True if a function was matched, false otherwise. Will throw if the model has illegal operation imports.</returns>
        internal static bool ResolveOperationFromList(string identifier, IEnumerable <string> parameterNames, IEdmType bindingType, IEdmModel model, out IEdmOperation matchingOperation, ODataUriResolver resolver)
        {
            // TODO: update code that is duplicate between operation and operation import, add more tests.
            // If the previous segment is an open type, the service action name is required to be fully qualified or else we always treat it as an open property name.
            if (bindingType != null)
            {
                // TODO: look up actual container names here?
                // When using extension, there may be function call with unqualified name. So loose the restriction here.
                if (bindingType.IsOpen() && !identifier.Contains(".") && resolver.GetType() == typeof(ODataUriResolver))
                {
                    matchingOperation = null;
                    return(false);
                }
            }

            IList <IEdmOperation> candidateMatchingOperations = null;

            // The extension method FindBoundOperations & FindOperations call IEdmModel.FindDeclaredBoundOperations which can be implemented by anyone and it could throw any type of exception
            // so catching all of them and simply putting it in the inner exception.
            try
            {
                if (bindingType != null)
                {
                    candidateMatchingOperations = resolver.ResolveBoundOperations(model, identifier, bindingType).ToList();
                }
                else
                {
                    candidateMatchingOperations = resolver.ResolveUnboundOperations(model, identifier).ToList();
                }
            }
            catch (Exception exc)
            {
                if (ExceptionUtils.IsCatchableExceptionType(exc))
                {
                    throw new ODataException(ODataErrorStrings.FunctionOverloadResolver_FoundInvalidOperation(identifier), exc);
                }

                throw;
            }

            IList <IEdmAction> foundActionsWhenLookingForFunctions = new List <IEdmAction>();
            int parameterNamesCount = parameterNames.Count();

            if (bindingType != null)
            {
                candidateMatchingOperations = candidateMatchingOperations.EnsureOperationsBoundWithBindingParameter().ToList();
            }

            // If the number of parameters > 0 then this has to be a function as actions can't have parameters on the uri only in the payload. Filter further by parameters in this case, otherwise don't.
            if (parameterNamesCount > 0)
            {
                // can only be a function as only functions have parameters on the uri.
                candidateMatchingOperations = candidateMatchingOperations.RemoveActions(out foundActionsWhenLookingForFunctions).FilterFunctionsByParameterNames(parameterNames, resolver.EnableCaseInsensitive).Cast <IEdmOperation>().ToList();
            }
            else if (bindingType != null)
            {
                // Filter out functions with more than one parameter. Actions should not be filtered as the parameters are in the payload not the uri
                candidateMatchingOperations = candidateMatchingOperations.Where(o =>
                                                                                (o.IsFunction() && (o.Parameters.Count() == 1 || o.Parameters.Skip(1).All(p => p is IEdmOptionalParameter))) || o.IsAction()).ToList();
            }
            else
            {
                // Filter out functions with any parameters
                candidateMatchingOperations = candidateMatchingOperations.Where(o => (o.IsFunction() && !o.Parameters.Any()) || o.IsAction()).ToList();
            }

            // Only filter if there is more than one and its needed.
            if (candidateMatchingOperations.Count > 1)
            {
                candidateMatchingOperations = candidateMatchingOperations.FilterBoundOperationsWithSameTypeHierarchyToTypeClosestToBindingType(bindingType).ToList();
            }

            // If any of the things returned are an action, it better be the only thing returned, and there can't be parameters in the URL
            if (candidateMatchingOperations.Any(f => f.IsAction()))
            {
                if (candidateMatchingOperations.Count > 1)
                {
                    if (candidateMatchingOperations.Any(o => o.IsFunction()))
                    {
                        throw new ODataException(ODataErrorStrings.FunctionOverloadResolver_MultipleOperationOverloads(identifier));
                    }
                    else
                    {
                        throw new ODataException(ODataErrorStrings.FunctionOverloadResolver_MultipleActionOverloads(identifier));
                    }
                }

                if (parameterNames.Count() != 0)
                {
                    throw ExceptionUtil.CreateBadRequestError(ODataErrorStrings.RequestUriProcessor_SegmentDoesNotSupportKeyPredicates(identifier));
                }

                matchingOperation = candidateMatchingOperations.Single();
                return(true);
            }

            if (foundActionsWhenLookingForFunctions.Count > 0)
            {
                throw ExceptionUtil.CreateBadRequestError(ODataErrorStrings.RequestUriProcessor_SegmentDoesNotSupportKeyPredicates(identifier));
            }

            // If more than one overload matches, try to select based on optional parameters
            if (candidateMatchingOperations.Count > 1)
            {
                candidateMatchingOperations = candidateMatchingOperations.FindBestOverloadBasedOnParameters(parameterNames).ToList();
            }

            if (candidateMatchingOperations.Count > 1)
            {
                throw new ODataException(ODataErrorStrings.FunctionOverloadResolver_NoSingleMatchFound(identifier, string.Join(",", parameterNames.ToArray())));
            }

            matchingOperation = candidateMatchingOperations.SingleOrDefault();
            return(matchingOperation != null);
        }
        public static async Task <IExchange[]> InitializeEngine(bool isSimulation = true)
        {
            IList <Exchange> exchangeModels = null;
            IList <Setting>  settings       = null;
            List <IExchange> integrations   = null;

            // Get all exchangeModels. We need them to construct the integrations.
            using (var ctx = new RBBotContext())
            {
                // Load the exchanges and all the stuff associated with them
                exchangeModels = ctx.Exchanges
                                 .Include(x => x.ExchangeState)
                                 .Include(x => x.Settings)
                                 .Include(x => x.TradeAccounts)
                                 .Include(x => x.ExchangeTradePairs.Select(y => y.ExchangeTradePairState))
                                 .Include(x => x.ExchangeTradePairs.Select(y => y.TradePair).Select(z => z.FromCurrency))
                                 .Include(x => x.ExchangeTradePairs.Select(y => y.TradePair).Select(z => z.ToCurrency))
                                 .Where(x => x.ExchangeState.Code != "OFF") // Don't get offline exchanges!
                                 .ToList();

                // Get / cache the settings.
                settings = ctx.Settings.ToList();


                // Now since I'm lazy, i first put setting unencrypted in db, and then encrypt them here.
                if (settings.Where(x => x.IsEncrypted == false && x.ShouldBeEncrypted == true).Any(x => { x.EncryptSetting(); return(true); }))
                {
                    ctx.SaveChanges();
                }

                // Now initialize the setting helper with all settings!
                SettingHelper.InitializeSettings(settings.ToArray());

                // Initialize system settings.
                SystemSetting.LoadSystemSettings(ctx);


                // Initialize all exchanges and their integrations.
                var ccExchangeIds = settings.Where(x => x.Name == "ReadFromCryptoCompare" && x.Value.ToLower() == "true").Select(x => x.ExchangeId).ToList();
                var ccExchanges   = exchangeModels.Where(x => ccExchangeIds.Contains(x.Id)).ToList();

                integrations = new List <Exchanges.IExchange>();
                integrations.Add(new CryptoCompareIntegration(ccExchanges.ToArray()));
                integrations.Add(new BitflyerIntegration(new[] { exchangeModels.Single(x => x.Name == "Bitflyer") }));
                integrations.Add(new GDAXIntegration(new[] { exchangeModels.Single(x => x.Name == "GDAX") }));
                //integrations.Add(new OKCoinComIntegration(priceObservers, new[] { exchangeModels.Single(x => x.Name == "OKCoin.com") }));
                //integrations.Add(new OKCoinCNIntegration(priceObservers, new[] { exchangeModels.Single(x => x.Name == "OKCoin.cn") }));

                integrations.Add(new PoloniexIntegration(exchangeModels.Single(x => x.Name == "Poloniex")));
                integrations.Add(new KrakenIntegration(exchangeModels.Single(x => x.Name == "Kraken")));



                // Cache other lookups
                TradeOpportunityRequirementType.RequirementTypes = ctx.TradeOpportunityRequirementTypes.ToArray();
                TradeOpportunityState.States = ctx.TradeOpportunityStates.ToArray();
                TradeOpportunityType.Types   = ctx.TradeOpportunityTypes.ToArray();

                // Initialize the price cache;
                TradePriceIndex.Initialize(exchangeModels.ToArray(), ctx.TradePairs.ToArray());



                // Synchronize all the trading accounts.
                var tradingExchanges = integrations.Where(x => x is IExchangeTrader).Select(x => x as IExchangeTrader).ToList();
                foreach (var te in tradingExchanges)
                {
                    te.Exchange.TradingIntegration = te; // Set the trading integration.
                    await SynchronizeAccounts(te, ctx, isSimulation);
                }
                await ctx.SaveChangesAsync();
            }

            var readerExchanges = integrations.Where(x => x is IExchangePriceReader).Select(x => x as IExchangePriceReader).ToList();

            foreach (var e in readerExchanges)
            {
                Task.Run(async() => e.InitializeExchangePriceProcessingAsync());
            }

            // Return list of discovered integrations. These will be used to observe the the pricing data.
            return(integrations.ToArray());
        }
Exemple #34
0
 public Task <Order> GetOrderByIdAsync(string id)
 {
     return(Task.FromResult(_orders.Single(o => Equals(o.Id, id))));
 }
        public async Task<IList<BuildUpdate>> CheckForUpdatedBuilds(IList<SubscribedBuild> subscribedBuilds)
        {
            List<List<SubscribedBuild>> groupedBuilds = subscribedBuilds.GroupBy(b => new
            {
                b.AccountDetails.AccountName,
                b.AccountDetails.ProjectId
            })
            .Select(grp => grp.ToList())
            .ToList();

            var updates = new List<BuildUpdate>();

            foreach (List<SubscribedBuild> groupedBuild in groupedBuilds)
            {
                IList<Build> buildsForAccount =
                    await
                        _vsoClient.GetBuilds(groupedBuild.First().AccountDetails,
                            groupedBuild.Select(g => g.BuildDefinitionId).ToList());
            
                List<List<Build>> buildsByDefinition = buildsForAccount
                    .GroupBy(b => b.BuildDefinitionId)
                    .Select(grp => grp.ToList())
                    .ToList();

                foreach (List<Build> buildList in buildsByDefinition)
                {
                    if (!buildList.Any()) continue;
                    
                    SubscribedBuild subscribedBuildToUpdate = subscribedBuilds.Single(sb => sb.BuildDefinitionId == buildList.First().BuildDefinitionId);
                    updates.AddRange(CheckForUpdateInternal(buildList, subscribedBuildToUpdate));
                }
            }

            SaveSubscribedBuilds(subscribedBuilds);

            if (!GetNotifyOnStart())
            {
                updates.RemoveAll(u => u.Result == null);
            }

            if (!GetNotifyOnFinish())
            {
                updates.RemoveAll(u => u.Result != null);
            }

            return updates;
        }
Exemple #36
0
 public Item GetItem(string name)
 {
     return(_items.Single(o => name.Equals(o.Name)));
 }
Exemple #37
0
        public PieceRequest PickPiece(IPieceRequester peer, BitField available, IReadOnlyList <IPieceRequester> otherPeers)
        {
            IList <PieceRequest> bundle = PickPiece(peer, available, otherPeers, 1);

            return(bundle?.Single());
        }
 public Task <User> GetUserByIdAsync(int id)
 {
     return(Task.FromResult(_users.Single(u => Equals(u.Id, id))));
 }
Exemple #39
0
 private QueryNode MergeResultsIntoQueryNode(IList<QueryConditionNodeResult> mergedLeafNodes, QueryNode originalQueryNode)
 {
     if (originalQueryNode is QueryGroupNode) {
         var qng = originalQueryNode as QueryGroupNode;
         for (var i = 0; i < qng.Nodes.Count; ++i) {
             if (qng.Nodes[i] is QueryGroupNode) {
                 qng.Nodes[i] = MergeResultsIntoQueryNode(mergedLeafNodes, qng.Nodes[i]);
             } else {
                 var qnr = qng.Nodes[i] as QueryConditionNode;
                 qng.Nodes[i] = mergedLeafNodes.Single(mn => mn.Id == qnr.Id);
             }
         }
         return qng;
     } else {
         return mergedLeafNodes.Single(mn => mn.Id == (originalQueryNode as QueryConditionNode).Id);
     }
 }
 public Task <Order> GetOrderByIDAsync(string id)
 {
     return(Task.FromResult(_orders.Single(x => Equals(x.Id))));
 }
        public void SetUpTests()
        {
            _newItem = GetProduct();
            _allProducts = GetProducts();

            // Mock repository
            _mockProductRepo = new Mock<IProductRepository>();

            // Get
            _mockProductRepo.Setup(c => c.GetAll()).Returns(_allProducts);

            // GetById
            _mockProductRepo
                .Setup(mr => mr.FindById(It.IsAny<int>()))
                .Returns((int i) => _allProducts.Single(x => x.ID == i));

            _service = new ProductService(
                    CompositionService,
                    _mockProductRepo.Object
                );
        }
 public virtual Task <T> GetAsync(int id)
 => Task.FromResult(Data.Single(x => x.Id == id));
        public string GenerateManifest(string dlcName, IList<Arrangement> arrangements, SongInfo songInfo, Platform platform)
        {
            var manifest = Manifest;
            manifest.Entries = new Dictionary<string, Dictionary<string, Attributes>>();
            bool firstarrangset = false;

            Arrangement vocal = null;
            if (arrangements.Any<Arrangement>(a => a.ArrangementType == Sng.ArrangementType.Vocal))
                vocal = arrangements.Single<Arrangement>(a => a.ArrangementType == Sng.ArrangementType.Vocal);

            var manifestFunctions = new ManifestFunctions(platform.version);
            var songPartition = new SongPartition();

            foreach (var x in arrangements)
            {
                var isVocal = x.ArrangementType == Sng.ArrangementType.Vocal;
                var song = (isVocal) ? null : Song.LoadFromFile(x.SongXml.File);

                var attribute = new Attributes();
                attribute.AlbumArt = String.Format("urn:llid:{0}", AggregateGraph.AlbumArt.LLID);
                attribute.AlbumNameSort = attribute.AlbumName = songInfo.Album;
                attribute.ArrangementName = x.Name.ToString();
                attribute.ArtistName = songInfo.Artist;
                attribute.ArtistNameSort = songInfo.ArtistSort;
                attribute.AssociatedTechniques = new List<string>();
                //Should be 51 for bass, 49 for vocal and guitar
                attribute.BinaryVersion = x.ArrangementType == Sng.ArrangementType.Bass ? 51 : 49;
                attribute.BlockAsset = String.Format("urn:emergent-world:{0}", AggregateGraph.XBlock.Name);
                attribute.ChordTemplates = null;
                attribute.DISC_DLC_OTHER = "Disc";
                attribute.DisplayName = songInfo.SongDisplayName;
                attribute.DLCPreview = false;
                attribute.EffectChainMultiplayerName = string.Empty;
                attribute.EffectChainName = isVocal ? "" : (dlcName + "_" + x.ToneBase == null ? "Default" : x.ToneBase.Replace(' ', '_'));
                attribute.EventFirstTimeSortOrder = 9999;
                attribute.ExclusiveBuild = new List<object>();
                attribute.FirstArrangementInSong = false;
                if (isVocal && !firstarrangset)
                {
                    firstarrangset = true;
                    attribute.FirstArrangementInSong = true;
                }
                attribute.ForceUseXML = true;
                attribute.Tag = "PLACEHOLDER Tag";
                attribute.InputEvent = isVocal ? "Play_Tone_Standard_Mic" : "Play_Tone_";
                attribute.IsDemoSong = false;
                attribute.IsDLC = true;
                attribute.LastConversionDateTime = "";
                int masterId = isVocal ? 1 : x.MasterId;
                attribute.MasterID_PS3 = masterId;
                attribute.MasterID_Xbox360 = masterId;
                attribute.MaxPhraseDifficulty = 0;
                attribute.PersistentID = x.Id.ToString().Replace("-", "").ToUpper();
                attribute.PhraseIterations = new List<PhraseIteration>();
                attribute.Phrases = new List<Phrase>();
                attribute.PluckedType = x.PluckedType == Sng.PluckedType.Picked ? "Picked" : "Not Picked";
                attribute.RelativeDifficulty = isVocal ? 0 : song.Levels.Count();
                attribute.RepresentativeArrangement = false;
                attribute.Score_MaxNotes = 0;
                attribute.Score_PNV = 0;
                attribute.Sections = new List<Section>();
                attribute.Shipping = true;
                attribute.SongAsset = String.Format("urn:llid:{0}", x.SongFile.LLID);
                attribute.SongEvent = String.Format("Play_{0}", dlcName);
                attribute.SongKey = dlcName;
                attribute.SongLength = 0;
                attribute.SongName = songInfo.SongDisplayName;
                attribute.SongNameSort = songInfo.SongDisplayNameSort;
                attribute.SongXml = String.Format("urn:llid:{0}", x.SongXml.LLID);
                attribute.SongYear = songInfo.SongYear;
                attribute.TargetScore = 0;
                attribute.ToneUnlockScore = 0;
                attribute.TwoHandTapping = false;
                attribute.UnlockKey = "";
                attribute.Tuning = x.Tuning;
                attribute.VocalsAssetId = x.ArrangementType == Sng.ArrangementType.Vocal ? "" : (vocal != null) ? String.Format("{0}|GRSong_{1}", vocal.Id, vocal.Name) : "";
                attribute.ChordTemplates = new List<ChordTemplate>();
                manifestFunctions.GenerateDynamicVisualDensity(attribute, song, x);

                if (!isVocal)
                {
                    #region "Associated Techniques"

                    attribute.PowerChords = song.HasPowerChords();
                    if (song.HasPowerChords()) AssociateTechniques(x, attribute, "PowerChords");
                    attribute.BarChords = song.HasBarChords();
                    if (song.HasBarChords()) AssociateTechniques(x, attribute, "BarChords");
                    attribute.OpenChords = song.HasOpenChords();
                    if (song.HasOpenChords()) AssociateTechniques(x, attribute, "ChordIntro");
                    attribute.DoubleStops = song.HasDoubleStops();
                    if (song.HasDoubleStops()) AssociateTechniques(x, attribute, "DoubleStops");
                    attribute.Sustain = song.HasSustain();
                    if (song.HasSustain()) AssociateTechniques(x, attribute, "Sustain");
                    attribute.Bends = song.HasBends();
                    if (song.HasBends()) AssociateTechniques(x, attribute, "Bends");
                    attribute.Slides = song.HasSlides();
                    if (song.HasSlides()) AssociateTechniques(x, attribute, "Slides");
                    attribute.Tremolo = song.HasTremolo();
                    if (song.HasTremolo()) AssociateTechniques(x, attribute, "Tremolo");
                    attribute.SlapAndPop = song.HasSlapAndPop();
                    if (song.HasSlapAndPop()) AssociateTechniques(x, attribute, "Slap");
                    attribute.Harmonics = song.HasHarmonics();
                    if (song.HasHarmonics()) AssociateTechniques(x, attribute, "Harmonics");
                    attribute.PalmMutes = song.HasPalmMutes();
                    if (song.HasPalmMutes()) AssociateTechniques(x, attribute, "PalmMutes");
                    attribute.HOPOs = song.HasHOPOs();
                    if (song.HasHOPOs()) AssociateTechniques(x, attribute, "HOPOs");
                    attribute.FretHandMutes = song.HasFretHandMutes();
                    if (song.HasFretHandMutes()) AssociateTechniques(x, attribute, "FretHandMutes");
                    attribute.DropDPowerChords = song.HasDropDPowerChords();
                    if (song.HasDropDPowerChords()) AssociateTechniques(x, attribute, "DropDPowerChords");
                    attribute.Prebends = song.HasPrebends();
                    if (song.HasPrebends()) AssociateTechniques(x, attribute, "Prebends");
                    attribute.Vibrato = song.HasVibrato();
                    if (song.HasVibrato()) AssociateTechniques(x, attribute, "Vibrato");

                    //Bass exclusive
                    attribute.TwoFingerPlucking = song.HasTwoFingerPlucking();
                    if (song.HasTwoFingerPlucking()) AssociateTechniques(x, attribute, "Plucking");
                    attribute.FifthsAndOctaves = song.HasFifthsAndOctaves();
                    if (song.HasFifthsAndOctaves()) AssociateTechniques(x, attribute, "Octave");
                    attribute.Syncopation = song.HasSyncopation();
                    if (song.HasSyncopation()) AssociateTechniques(x, attribute, "Syncopation");

                    #endregion

                    attribute.AverageTempo = songInfo.AverageTempo;
                    attribute.RepresentativeArrangement = true;
                    attribute.SongPartition = songPartition.GetSongPartition(x.Name, x.ArrangementType);
                    attribute.SongLength = (float)Math.Round((decimal)song.SongLength, 3, MidpointRounding.AwayFromZero); //rounded
                    attribute.LastConversionDateTime = song.LastConversionDateTime;
                    attribute.TargetScore = 100000;
                    attribute.ToneUnlockScore = 70000;
                    attribute.SongDifficulty = (float)song.PhraseIterations.Average(it => song.Phrases[it.PhraseId].MaxDifficulty);
                    manifestFunctions.GenerateChordTemplateData(attribute, song);
                    manifestFunctions.GeneratePhraseData(attribute, song);
                    manifestFunctions.GenerateSectionData(attribute, song);
                    manifestFunctions.GeneratePhraseIterationsData(attribute, song, platform.version);
                }
                var attrDict = new Dictionary<string, Attributes> { { "Attributes", attribute } };
                manifest.Entries.Add(attribute.PersistentID, attrDict);
            }
            manifest.ModelName = "GRSong_Asset";
            manifest.IterationVersion = 2;
            return JsonConvert.SerializeObject(manifest, Formatting.Indented);
        }
Exemple #44
0
        public virtual async Task DefaultProjectDtoControllersProviderShouldFindODataOperationParametersCorrectly()
        {
            const string sourceCodeOfDtoControllerWithActionAndParameter = @"
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.OData;
using Bit.Tests.Model.DomainModels;
using Bit.OData.ODataControllers;

namespace Bit.OData.ODataControllers
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public sealed class ActionAttribute : Attribute
    {

    }
}

public interface IDto {
}

public class TestModel : IDto {
}

public class DtoController<TDto>
    where TDto : IDto
{

}

[System.ComponentModel.DataAnnotations.Schema.ComplexType]
public class ComplexObj3
{
    public virtual string Name { get; set; }
}

namespace Bit.Tests.Api.ApiControllers
{
    public class TestController : DtoController<TestModel>
    {

        public class DoParameters
        {
            public virtual string Parameter1 { get; set; }
            public virtual string Parameter1 { get; set; }
        }

        [Action]
        public virtual async Task Do(DoParameters parameters)
        {

        }

        [Action]
        public virtual async System.Threading.Tasks.Task<int[]> Do1()
        {
        }

        public class Do3Parameters
        {
            public virtual int[] values { get; set; }
        }

        [Action]
        public virtual async System.Threading.Tasks.Task<ComplexObj3[]> Do3(Do3Parameters parameters)
        {
        }
    }
}
";

            IList <DtoController> controllers = await new DefaultProjectDtoControllersProvider()
                                                .GetProjectDtoControllersWithTheirOperations(CreateProjectFromSourceCodes(sourceCodeOfDtoControllerWithActionAndParameter));

            Assert.AreEqual("Edm.Int32", controllers.Single()
                            .Operations.ElementAt(1)
                            .ReturnType.GetEdmElementTypeName());

            Assert.AreEqual("ComplexObj3", controllers.Single()
                            .Operations.ElementAt(2)
                            .ReturnType.GetEdmElementTypeName());

            Assert.AreEqual("Edm.Int32", controllers.Single()
                            .Operations.ElementAt(2)
                            .Parameters.Single().Type.GetEdmElementTypeName());
        }
Exemple #45
0
        public BuildingModel(SiteContext context, string categoryId, string subCategoryId, int contentType, string articleId=null)
            : base(context, null)
        {
            _categoryId = categoryId;
            _subCategoryId = subCategoryId;
            _contentId = subCategoryId ?? categoryId;

            _buildings = context.Building.Include("Children").Include("BuildingItems").Where(b => b.ContentType == contentType).ToList();

            if (categoryId != null)
                if (subCategoryId == null)
                    ParentTitle = _buildings.Single(t => t.CategoryLevel == 0).Title;

            Building = _buildings.FirstOrDefault(t => t.Name == _contentId) ?? _buildings.First(t => t.CategoryLevel == 0);




            if (!HttpContext.Current.Request.IsAuthenticated)
            {
                if (Building.CategoryLevel == 0 && !Building.Active)
                {
                    Building = _buildings.Where(t => t.Parent == null && t.CategoryLevel != 0).Where(t => t.SortOrder == _buildings.Min(c => (int?)c.SortOrder)).FirstOrDefault();
                    //Building = _buildings.FirstOrDefault(t => t.Parent == null && t.CategoryLevel != 0);
                    if (Building != null)
                    {
                        ActiveCategoryNotFound = true;
                        RedirectCategoryId = Building.Name;
                        return;
                    }
                }
                if (Building != null)
                {
                    if (Building.CategoryLevel != 0 && !Building.Active && Building.Children.Any())
                    {
                        ActiveCategoryNotFound = true;
                        RedirectCategoryId = Building.Name;
                        RedirectSubCategoryId = Building.Children.First().Name;
                        return;
                    }
                }
            }

            if (Building != null)
            {
                if (Building.Parent != null)
                {
                    ParentTitle = Building.Parent.Title;
                }
                SeoDescription = Building.SeoDescription;
                SeoKeywords = Building.SeoKeywords;
            }
            GetMenu();
            if (contentType == 1)
            {
                BuildingObjects = context.BuildingObj.ToList();
            }


            if (articleId != null)
                Article = context.Article.First(a => a.Name == articleId);
        }
Exemple #46
0
 public Trivia GetTrivia(int triviaId)
 {
     return(_data.Single(t => t.Id == triviaId));
 }
Exemple #47
0
        public void Remove(Guid id)
        {
            var productToRemove = products.Single(product => product.Id.Equals(id));

            products.Remove(productToRemove);
        }
Exemple #48
0
 public static T Single <T>(this IList <ISensor> sensorList) where T : ISensor
 {
     return((T)sensorList.Single(m => string.Equals(m.Device, typeof(T).Name, StringComparison.OrdinalIgnoreCase)));
 }
        /// <summary>
        /// Syncs selected roles in front-end to user roles in database
        /// </summary>
        /// <param name="checkboxes">Roles selected in frontend</param>
        /// <param name="roles">Roles already assigned to user</param>
        private void SyncRoles(IList<RoleCheckbox> checkboxes, IList<Role> roles)
        {
            List<Role> selectedRoles = new List<Role>();

            foreach (Role role in DatabaseManager.Session.Query<Role>().ToList())
            {
                // Get the checkbox that matches the role id
                RoleCheckbox checkbox = checkboxes.Single(c => c.Id == role.Id);

                if (checkbox.IsChecked)
                {
                    checkbox.RoleName = role.RoleName;
                    selectedRoles.Add(role);
                }
            }

            // Add roles which were selected and not contained already in user roles
            foreach (var toAdd in selectedRoles.Where(r => !roles.Contains(r)).ToList())
                roles.Add(toAdd);

            // Remove roles which were de-selected
            foreach (var toRemove in roles.Where(r => !selectedRoles.Contains(r)).ToList())
                roles.Remove(toRemove);
        }
Exemple #50
0
 public Region Get(int itemId)
 {
     return(_Regions.Single(r => r.RegionId == itemId));
 }
Exemple #51
0
            public void OverrideData(Reign.Area area, IList<Reign.Province> provs, IList<UnitData> data)
            {
                var prov = provs.Single(p => p.No == _provNo);
                area.Province = prov;

                area.NumCity100 = _nCity;
                area.NumRoad100 = _nRoad;
                area.NumWall100 = _nWall;

                area.Units.Clear();
                area.Units.AddRange(_units.Select(u => u.ToUnit(data)));
            }
        public void Save_ValidEvent_EventCanBeRetreived()
        {
            // Arrange
            var correlationIdHelper = new CorrelationIdHelper(new ThreadedContextItemCollectionFactory());

            correlationIdHelper.SetCorrelationId(Guid.NewGuid());
            var logger = new ConsoleLogger(new LoggerSettings(), correlationIdHelper);

            try
            {
                // Arrange
                var connectionStringFactory = new TestMongoEventStoreConnectionStringFactory();
                TestMongoEventStoreConnectionStringFactory.DatabaseName = string.Format("Test-{0}", new Random().Next(0, 9999));

                var eventStore = new MongoDbEventStore <Guid>(new MongoDbEventBuilder <Guid>(), new MongoDbEventDeserialiser <Guid>(), logger, connectionStringFactory, new ConfigurationManager());

                var event1 = new TestEvent
                {
                    Rsn           = Guid.NewGuid(),
                    Id            = Guid.NewGuid(),
                    CorrelationId = correlationIdHelper.GetCorrelationId(),
                    Frameworks    = new List <string> {
                        "Test 1"
                    },
                    TimeStamp = DateTimeOffset.UtcNow
                };
                var event2 = new TestEvent
                {
                    Rsn           = Guid.NewGuid(),
                    Id            = Guid.NewGuid(),
                    CorrelationId = correlationIdHelper.GetCorrelationId(),
                    Frameworks    = new List <string> {
                        "Test 2"
                    },
                    TimeStamp = DateTimeOffset.UtcNow
                };

                // Act
                eventStore.Save <TestEvent>(event1);
                eventStore.Save <TestEvent>(event2);

                // Assert
                var timer = new Stopwatch();
                IList <IEvent <Guid> > events = eventStore.Get <TestEvent>(event1.Id).ToList();
                timer.Stop();
                Console.WriteLine("Load one operation took {0}", timer.Elapsed);
                Assert.AreEqual(1, events.Count);
                Assert.AreEqual(event1.Id, events.Single().Id);
                Assert.AreEqual(event1.Frameworks.Single(), events.Single().Frameworks.Single());

                timer.Restart();
                events = eventStore.Get <TestEvent>(event2.Id).ToList();
                timer.Stop();
                Console.WriteLine("Load one operation took {0}", timer.Elapsed);
                Assert.AreEqual(1, events.Count);
                Assert.AreEqual(event2.Id, events.Single().Id);
                Assert.AreEqual(event2.Frameworks.Single(), events.Single().Frameworks.Single());

                timer.Restart();
                IList <EventData> correlatedEvents = eventStore.Get(event1.CorrelationId).ToList();
                timer.Stop();
                Console.WriteLine("Load several correlated operation took {0}", timer.Elapsed);
                Assert.AreEqual(2, correlatedEvents.Count);
            }
            finally
            {
                // Clean-up
                TestMongoDataStoreConnectionStringFactory.DatabaseName = TestMongoEventStoreConnectionStringFactory.DatabaseName;
                var factory = new TestMongoDbDataStoreFactory(logger, new TestMongoDataStoreConnectionStringFactory());
                IMongoCollection <TestEvent> collection = factory.GetTestEventCollection();
                collection.Database.Client.DropDatabase(TestMongoDataStoreConnectionStringFactory.DatabaseName);
            }
        }
Exemple #53
0
        private static void PopulateStorage(IList<Tuple<IOverlayNodeService, IOverlayStorageService>> p2pServices, ServiceDescription[] serviceDescriptions, int? avgRegistrationsPerSecond)
        {
            var newStats = new Statistics();

            System.Console.WriteLine("Populating the data storage...");
            DbMgr.Clear();

            newStats.NodesCount = p2pServices.Count;
            newStats.AVPairsCount = serviceDescriptions.SelectMany(x => x.Data.Select(y => y.AttrValue)).Count();
            newStats.AvgRegistrationsPerSecond = avgRegistrationsPerSecond;

            foreach (var srv in serviceDescriptions) {
                srv.OwnerNode = p2pServices.Select(p => p.Item1.Node).ElementAt(Rnd.Next(p2pServices.Count()));

                var ownerNodeStorageSrv = p2pServices.Single(s => s.Item2.Node.Equals(srv.OwnerNode)).Item2;
                var putSrvResult = ownerNodeStorageSrv.PutService(srv);
                if (!putSrvResult) {
                    newStats.ServiceRegistrationFailsCount++;
                }
                if (avgRegistrationsPerSecond.HasValue) {
                    Thread.Sleep((int)Math.Round(GetPoissonInterarrivalDelay(avgRegistrationsPerSecond.Value) * 1000));
                }
            }

            var allServices = new Dictionary<long, ServiceDescription[]>();
            foreach (var storageSrv in p2pServices.Select(x => x.Item2)) {
                allServices.Add(storageSrv.Node.Id, storageSrv.GetServicesLocal());
            }

            newStats.NodesOverAVThresholdCount = allServices.Count(x => x.Value.Any(y => y.StorageState == ServiceStorageState.Failed));

            Stats.Add(newStats);
            System.Console.WriteLine("Populating the data storage - Finished");
        }
 public Supplier SupplierIdentifiedAs(string identificationType, string identificationNumber)
 {
     return(_suppliers.Single(supplier => supplier.IsIdentifiedAs(identificationType, identificationNumber)));
 }
        internal static async Task<IEnumerable<CodeActionOperation>> VerifyInputsAndGetOperationsAsync(
            int index, IList<CodeAction> actions, CodeActionPriority? priority = null)
        {
            Assert.NotNull(actions);
            if (actions.Count == 1)
            {
                var suppressionAction = actions.Single() as SuppressionCodeAction;
                if (suppressionAction != null)
                {
                    actions = suppressionAction.GetCodeActions().ToList();
                }
            }

            Assert.InRange(index, 0, actions.Count - 1);

            var action = actions[index];
            if (priority != null)
            {
                Assert.Equal(priority.Value, action.Priority);
            }
            return await action.GetOperationsAsync(CancellationToken.None);
        }
 public async Task <Domain.Models.Task> GetTaskByIdAsync(int id)
 {
     return(await Task.FromResult(_tasks.Single(o => Equals(o.Id, id))));
 }
        public IHttpActionResult Get(int key)
        {
            Employee employee = Employees.Single(e => e.Id == key);

            return(Ok(employee));
        }
Exemple #58
0
 public IHttpActionResult Get(int key)
 {
     return(Ok(_employees.Single(e => e.ID == key)));
 }
 public static Cell GetCell(this IList <Cell> cells, int i, int j)
 {
     return(cells.Single(x => x.I == i && x.J == j));
 }
        /// <summary>
        /// Try to resolve a function from the given inputs.
        /// </summary>
        /// <param name="identifier">The identifier of the function that we're trying to find</param>
        /// <param name="parameterNames">the names of the parameters to search for.</param>
        /// <param name="model">the model to use to look up the operation import</param>
        /// <param name="matchingOperationImport">The single matching function found.</param>
        /// <param name="resolver">Resolver to be used.</param>
        /// <returns>True if a function was matched, false otherwise. Will throw if the model has illegal operation imports.</returns>
        internal static bool ResolveOperationImportFromList(string identifier, IList <string> parameterNames, IEdmModel model, out IEdmOperationImport matchingOperationImport, ODataUriResolver resolver)
        {
            IList <IEdmOperationImport> candidateMatchingOperationImports         = null;
            IList <IEdmActionImport>    foundActionImportsWhenLookingForFunctions = new List <IEdmActionImport>();

            try
            {
                if (parameterNames.Count > 0)
                {
                    // In this case we have to return a function so filter out actions because the number of parameters > 0.
                    candidateMatchingOperationImports = resolver.ResolveOperationImports(model, identifier).RemoveActionImports(out foundActionImportsWhenLookingForFunctions).FilterFunctionsByParameterNames(parameterNames, resolver.EnableCaseInsensitive).Cast <IEdmOperationImport>().ToList();
                }
                else
                {
                    candidateMatchingOperationImports = resolver.ResolveOperationImports(model, identifier).ToList();
                }
            }
            catch (Exception exc)
            {
                if (!ExceptionUtils.IsCatchableExceptionType(exc))
                {
                    throw;
                }

                throw new ODataException(ODataErrorStrings.FunctionOverloadResolver_FoundInvalidOperationImport(identifier), exc);
            }

            if (foundActionImportsWhenLookingForFunctions.Count > 0)
            {
                throw ExceptionUtil.CreateBadRequestError(ODataErrorStrings.RequestUriProcessor_SegmentDoesNotSupportKeyPredicates(identifier));
            }

            // If any of the things returned are an action, it better be the only thing returned, and there can't be parameters in the URL
            if (candidateMatchingOperationImports.Any(f => f.IsActionImport()))
            {
                if (candidateMatchingOperationImports.Count > 1)
                {
                    if (candidateMatchingOperationImports.Any(o => o.IsFunctionImport()))
                    {
                        throw new ODataException(ODataErrorStrings.FunctionOverloadResolver_MultipleOperationImportOverloads(identifier));
                    }
                    else
                    {
                        throw new ODataException(ODataErrorStrings.FunctionOverloadResolver_MultipleActionImportOverloads(identifier));
                    }
                }

                if (parameterNames.Count() != 0)
                {
                    throw ExceptionUtil.CreateBadRequestError(ODataErrorStrings.RequestUriProcessor_SegmentDoesNotSupportKeyPredicates(identifier));
                }

                matchingOperationImport = candidateMatchingOperationImports.Single();
                return(true);
            }

            // If parameter count is zero and there is one function import whoese parameter count is zero, return this function import.
            if (candidateMatchingOperationImports.Count > 1 && parameterNames.Count == 0)
            {
                candidateMatchingOperationImports = candidateMatchingOperationImports.Where(operationImport => operationImport.Operation.Parameters.Count() == 0).ToList();
            }

            if (candidateMatchingOperationImports.Count == 0)
            {
                matchingOperationImport = null;
                return(false);
            }

            // If more than one overload matches, try to select based on optional parameters
            if (candidateMatchingOperationImports.Count > 1)
            {
                candidateMatchingOperationImports = candidateMatchingOperationImports.FindBestOverloadBasedOnParameters(parameterNames).ToList();
            }

            if (candidateMatchingOperationImports.Count > 1)
            {
                throw new ODataException(ODataErrorStrings.FunctionOverloadResolver_MultipleOperationImportOverloads(identifier));
            }

            matchingOperationImport = candidateMatchingOperationImports.Single();

            return(matchingOperationImport != null);
        }