示例#1
0
        public ActionResult MoveUp(int id)
        {
            try
            {
                var item = FindMenu(id);
                var menus = GetList(item.ParentId);
                var sortHelper = new SortHelper<Menu>(menus);
                sortHelper.MoveUp(item);
                SaveChanges();
                ShowSuccess(MessageResource.MoveSuccess);

                return RedirectToIndex();
            }
            catch (Exception ex)
            {
                LogError(ex.ToString());
                ShowError(MessageResource.MoveFailed);
            }

            return RedirectToIndex();
        }
示例#2
0
        public ListModel <ParameterGroupModel> List(FilterModel filterModel)
        {
            var startDate = filterModel.StartDate.ResetTimeToStartOfDay();
            var endDate   = filterModel.EndDate.ResetTimeToEndOfDay();
            Expression <Func <ParameterGroup, bool> > expression;

            if (filterModel.Status != -1)
            {
                var status = filterModel.Status.ToString().ToBoolean();
                if (filterModel.Searched != null)
                {
                    if (status)
                    {
                        expression = c => c.IsApproved && c.Name.Contains(filterModel.Searched);
                    }
                    else
                    {
                        expression = c => c.IsApproved == false && c.Name.Contains(filterModel.Searched);
                    }
                }
                else
                {
                    if (status)
                    {
                        expression = c => c.IsApproved;
                    }
                    else
                    {
                        expression = c => c.IsApproved == false;
                    }
                }
            }
            else
            {
                if (filterModel.Searched != null)
                {
                    expression = c => c.Name.Contains(filterModel.Searched);
                }
                else
                {
                    expression = c => c.Id != Guid.Empty;
                }
            }

            expression = expression.And(e => e.CreationTime >= startDate && e.CreationTime <= endDate);

            var model = filterModel.CreateMapped <FilterModel, ListModel <ParameterGroupModel> >();

            if (model.Paging == null)
            {
                model.Paging = new Paging
                {
                    PageSize   = filterModel.PageSize,
                    PageNumber = filterModel.PageNumber
                };
            }

            var sortHelper = new SortHelper <ParameterGroupModel>();

            var query = _repositoryParameterGroup
                        .Join(x => x.Creator.Person)
                        .Join(x => x.LastModifier.Person)

                        .Where(expression);

            sortHelper.OrderBy(x => x.DisplayOrder);

            model.Paging.TotalItemCount = query.Count();
            var items      = model.Paging.PageSize > 0 ? query.Skip((model.Paging.PageNumber - 1) * model.Paging.PageSize).Take(model.Paging.PageSize) : query;
            var modelItems = new HashSet <ParameterGroupModel>();

            foreach (var item in items)
            {
                var modelItem = item.CreateMapped <ParameterGroup, ParameterGroupModel>();
                modelItem.Creator      = new IdCodeName(item.Creator.Id, item.Creator.Username, item.Creator.Person.DisplayName);
                modelItem.LastModifier = new IdCodeName(item.LastModifier.Id, item.LastModifier.Username, item.LastModifier.Person.DisplayName);
                modelItems.Add(modelItem);
            }
            model.Items = modelItems.ToList();
            var pageSizeDescription = _serviceMain.ApplicationSettings.PageSizeList;
            var pageSizes           = pageSizeDescription.Split(',').Select(s => new KeyValuePair <int, string>(s.ToInt(), s)).ToList();

            pageSizes.Insert(0, new KeyValuePair <int, string>(-1, "[" + Dictionary.All + "]"));
            model.Paging.PageSizes = pageSizes;
            model.Paging.PageCount = (int)Math.Ceiling((float)model.Paging.TotalItemCount / model.Paging.PageSize);
            if (model.Paging.TotalItemCount > model.Items.Count)
            {
                model.Paging.HasNextPage = true;
            }

            // ilk sayfa ise

            if (model.Paging.PageNumber == 1)
            {
                if (model.Paging.TotalItemCount > 0)
                {
                    model.Paging.IsFirstPage = true;
                }

                // tek sayfa ise

                if (model.Paging.PageCount == 1)
                {
                    model.Paging.IsLastPage = true;
                }
            }

            // son sayfa ise
            else if (model.Paging.PageNumber == model.Paging.PageCount)
            {
                model.Paging.HasNextPage = false;
                // tek sayfa değilse

                if (model.Paging.PageCount > 1)
                {
                    model.Paging.IsLastPage      = true;
                    model.Paging.HasPreviousPage = true;
                }
            }

            // ara sayfa ise
            else
            {
                model.Paging.HasNextPage     = true;
                model.Paging.HasPreviousPage = true;
            }

            if (model.Paging.TotalItemCount > model.Items.Count && model.Items.Count <= 0)
            {
                model.Message = Messages.DangerRecordNotFoundInPage;
            }

            if (model.Paging.TotalItemCount == 0)
            {
                model.Message = Messages.DangerRecordNotFound;
            }
            return(model);
        }
        public ActionResult Page(int startRow, int endRow, SortEntry[] sortModel, Dictionary <string, FilterEntry> filterModel, string globalFilter)
        {
            IQueryable <Connection> query = connectionRepository.GetConnections();

            // if filters aren't posted, in filters we get values from MVC; with "action", "controller" as keys; they must be excluded, currently by their null value criterion
            foreach (var kvp in filterModel.Where(x => x.Value != null))
            {
                // get expression for this column
                LambdaExpression columnExpression = columnSource[kvp.Key];
                // convert grid-specific filter to an universal entry
                UniversalFilterEntry universalFilterEntry = FilterEntryConverter.Convert(kvp.Value);
                // check whether the entry was parsed successfully
                if (universalFilterEntry == null)
                {
                    continue;
                }
                // get the fltering expression from universalFilterEntry
                Expression <Func <Connection, bool> > filterExpression = FilterExpressions <Connection> .GetFilterExpression(columnExpression, universalFilterEntry);

                // and apply it to the query
                query = query.Where(filterExpression);
            }

            // global filtering
            if (String.IsNullOrWhiteSpace(globalFilter) == false)
            {
                query = query.Where(x => x.Name.Contains(globalFilter) || x.PPE.Contains(globalFilter) || x.MeterCode.Contains(globalFilter) || x.Company.Acronym.Contains(globalFilter) || x.Tariff.Name.Contains(globalFilter));
            }

            int count = query.Count();

            if (sortModel != null)
            {
                for (int i = 0; i < sortModel.Length; i++)
                {
                    SortEntry sortEntry = sortModel[i];

                    string column  = sortEntry.colId;
                    bool   isAsc   = sortEntry.sort == SortEntry.asc;
                    bool   isFirst = i == 0;

                    LambdaExpression columnExpression = columnSource[column];

                    query = SortHelper.ApplyOrderByFromLambda(query, columnExpression, isAsc, isFirst);
                }
            }
            else
            {
                query = query.OrderBy(x => x.Name);
            }

            var r = query.Skip(startRow).Take(endRow - startRow).Select(x =>
                                                                        new
            {
                id                      = x.Id,
                ppe                     = x.PPE,
                meterCode               = x.MeterCode,
                name                    = x.Name,
                tariff                  = x.Tariff.Name,
                company                 = x.Company.Acronym,
                startDate               = x.StartDate,
                endDate                 = x.EndDate,
                orderedCapacity         = x.OrderedCapacity,
                endDateNullable         = x.EndDate,
                orderedCapacityNullable = x.OrderedCapacity,
                isActive                = x.Name.Length % 2 == 0 // fake boolean column
            }).ToArray();


            var response = new { rows = r, count = count };

            return(new JsonNetResult(response));
        }
示例#4
0
        public static void SetGroupedList(bool includeRare)
        {
            int     cnt            = 0;
            Element Jati           = Util.AddOptionItem("జాతులు", "జాతులు", true);
            Element UpaJati        = Util.AddOptionItem("ఉప-జాతులు", "ఉప-జాతులు", true);
            Element Vruttam        = Util.AddOptionItem("తరుచుగా  వాడే వృత్తములు", "తరుచుగా  వాడే వృత్తములు", true);
            Element Ragadalu       = Util.AddOptionItem("రగడలు", "రగడలు", true);
            Element Shatpadalu     = Util.AddOptionItem("షట్పదలు", "షట్పదలు", true);
            Element Akkara         = Util.AddOptionItem("అక్కరలు(జాతులు)", "అక్కరలు(జాతులు)", true);
            Element Dvipadalu      = Util.AddOptionItem("ద్విపదలు(జాతులు)", "ద్విపదలు(జాతులు)", true);
            Element Sisamulu       = Util.AddOptionItem("సీసములు(ఉప-జాతులు)", "సీసములు(ఉప-జాతులు)", true);
            Element ASamaVruttam   = Util.AddOptionItem("అసమ వృత్తములు", "అసమ వృత్తములు", true);
            Element daMDakaVruttam = Util.AddOptionItem("దండకములు", "దండకములు", true);
            Element GenericVruttam = Util.AddOptionItem("ఏదేని వృత్తం ##", "ఏదేని వృత్తం ##", true);



            foreach (Rule R in SortHelper.SortByName(RuleHelper.GetRules2(PadyamSubType.DaMDakamu)))
            {
                Element O = Util.AddOptionItem(R.Name, R.Identifier, false);
                daMDakaVruttam.AppendChild(O);
                cnt++;
            }

            foreach (Rule R in SortHelper.SortByName(RuleHelper.GetRules5(PadyamType.Vruttam, Frequency.Frequent)))
            {
                Element O = Util.AddOptionItem(R.Name, R.Identifier, false);
                Vruttam.AppendChild(O);
                //cnt++;
            }

            foreach (Rule R in SortHelper.SortByName(RuleHelper.GetRules2(PadyamSubType.Akkara)))
            {
                Element O = Util.AddOptionItem(R.Name, R.Identifier, false);
                Akkara.AppendChild(O);
                cnt++;
            }

            foreach (Rule R in SortHelper.SortByName(RuleHelper.GetRules2(PadyamSubType.Ragada)))
            {
                Element O = Util.AddOptionItem(R.Name, R.Identifier, false);
                Ragadalu.AppendChild(O);
                cnt++;
            }

            foreach (Rule R in SortHelper.SortByName(RuleHelper.GetRules2(PadyamSubType.Ragada2)))
            {
                Element O = Util.AddOptionItem(R.Name, R.Identifier, false);
                Ragadalu.AppendChild(O);
                cnt++;
            }

            foreach (Rule R in SortHelper.SortByName(RuleHelper.GetRules2(PadyamSubType.Shatpada)))
            {
                Element O = Util.AddOptionItem(R.Name, R.Identifier, false);
                Shatpadalu.AppendChild(O);
                cnt++;
            }

            foreach (Rule R in SortHelper.SortByName(RuleHelper.GetRules2(PadyamSubType.Divpada)))
            {
                Element O = Util.AddOptionItem(R.Name, R.Identifier, false);
                Dvipadalu.AppendChild(O);
                cnt++;
            }

            foreach (Rule R in SortHelper.SortByName(RuleHelper.GetRules2(PadyamSubType.Sisamu)))
            {
                Element O = Util.AddOptionItem(R.Name, R.Identifier, false);
                Sisamulu.AppendChild(O);
                cnt++;
            }

            foreach (Rule R in SortHelper.SortByName(RuleHelper.GetRules2(PadyamSubType.Jati)))
            {
                Element O = Util.AddOptionItem(R.Name, R.Identifier, false);
                Jati.AppendChild(O);
                cnt++;
            }

            foreach (Rule R in SortHelper.SortByName(RuleHelper.GetRules2(PadyamSubType.UpaJati)))
            {
                Element O = Util.AddOptionItem(R.Name, R.Identifier, false);
                UpaJati.AppendChild(O);
                cnt++;
            }

            {
                Rule    R = new Chandam.Rules.Vruttam.GenricVruttam();
                Element O = Util.AddOptionItem(R.Name, R.Identifier, false);
                GenericVruttam.AppendChild(O);
                //cnt++;
            }

            List <Element> OrderedVruttams = new List <Element>();

            if (includeRare)
            {
                for (int i = 1; i <= 27; i++)
                {
                    string  cName = Helper.ChandamName(i) + (i <= 26 ? " (" + i + ")" : " (>26)");
                    Element Local = Util.AddOptionItem(cName, cName, true);

                    Rule[] VRules = i <= 26 ? RuleHelper.GetRules3(i) : RuleHelper.GetRules4(i);
                    foreach (Rule R in SortHelper.SortByName(VRules))
                    {
                        Element O = Util.AddOptionItem(R.Name, R.Identifier, false);
                        Local.AppendChild(O);
                        OrderedVruttams.Add(Local);
                        cnt++;
                    }
                }
            }

            Rule[] asamaRules = RuleHelper.GetRules2(PadyamSubType.VishamaVruttam);
            foreach (Rule R in SortHelper.SortByName(asamaRules))
            {
                Element O = Util.AddOptionItem(R.Name, R.Identifier, false);
                ASamaVruttam.AppendChild(O);
                cnt++;
            }

            Element E = Window.Document.GetElementById("list");

            E.InnerHTML = "";

            if (Jati.Children.Length > 0)
            {
                E.AppendChild(Jati);
            }
            if (Akkara.Children.Length > 0)
            {
                E.AppendChild(Akkara);
            }
            if (Dvipadalu.Children.Length > 0)
            {
                E.AppendChild(Dvipadalu);
            }
            if (UpaJati.Children.Length > 0)
            {
                E.AppendChild(UpaJati);
            }
            if (Sisamulu.Children.Length > 0)
            {
                E.AppendChild(Sisamulu);
            }
            if (Vruttam.Children.Length > 0)
            {
                E.AppendChild(Vruttam);
            }

            if (includeRare)
            {
                foreach (Element _E in OrderedVruttams)
                {
                    E.AppendChild(_E);
                }
            }

            if (daMDakaVruttam.Children.Length > 0)
            {
                E.AppendChild(daMDakaVruttam);
            }
            if (ASamaVruttam.Children.Length > 0)
            {
                E.AppendChild(ASamaVruttam);
            }
            if (Shatpadalu.Children.Length > 0)
            {
                E.AppendChild(Shatpadalu);
            }
            if (Ragadalu.Children.Length > 0)
            {
                E.AppendChild(Ragadalu);
            }
            if (GenericVruttam.Children.Length > 0)
            {
                E.AppendChild(GenericVruttam);
            }


            Document.GetElementById("totItems").InnerHTML = cnt.ToString() + "+";
        }
示例#5
0
        public static string BuildBook()
        {
            #region
            //foreach ( Rule R in SortHelper.OrderedRules ( ) )
            //{
            //    s=s+"<li>";
            //    s =s+ BuildHTMLRules ( R ,true);
            //    s = s + "</li>";
            //}
            #endregion

            //Why not going with a Loop...???
            //Should be Something Like this.
            //SortHelper.SortByName2 ( delegate (Rule R)
            //{
            //    return R.PadyamSubType == PadyamSubType.Jati;
            //} );

            string s2 = "<h1>అనుక్రమణిక</h1><ol>";
            string s  = "";

            string[] F = new string[] { };
            F  = SortByName2("జాతులు", PadyamSubType.Jati);
            s  = s + F[0];
            s2 = s2 + F[1];

            F  = SortByName2("అక్కరలు", PadyamSubType.Akkara);
            s  = s + F[0];
            s2 = s2 + F[1];

            F  = SortByName2("రగడలు", PadyamSubType.Ragada);
            s  = s + F[0];
            s2 = s2 + F[1];


            F  = SortByName2("ముత్యాలసరములు", PadyamSubType.Ragada2);
            s  = s + F[0];
            s2 = s2 + F[1];

            F  = SortByName2("షట్పదలు", PadyamSubType.Shatpada);
            s  = s + F[0];
            s2 = s2 + F[1];



            F  = SortByName2("ఉప-జాతులు", PadyamSubType.UpaJati);
            s  = s + F[0];
            s2 = s2 + F[1];

            F  = SortByName2("ద్విపదలు", PadyamSubType.Divpada);
            s  = s + F[0];
            s2 = s2 + F[1];

            F  = SortByName2("సీసములు", PadyamSubType.Divpada);
            s  = s + F[0];
            s2 = s2 + F[1];



            s  = s + "<h1>వృత్తములు</h1>";
            s2 = s2 + "<li>వృత్తములు</li><ol>";
            for (int i = 1; i <= 27; i++)
            {
                string cName  = Helper.ChandamName(i) + (i <= 26 ? " (" + i + ")" : " (>26)");
                Rule[] VRules = i <= 26 ? Helper.GetRules3(i) : Helper.GetRules4(i);

                s = s + "<h1>" + cName + "</h1>";
                s = s + "<ol>";

                s2 = s2 + "<li>" + cName + "</li>";
                s2 = s2 + "<ol>";
                foreach (Rule R in SortHelper.SortByName(VRules))
                {
                    s  = s + "<li  id='" + R.Identifier + "'>";
                    s  = s + BuildHTMLRules(R, true);
                    s  = s + "&nbsp; <a class='link' href='#TOP_" + R.Identifier + "'>[TOP]</a>";
                    s  = s + "</li>";
                    s2 = s2 + "<li id='TOP_" + R.Identifier + "'><a class='identifier' href='#" + R.Identifier + "'>" + R.Name + "</a></li>";
                }
                s  = s + "</ol>";
                s2 = s2 + "</ol>";
            }
            s2 = s2 + "</ol>";


            F  = SortByName2("దండకములు", PadyamSubType.DaMDakamu);
            s  = s + F[0];
            s2 = s2 + F[1];

            F  = SortByName2("అసమ వృత్తములు", PadyamSubType.VishamaVruttam);
            s  = s + F[0];
            s2 = s2 + F[1];

            s2 = s2 + "</ol>";
            return(s2 + s);
        }
示例#6
0
        protected override void InternalGenerate()
        {
            IColor clrBlack = AppHost.GfxProvider.CreateColor(0x000000);
            IColor clrBlue  = AppHost.GfxProvider.CreateColor(0x0000FF);

            fTitleFont = fWriter.CreateFont("", 22f, true, false, clrBlack);
            fChapFont  = fWriter.CreateFont("", 16f, true, false, clrBlack);
            fTextFont  = fWriter.CreateFont("", 10f, false, false, clrBlack);

            fWriter.AddParagraph(fTitle, fTitleFont, TextAlignment.taLeft);

            var names    = new List <NameItem>();
            var surnames = new List <NameItem>();

            GDMTree   tree   = fBase.Context.Tree;
            var       enumer = tree.GetEnumerator(GDMRecordType.rtIndividual);
            GDMRecord record;

            while (enumer.MoveNext(out record))
            {
                var iRec      = record as GDMIndividualRecord;
                var nameParts = GKUtils.GetNameParts(iRec, false);

                var item = names.Find(x => x.Name.Equals(nameParts.Name));
                if (item != null)
                {
                    item.Amount += 1;
                }
                else
                {
                    names.Add(new NameItem(nameParts.Name));
                }

                item = surnames.Find(x => x.Name.Equals(nameParts.Surname));
                if (item != null)
                {
                    item.Amount += 1;
                }
                else
                {
                    surnames.Add(new NameItem(nameParts.Surname));
                }
            }

            SortHelper.QuickSort(names, ItemsCompare);
            SortHelper.QuickSort(surnames, ItemsCompare);

            fWriter.AddParagraph(SRLangMan.LS(RLS.LSID_Names), fChapFont, TextAlignment.taLeft);
            fWriter.BeginList();
            foreach (var item in names)
            {
                fWriter.AddListItem(" " + item.Name + "\t" + item.Amount, fTextFont);
            }
            fWriter.EndList();

            fWriter.AddParagraph(SRLangMan.LS(RLS.LSID_Surnames), fChapFont, TextAlignment.taLeft);
            fWriter.BeginList();
            foreach (var item in surnames)
            {
                fWriter.AddListItem(" " + item.Name + "\t" + item.Amount, fTextFont);
            }
            fWriter.EndList();
        }
示例#7
0
 public IActionResult Lista(FormModel nums, SortHelper sh)
 {
     nums.Mayor = sh.NMayor(nums.Numeros);
     nums.Menor = sh.NMenor(nums.Numeros);
     return(View(nums));
 }
示例#8
0
        private void BuildCheatSheet(List <Rule> Rules, string file)
        {
            string s = CheatSheet.BuildCheatSheet2(false, false, SortHelper.SortByCharLength(Rules));

            File.WriteAllText(file, s, Encoding.UTF8);
        }
示例#9
0
        public void Test_Sort()
        {
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, 2016, 05, 05, "2016/05/05 [g]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, 2016, 05, 04, "2016/05/04 [g]"));

            fDates.Add(new UDNRecord(UDNCalendarType.ctJulian, 2016, 04, 21, "2016/05/04 [g] = 2016/04/21 [j]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctJulian, 2016, 04, 23, "2016/05/06 [g] = 2016/04/23 [j]"));

            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, 2016, 05, UDN.UnknownDay, "2016/05/?? [g]")); // must be first
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, 2016, 06, UDN.UnknownDay, "2016/06/?? [g]")); // must be last

            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, UDN.UnknownYear, UDN.UnknownMonth, UDN.UnknownDay, "??/??/?? [g]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, UDN.UnknownYear, 04, 23, "??/04/23 [g]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, UDN.UnknownYear, 03, 23, "??/03/23 [g]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, UDN.UnknownYear, UDN.UnknownMonth, 23, "??/??/23 [g]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, 2016, UDN.UnknownMonth, UDN.UnknownDay, "2016/??/?? [g]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, 2016, UDN.UnknownMonth, 10, "2016/??/10 [g]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, 2015, 03, 23, "2015/03/23 [g]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, 2014, UDN.UnknownMonth, 23, "2014/??/23 [g]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, 2016, 05, 31, "2016/05/31 [g]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, 2016, 05, 31, "2016/05/31 [g]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, -4712, 1, 2, "-4712/01/02 [g]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, -4712, 1, 3, "-4712/01/03 [g]"));

            fDates.Add(new UDNRecord(UDNCalendarType.ctHebrew, 5564, 04, 04, "1804/06/13 [g] = 5564/04/04 [h]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctIslamic, 1216, 01, 04, "1801/05/17 [g] = 1216/01/04 [i]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, 1802, 05, 01, "1802/05/01 [g]"));

            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, 0, 1, 3, "0000/01/03 [g]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, -1, 1, 3, "-0001/01/03 [g]"));

            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, 1, 1, 3, "0001/01/03 [g]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, 2015, 2, 27, "2015/02/27 [g]"));
            fDates.Add(new UDNRecord(UDNCalendarType.ctGregorian, 3268, 1, 23, "3268/01/23 [g]"));

            // Add dates before.
            fDates.Add(new UDNRecord(UDN.CreateBefore(
                                         UDNCalendarType.ctGregorian, 1, 1, 4), UDNCalendarType.ctGregorian, "before 0001/01/04 [g]"));
            fDates.Add(new UDNRecord(UDN.CreateBefore(
                                         UDNCalendarType.ctGregorian, 2016, 05, 31), UDNCalendarType.ctGregorian, "before 2016/05/31 [g]"));
            fDates.Add(new UDNRecord(UDN.CreateBefore(
                                         UDNCalendarType.ctGregorian, -4712, 1, 2), UDNCalendarType.ctGregorian, "before -4712/01/02 [g]"));
            fDates.Add(new UDNRecord(UDN.CreateBefore(
                                         UDNCalendarType.ctGregorian, UDN.UnknownYear, 05, 31), UDNCalendarType.ctGregorian, "before ????/05/31 [g]"));
            fDates.Add(new UDNRecord(UDN.CreateBefore(
                                         UDNCalendarType.ctGregorian, 2015, UDN.UnknownMonth, 31), UDNCalendarType.ctGregorian, "before 2015/??/31 [g]"));
            // Add dates after.
            fDates.Add(new UDNRecord(UDN.CreateAfter(
                                         UDNCalendarType.ctGregorian, 2016, 05, 31), UDNCalendarType.ctGregorian, "after 2016/05/31 [g]"));
            fDates.Add(new UDNRecord(UDN.CreateAfter(
                                         UDNCalendarType.ctGregorian, UDN.UnknownYear, 05, 31), UDNCalendarType.ctGregorian, "after ????/05/31 [g]"));
            fDates.Add(new UDNRecord(UDN.CreateAfter(
                                         UDNCalendarType.ctGregorian, UDN.UnknownYear, 06, 15), UDNCalendarType.ctGregorian, "after ????/06/15 [g]"));
            fDates.Add(new UDNRecord(UDN.CreateAfter(
                                         UDNCalendarType.ctGregorian, 2015, UDN.UnknownMonth, 31), UDNCalendarType.ctGregorian, "after 2015/??/31 [g]"));
            fDates.Add(new UDNRecord(UDN.CreateAfter(
                                         UDNCalendarType.ctGregorian, 2015, UDN.UnknownMonth, 30), UDNCalendarType.ctGregorian, "after 2015/??/30 [g]"));
            // Add approximate dates.
            fDates.Add(new UDNRecord(UDN.CreateApproximate(
                                         UDNCalendarType.ctGregorian, 2016, 05, 31), UDNCalendarType.ctGregorian, "~ 2016/05/31 [g]"));
            fDates.Add(new UDNRecord(UDN.CreateApproximate(
                                         UDNCalendarType.ctGregorian, 1, 1, 4), UDNCalendarType.ctGregorian, "~ 0001/01/04 [g]"));
            fDates.Add(new UDNRecord(UDN.CreateApproximate(
                                         UDNCalendarType.ctGregorian, 1, 1, UDN.UnknownDay), UDNCalendarType.ctGregorian, "~ 0001/01/?? [g]"));
            fDates.Add(new UDNRecord(UDN.CreateApproximate(
                                         UDNCalendarType.ctGregorian, UDN.UnknownYear, 05, 31), UDNCalendarType.ctGregorian, "~ ????/05/31 [g]"));
            fDates.Add(new UDNRecord(UDN.CreateApproximate(
                                         UDNCalendarType.ctGregorian, 2015, UDN.UnknownMonth, 31), UDNCalendarType.ctGregorian, "~ 2015/??/31 [g]"));
            fDates.Add(new UDNRecord(UDN.CreateApproximate(
                                         UDNCalendarType.ctGregorian, 2015, 2, 28), UDNCalendarType.ctGregorian, "~ 2015/02/28 [g]"));

            // standart sort for .NET and Mono gives different result at items 31 and 32
            SortHelper.QuickSort(fDates, delegate(UDNRecord left, UDNRecord right) { return(left.Value.CompareTo(right.Value)); });
            //fDates.Sort(delegate(UDNRecord left, UDNRecord right) { return left.Value.CompareTo(right.Value); });

            Assert.AreEqual("??/??/?? [g]", fDates[0].Description, "(00)");
            Assert.AreEqual("??/??/23 [g]", fDates[1].Description, "(01)");
            Assert.AreEqual("0000/01/03 [g]", fDates[2].Description, "(02)");
            Assert.AreEqual("??/03/23 [g]", fDates[3].Description, "(03)");
            Assert.AreEqual("??/04/23 [g]", fDates[4].Description, "(04)");
            Assert.AreEqual("before ????/05/31 [g]", fDates[5].Description, "(05)");
            Assert.AreEqual("~ ????/05/31 [g]", fDates[6].Description, "(06)");
            Assert.AreEqual("after ????/05/31 [g]", fDates[7].Description, "(07)");
            Assert.AreEqual("after ????/06/15 [g]", fDates[8].Description, "(08)");
            Assert.AreEqual("before -4712/01/02 [g]", fDates[9].Description, "(09)");

            Assert.AreEqual("-4712/01/02 [g]", fDates[10].Description, "(10)");
            Assert.AreEqual("-4712/01/03 [g]", fDates[11].Description, "(11)");
            Assert.AreEqual("-0001/01/03 [g]", fDates[12].Description, "(12)");
            Assert.AreEqual("~ 0001/01/?? [g]", fDates[13].Description, "(13)");
            Assert.AreEqual("0001/01/03 [g]", fDates[14].Description, "(14)");
            Assert.AreEqual("before 0001/01/04 [g]", fDates[15].Description, "(15)");
            Assert.AreEqual("~ 0001/01/04 [g]", fDates[16].Description, "(16)");
            Assert.AreEqual("1801/05/17 [g] = 1216/01/04 [i]", fDates[17].Description, "(17)");
            Assert.AreEqual("1802/05/01 [g]", fDates[18].Description, "(18)");
            Assert.AreEqual("1804/06/13 [g] = 5564/04/04 [h]", fDates[19].Description, "(19)");

            Assert.AreEqual("2014/??/23 [g]", fDates[20].Description, "(20)");
            Assert.AreEqual("after 2015/??/30 [g]", fDates[21].Description, "(21)");
            Assert.AreEqual("before 2015/??/31 [g]", fDates[22].Description, "(22)");
            Assert.AreEqual("~ 2015/??/31 [g]", fDates[23].Description, "(23)");
            Assert.AreEqual("after 2015/??/31 [g]", fDates[24].Description, "(24)");
            Assert.AreEqual("2015/02/27 [g]", fDates[25].Description, "(25)");
            Assert.AreEqual("~ 2015/02/28 [g]", fDates[26].Description, "(26)");
            Assert.AreEqual("2015/03/23 [g]", fDates[27].Description, "(27)");
            Assert.AreEqual("2016/??/?? [g]", fDates[28].Description, "(28)");
            Assert.AreEqual("2016/??/10 [g]", fDates[29].Description, "(29)");

            Assert.AreEqual("2016/05/?? [g]", fDates[30].Description, "(30)");
            Assert.AreEqual("2016/05/04 [g]", fDates[31].Description, "(31)");
            Assert.AreEqual("2016/05/04 [g] = 2016/04/21 [j]", fDates[32].Description, "(32)");

            Assert.AreEqual("2016/05/05 [g]", fDates[33].Description, "(33)");
            Assert.AreEqual("2016/05/06 [g] = 2016/04/23 [j]", fDates[34].Description, "(34)");
            Assert.AreEqual("before 2016/05/31 [g]", fDates[35].Description, "(35)");
            Assert.AreEqual("~ 2016/05/31 [g]", fDates[36].Description, "(36)");
            Assert.AreEqual("2016/05/31 [g]", fDates[37].Description, "(37)");
            Assert.AreEqual("2016/05/31 [g]", fDates[38].Description, "(38)");
            Assert.AreEqual("after 2016/05/31 [g]", fDates[39].Description, "(39)");

            Assert.AreEqual("2016/06/?? [g]", fDates[40].Description, "(40)");
            Assert.AreEqual("3268/01/23 [g]", fDates[41].Description, "(41)");

            UDNRecord rec;

            Assert.Throws(typeof(ArgumentOutOfRangeException), () => { rec = fDates[42]; }, "(42)"); // end
        }
        public static int CompareValues(string s1, string s2)
        {
            if (s1 == null || s2 == null)
            {
                return(0);
            }

            int thisMarker = 0, thisNumericChunk = 0;
            int thatMarker = 0, thatNumericChunk = 0;

            while ((thisMarker < s1.Length) || (thatMarker < s2.Length))
            {
                if (thisMarker >= s1.Length)
                {
                    return(-1);
                }
                else if (thatMarker >= s2.Length)
                {
                    return(1);
                }
                char thisCh = s1[thisMarker];
                char thatCh = s2[thatMarker];

                StringBuilder thisChunk = new StringBuilder();
                StringBuilder thatChunk = new StringBuilder();

                while ((thisMarker < s1.Length) && (thisChunk.Length == 0 || SortHelper.InChunk(thisCh, thisChunk[0])))
                {
                    thisChunk.Append(thisCh);
                    thisMarker++;

                    if (thisMarker < s1.Length)
                    {
                        thisCh = s1[thisMarker];
                    }
                }

                while ((thatMarker < s2.Length) && (thatChunk.Length == 0 || SortHelper.InChunk(thatCh, thatChunk[0])))
                {
                    thatChunk.Append(thatCh);
                    thatMarker++;

                    if (thatMarker < s2.Length)
                    {
                        thatCh = s2[thatMarker];
                    }
                }

                int result = 0;
                // If both chunks contain numeric characters, sort them numerically
                if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))
                {
                    if (!int.TryParse(thisChunk.ToString(), out thisNumericChunk))
                    {
                        return(0);
                    }
                    if (!int.TryParse(thatChunk.ToString(), out thatNumericChunk))
                    {
                        return(0);
                    }

                    if (thisNumericChunk < thatNumericChunk)
                    {
                        result = -1;
                    }

                    if (thisNumericChunk > thatNumericChunk)
                    {
                        result = 1;
                    }
                }
                else
                {
                    result = thisChunk.ToString().CompareTo(thatChunk.ToString());
                }

                if (result != 0)
                {
                    return(result);
                }
            }

            return(0);
        }
        private void SortByColumn(int theIndex, Comparison<SortHelper> theCompareFunc)
        {
            List<SortHelper> aList = new List<SortHelper>();
            for (int aRowIndex = 1; aRowIndex < dataGridView.Rows.Count; aRowIndex++)
            {
                var aRow = dataGridView.Rows[aRowIndex];
                var aHelper = new SortHelper();
                aList.Add(aHelper);
                aHelper.OriginalPosition = aRowIndex;
                for (int acellIndex = 1; acellIndex < aRow.Cells.Count; acellIndex++)
                {
                    aHelper.Values.Add(aRow.Cells[acellIndex].Value);
                    if (acellIndex == theIndex)
                    {
                        aHelper.SortObj = aRow.Cells[acellIndex].Value;
                    }
                }
            }

            aList.Sort((aSortHelper1, aSortHelper2) => theCompareFunc(aSortHelper1, aSortHelper2));

            for (int aRowIndex = 1; aRowIndex < dataGridView.Rows.Count; aRowIndex++)
            {
                var aRow = dataGridView.Rows[aRowIndex];
                for (int aCellIndex = 1; aCellIndex < aRow.Cells.Count; aCellIndex++)
                {
                    aRow.Cells[aCellIndex].Value = aList[aRowIndex - 1].Values[aCellIndex - 1];
                }
            }
        } 
        private void SortByRow(int theIndex, Comparison<SortHelper> theCompareFunc)
        {
            List<SortHelper> aList = new List<SortHelper>();
            for (int aI = 1; aI < dataGridView.Columns.Count; aI++)
            {
                var aHelper = new SortHelper();
                aHelper.OriginalPosition = aI;
                aList.Add(aHelper);
            }

            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                if (row.Index == 0)
                {
                    continue;
                }

                for (int aI = 1; aI < row.Cells.Count; aI++)
                {
                    if (row.Index == theIndex)
                    {
                        aList[aI - 1].SortObj = row.Cells[aI].Value;
                    }

                    aList[aI - 1].Values.Add(row.Cells[aI].Value);
                }
            }

            aList.Sort((aSortHelper1, aSortHelper2) => theCompareFunc(aSortHelper1, aSortHelper2));

            for (int aRowIndex = 1; aRowIndex < dataGridView.Rows.Count; aRowIndex++)
            {
                var aRow = dataGridView.Rows[aRowIndex];
                for (int aCellIndex = 1; aCellIndex < aRow.Cells.Count; aCellIndex++)
                {
                    aRow.Cells[aCellIndex].Value = aList[aCellIndex - 1].Values[aRowIndex - 1];
                }
            }
        }
示例#13
0
 public void BubbleSortTest_EmptyArray()
 {
     int[] myArray = new int[0];
     Assert.That(() => SortHelper.BubbleSort(myArray), Throws.TypeOf <Exception>().With.Message.EqualTo("Invalid input"));
 }
示例#14
0
        public virtual IQueryable <TEntity> GetBy(Expression <Func <TEntity, bool> > predicate, SortHelper order = null, int initialPage = 0, int recordsPerPage = 50)
        {
            var query = db.Where(predicate);
            var x     = query.Pagination(order, initialPage, recordsPerPage);

            return(x);
        }
示例#15
0
        private async void RestoreSortIfNeed()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(_RestoreSortIfNeedAction);
                return;
            }

            if (!_LastSortInfo.TryGetSorting(out var columnIndex, out var sortOrder))
            {
                DGV.ClearHeaderSortGlyphDirection();
                return;
            }

            #region [.get comparison routine.]
            var comparison = default(Comparison <DownloadRow>);
            switch (columnIndex)
            {
            case OUTPUTFILENAME_COLUMN_INDEX:
                comparison = (x, y) => string.Compare(x.OutputFileName, y.OutputFileName, true);
                break;

            case OUTPUTDIRECTORY_COLUMN_INDEX:
                comparison = (x, y) => string.Compare(x.OutputDirectory, y.OutputDirectory, true);
                break;

            case STATUS_COLUMN_INDEX:
                comparison = (x, y) => SortHelper.ToInt32(x.Status).CompareTo(SortHelper.ToInt32(y.Status));
                break;

            case DOWNLOAD_PROGRESS_COLUMN_INDEX:
                comparison = (x, y) => x.SuccessDownloadParts.CompareTo(y.SuccessDownloadParts);
                break;

            case DOWNLOAD_BYTES_COLUMN_INDEX:
                comparison = (x, y) => x.DownloadBytesLength.CompareTo(y.DownloadBytesLength);
                break;

            case APPROX_REMAINED_BYTES_COLUMN_INDEX:
                comparison = (x, y) => x.GetApproxRemainedBytes().CompareTo(y.GetApproxRemainedBytes());
                break;

            case APPROX_TOTAL_BYTES_COLUMN_INDEX:
                comparison = (x, y) => x.GetApproxTotalBytes().CompareTo(y.GetApproxTotalBytes());
                break;

            case URL_COLUMN_INDEX:
                comparison = (x, y) => string.Compare(x.Url, y.Url, true);
                break;

            case DOWNLOAD_TIME_COLUMN_INDEX:
            case APPROX_REMAINED_TIME_COLUMN_INDEX:
            case DOWNLOAD_SPEED_COLUMN_INDEX:
                //---comparison = (x, y) => x..CompareTo( y. );
                return;

            default:
                DGV.ClearHeaderSortGlyphDirection();
                throw (new NotImplementedException($"columnIndex: {columnIndex}"));
            }
            #endregion

            var coeff = ((sortOrder == SortOrder.Ascending) ? 1 : -1);
            var row   = GetSelectedDownloadRow();

            _Model.Sort(SortHelper.CreateComparison(comparison, coeff));

            DGV.SetHeaderSortGlyphDirection(columnIndex, sortOrder);
            await Task.Delay(1);

            SelectDownloadRowInternal(row, true);
        }
示例#16
0
        protected override void InternalGenerate()
        {
            IColor clrBlack = AppHost.GfxProvider.CreateColor(0x000000);
            IColor clrBlue  = AppHost.GfxProvider.CreateColor(0x0000FF);

            fTitleFont = fWriter.CreateFont("", 14f, true, false, clrBlack);
            fChapFont  = fWriter.CreateFont("", 12f, true, false, clrBlack);
            fTextFont  = fWriter.CreateFont("", 10f, false, false, clrBlack);

            //fWriter.AddParagraph(fTitle, fTitleFont, TextAlignment.taLeft);
            fWriter.AddParagraph(GKUtils.GetNameString(fPerson, true, false), fTitleFont, TextAlignment.taLeft);
            fWriter.NewLine();

            var evList = new List <PersonalEvent>();

            GDMIndividualRecord father = null, mother = null;

            if (fPerson.ChildToFamilyLinks.Count > 0)
            {
                GDMFamilyRecord family = fPerson.ChildToFamilyLinks[0].Family;
                if (fBase.Context.IsRecordAccess(family.Restriction))
                {
                    father = family.Husband.Individual;
                    mother = family.Wife.Individual;
                }
            }

            ExtractEvents(EventType.Personal, evList, fPerson);

            int num2 = fPerson.SpouseToFamilyLinks.Count;

            for (int j = 0; j < num2; j++)
            {
                GDMFamilyRecord family = fPerson.SpouseToFamilyLinks[j].Family;
                if (!fBase.Context.IsRecordAccess(family.Restriction))
                {
                    continue;
                }

                ExtractEvents(EventType.Spouse, evList, family);

                int num3 = family.Children.Count;
                for (int i = 0; i < num3; i++)
                {
                    GDMIndividualRecord child = family.Children[i].Individual;
                    GDMCustomEvent      evt   = child.FindEvent(GEDCOMTagType.BIRT);
                    if (evt != null && evt.GetChronologicalYear() != 0)
                    {
                        evList.Add(new PersonalEvent(EventType.Child, child, evt));
                    }
                }
            }

            SortHelper.QuickSort(evList, EventsCompare);
            fWriter.BeginList();

            int num4 = evList.Count;

            for (int i = 0; i < num4; i++)
            {
                PersonalEvent evObj = evList[i];
                if (!evObj.Date.HasKnownYear())
                {
                    continue;
                }

                GDMCustomEvent evt = evObj.Event;
                string         st  = GKUtils.GetEventName(evt);
                string         dt  = GKUtils.GEDCOMEventToDateStr(evt, GlobalOptions.Instance.DefDateFormat, false);

                if (ShowAges)
                {
                    int year = evt.GetChronologicalYear();
                    int age  = (evObj.Rec == fPerson) ? GKUtils.GetAge(fPerson, year) : -1;
                    if (age >= 0)
                    {
                        dt += string.Format(" ({0})", age);
                    }
                }

                string li = dt + ": " + st + ".";
                if (evt.Place.StringValue != "")
                {
                    li = li + " " + LangMan.LS(LSID.LSID_Place) + ": " + evt.Place.StringValue;
                }
                fWriter.AddListItem("   " + li, fTextFont);

                if (evObj.Rec is GDMIndividualRecord)
                {
                    GDMIndividualRecord iRec = evObj.Rec as GDMIndividualRecord;

                    if (evt.GetTagType() == GEDCOMTagType.BIRT)
                    {
                        if (evObj.Type == EventType.Personal)
                        {
                            if (father != null)
                            {
                                fWriter.AddListItem("   " + "   " + LangMan.LS(LSID.LSID_Father) + ": " + GKUtils.GetNameString(father, true, false) + " ", fTextFont);
                            }
                            if (mother != null)
                            {
                                fWriter.AddListItem("   " + "   " + LangMan.LS(LSID.LSID_Mother) + ": " + GKUtils.GetNameString(mother, true, false) + " ", fTextFont);
                            }
                        }
                        else if (evObj.Type == EventType.Child)
                        {
                            if (iRec.Sex == GDMSex.svMale)
                            {
                                st = LangMan.LS(LSID.LSID_RK_Son) + ": ";
                            }
                            else
                            {
                                st = LangMan.LS(LSID.LSID_RK_Daughter) + ": ";
                            }
                            st = ConvertHelper.UniformName(st) + GKUtils.GetNameString(iRec, true, false);
                            fWriter.AddListItem("   " + "   " + st, fTextFont);
                        }
                    }
                }
                else if (evObj.Rec is GDMFamilyRecord)
                {
                    GDMFamilyRecord famRec = evObj.Rec as GDMFamilyRecord;

                    GDMIndividualRecord sp;
                    string unk;
                    if (fPerson.Sex == GDMSex.svMale)
                    {
                        sp  = famRec.Wife.Individual;
                        st  = LangMan.LS(LSID.LSID_Wife) + ": ";
                        unk = LangMan.LS(LSID.LSID_UnkFemale);
                    }
                    else
                    {
                        sp  = famRec.Husband.Individual;
                        st  = LangMan.LS(LSID.LSID_Husband) + ": ";
                        unk = LangMan.LS(LSID.LSID_UnkMale);
                    }

                    string sps;
                    if (sp != null)
                    {
                        sps = st + GKUtils.GetNameString(sp, true, false) /* + GKUtils.GetPedigreeLifeStr(sp, fOptions.PedigreeOptions.Format)*/;
                    }
                    else
                    {
                        sps = st + unk;
                    }
                    fWriter.AddListItem("   " + "   " + sps, fTextFont);
                }
            }

            fWriter.EndList();
        }
示例#17
0
        public PrintLabelResult PrintBatch(long batchId,
                                           long companyId,
                                           long?by)
        {
            var printLabelResult = new PrintLabelResult()
            {
                IsPrintStarted = false
            };

            var syncInfo = new DbSyncInformer(_dbFactory,
                                              _log,
                                              _time,
                                              SyncType.PostagePurchase,
                                              "",
                                              MarketType.None,
                                              JsonConvert.SerializeObject(new { batchId = batchId }));

            using (var db = _dbFactory.GetRWDb())
            {
                var when           = _time.GetAppNowTime();
                var company        = db.Companies.GetByIdWithSettingsAsDto(companyId);
                var companyAddress = new CompanyAddressService(company);

                var labelProviders = _serviceFactory.GetShipmentProviders(_log,
                                                                          _time,
                                                                          _dbFactory,
                                                                          _weightService,
                                                                          company.ShipmentProviderInfoList,
                                                                          _defaultCustomType,
                                                                          _labelDirectory,
                                                                          _reserveDirectory,
                                                                          _templateDirectory);

                var labelService = new LabelService(labelProviders, _log, _time, _dbFactory, _emailService, _pdfMaker, _addressService);

                CompanyHelper.UpdateBalance(db,
                                            company,
                                            labelProviders,
                                            true,
                                            when);

                var orderIds = db.OrderBatches.GetOrderIdsForBatch(
                    batchId,
                    OrderStatusEnumEx.AllUnshippedWithShipped //for composing pdf file with all
                    );

                var batchDto = db.OrderBatches.GetAsDto(batchId);
                //Close batch
                db.OrderBatches.CloseBatch(batchId);

                SendBeforePrintNotificationMessage(batchDto.Name);

                var shippingList =
                    db.OrderShippingInfos.GetOrderInfoWithItems(_weightService,
                                                                orderIds.ToList(),
                                                                SortMode.ByLocation,
                                                                unmaskReferenceStyle: false,
                                                                includeSourceItems: false).ToList();

                //NOTE: Update from address
                var dropShipperList = db.DropShippers.GetAllAsDto().ToList();
                foreach (var shipping in shippingList)
                {
                    shipping.ReturnAddress = dropShipperList.FirstOrDefault(ds => ds.Id == shipping.DropShipperId)?.GetAddressDto();
                }

                //NOTE: update phone if missing
                foreach (var shipping in shippingList)
                {
                    if (shipping.ShippingMethod.CarrierName == ShippingServiceUtils.FedexCarrier &&
                        String.IsNullOrEmpty(shipping.ToAddress.FinalPhone))
                    {
                        shipping.ToAddress.Phone         = company.Phone;
                        shipping.ToAddress.ManuallyPhone = company.Phone;
                    }
                }

                //NOTE: Sort for setting #
                shippingList = SortHelper.Sort(shippingList, SortMode.ByShippingMethodThenLocation).ToList();

                IList <long> removedOrderIds = new List <long>();
                if (!syncInfo.IsSyncInProgress())
                {
                    UpdateLabelPrintStatus(db, orderIds, shippingList);

                    removedOrderIds = RemoveOrdersWithIssue(db, orderIds, shippingList, printLabelResult);
                    if (removedOrderIds.Any())
                    {
                        var batchName = string.Format("Issues of {0} {1} orders", batchDto.Name,
                                                      removedOrderIds.Count);

                        db.OrderBatches.CreateBatch(batchName,
                                                    BatchType.PrintLabel,
                                                    removedOrderIds,
                                                    when,
                                                    by);

                        //NOTE: keep to final email notification
                        //shippingList = shippingList.Where(sh => !removedOrderIds.Contains(sh.OrderId)).ToList();
                    }

                    //Removed list
                    var removedList = shippingList.Where(sh => removedOrderIds.Contains(sh.OrderId)).ToList();
                    if (batchDto.LockDate.HasValue)
                    {
                        var historyRemovedOrderIds = db.OrderChangeHistories.GetAll().Where(ch => ch.FromValue == batchDto.Id.ToString() &&
                                                                                            ch.FieldName == OrderHistoryHelper.AddToBatchKey &&
                                                                                            ch.ChangeDate >= batchDto.LockDate)
                                                     .Select(ch => ch.OrderId)
                                                     .Distinct()
                                                     .ToList();

                        historyRemovedOrderIds = historyRemovedOrderIds.Where(id => !orderIds.Contains(id)).ToList();
                        var historyShippingList = db.OrderShippingInfos.GetOrderInfoWithItems(_weightService,
                                                                                              historyRemovedOrderIds.ToList(),
                                                                                              SortMode.ByLocation,
                                                                                              unmaskReferenceStyle: false,
                                                                                              includeSourceItems: false).ToList();
                        removedList.AddRange(historyShippingList);
                    }

                    //Changed list
                    var styleChangedList = new List <StyleChangeInfo>();
                    if (batchDto.LockDate.HasValue)
                    {
                        var historyChangeStyles = db.OrderChangeHistories.GetAll().Where(ch => orderIds.Contains(ch.OrderId) &&
                                                                                         ch.FieldName == OrderHistoryHelper.ReplaceItemKey &&
                                                                                         ch.ChangeDate >= batchDto.LockDate)
                                                  .ToList();
                        foreach (var change in historyChangeStyles)
                        {
                            if (!String.IsNullOrEmpty(change.FromValue) &&
                                !String.IsNullOrEmpty(change.ToValue))
                            {
                                var fromStyleItemId = StringHelper.ToInt(change.FromValue);
                                var fromStyleItem   = db.StyleItems.GetAll().FirstOrDefault(si => si.Id == fromStyleItemId);
                                var toStyleItemId   = StringHelper.ToInt(change.ToValue);
                                var toStyleItem     = db.StyleItems.GetAll().FirstOrDefault(si => si.Id == toStyleItemId);
                                if (fromStyleItem != null &&
                                    toStyleItem != null)
                                {
                                    var fromStyle = db.Styles.Get(fromStyleItem.StyleId);
                                    var toStyle   = db.Styles.Get(toStyleItem.StyleId);

                                    styleChangedList.Add(new StyleChangeInfo()
                                    {
                                        SourceStyleString = fromStyle.StyleID,
                                        SourceStyleSize   = fromStyleItem.Size,
                                        DestStyleString   = toStyle.StyleID,
                                        DestStyleSize     = toStyleItem.Size,
                                    });
                                }
                            }
                        }
                    }

                    //Printing
                    printLabelResult = labelService.PrintLabels(db,
                                                                company,
                                                                companyAddress,
                                                                syncInfo,
                                                                batchId,
                                                                shippingList,
                                                                false,
                                                                removedList,
                                                                styleChangedList,
                                                                batchDto.ScanFormPath,
                                                                _labelDirectory,
                                                                _isSampleMode,
                                                                when,
                                                                by);
                    printLabelResult.RemovedIds = removedOrderIds;

                    long?failedBatchId = null;
                    //Move orders with errors to a new batch
                    if (printLabelResult.FailedIds.Count > 0)
                    {
                        var batchName = string.Format("Failed of {0} {1} orders", batchDto.Name,
                                                      printLabelResult.FailedIds.Count);

                        var failedOrderIds = printLabelResult.FailedIds.Select(s => s.OrderId).Distinct().ToList();
                        failedBatchId = db.OrderBatches.CreateBatch(batchName,
                                                                    BatchType.PrintLabel,
                                                                    failedOrderIds,
                                                                    when,
                                                                    by);
                        printLabelResult.Messages.Add(
                            new Message(
                                String.Format("{0} unprinted orders was moved to new batch \"{1}\"",
                                              failedOrderIds.Count, batchName), MessageTypes.Error));
                    }

                    if (printLabelResult.IsPrintStarted)
                    {
                        //Send notification to seller
                        SendAfterPrintNotificationMessage(db,
                                                          printLabelResult.Messages,
                                                          batchDto.Id,
                                                          batchDto.Name,
                                                          company,
                                                          shippingList.Where(sh => printLabelResult.RemovedIds.Any(f => f == sh.OrderId)).ToList(),
                                                          shippingList.Where(sh => printLabelResult.FailedIds.Any(f => f.ShipmentId == sh.Id)).ToList());

                        //Apply new balance to Session
                        CompanyHelper.UpdateBalance(db,
                                                    company,
                                                    labelProviders,
                                                    false,
                                                    _time.GetAppNowTime());

                        SaveBatchPrintResultToDb(db,
                                                 _log,
                                                 batchDto.Id,
                                                 printLabelResult,
                                                 shippingList,
                                                 _time.GetAppNowTime(),
                                                 by);

                        if (printLabelResult.FailedIds.Any())
                        {
                            printLabelResult.Messages.Add(new Message(printLabelResult.GetConcatFailedOrdersString(),
                                                                      MessageTypes.Error));
                        }
                    }
                    else
                    {
                        _emailService.SendSystemEmailToAdmin(String.Format("Batch \"{0}\" print wasn't started", batchDto.Name),
                                                             String.Format("Ended at {0}", _time.GetAppNowTime()));
                    }
                }
                else
                {
                    printLabelResult.Messages.Add(new Message("Request rejected. The system is already buys postage", MessageTypes.Warning));
                }

                return(printLabelResult);
            }
        }
示例#18
0
 public static string BuildCheatSheet(bool extended, bool fixedWidth)
 {
     return(BuildCheatSheet2(extended, fixedWidth, SortHelper.OrderedRules( )));
 }
示例#19
0
        public List <ApplicationUser> GetNotAllocatedStudentsJsonData(int?page, int?limit, string sortBy, string direction, out int total)
        {
            var approvedStudents = _context.ProjectStudents
                                   .Include(p => p.ApplicationUser)
                                   .Select(p => new ApplicationUser()
            {
                FirstName   = p.ApplicationUser.FirstName,
                LastName    = p.ApplicationUser.LastName,
                Email       = p.ApplicationUser.Email,
                PhoneNumber = p.ApplicationUser.PhoneNumber,
                UserName    = p.ApplicationUser.UserName
            });

            //var notApprovedStudents1 = _context.ProjectStudentChoices
            //   .Include(p => p.Project)
            //   .Include(p => p.ApplicationUser)
            //   .Where(p => p.IsApproved && p.Project.IsClosed)
            //   .Select(p => new ApplicationUser()
            //   {

            //       FirstName = p.ApplicationUser.FirstName,
            //       LastName = p.ApplicationUser.LastName,
            //       Email = p.ApplicationUser.Email,
            //       PhoneNumber = p.ApplicationUser.PhoneNumber,
            //       UserName = p.ApplicationUser.UserName
            //   });

            var notApprovedStudents = _context.ApplicationUsers
                                      .Where(p => !_context.ProjectStudentChoices.Where(a => a.IsApproved && a.Project.IsClosed).Select(c => c.ApplicationUserId).Contains(p.Id) &&
                                             _context.UserRoles.Where(c => c.RoleId == "1f8cd529-9587-48a9-8efe-f9a1ec3b6268").Select(c => c.UserId).Contains(p.Id)).Select(p => new ApplicationUser()
            {
                FirstName   = p.FirstName,
                LastName    = p.LastName,
                Email       = p.Email,
                PhoneNumber = p.PhoneNumber,
                UserName    = p.UserName
            });

            var records = notApprovedStudents.Except(approvedStudents);

            total = records.Count();

            if (!string.IsNullOrEmpty(sortBy) && !string.IsNullOrEmpty(direction))
            {
                if (direction.Trim().ToLower() == "asc")
                {
                    records = SortHelper.OrderBy(records, sortBy);
                }
                else
                {
                    records = SortHelper.OrderByDescending(records, sortBy);
                }
            }
            if (page.HasValue && limit.HasValue)
            {
                int start = (page.Value - 1) * limit.Value;
                records = records.Skip(start).Take(limit.Value);
            }

            return(records.ToList());
        }
示例#20
0
        public ListModel <LanguageModel> List(FilterModel filterModel)
        {
            var startDate = filterModel.StartDate.ResetTimeToStartOfDay();

            var endDate = filterModel.EndDate.ResetTimeToEndOfDay();

            Expression <Func <Language, bool> > expression;

            if (filterModel.Status != -1)
            {
                var status = filterModel.Status.ToString().ToBoolean();

                if (filterModel.Searched != null)
                {
                    if (status)
                    {
                        expression = c => c.IsApproved && c.Name.Contains(filterModel.Searched);
                    }
                    else
                    {
                        expression = c => c.IsApproved == false && c.Name.Contains(filterModel.Searched);
                    }
                }
                else
                {
                    if (status)
                    {
                        expression = c => c.IsApproved;
                    }
                    else
                    {
                        expression = c => c.IsApproved == false;
                    }
                }
            }
            else
            {
                if (filterModel.Searched != null)
                {
                    expression = c => c.Name.Contains(filterModel.Searched);
                }
                else
                {
                    expression = c => c.Id != Guid.Empty;
                }
            }

            expression = expression.And(e => e.CreationTime >= startDate && e.CreationTime <= endDate);

            var listModel = filterModel.CreateMapped <FilterModel, ListModel <LanguageModel> >();

            listModel.Paging ??= new Paging
            {
                PageSize   = filterModel.PageSize,
                PageNumber = filterModel.PageNumber
            };

            var sortHelper = new SortHelper <Language>();

            sortHelper.OrderBy(x => x.DisplayOrder);

            var query = (IOrderedQueryable <Language>)_repositoryLanguage
                        .Get().Where(expression);

            query = sortHelper.GenerateOrderedQuery(query);

            listModel.Paging.TotalItemCount = query.Count();

            var items = listModel.Paging.PageSize > 0 ? query.Skip((listModel.Paging.PageNumber - 1) * listModel.Paging.PageSize).Take(listModel.Paging.PageSize) : query;

            var modelItems = new HashSet <LanguageModel>();

            foreach (var item in items)
            {
                var modelItem = item.CreateMapped <Language, LanguageModel>();

                modelItems.Add(modelItem);
            }

            listModel.Items = modelItems.ToList();

            var pageSizeDescription = _serviceMain.ApplicationSettings.PageSizeList;

            var pageSizes = pageSizeDescription.Split(',').Select(s => new KeyValuePair <int, string>(s.ToInt(), s)).ToList();

            pageSizes.Insert(0, new KeyValuePair <int, string>(-1, "[" + Dictionary.All + "]"));

            listModel.Paging.PageSizes = pageSizes;

            listModel.Paging.PageCount = (int)Math.Ceiling((float)listModel.Paging.TotalItemCount / listModel.Paging.PageSize);

            if (listModel.Paging.TotalItemCount > listModel.Items.Count)
            {
                listModel.Paging.HasNextPage = true;
            }

            if (listModel.Paging.PageNumber == 1)
            {
                if (listModel.Paging.TotalItemCount > 0)
                {
                    listModel.Paging.IsFirstPage = true;
                }


                if (listModel.Paging.PageCount == 1)
                {
                    listModel.Paging.IsLastPage = true;
                }
            }

            else if (listModel.Paging.PageNumber == listModel.Paging.PageCount)
            {
                listModel.Paging.HasNextPage = false;

                if (listModel.Paging.PageCount > 1)
                {
                    listModel.Paging.IsLastPage      = true;
                    listModel.Paging.HasPreviousPage = true;
                }
            }

            else
            {
                listModel.Paging.HasNextPage     = true;
                listModel.Paging.HasPreviousPage = true;
            }

            if (listModel.Paging.TotalItemCount > listModel.Items.Count && listModel.Items.Count <= 0)
            {
                listModel.Message = Messages.DangerRecordNotFoundInPage;
            }

            if (listModel.Paging.TotalItemCount == 0)
            {
                listModel.Message = Messages.DangerRecordNotFound;
            }

            return(listModel);
        }
示例#21
0
        public IActionResult Index(
            string f          = "/",
            string colorClass = null,
            bool collections  = true,
            bool hidedelete   = true,
            SortType sort     = SortType.FileName
            )
        {
            // Used in Detail and Index View => does not hide this single item
            var colorClassActiveList = FileIndexItem.GetColorClassList(colorClass);

            var subPath = PathHelper.PrefixDbSlash(f);

            subPath = PathHelper.RemoveLatestSlash(subPath);
            if (string.IsNullOrEmpty(subPath))
            {
                subPath = "/";
            }

            // First check if it is a single Item
            var singleItem = _query.SingleItem(subPath, colorClassActiveList, collections, hidedelete, sort);

            // returns no object when it a directory

            if (singleItem?.IsDirectory == false)
            {
                singleItem.IsReadOnly = _appSettings.IsReadOnly(singleItem.FileIndexItem.ParentDirectory);
                return(Json(singleItem));
            }

            var fileIndexItems = SortHelper.Helper(
                _query.DisplayFileFolders(subPath, colorClassActiveList,
                                          collections, hidedelete), sort).ToList();
            var fileIndexItemsWithoutCollections = _query.DisplayFileFolders(
                subPath, null, false, hidedelete).ToList();

            // (singleItem.IsDirectory) or not found
            var directoryModel = new ArchiveViewModel
            {
                FileIndexItems       = fileIndexItems,
                ColorClassActiveList = colorClassActiveList,
                RelativeObjects      = _query.GetNextPrevInFolder(subPath), // Args are not shown in this view
                Breadcrumb           = Breadcrumbs.BreadcrumbHelper(subPath),
                SearchQuery          = subPath.Split("/").LastOrDefault(),
                SubPath          = subPath,
                CollectionsCount = fileIndexItemsWithoutCollections.
                                   Count(p => p.IsDirectory == false),
                // when change colorclass selection you should see all options
                ColorClassUsage = fileIndexItemsWithoutCollections
                                  .Select(p => p.ColorClass).Distinct()
                                  .OrderBy(p => (int)(p)).ToList(),
                IsReadOnly  = _appSettings.IsReadOnly(subPath),
                Collections = collections,
            };

            if (singleItem == null)
            {
                // For showing a new database
                var queryIfFolder = _query.GetObjectByFilePath(subPath);

                // For showing a new database
                if (f == "/" && queryIfFolder == null)
                {
                    return(Json(directoryModel));
                }

                if (queryIfFolder == null) // used to have: singleItem?.FileIndexItem.FilePath == null &&
                {
                    Response.StatusCode = 404;
                    return(Json("not found"));
                }
            }

            return(Json(directoryModel));
        }
示例#22
0
        private ListModel <CategoryModel> List(DateTime startDate, DateTime endDate, int pageNumber, int pageSize, int status, string searched, Guid languageId, ListModel <CategoryModel> model)
        {
            var resetedStartDate = startDate.ResetTimeToStartOfDay();
            var resetedEndDate   = endDate.ResetTimeToEndOfDay();
            var language         = languageId != Guid.Empty ? _repositoryLanguage.Get(x => x.Id == languageId) : _defaultLanguage;

            Expression <Func <Category, bool> > expression;

            if (model.Paging == null)
            {
                model.Paging = new Paging
                {
                    PageSize   = pageSize,
                    PageNumber = pageNumber
                };
            }

            if (status != -1)
            {
                var bStatus = status.ToString().ToBoolean();
                if (searched != null)
                {
                    if (bStatus)
                    {
                        expression = c => c.CategoryLanguageLines.Any(x => x.Name.Contains(searched) && x.IsApproved);
                    }
                    else
                    {
                        expression = c => c.CategoryLanguageLines.Any(x => x.Name.Contains(searched) && x.IsApproved == false);
                    }
                }
                else
                {
                    if (bStatus)
                    {
                        expression = c => c.CategoryLanguageLines.Any(x => x.IsApproved);
                    }
                    else
                    {
                        expression = c => c.CategoryLanguageLines.Any(x => x.IsApproved == false);
                    }
                }
            }
            else
            {
                if (searched != null)
                {
                    expression = c => c.CategoryLanguageLines.Any(x => x.Name.Contains(searched));
                }
                else
                {
                    expression = c => c.Id != Guid.Empty;
                }
            }

            expression = expression.And(e => e.CreationTime >= resetedStartDate && e.CreationTime <= resetedEndDate);

            var sortHelper = new SortHelper <CategoryModel>();

            var query = _repositoryCategory
                        .Join(x => x.Creator.Person)
                        .Join(x => x.LastModifier.Person)
                        .Join(z => z.CategoryLanguageLines)
                        .ThenJoin(x => x.Language)
                        .Where(expression);

            sortHelper.OrderBy(x => x.DisplayOrder);

            model.Paging.TotalItemCount = query.Count();
            var items      = model.Paging.PageSize > 0 ? query.Skip((model.Paging.PageNumber - 1) * model.Paging.PageSize).Take(model.Paging.PageSize) : query;
            var modelItems = new HashSet <CategoryModel>();

            foreach (var item in items)
            {
                CategoryModel modelItem;
                if (item.CategoryLanguageLines == null)
                {
                    modelItem = new CategoryModel();
                }
                else
                {
                    var itemLine = item.CategoryLanguageLines.FirstOrDefault(x => x.Language.Id == language.Id);
                    modelItem = itemLine != null?itemLine.CreateMapped <CategoryLanguageLine, CategoryModel>() : new CategoryModel();
                }

                modelItem.Creator      = new IdCodeName(item.Creator.Id, item.Creator.Username, item.Creator.Person.DisplayName);
                modelItem.LastModifier = new IdCodeName(item.LastModifier.Id, item.LastModifier.Username, item.LastModifier.Person.DisplayName);
                modelItem.Language     = new IdCodeName(language.Id, language.Code, language.Name);
                modelItem.CategoryId   = item.Id;
                modelItems.Add(modelItem);
            }
            model.Items = modelItems.ToList();
            var pageSizeDescription = _serviceMain.ApplicationSettings.PageSizeList;
            var pageSizes           = pageSizeDescription.Split(',').Select(s => new KeyValuePair <int, string>(s.ToInt(), s)).ToList();

            pageSizes.Insert(0, new KeyValuePair <int, string>(-1, "[" + Dictionary.All + "]"));
            model.Paging.PageSizes = pageSizes;
            model.Paging.PageCount = (int)Math.Ceiling((float)model.Paging.TotalItemCount / model.Paging.PageSize);
            if (model.Paging.TotalItemCount > model.Items.Count)
            {
                model.Paging.HasNextPage = true;
            }

            // ilk sayfa ise

            if (model.Paging.PageNumber == 1)
            {
                if (model.Paging.TotalItemCount > 0)
                {
                    model.Paging.IsFirstPage = true;
                }

                // tek sayfa ise

                if (model.Paging.PageCount == 1)
                {
                    model.Paging.IsLastPage = true;
                }
            }

            // son sayfa ise
            else if (model.Paging.PageNumber == model.Paging.PageCount)
            {
                model.Paging.HasNextPage = false;
                // tek sayfa değilse

                if (model.Paging.PageCount > 1)
                {
                    model.Paging.IsLastPage      = true;
                    model.Paging.HasPreviousPage = true;
                }
            }

            // ara sayfa ise
            else
            {
                model.Paging.HasNextPage     = true;
                model.Paging.HasPreviousPage = true;
            }

            if (model.Paging.TotalItemCount > model.Items.Count && model.Items.Count <= 0)
            {
                model.Message = Messages.DangerRecordNotFoundInPage;
            }

            if (model.Paging.TotalItemCount == 0)
            {
                model.Message = Messages.DangerRecordNotFound;
            }
            return(model);
        }
        public JsonResult GetNewOrder(string sidx, string sord, int page, int rows, string colName, string colValue)  //Gets the todo Lists.
        {
            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize  = rows;

            List <SaleRecordViewModel> vmorder = new List <SaleRecordViewModel>();
            var productList = _productBusiness.GetListWT();
            var orderList   = _orderBusiness.GetListWT();

            vmorder = (from c in orderList
                       select new SaleRecordViewModel
            {
                OrderId = c.OrderId,
                OrderStatus = c.OrderStatus,
                OrderCode = c.OrderCode,
                OrderDate = c.OrderDate,
                Vat = Convert.ToDouble(GetVATOrderedItems(c.OrderId, productList)),
                Sat = Convert.ToDouble(GetSATOrderedItems(c.OrderId, productList)),
                // TotalPrice = 2000,
                TotalPrice = Convert.ToDouble(GetOrderedItems(c.OrderId, productList)),
                CustomerName = c.FirstName + " " + c.LastName,
                Discount = Convert.ToDouble(GetDiscountedOrderedItems(c.OrderId, productList)),
                TaxTotalPrice = Convert.ToDouble(GetTotal(c.OrderId, productList))
            }).OrderByDescending(col => col.OrderDate).Where(u => u.OrderStatus == "Delivered").ToList();

            var records      = vmorder.AsQueryable();
            int totalRecords = records.Count();
            var totalPages   = (int)Math.Ceiling((float)totalRecords / (float)rows);

            if (!string.IsNullOrEmpty(sidx) && !string.IsNullOrEmpty(sord))
            {
                if (sord.Trim().ToLower() == "asc")
                {
                    records = SortHelper.OrderBy(records, sidx);
                }
                else
                {
                    records = SortHelper.OrderByDescending(records, sidx);
                }
            }

            if (!string.IsNullOrEmpty(colName) && !string.IsNullOrEmpty(colValue))
            {
                records = records.Where(c => c.GetType().GetProperty(colName).GetValue(c, null).ToString().ToLower().Contains(colValue.ToLower()));
            }
            //applying filter

            // int totalRecords = records.Count();
            //  var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);


            //applying paging
            records = records.Skip(pageIndex * pageSize).Take(pageSize);

            var jsonData = new
            {
                total = totalPages,
                page,
                records = totalRecords,
                rows    = records
            };

            return(Json(jsonData, JsonRequestBehavior.AllowGet));
        }
示例#24
0
 public void SwapSort()
 {
     Assert.Equal <int[]>(new int[] { 0, 1, 2, 2, 3, 3, 5, 9 }, SortHelper.SwapSort(new int[] { 2, 1, 3, 9, 5, 3, 2, 0 }));
 }
 // ...
 public void setDefaults()
 {
     PagerHelper.SetPage(1, 10);
     SortHelper.SetSort(SortOperator.Ascending);
     PagerHelper.RecordsPerPage = 10;
 }
        private IActionResult GetCollectionItem(string collectionId, int skip, int take)
        {
            var collection = _ds.GetCollection(collectionId);

            // Collection can actually just be empty, but in this case we handle it as it is not found
            if (!collection.AsQueryable().Any())
            {
                return(NotFound());
            }

            var options = QueryHelper.GetQueryOptions(Request.Query, skip, take);

            if (!options.Validate())
            {
                return(BadRequest());
            }

            var datas = options.IsTextSearch ? collection.Find(Request.Query["q"]) : collection.AsQueryable();

            foreach (var key in options.QueryParams)
            {
                string propertyName = key;
                Func <dynamic, dynamic, bool> compareFunc = ObjectHelper.Funcs[""];

                var idx = key.LastIndexOf("_");

                if (idx != -1)
                {
                    var op = key.Substring(idx);
                    compareFunc  = ObjectHelper.Funcs[op];
                    propertyName = key.Replace(op, "");
                }

                datas = datas.Where(d => ObjectHelper.GetPropertyAndCompare(d as ExpandoObject, propertyName, Request.Query[key], compareFunc));
            }

            var totalCount = datas.Count();

            var paginationHeader = QueryHelper.GetPaginationHeader($"{Request.Scheme}://{Request.Host.Value}{Request.Path}", totalCount, options.Skip, options.Take, options.SkipWord, options.TakeWord);

            var results = datas.Skip(options.Skip).Take(options.Take);

            if (options.Fields.Any())
            {
                results = ObjectHelper.SelectFields(results, options.Fields);
            }

            if (options.SortFields.Any())
            {
                results = SortHelper.SortFields(results, options.SortFields);
            }

            if (_apiSettings.UseResultObject)
            {
                return(Ok(QueryHelper.GetResultObject(results, totalCount, paginationHeader, options)));
            }
            else
            {
                Response.Headers.Add("X-Total-Count", totalCount.ToString());
                Response.Headers.Add("Link", QueryHelper.GetHeaderLink(paginationHeader));
                return(Ok(results));
            }
        }
示例#27
0
        public List <ItemType> GetJsonData(int?page, int?limit, string sortBy, string direction, out int total, string name)
        {
            var results = new List <ItemType>();

            results.Add(new ItemType()
            {
                ItemTypeId = 1, ItemTypeName = "Type1", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 2, ItemTypeName = "Type2", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 3, ItemTypeName = "Type3", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 4, ItemTypeName = "Type4", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 5, ItemTypeName = "Type5", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 6, ItemTypeName = "Type6", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 7, ItemTypeName = "Type7", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 8, ItemTypeName = "Type8", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 9, ItemTypeName = "Type9", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 10, ItemTypeName = "Type10", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 11, ItemTypeName = "Type11", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 12, ItemTypeName = "Type12", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 13, ItemTypeName = "Type13", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 14, ItemTypeName = "Type14", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 15, ItemTypeName = "Type15", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 16, ItemTypeName = "Type16", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 17, ItemTypeName = "Type17", ItemTypeDescription = "Type1"
            });
            results.Add(new ItemType()
            {
                ItemTypeId = 18, ItemTypeName = "Type18", ItemTypeDescription = "Type1"
            });

            var records = results.ToArray().AsQueryable();

            if (!string.IsNullOrEmpty(name))
            {
                records = records.Where(r => r.ItemTypeName.ToLower().Contains(name.Trim().ToLower()));
            }

            total = records.Count();

            if (!string.IsNullOrEmpty(sortBy) && !string.IsNullOrEmpty(direction))
            {
                if (direction.Trim().ToLower() == "asc")
                {
                    records = SortHelper.OrderBy(records, sortBy);
                }
                else
                {
                    records = SortHelper.OrderByDescending(records, sortBy);
                }
            }
            if (page.HasValue && limit.HasValue)
            {
                int start = (page.Value - 1) * limit.Value;
                records = records.Skip(start).Take(limit.Value);
            }
            return(records.ToList());
        }
        public async Task UpdateDocumentAsync(bool forceUpdate = false)
        {
            await Microsoft.VisualStudio.Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var activeDocument = DocumentHelper.GetActiveDocument(Dte);

            if (activeDocument == null)
            {
                return;
            }

            CodeDocumentViewModel.FilePath = activeDocument.FullName;

            // Do we need to change the side where the margin is displayed
            if (_margin?.MarginSide != null &&
                _margin?.MarginSide != Settings.Default.MarginSide &&
                Dte != null)
            {
                var filename = activeDocument.FullName;
                Dte.ExecuteCommand("File.Close");
                Dte.ExecuteCommand("File.OpenFile", filename);
            }

            try
            {
                if (forceUpdate)
                {
                    _cache = null;
                    CodeDocumentViewModel.CodeDocument.Clear();
                }

                // Do we have a cached version of this document
                if (_cache != null)
                {
                    CodeDocumentViewModel.CodeDocument = _cache;
                }

                // If not show a loading item
                if (!CodeDocumentViewModel.CodeDocument.Any())
                {
                    CodeDocumentViewModel.CodeDocument = CreateLoadingItem();
                }

                var codeItems = await SyntaxMapper.MapDocumentAsync(activeDocument, this, _workspace);

                if (codeItems == null)
                {
                    // CodeNav for document updated, no results
                    return;
                }

                // Filter all null items from the code document
                SyntaxMapper.FilterNullItems(codeItems);

                // Sort items
                CodeDocumentViewModel.SortOrder = Settings.Default.SortOrder;
                SortHelper.Sort(codeItems, Settings.Default.SortOrder);

                // Set currently active codeitem
                HighlightHelper.SetForeground(codeItems);

                // Set the new list of codeitems as DataContext
                CodeDocumentViewModel.CodeDocument = codeItems;
                _cache = codeItems;

                // Apply current visibility settings to the document
                VisibilityHelper.SetCodeItemVisibility(CodeDocumentViewModel);

                // Apply bookmarks
                LoadBookmarksFromStorage();
                BookmarkHelper.ApplyBookmarks(CodeDocumentViewModel, Dte?.Solution?.FileName);

                // Apply history items
                LoadHistoryItemsFromStorage();
                HistoryHelper.ApplyHistoryIndicator(CodeDocumentViewModel);
            }
            catch (Exception e)
            {
                LogHelper.Log("Error running UpdateDocument", e);
            }

            try
            {
                // Sync all regions
                OutliningHelper.SyncAllRegions(OutliningManagerService, TextView, CodeDocumentViewModel.CodeDocument);

                // Should the margin be shown and are there any items to show, if not hide the margin
                VisibilityHelper.SetMarginHeight(_row, CodeDocumentViewModel.CodeDocument);
            }
            catch (Exception e)
            {
                LogHelper.Log("Error finishing UpdateDocument", e);
            }
        }
示例#29
0
        private ListModel <UserModel> List(DateTime startDate, DateTime endDate, int pageNumber, int pageSize, int status, string searched, ICollection <Guid> parentIds, ListModel <UserModel> model)
        {
            var resetedStartDate = startDate.ResetTimeToStartOfDay();
            var resetedEndDate   = endDate.ResetTimeToEndOfDay();

            Expression <Func <User, bool> > expression;

            model.Paging ??= new Paging
            {
                PageSize   = pageSize,
                PageNumber = pageNumber
            };

            if (status != -1)
            {
                var bStatus = status.ToString().ToBoolean();

                if (searched != null)
                {
                    if (bStatus)
                    {
                        expression = c => c.IsApproved && c.Username.Contains(searched);
                    }
                    else
                    {
                        expression = c => c.IsApproved == false && c.Username.Contains(searched);
                    }
                }
                else
                {
                    if (bStatus)
                    {
                        expression = c => c.IsApproved;
                    }
                    else
                    {
                        expression = c => c.IsApproved == false;
                    }
                }
            }
            else
            {
                if (searched != null)
                {
                    expression = c => c.Username.Contains(searched);
                }
                else
                {
                    expression = c => c.Id != Guid.Empty;
                }
            }

            expression = expression.And(e => e.CreationTime >= resetedStartDate && e.CreationTime <= resetedEndDate);

            if (parentIds != null)
            {
                if (parentIds.Count > 0)
                {
                    expression = expression.And(e => e.RoleUserLines.Any(x => parentIds.Contains(x.Role.Id)));
                }
            }

            var identityUserMinRoleLevel = _serviceMain.IdentityUserMinRoleLevel;

            expression = expression.And(x => x.RoleUserLines.All(t => t.Role.Level > identityUserMinRoleLevel));

            var sortHelper = new SortHelper <User>();

            sortHelper.OrderBy(x => x.DisplayOrder);

            var query = (IOrderedQueryable <User>)_repositoryUser
                        .Join(x => x.Person)
                        .Join(x => x.Creator.Person)
                        .Join(x => x.LastModifier.Person)
                        .Join(x => x.RoleUserLines)
                        .ThenJoin(x => x.Role)
                        .Where(expression);

            query = sortHelper.GenerateOrderedQuery(query);

            model.Paging.TotalItemCount = query.Count();

            var items = model.Paging.PageSize > 0 ? query.Skip((model.Paging.PageNumber - 1) * model.Paging.PageSize).Take(model.Paging.PageSize) : query;

            var modelItems = new HashSet <UserModel>();

            foreach (var item in items)
            {
                var modelItem = item.CreateMapped <User, UserModel>();
                modelItem.Creator      = new IdName(item.Creator.Id, item.Creator.Person.DisplayName);
                modelItem.LastModifier = new IdName(item.LastModifier.Id, item.LastModifier.Person.DisplayName);
                modelItem.IdentityCode = item.Person.IdentityCode;
                modelItem.FirstName    = item.Person.FirstName;
                modelItem.LastName     = item.Person.LastName;
                modelItem.Roles        = item.RoleUserLines.Select(t => t.Role).Select(role => new IdCodeNameSelected(role.Id, role.Code, role.Name, true)).ToList();
                modelItems.Add(modelItem);
            }

            model.Items = modelItems.ToList();

            var pageSizeDescription = _serviceMain.ApplicationSettings.PageSizeList;

            var pageSizes = pageSizeDescription.Split(',').Select(s => new KeyValuePair <int, string>(s.ToInt(), s)).ToList();

            pageSizes.Insert(0, new KeyValuePair <int, string>(-1, "[" + Dictionary.All + "]"));

            model.Paging.PageSizes = pageSizes;

            model.Paging.PageCount = (int)Math.Ceiling((float)model.Paging.TotalItemCount / model.Paging.PageSize);

            if (model.Paging.TotalItemCount > model.Items.Count)
            {
                model.Paging.HasNextPage = true;
            }

            if (model.Paging.PageNumber == 1)
            {
                if (model.Paging.TotalItemCount > 0)
                {
                    model.Paging.IsFirstPage = true;
                }


                if (model.Paging.PageCount == 1)
                {
                    model.Paging.IsLastPage = true;
                }
            }

            else if (model.Paging.PageNumber == model.Paging.PageCount)
            {
                model.Paging.HasNextPage = false;

                if (model.Paging.PageCount > 1)
                {
                    model.Paging.IsLastPage      = true;
                    model.Paging.HasPreviousPage = true;
                }
            }

            else
            {
                model.Paging.HasNextPage     = true;
                model.Paging.HasPreviousPage = true;
            }

            if (model.Paging.TotalItemCount > model.Items.Count && model.Items.Count <= 0)
            {
                model.Message = Messages.DangerRecordNotFoundInPage;
            }

            if (model.Paging.TotalItemCount == 0)
            {
                model.Message = Messages.DangerRecordNotFound;
            }

            return(model);
        }
示例#30
0
 public virtual IQueryable <TEntity> GetAll(SortHelper order = null, int initialPage = 0, int recordsPerPage = 50)
 {
     return(db.Pagination(order, initialPage, recordsPerPage));
 }
示例#31
0
            public object Any(FindOrders req)
            {
                var grouping = GroupHelper.Parse(Request.QueryString.ToNameValueCollection());
                var sorting  = SortHelper.Parse(Request.QueryString.ToNameValueCollection());
                var result   = Request.GetRequestParams();

                if (sorting != null)
                {
                    var first = sorting.First();
                    if (first.Logic == "and")
                    {
                        foreach (var aa in first.Filters)
                        {
                            if (aa != null && aa.Any())
                            {
                                String sql   = "";
                                var    logic = aa.First();
                                // in case field has space
                                logic.Field = logic.Field.Replace(" ", "");
                                if (logic.Operator == "eq")
                                {
                                    result.Add(logic.Field, logic.Value);
                                }
                                else if (logic.Operator == "neq")
                                {
                                    typeof(KendoGridBaseRequest <SalesOrderDetail>)
                                    .GetProperty(logic.Field + "Temp")
                                    .AddAttributes(new QueryFieldAttribute {
                                        Template = "{Field} != {Value}", Field = logic.Field
                                    });

                                    typeof(KendoGridBaseRequest <SalesOrderDetail>)
                                    .GetProperty(logic.Field + "Temp").SetValue(req, logic.Value);
                                }
                                else if (logic.Operator == "startswith")
                                {
                                    result.Add(logic.Field + "StartsWith", logic.Value);
                                }
                                else if (logic.Operator == "contains")
                                {
                                    result.Add(logic.Field + "Contains", logic.Value);
                                }
                                else if (logic.Operator == "doesnotcontain")
                                {
                                    typeof(KendoGridBaseRequest <SalesOrderDetail>)
                                    .GetProperty(logic.Field + "Temp")
                                    .AddAttributes(new QueryFieldAttribute {
                                        Template = "UPPER({Field}) LIKE %UPPER({Value})%", Field = logic.Field
                                    });

                                    typeof(KendoGridBaseRequest <SalesOrderDetail>)
                                    .GetProperty(logic.Field + "Temp").SetValue(req, logic.Value);
                                }
                                else if (logic.Operator == "endswith")
                                {
                                    result.Add(logic.Field + "EndsWith", logic.Value);
                                }
                            }
                        }
                    }
                    else if (first.Logic == "or")
                    {
                    }
                }
                req.AllPrameterDictionary = result;



                // return sorting;
                //var q = AutoQuery.CreateQuery(req, Request.GetRequestParams());
                var q = AutoQuery.CreateQuery(req, req.AllPrameterDictionary);

                //q.GroupBy(x=>x.SalesOrderID).
                var resultA = AutoQuery.Execute(req, q);

                var groupBy = resultA.Results.GroupBy(x => x.SalesOrderID).ToList();
                var grouped = groupBy.Skip(req.Skip.GetValueOrDefault(0)).Take(req.Take.GetValueOrDefault(10));

                resultA.Total = groupBy.Count();

                //project into a kendoGroup and calculate the Aggregate
                var groupResponse = new List <KendoGroup>();

                foreach (var group in grouped)
                {
                    var sum = @group.Sum(salesOrderDetail => Convert.ToDouble(salesOrderDetail.LineTotal));
                    foreach (var salesOrderDetail in group)
                    {
                        salesOrderDetail.Sum = sum;
                    }
                    var aggDic = new Dictionary <string, string>();
                    aggDic.Add("sum", sum.ToString());
                    var kendoGroup = new KendoGroup
                    {
                        Field        = "salesOrderId",
                        HasSubgroups = false,
                        Items        = group,
                        Aggregates   = aggDic,
                        Value        = group.Key
                    };
                    groupResponse.Add(kendoGroup);
                }
                /* Here is the Sorting happening */
                //  KendoGridResponse<SalesOrderDetail> response = null;
                string data = Request.QueryString.Get("sort[0][field]");
                List <SalesOrderDetail> SalesList = null;

                if (data != null)
                {
                    string direction = Request.QueryString.Get("sort[0][dir]");
                    if (direction != null)
                    {
                        if (direction == "desc")
                        {
                            SalesList = resultA.ConvertTo <KendoGridResponse <SalesOrderDetail> >().Results.OrderBy(data).ToList();
                            SalesList.Reverse();
                        }
                        else
                        {
                            SalesList = resultA.ConvertTo <KendoGridResponse <SalesOrderDetail> >().Results.OrderBy(data).ToList();
                        }
                    }
                }


                var response = resultA.ConvertTo <KendoGridResponse <SalesOrderDetail> >();

                response.Results = SalesList ?? response.Results;

                response.Groups = groupResponse;
                return(response);
            }
示例#32
0
		private static void SortSelectedText(bool aAscending, bool aCaseSensitive) {
			IOTASourceEditor _SourceEditor = OtaUtils.GetCurrentSourceEditor();
			if (_SourceEditor == null)
			{
				return;
			}
			string _Text = OtaUtils.GetSelectedText(OtaUtils.GetCurrentModule());

			if (_Text == null || _Text.Length == 0) {
				OtaUtils.SelectLine(OtaUtils.GetCurrentSourceEditor());
				_Text = OtaUtils.GetSelectedText(OtaUtils.GetCurrentModule());
			}

			List<string>  _Lines = new List<string>(Lextm.StringHelper.GetLinesFromString(_Text));

			// Do the sorting
			SortHelper _SortHelper = new SortHelper();
			_SortHelper.Ascending = aAscending;
			_SortHelper.CaseSensitive = aCaseSensitive;

			_Lines.Sort(_SortHelper);

			_Text = OtaUtils.BuildLines(_Lines, true);
			OtaUtils.ReplaceSelectedText(_SourceEditor, _Text);
			_SourceEditor.GetEditView(0).Paint();
		}
        public List <Project> GetJsonData(int?page, int?limit, string sortBy, string direction, out int total, string projectName = null, string projectType = null,
                                          string projectSubType = null, string Professor = null)
        {
            var isBac   = _context.ApplicationUsers.Where(p => p.Id == UserIdentity.Id).Select(p => p.IsBachelorStudent).SingleOrDefault();
            var records = _context.Projects.Include(p => p.Creator).Include(p => p.Updater)
                          .Select(p => new Project()
            {
                Id                  = p.Id,
                Name                = p.Name,
                IsApproved          = p.IsApproved,
                IsClosed            = p.IsClosed,
                ApprovalSummary     = p.IsApproved.Value ? "Yes" : "No",
                CloserSummary       = p.IsClosed?"Yes":"No",
                MaxApprovedStudents = p.MaxApprovedStudents,
                ProjectType         = p.ProjectType,
                ProjectSubType      = p.ProjectSubType,
                CreatedBy           = (string.IsNullOrEmpty(p.Creator.FirstName) || string.IsNullOrEmpty(p.Creator.LastName)) ? p.Creator.UserName : (p.Creator.FirstName + " " + p.Creator.LastName)
            }).Where(p => p.IsApproved.Value && !p.IsClosed && !_context.ProjectStudents.Select(c => c.ApplicationUserId).Contains(UserIdentity.Id) && isBac == true)
                          .AsQueryable();


            if (!string.IsNullOrEmpty(projectName))
            {
                records = records.Where(r => r.Name.ToLower().Contains(projectName.Trim().ToLower()));
            }
            if (!string.IsNullOrEmpty(projectType) && projectType != "Select")
            {
                records = records.Where(r => r.ProjectType.ToLower().Contains(projectType.Trim().ToLower()));
            }
            if (!string.IsNullOrEmpty(projectSubType) && projectSubType != "Select")
            {
                records = records.Where(r => r.ProjectSubType.ToLower().Contains(projectSubType.Trim().ToLower()));
            }
            if (!string.IsNullOrEmpty(Professor))
            {
                records = records.Where(r => r.CreatedBy.ToLower().Contains(Professor.Trim().ToLower()));
            }


            total = records.Count();

            if (!string.IsNullOrEmpty(sortBy) && !string.IsNullOrEmpty(direction))
            {
                if (direction.Trim().ToLower() == "asc")
                {
                    records = SortHelper.OrderBy(records, sortBy);
                }
                else
                {
                    records = SortHelper.OrderByDescending(records, sortBy);
                }
            }
            if (page.HasValue && limit.HasValue)
            {
                int start = (page.Value - 1) * limit.Value;
                records = records.Skip(start).Take(limit.Value);
            }


            return(records.ToList());
        }
示例#34
0
            internal static CompareDelegate CompareDelegateFor(ScriptFunction fun)
            {
                if (fun == null)
                    return new CompareDelegate (SortHelper.nativeCompare);

                SortHelper helper = new SortHelper (fun);
                return new CompareDelegate (helper.userCompare);
            }
示例#35
0
        /// <inheritdoc/>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="performances"/> is <b>null</b>.<br/>
        /// -or-<br/>
        /// <paramref name="sample"/> is <b>null</b>.
        /// </exception>
        protected internal override sealed double UpdateLevel(
            DoubleMatrix performances,
            DoubleMatrix sample,
            EliteSampleDefinition eliteSampleDefinition,
            double rarity,
            out DoubleMatrix eliteSample)
        {
            if (performances is null)
            {
                throw new ArgumentNullException(nameof(performances));
            }

            if (sample is null)
            {
                throw new ArgumentNullException(nameof(sample));
            }

            var performanceArray = performances.GetStorage();

            SortHelper.Sort(
                performanceArray,
                SortDirection.Ascending,
                out int[] indexTable);

            if (this.TraceExecution)
            {
                Trace.WriteLine(
                    "Sample points ordered by performance:");
                var sampleInfo = DoubleMatrix.Dense(
                    numberOfRows: sample.NumberOfRows,
                    numberOfColumns: this.StateDimension + 1);
                sampleInfo.SetColumnName(0, "Performance");
                for (int j = 1; j < sampleInfo.NumberOfColumns; j++)
                {
                    sampleInfo.SetColumnName(j, "S" + j);
                }
                sampleInfo[":", 0] = performances;
                sampleInfo[":", IndexCollection.Range(1, this.StateDimension)]
                    = sample[
                          IndexCollection.FromArray(indexTable, false), ":"];
                Trace.WriteLine(sampleInfo);
            }

            int eliteFirstIndex = 0;
            int eliteLastIndex  = 0;
            int sampleSize      = sample.NumberOfRows;

            double level = Double.NaN;

            double thresholdLevel = this.ThresholdLevel;

            // Compute the relevant sample percentile (the level)
            // and achieved performance
            switch (eliteSampleDefinition)
            {
            case EliteSampleDefinition.HigherThanLevel:
                eliteFirstIndex = Convert.ToInt32(
                    Math.Ceiling(sampleSize * (1 - rarity)));
                eliteLastIndex = sampleSize - 1;

                level = performanceArray[eliteFirstIndex];
                if (level > thresholdLevel)
                {
                    level = thresholdLevel;
                }
                break;

            case EliteSampleDefinition.LowerThanLevel:
                eliteFirstIndex = 0;
                eliteLastIndex  = Convert.ToInt32(
                    Math.Ceiling(sampleSize * rarity));

                level = performanceArray[eliteLastIndex];
                if (level < thresholdLevel)
                {
                    level = thresholdLevel;
                }
                break;
            }

            // Update the reference parameter
            var eliteSamplePositions =
                IndexCollection.Range(eliteFirstIndex, eliteLastIndex);

            if (this.TraceExecution)
            {
                Trace.WriteLine(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "Elite positions: {0} - {1}.",
                        eliteFirstIndex,
                        eliteLastIndex));
            }

            var sortedIndexes =
                IndexCollection.FromArray(indexTable, false);

            eliteSample = sample[sortedIndexes[eliteSamplePositions], ":"];

            return(level);
        }