public static void AddToMenu(Menu menu, List<Spell> spells)
        {
            try
            {
                _menu = menu;

                spells =
                    spells.DistinctBy(s => s.Slot)
                        .Where(s => s.Slot != SpellSlot.Unknown && (s.IsSkillshot || s.Range > 0f))
                        .ToList();

                foreach (var spell in spells)
                {
                    _menu.AddItem(
                        new MenuItem(_menu.Name + "." + spell.Slot, "Use " + spell.Slot).SetValue(
                            spell.Slot != SpellSlot.R && spell.Instance.Cooldown < 20));
                }

                _menu.AddItem(
                    new MenuItem(_menu.Name + ".min-distance", "Min. Enemy Distance").SetValue(
                        new Slider(1000, 200, 3000)));
                _menu.AddItem(new MenuItem(_menu.Name + ".min-mana", "Min. Mana %").SetValue(new Slider(95, 1)));
                _menu.AddItem(new MenuItem(_menu.Name + ".fountain", "Only Inside Fountain").SetValue(false));
                _menu.AddItem(new MenuItem(_menu.Name + ".enabled", "Enabled").SetValue(false));

                _spells = spells.OrderBy(s => s.ManaCost).ThenBy(s => s.Instance.Cooldown).ToList();
                Core.OnPostUpdate += OnCorePostUpdate;
            }
            catch (Exception ex)
            {
                Global.Logger.AddItem(new LogItem(ex));
            }
        }
Example #2
0
        public string CreateXmlDb(List<MagicCard> listOfCards, ProgressDialogController dialogController)
        {
            var curCard = 0;
            var totalCards = listOfCards.Count;

            foreach (var distinctSet in listOfCards.DistinctBy(o => o.Set))
            {
                var enumerable = listOfCards.Where(op => op.Set == distinctSet.Set && op.PathOfCardImage.Contains("original")).DistinctBy(o => o.Name);
                foreach (var distinctCard in enumerable)
                {
                    var cardElement = _xmlfile.CreateElement("card");
                    AddChildElementAndValue(cardElement, _util.GetVariableName(() => distinctCard.Name), distinctCard.Name);
                    AddChildElementAndValue(cardElement, _util.GetVariableName(() => distinctCard.Set), distinctCard.Set);
                    AddChildElementAndValue(cardElement, _util.GetVariableName(() => distinctCard.PathOfCardImage), distinctCard.PathOfCardImage);

                    var phashesElement = _xmlfile.CreateElement("phashes");
                    foreach (var magicCard in listOfCards.Where(o => o.Name == distinctCard.Name && o.Set == distinctSet.Set))
                    {
                        foreach (var phash in magicCard.PHashes)
                        {
                            AddChildElementAndValue(phashesElement, "phash", phash.ToString());
                        }
                    }
                    cardElement.AppendChild(phashesElement);
                    _rootNode.AppendChild(cardElement);
                    curCard++;
                    dialogController.SetProgress((double)curCard / totalCards);
                    dialogController.SetMessage("Creating a Simple Database of all those pHashes: " + curCard + "/" + totalCards);
                }
            }

            SaveXmlFile();
            return Path.GetFullPath(XmlDbPath);
        }
Example #3
0
        public List<DiskSpace> GetFreeSpace()
        {
            var diskSpace = new List<DiskSpace>();
            diskSpace.AddRange(GetSeriesFreeSpace());
            diskSpace.AddRange(GetDroneFactoryFreeSpace());
            diskSpace.AddRange(GetFixedDisksFreeSpace());

            return diskSpace.DistinctBy(d => d.Path).ToList();
        }
        public static List<Price> GetHistoricalMINUTE_FromWEB(DateTime StartDate, DateTime EndDate, int TimeFrame, string ContractName)
        {
            string startdate = StartDate.ToString("yyyyMMdd");
            string endddate = EndDate.ToString("yyyyMMdd");

            string URL = "http://www.hisat.co.za/updater/minuteUpdate.aspx?Instrument=" + ContractName + "&StartDate=" + startdate + @"&EndDate=" + endddate + @"&Password=PieterF&Username=PFOUCHE&compression=" + TimeFrame;
            Debug.WriteLine(URL);

            List<Price> Data = new List<Price>();
            List<string> rawData = new List<string>();

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
            req.AutomaticDecompression = DecompressionMethods.GZip;
            WebResponse resp = req.GetResponse();
            Stream s = resp.GetResponseStream();
            StreamReader sr = new StreamReader(s, Encoding.ASCII);

            while (sr.Peek() >= 0)
            {
                string _rawData = sr.ReadLine();
                if (!rawData.Contains(_rawData)) rawData.Add(_rawData);
            }

            foreach (string ss in rawData)
            {
                Price p = new Price();
                List<string> data = new List<string>(ss.Split(','));
                string date = data[0];

                int y = int.Parse(date.Substring(0, 4));
                int mm = int.Parse(date.Substring(4, 2));
                int d = int.Parse(date.Substring(6, 2));

                string time = data[1];
                int h = int.Parse(time.Substring(0, 2));
                int m = int.Parse(time.Substring(3, 2));


                p.TimeStamp = new DateTime(y, mm, d, h, m, 0);
                p.Open = int.Parse(data[2]);
                p.High = int.Parse(data[3]);
                p.Low = int.Parse(data[4]);
                p.Close = int.Parse(data[5]);
                p.Volume = int.Parse(data[6]);
                p.InstrumentName = ContractName;
                Data.Add(p);

            }

            return Data.DistinctBy(t => t.TimeStamp).ToList();

        }
Example #5
0
        public BetModel(TournoiModel tournoi)
        {
            IDTournoi = tournoi.ID;
            List<JediModel> tmp = new List<JediModel>();

            // Liste des jedis concourrants
            foreach (MatchModel m in tournoi.Matchs)
            {
                tmp.Add(m.Jedi1);
                tmp.Add(m.Jedi2);
            }

            // Unique occurrence de chacun d'eux
            m_availableJedis = tmp.DistinctBy(j => j.ID).ToList();
        }
        public void RemoveRecordWithOpenTransaction(ISession session, ICollection <SVR_AnimeSeries> seriesToUpdate, bool updateMyListStatus = true, bool removeDuplicateFileEntries = true)
        {
            logger.Info("Removing VideoLocal_Place record for: {0}", FullServerPath ?? VideoLocal_Place_ID.ToString());
            SVR_VideoLocal v = VideoLocal;

            List <DuplicateFile> dupFiles = null;

            if (!string.IsNullOrEmpty(FilePath) && removeDuplicateFileEntries)
            {
                dupFiles = RepoFactory.DuplicateFile.GetByFilePathAndImportFolder(FilePath, ImportFolderID);
            }

            if (v?.Places?.Count <= 1)
            {
                if (updateMyListStatus)
                {
                    CommandRequest_DeleteFileFromMyList cmdDel =
                        new CommandRequest_DeleteFileFromMyList(v.MyListID);
                    cmdDel.Save();
                }

                List <SVR_AnimeEpisode> eps = v?.GetAnimeEpisodes()?.Where(a => a != null).ToList();
                eps?.DistinctBy(a => a.AnimeSeriesID).Select(a => a.GetAnimeSeries()).ToList().ForEach(seriesToUpdate.Add);
                using (var transaction = session.BeginTransaction())
                {
                    RepoFactory.VideoLocalPlace.DeleteWithOpenTransaction(session, this);
                    RepoFactory.VideoLocal.DeleteWithOpenTransaction(session, v);
                    dupFiles?.ForEach(a => RepoFactory.DuplicateFile.DeleteWithOpenTransaction(session, a));

                    transaction.Commit();
                }
            }
            else
            {
                using (var transaction = session.BeginTransaction())
                {
                    RepoFactory.VideoLocalPlace.DeleteWithOpenTransaction(session, this);
                    dupFiles?.ForEach(a => RepoFactory.DuplicateFile.DeleteWithOpenTransaction(session, a));
                    transaction.Commit();
                }
            }
        }
                public List<Suggestion> SuggestKeyword(string searchText, bool fuzzy)
                {
                    var         _serviceUri = new Uri("https://myjobs.search.windows.net");
                    var _httpClient = new HttpClient();
                    _httpClient.DefaultRequestHeaders.Add("api-key", "6917F2050016ACCA313196EB37DB826D");

                    // Pass the specified suggestion text and return the fields
                    //            Uri uri = new Uri(_serviceUri, "/indexes/index1/docs/suggest?suggesterName=sg&highlightPreTag=%3Cem%3E&highlightPostTag=%3C%2Fem%3E&fuzzy=" + fuzzy + "&search=" + Uri.EscapeDataString(searchText));
                    Uri uri = new Uri(_serviceUri, "/indexes/index-flat-jobs/docs/suggest?suggesterName=suggester-keyword&$top=100&fuzzy=" + fuzzy + "&search=" + Uri.EscapeDataString(searchText));
        
        
                    HttpResponseMessage response = AzureSearchHelper.SendSearchRequest(_httpClient, HttpMethod.Get, uri);
                    AzureSearchHelper.EnsureSuccessfulSearchResponse(response);
                    List<Suggestion> suggestionList = new List<Suggestion>();
        
                    //            List<string> suggestionList = new List<string>();
        
                    foreach (var option in AzureSearchHelper.DeserializeJson<dynamic>(response.Content.ReadAsStringAsync().Result).value)
                    {
                        Suggestion suggestion = new Suggestion();
                        suggestion.id = (string)option["id"];
                        suggestion.value = "\"" + (string)option["@search.text"] + "\"";
                        //                suggestion.name = (string)option["name"];
                        //                suggestion.species = (string)option["species"];
                        //                suggestion.thumbnail = (string)option["thumbnail"];
                        suggestionList.Add(suggestion);
                    }
        
                    //            return suggestionList;$top=#
        
                    var distinctTitles = suggestionList.DistinctBy(x => x.value);
        
                    List<Suggestion> distinctList = distinctTitles.ToList();
        
                    return distinctList;
                }
Example #8
0
        public List <IW2S_level1link> prehandle_data(List <IW2S_level1link> links, IW2S_BaiduCommend tsk, List <IW2S_ExcludeKeyword> excludedKeywords)
        {
            if (links == null || links.Count == 0)
            {
                log("BLOCKED " + tsk.CommendKeyword);
                return(links);
            }
            else
            {
                links = links.DistinctBy(x => x.LinkUrl);
                log(links.Count + " Level 1 Links for " + tsk.CommendKeyword);
            }

            //var itm = MySqlDbHelper.GetEfEntities<protectitem>(ctx,"Id="+tsk.ProtectItemId).FirstOrDefault();
            ////{ScoredKeywords:{aaa:12,bbb:13}}
            //if (itm != null && !string.IsNullOrEmpty(itm.FingerPrints2))
            //{
            //    string[] sks = itm.FingerPrints2.SplitWith("$;");
            //    Dictionary<string, int> scores = new Dictionary<string, int>();
            //    if (sks != null)
            //    {
            //        foreach (var sk in sks)
            //        {
            //            string[] sps = sk.SplitWith(":", ":");
            //            if (sps == null || sps.Length != 2)
            //                continue;
            //            string k = sps[0].GetTrimed();
            //            int? s = sps[1].ExInt();
            //            if (sps[1].IsContains2("-"))
            //                s = -1 * s;
            //            if (string.IsNullOrEmpty(k) || !s.HasValue || scores.ContainsKey(k))
            //                continue;
            //            scores.Add(k, s.Value);
            //        }
            //    }
            //    foreach (var l in links)
            //    {
            //        string txt = string.Format("{0}{1}", l.Title, l.Abstract);
            //        l.Score = scores.Sum(x => txt.IsContain(x.Key) ? x.Value : 0);
            //        l.Title = "[使用了自定义打分]" + l.Title;
            //    }
            //}
            //else if (tsk.ProjectType == (byte)ProjectType.Artical && !string.IsNullOrEmpty(itm.FingerPrints))
            //{
            //    foreach (var l in links)
            //    {
            //        var txt = string.Join("", "{0},{1}".FormatStr(l.Title, l.Abstract).SplitWith(
            //            ";", ",", ";", ".", ",", "。", ";",
            //           "-", " ", "?", "“", "!", "”").Select(x => x.GetTrimed()).Where(x => !string.IsNullOrEmpty(x)));
            //        string[] fps = itm.FingerPrints.SplitWith(",");
            //        l.Score = l.Score / 2 + fps.Where(x => txt.IsContain(x)).Count() * 50 / fps.Length;
            //    }
            //}

            links.ForEach(x =>
            {
                //x.Keywords = tsk.Keyword;

                cleaning(x, excludedKeywords);
            });

            links = links.Where(x => x.DataCleanStatus != (byte)DataCleanStatus.Excluded).ToList();
            return(links);
        }
Example #9
0
        /// <summary>
        /// Import payment
        /// </summary>
        /// <param name="documents"></param>
        /// <returns></returns>
        private async Task <ResultModel> SavePaymentsFromImport(Documents documents)
        {
            if (documents == null)
            {
                return(new InvalidParametersResultModel());
            }

            if (!documents.Document.Any())
            {
                return(new NotFoundResultModel());
            }

            var listErrors = new List <IErrorModel>();


            var listDocuments = documents.Document;


            foreach (var payment in listDocuments)
            {
                try
                {
                    var buyer = payment.SupplierInfo.Buyer;
                    if (buyer == null)
                    {
                        continue;
                    }

                    var organizationRequest = await _organizationService.GetOrganizationByFiscalCodeAsync(buyer.IDNO);

                    Guid?organizationId = null;

                    if (organizationRequest.IsSuccess)
                    {
                        organizationId = organizationRequest.Result.Id;
                    }
                    else
                    {
                        var addOrganizationRequest = await _organizationService.AddNewOrganizationAsync(new OrganizationViewModel
                        {
                            Name       = buyer.Title,
                            FiscalCode = buyer.IDNO,
                            Bank       = buyer.BankAccount.BranchTitle,
                            Email      = "*****@*****.**",
                            Phone      = "00000000",
                            ClientType = OrganizationType.Client
                        });

                        if (!addOrganizationRequest.IsSuccess)
                        {
                            listErrors.AddRange(addOrganizationRequest.Errors);
                            continue;
                        }
                        organizationId = addOrganizationRequest.Result;
                    }

                    var paymentDate = payment.SupplierInfo.DeliveryDate.StringToDateTime();


                    if (!paymentDate.HasValue)
                    {
                        listErrors.Add(new ErrorModel
                        {
                            Message = "Data [" + payment.SupplierInfo.DeliveryDate + "] wrong format"
                        });
                        continue;
                    }


                    var listRows = payment.SupplierInfo.Merchandises.Row;
                    if (listRows == null || !listRows.Any())
                    {
                        continue;
                    }

                    foreach (var row in listRows)
                    {
                        var newPayment = new AddPaymentViewModel
                        {
                            DateTransaction      = paymentDate.Value,
                            OrganizationId       = organizationId.Value,
                            TotalPrice           = row.TotalPrice,
                            TotalTVA             = row.TotalTVA,
                            TVA                  = row.TVA,
                            TotalPriceWithoutTVA = row.TotalPriceWithoutTVA,
                            UnitPriceWithoutTVA  = row.UnitPriceWithoutTVA,
                            Quantity             = row.Quantity,
                            Currency             = "MDL",
                            PaymentDestination   = row.Name,
                            DocumentNumber       = payment.AdditionalInformation.field,
                        };

                        var paymentCodeRequest = await GetPaymentCodeByNameAsync(row.Name);

                        if (!paymentCodeRequest.IsSuccess)
                        {
                            listErrors.Add(new ErrorModel
                            {
                                Message = "Payment name  [" + row.Name + "] not exist"
                            });
                            continue;
                        }

                        newPayment.PaymentCodeId = paymentCodeRequest.Result.Id;

                        if (await ExistPaymentAsync(newPayment))
                        {
                            continue;
                        }

                        var addPaymentResult = await AddPaymentAsync(newPayment);

                        if (!addPaymentResult.IsSuccess)
                        {
                            listErrors.AddRange(addPaymentResult.Errors);
                        }
                    }
                }
                catch (Exception ex)
                {
                    listErrors.Add(new ErrorModel
                    {
                        Message = "Error import payment code [" + payment.AdditionalInformation.field + "]  [" + ex.Message + "]" + "[" + ex.StackTrace + "]"
                    });
                }
            }

            listErrors = listErrors.DistinctBy(x => x.Message).ToList();
            return(listErrors.Any() ? new ResultModel {
                IsSuccess = false, Errors = listErrors
            } : new ResultModel {
                IsSuccess = true
            });
        }
Example #10
0
        /// <summary>
        /// Gets allowed recursive children of an item
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
        /// <returns>IEnumerable{BaseItem}.</returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            var list = new List<BaseItem>();

            var hasLinkedChildren = AddChildrenToList(user, includeLinkedChildren, list, false, true);

            return hasLinkedChildren ? list.DistinctBy(i => i.Id).ToList() : list;
        }
Example #11
0
        private async Task <List <PopularTaROutputDto> > GetRandomPopularTaR(List <PopularityDto> popularties)
        {
            int total  = 10;
            var result = new List <PopularTaROutputDto>();

            //Populerlerin categorilerini alıp distinct ettik
            var categortyIds = new List <int>();

            foreach (var popularty in popularties)
            {
                categortyIds.AddRange(await _tarRepository.GetQueryable()
                                      .Include(x => x.TaRCategories)
                                      .SelectMany(y => y.TaRCategories.Select(y => y.CategoryId)).ToListAsync());
            }

            categortyIds = categortyIds.Distinct().ToList();

            if (categortyIds.Count > 10)
            {
                categortyIds = categortyIds.Take(10).ToList();
            }

            /*
             * Test Case
             * 10/9 = 1 taneden 9 tane resim ve 1 resim eksik
             * 10/8 = 1 taneden 8 tane resim ve 2 resim eksik
             * 10/7 = 1 taneden 7 tane resim ve 3 resim eksik
             * 10/6 = 1 taneden 6 tane resim ve 4 resim eksik
             * 10/4 = 2 taneden 8 tane resim ve 2 resim eksik
             * 10/3 = 3 taneden 9 tane resim ve 1 resim eksik
             */
            int take   = total / categortyIds.Count;
            int maxTar = total - take * categortyIds.Count;

            foreach (var categoryId in categortyIds)
            {
                int oneTake = 0;
                if (maxTar != 0)
                {
                    oneTake = 1;
                    maxTar--;
                }
                var totalTake = take + oneTake;

                var tar = await _tarRepository.GetQueryable()
                          .Include(x => x.TaRCategories)
                          .Include(x => x.Content)
                          .Where(y => y.TaRCategories.Select(x => x.CategoryId).Contains(categoryId))
                          .OrderBy(x => Guid.NewGuid())
                          .Take(totalTake)
                          .Select(x => new PopularTaROutputDto()
                {
                    Id        = x.Id,
                    Title     = x.Content.Title,
                    MainImage = x.Content.MainImage
                }).ToListAsync();

                result.AddRange(tar);
            }
            result = result.DistinctBy(x => x.Id).ToList();
            return(result);
        }
Example #12
0
        private void UpdateTaggedModel(IDbConnection conn, IDbTransaction tran, string table, List<TagReplacement079> replacements)
        {
            var tagged = new List<TaggedModel079>();

            using (IDbCommand tagCmd = conn.CreateCommand())
            {
                tagCmd.Transaction = tran;
                tagCmd.CommandText = string.Format("SELECT Id, Tags FROM {0}", table);

                using (IDataReader tagReader = tagCmd.ExecuteReader())
                {
                    while (tagReader.Read())
                    {
                        if (!tagReader.IsDBNull(1))
                        {
                            var id = tagReader.GetInt32(0);
                            var tags = tagReader.GetString(1);

                            tagged.Add(new TaggedModel079
                                       {
                                           Id = id,
                                           Tags = Json.Deserialize<HashSet<int>>(tags)
                                       });
                        }
                    }
                }
            }

            var toUpdate = new List<TaggedModel079>();

            foreach (var model in tagged)
            {
                foreach (var replacement in replacements)
                {
                    if (model.Tags.Contains(replacement.OldId))
                    {
                        model.Tags.Remove(replacement.OldId);
                        model.Tags.Add(replacement.NewId);

                        toUpdate.Add(model);
                    }
                }
            }

            foreach (var model in toUpdate.DistinctBy(m => m.Id))
            {
                using (IDbCommand updateCmd = conn.CreateCommand())
                {
                    updateCmd.Transaction = tran;
                    updateCmd.CommandText = string.Format(@"UPDATE {0} SET Tags = ? WHERE Id = ?", table);
                    updateCmd.AddParameter(model.Tags.ToJson());
                    updateCmd.AddParameter(model.Id);

                    updateCmd.ExecuteNonQuery();
                }
            }
        }
Example #13
0
 IEnumerable<PropertyInfo> GetAvailableProperties(Type objectType)
 {
     var properties = new List<PropertyInfo>();
     var type = objectType;
     while(type != null && type != typeof(object))
     {
         properties.AddRange(type.GetProperties(CurrentBindingFlags)
                             .Where(x => x.IsCallable())
         );
         type = type.BaseType;
     }
     return properties.DistinctBy(x=> x.ToString()); //Look @ GetAvailableMethods for explanation.
 }
Example #14
0
 public static int CountUniqueDate(this List <Measure> items)      //<= measure is your T type
 {
     return(items.DistinctBy(i => i.DateMeasured).Count());
 }
Example #15
0
        /// <summary>
        /// Gets the recursive children.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="filter">The filter.</param>
        /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
        /// <returns>IList{BaseItem}.</returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        public IList<BaseItem> GetRecursiveChildren(User user, Func<BaseItem, bool> filter, bool includeLinkedChildren = true)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            var initialCount = _lastRecursiveCount == 0 ? _children.Count : _lastRecursiveCount;
            var list = new List<BaseItem>(initialCount);

            var hasLinkedChildren = AddChildrenToList(user, includeLinkedChildren, list, true, filter);

            _lastRecursiveCount = list.Count;

            return hasLinkedChildren ? list.DistinctBy(i => i.Id).ToList() : list;
        }
Example #16
0
        public Dashboard.CollectionStats GetStats()
        {
            List <SVR_AnimeSeries> series = RepoFactory.AnimeSeries.GetAll().Where(a => User.AllowedSeries(a)).ToList();
            int seriesCount = series.Count;

            int groupCount = series.DistinctBy(a => a.AnimeGroupID).Count();

            List <SVR_AnimeEpisode> episodes = series.SelectMany(a => a.GetAnimeEpisodes()).ToList();

            List <SVR_VideoLocal> files = episodes.SelectMany(a => a?.GetVideoLocals()).Where(a => a != null)
                                          .DistinctBy(a => a.VideoLocalID).ToList();
            int  fileCount = files.Count;
            long size      = files.Sum(a => a.FileSize);

            List <SVR_AnimeEpisode> watchedEpisodes = episodes.Where(a => a?.GetUserRecord(User.JMMUserID)?.WatchedDate != null).ToList();

            int watchedSeries = RepoFactory.AnimeSeries.GetAll().Count(a =>
            {
                CL_AnimeSeries_User contract = a.GetUserContract(User.JMMUserID);
                if (contract == null)
                {
                    return(false);
                }
                return(contract.WatchedEpisodeCount == a.GetAnimeEpisodesAndSpecialsCountWithVideoLocal());
            });

            decimal hours = Math.Round((decimal)watchedEpisodes.Select(a => a.GetVideoLocals().FirstOrDefault())
                                       .Where(a => a != null).Sum(a => a.Media?.GeneralStream?.Duration ?? 0) / 3600, 1, MidpointRounding.AwayFromZero); // Duration in s => 60m*60s = 3600

            List <SVR_VideoLocal_Place> places = files.SelectMany(a => a.Places).ToList();
            int duplicate = places.Where(a => a.VideoLocal.IsVariation == 0).SelectMany(a => RepoFactory.CrossRef_File_Episode.GetByHash(a.VideoLocal.Hash))
                            .GroupBy(a => a.EpisodeID).Count(a => a.Count() > 1);

            decimal percentDupe = places.Count == 0 ? 0 :
                                  Math.Round((decimal)duplicate * 100 / places.Count, 2, MidpointRounding.AwayFromZero);

            int missing           = series.Sum(a => a.MissingEpisodeCount);
            int missingCollecting = series.Sum(a => a.MissingEpisodeCountGroups);

            int unrecognized = RepoFactory.VideoLocal.GetVideosWithoutEpisodeUnsorted().Count();

            int missingLinks = series.Count(MissingBothTvDBAndMovieDBLink);

            int multipleEps = episodes.Count(a => a.GetVideoLocals().Count(b => b.IsVariation == 0) > 1);

            int duplicateFiles = places.GroupBy(a => a.VideoLocalID).Count(a => a.Count() > 1);

            return(new Dashboard.CollectionStats
            {
                FileCount = fileCount,
                FileSize = size,
                SeriesCount = seriesCount,
                GroupCount = groupCount,
                FinishedSeries = watchedSeries,
                WatchedEpisodes = watchedEpisodes.Count,
                WatchedHours = hours,
                PercentDuplicate = percentDupe,
                MissingEpisodes = missing,
                MissingEpisodesCollecting = missingCollecting,
                UnrecognizedFiles = unrecognized,
                SeriesWithMissingLinks = missingLinks,
                EpisodesWithMultipleFiles = multipleEps,
                FilesWithDuplicateLocations = duplicateFiles
            });
        }
Example #17
0
        public async Task <ActionResult> SubmitQuiz(string courseId, Guid slideId, string answer, bool isLti)
        {
            var course = courseManager.GetCourse(courseId);
            var slide  = course.FindSlideById(slideId) as QuizSlide;

            if (slide == null)
            {
                return(new HttpNotFoundResult());
            }

            var userId       = User.Identity.GetUserId();
            var maxDropCount = GetMaxDropCount(slide);
            var quizState    = GetQuizState(courseId, userId, slideId, maxDropCount).Item1;

            if (!CanUserFillQuiz(quizState))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.OK, "Already answered"));
            }

            if (slide.ManualChecking && !groupsRepo.IsManualCheckingEnabledForUser(course, userId))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.OK, "Manual checking is disabled for you"));
            }

            var time    = DateTime.Now;
            var answers = JsonConvert.DeserializeObject <List <QuizAnswer> >(answer).GroupBy(x => x.QuizId);
            var quizBlockWithTaskCount = slide.Blocks.Count(x => x is AbstractQuestionBlock);
            var allQuizInfos           = new List <QuizInfoForDb>();

            foreach (var ans in answers)
            {
                var quizInfos = CreateQuizInfo(slide, ans);
                if (quizInfos != null)
                {
                    allQuizInfos.AddRange(quizInfos);
                }
            }
            var blocksInAnswerCount = allQuizInfos.Select(x => x.QuizId).Distinct().Count();

            if (blocksInAnswerCount != quizBlockWithTaskCount)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Has empty blocks"));
            }

            using (var transaction = db.Database.BeginTransaction())
            {
                await userQuizzesRepo.RemoveUserQuizzes(courseId, slideId, userId);

                foreach (var quizInfoForDb in allQuizInfos)
                {
                    await userQuizzesRepo.AddUserQuiz(courseId, quizInfoForDb.IsRightAnswer, quizInfoForDb.ItemId, quizInfoForDb.QuizId,
                                                      slideId, quizInfoForDb.Text, userId, time, quizInfoForDb.QuizBlockScore, quizInfoForDb.QuizBlockMaxScore);
                }

                transaction.Commit();
            }

            if (slide.ManualChecking)
            {
                /* If this quiz is already queued for checking for this user, don't add it to queue again */
                if (quizState != QuizState.WaitForCheck)
                {
                    await slideCheckingsRepo.AddQuizAttemptForManualChecking(courseId, slideId, userId);

                    await visitsRepo.MarkVisitsAsWithManualChecking(slideId, userId);
                }
            }
            else
            {
                var score = allQuizInfos
                            .DistinctBy(forDb => forDb.QuizId)
                            .Sum(forDb => forDb.QuizBlockScore);
                await slideCheckingsRepo.AddQuizAttemptWithAutomaticChecking(courseId, slideId, userId, score);

                await visitsRepo.UpdateScoreForVisit(courseId, slideId, userId);

                if (isLti)
                {
                    LtiUtils.SubmitScore(slide, userId);
                }
            }

            return(new HttpStatusCodeResult(HttpStatusCode.OK));
        }
Example #18
0
        public async Task <ActionResult> SubmitQuiz(string courseId, Guid slideId, string answer, bool isLti)
        {
            metricSender.SendCount("quiz.submit");
            if (isLti)
            {
                metricSender.SendCount("quiz.submit.lti");
            }
            metricSender.SendCount($"quiz.submit.{courseId}");
            metricSender.SendCount($"quiz.submit.{courseId}.{slideId}");

            var course = courseManager.GetCourse(courseId);
            var slide  = course.FindSlideById(slideId) as QuizSlide;

            if (slide == null)
            {
                return(new HttpNotFoundResult());
            }

            var userId        = User.Identity.GetUserId();
            var maxTriesCount = GetMaxTriesCount(courseId, slide);
            var quizState     = GetQuizState(courseId, userId, slideId);

            if (!CanUserFillQuiz(quizState.Item1))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.OK, "Already answered"));
            }

            var tryIndex = quizState.Item2;

            metricSender.SendCount($"quiz.submit.try.{tryIndex}");
            metricSender.SendCount($"quiz.submit.{courseId}.try.{tryIndex}");
            metricSender.SendCount($"quiz.submit.{courseId}.{slideId}.try.{tryIndex}");

            if (slide.ManualChecking && !groupsRepo.IsManualCheckingEnabledForUser(course, userId))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.OK, "Manual checking is disabled for you"));
            }

            var time    = DateTime.Now;
            var answers = JsonConvert.DeserializeObject <List <QuizAnswer> >(answer).GroupBy(x => x.QuizId);
            var quizBlockWithTaskCount = slide.Blocks.Count(x => x is AbstractQuestionBlock);
            var allQuizInfos           = new List <QuizInfoForDb>();

            foreach (var ans in answers)
            {
                var quizInfos = CreateQuizInfo(slide, ans);
                if (quizInfos != null)
                {
                    allQuizInfos.AddRange(quizInfos);
                }
            }
            var blocksInAnswerCount = allQuizInfos.Select(x => x.QuizId).Distinct().Count();

            if (blocksInAnswerCount != quizBlockWithTaskCount)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Has empty blocks"));
            }

            using (var transaction = db.Database.BeginTransaction())
            {
                await userQuizzesRepo.RemoveUserQuizzes(courseId, slideId, userId);

                foreach (var quizInfoForDb in allQuizInfos)
                {
                    await userQuizzesRepo.AddUserQuiz(courseId, quizInfoForDb.IsRightAnswer, quizInfoForDb.ItemId, quizInfoForDb.QuizId,
                                                      slideId, quizInfoForDb.Text, userId, time, quizInfoForDb.QuizBlockScore, quizInfoForDb.QuizBlockMaxScore);
                }

                transaction.Commit();
            }

            if (slide.ManualChecking)
            {
                /* If this quiz is already queued for checking for this user, don't add it to queue again */
                if (quizState.Item1 != QuizState.WaitForCheck)
                {
                    await slideCheckingsRepo.AddQuizAttemptForManualChecking(courseId, slideId, userId);

                    await visitsRepo.MarkVisitsAsWithManualChecking(slideId, userId);
                }
            }
            /* Recalculate score for quiz if this attempt is allowed. Don't recalculate score if this attempt is more then maxTriesCount */
            else if (tryIndex < maxTriesCount)
            {
                var score = allQuizInfos
                            .DistinctBy(forDb => forDb.QuizId)
                            .Sum(forDb => forDb.QuizBlockScore);

                metricSender.SendCount($"quiz.submit.try.{tryIndex}.score", score);
                metricSender.SendCount($"quiz.submit.{courseId}.try.{tryIndex}.score", score);
                metricSender.SendCount($"quiz.submit.{courseId}.{slideId}.try.{tryIndex}.score", score);
                metricSender.SendCount($"quiz.submit.score", score);
                metricSender.SendCount($"quiz.submit.{courseId}.score", score);
                metricSender.SendCount($"quiz.submit.{courseId}.{slideId}.score", score);

                if (score == slide.MaxScore)
                {
                    metricSender.SendCount($"quiz.submit.try.{tryIndex}.full_passed");
                    metricSender.SendCount($"quiz.submit.{courseId}.try.{tryIndex}.full_passed");
                    metricSender.SendCount($"quiz.submit.{courseId}.{slideId}.try.{tryIndex}.full_passed");
                    metricSender.SendCount($"quiz.submit.full_passed");
                    metricSender.SendCount($"quiz.submit.{courseId}.full_passed");
                    metricSender.SendCount($"quiz.submit.{courseId}.{slideId}.full_passed");
                }

                await slideCheckingsRepo.AddQuizAttemptWithAutomaticChecking(courseId, slideId, userId, score);

                await visitsRepo.UpdateScoreForVisit(courseId, slideId, userId);

                if (isLti)
                {
                    LtiUtils.SubmitScore(slide, userId);
                }
            }

            return(Json(new
            {
                url = Url.RouteUrl("Course.SlideById", new { courseId = courseId, slideId = slide.Url, send = 1 })
            }));
        }
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();

            // Code for starting up the Xamarin Test Cloud Agent
#if ENABLE_TEST_CLOUD
            Xamarin.Calabash.Start();
#endif

            LoadApplication(new App());


            // Handling Push notification when app is closed if App was opened by Push Notification...
            if (options != null && options.Keys != null && options.Keys.Count() != 0 && options.ContainsKey(new NSString("UIApplicationLaunchOptionsRemoteNotificationKey")))
            {
                NSDictionary UIApplicationLaunchOptionsRemoteNotificationKey = options.ObjectForKey(new NSString("UIApplicationLaunchOptionsRemoteNotificationKey")) as NSDictionary;

                ProcessNotification(UIApplicationLaunchOptionsRemoteNotificationKey, true);
            }

            //added on 1/7/17 by aditmer to see if the device token from APNS has changed (like after an app update)
            if (ApplicationSettings.InstallationID != "")
            {
                //Push notifications registration
                if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                {
                    var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
                        UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
                        new NSSet());

                    UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
                    UIApplication.SharedApplication.RegisterForRemoteNotifications();
                }
                else
                {
                    UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
                    UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
                }
            }
            //added on 1/4/17 by aditmer to add 4 (1/6/17) customizable snooze options
            int snoozeTime1 = 1;
            int snoozeTime2 = 2;
            int snoozeTime3 = 3;
            int snoozeTime4 = 4;

            if (ApplicationSettings.AlarmUrgentLowMins1 != 0)
            {
                snoozeTime1 = ApplicationSettings.AlarmUrgentLowMins1;
            }

            if (ApplicationSettings.AlarmUrgentLowMins2 != 0)
            {
                snoozeTime2 = ApplicationSettings.AlarmUrgentLowMins2;
            }

            if (ApplicationSettings.AlarmUrgentMins1 != 0)
            {
                snoozeTime3 = ApplicationSettings.AlarmUrgentMins1;
            }

            if (ApplicationSettings.AlarmUrgentMins2 != 0)
            {
                snoozeTime4 = ApplicationSettings.AlarmUrgentMins2;
            }


            //added on 12/03/16 by aditmer to add custom actions to the notifications (I think this code goes here)
            // Create action
            var actionID = "snooze1";
            var title    = $"Snooze {snoozeTime1} minutes";
            var action   = UNNotificationAction.FromIdentifier(actionID, title, UNNotificationActionOptions.None);

            var actionID2 = "snooze2";
            var title2    = $"Snooze {snoozeTime2} minutes";
            var action2   = UNNotificationAction.FromIdentifier(actionID2, title2, UNNotificationActionOptions.None);

            var actionID3 = "snooze3";
            var title3    = $"Snooze {snoozeTime3} minutes";
            var action3   = UNNotificationAction.FromIdentifier(actionID3, title3, UNNotificationActionOptions.None);

            var actionID4 = "snooze4";
            var title4    = $"Snooze {snoozeTime4} minutes";
            var action4   = UNNotificationAction.FromIdentifier(actionID4, title4, UNNotificationActionOptions.None);

            // Create category
            var categoryID = "event";
            var actions    = new List <UNNotificationAction> {
                action, action2, action3, action4
            };
            var intentIDs       = new string[] { };
            var categoryOptions = new UNNotificationCategoryOptions[] { };

            //added on 1/19/17 by aditmer to remove duplicate snooze options (they can be custom set by each user in their Nightscout settings)
            actions = actions.DistinctBy((arg) => arg.Title).ToList();


            var category = UNNotificationCategory.FromIdentifier(categoryID, actions.ToArray(), intentIDs, UNNotificationCategoryOptions.AllowInCarPlay);

            // Register category
            var categories = new UNNotificationCategory[] { category };
            UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet <UNNotificationCategory>(categories));

            return(base.FinishedLaunching(app, options));
        }
Example #20
0
        /// <summary>
        /// Downloads historical data from the brokerage and saves it in LEAN format.
        /// </summary>
        /// <param name="brokerage">The brokerage from where to fetch the data</param>
        /// <param name="symbols">The list of symbols</param>
        /// <param name="startTimeUtc">The starting date/time (UTC)</param>
        /// <param name="endTimeUtc">The ending date/time (UTC)</param>
        public void DownloadAndSave(IBrokerage brokerage, List <Symbol> symbols, DateTime startTimeUtc, DateTime endTimeUtc)
        {
            if (symbols.Count == 0)
            {
                throw new ArgumentException("DownloadAndSave(): The symbol list cannot be empty.");
            }

            if (_tickType != TickType.Trade && _tickType != TickType.Quote)
            {
                throw new ArgumentException("DownloadAndSave(): The tick type must be Trade or Quote.");
            }

            if (symbols.Any(x => x.SecurityType != _securityType))
            {
                throw new ArgumentException($"DownloadAndSave(): All symbols must have {_securityType} security type.");
            }

            if (symbols.DistinctBy(x => x.ID.Symbol).Count() > 1)
            {
                throw new ArgumentException("DownloadAndSave(): All symbols must have the same root ticker.");
            }

            var dataType = LeanData.GetDataType(_resolution, _tickType);

            var marketHoursDatabase = MarketHoursDatabase.FromDataFolder();

            var ticker = symbols.First().ID.Symbol;
            var market = symbols.First().ID.Market;

            var canonicalSymbol = Symbol.Create(ticker, _securityType, market);

            var exchangeHours = marketHoursDatabase.GetExchangeHours(canonicalSymbol.ID.Market, canonicalSymbol, _securityType);
            var dataTimeZone  = marketHoursDatabase.GetDataTimeZone(canonicalSymbol.ID.Market, canonicalSymbol, _securityType);

            foreach (var symbol in symbols)
            {
                var historyRequest = new HistoryRequest(
                    startTimeUtc,
                    endTimeUtc,
                    dataType,
                    symbol,
                    _resolution,
                    exchangeHours,
                    dataTimeZone,
                    _resolution,
                    true,
                    false,
                    DataNormalizationMode.Raw,
                    _tickType
                    );

                var history = brokerage.GetHistory(historyRequest)
                              .Select(
                    x =>
                {
                    // Convert to date timezone before we write it
                    x.Time = x.Time.ConvertTo(exchangeHours.TimeZone, dataTimeZone);
                    return(x);
                })
                              .ToList();

                // Generate a writer for this data and write it
                var writer = new LeanDataWriter(_resolution, symbol, _dataDirectory, _tickType);
                writer.Write(history);
            }
        }
        public IEnumerable <Constructor> DescriptorConstructors()
        {
            var ctors = new List <Constructor>();

            if (IsPartless)
            {
                return(ctors);
            }
            var m = this.DescriptorType;

            foreach (var url in this.Url.Paths)
            {
                var requiredUrlRouteParameters = this.Url.Parts
                                                 .Where(p => !ApiUrl.BlackListRouteValues.Contains(p.Key))
                                                 .Where(p => p.Value.Required)
                                                 .Where(p => url.Contains($"{{{p.Value.Name}}}"))
                                                 .OrderBy(kv => url.IndexOf($"{{{kv.Value.Name}}}", StringComparison.Ordinal));

                var par     = string.Join(", ", requiredUrlRouteParameters.Select(p => $"{ClrParamType(p.Value.ClrTypeName)} {p.Key}"));
                var routing = string.Empty;
                //Routes that take {indices}/{types} and both are optional
                if (!requiredUrlRouteParameters.Any() && IndicesAndTypes)
                {
                    AddParameterlessIndicesTypesConstructor(ctors, m);
                    continue;
                }
                if (requiredUrlRouteParameters.Any())
                {
                    routing = "r=>r." + string.Join(".", requiredUrlRouteParameters
                                                    .Select(p => new
                    {
                        route = p.Key,
                        call  = p.Value.Required ? "Required" : "Optional",
                        v     = p.Key == "metric"
                                                                ? $"(Metrics){p.Key}"
                                                                : p.Key == "index_metric"
                                                                        ? $"(IndexMetrics){p.Key}"
                                                                        : p.Key
                    })
                                                    .Select(p => $"{p.call}(\"{p.route}\", {p.v})")
                                                    );
                }
                var doc = $@"/// <summary>{url}</summary>";
                if (requiredUrlRouteParameters.Any())
                {
                    doc += "\r\n\t\t" + string.Join("\r\n\t\t", requiredUrlRouteParameters.Select(p => $"///<param name=\"{p.Key}\"> this parameter is required</param>"));
                }

                var generated = $"public {m}({par}) : base({routing})";
                var body      = this.IsDocumentRequest ? $"Q(\"routing\", new Routing(() => AutoRouteDocument()));" : string.Empty;

                // Add typeof(T) as the default type when only index specified
                if ((m == "DeleteByQueryDescriptor" || m == "UpdateByQueryDescriptor") && requiredUrlRouteParameters.Count() == 1 && !string.IsNullOrEmpty(this.RequestTypeGeneric))
                {
                    var generic = this.RequestTypeGeneric.Replace("<", "").Replace(">", "");
                    generated = $"public {m}({par}) : base({routing}.Required(\"type\", (Types)typeof({generic})))";
                }

                if ((m == "SearchShardsDescriptor") && !string.IsNullOrEmpty(this.RequestTypeGeneric))
                {
                    var generic = this.RequestTypeGeneric.Replace("<", "").Replace(">", "");
                    doc       = AppendToSummary(doc, ". Will infer the index from the generic type");
                    generated = $"public {m}({par}) : base(r => r.Optional(\"index\", (Indices)typeof({generic})))";
                }

                // Use generic T to set the Indices and Types by default in the ctor
                if (m == "PutDatafeedDescriptor" || m == "UpdateDatafeedDescriptor")
                {
                    var generic = "T";
                    doc       = AppendToSummary(doc, ". Will infer the index and type from the generic type");
                    generated = $"public {m}({par}) : base({routing})";
                    body      = $"{{ Self.Indices = typeof({generic}); Self.Types = typeof({generic}); {body} }}";
                }

                var c = new Constructor
                {
                    Generated   = generated,
                    Description = doc,
                    Body        = (!body.IsNullOrEmpty() && !body.StartsWith("{")) ? ("=> " + body) : body
                };
                ctors.Add(c);
            }
            if (IsDocumentPath && !string.IsNullOrEmpty(this.DescriptorTypeGeneric))
            {
                var documentPathGeneric = Regex.Replace(this.DescriptorTypeGeneric, @"^<?([^\s,>]+).*$", "$1");
                var doc = $"/// <summary>{this.Url.Path}</summary>";
                doc += "\r\n\t\t" + $"///<param name=\"document\"> describes an elasticsearch document of type <typeparamref name=\"{documentPathGeneric}\"/> from which the index, type and id can be inferred</param>";
                var documentRoute    = "r=>r.Required(\"index\", document.Self.Index).Required(\"type\", document.Self.Type).Required(\"id\", document.Self.Id)";
                var documentFromPath = $"partial void DocumentFromPath({documentPathGeneric} document);";
                var autoRoute        = this.IsDocumentRequest ? $"Q(\"routing\", new Routing(() => AutoRouteDocument() ?? document.Document));" : string.Empty;
                var c = new Constructor
                {
                    AdditionalCode = documentFromPath,
                    Generated      =
                        $"public {m}(DocumentPath<{documentPathGeneric}> document) : base({documentRoute})",
                    Description = doc,
                    Body        = $"{{ this.DocumentFromPath(document.Document); {autoRoute}}}"
                };
                ctors.Add(c);
            }

            return(ctors.DistinctBy(c => c.Generated));
        }
Example #22
0
    public void SaveSong()
    {
        try
        {
            if (string.IsNullOrEmpty(directory))
            {
                directory = $"{(isWIPMap ? Settings.Instance.CustomWIPSongsFolder : Settings.Instance.CustomSongsFolder)}/{songName}";
            }
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            if (json == null)
            {
                json = new JSONObject();
            }
            if (customData == null)
            {
                customData = new JSONObject();
            }

            //Just in case, i'm moving them up here
            System.Threading.Thread.CurrentThread.CurrentCulture   = CultureInfo.InvariantCulture;
            System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;

            json["_version"]         = version;
            json["_songName"]        = songName;
            json["_songSubName"]     = songSubName;
            json["_songAuthorName"]  = songAuthorName;
            json["_levelAuthorName"] = levelAuthorName;

            json["_beatsPerMinute"]   = beatsPerMinute;
            json["_previewStartTime"] = previewStartTime;
            json["_previewDuration"]  = previewDuration;
            json["_songTimeOffset"]   = songTimeOffset;

            json["_shuffle"]       = shuffle;
            json["_shufflePeriod"] = shufflePeriod;

            json["_coverImageFilename"] = coverImageFilename;
            json["_songFilename"]       = songFilename;

            json["_environmentName"] = environmentName;
            json["_allDirectionsEnvironmentName"] = allDirectionsEnvironmentName;
            json["_customData"]            = customData;
            json["_customData"]["_editor"] = editor;

            JSONArray contributorArrayFUCKYOUGIT = new JSONArray();
            contributors.DistinctBy(x => x.ToJSONNode().ToString()).ToList().ForEach(x => contributorArrayFUCKYOUGIT.Add(x.ToJSONNode()));
            json["_customData"]["_contributors"] = contributorArrayFUCKYOUGIT;

            //BeatSaver schema changes, see below comment.
            if (string.IsNullOrEmpty(customData["_editor"]))
            {
                json["_customData"]["_editor"] = "chromapper";
            }
            if (string.IsNullOrEmpty(customData["_contributors"]))
            {
                json["_customData"].Remove("_contributors");
            }
            if (string.IsNullOrEmpty(customData["_customEnvironment"]))
            {
                json["_customData"].Remove("_customEnvironment");
            }
            if (string.IsNullOrEmpty(customData["_customEnvironmentHash"]))
            {
                json["_customData"].Remove("_customEnvironmentHash");
            }
            if (json["_customData"].Linq.Count() <= 0)
            {
                json.Remove("_customData");
            }

            JSONArray sets = new JSONArray();
            foreach (DifficultyBeatmapSet set in difficultyBeatmapSets)
            {
                JSONNode setNode = new JSONObject();
                setNode["_beatmapCharacteristicName"] = set.beatmapCharacteristicName;
                JSONArray diffs = new JSONArray();
                IEnumerable <DifficultyBeatmap> sortedBeatmaps = set.difficultyBeatmaps.OrderBy(x => x.difficultyRank);
                foreach (DifficultyBeatmap diff in sortedBeatmaps)
                {
                    JSONNode subNode = new JSONObject();
                    subNode["_difficulty"]              = diff.difficulty;
                    subNode["_difficultyRank"]          = diff.difficultyRank;
                    subNode["_beatmapFilename"]         = diff.beatmapFilename;
                    subNode["_noteJumpMovementSpeed"]   = diff.noteJumpMovementSpeed;
                    subNode["_noteJumpStartBeatOffset"] = diff.noteJumpStartBeatOffset;
                    subNode["_customData"]              = diff.customData;

                    if (diff.colorLeft != DEFAULT_LEFTNOTE)
                    {
                        subNode["_customData"]["_colorLeft"] = GetJSONNodeFromColor(diff.colorLeft);
                    }
                    if (diff.colorRight != DEFAULT_RIGHTNOTE)
                    {
                        subNode["_customData"]["_colorRight"] = GetJSONNodeFromColor(diff.colorRight);
                    }
                    if (diff.envColorLeft != DEFAULT_LEFTCOLOR && diff.envColorLeft != diff.colorLeft)
                    {
                        subNode["_customData"]["_envColorLeft"] = GetJSONNodeFromColor(diff.envColorLeft);
                    }
                    if (diff.envColorRight != DEFAULT_RIGHTCOLOR && diff.envColorRight != diff.colorRight)
                    {
                        subNode["_customData"]["_envColorRight"] = GetJSONNodeFromColor(diff.envColorRight);
                    }
                    if (diff.obstacleColor != DEFAULT_LEFTCOLOR)
                    {
                        subNode["_customData"]["_obstacleColor"] = GetJSONNodeFromColor(diff.obstacleColor);
                    }


                    /*
                     * More BeatSaver Schema changes, yayyyyy! (f**k)
                     * If any additional non-required fields are present, they cannot be empty.
                     *
                     * So ChroMapper is just gonna yeet anything that is null or empty, then keep going down the list.
                     * If customData is empty, then we just yeet that.
                     */
                    if (subNode["_customData"] != null)
                    {
                        if (string.IsNullOrEmpty(diff.customData["_difficultyLabel"]))
                        {
                            subNode["_customData"].Remove("_difficultyLabel");
                        }
                        if (diff.customData["_editorOldOffset"] != null && diff.customData["_editorOldOffset"].AsFloat <= 0)
                        {
                            subNode["_customData"].Remove("_editorOldOffset"); //For some reason these are used by MM but not by CM
                        }
                        if (diff.customData["_editorOffset"] != null && diff.customData["_editorOffset"].AsFloat <= 0)
                        {
                            subNode["_customData"].Remove("_editorOffset"); //So we're just gonna yeet them. Sorry squanksers.
                        }
                        if (diff.customData["_warnings"] != null && diff.customData["_warnings"].AsArray.Count <= 0)
                        {
                            subNode["_customData"].Remove("_warnings");
                        }
                        if (diff.customData["_information"] != null && diff.customData["_information"].AsArray.Count <= 0)
                        {
                            subNode["_customData"].Remove("_information");
                        }
                        if (diff.customData["_suggestions"] != null && diff.customData["_suggestions"].AsArray.Count <= 0)
                        {
                            subNode["_customData"].Remove("_suggestions");
                        }
                        if (diff.customData["_requirements"] != null && diff.customData["_requirements"].AsArray.Count <= 0)
                        {
                            subNode["_customData"].Remove("_requirements");
                        }
                        if (subNode["_customData"].Linq.Count() <= 0)
                        {
                            subNode.Remove("_customData");
                        }
                    }
                    else
                    {
                        subNode.Remove("_customData");  //Just remove it if it's null lmao
                    }
                    diffs.Add(subNode);
                }
                setNode["_difficultyBeatmaps"] = diffs;
                sets.Add(setNode);
            }

            json["_difficultyBeatmapSets"] = sets;

            using (StreamWriter writer = new StreamWriter(directory + "/info.dat", false))
                writer.Write(json.ToString(2));

            Debug.Log("Saved song info.dat for " + songName);
        }
        catch (Exception e)
        {
            Debug.LogException(e);
        }
    }
        public static Lazy<IContentType> GetContentTypeDefinition(Type modelType)
        {
            //Check for BaseType different from ContentTypeBase
            bool hasParent = modelType.BaseType != null && modelType.BaseType != typeof(ContentTypeBase) && modelType.BaseType != typeof(object);
            var parent = new Lazy<IContentType>();
            if(hasParent)
            {
                var isResolved = _contentTypeCache.ContainsKey(modelType.BaseType.FullName);
                parent = isResolved
                             ? _contentTypeCache[modelType.BaseType.FullName].ContentType
                             : GetContentTypeDefinition(modelType.BaseType);
            }

            var contentTypeAttribute = modelType.FirstAttribute<ContentTypeAttribute>();
            var contentTypeAlias = contentTypeAttribute == null ? modelType.Name.ToUmbracoAlias() : contentTypeAttribute.Alias;
            //Check if ContentType already exists by looking it up by Alias.
            var existing = ApplicationContext.Current.Services.ContentTypeService.GetContentType(contentTypeAlias);
            
            Lazy<IContentType> contentType = contentTypeAttribute == null
                                                 ? PlainPocoConvention(modelType, existing)
                                                 : ContentTypeConvention(contentTypeAttribute, modelType, existing);

            //Check for interfaces that'll be used for ContentTypeComposition
            var mixins = GetAliasesFromTypeInterfaces(modelType);

            var definitions = new List<PropertyDefinition>();
            int order = 0;
            var objProperties = modelType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly).ToList();
            foreach (var propertyInfo in objProperties)
            {
                var propertyTypeAttribute = propertyInfo.FirstAttribute<PropertyTypeConventionAttribute>();
                var definition = propertyTypeAttribute == null
                                     ? new PropertyDefinition()
                                     : propertyTypeAttribute.GetPropertyConvention();

                //DataTypeDefinition fallback
                if(definition.DataTypeDefinition == null)
                {
                    definition.DataTypeDefinition = Conventions.GetDataTypeDefinitionByAttributeOrType(null, propertyInfo.PropertyType);
                }

                if(string.IsNullOrEmpty(definition.PropertyGroup))
                {
                    definition.PropertyGroup = "Generic Properties";
                }

                //Alias fallback
                if (string.IsNullOrEmpty(definition.Alias))
                {
                    var aliasAttribute = propertyInfo.FirstAttribute<AliasAttribute>();
                    definition.Alias = Conventions.GetPropertyTypeAlias(aliasAttribute, propertyInfo.Name);
                    definition.Name = Conventions.GetPropertyTypeName(aliasAttribute, propertyInfo.Name);
                }

                //Description fallback
                if (string.IsNullOrEmpty(definition.Description))
                {
                    var descriptionAttribute = propertyInfo.FirstAttribute<DescriptionAttribute>();
                    definition.Description = descriptionAttribute != null
                                                 ? descriptionAttribute.Description
                                                 : string.Empty;
                }

                //SortOrder fallback
                if (definition.Order == default(int))
                {
                    var sortOrderAttribute = propertyInfo.FirstAttribute<SortOrderAttribute>();
                    definition.Order = sortOrderAttribute != null ? sortOrderAttribute.Order : order;
                }

                definitions.Add(definition);
                order++;
            }

            //Loop through definitions for PropertyGroups and create those that not already exists
            var groupDefinitions = definitions.DistinctBy(d => d.PropertyGroup);
            foreach (var groupDefinition in groupDefinitions)
            {
                var groupExists = contentType.Value.PropertyGroups.Contains(groupDefinition.PropertyGroup);
                if(groupExists == false)
                {
                    var propertyGroup = new PropertyGroup {Name = groupDefinition.PropertyGroup};
                    contentType.Value.PropertyGroups.Add(propertyGroup);
                }
            }

            //Loop through definitions for PropertyTypes and add them to the correct PropertyGroup
            foreach (var definition in definitions)
            {
                var group = contentType.Value.PropertyGroups.First(x => x.Name == definition.PropertyGroup);
                //Check if a PropertyType with the same alias already exists, as we don't want to override existing ones
                if(group.PropertyTypes.Contains(definition.Alias)) continue;

                var propertyType = new PropertyType(definition.DataTypeDefinition)
                                       {
                                           Mandatory = definition.Mandatory,
                                           ValidationRegExp = definition.ValidationRegExp,
                                           SortOrder = definition.Order,
                                           Alias = definition.Alias,
                                           Name = definition.Name
                                       };

                group.PropertyTypes.Add(propertyType);
            }

            //If current ContentType has a Parent the ParentId should be set and the ContentType added to the composition.
            if(hasParent)
            {
                contentType.Value.SetLazyParentId(new Lazy<int>(() => parent.Value.Id));
                contentType.Value.AddContentType(parent.Value);
            }
            //Add the resolved ContentType to the internal cache
            var field = new DependencyField {ContentType = contentType, Alias = contentType.Value.Alias};
            var dependencies = new List<string>();
            //If current type has a parent (inherited model) we add the alias of that type as a dependency
            if(hasParent)
            {
                dependencies.Add(parent.Value.Alias);
            }
            //Check ContentType for existing 'Allowed ContentTypes'
            if(contentType.Value.AllowedContentTypes.Any())
            {
                dependencies.AddRange(contentType.Value.AllowedContentTypes.Select(allowed => allowed.Alias));
            }
            //Check for interfaces with AliasAttribute and add those as dependencies 
            //NOTE: might also be an idea to check if ContentType has already been created/added to cache that implements the interface.
            if(mixins.Any())
            {
                foreach (var mixin in mixins)
                {
                    if(dependencies.Contains(mixin.Item1)) continue;

                    dependencies.Add(mixin.Item1);
                    var isMixinResolved = _contentTypeCache.ContainsKey(mixin.Item2);

                    Lazy<IContentType> compositionType = null;

                    if (isMixinResolved)
                    {
                        compositionType = _contentTypeCache[mixin.Item2].ContentType;
                    }
                    else
                    {
                        GetContentTypeDefinition(mixin.Item3);
                        compositionType = _contentTypeCache[mixin.Item2].ContentType;
                    }

                    contentType.Value.AddContentType(compositionType.Value);
                }
            }
            field.DependsOn = dependencies.ToArray();
            _contentTypeCache.AddOrUpdate(modelType.FullName, field, (x, y) => field);
            return contentType;
        }
Example #24
0
        public static List <Language> ParseLanguages(string title)
        {
            var lowerTitle = title.ToLower();
            var languages  = new List <Language>();

            if (lowerTitle.Contains("english"))
            {
                languages.Add(Language.English);
            }

            if (lowerTitle.Contains("french"))
            {
                languages.Add(Language.French);
            }

            if (lowerTitle.Contains("spanish"))
            {
                languages.Add(Language.Spanish);
            }

            if (lowerTitle.Contains("danish"))
            {
                languages.Add(Language.Danish);
            }

            if (lowerTitle.Contains("dutch"))
            {
                languages.Add(Language.Dutch);
            }

            if (lowerTitle.Contains("japanese"))
            {
                languages.Add(Language.Japanese);
            }

            if (lowerTitle.Contains("icelandic"))
            {
                languages.Add(Language.Icelandic);
            }

            if (lowerTitle.Contains("mandarin") || lowerTitle.Contains("cantonese") || lowerTitle.Contains("chinese"))
            {
                languages.Add(Language.Chinese);
            }

            if (lowerTitle.Contains("korean"))
            {
                languages.Add(Language.Korean);
            }

            if (lowerTitle.Contains("russian"))
            {
                languages.Add(Language.Russian);
            }

            if (lowerTitle.Contains("romanian"))
            {
                languages.Add(Language.Romanian);
            }

            if (lowerTitle.Contains("hindi"))
            {
                languages.Add(Language.Hindi);
            }

            if (lowerTitle.Contains("thai"))
            {
                languages.Add(Language.Thai);
            }

            if (lowerTitle.Contains("bulgarian"))
            {
                languages.Add(Language.Bulgarian);
            }

            if (lowerTitle.Contains("polish"))
            {
                languages.Add(Language.Polish);
            }

            if (lowerTitle.Contains("vietnamese"))
            {
                languages.Add(Language.Vietnamese);
            }

            if (lowerTitle.Contains("swedish"))
            {
                languages.Add(Language.Swedish);
            }

            if (lowerTitle.Contains("norwegian"))
            {
                languages.Add(Language.Norwegian);
            }

            if (lowerTitle.Contains("finnish"))
            {
                languages.Add(Language.Finnish);
            }

            if (lowerTitle.Contains("turkish"))
            {
                languages.Add(Language.Turkish);
            }

            if (lowerTitle.Contains("portuguese"))
            {
                languages.Add(Language.Portuguese);
            }

            if (lowerTitle.Contains("hungarian"))
            {
                languages.Add(Language.Hungarian);
            }

            if (lowerTitle.Contains("hebrew"))
            {
                languages.Add(Language.Hebrew);
            }

            // Case sensitive
            var caseSensitiveMatch = CaseSensitiveLanguageRegex.Match(title);

            if (caseSensitiveMatch.Groups["lithuanian"].Captures.Cast <Capture>().Any())
            {
                languages.Add(Language.Lithuanian);
            }

            if (caseSensitiveMatch.Groups["czech"].Captures.Cast <Capture>().Any())
            {
                languages.Add(Language.Czech);
            }

            var matches = LanguageRegex.Matches(title);

            foreach (Match match in matches)
            {
                if (match.Groups["italian"].Captures.Cast <Capture>().Any())
                {
                    languages.Add(Language.Italian);
                }

                if (match.Groups["german"].Captures.Cast <Capture>().Any())
                {
                    languages.Add(Language.German);
                }

                if (match.Groups["flemish"].Captures.Cast <Capture>().Any())
                {
                    languages.Add(Language.Flemish);
                }

                if (match.Groups["greek"].Captures.Cast <Capture>().Any())
                {
                    languages.Add(Language.Greek);
                }

                if (match.Groups["french"].Success)
                {
                    languages.Add(Language.French);
                }

                if (match.Groups["russian"].Success)
                {
                    languages.Add(Language.Russian);
                }

                if (match.Groups["english"].Success)
                {
                    languages.Add(Language.English);
                }

                if (match.Groups["bulgarian"].Success)
                {
                    languages.Add(Language.Bulgarian);
                }

                if (match.Groups["dutch"].Success)
                {
                    languages.Add(Language.Dutch);
                }

                if (match.Groups["hungarian"].Success)
                {
                    languages.Add(Language.Hungarian);
                }

                if (match.Groups["hebrew"].Success)
                {
                    languages.Add(Language.Hebrew);
                }

                if (match.Groups["chinese"].Success)
                {
                    languages.Add(Language.Chinese);
                }
            }

            if (title.ToLower().Contains("multi"))
            {
                //Let's add english language to multi release as a safe guard.
                if (!languages.Contains(Language.English) && languages.Count < 2)
                {
                    languages.Add(Language.English);
                }
            }

            if (!languages.Any())
            {
                languages.Add(Language.Unknown);
            }

            return(languages.DistinctBy(l => (int)l).ToList());
        }
Example #25
0
        void GenerateReleaseBundleTags(List<BundleItFile> BundleResolvedFiles, eBundleType type)
        {
            var bname = string.Empty;
            var path = type == eBundleType.script ? _settings.ScriptPath : _settings.StylePath;
            var tag_template = type == eBundleType.script ? _script_tag_template : _style_tag_template;
            var tag_cdn_template = type == eBundleType.script ? _script_tag_standard_template : _style_tag_standard_template;
            var obfuscated_source_hash = string.Empty;

            StringBuilder tags;
            var unique_bundles = BundleResolvedFiles.DistinctBy(b => b.bundle_name);
            foreach (var bundle in unique_bundles)
            {
                tags = new StringBuilder();
                var unique_resolved_bundles = BundleResolvedFiles.Where(b => b.bundle_name == bundle.bundle_name).DistinctBy(b2 => b2.resolved_bundle_name);
                
                foreach (var rbundle in unique_resolved_bundles)
                {
                    if (rbundle.IsCDN)
                        tags.AppendLine(string.Format(tag_cdn_template, rbundle.minifiedrelativepath));
                    else
                    {
                        if (type == eBundleType.script)
                            obfuscated_source_hash = _script_compressed_bundles[rbundle.resolved_bundle_name].obfuscated_source_hash;

                        if (type == eBundleType.style)
                            obfuscated_source_hash = _style_compressed_bundles[rbundle.resolved_bundle_name].obfuscated_source_hash;


                        tags.AppendLine(string.Format(tag_template, "/" + path + "/" + rbundle.resolved_bundle_name.ToLower(), obfuscated_source_hash));
                    }
                }

                if (type == eBundleType.script)
                    _script_tag_bundles.Add(bundle.bundle_name, tags.ToString());

                if (type == eBundleType.style)
                    _style_tag_bundles.Add(bundle.bundle_name, tags.ToString());
            }
        }
        public bool ProcessRecords(EntityCollection ec, List <EntityMetadata> emds, int organizationMajorVersion, BackgroundWorker worker)
        {
            var records  = new List <Entity>(ec.Entities);
            var progress = new ImportProgress(records.Count);

            var nextCycle = new List <Entity>();
            int loopIndex = 0;

            while (records.Any())
            {
                loopIndex++;
                if (loopIndex == maxErrorLoopCount)
                {
                    logger.LogWarning("Max loop count reached! Exit record first cycle processing !");
                    break;
                }

                for (int i = records.Count - 1; i >= 0; i--)
                {
                    if (worker.CancellationPending)
                    {
                        return(true);
                    }

                    var record = records[i];

                    if (record.LogicalName != "annotation")
                    {
                        if (record.Attributes.Values.Any(v =>
                                                         v is EntityReference &&
                                                         records.Select(r => r.Id).Contains(((EntityReference)v).Id)
                                                         ))
                        {
                            if (nextCycle.Any(r => r.Id == record.Id))
                            {
                                continue;
                            }

                            var newRecord = new Entity(record.LogicalName)
                            {
                                Id = record.Id
                            };
                            var toRemove = new List <string>();
                            foreach (var attr in record.Attributes)
                            {
                                if (attr.Value is EntityReference)
                                {
                                    newRecord.Attributes.Add(attr.Key, attr.Value);
                                    toRemove.Add(attr.Key);
                                    nextCycle.Add(newRecord);
                                }
                            }

                            foreach (var attr in toRemove)
                            {
                                record.Attributes.Remove(attr);
                            }
                        }

                        if (record.Attributes.Values.Any(v =>
                                                         v is Guid &&
                                                         records.Where(r => r.Id != record.Id)
                                                         .Select(r => r.Id)
                                                         .Contains((Guid)v)
                                                         ))
                        {
                            continue;
                        }
                    }

                    var entityProgress = progress.Entities.FirstOrDefault(e => e.LogicalName == record.LogicalName);
                    if (entityProgress == null)
                    {
                        var    emd         = emds.First(e => e.LogicalName == record.LogicalName);
                        string displayName = emd.DisplayName?.UserLocalizedLabel?.Label;

                        if (displayName == null && emd.IsIntersect.Value)
                        {
                            var rel = emds.SelectMany(ent => ent.ManyToManyRelationships)
                                      .First(r => r.IntersectEntityName == emd.LogicalName);

                            displayName = $"{emds.First(ent => ent.LogicalName == rel.Entity1LogicalName).DisplayName?.UserLocalizedLabel?.Label} / {emds.First(ent => ent.LogicalName == rel.Entity2LogicalName).DisplayName?.UserLocalizedLabel?.Label}";
                        }
                        if (displayName == null)
                        {
                            displayName = emd.SchemaName;
                        }

                        entityProgress = new EntityProgress(emd, displayName);
                        progress.Entities.Add(entityProgress);
                    }

                    try
                    {
                        record.Attributes.Remove("ownerid");

                        if (record.Attributes.Count == 3 && record.Attributes.Values.All(v => v is Guid))
                        {
                            try
                            {
                                var rel =
                                    emds.SelectMany(e => e.ManyToManyRelationships)
                                    .First(r => r.IntersectEntityName == record.LogicalName);

                                service.Associate(rel.Entity1LogicalName,
                                                  record.GetAttributeValue <Guid>(rel.Entity1IntersectAttribute),
                                                  new Relationship(rel.SchemaName),
                                                  new EntityReferenceCollection(new List <EntityReference>
                                {
                                    new EntityReference(rel.Entity2LogicalName,
                                                        record.GetAttributeValue <Guid>(rel.Entity2IntersectAttribute))
                                }));

                                logger.LogInfo($"Association {entityProgress.Entity} ({record.Id}) created");
                            }
                            catch (FaultException <OrganizationServiceFault> error)
                            {
                                if (error.Detail.ErrorCode != -2147220937)
                                {
                                    throw;
                                }

                                logger.LogInfo($"Association {entityProgress.Entity} ({record.Id}) already exists");
                            }
                        }
                        else
                        {
                            if (record.Attributes.Contains("statecode") &&
                                record.GetAttributeValue <OptionSetValue>("statecode").Value == 1)
                            {
                                logger.LogInfo($"Record {record.GetAttributeValue<string>(entityProgress.Metadata.PrimaryNameAttribute)} is inactive : Added for deactivation step");

                                recordsToDeactivate.Add(record.ToEntityReference());
                                record.Attributes.Remove("statecode");
                                record.Attributes.Remove("statuscode");
                            }

                            if (organizationMajorVersion >= 8)
                            {
                                var result = (UpsertResponse)service.Execute(new UpsertRequest
                                {
                                    Target = record
                                });

                                logger.LogInfo(
                                    $"Record {record.GetAttributeValue<string>(entityProgress.Metadata.PrimaryNameAttribute)} {(result.RecordCreated ? "created" : "updated")} ({entityProgress.Entity}/{record.Id})");
                            }
                            else
                            {
                                bool exists = false;
                                try
                                {
                                    service.Retrieve(record.LogicalName, record.Id, new ColumnSet());
                                    exists = true;
                                }
                                catch
                                {
                                    // Do nothing
                                }

                                if (exists)
                                {
                                    service.Update(record);
                                    logger.LogInfo(
                                        $"Record {record.GetAttributeValue<string>(entityProgress.Metadata.PrimaryNameAttribute)} updated ({entityProgress.Entity}/{record.Id})");
                                }
                                else
                                {
                                    service.Create(record);
                                    logger.LogInfo(
                                        $"Record {record.GetAttributeValue<string>(entityProgress.Metadata.PrimaryNameAttribute)} created ({entityProgress.Entity}/{record.Id})");
                                }
                            }
                        }

                        records.RemoveAt(i);
                        entityProgress.Success++;
                        entityProgress.Processed++;
                    }
                    catch (Exception error)
                    {
                        logger.LogError($"{record.GetAttributeValue<string>(entityProgress.Metadata.PrimaryNameAttribute)} ({entityProgress.Entity}/{record.Id}): {error.Message}");
                        entityProgress.Error++;
                    }
                    finally
                    {
                        worker.ReportProgress(0, progress.Clone());
                    }
                }
            }

            worker.ReportProgress(0, "Updating records to add references...");

            var count = nextCycle.DistinctBy(r => r.Id).Count();
            var index = 0;

            foreach (var record in nextCycle.DistinctBy(r => r.Id))
            {
                try
                {
                    index++;

                    logger.LogInfo($"Upating record {record.LogicalName} ({record.Id})");

                    record.Attributes.Remove("ownerid");
                    service.Update(record);
                    var percentage = index * 100 / count;
                    worker.ReportProgress(percentage, true);
                }
                catch (Exception error)
                {
                    logger.LogInfo(error.Message);
                    var percentage = index * 100 / count;
                    worker.ReportProgress(percentage, false);
                }
            }

            if (recordsToDeactivate.Any())
            {
                count = recordsToDeactivate.Count;
                index = 0;

                worker.ReportProgress(0, "Deactivating records...");

                foreach (var er in recordsToDeactivate)
                {
                    try
                    {
                        index++;

                        logger.LogInfo($"Deactivating record {er.LogicalName} ({er.Id})");

                        var recordToUpdate = new Entity(er.LogicalName)
                        {
                            Id             = er.Id,
                            ["statecode"]  = new OptionSetValue(1),
                            ["statuscode"] = new OptionSetValue(-1)
                        };

                        service.Update(recordToUpdate);

                        var percentage = index * 100 / count;
                        worker.ReportProgress(percentage, true);
                    }
                    catch (Exception error)
                    {
                        logger.LogInfo(error.Message);
                        var percentage = index * 100 / count;
                        worker.ReportProgress(percentage, false);
                    }
                }
            }

            return(false);
        }
Example #27
0
		public IEnumerable<Constructor> RequestConstructors()
		{
			var ctors = new List<Constructor>();
			if (IsPartless) return ctors;
			var m = this.RequestType;
			foreach (var url in this.Url.Paths)
			{
				var cp = this.Url.Parts
					.Where(p => !ApiUrl.BlackListRouteValues.Contains(p.Key))
					.Where(p => url.Contains($"{{{p.Value.Name}}}"))
					.OrderBy(kv => url.IndexOf($"{{{kv.Value.Name}}}", StringComparison.Ordinal));
				var par = string.Join(", ", cp.Select(p => $"{ClrParamType(p.Value.ClrTypeName)} {p.Key}"));
				var routing = string.Empty;

				//Routes that take {indices}/{types} and both are optional
				//we rather not generate a parameterless constructor and force folks to call Indices.All
				if (!cp.Any() && IndicesAndTypes)
				{
					ParameterlessIndicesTypesConstructor(ctors, m);
					continue;
				}

				if (cp.Any())
				{
					routing = "r=>r." + string.Join(".", cp
						.Select(p => new
						{
							route = p.Key,
							call = p.Value.Required ? "Required" : "Optional",
							v = p.Key == "metric"
								? $"(Metrics){p.Key}"
								: p.Key == "index_metric"
									? $"(IndexMetrics){p.Key}"
									: p.Key
						})
						.Select(p => $"{p.call}(\"{p.route}\", {p.v})")
						);
				}

				var doc = $@"/// <summary>{url}</summary>";
				if (cp.Any())
				{
					doc += "\r\n" + string.Join("\t\t\r\n", cp.Select(p => $"///<param name=\"{p.Key}\">{(p.Value.Required ? "this parameter is required" : "Optional, accepts null")}</param>"));
				}
				var generated = $"public {m}({par}) : base({routing}){{}}";

				// special case SearchRequest<T> to pass the type of T as the type, when only the index is specified.
				if (m == "SearchRequest" && cp.Count() == 1 && !string.IsNullOrEmpty(this.RequestTypeGeneric))
				{
					var generic = this.RequestTypeGeneric.Replace("<", "").Replace(">", "");
					generated = $"public {m}({par}) : this({cp.First().Key}, typeof({generic})){{}}";
                }

				var c = new Constructor { Generated = generated, Description = doc };
				ctors.Add(c);
			}
			if (IsDocumentPath && !string.IsNullOrEmpty(this.RequestTypeGeneric))
			{
				var doc = $@"/// <summary>{this.Url.Path}</summary>";
				doc += "\r\n\t\t\r\n" + "///<param name=\"document\"> describes an elasticsearch document of type T, allows implicit conversion from numeric and string ids </param>";
				var documentRoute = "r=>r.Required(\"index\", index ?? document.Self.Index).Required(\"type\", type ?? document.Self.Type).Required(\"id\", id ?? document.Self.Id)";
				var documentPathGeneric = Regex.Replace(this.DescriptorTypeGeneric, @"^<?([^\s,>]+).*$", "$1");
				var documentFromPath = $"partial void DocumentFromPath({documentPathGeneric} document);";

				var constructor = $"DocumentPath<{documentPathGeneric}> document, IndexName index = null, TypeName type = null, Id id = null";

				var c = new Constructor { AdditionalCode = documentFromPath, Generated = $"public {m}({constructor}) : base({documentRoute}){{ this.DocumentFromPath(document.Document); }}", Description = doc, };
				ctors.Add(c);
			}
			return ctors.DistinctBy(c => c.Generated);
		}
        public IEnumerable <Constructor> DescriptorConstructors()
        {
            var ctors = new List <Constructor>();

            if (IsPartless)
            {
                return(ctors);
            }
            var m = this.DescriptorType;

            foreach (var url in this.Url.Paths)
            {
                var cp = this.Url.Parts
                         .Where(p => !ApiUrl.BlackListRouteValues.Contains(p.Key))
                         .Where(p => p.Value.Required)
                         .Where(p => url.Contains($"{{{p.Value.Name}}}"))
                         .OrderBy(kv => url.IndexOf($"{{{kv.Value.Name}}}", StringComparison.Ordinal));
                var par     = string.Join(", ", cp.Select(p => $"{ClrParamType(p.Value.ClrTypeName)} {p.Key}"));
                var routing = string.Empty;
                //Routes that take {indices}/{types} and both are optional
                if (!cp.Any() && IndicesAndTypes)
                {
                    AddParameterlessIndicesTypesConstructor(ctors, m);
                    continue;
                }
                if (cp.Any())
                {
                    routing = "r=>r." + string.Join(".", cp
                                                    .Select(p => new
                    {
                        route = p.Key,
                        call  = p.Value.Required ? "Required" : "Optional",
                        v     = p.Key == "metric"
                                                                ? $"(Metrics){p.Key}"
                                                                : p.Key == "index_metric"
                                                                        ? $"(IndexMetrics){p.Key}"
                                                                        : p.Key
                    })
                                                    .Select(p => $"{p.call}(\"{p.route}\", {p.v})")
                                                    );
                }
                var doc = $@"/// <summary>{url}</summary>";
                if (cp.Any())
                {
                    doc += "\r\n" + string.Join("\t\t\r\n", cp.Select(p => $"///<param name=\"{p.Key}\"> this parameter is required</param>"));
                }
                var c = new Constructor {
                    Generated = $"public {m}({par}) : base({routing}){{}}", Description = doc
                };
                ctors.Add(c);
            }
            if (IsDocumentPath && !string.IsNullOrEmpty(this.DescriptorTypeGeneric))
            {
                var doc = $@"/// <summary>{this.Url.Path}</summary>";
                doc += "\r\n\t\t\r\n" + "///<param name=\"document\"> describes an elasticsearch document of type T, allows implicit conversion from numeric and string ids </param>";
                var documentRoute       = "r=>r.Required(\"index\", document.Self.Index).Required(\"type\", document.Self.Type).Required(\"id\", document.Self.Id)";
                var documentPathGeneric = Regex.Replace(this.DescriptorTypeGeneric, @"^<?([^\s,>]+).*$", "$1");
                var documentFromPath    = $"partial void DocumentFromPath({documentPathGeneric} document);";
                var c = new Constructor {
                    AdditionalCode = documentFromPath, Generated = $"public {m}(DocumentPath<{documentPathGeneric}> document) : base({documentRoute}){{ this.DocumentFromPath(document.Document); }}", Description = doc
                };
                ctors.Add(c);
            }

            return(ctors.DistinctBy(c => c.Generated));
        }
Example #29
0
 private IEnumerable<MethodInfo> GetAvailableMethods(Type objectType)
 {
     var methods = new List<MethodInfo>();
     var type = objectType;
     while(type != null && type != typeof(object))
     {
         methods.AddRange(type.GetMethods(CurrentBindingFlags)
                          .Where(x => !(x.IsSpecialName
         && (x.Name.StartsWith("get_", StringComparison.Ordinal) || x.Name.StartsWith("set_", StringComparison.Ordinal)
         || x.Name.StartsWith("add_", StringComparison.Ordinal) || x.Name.StartsWith("remove_", StringComparison.Ordinal)))
         && !x.IsAbstract
         && !x.IsConstructor
         && !x.IsGenericMethod
         && x.IsCallable()
         )
         );
         type = type.BaseType;
     }
     return methods.DistinctBy(x=> x.ToString()); //This acutally gives us a full, easily comparable signature. Brilliant solution to avoid duplicates from overloaded methods.
 }
        private async Task <List <StantionQq> > GetStationsFromPlanedRouteByIdAndDay(int planedRouteTrainId, DateTime day,
                                                                                     int userId, int?inputStationId = 0)
        {
            var result              = new List <Stantion>();
            var sqlRStations        = new StantionsRepository(_logger);
            var sqlRPlanedStOnTrips = new PlanedStationOnTripsRepository(_logger);
            var sqlRTrip            = new TripsRepository(_logger);

            if (userId == 0)
            {
                throw new ValidationException(Error.NotFilledOptionalField);
            }

            PlaneStantionOnTrip inputSt = null;

            if (inputStationId != 0)
            {
                inputSt = await sqlRPlanedStOnTrips.ById(inputStationId.Value);
            }

            var currentDayPlaneBrigadeTrain = await sqlRPlanedStOnTrips.ByUserIdAndTimeRange(userId,
                                                                                             day.Date.AddHours(3), day.Date.AddDays(1).AddMilliseconds(-1));

            //busyPlanedSt = busyPlanedSt.Where(x => x.PlanedRouteTrainId != planedRouteTrainId).ToList();
            //var curPlanedRoute = await sqlPlanedBr.ByPlannedRouteTrainId(planedRouteTrainId);
            var currentPlanedRSt = await sqlRPlanedStOnTrips.ByPlannedRouteTrainId(planedRouteTrainId);

            currentPlanedRSt = currentPlanedRSt.OrderBy(x => x.OutTime).ToList();

            //var curPlanedRouteBr = await sqlPlanedBr.ByPlannedRouteTrainId(planedRouteTrainId);
            var usedPlaneSt = new List <PlaneStantionOnTrip>();

            if (currentPlanedRSt.Any())
            {
                foreach (var item in currentDayPlaneBrigadeTrain)
                {
                    //все станки маршрута, на который назначена данная запись
                    var planSts = (await sqlRPlanedStOnTrips.ByPlannedRouteTrainId(item.PlanedRouteTrainId))
                                  .OrderBy(x => x.OutTime).ToList();
                    var start = planSts.IndexOf(planSts.First(x => x.Id == item.StantionStartId)) + 1;
                    var end   = planSts.IndexOf(planSts.First(x => x.Id == item.StantionEndId)) + 1;
                    usedPlaneSt.AddRange(planSts.GetRange(start, end - start));
                }
            }

            usedPlaneSt = usedPlaneSt.DistinctBy(x => x.Id).ToList();
            DateTime?minUsedTime = null;
            DateTime?maxUsedTime = null;

            if (usedPlaneSt.Count > 1)
            {
                minUsedTime = usedPlaneSt.First().OutTime;
                maxUsedTime = usedPlaneSt.Last().InTime;
            }
            if (usedPlaneSt.Count == 1)
            {
                minUsedTime = usedPlaneSt.First().OutTime;
                maxUsedTime = usedPlaneSt.First().InTime;
            }

            if (minUsedTime != null && maxUsedTime != null)
            {
                if (inputSt != null)
                {
                    if (inputSt.OutTime <= minUsedTime)
                    {
                        maxUsedTime = ((DateTime)maxUsedTime).AddDays(1);
                    }
                    if (inputSt.OutTime >= maxUsedTime)
                    {
                        minUsedTime = ((DateTime)minUsedTime).AddDays(-1);
                    }
                }
            }

            var res1 = new List <StantionQq>();

            var currentTripId = 0;

            for (var index = 0; index < currentPlanedRSt.Count; index++)
            {
                var item = currentPlanedRSt[index];
                var trip = await sqlRTrip.ById(item.TripId);


                if (minUsedTime != null && maxUsedTime != null)
                {
                    if (item.InTime >= minUsedTime && item.InTime <= maxUsedTime)
                    {
                        continue;
                    }
                    if (item.OutTime >= minUsedTime && item.OutTime <= maxUsedTime)
                    {
                        continue;
                    }
                }

                //foreach (var x in usedPlaneSt)
                //{
                //    if (item.InTime >= x.InTime && item.InTime <= x.OutTime)
                //        isUsed = true;
                //    if (item.OutTime >= x.InTime && item.OutTime <= x.OutTime)
                //        isUsed = true;
                //}
                //if (isUsed)
                //    continue;
                var station = await sqlRStations.ById(item.StantionId);

                station.Id = item.Id;
                //station.Name += $" ({item.InTime.ToStringTimeOnly()})";
                var sqq = _mapper.Map <Stantion, StantionQq>(station);
                sqq.InTime   = item.InTime;
                sqq.TripName = trip.Name;

                var qqStart = item.InTime.ToStringTimeOnly();
                var qqEnd   = item.OutTime.ToStringTimeOnly();
                if (currentTripId == 0 || item.TripId != currentTripId)
                {
                    qqStart = "н/д";
                }
                if (index != currentPlanedRSt.Count - 1)
                {
                    if (currentPlanedRSt[index + 1].TripId != item.TripId && currentTripId != 0)
                    {
                        qqEnd = "н/д";
                    }
                }
                else
                {
                    qqEnd = "н/д";
                }

                var qq1 = $"{station.Name} {qqStart}-{qqEnd} ({trip.Name})";
                sqq.Name += $" ({qq1})";
                res1.Add(sqq);
                currentTripId = item.TripId;
                //result.Add(station);
            }

            return(res1);
        }
 public ActionResult SearchNamesObjects(string q)
 {
     List<MemberJson> namesFound = new List<MemberJson>();
     var members = MemberCache.GetCurrentLeagueMembers(RDN.Library.Classes.Account.User.GetMemberId());
     var searchLeague = (from xx in members
                         where (xx.DerbyName != null && xx.DerbyName.ToLower().Contains(q))
                         || (xx.Firstname != null && xx.Firstname.ToLower().Contains(q))
                         || (xx.LastName != null && xx.LastName.ToLower().Contains(q))
                         select new MemberJson
                                {
                                    name = xx.DerbyName + " [" + (xx.Firstname + " " + xx.LastName).Trim() + "]",
                                    id = xx.MemberId
                                }).Take(10).ToList();
     namesFound.AddRange(searchLeague);
     namesFound.AddRange(RDN.Library.Classes.Account.User.SearchDerbyNamesJson(q, 10));
     namesFound = namesFound.DistinctBy(x => x.id).Take(10).ToList();
     return Json(namesFound, JsonRequestBehavior.AllowGet);
 }
Example #32
0
        public async Task <MethodResult <List <PokemonData> > > GetPokemonToTransfer()
        {
            if (!UserSettings.TransferPokemon)
            {
                LogCaller(new LoggerEventArgs("Transferring disabled", LoggerTypes.Debug));

                return(new MethodResult <List <PokemonData> >
                {
                    Data = new List <PokemonData>(),
                    Message = "Transferring disabled",
                    Success = true
                });
            }

            await UpdatePokemon(false);
            await UpdatePokemonCandy(false);
            await GetItemTemplates();

            if (Pokemon == null || Pokemon.Count == 0)
            {
                LogCaller(new LoggerEventArgs("You have no pokemon", LoggerTypes.Info));

                return(new MethodResult <List <PokemonData> >
                {
                    Message = "You have no pokemon"
                });
            }

            List <PokemonData> pokemonToTransfer = new List <PokemonData>();

            IEnumerable <IGrouping <PokemonId, PokemonData> > groupedPokemon = Pokemon.GroupBy(x => x.PokemonId);

            foreach (IGrouping <PokemonId, PokemonData> group in groupedPokemon)
            {
                TransferSetting settings = UserSettings.TransferSettings.FirstOrDefault(x => x.Id == group.Key);

                if (settings == null)
                {
                    LogCaller(new LoggerEventArgs(String.Format("Failed to find transfer settings for pokemon {0}", group.Key), LoggerTypes.Warning));

                    continue;
                }

                if (!settings.Transfer)
                {
                    continue;
                }

                switch (settings.Type)
                {
                case TransferType.All:
                    pokemonToTransfer.AddRange(group.ToList());
                    break;

                case TransferType.BelowCP:
                    pokemonToTransfer.AddRange(GetPokemonBelowCP(group, settings.MinCP));
                    break;

                case TransferType.BelowIVPercentage:
                    pokemonToTransfer.AddRange(GetPokemonBelowIVPercent(group, settings.IVPercent));
                    break;

                case TransferType.KeepPossibleEvolves:
                    pokemonToTransfer.AddRange(GetPokemonByPossibleEvolve(group, settings.KeepMax));
                    break;

                case TransferType.KeepStrongestX:
                    pokemonToTransfer.AddRange(GetPokemonByStrongest(group, settings.KeepMax));
                    break;

                case TransferType.KeepXHighestIV:
                    pokemonToTransfer.AddRange(GetPokemonByIV(group, settings.KeepMax));
                    break;

                case TransferType.BelowCPAndIVAmount:
                    pokemonToTransfer.AddRange(GetPokemonBelowCPIVAmount(group, settings.MinCP, settings.IVPercent));
                    break;

                case TransferType.BelowCPOrIVAmount:
                    pokemonToTransfer.AddRange(GetPokemonBelowIVPercent(group, settings.IVPercent));
                    pokemonToTransfer.AddRange(GetPokemonBelowCP(group, settings.MinCP));
                    pokemonToTransfer = pokemonToTransfer.DistinctBy(x => x.Id).ToList();
                    break;
                }
            }

            return(new MethodResult <List <PokemonData> >
            {
                Data = pokemonToTransfer,
                Message = String.Format("Found {0} pokemon to transfer", pokemonToTransfer.Count),
                Success = true
            });
        }
Example #33
0
        public async Task <ShopifySharp.Product> CreateProduct(ImportService.Wrapper.Product product, string vendor, string myShopifyDomain, string accessToken, ImportService.Wrapper.ColorList colorMapping)
        {
            ShopifySharp.ProductService service = new ShopifySharp.ProductService(myShopifyDomain, accessToken);

            var newProduct = new ShopifySharp.Product()
            {
                Vendor = vendor,
            };

            newProduct.Options = new List <ProductOption> {
                new ProductOption {
                    Name = "Color"
                }, new ProductOption {
                    Name = "Size"
                }
            };
            string productTitle  = product.Name;
            string productHandle = product.Name;
            var    colorList     = product.ProductVariants.ProductVariant.Select(x => new { colorName = x.ColorName, colorCode = x.ColorCode }).ToList();
            var    distColorList = colorList.Distinct().Select(x => x).ToList();

            string colorName = colorList.Distinct().FirstOrDefault().colorName;

            if (!string.IsNullOrEmpty(colorName))
            {
                colorName = CheckColorMapping(colorMapping, colorName);

                productHandle += "-" + colorName;
                productTitle  += " " + colorName;
            }
            newProduct.Handle = productHandle.ToLower();
            newProduct.Title  = productTitle.ToUpper();
            var productTags = new List <string>();

            foreach (var c in distColorList)
            {
                string _color = CheckColorMapping(colorMapping, c.colorName);
                productTags.Add(product.Name.ToLower() + "-" + _color.ToLower());
            }
            // product variant list created from ftp xml.
            var _pvList      = new List <ShopifySharp.ProductVariant>();
            var priceTagList = new List <string>();

            foreach (var pv in product.ProductVariants.ProductVariant)
            {
                var    _pv           = new ShopifySharp.ProductVariant();
                string variant_color = CheckColorMapping(colorMapping, pv.ColorName);
                _pv.SKU               = product.Name.Replace(" ", "-").ToUpper();
                _pv.Option1           = variant_color;
                _pv.Option2           = pv.SizeName;
                _pv.Option3           = pv.ColorCode;
                _pv.TaxCode           = "PC040144";
                _pv.Title             = $@"{pv.ColorName.ToUpper()} /\ {pv.SizeName} /\ {variant_color}";
                _pv.Price             = Convert.ToDecimal(pv.ProductVariantSources.ProductVariantSource.Price);
                _pv.InventoryQuantity = Convert.ToInt32(pv.Quantity);
                _pvList.Add(_pv);
                if (_pv.Price < 25)
                {
                    priceTagList.Add("PRICE_under_$25");
                }
                else if (_pv.Price >= 25 && _pv.Price <= 50)
                {
                    priceTagList.Add("PRICE_$25-$50");
                }
                else if (_pv.Price >= 50 && _pv.Price <= 100)
                {
                    priceTagList.Add("PRICE_$50-$100");
                }
                else if (_pv.Price >= 100 && _pv.Price <= 150)
                {
                    priceTagList.Add("PRICE_$100-$150");
                }
            }
            var productVariants = _pvList.DistinctBy(x => x.Title).Select(x => x).ToList();


            var exist = await GetProductByHandle(newProduct.Handle, service);

            if (exist.Count() > 0)
            {
                foreach (var p in exist)
                {
                    var existingPV = p.Variants;
                    var result     = from x in productVariants
                                     join y in existingPV
                                     on new { X1 = x.Option1, X2 = x.Option2 } equals new { X1 = y.Option1, X2 = y.Option2 } select x;
                    var newVariants = productVariants.Where(p1 => !result.Any(p2 => p2.Option1 == p1.Option1 && p2.Option2 == p1.Option2));
                    if (newVariants != null)
                    {
                        ShopifySharp.ProductVariantService pvs = new ProductVariantService(myShopifyDomain, accessToken);

                        foreach (var nvp in newVariants)
                        {
                            var variant = await pvs.CreateAsync(p.Id ?? 0, nvp);
                        }
                    }
                }
            }
            else
            {
                newProduct.Variants = productVariants;
                foreach (var p in priceTagList.Distinct().Select(x => x).ToList())
                {
                    productTags.Add(p.ToLower());
                }
                newProduct.Tags = string.Join(",", productTags.ToArray());

                var createdDate = product.Attributes.Attribute.Where(x => x.ProductAttributeCode == "createddate").Select(x => x.ProductAttributeValue).FirstOrDefault();
                if (createdDate != null)
                {
                    newProduct.CreatedAt = Convert.ToDateTime(createdDate);
                }



                try
                {
                    newProduct = await service.CreateAsync(newProduct);
                }
                catch (Exception ex)
                {
                    string exception = ex.Message;
                    if (ex.InnerException != null)
                    {
                        exception = ex.InnerException.Message;
                    }
                    Log.Error("Error in CreateProduct method in class ProductService.cs", ex, vendor);
                }
            }
            return(newProduct);
        }
Example #34
0
        public async Task ImportExcel(List <BPFCEstablishDtoForImportExcel> bPFCEstablishDtos)
        {
            try
            {
                var list         = new List <BPFCEstablishDto>();
                var listChuaAdd  = new List <BPFCEstablishDto>();
                var listAddBiLoi = new List <BPFCEstablishDto>();
                var result       = bPFCEstablishDtos.DistinctBy(x => new
                {
                    x.ModelName,
                    x.ModelNo,
                    x.ArticleNo,
                    x.Process
                }).ToList();

                foreach (var item in result)
                {
                    var bpfc = await AddBPFC(item);

                    list.Add(bpfc);
                }

                var listAdd = new List <BPFCEstablish>();
                foreach (var bpfc in list)
                {
                    if (!await CheckExistBPFC(bpfc))
                    {
                        var bp = new BPFCEstablish();
                        bp.ModelNameID    = bpfc.ModelNameID;
                        bp.ModelNoID      = bpfc.ModelNoID;
                        bp.ArticleNoID    = bpfc.ArticleNoID;
                        bp.ArtProcessID   = bpfc.ArtProcessID;
                        bp.CreatedBy      = bpfc.CreatedBy;
                        bp.ApprovalBy     = bpfc.ApprovalBy;
                        bp.CreatedDate    = DateTime.Now;
                        bp.UpdateTime     = DateTime.Now;
                        bp.ApprovalStatus = bpfc.ApprovalStatus;
                        bp.FinishedStatus = bpfc.FinishedStatus;
                        bp.Season         = bpfc.Season;
                        bp.ModelName      = null;
                        bp.ModelNo        = null;
                        bp.ArticleNo      = null;
                        bp.ArtProcess     = null;
                        bp.Glues          = null;
                        bp.Plans          = null;
                        _repoBPFCEstablish.Add(bp);
                        await _repoBPFCEstablish.SaveAll();

                        listAdd.Add(bp);
                    }
                    else
                    {
                        listChuaAdd.Add(bpfc);
                    }
                }
                var result1 = listAdd.Where(x => x.ID > 0).ToList();
                var result2 = listAdd.Where(x => x.ID == 0).ToList();
            }
            catch
            {
                throw;
            }
        }
Example #35
0
 private IEnumerable<KeyValuePair<XElement, string>> GetDependencies(IEnumerable<KeyValuePair<string, IEnumerable<XElement>>> references, bool isLibSpec)
 {
     var elements = new List<KeyValuePair<XElement, string>>();
     foreach (var reference in references){
         var path = Path.Combine(Path.GetDirectoryName(reference.Key)+"", "packages.config");
         foreach (var element in reference.Value){
             var assemblyName = GetAssemblyName(element).ToLowerInvariant();
             var version = _version;
             if(!assemblyName.StartsWith("xpand")) {
                 var packageId = GetPackageId(element)??assemblyName;
                 var packagesConfig = (File.Exists(path) ? File.ReadAllText(path) : "").ToLowerInvariant();
                 var regex = new Regex("<package id=\"" + packageId + "\" .*version=\"([^\"]*)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Multiline);
                 var match = regex.Match(packagesConfig);
                 if (match.Success){
                     version = match.Groups[1].Value;
                 }
                 else{
                     continue;
                 }
             }
             if (isLibSpec && GetLibHashSet().Any(s => assemblyName.ToLowerInvariant().Contains(s)))
                 continue;
             elements.Add(new KeyValuePair<XElement, string>(element, version));
         }
     }
     return elements.DistinctBy(pair => pair.Key.Attribute("Include").Value);
 }
Example #36
0
        public void CreateCrossEpisodes(string localFileName)
        {
            if (episodesRAW == null)
            {
                return;
            }
            List <CrossRef_File_Episode> fileEps = RepoFactory.CrossRef_File_Episode.GetByHash(Hash);

            // Use a single session A. for efficiency and B. to prevent regenerating stats
            using (var session = DatabaseFactory.SessionFactory.OpenSession())
            {
                using (var trans = session.BeginTransaction())
                {
                    RepoFactory.CrossRef_File_Episode.DeleteWithOpenTransaction(session, fileEps);
                    trans.Commit();
                }

                fileEps = new List <CrossRef_File_Episode>();

                char apostrophe = "'".ToCharArray()[0];
                char epiSplit   = ',';
                if (episodesRAW.Contains(apostrophe))
                {
                    epiSplit = apostrophe;
                }

                char eppSplit = ',';
                if (episodesPercentRAW.Contains(apostrophe))
                {
                    eppSplit = apostrophe;
                }

                string[] epi = episodesRAW.Split(epiSplit);
                string[] epp = episodesPercentRAW.Split(eppSplit);
                for (int x = 0; x < epi.Length; x++)
                {
                    string epis = epi[x].Trim();
                    string epps = epp[x].Trim();
                    if (epis.Length <= 0)
                    {
                        continue;
                    }
                    if (!int.TryParse(epis, out int epid))
                    {
                        continue;
                    }
                    if (!int.TryParse(epps, out int eppp))
                    {
                        continue;
                    }
                    if (epid == 0)
                    {
                        continue;
                    }
                    CrossRef_File_Episode cross = new CrossRef_File_Episode
                    {
                        Hash           = Hash,
                        CrossRefSource = (int)CrossRefSource.AniDB,
                        AnimeID        = AnimeID,
                        EpisodeID      = epid,
                        Percentage     = eppp,
                        EpisodeOrder   = x + 1,
                        FileName       = localFileName,
                        FileSize       = FileSize
                    };
                    fileEps.Add(cross);
                }

                // There is a chance that AniDB returned a dup, however unlikely
                using (var trans = session.BeginTransaction())
                {
                    RepoFactory.CrossRef_File_Episode.SaveWithOpenTransaction(session,
                                                                              fileEps.DistinctBy(a => $"{a.Hash}-{a.EpisodeID}").ToList());
                    trans.Commit();
                }
            }
        }
        public IEnumerable <Constructor> RequestConstructors()
        {
            var ctors = new List <Constructor>();

            if (IsPartless)
            {
                return(ctors);
            }

            // Do not generate ctors for scroll apis
            // Scroll ids should always be passed as part of the request body and enforced via manual ctors
            if (IsScroll)
            {
                return(ctors);
            }

            var m = this.RequestType;

            foreach (var url in this.Url.Paths)
            {
                var urlRouteParameters = this.Url.Parts
                                         .Where(p => !ApiUrl.BlackListRouteValues.Contains(p.Key))
                                         .Where(p => url.Contains($"{{{p.Value.Name}}}"))
                                         .OrderBy(kv => url.IndexOf($"{{{kv.Value.Name}}}", StringComparison.Ordinal));

                var par     = string.Join(", ", urlRouteParameters.Select(p => $"{ClrParamType(p.Value.ClrTypeName)} {p.Key}"));
                var routing = string.Empty;

                //Routes that take {indices}/{types} and both are optional
                //we rather not generate a parameterless constructor and force folks to call Indices.All
                if (!urlRouteParameters.Any() && IndicesAndTypes)
                {
                    ParameterlessIndicesTypesConstructor(ctors, m);
                    continue;
                }

                if (urlRouteParameters.Any())
                {
                    routing = "r=>r." + string.Join(".", urlRouteParameters
                                                    .Select(p => new
                    {
                        route = p.Key,
                        call  = p.Value.Required ? "Required" : "Optional",
                        v     = p.Key == "metric" || p.Key == "watcher_stats_metric"
                                                                ? $"(Metrics){p.Key}"
                                                                : p.Key == "index_metric"
                                                                        ? $"(IndexMetrics){p.Key}"
                                                                        : p.Key
                    })
                                                    .Select(p => $"{p.call}(\"{p.route}\", {p.v})")
                                                    );
                }

                var doc = $@"///<summary>{url}</summary>";
                if (urlRouteParameters.Any())
                {
                    doc += "\r\n\t\t" + string.Join("\r\n\t\t", urlRouteParameters.Select(p => $"///<param name=\"{p.Key}\">{(p.Value.Required ? "this parameter is required" : "Optional, accepts null")}</param>"));
                }
                var generated = $"public {m}({par}) : base({routing})";

                // special case SearchRequest<T> to pass the type of T as the type, when only the index is specified.
                if ((m == "SearchRequest") && urlRouteParameters.Count() == 1 && !string.IsNullOrEmpty(this.RequestTypeGeneric))
                {
                    var generic = this.RequestTypeGeneric.Replace("<", "").Replace(">", "");
                    generated = $"public {m}({par}) : this({urlRouteParameters.First().Key}, typeof({generic}))";
                }

                if (string.IsNullOrEmpty(par) && !string.IsNullOrEmpty(this.RequestTypeGeneric))
                {
                    var generic = this.RequestTypeGeneric.Replace("<", "").Replace(">", "");
                    doc       = AppendToSummary(doc, ". Will infer the index from the generic type");
                    generated = $"public {m}({par}) : this(typeof({generic}))";
                }

                var c = new Constructor
                {
                    Generated   = generated,
                    Description = doc,
                    Body        = this.IsDocumentRequest ? $" => Q(\"routing\", new Routing(() => AutoRouteDocument()));" : string.Empty
                };

                ctors.Add(c);
            }
            if (IsDocumentPath && !string.IsNullOrEmpty(this.RequestTypeGeneric))
            {
                var documentPathGeneric = Regex.Replace(this.DescriptorTypeGeneric, @"^<?([^\s,>]+).*$", "$1");
                var doc = $"/// <summary>{this.Url.Path}</summary>";
                doc += "\r\n\t\t" + $"///<param name=\"document\"> describes an elasticsearch document of type <typeparamref name=\"{documentPathGeneric}\"/> from which the index, type and id can be inferred</param>";
                var documentRoute    = "r=>r.Required(\"index\", index ?? document.Self.Index).Required(\"type\", type ?? document.Self.Type).Required(\"id\", id ?? document.Self.Id)";
                var documentFromPath = $"partial void DocumentFromPath({documentPathGeneric} document);";

                var constructor = $"DocumentPath<{documentPathGeneric}> document, IndexName index = null, TypeName type = null, Id id = null";

                var autoRoute = this.IsDocumentRequest ? "Q(\"routing\", new Routing(() => AutoRouteDocument() ?? document.Document));" : string.Empty;
                var body      = $"{{ this.DocumentFromPath(document.Document); {autoRoute} }}";

                var c = new Constructor
                {
                    AdditionalCode = documentFromPath,
                    Generated      = $"public {m}({constructor}) : base({documentRoute})",
                    Body           = body,
                    Description    = doc,
                };
                ctors.Add(c);
            }
            return(ctors.DistinctBy(c => c.Generated));
        }
Example #38
0
        public ActionResult settingGroup(int id)
        {
            ViewBag.message = "";
            UnitOfWork u        = new UnitOfWork();
            var        allowLog = u.Setting.GetRecord(1).ActiveLog;
            var        user     = User.Identity.Name.GetFullUser();

            if (User.Identity.IsAuthenticated)
            {
                if (!User.IsInRole("settingGroups"))
                {
                    if (user != null)
                    {
                        if (allowLog)
                        {
                            Logs log = new Logs()
                            {
                                UserId      = user.ID,
                                LogDate     = DateTime.Now,
                                Description = "درخواست مشاهده تنظیمات گروه بدون داشتن دسترسی لازم"
                            };
                            u.Log.Insert(log);
                            u.Log.Save();
                        }
                        ViewBag.message = "کاربر گرامی شما دسترسی لازم جهت انجام این عملیات را ندارید";
                    }
                    else
                    {
                        ViewBag.message = "کاربر گرامی اطلاعات ارسالی معتبر نمی باشد";
                    }
                }
                else
                {
                    if (user != null)
                    {
                        var group = u.Group.GetRecord(id);
                        if (group != null)
                        {
                            ViewBag.group = u.ContactInGroup.Get(p => p.Remove == false && p.GroupId == group.ID).ToList();
                            var             userOrganization = u.UserInOrganization.Get(p => p.Remove == false && p.UserId == user.ID && p.Users.Remove == false && p.Organization.Remove == false).ToList();
                            var             tempContact      = u.ContactInOrganization.Get(p => p.Remove == false && p.Contacts.Remove == false && p.Organization.Remove == false).ToList();
                            List <Contacts> contacts         = u.Contact.Get(p => p.Remove == false && p.PublicContact == true).ToList();
                            foreach (var item in tempContact)
                            {
                                foreach (var str in userOrganization)
                                {
                                    if (item.OrganizationId == str.OrganizationId)
                                    {
                                        contacts.Add(item.Contacts);
                                    }
                                }
                            }

                            ViewBag.contact = contacts.DistinctBy(p => p.ID).ToList();
                            return(PartialView(group));
                        }
                        else
                        {
                            ViewBag.message = "کاربر گرامی اطلاعات ارسالی معتبر نمی باشد";
                        }
                    }
                    else
                    {
                        ViewBag.message = "کاربر گرامی اطلاعات ارسالی معتبر نمی باشد";
                    }
                }
            }
            else
            {
                ViewBag.message = "کاربر گرامی سشن شما به پایان رسید لطفا مجددا لاگین فرمایید";
            }
            return(PartialView(null));
        }
Example #39
0
 public void DistinctByTest_IEnumerable()
 {
     List<int> source = new List<int> { 1, 2, 3, 3, 4, 4, 5, 6, 7, 7 };
     List<int> actual = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
     Assert.Equal(source.DistinctBy(m => m).ToList(), actual);
 }
Example #40
0
        //public object Get(Details details)
        //{
        //    Models.Recording recording = _recordingRepository.GetById(details.Id);
        //    if (recording.Restricted && !UserSession.IsAuthenticated)
        //        return HttpResult.Redirect("/Login".AddQueryParam("redirect", Request.AbsoluteUri));

        //    return new DetailsResponse {Recording = recording};
        //}

        //public object Get(Delete delete)
        //{
        //    Models.Recording recording = _recordingRepository.GetById(delete.Id);
        //    if (recording.Restricted && !UserSession.IsAuthenticated) return HttpResult.Redirect("/Login".AddQueryParam("redirect", Request.AbsoluteUri));


        //    return new DeleteResponse {Recording = recording};
        //}

        //[Authenticate]
        //[RequiredRole(RoleNames.Admin)]
        //public object Post(Delete delete)
        //{
        //    _recordingRepository.Delete(delete.Id);

        //    return this.Redirect("/Recording");
        //}

        public object Get(SpeakerDetails speaker)
        {
            if (speaker.EscapedFragment == null && !Request.RawUrl.IsNormalizedUrl())
            {
                return(this.RedirectPermanently(Request.RawUrl.ToNormalizedUrl()));
            }

            if (speaker.EscapedFragment != null && speaker.EscapedFragment.StartsWith("/"))
            {
                speaker.Album = speaker.EscapedFragment.Substring(1);
            }

            var includeRestricted = UserSession.IsAuthenticated;

            NameInfo nameInfo = speaker.Name.ToNameInfo();

            using (IDbConnection db = _dbConnectionFactory.Open())
            {
                DbSpeaker dbSpeaker = db.Single <DbSpeaker>(s => s.FirstName == nameInfo.FirstName && s.LastName == nameInfo.LastName && !s.Deleted);
                if (dbSpeaker == null)
                {
                    throw HttpError.NotFound("Speaker not found");
                }

                SqlExpression <DbRecording> albumIdQuery =
                    db.From <DbRecording>()
                    .Join <DbRecordingSpeaker>((recording, recordingSpeaker) => recording.Id == recordingSpeaker.RecordingId)
                    .Where <DbRecording, DbRecordingSpeaker>((recording, recordingSpeaker) => !recording.Deleted && recordingSpeaker.SpeakerId == dbSpeaker.Id)
                    .SelectDistinct(rs => rs.AlbumId);

                SqlExpression <DbSpeaker> query = db.From <DbSpeaker>()
                                                  .Join <DbRecordingSpeaker>((sp, recordingSpeaker) => sp.Id == recordingSpeaker.SpeakerId)
                                                  .Join <DbRecordingSpeaker, DbRecording>((recordingSpeaker, recording) => recordingSpeaker.RecordingId == recording.Id)
                                                  .Join <DbRecording, DbAlbum>((recording, album) => recording.AlbumId == album.Id)
                                                  .Where <DbSpeaker, DbAlbum>((sp, album) => !sp.Deleted && !album.Deleted && Sql.In(album.Id, albumIdQuery))
                                                  .OrderBy <DbAlbum>(a => a.Name)
                                                  .ThenBy <DbRecording>(r => r.Track);

                if (!includeRestricted)
                {
                    query.And <DbAlbum>(a => !a.Restricted);
                }

                List <Tuple <DbSpeaker, DbRecordingSpeaker, DbRecording, DbAlbum> > recordings = db.SelectMulti <DbSpeaker, DbRecordingSpeaker, DbRecording, DbAlbum>(query);

                Dictionary <long, DbAlbum> albums = recordings.DistinctBy(r => r.Item4.Id).Select(r => r.Item4).ToDictionary(a => a.Id);

                ILookup <long, Tuple <DbSpeaker, DbRecordingSpeaker, DbRecording, DbAlbum> > albumLookup = recordings.ToLookup(r => r.Item4.Id);
                ILookup <long, Tuple <DbSpeaker, DbRecordingSpeaker, DbRecording, DbAlbum> > speakers    = recordings.ToLookup(r => r.Item3.Id);

                List <AlbumInfo> albumInfos =
                    (from g in albumLookup
                     let album = albums[g.Key]
                                 select new AlbumInfo
                {
                    Uid = album.Uid,
                    Name = album.Name,
                    Description = album.Description,
                    AlbumSpeakers = GetSpeakers(g),
                    HasAlbumArt = album.AlbumArtPath != null,
                    Recordings = g.DistinctBy(r => r.Item3.Id)
                                 .OrderBy(r => r.Item3.Track)
                                 .Select(r => new RecordingInfo
                    {
                        Uid = r.Item3.Uid,
                        Title = r.Item3.Title,
                        Track = r.Item3.Track,
                        Year = r.Item3.Year,
                        Comment = r.Item3.Comment,
                        Speakers = speakers[r.Item3.Id]
                                   .DistinctBy(rs => rs.Item1.Id)
                                   .Select(rs => rs.Item1.ToSpeakerInfo())
                                   .ToList()
                    }).ToList(),
                    Attachments = album.AttachmentPaths
                                  .Select((attachment, index) => new AttachmentInfo
                    {
                        Name =
                            _fileSystem.Path.GetFileName(attachment),
                        Index = index
                    }).ToList()
                }).ToList();

                return(new SpeakerDetailsResponse
                {
                    Uid = dbSpeaker.Uid,
                    Speaker = speaker.Name,
                    Albums = albumInfos.ToList(),
                    Speakers = _recordingRepository.GetSpeakers(includeRestricted).Select(s => s.ToSpeakerInfo(sp => sp.FullName == speaker.Name)).ToList(),
                    SelectedAlbum = albumInfos.FirstOrDefault(a => a.Name == (speaker.Album ?? speaker.EscapedFragment)),
                    HasPhoto = dbSpeaker.PhotoPath != null,
                    Description = dbSpeaker.Description
                });
            }
        }
        public IQueryable<FamilySearchResult> GetFamiliesByPersonNameSearch( string searchString, int maxResults = 20 )
        {
            bool reversed;

            RockContext rockContext = new RockContext();
            PersonService personService = new PersonService( rockContext );
            Guid homeAddressGuid = Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid();

            // get list of people matching the search string
            IOrderedQueryable<Person> sortedPersonQry = personService
                .GetByFullNameOrdered( searchString, true, false, false, out reversed );

            var personResults = sortedPersonQry.AsNoTracking().ToList();

            List<FamilySearchResult> familyResults = new List<FamilySearchResult>();
            foreach ( var person in personResults )
            {
                var families = personService.GetFamilies( person.Id )
                                    .Select( f => new FamilySearchResult
                                                        {
                                                            Id = f.Id,
                                                            Name = f.Name,
                                                            FamilyMembers = f.Members.ToList(),
                                                            HomeLocation = f.GroupLocations
                                                                            .Where( l => l.GroupLocationTypeValue.Guid == homeAddressGuid )
                                                                            .OrderByDescending( l => l.IsMailingLocation )
                                                                            .Select( l => l.Location )
                                                                            .FirstOrDefault(),
                                                            MainPhone = f.Members
                                                                            .OrderBy( m => m.GroupRole.Order )
                                                                            .ThenBy( m => m.Person.Gender )
                                                                            .FirstOrDefault()
                                                                            .Person.PhoneNumbers.OrderBy( p => p.NumberTypeValue.Order ).FirstOrDefault()
                                                        } )
                                                        .ToList();

                foreach ( var family in families )
                {
                    familyResults.Add( family );
                }
            }

            return familyResults.DistinctBy( f => f.Id ).AsQueryable();
        }
        public Application GetPreviousLiveApplication(string applicationReference)
        {
            var application = _applicationsContext.Applications.Active()
                .Include(a => a.Customers.Select(t => t.TelephoneNumbers))
                .Include(a => a.Customers.Select(e => e.Emails))
                .FirstOrDefault(a => a.ApplicationReference == applicationReference);

            if (application.IsNull())
                return null;

            var applications = new List<Application>();

            foreach (var contactDetail in application.Usernames())
            {
                applications.AddRange(GetApplicationsByUsername(contactDetail));
            }

            if (applications.DistinctBy(a => a.ApplicationReference).Count(x => x.Status == Status.Live) > 1)
                throw new Exception("There is more than one LIVE agreement for this customer.");

            return applications.DistinctBy(a => a.ApplicationReference).FirstOrDefault(a => a.TenancyIsEnding());
        }
Example #43
0
        void GenerateReleaseBundles(List<BundleItFile> BundleResolvedFiles, eBundleType type)
        {
            var RootFolder = System.AppDomain.CurrentDomain.BaseDirectory;
            var unique_resolved_bundles = BundleResolvedFiles.DistinctBy(b => b.resolved_bundle_name);

            foreach (var rbundle in unique_resolved_bundles)
            {
                if (rbundle.IsCDN)
                    continue;

                var compressed_bundle = new StringBuilder();
                var bfiles = BundleResolvedFiles.Where(bsf => bsf.resolved_bundle_name == rbundle.resolved_bundle_name);
                foreach (var f in bfiles)
                {
                    // if has_minified returns true, then find which path to use.
                    var path = string.Empty;
                    if (f.has_minified)
                        path = string.IsNullOrEmpty(f.minifiedrelativepath) ? f.debugrelativepath : f.minifiedrelativepath;
                    else
                        path = f.debugrelativepath;


                    // check for leading '/'
                    if (path[0] == "/".ToCharArray()[0])
                        path = path.Substring(1);


                    var filesource = LoadFile(Path.Combine(RootFolder, path));

                    // run it through YUI if not already minified
                    string compressed_src = string.Empty;
                    if (f.has_minified)
                        compressed_src = filesource;
                    else
                    {
                        if (type == eBundleType.script)
                        {
                            var YuiJsSettings = f.YuiJsSettings == null ? ConfigSettings.Instance.GlobalYuiCompressionSettings.Javascript : f.YuiJsSettings;
                            compressed_src = YUI_JS(filesource, YuiJsSettings);
                        }
                        if (type == eBundleType.style)
                        {
                            var YuiCssSettings = f.YuiCssSettings == null ? ConfigSettings.Instance.GlobalYuiCompressionSettings.Css : f.YuiCssSettings;
                            compressed_src = YUI_CSS(filesource, YuiCssSettings);
                        }
                    }

                    compressed_bundle.Append(compressed_src);
                }

                if (type == eBundleType.script)
                    _script_compressed_bundles.Add(rbundle.resolved_bundle_name, new BundleAsset(compressed_bundle.ToString()));

                if (type == eBundleType.style)
                    _style_compressed_bundles.Add(rbundle.resolved_bundle_name, new BundleAsset(compressed_bundle.ToString()));
            }
        }
Example #44
0
        public SubjectsFinalResults(List<SubjectFinalResult> items)
        {
            items = items.DistinctBy(x => x.GUID).ToList();

            All = items;
            _helperData = new SubjectHelperData();
        }
Example #45
0
        public async Task ImportExcel(List <ScheduleDtoForImportExcel> scheduleDto)
        {
            try
            {
                var list      = new List <ScheduleUpdateDto>();
                var listExist = new List <object>();
                var result    = scheduleDto.DistinctBy(x => new
                {
                    x.ModelName,
                    x.ModelNo,
                    x.ArticleNo,
                    x.Process,
                    x.Object,
                    x.Part,
                    x.ProductionDate
                }).Where(x => x.ModelName != "").ToList();

                foreach (var item in result)
                {
                    var Schedule = await AddSchedule(item);

                    list.Add(Schedule);
                }

                var listAdd  = new List <SchedulesUpdate>();
                var listAdd2 = new List <ScheduleUpdateDto>();
                var b        = list.GroupBy(x => new
                {
                    x.ModelName,
                    x.ModelNo,
                    x.ArticleNo,
                    x.Treatment,
                    x.Process,
                    x.ProductionDate
                }).DistinctBy(x => x.Key);
                foreach (var x in b)
                {
                    if (!await _repoScheduleUpdate.FindAll().AnyAsync(y => y.ModelName == x.Key.ModelName && y.ModelNo == x.Key.ModelNo && y.ArticleNo == x.Key.ArticleNo && y.Treatment == x.Key.Treatment && y.Process == x.Key.Process))
                    {
                        // add schedule
                        var schedules = new SchedulesUpdate();

                        schedules.ModelName = x.Key.ModelName;
                        schedules.ModelNo   = x.Key.ModelNo;
                        schedules.ArticleNo = x.Key.ArticleNo;
                        schedules.Treatment = x.Key.Treatment;
                        schedules.Process   = x.Key.Process;
                        // schedules.a = x.Key.ArtProcessID;
                        schedules.CreatedBy  = x.FirstOrDefault().CreatedBy;
                        schedules.ApprovalBy = x.FirstOrDefault().ApprovalBy;
                        if (x.FirstOrDefault().ProcessID == 1)
                        {
                            schedules.ProductionDate = x.FirstOrDefault().ProductionDate;
                            schedules.EstablishDate  = x.FirstOrDefault().ProductionDate.AddDays(-30);
                        }
                        else
                        {
                            schedules.ProductionDate = x.FirstOrDefault().ProductionDate;
                            schedules.EstablishDate  = x.FirstOrDefault().ProductionDate.AddDays(-15);
                        }
                        schedules.CreatedDate    = DateTime.Now;
                        schedules.UpdateTime     = DateTime.Now;
                        schedules.ApprovalStatus = x.FirstOrDefault().ApprovalStatus;
                        schedules.FinishedStatus = x.FirstOrDefault().FinishedStatus;
                        _repoScheduleUpdate.Add(schedules);
                        listAdd.Add(schedules);
                        await _repoScheduleUpdate.SaveAll();

                        // luu db xong moi add part
                        foreach (var part in x.ToList())
                        {
                            if (part.Part == string.Empty)
                            {
                                var dataPart = new Part {
                                    Name = "Whole", ScheduleID = schedules.ID, Status = true
                                };
                                _repoPart.Add(dataPart);
                                await _repoPart.SaveAll();
                            }
                            else
                            {
                                _repoPart.Add(new Part
                                {
                                    ScheduleID = schedules.ID,
                                    Name       = part.Part,
                                });
                                await _repoPart.SaveAll();
                            }
                        }
                    }
                    else
                    {
                        listExist.Add(x.ToList());
                    }
                }
                var result1 = listAdd.Where(x => x.ID > 0).ToList();
                var result2 = listAdd.Where(x => x.ID == 0).ToList();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #46
0
        public void distinctby_returns_empty_collection_if_enumerable_is_null()
        {
            List <Item> list = null;

            list.DistinctBy(x => x.Value).ShouldBeEmpty();
        }
Example #47
0
		public IEnumerable<Constructor> DescriptorConstructors()
		{
			var ctors = new List<Constructor>();
			if (IsPartless) return ctors;
			var m = this.DescriptorType;
			foreach (var url in this.Url.Paths)
			{
				var cp = this.Url.Parts
					.Where(p => !ApiUrl.BlackListRouteValues.Contains(p.Key))
					.Where(p => p.Value.Required)
					.Where(p => url.Contains($"{{{p.Value.Name}}}"))
					.OrderBy(kv => url.IndexOf($"{{{kv.Value.Name}}}", StringComparison.Ordinal));
				var par = string.Join(", ", cp.Select(p => $"{ClrParamType(p.Value.ClrTypeName)} {p.Key}"));
				var routing = string.Empty;
				//Routes that take {indices}/{types} and both are optional
				if (!cp.Any() && IndicesAndTypes)
				{
					AddParameterlessIndicesTypesConstructor(ctors, m);
					continue;
				}
				if (cp.Any())
					routing = "r=>r." + string.Join(".", cp
						.Select(p => new
						{
							route = p.Key,
							call = p.Value.Required ? "Required" : "Optional",
							v = p.Key == "metric"
								? $"(Metrics){p.Key}"
								: p.Key == "index_metric"
									? $"(IndexMetrics){p.Key}"
									: p.Key
						})
						.Select(p => $"{p.call}(\"{p.route}\", {p.v})")
					);
				var doc = $@"/// <summary>{url}</summary>";
				if (cp.Any())
				{
					doc += "\r\n" + string.Join("\t\t\r\n", cp.Select(p => $"///<param name=\"{p.Key}\"> this parameter is required</param>"));
				}
				var c = new Constructor { Generated = $"public {m}({par}) : base({routing}){{}}", Description = doc };
				ctors.Add(c);
			}
			if (IsDocumentPath && !string.IsNullOrEmpty(this.DescriptorTypeGeneric))
			{
				var doc = $@"/// <summary>{this.Url.Path}</summary>";
				doc += "\r\n\t\t\r\n" + "///<param name=\"document\"> describes an elasticsearch document of type T, allows implicit conversion from numeric and string ids </param>";
				var documentRoute = "r=>r.Required(\"index\", document.Self.Index).Required(\"type\", document.Self.Type).Required(\"id\", document.Self.Id)";
				var documentPathGeneric = Regex.Replace(this.DescriptorTypeGeneric, @"^<?([^\s,>]+).*$", "$1");
				var documentFromPath = $"partial void DocumentFromPath({documentPathGeneric} document);";
				var c = new Constructor { AdditionalCode = documentFromPath, Generated = $"public {m}(DocumentPath<{documentPathGeneric}> document) : base({documentRoute}){{ this.DocumentFromPath(document.Document); }}", Description = doc };
				ctors.Add(c);
			}

			return ctors.DistinctBy(c => c.Generated);
		}
Example #48
0
        public void distinctby_returns_empty_collectionn_if_enumerable_is_empty()
        {
            var list = new List <Item>();

            list.DistinctBy(x => x.Value).ShouldBeEmpty();
        }
		/// <summary>
		/// Extracts pipeline states
		/// </summary>
		/// <param name="buildContext"></param>
		/// <param name="include"></param>
		/// <param name="shaderSource"></param>
		/// <param name="defines"></param>
		/// <returns></returns>
		KeyValuePair<string,string>[] ExtractPipelineStates ( BuildContext buildContext, Include include, string shaderSource, string sourceFile, string defines, string listing )
		{
			defines = defines + " _UBERSHADER";

			var defs = defines.Split(new[]{' ','\t'}, StringSplitOptions.RemoveEmptyEntries)	
						.Select( entry => new SharpDX.Direct3D.ShaderMacro( entry, "1" ) )
						.ToArray();
			
			string errors		=	null;
			var preprocessed	=	FX.ShaderBytecode.Preprocess( shaderSource, defs, include, out errors, sourceFile );

			var stateList = new List<KeyValuePair<string,string>>();

			using ( var sr = new StringReader(preprocessed) ) {

				while (true) {
					var line = sr.ReadLine();

					if (line==null) {
						break;
					}

					line = line.Trim();

					if (line.StartsWith("$")) {
						var words = line.Split(new[]{' ','\t'}, StringSplitOptions.RemoveEmptyEntries );

						if (words.Contains("ubershader")) {
							continue;
						}

						if (words.Length==2) {
							stateList.Add( new KeyValuePair<string,string>( words[1], "" ) );
						} else
						if (words.Length==3) {
							stateList.Add( new KeyValuePair<string,string>( words[1], words[2] ) );
						} else {
							Log.Warning("Bad ubershader $-statement: {0}", line);
						}
					}
				}
			}

			stateList	=	stateList
							.DistinctBy( s0 => s0.Key )
							.ToList();

 
			var html = "<pre>"
				+ "<b>Pipeline States:</b>\r\n\r\n"
				+ string.Join("\r\n", stateList.Select( s => string.Format("{0,-20} = <i>{1}</i>", s.Key, s.Value ) ) )
				+ "</pre>";
			
			File.WriteAllText( listing, html );

			return stateList.ToArray();
		}
        public static void SaveAcvt(Model.DataUnion.BASE_ACVT[] acvts)
        {
            if (acvts?.Length > 0)
            {
                int seq_acvt = 0;
                List<Model.DataUnion.BASE_ACVT> acvtList = acvts.ToList();
                List<Model.DataUnion.BASE_ACVT_QST> qstList = new List<Model.DataUnion.BASE_ACVT_QST>();
                List<Model.DataUnion.BASE_ACVT_QST_OPT> optList = new List<Model.DataUnion.BASE_ACVT_QST_OPT>();
                acvtList.ForEach(a =>
                {
                    a.seq = seq_acvt++;
                    if (a.qst?.Length > 0)
                    {
                        qstList.AddRange(a.qst);
                        (qstList = a.qst.ToList()).ForEach(q =>
                        {
                            try
                            {
                                q._id = Convert.ToInt32(q.acvtQstId);
                            }
                            catch (Exception ex)
                            {
                                Logger.Log(LogType.Exception, "Convert.ToInt32 Error @SaveAcvt.", ex);
                            }
                            if (q.opt?.Length > 0)
                            {
                                optList.AddRange(q.opt);
                                int optSeq = 0;
                                optList.ForEach(o => o.seq = optSeq++);
                            }
                        });
                    }
                });

                Service.LocalDatabaseService.InsertAll(acvtList, Model.DataUnion.BASE_ACVT.TableName);
                Service.LocalDatabaseService.InsertAll(qstList, Model.DataUnion.BASE_ACVT_QST.TableName);
                //Service.LocalDatabaseService.InsertAllOneByOne(optList, Model.DataUnion.BASE_ACVT_QST_OPT.TableName);
                Service.LocalDatabaseService.InsertAll(optList.DistinctBy(o => o._id), Model.DataUnion.BASE_ACVT_QST_OPT.TableName);//Distinct the same id item.
            }
        }
Example #51
0
 private IEnumerable<FieldInfo> GetAvailableFields(Type objectType)
 {
     var fields = new List<FieldInfo>();
     var type = objectType;
     while(type != null && type != typeof(object))
     {
         fields.AddRange(type.GetFields(CurrentBindingFlags)
                         .Where(x => x.IsCallable())
         );
         type = type.BaseType;
     }
     return fields.DistinctBy(x=> x.ToString()); //Look @ GetAvailableMethods for explanation.
 }
Example #52
0
        /// <summary>
        /// Function used for Worklist Based on the search condition
        /// </summary>
        /// <param name="ReferID">ReferenceID (Optional)</param>
        /// <param name="CStat">Status (Optional)</param>
        /// <param name="FDate">FromDate (Optional)</param>
        /// <param name="TDate">ToDate (Optional)</param>
        /// <param name="Appl">Applicant Name (Optional)</param>
        /// <param name="UserId">UserId for checking authentication</param>
        /// <param name="Type">Task Owner</param>
        ///  SP  : K2_WorkList
        /// <returns></returns>
        /// <summary>
        public List <ChkFrmStatus> GetWorklist(string ReferID, string CStat, string FDate, string TDate, string UserId, string SUser, string ProsIncId, int offset = 0, int limit = 999999, string sort = null, string applicant = null, string applicantEmpNo = null)
        {
            string              proinsid   = "";
            WorkflowFacade      workfacade = new WorkflowFacade();
            List <WorklistItem> worklist   = new List <WorklistItem>();

            if (string.IsNullOrEmpty(SUser))
            {
                worklist = workfacade.GetWorklistItemForAllTasks(UserId);
                //if (worklist.Count() > 0)
                //{
                //    proinsid = String.Join(",", worklist.Select(P => P.ProcInstID)).TrimEnd(',');
                //}
            }
            else
            {
                List <WorklistItem> sharedworklist = workfacade.GetWorklistItemForAllTasks(SUser);
                var sharePermit = (from a in Db.SharingList
                                   join b in Db.DelegationProcess on a.ActivityGroupID equals b.GroupID into ps
                                   from b in ps.DefaultIfEmpty()
                                   where a.DelegationType == "Sharing" &&
                                   a.FromWorkerID == SUser &&
                                   a.ToWorkerID == UserId
                                   select b.K2StepName
                                   ).ToList();
                foreach (var i in sharedworklist)
                {
                    if (sharePermit.Contains(i.ActivityName))
                    {
                        worklist.Add(i);
                    }
                }
            }

            List <CheckStatus>  StatusList   = new List <CheckStatus>();
            List <ChkFrmStatus> FormRequests = new List <ChkFrmStatus>();

            if (worklist.Count() > 0)
            {
                try
                {
                    SqlParameter[] sqlp =
                    {
                        new SqlParameter("ReferID",        DBNull.Value),
                        new SqlParameter("CStatus",        DBNull.Value),
                        new SqlParameter("FDate",          DBNull.Value),
                        new SqlParameter("TDate",          DBNull.Value),
                        new SqlParameter("SUser",          DBNull.Value),
                        new SqlParameter("userid",         DBNull.Value),
                        new SqlParameter("TOwner",         DBNull.Value),
                        new SqlParameter("ProcIncId",      DBNull.Value),
                        new SqlParameter("offset",         offset),
                        new SqlParameter("limit",          limit),
                        new SqlParameter("sort",           sort),
                        new SqlParameter("applicant",      DBNull.Value),
                        new SqlParameter("applicantEmpNo", DBNull.Value)
                    };

                    if (!string.IsNullOrEmpty(ReferID))
                    {
                        sqlp[0].Value = ReferID;
                    }
                    if (!string.IsNullOrEmpty(CStat))
                    {
                        sqlp[1].Value = CStat;
                    }
                    if (!string.IsNullOrEmpty(FDate))
                    {
                        sqlp[2].Value = FDate;
                    }
                    if (!string.IsNullOrEmpty(TDate))
                    {
                        sqlp[3].Value = TDate;
                    }
                    if (!string.IsNullOrEmpty(SUser))
                    {
                        sqlp[4].Value = SUser;
                    }
                    if (!string.IsNullOrEmpty(UserId))
                    {
                        sqlp[5].Value = UserId;
                    }
                    if (!string.IsNullOrEmpty(applicant))
                    {
                        sqlp[11].Value = applicant;
                    }
                    if (!string.IsNullOrEmpty(applicantEmpNo))
                    {
                        sqlp[12].Value = applicantEmpNo;
                    }

                    if (string.IsNullOrEmpty(ProsIncId))
                    {
                        if (worklist.Count > 0)
                        {
                            sqlp[7].Value = String.Join(",", worklist.Select(P => P.ProcInstID)).TrimEnd(',');
                        }
                    }
                    else
                    {
                        sqlp[7].Value = ProsIncId;
                    }

                    StatusList = Db.Database.SqlQuery <CheckStatus>("exec [K2_WorkList] @ReferID,@CStatus,@FDate,@TDate,@SUser,@UserId,@TOwner,@ProcIncId,@offset,@limit,@sort,@applicant,@applicantEmpNo", sqlp).ToList();

                    //foreach (int FormID in StatusList.Select(P => P.FormID).Distinct())
                    foreach (var request in StatusList.DistinctBy(P => P.ProcInstID))
                    {
                        ChkFrmStatus status = new ChkFrmStatus();
                        //var request = StatusList.Where(P => P.FormID == FormID).FirstOrDefault();
                        if (!string.IsNullOrEmpty(request.ProcInstID))
                        {
                            int procid = 0;
                            procid = Convert.ToInt32(request.ProcInstID);
                            //if (worklist.Select(P => P.ProcInstID).Contains(procid))
                            //{
                            status.FormID              = request.FormID;
                            status.ProcInstID          = request.ProcInstID;
                            status.ReferenceID         = request.ReferenceID;
                            status.FormStatus          = request.FormStatus;
                            status.SubmittedOn         = request.SubmittedOn;
                            status.ApplicantUserId     = request.ApplicantUserID;
                            status.ApplicantEMP        = request.ApplicantEMP;
                            status.ApplicantFNAME      = request.ApplicantFNAME;
                            status.ApproverEmp         = request.ApproverEMP;
                            status.ApproverFNAME       = request.ApproverFNAME;
                            status.ProcInstID          = request.ProcInstID;
                            status.DisplayStatus       = request.DisplayStatus;
                            status.LastUser            = request.LastUser;
                            status.ActionTakerFullName = request.ActionTakerFullName;
                            status.ITSApproverFullName = request.ITSApproverFullName;
                            status.PreparerFNAME       = request.PreparerFullName;
                            status.CurrentActor        = request.CurrentActor;
                            status.SUser = request.SUser;

                            //if (!string.IsNullOrEmpty(request.ProcInstID))
                            //{

                            //if (!proinsid.Split(',').Contains(request.ProcInstID))
                            //{
                            //    status.ProcessUrl = worklist.Where(p => p.ProcInstID == procid).Select(P => P.Data).FirstOrDefault() + "&SharedBy=" + SUser;
                            //    status.Type = "Sharing";
                            //}
                            //else
                            //    status.ProcessUrl = worklist.Where(p => p.ProcInstID == procid).Select(P => P.Data).FirstOrDefault();

                            if (!string.IsNullOrEmpty(SUser))
                            {
                                status.Type = "Sharing";
                            }


                            //}
                            //status.ProcessUrl = worklist.Where(p => p.ProcInstID == procid).Select(P => P.Data).FirstOrDefault();
                            status.SN = worklist.Where(p => p.ProcInstID == procid).Select(P => P.SN).FirstOrDefault();
                            //var actions = worklist.Where(p => p.ProcInstID == procid).Select(P => P.Actions).FirstOrDefault();
                            //if (actions != null)
                            //    status.actions = actions.Select(P => P.Name).ToList();

                            if (request.Permission != "2")
                            {
                                List <ServiceLevel1> Level1lst = new List <ServiceLevel1>();
                                foreach (var FirstLevelService in StatusList.Where(P => P.FormID == request.FormID && P.ProcInstID == request.ProcInstID).Select(P => new { P.MMenu, P.MMenuGUID }).Distinct())
                                {
                                    if (!string.IsNullOrEmpty(FirstLevelService.MMenu))
                                    {
                                        ServiceLevel1 Level1 = new ServiceLevel1();
                                        Level1.Name = FirstLevelService.MMenu;
                                        Level1.GUID = new Guid(FirstLevelService.MMenuGUID);
                                        List <ServiceLevel2> Level2lst = new List <ServiceLevel2>();
                                        foreach (var SecondLevelService in StatusList.Where(P => P.FormID == request.FormID && P.ProcInstID == request.ProcInstID && P.MMenu == FirstLevelService.MMenu).DistinctBy(P => P.SubMenu))
                                        {
                                            ServiceLevel2 Level2 = new ServiceLevel2();
                                            Level2.Name   = SecondLevelService.SubMenu;
                                            Level2.GUID   = new Guid(SecondLevelService.SubMenuGUID);
                                            Level2.SValue = SecondLevelService.ServiceTypeValue;
                                            List <ServiceLevel3> Level3lst = new List <ServiceLevel3>();
                                            foreach (var ThirsLevelService in StatusList.Where(P => P.FormID == request.FormID && P.ProcInstID == request.ProcInstID && P.MMenu == FirstLevelService.MMenu && P.SubMenu == SecondLevelService.SubMenu).OrderBy(P => P.ServiceGUID))
                                            {
                                                ServiceLevel3 Level3 = new ServiceLevel3();
                                                Level3.Name        = ThirsLevelService.SSubMenu;
                                                Level3.GUID        = new Guid(ThirsLevelService.SSubMenuGUID);
                                                Level3.SValue      = ThirsLevelService.ServiceTypeValue;
                                                Level3.ControlFlag = ThirsLevelService.ControlFlag;
                                                Level3lst.Add(Level3);
                                            }
                                            if (Level3lst.Count > 0)
                                            {
                                                Level2.Level3 = Level3lst;
                                                //Level2.GUID = Guid.Empty;   // To return Null Value.
                                                Level2.SValue = null;
                                            }
                                            else
                                            {
                                                Level2.Level3 = null;
                                            }
                                            Level2lst.Add(Level2);
                                        }
                                        if (Level2lst.Count > 0)
                                        {
                                            Level1.Level2 = Level2lst;
                                        }
                                        else
                                        {
                                            Level1.Level2 = null;
                                        }
                                        Level1lst.Add(Level1);
                                    }
                                }
                                if (Level1lst.Count > 0)
                                {
                                    status.RequestList = Level1lst;
                                }
                                else
                                {
                                    status.RequestList = null;
                                }
                            }
                            FormRequests.Add(status);
                            //}
                        }
                    }
                }
                catch (Exception ex)
                {
                    FormRequests = null;
                    throw ex;
                }
            }
            return(FormRequests);
        }
Example #53
0
        internal IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren, bool includeHidden)
        {
            if (user == null)
            {
                throw new ArgumentNullException();
            }

            //the true root should return our users root folder children
            if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);

            var list = new List<BaseItem>();

            var hasLinkedChildren = AddChildrenToList(user, includeLinkedChildren, list, includeHidden, false);

            return hasLinkedChildren ? list.DistinctBy(i => i.Id).ToList() : list;
        }
Example #54
0
        public MethodResult <List <PokemonData> > GetPokemonToTransfer()
        {
            if (!UserSettings.TransferPokemon)
            {
                LogCaller(new LoggerEventArgs("Transferring disabled", LoggerTypes.Debug));

                return(new MethodResult <List <PokemonData> >
                {
                    Data = new List <PokemonData>(),
                    Message = "Transferring disabled",
                    Success = true
                });
            }

            if (!Pokemon.Any())
            {
                LogCaller(new LoggerEventArgs("You have no pokemon", LoggerTypes.Info));

                return(new MethodResult <List <PokemonData> >
                {
                    Message = "You have no pokemon"
                });
            }

            var pokemonToTransfer = new List <PokemonData>();

            IEnumerable <IGrouping <PokemonId, PokemonData> > groupedPokemon = Pokemon.GroupBy(x => x.PokemonId);

            foreach (IGrouping <PokemonId, PokemonData> group in groupedPokemon)
            {
                TransferSetting settings = UserSettings.TransferSettings.FirstOrDefault(x => x.Id == group.Key);

                if (settings == null)
                {
                    LogCaller(new LoggerEventArgs(String.Format("Failed to find transfer settings for pokemon {0}", group.Key), LoggerTypes.Warning));

                    continue;
                }

                if (!settings.Transfer)
                {
                    continue;
                }

                switch (settings.Type)
                {
                case TransferType.All:
                    pokemonToTransfer.AddRange(group.ToList());
                    break;

                case TransferType.BelowCP:
                    pokemonToTransfer.AddRange(GetPokemonBelowCP(group, settings.MinCP));
                    break;

                case TransferType.BelowIVPercentage:
                    pokemonToTransfer.AddRange(GetPokemonBelowIVPercent(group, settings.IVPercent));
                    break;

                case TransferType.KeepPossibleEvolves:
                    pokemonToTransfer.AddRange(GetPokemonByPossibleEvolve(group, settings.KeepMax));
                    break;

                case TransferType.KeepStrongestX:
                    pokemonToTransfer.AddRange(GetPokemonByStrongest(group, settings.KeepMax));
                    break;

                case TransferType.KeepXHighestIV:
                    pokemonToTransfer.AddRange(GetPokemonByIV(group, settings.KeepMax));
                    break;

                case TransferType.BelowCPAndIVAmount:
                    pokemonToTransfer.AddRange(GetPokemonBelowCPIVAmount(group, settings.MinCP, settings.IVPercent));
                    break;

                case TransferType.BelowCPOrIVAmount:
                    pokemonToTransfer.AddRange(GetPokemonBelowIVPercent(group, settings.IVPercent));
                    pokemonToTransfer.AddRange(GetPokemonBelowCP(group, settings.MinCP));
                    pokemonToTransfer = pokemonToTransfer.DistinctBy(x => x.Id).ToList();
                    break;

                case TransferType.Slashed:
                    pokemonToTransfer.AddRange(group.ToList());
                    pokemonToTransfer = pokemonToTransfer.DistinctBy(x => x.IsBad).ToList();
                    break;
                }
            }

            if (UserSettings.TransferSlashPokemons)
            {
                var slashPokemons = Pokemon.Where(x => x.IsBad);
                foreach (var slashPokemon in slashPokemons)
                {
                    var inlist = pokemonToTransfer.FirstOrDefault(x => x.Id == slashPokemon.Id);
                    if (inlist == null)
                    {
                        pokemonToTransfer.Add(slashPokemon);
                    }
                }
            }

            return(new MethodResult <List <PokemonData> >
            {
                Data = pokemonToTransfer,
                Message = String.Format("Found {0} pokemon to transfer", pokemonToTransfer.Count),
                Success = true
            });
        }
        private IEnumerable<ParticipationsPerSubject> GetParticipationsPerSubject(DateTime from, DateTime to, int subjectId = 0)
        {
            var result = new List<ParticipationsPerSubject>();
            var queryableParticipations = db.Participations.Where(p => p.ParticipationDateTime > from &&
                                                                       p.ParticipationDateTime <= to &&
                                                                       p.Participating == true);
            if (subjectId > 0)
            {
                queryableParticipations = queryableParticipations.Where(p => p.SubjectId == subjectId);
            }
            var participations = queryableParticipations.OrderBy(p => p.ParticipationDateTime).ToList();

            foreach (var participation in participations)
            {
                var activity = db.Activities.Find(participation.ActivityId);
                var subject = db.Subjects.Find(activity.SubjectId);

                var participationPerSubject = new ParticipationsPerSubject()
                    {
                        SubjectName = subject.Name,
                        SubjectId = subject.SubjectId,
                        ActivityName = activity.Name,
                        ActivityId = participation.ActivityId,
                        NumberOfParticipations = participations.Count(p => p.ActivityId == participation.Activity.ActivityId)
                    };
                result.Add(participationPerSubject);
            }
            return result.DistinctBy(p => p.ActivityId).OrderBy(p => p.SubjectName).ThenBy(p => p.ActivityName);
        }
Example #56
0
        public bool ProcessRecords(EntityCollection ec, List <EntityMetadata> emds, int organizationMajorVersion = 9)
        {
            var records = new List <Entity>(ec.Entities);

            // Move annotation at the beginning if the list as the list will be
            // inverted to allow list removal. This way, annotation are
            // processed as the last records
            var annotations = records.Where(e => e.LogicalName == "annotation").ToList();

            records = records.Except(annotations).ToList();
            records.InsertRange(0, annotations);

            var progress = new ImportProgress(records.Count);

            var nextCycle = new List <Entity>();

            // reset Error state for each
            progress.Entities.ForEach(p => { p.ErrorFirstPhase = 0; });

            for (int i = records.Count - 1; i >= 0; i--)
            {
                EntityProgress entityProgress;

                var record = records[i];

                // Handle annotations.
                if (record.LogicalName != "annotation")
                {
                    // see if any records in the entity collection have a reference to this Annotation
                    if (record.Attributes.Values.Any(v =>
                                                     v is EntityReference reference &&
                                                     records.Select(r => r.Id).Contains(reference.Id)
                                                     ))
                    {
                        if (nextCycle.Any(r => r.Id == record.Id))
                        {
                            continue;
                        }

                        var newRecord = new Entity(record.LogicalName)
                        {
                            Id = record.Id
                        };
                        var toRemove = new List <string>();
                        foreach (var attr in record.Attributes)
                        {
                            if (attr.Value is EntityReference)
                            {
                                newRecord.Attributes.Add(attr.Key, attr.Value);
                                toRemove.Add(attr.Key);
                                nextCycle.Add(newRecord);
                            }
                        }

                        foreach (var attr in toRemove)
                        {
                            record.Attributes.Remove(attr);
                        }
                    }

                    if (record.Attributes.Values.Any(v =>
                                                     v is Guid guid &&
                                                     records.Where(r => r.Id != record.Id)
                                                     .Select(r => r.Id)
                                                     .Contains(guid)
                                                     ))
                    {
                        nextCycle.Add(record);
                        records.RemoveAt(i);
                        continue;
                    }
                }
                // check for entity progress.. entity may not be in target system
                entityProgress = GetEntityProgress(records, record, progress, emds);
                if (entityProgress == null)
                {
                    continue;
                }
                try
                {
                    record.Attributes.Remove("ownerid");

                    if (record.Attributes.Contains("statecode") &&
                        record.GetAttributeValue <OptionSetValue>("statecode").Value == 1)
                    {
                        PortalMover.ReportProgress($"Import: Record {record.GetAttributeValue<string>(entityProgress.Metadata.PrimaryNameAttribute)} is inactive : Added for deactivation step");

                        recordsToDeactivate.Add(record.ToEntityReference());
                        record.Attributes.Remove("statecode");
                        record.Attributes.Remove("statuscode");
                    }

                    if (organizationMajorVersion >= 8)
                    {
                        var result = (UpsertResponse)service.Execute(new UpsertRequest
                        {
                            Target = record
                        });

                        PortalMover.ReportProgress($"Import: Record {record.GetAttributeValue<string>(entityProgress.Metadata.PrimaryNameAttribute)} {(result.RecordCreated ? "created" : "updated")} ({entityProgress.Entity}/{record.Id})");
                    }
                    else
                    {
                        bool exists = false;
                        try
                        {
                            service.Retrieve(record.LogicalName, record.Id, new ColumnSet());
                            exists = true;
                        }
                        catch
                        {
                            // Do nothing
                        }

                        if (exists)
                        {
                            service.Update(record);
                            PortalMover.ReportProgress($"Import: Record {record.GetAttributeValue<string>(entityProgress.Metadata.PrimaryNameAttribute)} updated ({entityProgress.Entity}/{record.Id})");
                        }
                        else
                        {
                            service.Create(record);
                            PortalMover.ReportProgress($"Import: Record {record.GetAttributeValue<string>(entityProgress.Metadata.PrimaryNameAttribute)} created ({entityProgress.Entity}/{record.Id})");
                        }
                    }

                    if (record.LogicalName == "annotation" && settings.Config.CleanWebFiles)
                    {
                        var reference = record.GetAttributeValue <EntityReference>("objectid");
                        if (reference?.LogicalName == "adx_webfile")
                        {
                            PortalMover.ReportProgress($"Import: Searching for extra annotation in web file {reference.Id:B}");

                            var qe = new QueryExpression("annotation")
                            {
                                NoLock   = true,
                                Criteria = new FilterExpression
                                {
                                    Conditions =
                                    {
                                        new ConditionExpression("annotationid", ConditionOperator.NotEqual,
                                                                record.Id),
                                        new ConditionExpression("objectid",     ConditionOperator.Equal,
                                                                reference.Id),
                                    }
                                }
                            };

                            var extraNotes = service.RetrieveMultiple(qe);
                            foreach (var extraNote in extraNotes.Entities)
                            {
                                PortalMover.ReportProgress($"Import: Deleting extra note {extraNote.Id:B}");
                                service.Delete(extraNote.LogicalName, extraNote.Id);
                            }
                        }
                    }

                    records.RemoveAt(i);
                    entityProgress.SuccessFirstPhase++;
                }
                catch (Exception error)
                {
                    PortalMover.ReportProgress($"Import: {record.GetAttributeValue<string>(entityProgress.Metadata.PrimaryNameAttribute)} ({entityProgress.Entity}/{record.Id}): {error.Message}");
                    entityProgress.ErrorFirstPhase++;
                }
                finally
                {
                    entityProgress.Processed++;
                }
            }

            PortalMover.ReportProgress($"Import: Updating records to add references and processing many-to-many relationships...");

            var count = nextCycle.DistinctBy(r => r.Id).Count();
            var index = 0;

            foreach (var record in nextCycle.DistinctBy(r => r.Id))
            {
                var entityProgress = GetEntityProgress(nextCycle, record, progress, emds);

                if (!entityProgress.SuccessSecondPhase.HasValue)
                {
                    entityProgress.SuccessSecondPhase = 0;
                    entityProgress.ErrorSecondPhase   = 0;
                }

                try
                {
                    index++;

                    PortalMover.ReportProgress($"Import: Upating record {record.LogicalName} ({record.Id})");

                    record.Attributes.Remove("ownerid");

                    if (record.Attributes.Count == 3 && record.Attributes.Values.All(v => v is Guid))
                    {
                        PortalMover.ReportProgress($"Import: Creating association {entityProgress.Entity} ({record.Id})");

                        try
                        {
                            var rel =
                                emds.SelectMany(e => e.ManyToManyRelationships)
                                .First(r => r.IntersectEntityName == record.LogicalName);

                            service.Associate(rel.Entity1LogicalName,
                                              record.GetAttributeValue <Guid>(rel.Entity1IntersectAttribute),
                                              new Relationship(rel.SchemaName),
                                              new EntityReferenceCollection(new List <EntityReference>
                            {
                                new EntityReference(rel.Entity2LogicalName,
                                                    record.GetAttributeValue <Guid>(rel.Entity2IntersectAttribute))
                            }));

                            PortalMover.ReportProgress($"Import: Association {entityProgress.Entity} ({record.Id}) created");
                        }
                        catch (FaultException <OrganizationServiceFault> error)
                        {
                            if (error.Detail.ErrorCode != -2147220937)
                            {
                                throw;
                            }

                            PortalMover.ReportProgress($"Import: Association {entityProgress.Entity} ({record.Id}) already exists");
                        }
                        finally
                        {
                            entityProgress.Processed++;
                        }
                    }
                    else
                    {
                        service.Update(record);
                    }
                }
                catch (Exception error)
                {
                    PortalMover.ReportProgress($"Import: An error occured during import: {error.Message}");
                    entityProgress.ErrorSecondPhase = entityProgress.ErrorSecondPhase.Value + 1;
                }
            }

            #region Deactivate Records
            if (recordsToDeactivate.Any())
            {
                count = recordsToDeactivate.Count;
                index = 0;

                PortalMover.ReportProgress($"Import: Deactivating records...");

                foreach (var er in recordsToDeactivate)
                {
                    var entityProgress = progress.Entities.First(e => e.LogicalName == er.LogicalName);
                    if (!entityProgress.SuccessSecondPhase.HasValue)
                    {
                        entityProgress.SuccessSetStatePhase = 0;
                        entityProgress.ErrorSetState        = 0;
                    }

                    try
                    {
                        index++;

                        PortalMover.ReportProgress($"Import: Deactivating record {er.LogicalName} ({er.Id})");

                        var recordToUpdate = new Entity(er.LogicalName)
                        {
                            Id             = er.Id,
                            ["statecode"]  = new OptionSetValue(1),
                            ["statuscode"] = new OptionSetValue(-1)
                        };

                        service.Update(recordToUpdate);

                        var percentage = index * 100 / count;
                        entityProgress.SuccessSetStatePhase++;
                    }
                    catch (Exception error)
                    {
                        var percentage = index * 100 / count;
                        entityProgress.ErrorSetState++;
                    }
                }
            }
            #endregion

            return(false);
        }
Example #57
0
        async Task ProcessSynqObjects(bool noCheckout, bool skipWhenFileMatches, IReadOnlyCollection<Package> packages,
            ICollection<Package> syncedPackages) {
            var objects = new List<FileObjectMapping>();
            var allRemotes = new List<Uri>();

            foreach (var package in packages) {
                var name = package.MetaData.GetFullName();
                var remotes = FindRemotesWithPackage(name).ToArray();
                Console.WriteLine(String.Empty);
                if (!remotes.Any())
                    throw new NoSourceFoundException("No source found with " + name);
                allRemotes.AddRange(remotes);
                Repository.Log("Processing package: {0}", name);
                objects.AddRange(package.GetNeededObjects(skipWhenFileMatches));
            }

            var objectsToFetch = objects.DistinctBy(x => x.Checksum).ToArray();
            await
                UpdateMultiple(objectsToFetch, packages,
                    allRemotes.Distinct().ToArray()).ConfigureAwait(false);

            StatusRepo.Reset(RepoStatus.CheckOut, packages.Count);
            foreach (var package in packages) {
                syncedPackages.Add(package);
                if (noCheckout)
                    continue;
                if (Settings.GlobalWorkingPath != null)
                    package.SetWorkingPath(Settings.GlobalWorkingPath.ToString());
                Repository.Log("\nChecking out {0} into {1}, please be patient...",
                    package.MetaData.GetFullName(), package.WorkingPath);
                switch (Settings.CheckoutType) {
                case CheckoutType.NormalCheckout:
                    await package.CheckoutAsync().ConfigureAwait(false);
                    break;
                case CheckoutType.CheckoutWithoutRemoval:
                    await package.CheckoutWithoutRemovalAsync().ConfigureAwait(false);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            if (!noCheckout && skipWhenFileMatches) {
                Repo.DeleteObject(objectsToFetch.Select(x => new ObjectInfo(x.Checksum, x.Checksum)));
                // nasty using checksum for packed checksum or ? not needed here anyway??
            }
        }
Example #58
0
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_UpdateMyListFileStatus: {0}", Hash);


            try
            {
                // NOTE - we might return more than one VideoLocal record here, if there are duplicates by hash
                SVR_VideoLocal vid = Repo.Instance.VideoLocal.GetByHash(Hash);
                if (vid != null)
                {
                    if (vid.GetAniDBFile() != null)
                    {
                        if (WatchedDateAsSecs > 0)
                        {
                            DateTime?watchedDate = Commons.Utils.AniDB.GetAniDBDateAsDate(WatchedDateAsSecs);
                            ShokoService.AnidbProcessor.UpdateMyListFileStatus(vid, Watched, watchedDate);
                        }
                        else
                        {
                            ShokoService.AnidbProcessor.UpdateMyListFileStatus(vid, Watched);
                        }
                    }
                    else
                    {
                        // we have a manual link, so get the xrefs and add the episodes instead as generic files
                        var xrefs = vid.EpisodeCrossRefs;
                        foreach (var xref in xrefs)
                        {
                            var episode = xref.GetEpisode();
                            if (episode == null)
                            {
                                continue;
                            }
                            if (WatchedDateAsSecs > 0)
                            {
                                DateTime?watchedDate = Commons.Utils.AniDB.GetAniDBDateAsDate(WatchedDateAsSecs);
                                ShokoService.AnidbProcessor.UpdateMyListFileStatus(vid, episode.AnimeID,
                                                                                   episode.EpisodeNumber, Watched, watchedDate);
                            }
                            else
                            {
                                ShokoService.AnidbProcessor.UpdateMyListFileStatus(vid, episode.AnimeID,
                                                                                   episode.EpisodeNumber, Watched);
                            }
                        }
                    }

                    logger.Info("Updating file list status: {0} - {1}", vid, Watched);

                    if (UpdateSeriesStats)
                    {
                        // update watched stats
                        List <SVR_AnimeEpisode> eps = Repo.Instance.AnimeEpisode.GetByHash(vid.ED2KHash);
                        if (eps.Count > 0)
                        {
                            eps.DistinctBy(a => a.AnimeSeriesID).ForEach(a => a.GetAnimeSeries().QueueUpdateStats());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_UpdateMyListFileStatus: {0} - {1}", Hash, ex);
            }
        }
Example #59
0
        private static IEnumerable<ApplicationWindow> FindAltTabableWindows()
        {
            List<ApplicationWindow> windows = new List<ApplicationWindow>();
            var ewp = new User32.EnumWindowsProc((hwnd, lparam) =>
            {
                ApplicationWindow window = null;
                var shouldContinue = ApplicationWindows.Filter(hwnd, lparam, out window);
                if (window != null)
                    windows.Add(window);
                return shouldContinue;

            });
            User32.EnumWindows(ewp, 0);
            return windows.DistinctBy(w => w.hWnd);
        }
Example #60
0
        public iOrgs GetAllImplementingOrg(FilterBDModel filterDBModel)
        {
            if (filterDBModel != null)
            {
                Sessions.filterBDModel.iatiActivities = filterDBModel.iatiActivities;
                UpdateActivities(filterDBModel.iatiActivities, Sessions.activitiesContainer.iatiActivities);
            }

            //actual method begins here
            var managingDPs = GetAllFundSources();

            var iOrgs = new List<participatingorg>();
            foreach (var activity in Sessions.activitiesContainer?.RelevantActivities)
            {
                if (activity.ImplementingOrgs != null)
                    iOrgs.AddRange(activity.ImplementingOrgs);


            }

            var distictOrgs = iOrgs.DistinctBy(l => l.Name).OrderBy(o => o.Name);

            var exAgencies = aimsDAL.GetExecutingAgencies();

            var returtResult = new iOrgs
            {
                Orgs = distictOrgs.ToList(),
                FundSources = managingDPs,
                ExecutingAgencyTypes = aimsDAL.GetExecutingAgencyTypes(),
                ExecutingAgencies = exAgencies

            };
            Sessions.iOrgs = returtResult;

            foreach (var org in distictOrgs)
            {
                //check for matching managing DP from AIMS
                var managingDP = !string.IsNullOrWhiteSpace(org.@ref) ? managingDPs.FirstOrDefault(q => q.IATICode != null && q.IATICode.Contains(org.@ref)) : null;

                //Add selected value
                org.AllID = managingDP == null ? Sessions.DP.AllID : managingDP.AllID;

                GuessAgency(org, false);
            }


            Sessions.CurrentStage = Stage.FilterDP;

            return returtResult;
        }