Exemplo n.º 1
1
        public IObservable<Unit> InsertAll(IList<Session> sessions)
        {
            return blob.GetOrCreateObject<IList<Session>>(KEY_SESSIONS, () => new List<Session>())
                .Select(source =>
                    {
                        var checkedSessions = sessions.Where(session => session.IsChecked).ToDictionary(session => session.id);
                        var merged = sessions.Union(source);

                        return merged.Select(session =>
                            {
                                session.IsChecked = checkedSessions.ContainsKey(session.id);
                                return session;
                            });
                    })
                .SelectMany(merged =>
                    {
                        return Observable.Merge(
                            merged.ToObservable()
                                .Select(session => session.category)
                                .ToList().Distinct()
                                .SelectMany(categoryDao.InsertAll),
                            merged.ToObservable()
                                .Select(session => session.place)
                                .ToList().Distinct()
                                .SelectMany(placeDao.InsertAll),
                            blob.InsertObject(KEY_SESSIONS, merged)
                        );
                    });
        }
Exemplo n.º 2
1
 /// <summary>
 /// Initialises the list of profiles
 /// </summary>
 private void InitialiseProfiles()
 {
     _existingProfiles = _authService.GetProfiles();
     foreach (var i in _existingProfiles.Union(new[] { NewProfileItem }))
     {
         cbbProfiles.Items.Add(i);
     }
     cbbProfiles.SelectedIndex = 0;
 }
Exemplo n.º 3
1
 public IObservable<Unit> InsertAll(IList<Category> categories)
 {
     return blob.GetOrCreateObject<IList<Category>>(KEY_CATEGORIES, () => new List<Category>())
         .Select(source =>
             {
                 return categories.Union(source);
             })
         .SelectMany(merged => blob.InsertObject(KEY_CATEGORIES, merged));
 }
        public void Subscribe(string client, IList<string> messageTypes)
        {
            using (var session = _sessionFactory.OpenSession())
            {
                var existingSubscription = session.AsQueryable<Subscription>().SingleOrDefault(x => x.SubscriberEndpoint == client) 
                    ?? new Subscription { SubscriberEndpoint = client, MessageTypes = new List<string>() };

                var messageTypesToSubscribe = messageTypes.Union(existingSubscription.MessageTypes).ToList();

                existingSubscription.MessageTypes = messageTypesToSubscribe;
                session.Store(existingSubscription);
                session.Commit();
            }
        }
 public byte[] Serialize(IList<HeaderInfo> headers)
 {
   if (CurrentSagaIds.OutgoingIds != null && CurrentSagaIds.OutgoingIds.Length > 0)
   {
     var value = String.Join(",", CurrentSagaIds.OutgoingIds.Select(x => x.ToString()).ToArray());
     var header = new HeaderInfo()
     {
       Key = "machine.sagas",
       Value = value
     };
     _log.Debug("Serializing: " + value);
     return _serializer.Serialize(headers.Union(new[] { header }).ToList());
   }
   return _serializer.Serialize(headers);
 }
Exemplo n.º 6
1
    protected void Page_Init(object sender, EventArgs e)
    {
        #region 設定搜尋控制項目

        plSearch.Controls.Add(new LiteralControl("<br />"));

        Search_Date sd = new Search_Date(this.ViewState, plSearch, "日期範圍", "selectDate", "sCreatetime", "tbStartDate", "tbEndDate");
        SearchItems = SearchItems.Union(sd.SearchItems).ToList();
        Search_Checkbox sc = new Search_Checkbox(this.ViewState, plSearch, "僅列出有效資料", "chksFBUID", "sFBUID");
        SearchItems = SearchItems.Union(sc.SearchItems).ToList();
        st = new Search_Textfield(this.ViewState, plSearch, "sFBUID:", "tbsFBUID", "sFBUID", "sFBUID");
        SearchItems = SearchItems.Union(st.SearchItems).ToList();
        st = new Search_Textfield(this.ViewState, plSearch, "sFBDisplayName:", "tbsFBDisplayName", "sFBDisplayName", "sFBDisplayName");
        SearchItems = SearchItems.Union(st.SearchItems).ToList();
        st = new Search_Textfield(this.ViewState, plSearch, "sName:", "tbsName", "sName", "sName");
        SearchItems = SearchItems.Union(st.SearchItems).ToList();

        #endregion
    }
Exemplo n.º 7
1
        /// <summary>
        /// This method determins if straight flush of clubs combination is available 
        /// </summary>
        /// <param name="charactersCardsCollection">
        /// Player's cards
        /// </param>
        /// <param name="tableCardsCollection">
        /// All cards visible on the table
        /// </param>
        /// <param name="character">
        /// current player
        /// </param>
        /// <returns></returns>
        private bool CheckForStraightFlushOfClubs(IList<ICard> charactersCardsCollection,
            IList<ICard> tableCardsCollection, ICharacter character)
        {
            bool hasStraightFlush = false;

            List<ICard> joinedCardCollection = charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).ToList();

            List<ICard> straightFlushCardsCollection = joinedCardCollection.Where(c => c.Suit == CardSuit.Clubs).ToList();

            straightFlushCardsCollection = new List<ICard>(straightFlushCardsCollection.OrderByDescending(c => c.Rank));

            if (straightFlushCardsCollection.Count < 5)
            {
                return false;
            }
            else
            {
                straightFlushCardsCollection = straightFlushCardsCollection.Take(5).ToList();

                double power = 0;
                for (int i = 0; i < straightFlushCardsCollection.Count - 1; i++)
                {
                    if ((int)straightFlushCardsCollection[i].Rank - 1 != (int)straightFlushCardsCollection[i + 1].Rank)
                    {
                        return false;
                    }
                }

                if (straightFlushCardsCollection[0].Rank == CardRank.Ace)
                {
                    power = (int)straightFlushCardsCollection[0].Rank + BigStraightFlushBehaviourPower * 100;
                }

                else
                {
                    power = (int)straightFlushCardsCollection[0].Rank + LittleStraightFlushBehaviourPower * 100;
                }

                IList<ICard> theOtherCardsFromTheHandNotIncludedInTheCombination = joinedCardCollection.Where(x => !straightFlushCardsCollection.Contains(x)).ToList();

                if (character.CardsCombination == null || character.CardsCombination.Type < CombinationType.StraightFlush)
                {
                    character.CardsCombination = new Combination(
                        power,
                        CombinationType.StraightFlush,
                        LittleStraightFlushBehaviourPower,
                        straightFlushCardsCollection,
                        theOtherCardsFromTheHandNotIncludedInTheCombination);
                }

                hasStraightFlush = true;
            }

            return hasStraightFlush;
        }
Exemplo n.º 8
1
        /// <summary>
        /// Checks if the character has two pairs.
        /// </summary>
        /// <param name="charactersCardsCollection"></param>
        /// <param name="tableCardsCollection"></param>
        /// <param name="character"></param>
        /// <returns></returns>
        private bool CheckForTwoPairs(IList<ICard> charactersCardsCollection,
        IList<ICard> tableCardsCollection, ICharacter character)
        {
            bool hasOnePair = CheckForOnePair(charactersCardsCollection, tableCardsCollection, character, false);

            bool hasASecondPair = false;

            if (hasOnePair)
            {
                IList<ICard> nonCombinationCards = charactersCardsCollection.Union(tableCardsCollection).Where(x => !character.CardsCombination.CombinationCardsCollection.Contains(x) && x.IsVisible).ToList();

                IList<ICard> emptyCollection = new List<ICard>();

                hasASecondPair = CheckForOnePair(nonCombinationCards, emptyCollection, character, true);
            }
            return hasASecondPair;
        }
        /// <summary>
        /// Gets the full source code by applying an appropriate template based on the current <see cref="RoslynCodeTaskFactoryCodeType"/>.
        /// </summary>
        internal static string GetSourceCode(RoslynCodeTaskFactoryTaskInfo taskInfo, ICollection <TaskPropertyInfo> parameters)
        {
            if (taskInfo.CodeType == RoslynCodeTaskFactoryCodeType.Class)
            {
                return(taskInfo.SourceCode);
            }

            CodeTypeDeclaration codeTypeDeclaration = new CodeTypeDeclaration
            {
                IsClass        = true,
                Name           = taskInfo.Name,
                TypeAttributes = TypeAttributes.Public,
                Attributes     = MemberAttributes.Final
            };

            codeTypeDeclaration.BaseTypes.Add("Microsoft.Build.Utilities.Task");

            foreach (TaskPropertyInfo propertyInfo in parameters)
            {
                CreateProperty(codeTypeDeclaration, propertyInfo.Name, propertyInfo.PropertyType);
            }

            if (taskInfo.CodeType == RoslynCodeTaskFactoryCodeType.Fragment)
            {
                CodeMemberProperty successProperty = CreateProperty(codeTypeDeclaration, "Success", typeof(bool), true);

                CodeMemberMethod executeMethod = new CodeMemberMethod
                {
                    Name = "Execute",
                    // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags
                    Attributes = MemberAttributes.Override | MemberAttributes.Public,
                    ReturnType = new CodeTypeReference(typeof(Boolean))
                };
                executeMethod.Statements.Add(new CodeSnippetStatement(taskInfo.SourceCode));
                executeMethod.Statements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(null, successProperty.Name)));
                codeTypeDeclaration.Members.Add(executeMethod);
            }
            else
            {
                codeTypeDeclaration.Members.Add(new CodeSnippetTypeMember(taskInfo.SourceCode));
            }

            CodeNamespace codeNamespace = new CodeNamespace("InlineCode");

            codeNamespace.Imports.AddRange(DefaultNamespaces.Union(taskInfo.Namespaces, StringComparer.OrdinalIgnoreCase).Select(i => new CodeNamespaceImport(i)).ToArray());

            codeNamespace.Types.Add(codeTypeDeclaration);

            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

            codeCompileUnit.Namespaces.Add(codeNamespace);

            using (CodeDomProvider provider = CodeDomProvider.CreateProvider(taskInfo.CodeLanguage))
            {
                using (StringWriter writer = new StringWriter(new StringBuilder(), CultureInfo.CurrentCulture))
                {
                    provider.GenerateCodeFromCompileUnit(codeCompileUnit, writer, new CodeGeneratorOptions
                    {
                        BlankLinesBetweenMembers = true,
                        VerbatimOrder            = true
                    });

                    return(writer.ToString());
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Checks for a "High card" combination
        /// </summary>
        /// <param name="charactersCardsCollection"></param>
        /// <param name="tableCardsCollection"></param>
        /// <param name="character"></param>
        /// <returns></returns>
        private bool CheckForHighCard(IList<ICard> charactersCardsCollection, IList<ICard> tableCardsCollection, ICharacter character)
        {
            double power = Math.Max((double)charactersCardsCollection[0].Rank, (double)charactersCardsCollection[1].Rank);

            IList<ICard> joinedCardCollection = charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).OrderByDescending(x => x.Rank).ToList();

            IList<ICard> combinationCardsCollection = new List<ICard>();
            combinationCardsCollection.Add(joinedCardCollection[0]);

            IList<ICard> nonCombinationCards = joinedCardCollection.Where(x => !combinationCardsCollection.Contains(x)).ToList();

            RegisterCombination(character, power, combinationCardsCollection, nonCombinationCards, CombinationType.HighCard, Constants.HighCardBehaviourPower);

            return true;
        }
Exemplo n.º 11
0
        /// <summary>
        /// This method checks if the character has card combination "Flush"
        /// </summary>
        /// <param name="charactersCardsCollection">The collection of cards in the characters hand.</param>
        /// <param name="tableCardsCollection">The collection of cards on the table.</param>
        /// <param name="character">The character that holds the cards.</param>
        /// <returns><c>true</c> if the character has a Flush, <c>false</c> if they don't.</returns>
        private bool CheckForFlush(IList<ICard> charactersCardsCollection, IList<ICard> tableCardsCollection,
            ICharacter character)
        {
            List<ICard> joinedCardCollection =
                charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).ToList();

            bool hasFlush = false;
            int requiredCardsForFlush = 5;

            List<ICard> cardsThatMakeUpFlush = new List<ICard>();

            foreach (ICard card in joinedCardCollection)
            {
                List<ICard> sameSuitCardsCollection = joinedCardCollection.Where(x => x.Suit == card.Suit).ToList();

                if (sameSuitCardsCollection.Count >= requiredCardsForFlush)
                {
                    hasFlush = true;
                    cardsThatMakeUpFlush = sameSuitCardsCollection;
                    break;
                }
            }
            if (hasFlush)
            {
                List<ICard> tableCardsThatMakeUpFlush = cardsThatMakeUpFlush;

                tableCardsThatMakeUpFlush.RemoveAll(x => charactersCardsCollection.Contains(x));

                if (tableCardsThatMakeUpFlush.Count == requiredCardsForFlush)
                {
                    return CheckForFlushIfTableCardsMakeFlush(charactersCardsCollection, tableCardsThatMakeUpFlush, joinedCardCollection,
                        character);
                }
                else
                {
                    if (cardsThatMakeUpFlush.Count > requiredCardsForFlush)
                    {
                        int lowestCardInFlush = (int)cardsThatMakeUpFlush.Min(x => x.Rank);
                        cardsThatMakeUpFlush.RemoveAll(x => (int)x.Rank == lowestCardInFlush);
                    }

                    int highestCardInFlush = (int)cardsThatMakeUpFlush.Max(x => x.Rank);
                    double currentFlushBehaviourPower = Constants.LittleFlushBehaviourPower;

                    //Check if character has Ace in his hand that is part of the flush
                    //If they do -> the behaviour power is different (greater)
                    foreach (ICard card in charactersCardsCollection)
                    {
                        if (card.Suit == cardsThatMakeUpFlush[0].Suit && card.Rank == CardRank.Ace)
                        {
                            currentFlushBehaviourPower = Constants.BigFlushBehaviourPower;
                        }
                    }

                    double power = highestCardInFlush + currentFlushBehaviourPower * 100;
                    List<ICard> theOtherCardsFromTheHandNotIncludedInTheCombination =
                        joinedCardCollection.Where(x => !cardsThatMakeUpFlush.Contains(x)).ToList();

                    RegisterCombination(character, power, cardsThatMakeUpFlush, theOtherCardsFromTheHandNotIncludedInTheCombination, CombinationType.Flush, currentFlushBehaviourPower);
                }
            }
            return hasFlush;
        }
Exemplo n.º 12
0
        /// <summary>
        /// This method checks if the character has card combination "Full House"
        /// </summary>
        /// <param name="charactersCardsCollection">The collection of cards in the characters hand.</param>
        /// <param name="tableCardsCollection">The collection of cards on the table.</param>
        /// <param name="character">The character that holds the cards.</param>
        /// <returns><c>true</c> if the character has a Full House, <c>false</c> if they don't.</returns>
        private bool CheckForFullHouse(IList<ICard> charactersCardsCollection, IList<ICard> tableCardsCollection,
            ICharacter character)
        {
            bool hasFullHouse = false;

            IList<ICard> joinedCardCollection = charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).ToList();

            bool characterHasThreeOfAKind = CheckForThreeOfAKind(charactersCardsCollection, tableCardsCollection,
                character);

            IList<ICard> threeOfAKindCards = new List<ICard>();

            int threeOfAKindRank = -1;

            if (characterHasThreeOfAKind)
            {
                threeOfAKindRank = GetThreeOfAKindCardRank(charactersCardsCollection, tableCardsCollection);

                //removes the three-of-a-kind cards from the joinedCardCollection (hand+table cards)
                // and adds them to the threeOfAKindCards list
                for (int i = 0; i < joinedCardCollection.Count; i++)
                {
                    if ((int)joinedCardCollection[i].Rank == threeOfAKindRank)
                    {
                        threeOfAKindCards.Add(joinedCardCollection[i]);
                        joinedCardCollection.RemoveAt(i);
                        i--;
                    }
                }

                //checks if there is a pair in the remaining collection
                //if yes -> the player has a full house combination
                int maxPairRank = -1;
                foreach (ICard card in joinedCardCollection)
                {
                    IList<ICard> remainingEqualRankCards =
                        joinedCardCollection.Where(x => x.Rank == card.Rank).ToList();

                    if (remainingEqualRankCards.Count == 2)
                    {
                        hasFullHouse = true;

                        //This is a check for multiple pairs in the remaining cards
                        //If there is more than one pair, the highest one is taken
                        maxPairRank = Math.Max(maxPairRank, (int)card.Rank); //  take the one with the higher rank

                        IList<ICard> theOtherCardsFromTheHandNotIncludedInTheCombination =
                            joinedCardCollection.Where(x => x != remainingEqualRankCards[0]).ToList();

                        IList<ICard> fullHouseCards = threeOfAKindCards;
                        fullHouseCards = fullHouseCards.Union(remainingEqualRankCards).ToList();


                        double power = maxPairRank * 2 + FullHouseBehaviourPower * 100;

                        if (character.CardsCombination == null ||
                            character.CardsCombination.Type < CombinationType.FullHouse)
                        {
                            character.CardsCombination = new Combination(power, CombinationType.FullHouse, Constants.FullHouseBehaviourPower, fullHouseCards, theOtherCardsFromTheHandNotIncludedInTheCombination);
                        }

                    }
                }
            }

            return hasFullHouse;
        }
Exemplo n.º 13
0
        private IPagedList<MovimientoDTO> BusquedaYPaginado_Movimiento(IList<MovimientoDTO> lista, string sortOrder, string currentFilter, string searchString, int? page)
        {
            if (!String.IsNullOrEmpty(searchString))
            { searchString = searchString.ToLower(); }
            ViewBag.CurrentSort = sortOrder;

            ViewBag.vbFecha = sortOrder == "Fecha" ? "Fecha_desc" : "Fecha";
            ViewBag.vbTipo = sortOrder == "Tipo" ? "Tipo_desc" : "Tipo";
            ViewBag.vbDetalle = sortOrder == "Detalle" ? "Detalle_desc" : "Detalle";
            ViewBag.vbMonto = sortOrder == "Monto" ? "Monto_desc" : "Monto";
            ViewBag.vbCategoria = sortOrder == "Categoria" ? "Categoria_desc" : "Categoria";
            ViewBag.vbEntidad = sortOrder == "Entidad" ? "Entidad_desc" : "Entidad";
            ViewBag.vbDocumento = sortOrder == "Documento" ? "Documento_desc" : "Documento";
            ViewBag.vbUsuario = sortOrder == "Usuario" ? "Usuario_desc" : "Usuario";
            ViewBag.vbEstado = sortOrder == "Estado" ? "Estado_desc" : "Estado";

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            string tipoDato = "cadena";
            DateTime pTiempo;
            if (DateTime.TryParse(searchString, out pTiempo))
            {
                tipoDato = "tiempo";
                pTiempo = Convert.ToDateTime(searchString);
            }

            Decimal pDecimal;
            if (Decimal.TryParse(searchString, out pDecimal))
            {
                tipoDato = "numerico";
                pDecimal = Convert.ToDecimal(searchString);
            }

            if (!String.IsNullOrEmpty(searchString))
            {
                IList<MovimientoDTO> listaP;
                listaP = lista.Where(s => (s.NroOperacion.ToLower() ?? "").Contains(searchString)
                        || (s.NombreCategoria.ToLower() ?? "").Contains(searchString)
                        || (s.NombreEntidadR.ToLower() ?? "").Contains(searchString)
                        || (s.NumeroDocumento.ToLower() ?? "").Contains(searchString)
                        || (s.NombreUsuario.ToLower() ?? "").Contains(searchString)
                        ).ToList();

                switch (tipoDato)
                {
                    case "tiempo":
                        lista = lista.Where(s => DateTime.Compare(s.Fecha, pTiempo) <= 0).ToList();
                        lista = lista.Union(listaP).ToList();
                        break;
                    case "numerico":
                        lista = lista.Where(s => s.Monto.ToString().Contains(pDecimal.ToString())).ToList();
                        lista = lista.Union(listaP).ToList();
                        break;
                    default:
                        lista = listaP;
                        break;
                }
            }

            switch (sortOrder)
            {
                case "Fecha":
                    lista = lista.OrderBy(s => s.Fecha).ToList();
                    break;
                case "Tipo":
                    lista = lista.OrderBy(s => s.IdTipoMovimiento).ToList();
                    break;
                case "Detalle":
                    lista = lista.OrderBy(s => s.NroOperacion).ToList();
                    break;
                case "Monto":
                    lista = lista.OrderBy(s => s.Monto).ToList();
                    break;
                case "Categoria":
                    lista = lista.OrderBy(s => s.NombreCategoria).ToList();
                    break;
                case "Entidad":
                    lista = lista.OrderBy(s => s.NombreEntidadR).ToList();
                    break;
                case "Documento":
                    lista = lista.OrderBy(s => s.NumeroDocumento).ToList();
                    break;
                case "Usuario":
                    lista = lista.OrderBy(s => s.NombreUsuario).ToList();
                    break;
                case "Estado":
                    lista = lista.OrderBy(s => s.IdEstadoMovimiento).ToList();
                    break;
                case "Fecha_desc":
                    lista = lista.OrderByDescending(s => s.Fecha).ToList();
                    break;
                case "Tipo_desc":
                    lista = lista.OrderByDescending(s => s.IdTipoMovimiento).ToList();
                    break;
                case "Detalle_desc":
                    lista = lista.OrderByDescending(s => s.NroOperacion).ToList();
                    break;
                case "Monto_desc":
                    lista = lista.OrderByDescending(s => s.Monto).ToList();
                    break;
                case "Categoria_desc":
                    lista = lista.OrderByDescending(s => s.NombreCategoria).ToList();
                    break;
                case "Entidad_desc":
                    lista = lista.OrderByDescending(s => s.NombreEntidadR).ToList();
                    break;
                case "Documento_desc":
                    lista = lista.OrderByDescending(s => s.NumeroDocumento).ToList();
                    break;
                case "Usuario_desc":
                    lista = lista.OrderByDescending(s => s.NombreUsuario).ToList();
                    break;
                case "Estado_desc":
                    lista = lista.OrderByDescending(s => s.IdEstadoMovimiento).ToList();
                    break;
            }

            int pageSize = 50;
            int pageNumber = (page ?? 1);

            return lista.ToPagedList(pageNumber, pageSize);
        }
 private void activatePackages(IList<IPackageInfo> packages, IList<IActivator> discoveredActivators)
 {
     var discoveredPlusRegisteredActivators = discoveredActivators.Union(_activators);
     _diagnostics.LogExecutionOnEach(discoveredPlusRegisteredActivators,
                                     activator => activator.Activate(packages, _diagnostics.LogFor(activator)));
 }
Exemplo n.º 15
0
 public ConstructorInfo Select(Type pluggedType)
 {
     return(_selectors.Union(_defaults).FirstValue(x => x.Find(pluggedType)));
 }
 /// <summary>
 /// Gets an enumerator to the combined set of keys.
 /// </summary>
 /// <returns>Enumerator</returns>
 public IEnumerator <SecurityKeyIdentifierClause> GetEnumerator()
 {
     return(configuredItems.Union(loadedItems).GetEnumerator());
 }
Exemplo n.º 17
0
        protected override void FilterInitialize()
        {
            if (_filterInitialized)
            {
                return;
            }
            _filterInitialized = true;

            _filters = (IList <Filter>)HttpContext.Current.Items["DIC_MyFirstDictionary.FiltersCache"];
            if (Page == null && _filters != null)
            {
                _filterHandlers = _filters.
                                  Union(_filters.SelectMany(r => r.AllChildren)).
                                  Where(p => p.FilterHandler != null).
                                  ToDictionary(p => LinqFilterGenerator.GetFilterName(p.FilterName));
                return;
            }

            BrowseFilterParameters parameters;
            IList <Filter>         filters = new List <Filter>();
            var stack = new Stack <IList <Filter> >();

            _filters = filters;
            Filter current;
            BaseFilterParameter currentBF = null;



            //колонка 'System code'
            current = currentBF = new BaseFilterParameterString <DIC_MyFirstDictionary>(r => r.Code)
            {
                FilterName      = "Code",
                Header          = DIC_MyFirstDictionaryResources.Code__Header,
                IsJournalFilter = true,
                Mandatory       = true,
                Type            = FilterHtmlGenerator.FilterType.Text,
                MaxLength       = 4,
                Columns         = 4,
            };
            currentBF.AddFilter(filters);
            //filters.Add(current);



            //колонка 'Name'
            current = currentBF = new BaseFilterParameterString <DIC_MyFirstDictionary>(r => r.Name)
            {
                FilterName      = "Name",
                Header          = DIC_MyFirstDictionaryResources.Name__Header,
                IsJournalFilter = true,
                Mandatory       = true,
                Type            = FilterHtmlGenerator.FilterType.Text,
                MaxLength       = 255,
                Width           = "98%",
            };
            currentBF.AddFilter(filters);
            //filters.Add(current);



            //колонка 'Date time Start'
            current = currentBF = new BaseFilterParameter <DIC_MyFirstDictionary, DateTime>(r => r.DateStart)
            {
                FilterName      = "DateStart",
                Header          = DIC_MyFirstDictionaryResources.DateStart__Header,
                IsJournalFilter = true,
                Mandatory       = true,
                Type            = FilterHtmlGenerator.FilterType.Numeric,
                IsDateTime      = true,
            };
            currentBF.AddFilter(filters);
            //filters.Add(current);



            //колонка 'Date time End'
            current = currentBF = new BaseFilterParameter <DIC_MyFirstDictionary, DateTime>(r => r.DateEnd)
            {
                FilterName      = "DateEnd",
                Header          = DIC_MyFirstDictionaryResources.DateEnd__Header,
                IsJournalFilter = true,
                Mandatory       = false,
                Type            = FilterHtmlGenerator.FilterType.Numeric,
                IsDateTime      = true,
            };
            currentBF.AddFilter(filters);
            //filters.Add(current);



            if (Url.IsMultipleSelect)
            {
                current = new Filter
                {
                    FilterName       = MultipleSelectedValues,
                    Header           = TableResources.MultipleSelectedFilterHeader,
                    Type             = FilterHtmlGenerator.FilterType.Boolean,
                    TrueBooleanText  = TableResources.MultipleSelectedFilterSelected,
                    FalseBooleanText = TableResources.MultipleSelectedFilterNotSelected,
                    Mandatory        = true,
                    FilterHandler    =
                        delegate(IQueryable enumerable, Enum type, string value1, string value2)
                    {
                        throw new Exception("Is not actual delegate");
                    },
                };
                filters.Add(current);
            }

            AddSearchFilter(filters);
            SetDefaultFilterType(filters);
            FilterInitialize(filters);
            if (CustomFilter != null && !_customFiltersInitialized)
            {
                _customFiltersInitialized = true;
                InitializeCustomFilters(filters);
            }

            _filterHandlers = filters.
                              Union(filters.SelectMany(r => r.AllChildren)).
                              Where(p => p.FilterHandler != null).
                              ToDictionary(p => LinqFilterGenerator.GetFilterName(p.FilterName));
            HttpContext.Current.Items["DIC_MyFirstDictionary.FiltersCache"] = filters;
        }
Exemplo n.º 18
0
        /// <summary>
        /// Loads all settings from all available levels.
        /// </summary>
        /// <returns>A collection of all available definitions.</returns>
        public IList <ExternalLinkDefinition> GetEffectiveSettings()
        {
            var effective = _definitions.Union(_lowerPriority?.GetEffectiveSettings() ?? Enumerable.Empty <ExternalLinkDefinition>()).ToList();

            return(effective.ToList());
        }
Exemplo n.º 19
0
        protected virtual Expression AnalyzeCall(MethodCallExpression expression, IList<Expression> parameters, TranslationContext context)
        {
            var operands = expression.GetOperands().ToList();
            var operarandsToSkip = expression.Method.IsStatic ? 1 : 0;
            var originalParameters = operands.Skip(parameters.Count + operarandsToSkip);
            var newParameters = parameters.Union(originalParameters).ToList();

            var dt = expression.Method.DeclaringType;
            if(dt == typeof(Queryable) || dt == typeof(Enumerable))
              return AnalyzeQueryableCall(expression.Method, newParameters, context);
            if(dt == typeof(Vita.Entities.EntityQueryExtensions))
              return AnalyzeQueryExtensionsCall(expression.Method, newParameters, context);
            if(dt == typeof(string))
              return AnalyzeStringCall(expression.Method, newParameters, context);
            if(dt == typeof(Math))
              return AnalyzeMathCall(expression.Method, newParameters, context);
            return AnalyzeUnknownCall(expression, newParameters, context);
        }
Exemplo n.º 20
0
        IList <IType> FindTypesInBounds(IList <IType> lowerBounds, IList <IType> upperBounds)
        {
            // If there's only a single type; return that single type.
            // If both inputs are empty, return the empty list.
            if (lowerBounds.Count == 0 && upperBounds.Count <= 1)
            {
                return(upperBounds);
            }
            if (upperBounds.Count == 0 && lowerBounds.Count <= 1)
            {
                return(lowerBounds);
            }
            if (nestingLevel > maxNestingLevel)
            {
                return(EmptyList <IType> .Instance);
            }

            // Finds a type X so that "LB <: X <: UB"

            // First try the Fixing algorithm from the V# spec (§7.5.2.11)
            List <IType> candidateTypes = lowerBounds.Union(upperBounds)
                                          .Where(c => lowerBounds.All(b => conversions.ImplicitConversion(b, c).IsValid))
                                          .Where(c => upperBounds.All(b => conversions.ImplicitConversion(c, b).IsValid))
                                          .ToList(); // evaluate the query only once



            // According to the V# specification, we need to pick the most specific
            // of the candidate types. (the type which has conversions to all others)
            // However, csc actually seems to choose the least specific.
            candidateTypes = candidateTypes.Where(
                c => candidateTypes.All(o => conversions.ImplicitConversion(o, c).IsValid)
                ).ToList();

            // If the specified algorithm produces a single candidate, we return
            // that candidate.
            // We also return the whole candidate list if we're not using the improved
            // algorithm.
            if (candidateTypes.Count == 1 || !(algorithm == TypeInferenceAlgorithm.Improved || algorithm == TypeInferenceAlgorithm.ImprovedReturnAllResults))
            {
                return(candidateTypes);
            }
            candidateTypes.Clear();

            // Now try the improved algorithm

            List <ITypeDefinition> candidateTypeDefinitions;

            if (lowerBounds.Count > 0)
            {
                // Find candidates by using the lower bounds:
                var hashSet = new HashSet <ITypeDefinition>(lowerBounds[0].GetAllBaseTypeDefinitions());
                for (int i = 1; i < lowerBounds.Count; i++)
                {
                    hashSet.IntersectWith(lowerBounds[i].GetAllBaseTypeDefinitions());
                }
                candidateTypeDefinitions = hashSet.ToList();
            }
            else
            {
                // Find candidates by looking at all classes in the project:
                candidateTypeDefinitions = compilation.GetAllTypeDefinitions().ToList();
            }

            // Now filter out candidates that violate the upper bounds:
            foreach (IType ub in upperBounds)
            {
                ITypeDefinition ubDef = ub.GetDefinition();
                if (ubDef != null)
                {
                    candidateTypeDefinitions.RemoveAll(c => !c.IsDerivedFrom(ubDef));
                }
            }

            foreach (ITypeDefinition candidateDef in candidateTypeDefinitions)
            {
                // determine the type parameters for the candidate:
                IType candidate;
                if (candidateDef.TypeParameterCount == 0)
                {
                    candidate = candidateDef;
                }
                else
                {
                    bool    success;
                    IType[] result = InferTypeArgumentsFromBounds(
                        candidateDef.TypeParameters,
                        new ParameterizedTypeSpec(candidateDef, candidateDef.TypeParameters),
                        lowerBounds, upperBounds,
                        out success);
                    if (success)
                    {
                        candidate = new ParameterizedTypeSpec(candidateDef, result);
                    }
                    else
                    {
                        continue;
                    }
                }


                if (upperBounds.Count == 0)
                {
                    // if there were only lower bounds, we aim for the most specific candidate:

                    // if this candidate isn't made redundant by an existing, more specific candidate:
                    if (!candidateTypes.Any(c => c.GetDefinition().IsDerivedFrom(candidateDef)))
                    {
                        // remove all existing candidates made redundant by this candidate:
                        candidateTypes.RemoveAll(c => candidateDef.IsDerivedFrom(c.GetDefinition()));
                        // add new candidate
                        candidateTypes.Add(candidate);
                    }
                }
                else
                {
                    // if there were upper bounds, we aim for the least specific candidate:

                    // if this candidate isn't made redundant by an existing, less specific candidate:
                    if (!candidateTypes.Any(c => candidateDef.IsDerivedFrom(c.GetDefinition())))
                    {
                        // remove all existing candidates made redundant by this candidate:
                        candidateTypes.RemoveAll(c => c.GetDefinition().IsDerivedFrom(candidateDef));
                        // add new candidate
                        candidateTypes.Add(candidate);
                    }
                }
            }

            return(candidateTypes);
        }
Exemplo n.º 21
0
        public async Task<IList<JiraIssue>> UpdateCache(IList<JiraIssue> updatedIssues)
        {
            if (_jiraUrl == "demo")
                return updatedIssues;

            try
            {
                if (IsAvailable == false)
                    InitializeCacheDirectory();

                var cachedItems = await LoadIssuesFromCache();

                var updatedCache = (await Task.Factory.StartNew(() => updatedIssues.Union(cachedItems))).ToList();

                await DumpCache(updatedCache);
                await StoreMetafile();

                return updatedCache;
            }
            catch (Exception e)
            {
                _logger.Warn(e, "Cache update failed");
                throw new CacheCorruptedException();
            }
        }
        void DeleteHandler(IList<string> pathStack, string user, string pass,string privateKeyFile)
        {
            if(pathStack.Count > 0)
            {
                string path = pathStack[0];
                pathStack.RemoveAt(0);

                bool addBack = true;

                IList<IActivityIOPath> allFiles = ListFilesInDirectory(ActivityIOFactory.CreatePathFromString(path, user, pass, privateKeyFile)).GroupBy(a => a.Path).Select(g => g.First()).ToList();
                IList<IActivityIOPath> allDirs = ListFoldersInDirectory(ActivityIOFactory.CreatePathFromString(path, user, pass, privateKeyFile));

                if(allDirs.Count == 0)
                {
                    // delete path ;)
                    foreach(var file in allFiles)
                    {
                        DeleteOp(file);
                    }
                    IActivityIOPath tmpPath = ActivityIOFactory.CreatePathFromString(path, user, pass, privateKeyFile);
                    DeleteOp(tmpPath);
                    addBack = false;
                }
                else
                {
                    // more dirs to process 
                    pathStack = pathStack.Union(allDirs.Select(ioPath => ioPath.Path)).ToList();
                }

                DeleteHandler(pathStack, user, pass, privateKeyFile);

                if(addBack)
                {
                    // remove the dir now all its sub-dirs are gone ;)
                    DeleteHandler(new List<string> { path }, user, pass, privateKeyFile);
                }
            }
        }
Exemplo n.º 23
0
            private CharacterGroupListItemViewModel GenerateFrom(CharacterGroup characterGroup, int deepLevel, IList <CharacterGroup> pathToTop)
            {
                if (!characterGroup.IsVisible(CurrentUserId))
                {
                    return(null);
                }
                var prevCopy = Results.FirstOrDefault(cg => cg.FirstCopy && cg.CharacterGroupId == characterGroup.CharacterGroupId);

                var vm = new CharacterGroupListItemViewModel
                {
                    CharacterGroupId    = characterGroup.CharacterGroupId,
                    DeepLevel           = deepLevel,
                    Name                = characterGroup.CharacterGroupName,
                    FirstCopy           = prevCopy == null,
                    AvaiableDirectSlots = characterGroup.HaveDirectSlots ? characterGroup.AvaiableDirectSlots : 0,
                    IsAcceptingClaims   = characterGroup.IsAcceptingClaims(),
                    ActiveCharacters    =
                        prevCopy?.ActiveCharacters ??
                        GenerateCharacters(characterGroup)
                        .ToList(),
                    Description       = characterGroup.Description.ToHtmlString(),
                    ActiveClaimsCount = characterGroup.Claims.Count(c => c.ClaimStatus.IsActive()),
                    Path        = pathToTop.Select(cg => Results.First(item => item.CharacterGroupId == cg.CharacterGroupId)),
                    IsPublic    = characterGroup.IsPublic,
                    IsSpecial   = characterGroup.IsSpecial,
                    IsRootGroup = characterGroup.IsRoot,
                    ProjectId   = characterGroup.ProjectId,
                    RootGroupId = Root.CharacterGroupId,
                };

                if (Root == characterGroup)
                {
                    vm.First = true;
                    vm.Last  = true;
                }

                if (vm.IsSpecial)
                {
                    var variant = characterGroup.GetBoundFieldDropdownValueOrDefault();

                    if (variant != null)
                    {
                        vm.BoundExpression = $"{variant.ProjectField.FieldName} = {variant.Label}";
                    }
                }

                Results.Add(vm);

                if (prevCopy != null)
                {
                    vm.ChildGroups = prevCopy.ChildGroups;
                    return(vm);
                }

                var childGroups     = characterGroup.GetOrderedChildGroups().OrderBy(g => g.IsSpecial).Where(g => g.IsActive && g.IsVisible(CurrentUserId)).ToList();
                var pathForChildren = pathToTop.Union(new[] { characterGroup }).ToList();

                vm.ChildGroups = childGroups.Select(childGroup => GenerateFrom(childGroup, deepLevel + 1, pathForChildren)).ToList().MarkFirstAndLast();

                return(vm);
            }
Exemplo n.º 24
0
        private IPagedList<ComprobanteDTO> BusquedaYPaginado_Comprobantes(IList<ComprobanteDTO> lista, string sortOrder, string currentFilter, string searchString, int? page)
        {
            if (!String.IsNullOrEmpty(searchString))
            { searchString = searchString.ToLower(); }
            ViewBag.CurrentSort = sortOrder;

            ViewBag.vbFecha = sortOrder == "Fecha" ? "Fecha_desc" : "Fecha";
            ViewBag.vbDocumento = sortOrder == "Documento" ? "Documento_desc" : "Documento";
            ViewBag.vbNumero = sortOrder == "Numero" ? "Numero_desc" : "Numero";
            ViewBag.vbEntidad = sortOrder == "Entidad" ? "Entidad_desc" : "Entidad";
            ViewBag.vbProyecto = sortOrder == "Proyecto" ? "Proyecto_desc" : "Proyecto";
            ViewBag.vbMontoSinIGV = sortOrder == "MontoSinIGV" ? "MontoSinIGV_desc" : "MontoSinIGV";
            ViewBag.vbCategoria = sortOrder == "Categoria" ? "Categoria_desc" : "Categoria";
            ViewBag.vbFechaFin = sortOrder == "FechaFin" ? "FechaFin_desc" : "FechaFin";
            ViewBag.vbUsuario = sortOrder == "Usuario" ? "Usuario_desc" : "Usuario";
            ViewBag.vbEstado = sortOrder == "Estado" ? "Estado_desc" : "Estado";

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            string tipoDato = "cadena";
            DateTime pTiempo;
            if (DateTime.TryParse(searchString, out pTiempo))
            {
                tipoDato = "tiempo";
                pTiempo = Convert.ToDateTime(searchString);
            }

            Decimal pDecimal;
            if (Decimal.TryParse(searchString, out pDecimal))
            {
                tipoDato = "numerico";
                pDecimal = Convert.ToDecimal(searchString);
            }

            if (!String.IsNullOrEmpty(searchString))
            {
                IList<ComprobanteDTO> listaP;
                listaP = lista.Where(s => (s.NombreTipoDocumento.ToLower() ?? "").Contains(searchString)
                        || (s.NombreCategoria.ToLower() ?? "").Contains(searchString)
                        || (s.NroDocumento.ToLower() ?? "").Contains(searchString)
                        || (s.NombreEntidad.ToLower() ?? "").Contains(searchString)
                        || (s.NombreUsuario.ToLower() ?? "").Contains(searchString)
                        || (s.NombreProyecto.ToLower() ?? "").Contains(searchString)
                        ).ToList();

                switch (tipoDato)
                {
                    case "tiempo":
                        lista = lista.Where(s => DateTime.Compare(s.FechaEmision, pTiempo) <= 0 || DateTime.Compare(s.FechaConclusion.GetValueOrDefault(), pTiempo) <= 0).ToList();
                        lista = lista.Union(listaP).ToList();
                        break;
                    case "numerico":
                        lista = lista.Where(s => s.MontoSinIGV.ToString().Contains(pDecimal.ToString())).ToList();
                        lista = lista.Union(listaP).ToList();
                        break;
                    default:
                        lista = listaP;
                        break;
                }
            }

            switch (sortOrder)
            {
                case "Documento":
                    lista = lista.OrderBy(s => s.NombreTipoDocumento).ToList();
                    break;
                case "Numero":
                    lista = lista.OrderBy(s => s.NroDocumento).ToList();
                    break;
                case "Categoria":
                    lista = lista.OrderBy(s => s.NombreCategoria).ToList();
                    break;
                case "Entidad":
                    lista = lista.OrderBy(s => s.NombreEntidad).ToList();
                    break;
                case "MontoSinIGV":
                    lista = lista.OrderBy(s => s.MontoSinIGV).ToList();
                    break;
                case "Usuario":
                    lista = lista.OrderBy(s => s.NombreUsuario).ToList();
                    break;
                case "Fecha":
                    lista = lista.OrderBy(s => s.FechaEmision).ToList();
                    break;
                case "FechaFin":
                    lista = lista.OrderBy(s => s.FechaConclusion).ToList();
                    break;
                case "Estado":
                    lista = lista.OrderBy(s => s.Ejecutado).ToList();
                    break;
                case "Documento_desc":
                    lista = lista.OrderByDescending(s => s.NombreTipoDocumento).ToList();
                    break;
                case "Numero_desc":
                    lista = lista.OrderByDescending(s => s.NroDocumento).ToList();
                    break;
                case "Categoria_desc":
                    lista = lista.OrderByDescending(s => s.NombreCategoria).ToList();
                    break;
                case "Entidad_desc":
                    lista = lista.OrderByDescending(s => s.NombreEntidad).ToList();
                    break;
                case "MontoSinIGV_desc":
                    lista = lista.OrderByDescending(s => s.MontoSinIGV).ToList();
                    break;
                case "Usuario_desc":
                    lista = lista.OrderByDescending(s => s.NombreUsuario).ToList();
                    break;
                case "Fecha_desc":
                    lista = lista.OrderByDescending(s => s.FechaEmision).ToList();
                    break;
                case "FechaFin_desc":
                    lista = lista.OrderByDescending(s => s.FechaConclusion).ToList();
                    break;
                case "Estado_desc":
                    lista = lista.OrderByDescending(s => s.Ejecutado).ToList();
                    break;
                default:
                    lista = lista.OrderByDescending(s => s.FechaEmision).ToList();
                    break;
            }

            int pageSize = 50;
            int pageNumber = (page ?? 1);

            return lista.ToPagedList(pageNumber, pageSize);
        }
Exemplo n.º 25
0
            public virtual void PrepareSpecsFilters(IList <string> alreadyFilteredSpecOptionIds,
                                                    IList <string> filterableSpecificationAttributeOptionIds,
                                                    ISpecificationAttributeService specificationAttributeService,
                                                    IWebHelper webHelper, IWorkContext workContext, ICacheManager cacheManager)
            {
                Enabled = false;
                var optionIds = filterableSpecificationAttributeOptionIds != null
                    ? string.Join(",", filterableSpecificationAttributeOptionIds.Union(alreadyFilteredSpecOptionIds)) : string.Empty;

                var cacheKey = string.Format(ModelCacheEventConsumer.SPECS_FILTER_MODEL_KEY, optionIds, workContext.WorkingLanguage.Id);

                //var allFilters = cacheManager.Get(cacheKey, () =>
                //{
                var _allFilters = new List <SpecificationAttributeOptionFilter>();

                foreach (var sao in filterableSpecificationAttributeOptionIds.Union(alreadyFilteredSpecOptionIds))
                {
                    var sa = specificationAttributeService.GetSpecificationAttributeByOptionId(sao);
                    if (sa != null)
                    {
                        _allFilters.Add(new SpecificationAttributeOptionFilter
                        {
                            SpecificationAttributeId                 = sa.Id,
                            SpecificationAttributeName               = sa.GetLocalized(x => x.Name, workContext.WorkingLanguage.Id),
                            SpecificationAttributeDisplayOrder       = sa.DisplayOrder,
                            SpecificationAttributeOptionId           = sao,
                            SpecificationAttributeOptionName         = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == sao).GetLocalized(x => x.Name, workContext.WorkingLanguage.Id),
                            SpecificationAttributeOptionDisplayOrder = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == sao).DisplayOrder,
                            SpecificationAttributeOptionColorRgb     = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == sao).ColorSquaresRgb,
                        });
                    }
                }
                //return _allFilters.ToList();
                var allFilters = _allFilters.ToList();

                //});
                if (!allFilters.Any())
                {
                    return;
                }

                //sort loaded options
                allFilters = allFilters.OrderBy(saof => saof.SpecificationAttributeDisplayOrder)
                             .ThenBy(saof => saof.SpecificationAttributeName)
                             .ThenBy(saof => saof.SpecificationAttributeOptionDisplayOrder)
                             .ThenBy(saof => saof.SpecificationAttributeOptionName).ToList();

                //prepare the model properties
                Enabled = true;
                var removeFilterUrl = webHelper.RemoveQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM);

                RemoveFilterUrl = ExcludeQueryStringParams(removeFilterUrl, webHelper);

                //get already filtered specification options
                var alreadyFilteredOptions = allFilters.Where(x => alreadyFilteredSpecOptionIds.Contains(x.SpecificationAttributeOptionId));

                AlreadyFilteredItems = alreadyFilteredOptions.Select(x =>
                                                                     new SpecificationFilterItem
                {
                    SpecificationAttributeName           = x.SpecificationAttributeName,
                    SpecificationAttributeOptionName     = x.SpecificationAttributeOptionName,
                    SpecificationAttributeOptionColorRgb = x.SpecificationAttributeOptionColorRgb
                }).ToList();

                //get not filtered specification options
                NotFilteredItems = allFilters.Except(alreadyFilteredOptions).Select(x =>
                {
                    //filter URL
                    var alreadyFiltered = alreadyFilteredSpecOptionIds.Concat(new List <string> {
                        x.SpecificationAttributeOptionId
                    });
                    var queryString = string.Format("{0}={1}", QUERYSTRINGPARAM, GenerateFilteredSpecQueryParam(alreadyFiltered.ToList()));
                    var filterUrl   = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), queryString, null);

                    return(new SpecificationFilterItem()
                    {
                        SpecificationAttributeName = x.SpecificationAttributeName,
                        SpecificationAttributeOptionName = x.SpecificationAttributeOptionName,
                        SpecificationAttributeOptionColorRgb = x.SpecificationAttributeOptionColorRgb,
                        FilterUrl = ExcludeQueryStringParams(filterUrl, webHelper)
                    });
                }).ToList();
            }
Exemplo n.º 26
0
        //: BaseService, IContentAdminService {
        // **************************************
        //  Update
        // **************************************
        public static void Update(Content contentModel, 
			IList<int> tagsModel,
			IDictionary<TagType, string> newTagsModel,
			IList<ContentRepresentationUpdateModel> representationModel)
        {
            using (var ctx = new SongSearchContext()) {
                    //UpdateModelWith Content
                    var content = ctx.Contents
                            .Include("Tags")
                            .Include("Catalog")
                            .Include("ContentRepresentations")
                            .Include("ContentRepresentations.Territories")
                        .Where(c => c.ContentId == contentModel.ContentId).SingleOrDefault();// && user.UserCatalogRoles.Any(x => x.CatalogId == c.CatalogId)).SingleOrDefault();

                    if (content == null) {
                        throw new ArgumentOutOfRangeException("Content does not exist");
                    }

                    content.UpdateModelWith(contentModel);

                    //UpdateModelWith Tags
                    tagsModel = tagsModel.Where(t => t > 0).ToList();
                    // create new tags
                    var newTags = ctx.CreateTags(newTagsModel);
                    tagsModel = tagsModel.Union(newTags).ToList();

                    // add to tagsModel
                    content = ctx.UpdateTags(content, tagsModel);

                    //UpdateModelWith Representation
                    content = ctx.UpdateRepresentation(content, representationModel);

                    content.LastUpdatedByUserId = Account.User().UserId;
                    content.LastUpdatedOn = DateTime.Now;

                    ctx.SaveChanges();

                    CacheService.InitializeApp(true);
                    //CacheService.CacheUpdate(CacheService.CacheKeys.Content);
                    //CacheService.CacheUpdate(CacheService.CacheKeys.Rights);
                    //CacheService.CacheUpdate(CacheService.CacheKeys.TopTags);
                    //CacheService.CacheUpdate(CacheService.CacheKeys.Tags);
                    //CacheService.CacheUpdate(CacheService.CacheKeys.Territories);
                }
        }
Exemplo n.º 27
0
        public void RetriveData()
        {
            //该用户所属角色
            SysRole sysRole = bizSysRole.ListSysRoleByUserID(UserId.Value);

            //该用户可以访问的所有菜单
            IList<SysMenu> userTypeVisitMenu = bizSysMenu.ListSysMenuByUserTypeID(sysRole == null ? Guid.Empty : sysRole.UserTypeID.Value);

            //该用户角色可以访问的所有菜单
            IList<SysMenu> userRoleMenu = bizSysMenu.ListSysMenuBySysRoleID(sysRole == null ? Guid.Empty : sysRole.ID).Where(x=>userTypeVisitMenu.Select(y=>y.ID).Contains(x.ID)).ToList();

            //该用户可以访问的菜单
            UserMenu = bizSysMenu.ListSysMenuByUserId(UserId.Value).Distinct().ToList().Where(x=>userTypeVisitMenu.Select(y=>y.ID).Contains(x.ID)).ToList();

            //用户已分配权限菜单
            AssignedRoleMenu = UserMenu.Union(userRoleMenu).ToList();

            //用户未分配权限菜单
            NonAssignedRoleMenu = userTypeVisitMenu.Where(x => !AssignedRoleMenu.Select(s => s.ID).Contains(x.ID)).ToList();

            //所有菜单

            IList<SysMenu> MenuList = bizSysMenu.ListBy(ReflectionTools.SerializeExpression<SysMenu>(x => x.Level.Value == 1 || x.Level.Value == 2));

            // 未分配权限父节点
            NonAssignedRoleMenuParent = GetSysMenuParentID(MenuList, NonAssignedRoleMenu);

            //已分配权限父节点
            AssignedRoleMenuParent = GetSysMenuParentID(MenuList, AssignedRoleMenu);
        }
Exemplo n.º 28
0
        /// <summary>
        /// This method checks if the character has card combination "Straight"
        /// </summary>
        /// <param name="charactersCardsCollection">The collection of cards in the characters hand.</param>
        /// <param name="tableCardsCollection">The collection of cards on the table.</param>
        /// <param name="character">The character that holds the cards.</param>
        /// <returns><c>true</c> if the character has a Straight, <c>false</c> if they don't.</returns>     
        private bool CheckForStraight(IList<ICard> charactersCardsCollection, IList<ICard> tableCardsCollection,
            ICharacter character)
        {
            List<ICard> joinedCardCollection =
                charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).ToList();
            joinedCardCollection = new List<ICard>(joinedCardCollection.OrderByDescending(x => x.Rank));
            List<int> distinctCardRanks = joinedCardCollection.Select(x => (int)x.Rank).Distinct().OrderByDescending(x => x).ToList();

            int endBorderOfStraight = 4; // if a number is the beginning of a straight, then the end is '4' numbers later (straight must be 5 cards))
            bool hasStraight = false;
            double power = 0;

            for (int currentCardIndex = 0; currentCardIndex < distinctCardRanks.Count - endBorderOfStraight; currentCardIndex++)
            {
                if (distinctCardRanks[currentCardIndex] - endBorderOfStraight == distinctCardRanks[currentCardIndex + endBorderOfStraight])
                {
                    hasStraight = true;
                    int highestCardInStraight = distinctCardRanks[currentCardIndex];
                    power = highestCardInStraight + Constants.StraightBehaviourPower * 100;
                    break;
                }
            }

            if (hasStraight)
            {
                List<ICard> straightCombinationCards = new List<ICard>();

                foreach (int distinctRank in distinctCardRanks)
                {
                    ICard cardToBeAdded = joinedCardCollection.Find(card => (int)card.Rank == distinctRank);
                    straightCombinationCards.Add(cardToBeAdded);
                }
                IList<ICard> theOtherCardsFromTheHandNotIncludedInTheCombination =
                    joinedCardCollection.Where(x => !straightCombinationCards.Contains(x)).ToList();

                RegisterCombination(character, power, straightCombinationCards,
                    theOtherCardsFromTheHandNotIncludedInTheCombination, CombinationType.Straight,
                    Constants.StraightBehaviourPower);
            }

            return hasStraight;
        }
Exemplo n.º 29
0
 private void activatePackages(IList<IPackageInfo> packages, IList<IActivator> discoveredActivators)
 {
     _diagnostics.LogExecutionOnEach(discoveredActivators.Union(_activators),
                                     a => { a.Activate(packages, _diagnostics.LogFor(a)); });
 }
Exemplo n.º 30
0
        /// <summary>
        /// This method cheks for forur of a kind combination
        /// </summary>
        /// <param name="charactersCardsCollection">
        /// Cards in player's hand
        /// </param>
        /// <param name="tableCardsCollection">
        /// Cards on table
        /// </param>
        /// <param name="character">
        /// player whose cards are checked
        /// </param>
        /// <returns></returns>
        private bool CheckForFourOfAKind(
            IList<ICard> charactersCardsCollection,
            IList<ICard> tableCardsCollection,
            ICharacter character)
        {
            IList<ICard> joinedCardCollection =
                charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).ToList();

            foreach (var element in joinedCardCollection)
            {
                IList<ICard> sameRankCardsCollection = joinedCardCollection.Where(x => x.Rank == element.Rank).ToList();

                if (sameRankCardsCollection.Count == 4)
                {
                    double power = (int)sameRankCardsCollection[0].Rank * 4 + FourOfAKindBehaviourPower * 100;

                    IList<ICard> theOtherCardsFromTheHandNotIncludedInTheCombination =
                        joinedCardCollection.Where(x => !sameRankCardsCollection.Contains(x)).ToList();

                    RegisterCombination(character, power, sameRankCardsCollection, theOtherCardsFromTheHandNotIncludedInTheCombination, CombinationType.FourOfAKind, Constants.FourOfAKindBehavourPower);

                    return true;
                }
            }
            return false;
        }
Exemplo n.º 31
0
        public void SaveToCache(IList<ITweetable> viewport)
        {
            if (!Cached)
                return;

            var toSave = viewport
                .Union(Source.OrderByDescending(x => x.Id).Take(CacheSize))
                .OfType<TwitterStatus>()
                .OrderByDescending(x => x.Id);

            try
            {
                Cacher.SaveToCache(Resource, toSave);
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 32
0
        //This method gets the rank (number) of the cards that make up a three-of-a-kind
        private int GetThreeOfAKindCardRank(IList<ICard> charactersCardsCollection, IList<ICard> tableCardsCollection)
        {
            int cardRank = -1;

            IList<ICard> joinedCardCollection =
                charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).ToList();

            foreach (var element in joinedCardCollection)
            {
                IList<ICard> sameRankCardsCollection = joinedCardCollection.Where(x => x.Rank == element.Rank).ToList();

                if (sameRankCardsCollection.Count == 3)
                {
                    cardRank = (int)element.Rank;
                }
            }

            return cardRank;
        }
Exemplo n.º 33
0
        IList<IType> FindTypesInBounds(IList<IType> lowerBounds, IList<IType> upperBounds)
        {
            // If there's only a single type; return that single type.
            // If both inputs are empty, return the empty list.
            if (lowerBounds.Count == 0 && upperBounds.Count <= 1)
                return upperBounds;
            if (upperBounds.Count == 0 && lowerBounds.Count <= 1)
                return lowerBounds;
            if (nestingLevel > maxNestingLevel)
                return EmptyList<IType>.Instance;

            // Finds a type X so that "LB <: X <: UB"
            Log.WriteCollection("FindTypesInBound, LowerBounds=", lowerBounds);
            Log.WriteCollection("FindTypesInBound, UpperBounds=", upperBounds);

            // First try the Fixing algorithm from the C# spec (§7.5.2.11)
            List<IType> candidateTypes = lowerBounds.Union(upperBounds)
                .Where(c => lowerBounds.All(b => conversions.ImplicitConversion(b, c).IsValid))
                .Where(c => upperBounds.All(b => conversions.ImplicitConversion(c, b).IsValid))
                .ToList(); // evaluate the query only once

            Log.WriteCollection("FindTypesInBound, Candidates=", candidateTypes);

            // According to the C# specification, we need to pick the most specific
            // of the candidate types. (the type which has conversions to all others)
            // However, csc actually seems to choose the least specific.
            candidateTypes = candidateTypes.Where(
                c => candidateTypes.All(o => conversions.ImplicitConversion(o, c).IsValid)
            ).ToList();

            // If the specified algorithm produces a single candidate, we return
            // that candidate.
            // We also return the whole candidate list if we're not using the improved
            // algorithm.
            if (candidateTypes.Count == 1 || !(algorithm == TypeInferenceAlgorithm.Improved || algorithm == TypeInferenceAlgorithm.ImprovedReturnAllResults))
            {
                return candidateTypes;
            }
            candidateTypes.Clear();

            // Now try the improved algorithm
            Log.Indent();
            List<ITypeDefinition> candidateTypeDefinitions;
            if (lowerBounds.Count > 0) {
                // Find candidates by using the lower bounds:
                var hashSet = new HashSet<ITypeDefinition>(lowerBounds[0].GetAllBaseTypeDefinitions());
                for (int i = 1; i < lowerBounds.Count; i++) {
                    hashSet.IntersectWith(lowerBounds[i].GetAllBaseTypeDefinitions());
                }
                candidateTypeDefinitions = hashSet.ToList();
            } else {
                // Find candidates by looking at all classes in the project:
                candidateTypeDefinitions = compilation.GetAllTypeDefinitions().ToList();
            }

            // Now filter out candidates that violate the upper bounds:
            foreach (IType ub in upperBounds) {
                ITypeDefinition ubDef = ub.GetDefinition();
                if (ubDef != null) {
                    candidateTypeDefinitions.RemoveAll(c => !c.IsDerivedFrom(ubDef));
                }
            }

            foreach (ITypeDefinition candidateDef in candidateTypeDefinitions) {
                // determine the type parameters for the candidate:
                IType candidate;
                if (candidateDef.TypeParameterCount == 0) {
                    candidate = candidateDef;
                } else {
                    Log.WriteLine("Inferring arguments for candidate type definition: " + candidateDef);
                    bool success;
                    IType[] result = InferTypeArgumentsFromBounds(
                        candidateDef.TypeParameters,
                        new ParameterizedType(candidateDef, candidateDef.TypeParameters),
                        lowerBounds, upperBounds,
                        out success);
                    if (success) {
                        candidate = new ParameterizedType(candidateDef, result);
                    } else {
                        Log.WriteLine("Inference failed; ignoring candidate");
                        continue;
                    }
                }
                Log.WriteLine("Candidate type: " + candidate);

                if (upperBounds.Count == 0) {
                    // if there were only lower bounds, we aim for the most specific candidate:

                    // if this candidate isn't made redundant by an existing, more specific candidate:
                    if (!candidateTypes.Any(c => c.GetDefinition().IsDerivedFrom(candidateDef))) {
                        // remove all existing candidates made redundant by this candidate:
                        candidateTypes.RemoveAll(c => candidateDef.IsDerivedFrom(c.GetDefinition()));
                        // add new candidate
                        candidateTypes.Add(candidate);
                    }
                } else {
                    // if there were upper bounds, we aim for the least specific candidate:

                    // if this candidate isn't made redundant by an existing, less specific candidate:
                    if (!candidateTypes.Any(c => candidateDef.IsDerivedFrom(c.GetDefinition()))) {
                        // remove all existing candidates made redundant by this candidate:
                        candidateTypes.RemoveAll(c => c.GetDefinition().IsDerivedFrom(candidateDef));
                        // add new candidate
                        candidateTypes.Add(candidate);
                    }
                }
            }
            Log.Unindent();
            return candidateTypes;
        }
Exemplo n.º 34
0
        /// <summary>
        /// Checks if the two character's cards make a "Pair" or if one of the character's cards makes a "Pair" with one card from the table.
        /// </summary>
        /// <param name="charactersCardsCollection"></param>
        /// <param name="tableCardsCollection"></param>
        /// <param name="character"></param>
        /// <returns></returns>
        private bool CheckForOnePair(IList<ICard> charactersCardsCollection, IList<ICard> tableCardsCollection, ICharacter character, bool isCheckingForASecondPair)
        {
            IList<ICombination> combinationsCollection = new List<ICombination>();

            bool foundOnePair = false;
            bool foundASecondPair = false;

            IList<ICard> joinedCardCollection = charactersCardsCollection.Union(tableCardsCollection.Where(x => x.IsVisible)).ToList();

            FindAllOnePairCombinations(joinedCardCollection, combinationsCollection);

            combinationsCollection = combinationsCollection.OrderByDescending(x => x.Power).ToList();

            if (isCheckingForASecondPair)
            {
                if (combinationsCollection.Count >= 1)
                {
                    foundASecondPair = true;
                }

                if (foundASecondPair)
                {
                    RegisterTwoPairs(character, combinationsCollection);
                }
            }
            else
            {
                if (combinationsCollection.Count >= 1)
                {
                    foundOnePair = true;
                    RegisterOnePair(character, combinationsCollection);
                }
            }

            bool foundAPairOrPairs = foundOnePair || foundASecondPair;

            return foundAPairOrPairs;
        }
Exemplo n.º 35
0
        protected override void FilterInitialize()
        {
            if (_filterInitialized)
            {
                return;
            }
            _filterInitialized = true;

            _filters = (IList <Filter>)HttpContext.Current.Items["MyProducts.FiltersCache"];
            if (Page == null && _filters != null)
            {
                _filterHandlers = _filters.
                                  Union(_filters.SelectMany(r => r.AllChildren)).
                                  Where(p => p.FilterHandler != null).
                                  ToDictionary(p => LinqFilterGenerator.GetFilterName(p.FilterName));
                return;
            }

            BrowseFilterParameters parameters;
            IList <Filter>         filters = new List <Filter>();
            var stack = new Stack <IList <Filter> >();

            _filters = filters;
            Filter current;
            BaseFilterParameter currentBF = null;



            //колонка 'Наименование'
            current = currentBF = new BaseFilterParameterString <MyProduct>(r => r.Name)
            {
                FilterName      = "Name",
                Header          = MyProductsResources.Name__Header,
                IsJournalFilter = true,
                Mandatory       = true,
                Type            = FilterHtmlGenerator.FilterType.Text,
                MaxLength       = 200,
                Width           = "98%",
            };
            currentBF.AddFilter(filters);
            //filters.Add(current);



            //колонка 'Дата создания'
            current = currentBF = new BaseFilterParameter <MyProduct, DateTime>(r => r.CreationDate)
            {
                FilterName      = "CreationDate",
                Header          = MyProductsResources.CreationDate__Header,
                IsJournalFilter = true,
                Mandatory       = true,
                Type            = FilterHtmlGenerator.FilterType.Numeric,
                IsDateTime      = true,
            };
            currentBF.AddFilter(filters);
            //filters.Add(current);



            //колонка 'Цена'
            current = currentBF = new BaseFilterParameter <MyProduct, Decimal>(r => r.Price)
            {
                FilterName       = "Price",
                Header           = MyProductsResources.Price__Header,
                IsJournalFilter  = true,
                Mandatory        = true,
                Type             = FilterHtmlGenerator.FilterType.Numeric,
                DecimalPrecision = 2,
                MaxLength        = 8,
                Columns          = 8,
            };
            currentBF.AddFilter(filters);
            //filters.Add(current);



            //колонка 'Доступно'
            current = currentBF = new BaseFilterParameter <MyProduct, Decimal>(r => r.Amount)
            {
                FilterName       = "Amount",
                Header           = MyProductsResources.Amount__Header,
                IsJournalFilter  = true,
                Mandatory        = true,
                Type             = FilterHtmlGenerator.FilterType.Numeric,
                DecimalPrecision = 2,
                MaxLength        = 8,
                Columns          = 8,
            };
            currentBF.AddFilter(filters);
            //filters.Add(current);



            if (Url.IsMultipleSelect)
            {
                current = new Filter
                {
                    FilterName       = MultipleSelectedValues,
                    Header           = TableResources.MultipleSelectedFilterHeader,
                    Type             = FilterHtmlGenerator.FilterType.Boolean,
                    TrueBooleanText  = TableResources.MultipleSelectedFilterSelected,
                    FalseBooleanText = TableResources.MultipleSelectedFilterNotSelected,
                    Mandatory        = true,
                    FilterHandler    =
                        delegate(IQueryable enumerable, Enum type, string value1, string value2)
                    {
                        throw new Exception("Is not actual delegate");
                    },
                };
                filters.Add(current);
            }

            AddSearchFilter(filters);
            SetDefaultFilterType(filters);
            FilterInitialize(filters);
            if (CustomFilter != null && !_customFiltersInitialized)
            {
                _customFiltersInitialized = true;
                InitializeCustomFilters(filters);
            }

            _filterHandlers = filters.
                              Union(filters.SelectMany(r => r.AllChildren)).
                              Where(p => p.FilterHandler != null).
                              ToDictionary(p => LinqFilterGenerator.GetFilterName(p.FilterName));
            HttpContext.Current.Items["MyProducts.FiltersCache"] = filters;
        }
            public virtual async Task PrepareSpecsFilters(IList <string> alreadyFilteredSpecOptionIds,
                                                          IList <string> filterableSpecificationAttributeOptionIds,
                                                          ISpecificationAttributeService specificationAttributeService,
                                                          IWebHelper webHelper, ICacheManager cacheManager, string langId)
            {
                Enabled = false;
                var optionIds = filterableSpecificationAttributeOptionIds != null
                    ? string.Join(",", filterableSpecificationAttributeOptionIds.Union(alreadyFilteredSpecOptionIds)) : string.Empty;

                var cacheKey = string.Format(ModelCacheEventConst.SPECS_FILTER_MODEL_KEY, optionIds, langId);

                var allFilters = await cacheManager.GetAsync(cacheKey, async() =>
                {
                    var _allFilters = new List <SpecificationAttributeOptionFilter>();
                    foreach (var sao in filterableSpecificationAttributeOptionIds.Union(alreadyFilteredSpecOptionIds))
                    {
                        var sa = await specificationAttributeService.GetSpecificationAttributeByOptionId(sao);
                        if (sa != null)
                        {
                            _allFilters.Add(new SpecificationAttributeOptionFilter {
                                SpecificationAttributeId                 = sa.Id,
                                SpecificationAttributeName               = sa.GetLocalized(x => x.Name, langId),
                                SpecificationAttributeSeName             = sa.SeName,
                                SpecificationAttributeDisplayOrder       = sa.DisplayOrder,
                                SpecificationAttributeOptionId           = sao,
                                SpecificationAttributeOptionName         = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == sao).GetLocalized(x => x.Name, langId),
                                SpecificationAttributeOptionSeName       = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == sao).SeName,
                                SpecificationAttributeOptionDisplayOrder = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == sao).DisplayOrder,
                                SpecificationAttributeOptionColorRgb     = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == sao).ColorSquaresRgb,
                            });
                        }
                    }
                    return(_allFilters.ToList());
                });

                if (!allFilters.Any())
                {
                    return;
                }

                //sort loaded options
                allFilters = allFilters.OrderBy(saof => saof.SpecificationAttributeDisplayOrder)
                             .ThenBy(saof => saof.SpecificationAttributeName)
                             .ThenBy(saof => saof.SpecificationAttributeOptionDisplayOrder)
                             .ThenBy(saof => saof.SpecificationAttributeOptionName).ToList();

                //prepare the model properties
                Enabled = true;
                string removeFilterUrl = webHelper.GetThisPageUrl(true);

                foreach (var item in allFilters.GroupBy(x => x.SpecificationAttributeSeName))
                {
                    removeFilterUrl = webHelper.ModifyQueryString(removeFilterUrl, item.Key, null);
                }
                RemoveFilterUrl = ExcludeQueryStringParams(removeFilterUrl, webHelper);

                //get already filtered specification options
                var alreadyFilteredOptions = allFilters.Where(x => alreadyFilteredSpecOptionIds.Contains(x.SpecificationAttributeOptionId));

                AlreadyFilteredItems = alreadyFilteredOptions.Select(x =>
                {
                    var alreadyFiltered = alreadyFilteredOptions.Where(y => y.SpecificationAttributeId == x.SpecificationAttributeId).Select(z => z.SpecificationAttributeOptionSeName)
                                          .Except(new List <string> {
                        x.SpecificationAttributeOptionSeName
                    }).ToList();

                    var filterUrl = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), x.SpecificationAttributeSeName, GenerateFilteredSpecQueryParam(alreadyFiltered));

                    return(new SpecificationFilterItem {
                        SpecificationAttributeName = x.SpecificationAttributeName,
                        SpecificationAttributeSeName = x.SpecificationAttributeSeName,
                        SpecificationAttributeOptionName = x.SpecificationAttributeOptionName,
                        SpecificationAttributeOptionSeName = x.SpecificationAttributeOptionSeName,
                        SpecificationAttributeOptionColorRgb = x.SpecificationAttributeOptionColorRgb,
                        FilterUrl = ExcludeQueryStringParams(filterUrl, webHelper)
                    });
                }).ToList();

                //get not filtered specification options
                NotFilteredItems = allFilters.Except(alreadyFilteredOptions).Select(x =>
                {
                    //filter URL
                    var alreadyFiltered = alreadyFilteredOptions.Where(y => y.SpecificationAttributeId == x.SpecificationAttributeId).Select(x => x.SpecificationAttributeOptionSeName)
                                          .Concat(new List <string> {
                        x.SpecificationAttributeOptionSeName
                    });

                    var filterUrl = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), x.SpecificationAttributeSeName, GenerateFilteredSpecQueryParam(alreadyFiltered.ToList()));
                    return(new SpecificationFilterItem()
                    {
                        SpecificationAttributeName = x.SpecificationAttributeName,
                        SpecificationAttributeSeName = x.SpecificationAttributeSeName,
                        SpecificationAttributeOptionName = x.SpecificationAttributeOptionName,
                        SpecificationAttributeOptionSeName = x.SpecificationAttributeOptionSeName,
                        SpecificationAttributeOptionColorRgb = x.SpecificationAttributeOptionColorRgb,
                        FilterUrl = ExcludeQueryStringParams(filterUrl, webHelper)
                    });
                }).ToList();
            }
Exemplo n.º 37
0
        public List <SalesboardReportObject> BuildSalesboardReport(List <int> dealerIDs)
        {
            List <SalesboardReportObject> report = new List <SalesboardReportObject>();

            //pull out the individual Dealerships
            List <DealerShip> dealers = context.DealerShips.Where(d => dealerIDs.Contains(d.DealerID) && (d.DisableDate == null || d.DisableDate > StartDate)).ToList();

            SalesboardReportObject sbObj = null;
            var sundays = DateHelper.GetAllDatesOfSpecifiedDayOfWeekInMonth(EndDate, DayOfWeek.Sunday);

            foreach (var dealer in dealers)
            {
                sbObj            = new SalesboardReportObject();
                sbObj.Dealership = dealer;
                var id       = dealer.DealerID;
                var saleDate = StartDate;
                SalesboardRecord sbRecord = null;
                while (saleDate <= EndDate)
                {
                    sbRecord                  = new SalesboardRecord();
                    sbRecord.Dealership       = dealer.DealerName;
                    sbRecord.DateOfSale       = saleDate;
                    sbRecord.DayOfTheWeek     = saleDate.DayOfWeek.ToString();
                    sbRecord.SellingDayNumber = DateHelper.WorkingDaysInMonthUntilDate(saleDate);
                    sbRecord.WeekNumber       = (saleDate.DayOfWeek == DayOfWeek.Sunday) ? sundays.IndexOf(saleDate) + 1 : 0;

                    var salesBoardQuery = (mFIs.Union(mUnwinds))
                                          .Where(s => (id == 99 ? s.Record.Dealerid > 0 : s.Record.Dealerid == id) &&
                                                 ((s.RecordType == "M") ? s.Record.delvdate : s.Record.unwinddate) == saleDate)
                                          .Select(s => new
                    {
                        New         = (s.RecordType == "M" && s.Record.vehicletype == "N" ? 1 : 0),
                        Used        = (s.RecordType == "M" && s.Record.vehicletype == "U" ? 1 : 0),
                        BackoutNew  = (s.RecordType == "M" && s.Record.vehicletype == "N" && s.Record.status == 8 ? 1 : 0),
                        BackoutUsed = (s.RecordType == "M" && s.Record.vehicletype == "U" && s.Record.status == 8 ? 1 : 0),
                        Unwind      = (s.RecordType == "U") ? 1 : 0
                    });

                    int newSales = 0, usedSales = 0;
                    if (sbRecord.WeekNumber == 1) //First Sunday
                    {
                        newSales = sbObj.SalesboardRecords
                                   .Where(s => s.DateOfSale >= DateHelper.FirstDayOfTheMonth(saleDate) && s.DateOfSale <= saleDate)
                                   .Select(s => s.NewSalesCount).Sum();

                        usedSales = sbObj.SalesboardRecords
                                    .Where(s => s.DateOfSale >= DateHelper.FirstDayOfTheMonth(saleDate) && s.DateOfSale <= saleDate)
                                    .Select(s => s.UsedSalesCount).Sum();
                    }
                    else if (sbRecord.WeekNumber > 1)   //Sunday besides the First Sunday
                    {
                        newSales = sbObj.SalesboardRecords
                                   .Where(s => s.DateOfSale >= saleDate.AddDays(-6) && s.DateOfSale <= saleDate)
                                   .Select(s => s.NewSalesCount).Sum();

                        usedSales = sbObj.SalesboardRecords
                                    .Where(s => s.DateOfSale >= saleDate.AddDays(-6) && s.DateOfSale <= saleDate)
                                    .Select(s => s.UsedSalesCount).Sum();
                    }
                    else //Weekday
                    {
                        newSales  = salesBoardQuery.Select(x => x.New).Sum();
                        usedSales = salesBoardQuery.Select(x => x.Used).Sum();
                    }
                    sbRecord.NewSalesCount  = newSales;
                    sbRecord.UsedSalesCount = usedSales;

                    sbRecord.NewBackoutCount  = salesBoardQuery.Select(x => x.BackoutNew).Sum();
                    sbRecord.UsedBackoutCount = salesBoardQuery.Select(x => x.BackoutUsed).Sum();
                    sbRecord.UnwindSalesCount = salesBoardQuery.Select(x => x.Unwind).Sum();

                    sbObj.SalesboardRecords.Add(sbRecord);

                    saleDate = saleDate.AddDays(1);
                }

                //Report is Built.  Not we have to set the Report totals
                sbObj.DaysOfWeek = sbObj.SalesboardRecords
                                   .Select(s => new SalesboardDayOfTheWeek
                {
                    DateOfSale     = s.DateOfSale,
                    DayOfTheWeek   = s.DayOfTheWeek,
                    IsSunday       = (s.DayOfTheWeek == "Sunday" ? true : false),
                    SellingDay     = s.SellingDayNumber,
                    WeekNumber     = s.WeekNumber,
                    NewSalesCount  = s.NewSalesCount,
                    UsedSalesCount = s.UsedSalesCount
                }).OrderBy(s => s.DateOfSale).ToList();

                sbObj.ActualNewSalesCount  = sbObj.SalesboardRecords.Where(x => x.DayOfTheWeek != "Sunday").Select(x => x.NewSalesCount).Sum();
                sbObj.ActualUsedSalesCount = sbObj.SalesboardRecords.Where(x => x.DayOfTheWeek != "Sunday").Select(x => x.UsedSalesCount).Sum();
                sbObj.NewBackoutCount      = sbObj.SalesboardRecords.Select(x => x.NewBackoutCount).Sum();
                sbObj.UsedBackoutCount     = sbObj.SalesboardRecords.Select(x => x.UsedBackoutCount).Sum();
                sbObj.UnwindCount          = sbObj.SalesboardRecords.Select(x => x.UnwindSalesCount).Sum();
                var sbPrevTravelQuery = GetPrevSalesboardCount().Where(s => (id == 99 ? s.Record.Dealerid > 0 : s.Record.Dealerid == id));
                sbObj.PrevNewTravel = sbPrevTravelQuery.Where(x => x.Record.vehicletype == "N").Count();
                sbObj.PrevOldTravel = sbPrevTravelQuery.Where(x => x.Record.vehicletype == "U").Count();

                report.Add(sbObj);
            }


            return(report);
        }
Exemplo n.º 38
0
        public (bool, string, TrainOrder) BookTrainTicket(TrainShift TrainShift, TrainStation StartTrainStation, TrainStation EndTrainStation, IList <SeatTypeConfig> SeatTypes, CustomerInfo CustomerInfo, IList <UserContract> UserContracts)
        {
            if (StartTrainStation == null)
            {
                throw new ArgumentNullException("StartTrainStation");
            }
            if (!StartTrainStation.IsSale)
            {
                throw new ArgumentNullException($"{StartTrainStation} is Not Sale");
            }
            if (EndTrainStation == null)
            {
                throw new ArgumentNullException("EndTrainStation");
            }
            if (SeatTypes == null)
            {
                throw new ArgumentNullException("SeatTypes");
            }
            if (UserContracts == null || UserContracts.Count == 0)
            {
                throw new ArgumentNullException("UserContract");
            }
            if (UserContracts.Count(o => o.UserType != ContractUserType.Children) == 0)
            {
                throw new Exception("儿童不能单独买票");
            }
            if (StartTrainStation.Order > EndTrainStation.Order)
            {
                throw new ArgumentNullException("StartTrainStation same EndTrainStation Order");
            }
            if (StartTrainStation.Order > EndTrainStation.Order)
            {
                var temp = StartTrainStation;
                StartTrainStation = EndTrainStation;
                EndTrainStation   = temp;
            }

            var trainStationWay = new TrainStationWay(StartTrainStation, EndTrainStation);

            IList <Seat> seats = isMatchSeats(TrainShift, StartTrainStation, EndTrainStation, SeatTypes);

            //匹配优先在同一车厢
            if (seats == null || seats.Count == 0)
            {
                seats = TrainShift.ExtraSeatInfos.Select(o => o.Seat).Where(o => SeatTypes.Contains(o.SeatType)).GroupBy(o => o.TrainCarriage).Where(o => o.Count() >= UserContracts.Count).FirstOrDefault().Take(UserContracts.Count).ToList();

                if (seats == null)
                {
                    seats = TrainShift.ExtraSeatInfos.Select(o => o.Seat).Where(o => SeatTypes.Contains(o.SeatType)).Take(UserContracts.Count).ToList();
                    if (seats == null || seats.Count < UserContracts.Count)
                    {
                        throw new Exception("余票不足,建议单独购买");
                    }
                }
            }
            else if (seats.Count < UserContracts.Count)
            {
                foreach (var item in seats)
                {
                    seats = seats.Union(TrainShift.ExtraSeatInfos.Select(o => o.Seat).Where(o => SeatTypes.Contains(o.SeatType) && o.TrainCarriage == item.TrainCarriage).Take(UserContracts.Count - seats.Count).ToList()).ToList();
                    if (seats.Count == UserContracts.Count)
                    {
                        break;
                    }
                }

                if (seats.Count < UserContracts.Count)
                {
                    seats = seats.Union(TrainShift.ExtraSeatInfos.Select(o => o.Seat).Where(o => SeatTypes.Contains(o.SeatType)).Take(UserContracts.Count - seats.Count).ToList()).ToList();
                    if (seats.Count < UserContracts.Count)
                    {
                        throw new Exception("余票不足,建议单独购买");
                    }
                }
            }
            else
            {
                seats = seats.GroupBy(o => o.TrainCarriage).Where(o => o.Count() >= UserContracts.Count).FirstOrDefault().Take(UserContracts.Count).ToList();
                if (seats == null || seats.Count == 0)
                {
                    seats = seats.Take(UserContracts.Count).ToList();
                }
            }
            if (seats == null || UserContracts.Count > seats.Count)
            {
                throw new Exception("余票不足");
            }

            IList <TrainOrderItem> trainOrderItems = new List <TrainOrderItem>();

            for (int i = 0; i < seats.Count; i++)
            {
                var seat         = seats[i];
                var userContract = UserContracts[i];
                var b            = TrainShift.ExtraSeatInfos.Remove(new ExtraSeatInfo(TrainShift, seat));


                new FreezeSeatInfo(TrainShift, new DestinationSeat(seat, new List <TrainStationWay>()
                {
                    trainStationWay
                }));
                new FreezeSeatInfo(TrainShift, new DestinationSeat(seat, new List <TrainStationWay>()
                {
                    trainStationWay
                }));

                var            price          = TrainShift.TrainNumber.GetTrainStationWayPrice(trainStationWay, seat.SeatType);
                TrainOrderItem trainOrderItem = new TrainOrderItem(seat, userContract, price);
                trainOrderItems.Add(trainOrderItem);
            }


            TrainOrder trainOrder = new TrainOrder(trainStationWay.StartTrainStation, trainStationWay.EndTrainStation, CustomerInfo, trainOrderItems);

            return(true, "预定成功", trainOrder);
        }
Exemplo n.º 39
0
        IList <IType> FindTypesInBounds(IList <IType> lowerBounds, IList <IType> upperBounds)
        {
            // If there's only a single type; return that single type.
            // If both inputs are empty, return the empty list.
            if (lowerBounds.Count == 0 && upperBounds.Count <= 1)
            {
                return(upperBounds);
            }
            if (upperBounds.Count == 0 && lowerBounds.Count <= 1)
            {
                return(lowerBounds);
            }
            if (nestingLevel > maxNestingLevel)
            {
                return(EmptyList <IType> .Instance);
            }

            // Finds a type X so that "LB <: X <: UB"
            Log.WriteCollection("FindTypesInBound, LowerBounds=", lowerBounds);
            Log.WriteCollection("FindTypesInBound, UpperBounds=", upperBounds);

            // First try the Fixing algorithm from the C# spec (§7.5.2.11)
            List <IType> candidateTypes = lowerBounds.Union(upperBounds)
                                          .Where(c => lowerBounds.All(b => conversions.ImplicitConversion(b, c)))
                                          .Where(c => upperBounds.All(b => conversions.ImplicitConversion(c, b)))
                                          .ToList(); // evaluate the query only once

            candidateTypes = candidateTypes.Where(
                c => candidateTypes.All(o => conversions.ImplicitConversion(c, o))
                ).ToList();
            // If the specified algorithm produces a single candidate, we return
            // that candidate.
            // We also return the whole candidate list if we're not using the improved
            // algorithm.
            if (candidateTypes.Count == 1 || !(algorithm == TypeInferenceAlgorithm.Improved || algorithm == TypeInferenceAlgorithm.ImprovedReturnAllResults))
            {
                return(candidateTypes);
            }
            candidateTypes.Clear();

            // Now try the improved algorithm
            Log.Indent();
            List <ITypeDefinition> candidateTypeDefinitions;

            if (lowerBounds.Count > 0)
            {
                // Find candidates by using the lower bounds:
                var hashSet = new HashSet <ITypeDefinition>(lowerBounds[0].GetAllBaseTypeDefinitions(context));
                for (int i = 1; i < lowerBounds.Count; i++)
                {
                    hashSet.IntersectWith(lowerBounds[i].GetAllBaseTypeDefinitions(context));
                }
                candidateTypeDefinitions = hashSet.ToList();
            }
            else
            {
                // Find candidates by looking at all classes in the project:
                candidateTypeDefinitions = context.GetAllTypes().ToList();
            }

            // Now filter out candidates that violate the upper bounds:
            foreach (IType ub in upperBounds)
            {
                ITypeDefinition ubDef = ub.GetDefinition();
                if (ubDef != null)
                {
                    candidateTypeDefinitions.RemoveAll(c => !c.IsDerivedFrom(ubDef, context));
                }
            }

            foreach (ITypeDefinition candidateDef in candidateTypeDefinitions)
            {
                // determine the type parameters for the candidate:
                IType candidate;
                if (candidateDef.TypeParameterCount == 0)
                {
                    candidate = candidateDef;
                }
                else
                {
                    Log.WriteLine("Inferring arguments for candidate type definition: " + candidateDef);
                    bool    success;
                    IType[] result = InferTypeArgumentsFromBounds(
                        candidateDef.TypeParameters,
                        new ParameterizedType(candidateDef, candidateDef.TypeParameters),
                        lowerBounds, upperBounds,
                        out success);
                    if (success)
                    {
                        candidate = new ParameterizedType(candidateDef, result);
                    }
                    else
                    {
                        Log.WriteLine("Inference failed; ignoring candidate");
                        continue;
                    }
                }
                Log.WriteLine("Candidate type: " + candidate);

                if (lowerBounds.Count > 0)
                {
                    // if there were lower bounds, we aim for the most specific candidate:

                    // if this candidate isn't made redundant by an existing, more specific candidate:
                    if (!candidateTypes.Any(c => c.GetDefinition().IsDerivedFrom(candidateDef, context)))
                    {
                        // remove all existing candidates made redundant by this candidate:
                        candidateTypes.RemoveAll(c => candidateDef.IsDerivedFrom(c.GetDefinition(), context));
                        // add new candidate
                        candidateTypes.Add(candidate);
                    }
                }
                else
                {
                    // if there only were upper bounds, we aim for the least specific candidate:

                    // if this candidate isn't made redundant by an existing, less specific candidate:
                    if (!candidateTypes.Any(c => candidateDef.IsDerivedFrom(c.GetDefinition(), context)))
                    {
                        // remove all existing candidates made redundant by this candidate:
                        candidateTypes.RemoveAll(c => c.GetDefinition().IsDerivedFrom(candidateDef, context));
                        // add new candidate
                        candidateTypes.Add(candidate);
                    }
                }
            }
            Log.Unindent();
            return(candidateTypes);
        }
        public void PrepareForUpdateChildrenMasterPages(PageProperties page, Guid? masterPageId, out IList<Guid> newMasterIds, out IList<Guid> oldMasterIds, out IList<Guid> childrenPageIds, out IList<MasterPage>  existingChildrenMasterPages)
        {
            if ((page.MasterPage != null && page.MasterPage.Id != masterPageId) || (page.MasterPage == null && masterPageId.HasValue))
            {
                newMasterIds = masterPageId.HasValue ? GetPageMasterPageIds(masterPageId.Value) : new List<Guid>(0);

                oldMasterIds = page.MasterPage != null && page.MasterPages != null ? page.MasterPages.Select(mp => mp.Master.Id).Distinct().ToList() : new List<Guid>(0);

                var intersectingIds = newMasterIds.Intersect(oldMasterIds).ToArray();
                foreach (var id in intersectingIds)
                {
                    oldMasterIds.Remove(id);
                    newMasterIds.Remove(id);
                }

                var updatingIds = newMasterIds.Union(oldMasterIds).Distinct().ToList();
                existingChildrenMasterPages = GetChildrenMasterPagesToUpdate(page, updatingIds, out childrenPageIds);
            }
            else
            {
                newMasterIds = null;
                oldMasterIds = null;
                childrenPageIds = null;
                existingChildrenMasterPages = null;
            }
        }
 public void AtualizarListaParticipantes(IEnumerable <Participante> participantes)
 {
     _participantes.Clear();
     _participantes.Union(participantes);
 }
Exemplo n.º 42
0
        private DelegateDefinition GetExistingDelegate(IList<string> libraries, string delegateString)
        {
            if (libraries.Count == 0)
                return Context.Delegates.Values.FirstOrDefault(t => t.Signature == delegateString);

            DelegateDefinition @delegate = null;
            if (libraries.Union(
                Context.Symbols.Libraries.Where(l => libraries.Contains(l.FileName)).SelectMany(
                    l => l.Dependencies)).Any(l => libsDelegates.ContainsKey(l) &&
                        libsDelegates[l].TryGetValue(delegateString, out @delegate)))
                return @delegate;

            return null;
        }
 public IObservable<Unit> UpdateAll(IList<Session> sessions)
 {
     return blob.GetOrCreateObject<IList<Session>>(KEY_SESSIONS, () => new List<Session>())
         .Select(source =>
             {
                 return sessions.Union(source);
             })
         .SelectMany(merged => blob.InsertObject(KEY_SESSIONS, merged));
 }
 private void activatePackages(IList<IPackageInfo> packages, IList<IActivator> discoveredActivators)
 {
     var discoveredPlusRegisteredActivators = discoveredActivators.Union(_activators);
     _diagnostics.LogExecutionOnEach(discoveredPlusRegisteredActivators,
                                     activator => activator.Activate(packages, _diagnostics.LogFor(activator)));
 }
Exemplo n.º 45
0
        private static void BuildReferenceBookItems(IObjectsRepository repository, IEnumerable <IOrganisationUnit> positions, ICollection <ReferenceBookOrgUnitItem> items, IList <string> categories)
        {
            var people = repository.GetPeople().ToList();

            foreach (var unit in positions)
            {
                if (unit.IsPosition)
                {
                    var person = people.Where(p => p.Positions.Select(m => m.Position).Contains(unit.Id))
                                 .OrderBy(o => o.Positions.First(x => x.Position == unit.Id).Order)
                                 .FirstOrDefault();

                    items.Add(person == null
                        ? new ReferenceBookOrgUnitItem(unit.Title, categories.ToList())
                        : new ReferenceBookOrgUnitItem(person.DisplayName, categories.ToList()));
                }
                else
                {
                    BuildReferenceBookItems(repository, GetSortedChildren(unit, repository), items, categories.Union(new[] { unit.Title }).ToList());
                }
            }
        }