public async Task AssignBatchActionResultsAsync(IODataClient client, ODataResponse batchResponse, IList<Func<IODataClient, Task>> actions, IList<int> responseIndexes) { var exceptions = new List<Exception>(); for (var actionIndex = 0; actionIndex < actions.Count && !exceptions.Any(); actionIndex++) { var responseIndex = responseIndexes[actionIndex]; if (responseIndex >= 0 && responseIndex < batchResponse.Batch.Count) { var actionResponse = batchResponse.Batch[responseIndex]; if (actionResponse.Exception != null) { exceptions.Add(actionResponse.Exception); } else if (actionResponse.StatusCode >= (int)HttpStatusCode.BadRequest) { exceptions.Add(WebRequestException.CreateFromStatusCode((HttpStatusCode)actionResponse.StatusCode)); } else { await actions[actionIndex](new ODataClient(client as ODataClient, actionResponse)); } } } if (exceptions.Any()) { throw exceptions.First(); } }
public SendGridMessage Send(string from, IList<string> to, string subject, string body) { var message = SendGrid.GenerateInstance(); var errors = new List<string>(); if (to.Count > 0) { foreach(var recipient in to) message.AddTo(recipient); } else errors.Add("Please add at least one recipient to the email."); message.From = new MailAddress(from); message.Subject = subject; message.Html = body; try { if (!errors.Any()) { var transportInstance = SMTP.GenerateInstance(new NetworkCredential(_username, _password)); transportInstance.Deliver(message); } } catch(Exception ex) { throw ex; } return new SendGridMessage { Success = !errors.Any(), ErrorMessages = errors }; }
/// <summary> /// Returns a list of visual branches which are around the given commit. /// </summary> /// <param name="commit"></param> /// <param name="repo"></param> /// <returns></returns> public static List<Branch> GetBranchesAroundCommit(Commit commit, ObservableCollection<Branch> branches) { List<Branch> list = new List<Branch>(); // Loop through all branches and determine if they are around the specified commit. foreach (Branch branch in branches) { // Tip has to be found and in case multiple branches share the tree, get rid of the others -- messes up visual position counting. if (branch.Tip == null || list.Any(b => branch.Tip.Branches.Contains(b)) || list.Any(b => b.Tip.Branches.Contains(branch))) continue; // The branch's tip must be newer/same than the commit. if (branch.Tip.Date >= commit.Date) // TODO: && first commit-ever must be older? We might not need to do that... ... ? { list.Add(branch); } else { // If there's a branch with a tip commit older than commit.Date, then it's around this commit if they don't share a single branch. bool foundThisBranch = branch.Tip.Branches.Any(b => commit.Branches.Contains(b)); if (foundThisBranch == false) list.Add(branch); } } return list; }
public static List<int> Merge(List<int> left, List<int> right) { var ret = new List<int>(); while (left.Any() || right.Any()) { if (left.Any() && right.Any()) { if (left.First() <= right.First()) { ret.Add(left.First()); left.Remove(left.First()); } else { ret.Add(right.First()); right.Remove(right.First()); } } else if (left.Any()) { ret.Add(left.First()); left.Remove(left.First()); } else if (right.Any()) { ret.Add(right.First()); right.Remove(right.First()); } } return ret; }
private IList<ClassificationSpan> DoGetClassificationSpans(SnapshotSpan span) { List<ClassificationSpan> spans = null; object prop; if (span.Snapshot.TextBuffer.Properties.TryGetProperty(typeof(ITextDocument), out prop)) { var doc = (ITextDocument)prop; string fileName = System.IO.Path.GetFileName(doc.FilePath); Language lang = Languages.FindLanguage(fileName); if (lang != null) { List<ClassificationSpan> strings = new List<ClassificationSpan>(); List<ClassificationSpan> comments = new List<ClassificationSpan>(); DoGetStringSpans(lang, span, strings, comments); spans = new List<ClassificationSpan>(); if (!strings.Any(s => s.Span.Contains(span) && !comments.Any(t => t.Span.Contains(span)))) { IEnumerable<ClassificationSpan> mine = lang.GetClassificationSpans(span); spans.AddRange(from c in mine where !strings.Any(d => d.Span.OverlapsWith(c.Span)) && !comments.Any(d => d.Span.OverlapsWith(c.Span)) select c); } spans.AddRange(strings); spans.AddRange(comments); } } return spans ?? ms_noSpans; }
public static async Task<BackupResultHelper> StartBackup(List<Game> games, BackupType backupType, bool backupEnabled, BackupSyncOptions backupSyncOptions, int intervalMinute = 0, int intervalHour = 0) { //Check for problems with parameters if (!games.Any() && backupType == BackupType.Autobackup && backupEnabled) { _resultHelper = new BackupResultHelper {Message = @"Auto-backup disabled", AutobackupEnabled = false}; return _resultHelper; } if (!games.Any()) { ErrorResultHelper.Message = @"No games selected"; return ErrorResultHelper; } var gamesToBackup= new List<Game>(); if (!backupEnabled) { if (!GetDirectoryOrFile(backupType)) return ErrorResultHelper; gamesToBackup = ModifyGamePaths(games); } switch (backupType) { case BackupType.ToZip: return await BackupToZip.BackupAndZip(gamesToBackup, _specifiedFile); case BackupType.ToFolder: return BackupToFolder.BackupSaves(gamesToBackup, _specifiedFolder); case BackupType.Autobackup: return BackupAuto.ToggleAutoBackup(gamesToBackup, backupEnabled, backupSyncOptions, intervalMinute, intervalHour, _specifiedFolder); } return ErrorResultHelper; }
private static BaseWrapper CreateWrapperFromType(Type type, Type itemType) { BaseWrapper retval = null; if (type.IsArray) { retval = (BaseWrapper)Activator.CreateInstance(typeof(ArrayWrapper<>).MakeGenericType(itemType)); } else { var types = new List<Type>(type.GetInterfaces() .Select(h => h.IsGenericType ? h.GetGenericTypeDefinition() : h)); types.Insert(0, type.IsGenericType ? type.GetGenericTypeDefinition() : type); if (types.Any(i => typeof(IList<>).IsAssignableFrom(i) || typeof(IList).IsAssignableFrom(i))) { retval = new ListWrapper(); } else if (types.Any(y => typeof(ICollection<>).IsAssignableFrom(y))) { retval = (BaseWrapper)Activator.CreateInstance(typeof(CollectionWrapper<>).MakeGenericType(itemType)); } else if (types.Any(i => typeof(IEnumerable<>).IsAssignableFrom(i) || typeof(IEnumerable).IsAssignableFrom(i))) { retval = new ListWrapper(); } else if (retval == null) { //we gave it our best shot, but we couldn't figure out how to deserialize this badboy. throw new MongoException(string.Format("Collection of type {0} cannot be deserialized.", type.FullName)); } } return retval; }
public BodyDeposits(GeneratorConfiguration resource, ConfigNode node) { if (node == null) { node = new ConfigNode(); } this.deposits = new List<Deposit>(); this.seed = Misc.Parse(node.GetValue("Seed"), seedGenerator.Next()); var random = new System.Random(seed); for (int i = 0; i < resource.DepositCount; i++) { float R = random.Range(resource.MinRadius, resource.MaxRadius); for (int j = 0; j < resource.NumberOfTries; j++) { Vector2 Pos = new Vector2(random.Range(R, 360 - R), random.Range(R, 180 - R)); var deposit = Deposit.Generate(Pos, R, random, resource); if (!deposits.Any(d => d.Shape.Vertices.Any(v => deposit.Shape.PointInPolygon(new Vector2(v.x, v.y)))) && !deposit.Shape.Vertices.Any(v => deposits.Any(d => d.Shape.PointInPolygon(new Vector2(v.x, v.y))))) { deposits.Add(deposit); break; } } } var depositValues = node.GetValues("Deposit"); for (int i = 0; i < Math.Min(deposits.Count, depositValues.Length); i++) { deposits[i].Quantity = Misc.Parse(depositValues[i], deposits[i].InitialQuantity); } MaxQuantity = resource.MaxQuantity; }
public AssetFile(string file, string assetDir) { OriginalFile = file; File = file.NormalizePath(); assetDir = assetDir.NormalizePath(); Name = File.Remove(0, assetDir.Length).NormalizePath(); int nameIndex = Name.LastIndexOf("/", System.StringComparison.Ordinal); Path = nameIndex == -1 ? "" : Name.Substring(0, nameIndex); Extensions = new List<string>(); foreach (string extension in Name.Split('.').Reverse()) { if (!AssetPipeline.KnownExtensions.Any(i => i.NormalizePath() == extension)) break; Extensions.Add(extension); } Extension = "." + string.Join(".", ((IEnumerable<string>)Extensions).Reverse()); if (Extension.Length > 1) { Name = Name.Remove(Name.Length - Extension.Length, Extension.Length); } if (Extensions.Any(i => AssetPipeline.JavascriptExtensions.Contains(i))) { Type = AssetType.Js; } else if (Extensions.Any(i => AssetPipeline.CssExtensions.Contains(i))) { Type = AssetType.Css; } }
public IReadOnlyList<object> Read() { Row += 1; position = 0; if (reader.Peek() <= 0) return null; var result = new List<object>(); var readingValue = true; var value = new StringBuilder(); char character; while (ReadNext(out character)) { switch (character) { case '\r': break; case '\n': if (readingValue) result.Add(ConvertUnquotedValue(value.ToString())); if (!result.Any()) // Skip empty row and continue break; return result; case ',': if (readingValue) result.Add(ConvertUnquotedValue(value.ToString())); value.Clear(); readingValue = true; break; case '"': if (value.Length > 0 || !readingValue) throw UnexpectedCharacter(character); result.Add(ReadQuotedValue()); readingValue = false; break; case ' ': case '\t': // Trim spaces and tabs at the beginning of unquoted values if (value.Length > 0) value.Append(character); break; default: if (!readingValue) throw UnexpectedCharacter(character); value.Append(character); break; } } // At the EOF, only append a value if it actualy has anything in it, or we had values before it if (readingValue && (value.Length > 0 || result.Any())) result.Add(ConvertUnquotedValue(value.ToString())); return result.Any() ? result : null; }
private static void AddActivitiesAndTransitions(ProcessDefinition processDefinition, List<ActivityDefinition> activities, List<TransitionDefinition> transitions, TransitionDefinition startingTransition, List<string> finalActivities, int cutoffNestingLevel) { if (transitions.Any<TransitionDefinition>((TransitionDefinition t) => t.Name.Equals(startingTransition.Name, StringComparison.InvariantCulture))) { return; } ActivityDefinition to = startingTransition.To; if (startingTransition.ForkType == TransitionForkType.ForkEnd) { int? nestingLevel = to.NestingLevel; if ((nestingLevel.GetValueOrDefault() > cutoffNestingLevel ? false : nestingLevel.HasValue)) { TransitionDefinition transitionDefinition = startingTransition.Clone() as TransitionDefinition; transitionDefinition.IsFork = false; transitions.Add(transitionDefinition); if (!activities.Any<ActivityDefinition>((ActivityDefinition a) => a.Name.Equals(to.Name, StringComparison.InvariantCulture))) { ActivityDefinition activityDefinition = ActivityDefinition.Create(to.Name, to.State, false, true, false, false); activities.Add(activityDefinition); finalActivities.Add(to.Name); } return; } } transitions.Add(startingTransition); if (!activities.Any<ActivityDefinition>((ActivityDefinition a) => a.Name.Equals(to.Name, StringComparison.InvariantCulture))) { activities.Add(to.Clone() as ActivityDefinition); } foreach (TransitionDefinition possibleTransitionsForActivity in processDefinition.GetPossibleTransitionsForActivity(startingTransition.To, ForkTransitionSearchType.Both)) { SubprocessUtils.AddActivitiesAndTransitions(processDefinition, activities, transitions, possibleTransitionsForActivity, finalActivities, cutoffNestingLevel); } }
public List<Post> Search(string searchParameters, List<string> searchEnginesName) { var results = new List<Post>(); if (!string.IsNullOrEmpty(searchParameters)) { // Si indica que busque post guardados, primero agrego esos posts. if (searchEnginesName.Any(y => y == "SavedPosts")) results.AddRange(SearchSavedPosts(searchParameters)); foreach (var searchEngine in _searchEngines.Where(x => searchEnginesName.Any(y => y == x.Name))) { try { if (searchEngine.Instance != null) { var socialNetworkingSearchResult = searchEngine.Instance.Search(searchParameters, 1); if (socialNetworkingSearchResult != null) { results.AddRange(ConvertFromSocialNetworkingItemToPosts(socialNetworkingSearchResult.SocialNetworkingItems, searchParameters)); } } } catch (Exception ex) { Logger.Log.Error(ex.Message, ex); } } } return results; }
public void PrintGeneration() { var orderedFirstGeneration = new List<Cell>(_thisGeneration.OrderBy(criteria => criteria.Line).ThenBy(criteria => criteria.Column)); for (int i = 0; i < 20; i++) { for (int j = 0; j < 20; j++) { if (orderedFirstGeneration.Any(x => x.Line == i && x.Column == j && x.State == State.Head)) { Console.ForegroundColor = ConsoleColor.Blue; Console.Write("*"); } else if (orderedFirstGeneration.Any(x => x.Line == i && x.Column == j && x.State == State.Tail)) { Console.ForegroundColor = ConsoleColor.Red; Console.Write("*"); } else if (orderedFirstGeneration.Any(x => x.Line == i && x.Column == j && x.State == State.Conductor)) { Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("*"); } else Console.Write(" "); } Console.WriteLine(); } }
/// <summary> /// /// </summary> /// <param name="packages"></param> public static void Load(List<Package> packages) { try { var themes = GetThemes(); var widgets = GetWidgets(); if(themes != null && themes.Count > 0) { foreach (var theme in from theme in themes let found = packages.Any(pkg => theme.Id.ToLower() == pkg.Id.ToLower()) where !found select theme) { packages.Add(theme); } } if (widgets != null && widgets.Count > 0) { foreach (var wdg in from wdg in widgets let found = packages.Any(pkg => wdg.Id.ToLower() == pkg.Id.ToLower()) where !found select wdg) { packages.Add(wdg); } } } catch (Exception ex) { Utils.Log(System.Reflection.MethodBase.GetCurrentMethod().Name, ex); } }
private bool CardsAreConsecutiveWithAce(List<PokerCard> cards) { var aceHasPartner = cards.Any(c => c.CardFace.Value == Card.Face.Two) || cards.Any(c => c.CardFace.Value == Card.Face.King); var cardsWithoutAce = cards.Where(c => c.CardFace.Value != Card.Face.Ace).ToList(); return aceHasPartner && CardsAreConsecutive(cardsWithoutAce); }
private static IDictionary<string, string[]> SplitSections(string[] lines) { var ret = new Dictionary<string, string[]>(); var currentSegmentEntries = new List<string>(); string currentSegment = ""; for (int i = 0; i < lines.Length; i++) { string line = lines[i]; if (string.IsNullOrEmpty(line)) { if (currentSegmentEntries.Any()) { ret[currentSegment] = currentSegmentEntries.ToArray(); currentSegmentEntries.Clear(); } } else if (line[0] != ' ') { currentSegment = line.Trim(); } else { currentSegmentEntries.Add(line); } } if (currentSegmentEntries.Any()) { ret[currentSegment] = currentSegmentEntries.ToArray(); } return ret; }
protected override bool? AdditionalVerify(Player source, List<Card> cards, List<Player> players) { if (source[DuWuUsed] != 0) return false; if ((players == null || players.Count == 0) && (cards != null && cards.Count > 0)) return false; if (players == null || players.Count == 0) return null; int req = players[0].Health; if (players.Any(p => Game.CurrentGame.DistanceTo(source, p) > source[Player.AttackRange] + 1)) { return false; } if (req > 0 && (cards == null || cards.Count < req)) return null; if (req > 0 && (cards != null && cards.Count > req)) return false; if (req > 0 && cards != null && cards.Count > 0) { var temp = new Sha(); temp.HoldInTemp(cards); if (players.Any(p => Game.CurrentGame.DistanceTo(source, p) > source[Player.AttackRange] + 1)) { temp.ReleaseHoldInTemp(); return false; } temp.ReleaseHoldInTemp(); } return true; }
public void UpdateImages(List<ScannedImage> images, List<int> selection = null) { int delta = images.Count - Items.Count; for (int i = 0; i < delta; i++) { Items.Add("", i); Debug.Assert(selection == null); } for (int i = 0; i < -delta; i++) { Items.RemoveAt(Items.Count - 1); ilThumbnailList.Images.RemoveAt(ilThumbnailList.Images.Count - 1); Debug.Assert(selection == null); } // Determine the smallest range that contains all images in the selection int min = selection == null || !selection.Any() ? 0 : selection.Min(); int max = selection == null || !selection.Any() ? images.Count : selection.Max() + 1; for (int i = min; i < max; i++) { if (i >= ilThumbnailList.Images.Count) { ilThumbnailList.Images.Add(thumbnails[images[i]]); Debug.Assert(selection == null); } else { ilThumbnailList.Images[i] = thumbnails[images[i]]; } } thumbnails.TrimCache(images); Invalidate(); }
public Cbr GenerateCbr(List<KeyInfo> keys, bool isExport = false, KeyStoreContext context = null) { if (keys.Count == 0 || keys.Count > Constants.BatchLimit) throw new ArgumentOutOfRangeException("Keys are invalid to generate CBR."); string soldTo = keys.First().SoldToCustomerId; if (keys.Any(k => k.SoldToCustomerId != soldTo)) throw new ApplicationException("Keys are not sold to the same customer."); string shipTo = keys.First().ShipToCustomerId; if (keys.Any(k => k.ShipToCustomerId != shipTo)) throw new ApplicationException("Keys are not shipped to the same customer."); Guid customerReportId = Guid.NewGuid(); Cbr cbr = new Cbr() { CbrUniqueId = customerReportId, CbrStatus = (isExport ? CbrStatus.Reported : CbrStatus.Generated), SoldToCustomerId = soldTo, ReceivedFromCustomerId = shipTo, CbrKeys = keys.Select(k => new CbrKey() { CustomerReportUniqueId = customerReportId, KeyId = k.KeyId, HardwareHash = k.HardwareHash, OemOptionalInfo = k.OemOptionalInfo.ToString(), }).ToList() }; cbrRepository.InsertCbrAndCbrKeys(cbr, context = null); return cbr; }
public void RunTests(string resultDirectory) { var results = new List<PerformanceMetric>(); var failedRunResult = new List<Exception>(); var performanceCaseResult = new PerformanceCaseResult(); performanceCaseResult.StartTimer(); foreach (var testDefinition in _tests) { var result = Run(testDefinition); PrintSummary(result); results.AddRange(ConvertResultToMetrics(result)); if (!result.Successful) { failedRunResult.Add(result.ReportedException); } } performanceCaseResult.StopTimer(); performanceCaseResult.Metrics = results.ToArray(); Assert.False(failedRunResult.Any(), failedRunResult.Any() ? failedRunResult.First().Message : string.Empty); Assert.False(results.Count == 0, "tests returned no results"); WriteResultFiles(resultDirectory, results, performanceCaseResult); }
private void InitRepositories(List<Type> entities) { _errorsRepository = _dataRepositoryFactory.GetDataRepository<Error>(RequestMessage); if (entities.Any(e => e.FullName == typeof(Movie).FullName)) { _moviesRepository = _dataRepositoryFactory.GetDataRepository<Movie>(RequestMessage); } if (entities.Any(e => e.FullName == typeof(Rental).FullName)) { _rentalsRepository = _dataRepositoryFactory.GetDataRepository<Rental>(RequestMessage); } if (entities.Any(e => e.FullName == typeof(Customer).FullName)) { _customersRepository = _dataRepositoryFactory.GetDataRepository<Customer>(RequestMessage); } if (entities.Any(e => e.FullName == typeof(Stock).FullName)) { _stocksRepository = _dataRepositoryFactory.GetDataRepository<Stock>(RequestMessage); } if (entities.Any(e => e.FullName == typeof(User).FullName)) { _stocksRepository = _dataRepositoryFactory.GetDataRepository<Stock>(RequestMessage); } }
/// <summary> /// 作者:Beta /// 时间:2014.03.17 /// 描述:获取样式列表(需求展示) /// </summary> /// <param name="list"></param> /// <param name="dt"></param> /// <returns></returns> public static string GetStudentClassList(List<Model.Eme.BookRequirement> list, DateTime dt) { var classlist = " select-item"; if (dt.AddHours(-1) < DateTime.Now) { if (list.Any(p => p.BookStartTime <= dt && p.BookEndTime >= dt.AddMinutes(30) && p.IsSuccessful)) { classlist = classlist + " successful"; } else if (list.Any(p => p.BookStartTime <= dt && p.BookEndTime >= dt.AddMinutes(30) && !p.IsSuccessful)) { classlist = classlist + " pass"; } else { classlist = classlist + " unavailable"; } } else { if (list.Any(p => p.BookStartTime <= dt && p.BookEndTime >= dt.AddMinutes(30) && p.IsSuccessful)) { classlist = classlist + " successful"; } else if (list.Any(p => p.BookStartTime <= dt && p.BookEndTime >= dt.AddMinutes(30) && !p.IsSuccessful)) { classlist = classlist + " normal oking"; } } return classlist; }
private IEnumerable<Section> BreakDownSection(IEnumerable<string> lines, int level) { var headingMarker = new String('#', level) + " "; var currentSection = new List<string>(); foreach (var line in lines) { if (!line.StartsWith(headingMarker)) { currentSection.Add(line); } else { if (currentSection.Any(x => !string.IsNullOrWhiteSpace(x))) { yield return CreateSection(currentSection, level); currentSection.Clear(); } currentSection.Add(line); } } if (currentSection.Any(x => !string.IsNullOrWhiteSpace(x))) { yield return CreateSection(currentSection, level); } }
public IEnumerable<QuickFix> CodeCheck(Request request) { var errors = new List<QuickFix>(); var syntaxErrors = _syntaxErrorsHandler.FindSyntaxErrors(request) .Errors.Select( x => new QuickFix {Column = x.Column, FileName = x.FileName, Line = x.Line, Text = x.Message, LogLevel = "Error"}); errors.AddRange(syntaxErrors); if (errors.Any()) { return errors; } var semanticErrors = _semanticErrorsHandler.FindSemanticErrors(request) .Errors.Select( x => new QuickFix {Column = x.Column, FileName = x.FileName, Line = x.Line, Text = x.Message , LogLevel = "Error"}); errors.AddRange(semanticErrors); if (errors.Any()) { return errors; } var codeErrors = _codeIssuesHandler.GetCodeIssues(request).QuickFixes; errors.AddRange(codeErrors); return errors; }
private List<int> MakeListOfFileTypesThatUseJustTheseTabs(List<int> listOfTabTypesUsedInThisFile) { List<int> possibleFileTypes = new List<int>(); foreach (var tabType in listOfTabTypesUsedInThisFile) { // all of these tab types are real non zero types var thisTabFileTypes = from x in db.WhichTabsInWhichFiles where x.TabTypeID == tabType select x.FileTypeID; // now we have a list of the file types that use this tab type if (possibleFileTypes.Any()) { // we have started building a list foreach (var fileType in possibleFileTypes) { // let's look at the list we have built of potential file types if (!thisTabFileTypes.Contains(fileType)) possibleFileTypes.Remove(fileType); // if the list of file types that matches the current tab type // does not include the file type from our current list then remove // that file type from our current list if (!possibleFileTypes.Any()) return possibleFileTypes; // if our current list is empty bail out } } else { // this is the first time through foreach (var fileType in thisTabFileTypes) { // let's add all of the results for this column to our comparison list possibleFileTypes.Add(fileType); } } } return possibleFileTypes; }
public static void TrySeveralTimesIfException(uint numTries, int timeSleepInMs, Action<int> action, List<Type> ignoredExceptions = null) { bool ignoreAll = ignoredExceptions == null || ignoredExceptions.Count == 0; if (!ignoreAll && ignoredExceptions.Any(type => !type.IsSubclassOf(typeof(Exception)))) throw new ArgumentException("Elements must be subclass of 'Exception'", nameof(ignoredExceptions)); if (action == null) throw new ArgumentNullException(nameof(action)); int tries = 0; while (true) { try { ++tries; action(tries); break; } catch (Exception e) { if (ignoreAll || ignoredExceptions.Any(ignored => e.GetType() == ignored)) { if (tries > numTries) throw; // Wait and retry Thread.Sleep(timeSleepInMs); } else throw; } } }
protected void btnBuscar_Click(object sender, EventArgs e) { List<string> lista = new List<string>(); if (string.IsNullOrEmpty(txtDataDe.Text)) lista.Add("<b>Data Inicial</b> precisa ser preenchida"); if (string.IsNullOrEmpty(txtDataDe.Text)) lista.Add("<b>Data Final</b> precisa ser preenchida"); if (!lista.Any()) { try { if (Convert.ToDateTime(txtDataDe.Text) > Convert.ToDateTime(txtDataAte.Text)) lista.Add("<b>Data Inicial</b> deve ser menor que <b>Data Final</b>"); } catch { lista.Add("Data deve estar incorreta"); } } if (lista.Any()) CRB.BOSS.UI.Controle.Popup.Mensagem.Alerta(lista); else Buscar(); }
public static void InternalExecute(ProjectItem projectItem) { var ctors = new List<CodeFunction>(); foreach (CodeFunction constructor in projectItem.FindContructors().Where(m => m.Parameters.Count > 0)) { var codeElement = constructor.As<CodeElement>(); string ctorText = codeElement.InnerText(); var editPoint = codeElement.AtTheFirstLineAfterTheOpeningBrakect(); bool lineAdded = false; foreach (var param in constructor.Parameters().Reverse()) { if (param.Type.CodeType.Kind != vsCMElement.vsCMElementStruct && !ctorText.Contains($"ArgumentNullException(\"{param.Name}\")")) { lineAdded = true; projectItem.AddLine(editPoint, param.Name.ToCtorNullCheck()); } } if (lineAdded) { ctors.Add(constructor); } } if (ctors.Any()) { if (!projectItem.Contains("using System;")) { projectItem.AddLine(projectItem.FindNameSpace().As<CodeElement>().AtTheFirstLineAfterTheOpeningBrakect(), "using System;"); } } foreach (CodeFunction constructor in projectItem.FindContructors().Where(m => m.Parameters.Count > 0)) { if (string.IsNullOrWhiteSpace(constructor.DocComment)) { AddCommentsToCodeElements.AddDocCommentToCtor(constructor); } var docComment = constructor.DocComment; var codeElement = constructor.As<CodeElement>(); if ((codeElement.Contains("throw new ArgumentNullException") || codeElement.Contains("throw new System.ArgumentNullException")) && (!docComment.Contains(exceptionMessage1) && !docComment.Contains(exceptionMessage2))) { codeElement.AppendToDocComment(exceptionMessage1); } } if (ctors.Any()) { var dte = (DTE)Package.GetGlobalService(typeof(SDTE)); try { dte.ExecuteCommand("Edit.FormatDocument"); } catch { } } }
public static List<Plan> GetPlans() { if (LayoutUID == Guid.Empty) { return ClientManager.PlansConfiguration.AllPlans.Where(x => !x.IsNotShowPlan).ToList(); } else { var plans = new List<Guid>(); var layout = ClientManager.LayoutsConfiguration.Layouts.FirstOrDefault(x => x.UID == LayoutUID); if (layout != null) { foreach (var part in layout.Parts) { if (part.Properties != null && part.Properties is LayoutPartPlansProperties) { var layoutPartPlansProperties = part.Properties as LayoutPartPlansProperties; if (layoutPartPlansProperties.Type == LayoutPartPlansType.All) { return ClientManager.PlansConfiguration.AllPlans.Where(x=> !x.IsNotShowPlan).ToList(); } foreach (var planUID in layoutPartPlansProperties.Plans) { if (!plans.Any(x => x == planUID)) { plans.Add(planUID); } } } } } return ClientManager.PlansConfiguration.AllPlans.Where(x => plans.Any(w => w == x.UID)).ToList(); } }
//method that finds word in text static string ForbiddenWord(string text, List<string> forbiddenWords) { string[] array = text.Split(new char[] { ' ' }); StringBuilder sb = new StringBuilder(); foreach (var word in array) { if (forbiddenWords.Any(x => x == word)) { sb.Append(new String('*', word.Length) + " "); continue; } else if (forbiddenWords.Any(x => (x + ".") == word )) { sb.Append(new String('*', word.Length) + "."); continue; } else { sb.Append(word + " "); } } return sb.ToString(); }
public List <PageDto> GetDetailPages(string template, int tabModuleId) { string format; int othermoduleTabId = ActiveModule.TabID; int moduleId = ActiveModule.ModuleID; var listItems = new List <PageDto>(); var templateUri = new FileUri(template); var manifest = templateUri.ToTemplateManifest(); int othermoduleDetailTabId = -1; if (manifest != null && manifest.IsListTemplate && manifest.Manifest.Templates.Any(t => t.Value.Detail != null)) { if (tabModuleId > 0) { var dsModule = (new ModuleController()).GetTabModule(tabModuleId); othermoduleTabId = dsModule.TabID; moduleId = dsModule.ModuleID; othermoduleDetailTabId = GetOtherModuleDetailTabId(othermoduleTabId, moduleId); //if (othermoduleDetailTabId > 0) //{ // //add extra li with "Default Detail Page" directly to dropdown // format = LogContext.IsLogActive ? "Main Module Detail Page - [{0}]" : "Main Module Detail Page"; // listItems.Add(new PageDto() // { // Text = string.Format(format, othermoduleDetailTabId), // TabId = othermoduleDetailTabId // }); //} } Dictionary <string, int> tabs = TabController.GetTabPathDictionary(ActiveModule.PortalID, DnnLanguageUtils.GetCurrentCultureCode()); foreach (var tabId in tabs.Where(i => IsTabWithModuleWithSameMainModule(i.Value, moduleId) && IsAccessibleTab(i.Value))) { string tabname = tabId.Key.Replace("//", " / ").TrimStart(" / "); List <string> infoText = new List <string>(); if (othermoduleDetailTabId > 0 && tabId.Value == othermoduleDetailTabId) { infoText.Add("Main Module Detail"); } if ((othermoduleTabId > 0 && tabId.Value == othermoduleTabId) || (othermoduleTabId == -1 && tabId.Value == ActiveModule.TabID)) { //add extra li with "Main Module Page" directly to dropdown //format = LogContext.IsLogActive ? "Main Module Page - {0} [{1}]" : "Main Module Page"; //listItems.Add(new PageDto() //{ // Text = string.Format(format, tabname, tabId.Value), // TabId = -1 //}); infoText.Add("Main Module "); } if (othermoduleTabId > 0 && tabId.Value == ActiveModule.TabID) { //add extra li with "CurrentPage" directly to dropdown //format = LogContext.IsLogActive ? "Current Page - {0} [{1}]" : "Current Page"; //listItems.Add(new PageDto() //{ // Text = string.Format(format, tabname, tabId.Value), // TabId = tabId.Value //}); infoText.Add("Current"); } format = LogContext.IsLogActive ? "{0} [{1}]" : "{0}"; if (othermoduleTabId > 0 && tabId.Value == ActiveModule.TabID) { listItems.Add(new PageDto() { Text = string.Format(format, tabname, tabId.Value) + " (Current)", TabId = tabId.Value }); } else { listItems.Add(new PageDto() { Text = string.Format(format, tabname, tabId.Value) + (infoText.Any() ? " (" + string.Join(",", infoText.ToArray()) + ")" : ""), TabId = tabId.Value }); } } return(listItems.OrderBy(x => x.Text).ToList()); } return(listItems); }
public async Task Create() { if (wizardProvider.HasWizard) { wizardProvider.BeforeProjectIsCreated(); } if (!CreateProject()) { return; } Solution parentSolution = null; if (ParentFolder == null) { //NOTE: we can only create one solution, so if the first item is a solution, it's the only item parentSolution = processedTemplate.WorkspaceItems.FirstOrDefault() as Solution; if (parentSolution != null) { if (parentSolution.RootFolder.Items.Count > 0) { currentEntries = new List <SolutionItem> (parentSolution.GetAllSolutionItems()); } ParentFolder = parentSolution.RootFolder; } } else { parentSolution = ParentFolder.ParentSolution; currentEntries = processedTemplate.WorkspaceItems.OfType <SolutionItem> ().ToList(); } // New combines (not added to parent combines) already have the project as child. if (!projectConfiguration.CreateSolution) { // Make sure the new item is saved before adding. In this way the // version control add-in will be able to put it under version control. foreach (SolutionItem currentEntry in currentEntries) { var eitem = currentEntry as SolutionItem; if (eitem != null) { // Inherit the file format from the solution eitem.ConvertToFormat(ParentFolder.ParentSolution.FileFormat); var project = eitem as Project; if (project != null) { // Remove any references to other projects and add them back after the // project is saved because a project reference cannot be resolved until // the project has a parent solution. List <ProjectReference> projectReferences = GetProjectReferences(project); if (projectReferences.Any()) { project.Items.RemoveRange(projectReferences); } await IdeApp.ProjectOperations.SaveAsync(eitem); if (projectReferences.Any()) { project.Items.AddRange(projectReferences); } } } ParentFolder.AddItem(currentEntry, true); } } else { string solutionFileName = Path.Combine(projectConfiguration.SolutionLocation, finalConfigurationPage.SolutionFileName); if (File.Exists(solutionFileName)) { if (!MessageService.Confirm(GettextCatalog.GetString("File {0} already exists. Overwrite?", solutionFileName), AlertButton.OverwriteFile)) { ParentFolder = null; //Reset process of creating solution return; } File.Delete(solutionFileName); } } if (ParentFolder != null) { await IdeApp.ProjectOperations.SaveAsync(ParentFolder.ParentSolution); } else { await IdeApp.ProjectOperations.SaveAsync(processedTemplate.WorkspaceItems); } CreateVersionControlItems(); if (OpenSolution) { DisposeExistingNewItems(); TemplateWizard wizard = wizardProvider.CurrentWizard; if (await OpenCreatedSolution(processedTemplate)) { var sol = IdeApp.Workspace.GetAllSolutions().FirstOrDefault(); if (sol != null) { if (wizard != null) { wizard.ItemsCreated(new [] { sol }); } InstallProjectTemplatePackages(sol); } } } else { // The item is not a solution being opened, so it is going to be added to // an existing item. In this case, it must not be disposed by the dialog. disposeNewItem = false; RunTemplateActions(processedTemplate); if (wizardProvider.HasWizard) { wizardProvider.CurrentWizard.ItemsCreated(processedTemplate.WorkspaceItems); } if (ParentFolder != null) { InstallProjectTemplatePackages(ParentFolder.ParentSolution); } } IsNewItemCreated = true; UpdateDefaultSettings(); dialog.CloseDialog(); }
public bool CurrentlyActiveExplosionsOrBombs() { return(_bombs.Any(b => b.IsActive) || _explosionOverlayData.Any(e => e.IsActive)); }
public async Task <RelatorioSondagemComponentesMatematicaAditMulConsolidadoDto> Handle(ObterSondagemMatAditMultiConsolidadoQuery request, CancellationToken cancellationToken) { var relatorio = new RelatorioSondagemComponentesMatematicaAditMulConsolidadoDto(); var respostas = new List <RelatorioSondagemComponentesMatematicaAditMulConsolidadoPerguntasRespostasDto>(); var perguntas = new List <RelatorioSondagemComponentesMatematicaAditMulConsolidadoPerguntaDto>(); MontarPerguntas(perguntas); MontarCabecalho(relatorio, request.Proficiencia, request.Dre, request.Ue, request.TurmaAno.ToString(), request.AnoLetivo, request.Semestre, request.Usuario.CodigoRf, request.Usuario.Nome); int qtdAlunos = 0; if (request.Proficiencia == ProficienciaSondagemEnum.CampoAditivo) { var listaAlunos = await mathPoolCARepository.ObterPorFiltros(request.Dre?.Codigo, request.Ue?.Codigo, request.TurmaAno, request.AnoLetivo, request.Semestre); qtdAlunos = listaAlunos.DistinctBy(a => a.AlunoEolCode).Count(); var ordem1Ideia = listaAlunos.GroupBy(fu => fu.Ordem1Ideia); var ordem1Resultado = listaAlunos.GroupBy(fu => fu.Ordem1Resultado); var ordem2Ideia = listaAlunos.GroupBy(fu => fu.Ordem2Ideia); var ordem2Resultado = listaAlunos.GroupBy(fu => fu.Ordem2Resultado); if (request.TurmaAno != 2) { var ordem3Ideia = listaAlunos.GroupBy(fu => fu.Ordem3Ideia); var ordem3Resultado = listaAlunos.GroupBy(fu => fu.Ordem3Resultado); AdicionarOrdem(request.Proficiencia, request.TurmaAno, ordem3Ideia, ordem3Resultado, ordem: 3, respostas, request.QuantidadeTotalAlunos); if (request.TurmaAno != 1 && request.TurmaAno != 3) { var ordem4Ideia = listaAlunos.GroupBy(fu => fu.Ordem4Ideia); var ordem4Resultado = listaAlunos.GroupBy(fu => fu.Ordem4Resultado); AdicionarOrdem(request.Proficiencia, request.TurmaAno, ordem4Ideia, ordem4Resultado, ordem: 4, respostas, request.QuantidadeTotalAlunos); } } AdicionarOrdem(request.Proficiencia, request.TurmaAno, ordem1Ideia, ordem1Resultado, ordem: 1, respostas, request.QuantidadeTotalAlunos); AdicionarOrdem(request.Proficiencia, request.TurmaAno, ordem2Ideia, ordem2Resultado, ordem: 2, respostas, request.QuantidadeTotalAlunos); } else { var listaAlunos = await mathPoolCMRepository.ObterPorFiltros(request.Dre?.Codigo, request.Ue?.Codigo, request.TurmaAno, request.AnoLetivo, request.Semestre); qtdAlunos = listaAlunos.DistinctBy(a => a.AlunoEolCode).Count(); if (request.TurmaAno == 2) { var ordem3Ideia = listaAlunos.GroupBy(fu => fu.Ordem3Ideia); var ordem3Resultado = listaAlunos.GroupBy(fu => fu.Ordem3Resultado); AdicionarOrdem(request.Proficiencia, request.TurmaAno, ordem3Ideia, ordem3Resultado, ordem: 3, respostas, request.QuantidadeTotalAlunos); } else { if (request.TurmaAno == 3) { var ordem4Ideia = listaAlunos.GroupBy(fu => fu.Ordem4Ideia); var ordem4Resultado = listaAlunos.GroupBy(fu => fu.Ordem4Resultado); AdicionarOrdem(request.Proficiencia, request.TurmaAno, ordem4Ideia, ordem4Resultado, ordem: 4, respostas, request.QuantidadeTotalAlunos); } var ordem5Ideia = listaAlunos.GroupBy(fu => fu.Ordem5Ideia); var ordem5Resultado = listaAlunos.GroupBy(fu => fu.Ordem5Resultado); AdicionarOrdem(request.Proficiencia, request.TurmaAno, ordem5Ideia, ordem5Resultado, ordem: 5, respostas, request.QuantidadeTotalAlunos); if (request.TurmaAno != 3) { var ordem6Ideia = listaAlunos.GroupBy(fu => fu.Ordem6Ideia); var ordem6Resultado = listaAlunos.GroupBy(fu => fu.Ordem6Resultado); AdicionarOrdem(request.Proficiencia, request.TurmaAno, ordem6Ideia, ordem6Resultado, ordem: 6, respostas, request.QuantidadeTotalAlunos); var ordem7Ideia = listaAlunos.GroupBy(fu => fu.Ordem7Ideia); var ordem7Resultado = listaAlunos.GroupBy(fu => fu.Ordem6Resultado); AdicionarOrdem(request.Proficiencia, request.TurmaAno, ordem7Ideia, ordem7Resultado, ordem: 7, respostas, request.QuantidadeTotalAlunos); } if (request.TurmaAno != 3 && request.TurmaAno != 4) { var ordem8Ideia = listaAlunos.GroupBy(fu => fu.Ordem8Ideia); var ordem8Resultado = listaAlunos.GroupBy(fu => fu.Ordem8Resultado); AdicionarOrdem(request.Proficiencia, request.TurmaAno, ordem8Ideia, ordem8Resultado, ordem: 8, respostas, request.QuantidadeTotalAlunos); } } } if (perguntas.Any()) { relatorio.Perguntas = perguntas; } if (respostas.Any()) { respostas.ForEach(resposta => resposta.Respostas = resposta.Respostas.OrderBy(r => r.Resposta).ToList()); relatorio.PerguntasRespostas = respostas.OrderBy(r => r.Ordem).ToList(); } TrataAlunosQueNaoResponderam(relatorio, request.QuantidadeTotalAlunos); GerarGrafico(relatorio, qtdAlunos); return(relatorio); }
private void btnProcurarInscrição_Click(object sender, EventArgs e) { InscricaoRequestViewModel filtro = null; if (cboEvento.SelectedIndex != 0) { filtro = new InscricaoRequestViewModel(); filtro.IdEncontro = (int)cboEvento.SelectedValue; } if (!string.IsNullOrEmpty(txtELEBusca.Text)) { if (filtro == null) { filtro = new InscricaoRequestViewModel(); } if (filtro.Casal == null) { filtro.Casal = new CasalRequestViewModel(); } filtro.Casal.NomeEle = txtELEBusca.Text; } if (!string.IsNullOrEmpty(txtELABusca.Text)) { if (filtro == null) { filtro = new InscricaoRequestViewModel(); } if (filtro.Casal == null) { filtro.Casal = new CasalRequestViewModel(); } filtro.Casal.NomeEla = txtELABusca.Text; } EccDomain.Inscricao insc = new EccDomain.Inscricao(); var lista = filtro == null?insc.GetAll() : insc.GetByFilter(filtro); List <InscricaoGridResultViewModel> ListaResultado = new List <InscricaoGridResultViewModel>(); lista.ForEach(x => { var item = new InscricaoGridResultViewModel(); item.Casal = x.Casal; item.Convidador = x.Convidador; item.Encontro = x.Encontro; item.IdCasal = x.IdCasal; item.IdCasalConvidador = x.IdCasalConvidador; item.IdCasalVisitador = x.IdCasalVisitador; item.IdEncontro = x.IdEncontro; item.IdInscricao = x.IdInscricao; item.ListaVisitadores = x.ListaVisitadores; item.NomeEle = x.Casal.NomeEle; item.NomeEla = x.Casal.NomeEla; item.NomeEncontro = x.Encontro.Nome; item.Participou = x.Participou ? "Sim" : "Não"; ListaResultado.Add(item); }); gridResultado.DataSource = null; gridResultado.DataSource = ListaResultado; gridResultado.Visible = ListaResultado.Any(); lblResultado.Visible = !ListaResultado.Any(); }
public override void CreateOrUpdateTable(TableSchema schema, bool recreateTable, bool recreateIndexes, SqlDataProvider dataProvider) { const string longTextType = "LONGTEXT"; var columnMappings = new[] { new {Flags = TypeFlags.Array | TypeFlags.Byte, ColumnType = "LONGBLOB"}, new {Flags = TypeFlags.Boolean, ColumnType = "BOOLEAN"}, new {Flags = TypeFlags.Byte, ColumnType = "TINYINT UNSIGNED"}, new {Flags = TypeFlags.SByte, ColumnType = "TINYINT"}, new {Flags = TypeFlags.Int16, ColumnType = "SMALLINT"}, new {Flags = TypeFlags.UInt16, ColumnType = "SMALLINT UNSIGNED"}, new {Flags = TypeFlags.Int32, ColumnType = "INT"}, new {Flags = TypeFlags.UInt32, ColumnType = "INT UNSIGNED"}, new {Flags = TypeFlags.Int64, ColumnType = "BIGINT"}, new {Flags = TypeFlags.UInt64, ColumnType = "BIGINT UNSIGNED"}, new {Flags = TypeFlags.Decimal, ColumnType = "DECIMAL({0},{1})"}, new {Flags = TypeFlags.Double, ColumnType = "DOUBLE"}, new {Flags = TypeFlags.Single, ColumnType = "FLOAT"}, new {Flags = TypeFlags.String, ColumnType = "VARCHAR({0})"}, new {Flags = TypeFlags.DateTime, ColumnType = "DATETIME"} }; if (recreateTable) recreateIndexes = true; var existingColumns = dataProvider.ExecuteSqlReader("select * from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA=DATABASE() and TABLE_NAME=@name", QueryParameterCollection.FromObject(new { name = schema.MappedName })).ToLookup(rec => rec["COLUMN_NAME"].ToString()); if (existingColumns.Any() && recreateTable) { dataProvider.ExecuteSql("DROP TABLE " + QuoteTable(schema.MappedName)); } var parts = new List<string>(); bool createNew = true; foreach (var field in schema.Fields) { var columnMapping = columnMappings.FirstOrDefault(mapping => field.FieldInfo.Inspector().Type.Inspector().Is(mapping.Flags)); if (columnMapping == null) continue; if (existingColumns.Contains(field.MappedName) && !recreateTable) { createNew = false; continue; } if (columnMapping.Flags == TypeFlags.String && field.ColumnSize == int.MaxValue) columnMapping = new { columnMapping.Flags, ColumnType = longTextType }; var part = $"{QuoteField(field.MappedName)} {string.Format(columnMapping.ColumnType, field.ColumnSize, field.ColumnScale)}"; if (!field.ColumnNullable) part += " NOT"; part += " NULL"; if (field.AutoIncrement) part += " AUTO_INCREMENT"; parts.Add(part); } if (parts.Any() && schema.PrimaryKeys.Length > 0 && createNew) { parts.Add("PRIMARY KEY (" + string.Join(",", schema.PrimaryKeys.Select(pk => QuoteField(pk.MappedName))) + ")"); } if (!parts.Any()) return; string sql = (createNew ? "CREATE TABLE " : "ALTER TABLE ") + QuoteTable(schema.MappedName); if (createNew) sql += " ("; if (createNew) sql += string.Join(",", parts); else sql += string.Join(",", parts.Select(s => "ADD COLUMN " + s)); if (createNew) sql += ")"; dataProvider.ExecuteSql(sql); }
private async Task ReadyCheck(DiscordChannel channel, InhouseGame inhouseGame) { var inhouseQueue = InhouseQueues.FirstOrDefault(x => x.ChannelId == channel.Id); var mentionMsg = ""; foreach (var player in inhouseGame.InhousePlayers) { mentionMsg += $"{player.Player.Mention} "; } var embedBuilder = BuildGameFoundMessage(inhouseGame, inhouseQueue); var channelMessage = await channel.SendMessageAsync(mentionMsg, embed : embedBuilder.Build()).ConfigureAwait(false); var checkEmoji = DiscordEmoji.FromName(_client, ":white_check_mark:"); var xEmoji = DiscordEmoji.FromName(_client, ":x:"); await channelMessage.CreateReactionAsync(checkEmoji).ConfigureAwait(false); await channelMessage.CreateReactionAsync(xEmoji).ConfigureAwait(false); await Task.Run(async() => { while (true) { var interactivity = _client.GetInteractivity(); var response = await interactivity.WaitForReactionAsync(x => x.Message.Id == channelMessage.Id && x.User.Id != _client.CurrentUser.Id).ConfigureAwait(false); if (response.TimedOut) { // put everyone who was ready back to queue foreach (var queueGroup in inhouseGame.QueueGroups) { var removedPlayers = new List <InhousePlayer>(); foreach (var inhousePlayer in queueGroup.Players) { if (inhousePlayer.PlayerStatus == PlayerStatus.Ready) { inhousePlayer.PlayerStatus = PlayerStatus.None; } else { removedPlayers.Add(inhousePlayer); } } queueGroup.Players.RemoveAll(x => removedPlayers.Any(y => x == y)); inhouseQueue.PlayersInQueue.Insert(0, queueGroup); } await ShowQueue(channel, "Game timed out, readied players will now be put back in queue.").ConfigureAwait(false); InhouseGames.Remove(inhouseGame); return; } if (response.Result.Emoji == checkEmoji) { // check if it is one of the players var player = inhouseGame.InhousePlayers.FirstOrDefault(x => x.Player.Id == response.Result.User.Id); if (player == null) { continue; } var readyPlayer = inhouseGame.InhousePlayers.FirstOrDefault(x => x.Player.Id == response.Result.User.Id); readyPlayer.PlayerStatus = PlayerStatus.Ready; var embedBuilder = BuildGameFoundMessage(inhouseGame, inhouseQueue); await channelMessage.ModifyAsync(embed: embedBuilder.Build()).ConfigureAwait(false); if (inhouseGame.InhousePlayers.All(x => x.PlayerStatus == PlayerStatus.Ready)) { await channel.SendMessageAsync($"Everybody has readied, game will now start\nUse {_prefix}won to score the game."); return; } } else if (response.Result.Emoji == xEmoji) { // check if it is one of the players var player = inhouseGame.InhousePlayers.FirstOrDefault(x => x.Player.Id == response.Result.User.Id); if (player == null) { continue; } // put everyone back to queue except the author foreach (var queueGroup in inhouseGame.QueueGroups) { var removedPlayers = new List <InhousePlayer>(); foreach (var inhousePlayer in queueGroup.Players) { if (inhousePlayer.Player.Id == response.Result.User.Id) { removedPlayers.Add(inhousePlayer); } else { inhousePlayer.PlayerStatus = PlayerStatus.None; } } queueGroup.Players.RemoveAll(x => removedPlayers.Any(y => x == y)); inhouseQueue.PlayersInQueue.Insert(0, queueGroup); } InhouseGames.Remove(inhouseGame); await ShowQueue(channel, "A player cancelled the game and was removed from the queue\nAll other players have been put back into the queue").ConfigureAwait(false); return; } } }); }
/// <summary> /// C03 Mortgage save /// </summary> /// <param name="yearQuartly"></param> public void saveC03Mortgage(string yearQuartly) { string logPath = log.txtLocation(TableType.C03Mortgage.ToString()); DateTime startTime = DateTime.Now; try { List <Loan_default_Info> A06Data = db.Loan_default_Info .Where(x => x.Year_Quartly == yearQuartly).ToList(); List <Econ_Domestic> A07Data = db.Econ_Domestic .Where(x => x.Year_Quartly == yearQuartly).ToList(); if (!A06Data.Any()) { log.txtLog( TableType.C03Mortgage.ToString(), false, startTime, logPath, "Loan_default_Info 無 " + yearQuartly + " 的資料"); } else if (!A07Data.Any()) { log.txtLog( TableType.C03Mortgage.ToString(), false, startTime, logPath, "Econ_Domestic 無 " + yearQuartly + " 的資料"); } else { string productCode = GroupProductCode.M.GetDescription(); Group_Product_Code_Mapping gpcm = db.Group_Product_Code_Mapping.Where(x => x.Group_Product_Code.StartsWith(productCode)).FirstOrDefault(); if (gpcm == null) { log.txtLog( TableType.C03Mortgage.ToString(), false, startTime, logPath, "Group_Product_Code_Mapping 無房貸的 Product_Code"); } else { productCode = gpcm.Product_Code; var query = db.Econ_D_YYYYMMDD .Where(x => x.Year_Quartly == yearQuartly); db.Econ_D_YYYYMMDD.RemoveRange(query); db.Econ_D_YYYYMMDD.AddRange( A07Data.Select(x => new Econ_D_YYYYMMDD() { Processing_Date = DateTime.Now.ToString("yyyy/MM/dd"), Product_Code = productCode, Data_ID = "", Year_Quartly = x.Year_Quartly, PD_Quartly = A06Data[0].PD_Quartly, var1 = Extension.doubleNToDouble(x.TWSE_Index), var2 = Extension.doubleNToDouble(x.TWRGSARP_Index), var3 = Extension.doubleNToDouble(x.TWGDPCON_Index), var4 = Extension.doubleNToDouble(x.TWLFADJ_Index), var5 = Extension.doubleNToDouble(x.TWCPI_Index), var6 = Extension.doubleNToDouble(x.TWMSA1A_Index), var7 = Extension.doubleNToDouble(x.TWMSA1B_Index), var8 = Extension.doubleNToDouble(x.TWMSAM2_Index), var9 = Extension.doubleNToDouble(x.GVTW10YR_Index), var10 = Extension.doubleNToDouble(x.TWTRBAL_Index), var11 = Extension.doubleNToDouble(x.TWTREXP_Index), var12 = Extension.doubleNToDouble(x.TWTRIMP_Index), var13 = Extension.doubleNToDouble(x.TAREDSCD_Index), var14 = Extension.doubleNToDouble(x.TWCILI_Index), var15 = Extension.doubleNToDouble(x.TWBOPCUR_Index), var16 = Extension.doubleNToDouble(x.EHCATW_Index), var17 = Extension.doubleNToDouble(x.TWINDPI_Index), var18 = Extension.doubleNToDouble(x.TWWPI_Index), var19 = Extension.doubleNToDouble(x.TARSYOY_Index), var20 = Extension.doubleNToDouble(x.TWEOTTL_Index), var21 = Extension.doubleNToDouble(x.SLDETIGT_Index), var22 = Extension.doubleNToDouble(x.TWIRFE_Index), var23 = Extension.doubleNToDouble(x.SINYI_HOUSE_PRICE_index), var24 = Extension.doubleNToDouble(x.CATHAY_ESTATE_index), var25 = Extension.doubleNToDouble(x.Real_GDP2011), var26 = Extension.doubleNToDouble(x.MCCCTW_Index), var27 = Extension.doubleNToDouble(x.TRDR1T_Index) }) ); db.SaveChanges(); log.txtLog( TableType.C03Mortgage.ToString(), true, startTime, logPath, MessageType.Success.GetDescription()); } } } catch (Exception ex) { log.txtLog( TableType.C03Mortgage.ToString(), false, startTime, logPath, ex.Message); } }
private static FormElement _extract_xml_node_data(Guid applicationId, XmlNode parentNode, XmlNodeList nodeList, XmlNamespaceManager nsmgr, FormElement formElement, Dictionary <string, object> map, Dictionary <string, object> parentMap) { if (formElement == null || !formElement.ElementID.HasValue || nodeList == null || nodeList.Count == 0) { return(null); } FormElement retElement = new FormElement() { ElementID = formElement.ElementID, RefElementID = formElement.RefElementID, FormInstanceID = formElement.FormInstanceID, Type = formElement.Type, SequenceNumber = formElement.SequenceNumber, Name = formElement.Name }; if (!retElement.RefElementID.HasValue || retElement.RefElementID == retElement.ElementID) { retElement.RefElementID = retElement.ElementID; retElement.ElementID = Guid.NewGuid(); } switch (formElement.Type) { case FormElementTypes.Text: case FormElementTypes.Select: case FormElementTypes.Node: case FormElementTypes.User: { string strValue = nodeList.Item(0).InnerText.Trim(); int intValue = 0; List <string> options = null; if (formElement.Type == FormElementTypes.Select && int.TryParse(strValue, out intValue) && intValue > 0) { //if strValue is an integer, probably it is the index of selected option Dictionary <string, object> dic = PublicMethods.fromJSON(formElement.Info); if (dic.ContainsKey("Options") && dic["Options"].GetType() == typeof(ArrayList)) { ArrayList arr = (ArrayList)dic["Options"]; options = new List <string>(); foreach (object obj in arr) { options.Add(Base64.decode((string)obj)); } if (options.Count >= intValue && !options.Any(u => u == strValue)) { strValue = options[intValue - 1]; } } } if (!string.IsNullOrEmpty(strValue)) { retElement.TextValue = strValue; return(retElement); } else { return(null); } } case FormElementTypes.Checkbox: case FormElementTypes.MultiLevel: { List <string> strItems = new List <string>(); foreach (XmlNode nd in nodeList) { strItems.Add(nd.InnerText.Trim()); } string strValue = string.Join(" ~ ", strItems.Where(u => !string.IsNullOrEmpty(u))); if (!string.IsNullOrEmpty(strValue)) { retElement.TextValue = strValue; return(retElement); } else { return(null); } } case FormElementTypes.Binary: { Dictionary <string, object> dic = PublicMethods.fromJSON(formElement.Info); string yes = dic.ContainsKey("Yes") ? Base64.decode((string)dic["Yes"]) : string.Empty; string no = dic.ContainsKey("No") ? Base64.decode((string)dic["No"]) : string.Empty; string txt = nodeList.Item(0).InnerText.Trim().ToLower(); bool? bitValue = null; if (!string.IsNullOrEmpty(txt) && "truefalse".IndexOf(txt) >= 0) { bitValue = txt == "true"; } if (bitValue.HasValue) { retElement.BitValue = bitValue; retElement.TextValue = bitValue.Value ? (string.IsNullOrEmpty(yes) ? null : yes) : (string.IsNullOrEmpty(no) ? null : no); return(retElement); } else { return(null); } } case FormElementTypes.Numeric: { double dblValue = 0; if (double.TryParse(nodeList.Item(0).InnerText, out dblValue)) { retElement.FloatValue = dblValue; return(retElement); } else { return(null); } } case FormElementTypes.Date: { string calendarType = map != null && map.ContainsKey("calendar_type") ? map["calendar_type"].ToString() : string.Empty; DateTime?dateValue = null; if (string.IsNullOrEmpty(calendarType) || calendarType.ToLower() == "jalali") { string[] parts = nodeList.Item(0).InnerText.Trim().Split('/'); int first = 0, second = 0, third = 0; if (parts.Length == 3 && int.TryParse(parts[0], out first) && int.TryParse(parts[1], out second) && int.TryParse(parts[2], out third)) { dateValue = PublicMethods.persian_to_gregorian_date(first, second, third, null, null, null); } } if (!dateValue.HasValue && parentMap != null) { int year = 0; if (int.TryParse(nodeList.Item(0).InnerText, out year) && year > 0) { dateValue = extract_date_from_parts(year, retElement.Name, parentNode, nsmgr, parentMap); } } if (dateValue.HasValue) { retElement.DateValue = dateValue; retElement.TextValue = PublicMethods.get_local_date(dateValue); return(retElement); } else { string strValue = nodeList.Item(0).InnerText.Trim(); if (!string.IsNullOrEmpty(strValue)) { retElement.TextValue = strValue; return(retElement); } else { return(null); } } } case FormElementTypes.File: { string strContent = nodeList.Item(0).InnerText.Trim(); DocFileInfo doc = DocumentUtilities.decode_base64_file_content(applicationId, retElement.ElementID, strContent, FileOwnerTypes.FormElement); if (doc != null && !string.IsNullOrEmpty(doc.FileName) && doc.Size.HasValue && doc.Size > 0) { retElement.AttachedFiles.Add(doc); } return(retElement.AttachedFiles.Count > 0 ? retElement : null); } case FormElementTypes.Form: { Dictionary <string, object> dic = PublicMethods.fromJSON(formElement.Info); Guid formId = Guid.Empty; if (!dic.ContainsKey("FormID") || map == null || !map.ContainsKey("sub") || map["sub"].GetType() != typeof(Dictionary <string, object>) || !Guid.TryParse(dic["FormID"].ToString(), out formId)) { return(null); } List <FormElement> elements = FGController.get_form_elements(applicationId, formId); if (elements == null || elements.Count == 0) { return(null); } Dictionary <string, object> subMap = (Dictionary <string, object>)map["sub"]; foreach (XmlNode node in nodeList) { Guid formInstanceId = Guid.NewGuid(); List <FormElement> subElements = new List <FormElement>(); foreach (string name in subMap.Keys) { List <FormElement> newElements = _parse_imported_form(applicationId, node, get_child_nodes(node, name, nsmgr), nsmgr, subMap[name], elements, subMap); if (newElements != null && newElements.Count > 0) { subElements.AddRange(newElements); } } if (subElements.Count == 0) { continue; } //add [national_id], [first_name], [last_name] & [full_name] elements that are empty List <string> strAll = new List <string>(); strAll.AddRange(StrNationalID); strAll.AddRange(StrFirstName); strAll.AddRange(StrLastName); strAll.AddRange(StrFullName); foreach (FormElement e in elements.Where(u => u.Type == FormElementTypes.Text && field_name_match(u.Name, strAll) && !subElements.Any(x => x.RefElementID == u.ElementID))) { subElements.Add(new FormElement() { ElementID = Guid.NewGuid(), RefElementID = e.ElementID, FormInstanceID = formInstanceId, Type = e.Type, SequenceNumber = e.SequenceNumber, Name = e.Name }); } //end of add [national_id], [first_name], [last_name] & [full_name] elements that are empty retElement.TableContent.Add(new FormType() { FormID = formId, InstanceID = formInstanceId, OwnerID = retElement.ElementID, Elements = subElements }); } return(retElement.TableContent.Count > 0 ? retElement : null); } default: return(null); } }
static void Main(string[] args) { List <Team> teams = new List <Team>(); int numOfTeams = int.Parse(Console.ReadLine()); for (int i = 0; i < numOfTeams; i++) { var info = Console.ReadLine().Split("-").ToArray(); string creator = info[0]; string teamName = info[1]; // Create a team if (teams.Any(x => x.Name == teamName)) { Console.WriteLine($"Team {teamName} was already created!"); continue; } if (teams.Any(x => x.Creator == creator)) { Console.WriteLine($"{creator} cannot create another team!"); continue; } Team team = new Team(teamName, creator); teams.Add(team); Console.WriteLine($"Team {teamName} has been created by {creator}!"); } string command = String.Empty; while ((command = Console.ReadLine()) != "end of assignment") { var info = command.Split("->").ToArray(); string person = info[0]; string teamName = info[1]; if (!teams.Any(x => x.Name == teamName)) { Console.WriteLine($"Team {teamName} does not exist!"); continue; } if (teams.Any(x => x.peopleJoined.Contains(person)) || teams.Any(x => x.Creator == person && x.Name == teamName)) { Console.WriteLine($"Member {person} cannot join team {teamName}!"); continue; } int index = teams.FindIndex(x => x.Name == teamName); teams[index].peopleJoined.Add(person); } var teamsToBeDisbanded = teams .FindAll(x => x.peopleJoined.Count == 0) .OrderBy(x => x.Name) .ToList(); foreach (var team in teams.Where(x => x.peopleJoined.Count > 0) .OrderByDescending(x => x.peopleJoined.Count) .ThenBy(x => x.Name)) { Console.WriteLine(team.ToString()); } Console.WriteLine("Teams to disband:"); foreach (var team in teamsToBeDisbanded) { Console.WriteLine(team.Name); } }
public void ContactSync(Logger Logger, IConfiguration config, IAuthenticationProvidor authProvidor, IAzureADFunctions azureAdFunctions, IOnPremADHelper onPremAdHelper, IOnPremAdFunctions onPremAdFunctions, ActiveDirectoryClient AzureClientSession) { //Get Entry into On-prem Active Directory Contacts OU. DirectoryEntry _OnPremContactsDirectoryEntry = onPremAdHelper.GetADDirectoryEntry(config.FQDomainName, config.ContactsDestinationOUDN, Logger); //Gather User Objects for the Work we intend to do later: Group _AzureUsersgroup = azureAdFunctions.GetADGroup(AzureClientSession, config.AzureADUserGroup, Logger); if (_AzureUsersgroup != null) { List <Tuple <string, IDirectoryObject> > _AzureGroupMembers = azureAdFunctions.GetAdGroupMembers(_AzureUsersgroup, config, Logger); if (_AzureGroupMembers.Any(members => members.Item1 == "user")) { List <IUser> _AzureGroupUsers = _AzureGroupMembers.Where(member => member.Item1.Equals("user")) .Select(member => member.Item2) .Select(member => member as IUser) .ToList(); List <DirectoryEntry> _OnPremContactObjects = onPremAdFunctions.GetOUContactObjects(config.FQDomainName, config.ContactsDestinationOUDN, onPremAdHelper, Logger); #region Add Contact Objects to AD Contacts OU //foreach user in Cloud check if they reside onprem and add them if they dont. if (config.AllowCreationOfADObjects) { Dictionary <string, IUser> azureUsers = _AzureGroupUsers.Where(x => x.Mail != null) .ToDictionary(x => x.Mail.ToLower(), x => x); foreach (string OnPremUser in _OnPremContactObjects.Where(x => x.Properties["Mail"].Value != null) .Select(x => x.Properties["Mail"].Value.ToString())) { azureUsers.Remove(OnPremUser.ToLower()); } int CreatedUsers = onPremAdFunctions.CreateADUserContacts(Logger, config, _OnPremContactsDirectoryEntry, onPremAdHelper, azureUsers); Logger.Debug(String.Format("Created {0} user(s) in On-Prem Active Directory", CreatedUsers.ToString())); Console.WriteLine("Created {0} user(s) in On-Prem Active Directory", CreatedUsers.ToString()); } #endregion #region Delete Contact Objects from AD OU //foreach user onprem check if they reside in cloud - delete them from AD if they dont (Make this over-rideable with a key) if (config.AllowDeletionOfADObjects) { Dictionary <string, DirectoryEntry> onpremUsers = _OnPremContactObjects.Where(y => y.Properties["Mail"].Value != null) .ToDictionary(y => y.Properties["Mail"].Value.ToString().ToLower(), y => y); foreach (string AzureUser in _AzureGroupUsers.Where(y => y.Mail != null) .Select(y => y.Mail.ToLower())) { onpremUsers.Remove(AzureUser.ToLower()); } int DeletedUsers = onPremAdFunctions.DeleteADContacts(Logger, config, _OnPremContactsDirectoryEntry, onpremUsers); Logger.Debug(String.Format("Deleted {0} user(s) in On-Prem Active Directory", DeletedUsers.ToString())); Console.WriteLine("Deleted {0} user(s) in On-Prem Active Directory", DeletedUsers.ToString()); } } else { Console.WriteLine("Could not find any USER objects in group {0}", config.AzureADUserGroup); Logger.Error(String.Format("Could not find any USER objects in group {0}", config.AzureADUserGroup)); } } else { Console.WriteLine("Could not find Group in Azure ({0} to enumerate users from", config.AzureADUserGroup); Logger.Error(String.Format("Could not find Group in Azure ({0} to enumerate users from", config.AzureADUserGroup)); } //Close AD Directory Entry Handle onPremAdHelper.DisposeADDirectoryEntry(_OnPremContactsDirectoryEntry, Logger); Console.WriteLine("Contact Creation/Deletion complete - Changes will be reflected on Office365 Sync on Next Dir-Sync Cycle but may not appear in Address book until the following day."); Logger.Debug(@"Contact Creation/Deletion complete - Changes will be reflected on Office365 upon next DirSync."); #endregion }
private static List <FormElement> _parse_imported_form(Guid applicationId, XmlNode parentNode, XmlNodeList nodeList, XmlNamespaceManager nsmgr, object mapEntry, List <FormElement> formElements, Dictionary <string, object> parentMap) { if (nodeList == null || nodeList.Count == 0) { return(new List <FormElement>()); } List <FormElement> retList = new List <FormElement>(); Type tp = mapEntry.GetType(); if (tp == typeof(Dictionary <string, object>)) { Dictionary <string, object> map = (Dictionary <string, object>)mapEntry; string target = map.ContainsKey("target") && formElements.Any(u => !string.IsNullOrEmpty(u.Name) && u.Name.ToLower() == map["target"].ToString().ToLower()) ? map["target"].ToString().ToLower() : string.Empty; if (!string.IsNullOrEmpty(target)) { FormElement elem = formElements.Where( u => !string.IsNullOrEmpty(u.Name) && u.Name.ToLower() == target).FirstOrDefault(); FormElement newElement = _extract_xml_node_data(applicationId, parentNode, nodeList, nsmgr, elem, map, parentMap); if (newElement != null) { retList.Add(newElement); } } else { Dictionary <string, object> subMap = map.ContainsKey("sub") && map["sub"].GetType() == typeof(Dictionary <string, object>) ? (Dictionary <string, object>)map["sub"] : null; if (subMap != null) { foreach (string name in subMap.Keys) { foreach (XmlNode nd in nodeList) { if (!string.IsNullOrEmpty(nd.Prefix)) { nsmgr.AddNamespace(nd.Prefix, nd.NamespaceURI); } List <FormElement> lst = _parse_imported_form(applicationId, nd, get_child_nodes(nd, name, nsmgr), nsmgr, subMap[name], formElements, subMap); if (lst != null && lst.Count > 0) { retList.AddRange(lst); } } } } } } else if (tp == typeof(string)) { FormElement elem = formElements .Where(u => !string.IsNullOrEmpty(u.Name) && u.Name.ToLower() == ((string)mapEntry).ToString().ToLower()).FirstOrDefault(); FormElement el = _extract_xml_node_data(applicationId, parentNode, nodeList, nsmgr, elem, null, parentMap); if (el != null) { retList.Add(el); } } return(retList); }
public bool MeesageParsing(string msgType, string msg_body, int msg_idnum) { bool result = false; try { #region Initialize values string[] msgBody; string[] rowLine; string header; EDI315 dbEDI315 = new EDI315(); EDI315_Detail dbEDI315_Detail = new EDI315_Detail(); List <EDI315_Detail_N9> dbEDI315_Detail_N9List = new List <EDI315_Detail_N9>(); List <EDI315_Detail_R4> dbEDI315_Detail_R4List = new List <EDI315_Detail_R4>(); List <EDI315_Detail_R4_DTM> dbEDI315_Detail_R4_DTMList = new List <EDI315_Detail_R4_DTM>(); int convertToInt = 0; decimal convertToDecimal = 0; #endregion msg_body = Regex.Replace(msg_body, @"^\s+$[\r\n]*", "", RegexOptions.Multiline); msgBody = msg_body.Split(new[] { Environment.NewLine }, StringSplitOptions.None); foreach (string row in msgBody) { if (row != null && row.Length > 0) { rowLine = row.Split('*'); header = ""; if (EDI315_HEADERS.Any(x => x.ToUpper() == rowLine[0])) { header = rowLine[0]; } switch (header) { case "ISA": #region ISA if (rowLine.Count() == 17) // header 1 + element 16 == 17 { dbEDI315 = new EDI315() { ISA_auth_info_qualifier = SubstringValue(rowLine[1] ?? "", 2), ISA_auth_info = SubstringValue(rowLine[2] ?? "", 10), ISA_security_info_qualifier = SubstringValue(rowLine[3] ?? "", 2), ISA_security_info = SubstringValue(rowLine[4] ?? "", 10), ISA_interchange_id_qualifier_1 = SubstringValue(rowLine[5] ?? "", 2), ISA_interchange_sender_id = SubstringValue(rowLine[6] ?? "", 15), ISA_interchange_id_qualifier_2 = SubstringValue(rowLine[7] ?? "", 2), ISA_interchange_receiver_id = SubstringValue(rowLine[8] ?? "", 15), ISA_interchage_date = SubstringValue(rowLine[9] ?? "", 8), ISA_interchange_time = SubstringValue(rowLine[10] ?? "", 4), ISA_interchange_control_standards_id = SubstringValue(rowLine[11] ?? "", 1), ISA_interchange_control_version_number = SubstringValue(rowLine[12] ?? "", 5), ISA_interchange_control_number = SubstringValue(rowLine[13] ?? "", 9), ISA_ack_requested = SubstringValue(rowLine[14] ?? "", 1), ISA_usage_indicator = SubstringValue(rowLine[15] ?? "", 1), ISA_component_element_separator = SubstringValue(rowLine[16] ?? "", 1), }; } else { throw new Exception("Mandatory elements are missing for " + header + ". " + header + " message line is \r\n" + row + "\r\n"); } #endregion break; case "GS": // insert DB #region GS if (rowLine.Count() == 9) // header 1 + element 8 == 9 { dbEDI315.GS_functional_id_code = SubstringValue(rowLine[1] ?? "", 2); dbEDI315.GS_app_sender_code = SubstringValue(rowLine[2] ?? "", 15); dbEDI315.GS_app_receiver_code = SubstringValue(rowLine[3] ?? "", 15); dbEDI315.GS_date = SubstringValue(rowLine[4] ?? "", 8); dbEDI315.GS_time = SubstringValue(rowLine[5] ?? "", 8); dbEDI315.GS_group_control_number = SubstringValue(rowLine[6] ?? "", 9); dbEDI315.GS_reponsible_agency_code = SubstringValue(rowLine[7] ?? "", 2); dbEDI315.GS_industry_id_code = SubstringValue(rowLine[8] ?? "", 12); /* Insert table EDI315 after done with ISA & GS */ if (msg_idnum != 0) { if (util.dbConnectionCheck()) { using (DBContext context = new DBContext()) { dbEDI315.msg_idnum = msg_idnum; dbEDI315.created_date = DateTime.Now; context.EDI315.Add(dbEDI315); context.SaveChanges(); /* DB context. END. */ context.Dispose(); } } else { string logMsg = "Date: " + DateTime.Now.ToString(); logMsg += "\r\nFunction: MeesageParsing - Table EDI315"; logMsg += "\r\nError Message: Not able to access DB. Process rollbacked."; logMsg += "\r\nValues Info:"; logMsg += "\r\nmstType: 315"; if (msg_idnum != 0) { logMsg += "\r\nmsg_idnum: " + msg_idnum; } if (dbEDI315.EDI315_idnum != 0) { logMsg += "\r\nEDI_idnum: " + dbEDI315.EDI315_idnum; } util.insertLog_TextFile(msgType, msg_idnum, dbEDI315.EDI315_idnum, 0, logMsg); rollbackProcess(msg_idnum, msgType); return(false); } } } else { throw new Exception("Mandatory elements are missing for " + header + ". " + header + " message line is \r\n" + row + "\r\n"); } #endregion break; case "ST": #region ST /* Detail start. Init. */ dbEDI315_Detail = new EDI315_Detail(); dbEDI315_Detail_N9List = new List <EDI315_Detail_N9>(); dbEDI315_Detail_R4List = new List <EDI315_Detail_R4>(); dbEDI315_Detail_R4_DTMList = new List <EDI315_Detail_R4_DTM>(); #endregion break; case "SE": /* Detail End. Insert into Tables. */ #region SE if (dbEDI315 == null || dbEDI315.EDI315_idnum == 0) { return(result); } if (rowLine.Count() > 2) { convertToInt = 0; if (rowLine[1] != null && rowLine[1].Trim() != string.Empty && Int32.TryParse(rowLine[1], out convertToInt)) { dbEDI315_Detail.SE_included_segments_number = convertToInt; } dbEDI315_Detail.SE_transaction_set_control_number = SubstringValue(rowLine[2] ?? "", 9); /* insert Table EDI315_Detail, EDI315_Detail_N9, EDI315_Detail_R4 & EDI315_Detail_R4_DTM */ if (util.dbConnectionCheck()) { using (DBContext context = new DBContext()) { /* EDI315_Detail Insert */ dbEDI315_Detail.msg_idnum = msg_idnum; dbEDI315_Detail.EDI315_idnum = dbEDI315.EDI315_idnum; context.EDI315_Detail.Add(dbEDI315_Detail); context.SaveChanges(); /* EDI315_Detail_N9 Insert */ foreach (EDI315_Detail_N9 dbN9Row in dbEDI315_Detail_N9List) { dbN9Row.msg_idnum = msg_idnum; dbN9Row.EDI315_Detail_idnum = dbEDI315_Detail.EDI315_Detail_idnum; } context.EDI315_Detail_N9.AddRange(dbEDI315_Detail_N9List); context.SaveChanges(); /* EDI315_Detail_R4 & EDI315_Detail_R4_DTM Insert */ foreach (EDI315_Detail_R4 dbR4Row in dbEDI315_Detail_R4List) { List <EDI315_Detail_R4_DTM> dtmList = dbEDI315_Detail_R4_DTMList.Where(x => x.Detail_R4_idnum == dbR4Row.Detail_R4_idnum).ToList(); dbR4Row.msg_idnum = msg_idnum; dbR4Row.EDI315_Detail_idnum = dbEDI315_Detail.EDI315_Detail_idnum; context.EDI315_Detail_R4.Add(dbR4Row); context.SaveChanges(); if (dtmList != null && dtmList.Count() > 0) { foreach (EDI315_Detail_R4_DTM dtmRow in dtmList) { dtmRow.msg_idnum = msg_idnum; dtmRow.Detail_R4_idnum = dbR4Row.Detail_R4_idnum; } context.EDI315_Detail_R4_DTM.AddRange(dtmList); context.SaveChanges(); } } /* DB context. END. */ context.Dispose(); } } else { string logMsg = "Date: " + DateTime.Now.ToString(); logMsg += "\r\nFunction: MeesageParsing - Table EDI315_Detail, EDI315_Detail_N9, EDI315_Detail_R4, EDI315_Detail_R4_DTM"; logMsg += "\r\nError Message: Not able to access DB. Process rollbacked."; logMsg += "\r\nValues Info:"; logMsg += "\r\nmstType: 315"; if (msg_idnum != 0) { logMsg += "\r\nmsg_idnum: " + msg_idnum; } if (dbEDI315.EDI315_idnum != 0) { logMsg += "\r\nEDI_idnum: " + dbEDI315.EDI315_idnum; } if (dbEDI315_Detail.EDI315_Detail_idnum != 0) { logMsg += "\r\nDetail_idnum: " + dbEDI315_Detail.EDI315_Detail_idnum; } util.insertLog_TextFile(msgType, msg_idnum, dbEDI315.EDI315_idnum, dbEDI315_Detail.EDI315_Detail_idnum, logMsg); rollbackProcess(msg_idnum, msgType); return(false); } } else { throw new Exception("Mandatory elements are missing for " + header + ". " + header + " message line is \r\n" + row + "\r\n"); } #endregion break; case "B4": #region B4 if (dbEDI315 == null || dbEDI315.EDI315_idnum == 0) { return(result); } if (rowLine.Count() > 6) { dbEDI315_Detail.B4_SHC = SubstringValue(rowLine[1], 3); convertToInt = 0; if (rowLine[2] != null && rowLine[2].Trim() != string.Empty && Int32.TryParse(rowLine[2], out convertToInt)) { dbEDI315_Detail.B4_request_number = convertToInt; } dbEDI315_Detail.B4_status_code = SubstringValue(rowLine[3], 2); dbEDI315_Detail.B4_date = SubstringValue(rowLine[4] ?? "", 8); dbEDI315_Detail.B4_status_time = SubstringValue(rowLine[5] ?? "", 4); dbEDI315_Detail.B4_status_location = SubstringValue(rowLine[6] ?? "", 5); if (rowLine.Count() > 7) { dbEDI315_Detail.B4_equip_initial = SubstringValue(rowLine[7], 4); } if (rowLine.Count() > 8) { dbEDI315_Detail.B4_equip_number = SubstringValue(rowLine[8], 10); } if (rowLine.Count() > 9) { dbEDI315_Detail.B4_equip_status_code = SubstringValue(rowLine[9], 2); } if (rowLine.Count() > 10) { dbEDI315_Detail.B4_equip_type = SubstringValue(rowLine[10], 4); } if (rowLine.Count() > 11) { dbEDI315_Detail.B4_location_code = SubstringValue(rowLine[11], 30); } if (rowLine.Count() > 12) { dbEDI315_Detail.B4_location_id = SubstringValue(rowLine[12], 2); } if (rowLine.Count() > 13) { convertToInt = 0; if (rowLine[13] != null && rowLine[13].Trim() != string.Empty && Int32.TryParse(rowLine[13], out convertToInt)) { dbEDI315_Detail.B4_equip_check_digit = convertToInt; } } } else { throw new Exception("Mandatory elements are missing for " + header + ". " + header + " message line is \r\n" + row + "\r\n"); } #endregion break; case "Q2": #region Q2 if (dbEDI315 == null || dbEDI315.EDI315_idnum == 0) { return(result); } dbEDI315_Detail.Q2_vessel_code = SubstringValue(rowLine[1], 8); dbEDI315_Detail.Q2_country_code = SubstringValue(rowLine[2], 3); dbEDI315_Detail.Q2_date_1 = SubstringValue(rowLine[3], 8); dbEDI315_Detail.Q2_date_2 = SubstringValue(rowLine[4], 8); dbEDI315_Detail.Q2_date_3 = SubstringValue(rowLine[5], 8); convertToInt = 0; if (rowLine[6] != null && rowLine[6].Trim() != string.Empty && Int32.TryParse(rowLine[6], out convertToInt)) { dbEDI315_Detail.Q2_lading_quantity = convertToInt; } convertToDecimal = 0; if (rowLine[7] != null && rowLine[7].Trim() != string.Empty && Decimal.TryParse(rowLine[7], out convertToDecimal)) { dbEDI315_Detail.Q2_weight = convertToDecimal; } dbEDI315_Detail.Q2_weight_qualifier = SubstringValue(rowLine[8], 2); dbEDI315_Detail.Q2_voyage_number = SubstringValue(rowLine[9], 10); dbEDI315_Detail.Q2_reference_id_qualifier = SubstringValue(rowLine[10], 3); dbEDI315_Detail.Q2_reference_id = SubstringValue(rowLine[11], 30); dbEDI315_Detail.Q2_vessel_code_qualifier = SubstringValue(rowLine[12], 1); dbEDI315_Detail.Q2_vessel_name = SubstringValue(rowLine[13], 28); convertToDecimal = 0; if (rowLine[14] != null && rowLine[14].Trim() != string.Empty && Decimal.TryParse(rowLine[14], out convertToDecimal)) { dbEDI315_Detail.Q2_volume = convertToDecimal; } dbEDI315_Detail.Q2_volume_unit_qualifier = SubstringValue(rowLine[15], 1); dbEDI315_Detail.Q2_weight_unit_code = SubstringValue(rowLine[16], 1); #endregion break; case "N9": #region N9 if (dbEDI315 == null || dbEDI315.EDI315_idnum == 0) { return(result); } { EDI315_Detail_N9 dbTemp = new EDI315_Detail_N9(); dbTemp.reference_id_qualifier = SubstringValue(rowLine[1] ?? "", 3); if (rowLine.Count() > 2) { dbTemp.reference_id = SubstringValue(rowLine[2], 30); } if (rowLine.Count() > 3) { dbTemp.free_form_description = SubstringValue(rowLine[3], 45); } if (rowLine.Count() > 4) { dbTemp.date = SubstringValue(rowLine[4], 8); } if (rowLine.Count() > 5) { dbTemp.time = SubstringValue(rowLine[5], 8); } if (rowLine.Count() > 6) { dbTemp.time_code = SubstringValue(rowLine[6], 2); } dbEDI315_Detail_N9List.Add(dbTemp); } #endregion break; case "R4": #region R4 if (dbEDI315 == null || dbEDI315.EDI315_idnum == 0) { return(result); } { EDI315_Detail_R4 dbTemp = new EDI315_Detail_R4(); dbTemp.Detail_R4_idnum = dbEDI315_Detail_R4List.Count() + 1; dbTemp.port_function_code = SubstringValue(rowLine[1] ?? "", 1); if (rowLine.Count() > 2) { dbTemp.location_qualifier = SubstringValue(rowLine[2], 2); } if (rowLine.Count() > 3) { dbTemp.location_id = SubstringValue(rowLine[3], 30); } if (rowLine.Count() > 4) { dbTemp.port_name = SubstringValue(rowLine[4], 24); } if (rowLine.Count() > 5) { dbTemp.country_code = SubstringValue(rowLine[5], 3); } if (rowLine.Count() > 6) { dbTemp.terminal_name = SubstringValue(rowLine[6], 30); } if (rowLine.Count() > 7) { dbTemp.pier_number = SubstringValue(rowLine[7], 4); } if (rowLine.Count() > 8) { dbTemp.province_code = SubstringValue(rowLine[8], 2); } dbEDI315_Detail_R4List.Add(dbTemp); } #endregion break; case "DTM": #region DTM if (dbEDI315 == null || dbEDI315.EDI315_idnum == 0) { return(result); } { if (dbEDI315_Detail_R4List.Count() > 9) { EDI315_Detail_R4_DTM dbTemp = new EDI315_Detail_R4_DTM(); } dbTemp.Detail_R4_idnum = dbEDI315_Detail_R4List.Count(); if (rowLine.Count() > 1) { dbTemp.datetime_qualifier = SubstringValue(rowLine[1] ?? "", 3); } if (rowLine.Count() > 2) { dbTemp.date = SubstringValue(rowLine[2], 8); } if (rowLine.Count() > 3) { dbTemp.time = SubstringValue(rowLine[3], 4); } if (rowLine.Count() > 4) { dbTemp.time_code = SubstringValue(rowLine[4], 2); } dbEDI315_Detail_R4_DTMList.Add(dbTemp); } #endregion break; } } } result = true; } catch (DbEntityValidationException ex) { #region Exception string logMsg = "Date: " + DateTime.Now.ToString(); logMsg += "\r\nFunction: MeesageParsing"; logMsg += "\r\nProcess rollbacked."; logMsg += "\r\nError Message: "; foreach (DbEntityValidationResult item in ex.EntityValidationErrors) { // Get entry DbEntityEntry entry = item.Entry; string entityTypeName = entry.Entity.GetType().Name; foreach (DbValidationError subItem in item.ValidationErrors) { logMsg += string.Format("\r\nError '{0}' occurred in {1} at {2}", subItem.ErrorMessage, entityTypeName, subItem.PropertyName); } } util.insertLog(msgType, msg_idnum, 0, 0, logMsg); rollbackProcess(msg_idnum, msgType); result = false; #endregion } catch (Exception ex) { #region Exception string logMsg = "Date: " + DateTime.Now.ToString(); logMsg += "\r\nFunction: MeesageParsing"; logMsg += "\r\nProcess rollbacked."; logMsg += "\r\nError Message:\r\n" + ex.ToString(); util.insertLog(msgType, msg_idnum, 0, 0, logMsg); rollbackProcess(msg_idnum, msgType); result = false; #endregion } return(result); }
/// <summary> /// Handles the Click event of the lbSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbSave_Click(object sender, EventArgs e) { var rockContext = new RockContext(); rockContext.WrapTransaction(() => { var personService = new PersonService(rockContext); var changes = new List <string>(); Person business = null; if (int.Parse(hfBusinessId.Value) != 0) { business = personService.Get(int.Parse(hfBusinessId.Value)); } if (business == null) { business = new Person(); personService.Add(business); } // Business Name History.EvaluateChange(changes, "Last Name", business.LastName, tbBusinessName.Text); business.LastName = tbBusinessName.Text; // Phone Number var businessPhoneTypeId = new DefinedValueService(rockContext).GetByGuid(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK)).Id; string oldPhoneNumber = string.Empty; string newPhoneNumber = string.Empty; var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == businessPhoneTypeId); if (phoneNumber != null) { oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode; } if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number))) { if (phoneNumber == null) { phoneNumber = new PhoneNumber { NumberTypeValueId = businessPhoneTypeId }; business.PhoneNumbers.Add(phoneNumber); } phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode); phoneNumber.Number = PhoneNumber.CleanNumber(pnbPhone.Number); phoneNumber.IsMessagingEnabled = cbSms.Checked; phoneNumber.IsUnlisted = cbUnlisted.Checked; newPhoneNumber = phoneNumber.NumberFormattedWithCountryCode; } else { if (phoneNumber != null) { business.PhoneNumbers.Remove(phoneNumber); new PhoneNumberService(rockContext).Delete(phoneNumber); } } History.EvaluateChange( changes, string.Format("{0} Phone", DefinedValueCache.GetName(businessPhoneTypeId)), oldPhoneNumber, newPhoneNumber); // Record Type - this is always "business". it will never change. business.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id; // Record Status int?newRecordStatusId = ddlRecordStatus.SelectedValueAsInt(); History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(business.RecordStatusValueId), DefinedValueCache.GetName(newRecordStatusId)); business.RecordStatusValueId = newRecordStatusId; // Record Status Reason int?newRecordStatusReasonId = null; if (business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id) { newRecordStatusReasonId = ddlReason.SelectedValueAsInt(); } History.EvaluateChange(changes, "Record Status Reason", DefinedValueCache.GetName(business.RecordStatusReasonValueId), DefinedValueCache.GetName(newRecordStatusReasonId)); business.RecordStatusReasonValueId = newRecordStatusReasonId; // Email business.IsEmailActive = true; History.EvaluateChange(changes, "Email", business.Email, tbEmail.Text); business.Email = tbEmail.Text.Trim(); var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>(); History.EvaluateChange(changes, "EmailPreference", business.EmailPreference, newEmailPreference); business.EmailPreference = newEmailPreference; if (business.IsValid) { if (rockContext.SaveChanges() > 0) { if (changes.Any()) { HistoryService.SaveChanges( rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), business.Id, changes); } } } // Add/Update Family Group var familyGroupType = GroupTypeCache.GetFamilyGroupType(); int adultRoleId = familyGroupType.Roles .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid())) .Select(r => r.Id) .FirstOrDefault(); var adultFamilyMember = UpdateGroupMember(business.Id, familyGroupType, business.LastName + " Business", ddlCampus.SelectedValueAsInt(), adultRoleId, rockContext); business.GivingGroup = adultFamilyMember.Group; // Add/Update Known Relationship Group Type var knownRelationshipGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid()); int knownRelationshipOwnerRoleId = knownRelationshipGroupType.Roles .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid())) .Select(r => r.Id) .FirstOrDefault(); var knownRelationshipOwner = UpdateGroupMember(business.Id, knownRelationshipGroupType, "Known Relationship", null, knownRelationshipOwnerRoleId, rockContext); // Add/Update Implied Relationship Group Type var impliedRelationshipGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS.AsGuid()); int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_IMPLIED_RELATIONSHIPS_OWNER.AsGuid())) .Select(r => r.Id) .FirstOrDefault(); var impliedRelationshipOwner = UpdateGroupMember(business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext); rockContext.SaveChanges(); // Location int workLocationTypeId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK).Id; var groupLocationService = new GroupLocationService(rockContext); var workLocation = groupLocationService.Queryable("Location") .Where(gl => gl.GroupId == adultFamilyMember.Group.Id && gl.GroupLocationTypeValueId == workLocationTypeId) .FirstOrDefault(); if (string.IsNullOrWhiteSpace(acAddress.Street1)) { if (workLocation != null) { groupLocationService.Delete(workLocation); History.EvaluateChange(changes, "Address", workLocation.Location.ToString(), string.Empty); } } else { var oldValue = string.Empty; var newLocation = new LocationService(rockContext).Get( acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country); if (workLocation != null) { oldValue = workLocation.Location.ToString(); } else { workLocation = new GroupLocation(); groupLocationService.Add(workLocation); workLocation.GroupId = adultFamilyMember.Group.Id; workLocation.GroupLocationTypeValueId = workLocationTypeId; } workLocation.Location = newLocation; workLocation.IsMailingLocation = true; History.EvaluateChange(changes, "Address", oldValue, newLocation.ToString()); } rockContext.SaveChanges(); hfBusinessId.Value = business.Id.ToString(); }); ShowSummary(hfBusinessId.Value.AsInteger()); }
public void ResolveOrder(Actor self, Order order) { if (!Enabled) { return; } var rules = self.World.Map.Rules; switch (order.OrderString) { case "StartProduction": var unit = rules.Actors[order.TargetString]; var bi = unit.TraitInfo <BuildableInfo>(); // Not built by this queue if (!bi.Queue.Contains(Info.Type)) { return; } // You can't build that if (BuildableItems().All(b => b.Name != order.TargetString)) { return; } // Check if the player is trying to build more units that they are allowed var fromLimit = int.MaxValue; if (!developerMode.AllTech) { if (Info.QueueLimit > 0) { fromLimit = Info.QueueLimit - Queue.Count; } if (Info.ItemLimit > 0) { fromLimit = Math.Min(fromLimit, Info.ItemLimit - Queue.Count(i => i.Item == order.TargetString)); } if (bi.BuildLimit > 0) { var inQueue = Queue.Count(pi => pi.Item == order.TargetString); var owned = self.Owner.World.ActorsHavingTrait <Buildable>().Count(a => a.Info.Name == order.TargetString && a.Owner == self.Owner); fromLimit = Math.Min(fromLimit, bi.BuildLimit - (inQueue + owned)); } if (fromLimit <= 0) { return; } } var cost = GetProductionCost(unit); var time = GetBuildTime(unit, bi); var amountToBuild = Math.Min(fromLimit, order.ExtraData); for (var n = 0; n < amountToBuild; n++) { var hasPlayedSound = false; BeginProduction(new ProductionItem(this, order.TargetString, cost, playerPower, () => self.World.AddFrameEndTask(_ => { // Make sure the item hasn't been invalidated between the ProductionItem ticking and this FrameEndTask running if (!Queue.Any(i => i.Done && i.Item == unit.Name)) { return; } var isBuilding = unit.HasTraitInfo <BuildingInfo>(); if (isBuilding && !hasPlayedSound) { hasPlayedSound = Game.Sound.PlayNotification(rules, self.Owner, "Speech", Info.ReadyAudio, self.Owner.Faction.InternalName); TextNotificationsManager.AddTransientLine(Info.ReadyTextNotification, self.Owner); } else if (!isBuilding) { if (BuildUnit(unit)) { Game.Sound.PlayNotification(rules, self.Owner, "Speech", Info.ReadyAudio, self.Owner.Faction.InternalName); TextNotificationsManager.AddTransientLine(Info.ReadyTextNotification, self.Owner); } else if (!hasPlayedSound && time > 0) { hasPlayedSound = Game.Sound.PlayNotification(rules, self.Owner, "Speech", Info.BlockedAudio, self.Owner.Faction.InternalName); TextNotificationsManager.AddTransientLine(Info.BlockedTextNotification, self.Owner); } } })), !order.Queued); } break; case "PauseProduction": PauseProduction(order.TargetString, order.ExtraData != 0); break; case "CancelProduction": CancelProduction(order.TargetString, order.ExtraData); break; } }
/// <summary>Returns the node that need to be followed in order to reach the destination. Currently only works /// on a Grid, without costs associated with the movements.</summary> // This method is actually faster than the one above, even though it should not be. Might have to looks at some // of the algorithm to improve performance. public List <GridNodeAStar> GetAStarNodesWithList(string originId, string targetId) { var origin = GetNode(originId); var target = GetNode(targetId); var openSet = new List <GridNodeAStar>(); var closedSet = new HashSet <GridNodeAStar>(); var aStarOrigin = new GridNodeAStar(origin, origin, target); openSet.Add(aStarOrigin); while (openSet.Any()) { var currentNode = openSet[0]; for (var i = 1; i < openSet.Count; i++) { if (openSet[i].FCost < currentNode.FCost || openSet[i].FCost == currentNode.FCost && openSet[i].HCost < currentNode.HCost) { currentNode = openSet[i]; } } openSet.Remove(currentNode); closedSet.Add(currentNode); if (currentNode.Id == target.Id) { // Found the target node. Retracing steps. var path = new List <GridNodeAStar>(); var pathPosition = currentNode; while (pathPosition.Id != origin.Id) { path.Add(pathPosition); pathPosition = pathPosition.Parent; } path.Reverse(); return(path); } foreach (var neighbour in GetNeighbours(currentNode).Select(node => new GridNodeAStar(node, origin, target))) { if (closedSet.FirstOrDefault(node => node.Id == neighbour.Id) != null) { continue; } var newMovementCostToNeighbour = currentNode.GCost + Trigonometry.GetGridDistance( new Point(currentNode.X, currentNode.Y), new Point(neighbour.X, neighbour.Y)); var neighbourInOpenSet = openSet.FirstOrDefault(node => node.Id == neighbour.Id); if (neighbourInOpenSet == null) { // Neighbour has not been analyzed yet, so we are generating the costs and adding to open set. neighbour.GCost = newMovementCostToNeighbour; neighbour.HCost = Trigonometry.GetGridDistance( new Point(neighbour.X, neighbour.Y), new Point(target.X, target.Y)); neighbour.Parent = currentNode; openSet.Add(neighbour); } if (neighbourInOpenSet != null && newMovementCostToNeighbour > neighbourInOpenSet.GCost) { // Neighbour already exists in open set, but the new movement cost is cheaper, so we're updating it. neighbourInOpenSet.GCost = newMovementCostToNeighbour; neighbourInOpenSet.HCost = Trigonometry.GetDistance( new Point(neighbourInOpenSet.X, neighbourInOpenSet.Y), new Point(target.X, target.Y)); neighbourInOpenSet.Parent = currentNode; } } } return(new List <GridNodeAStar>()); }
private void StepFour_RetrieveDeviceList() { logger.Trace("Start StepFour_RetrieveDeviceList."); txtXDaggerWalletAddress.Text = ManagerConfig.Current.DefaultXDagger.WalletAddress; txtXDaggerPoolAddress.Text = ManagerConfig.Current.DefaultXDagger.PoolAddress; txtWalletAddressEth.Text = ManagerConfig.Current.DefaultEth.WalletAddress; txtEmailAddressEth.Text = ManagerConfig.Current.DefaultEth.EmailAddress; txtEthWorkerName.Text = ManagerConfig.Current.DefaultEth.WorkerName; if (ManagerConfig.Current.DefaultEth.PoolIndex != null) { cbxTargetEthPool.SelectedIndex = ManagerConfig.Current.DefaultEth.PoolIndex.GetHashCode(); } if (ManagerConfig.Current.DefaultEth.PoolHostIndex != null) { cbxTargetEthPoolHost.SelectedIndex = ManagerConfig.Current.DefaultEth.PoolHostIndex.Value; } BackgroundWork.CreateWork( this, () => { ShowProgressIndicator("正在获取硬件信息...", btnStepFourXDaggerNext, btnStepFourXDaggerBack); }, () => { StepFour_RetrieveDeviceList_Sync(); return(0); }, (taskResult) => { HideProgressIndicator(); if (taskResult.HasError) { logger.Error("ExecuteCommand failed: " + taskResult.Exception.ToString()); } displayeDeviceList = new List <MinerDevice>(); displayeDeviceList.AddRange(createdClients.First().Machine.Devices); foreach (MinerClient client in createdClients) { // Note: If a machine has null devices, we consider there is temporary issue while retrieving devices so ignore it List <MinerDevice> machineDevices = client.Machine.Devices; if (machineDevices == null) { continue; } for (int i = displayeDeviceList.Count - 1; i >= 0; i--) { if (!machineDevices.Any(device => device.DisplayName.Equals(displayeDeviceList[i].DisplayName))) { displayeDeviceList.RemoveAt(i); } } } if (displayeDeviceList.Count == 0) { MessageBox.Show("没有找到在所选择机器上共有的硬件,请检查目标机器配置"); logger.Warning("没有找到在所选择机器上共有的硬件,请检查目标机器配置"); return; } cbxTargetDevice.Items.Clear(); cbxTargetDeviceEth.Items.Clear(); logger.Trace("Got Devices count: " + displayeDeviceList.Count); foreach (MinerDevice device in displayeDeviceList) { cbxTargetDevice.Items.Add(device.DisplayName); cbxTargetDeviceEth.Items.Add(device.DisplayName); } } ).Execute(); }
public ActionResult<GenericValidator> ExportLineList([FromBody] QueryModel query) { var gVal = new GenericValidator(); try { var comlumHeadrs = new string[] { "Client Id", "Gender", "Age(yrs)", "Preg.", "Art Date", "First Regimen", "First Regimen Line", "Current Visit Date", "Current Viral Load Sample Date", "Current Viral Load Result", "Current Regimen", "Current Regimen Line" }; var user = HttpContext.Session.GetObjectFromJson<UserModel>("_user"); if (user == null) { gVal.Code = -1; gVal.Message = "You need to login or contact the Admin to get an account."; return gVal; } string sWebRootFolder = _hostingEnvironment.WebRootPath; var excelName = $"linelist-{user.Id.Replace("-", string.Empty)}.xlsx"; string URL = string.Format("{0}://{1}/{2}/{3}", Request.Scheme, Request.Host, "Exports", excelName); var exports = Path.Combine(sWebRootFolder, "Exports"); if (!Directory.Exists(exports)) { var directory = Directory.CreateDirectory(exports); // Get a DirectorySecurity object that represents the // current security settings. var dSecurity = directory.GetAccessControl(); // Add the FileSystemAccessRule to the security settings. dSecurity.AddAccessRule( new FileSystemAccessRule( new System.Security.Principal.SecurityIdentifier( System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null ), FileSystemRights.FullControl, AccessControlType.Allow ) ); // Set the new access settings. directory.SetAccessControl(dSecurity); } var path = Path.Combine(sWebRootFolder, "Exports", excelName); var file = new FileInfo(path); if (file.Exists) { file.Delete(); } using (var package = new ExcelPackage(file)) { // add a new worksheet to the empty workbook var worksheet = package.Workbook.Worksheets.Add("Line List"); //Worksheet name using (var cells = worksheet.Cells["A1:O1"]) //(1,1) (1,5) { cells.Merge = true; cells.Style.WrapText = true; cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center; cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; cells.Value = query.Header + ": " + Convert.ToDateTime(query.From).ToShortDateString() + " - " + Convert.ToDateTime(query.To).ToShortDateString(); cells.Style.Font.Bold = true; } using (var cells = worksheet.Cells["A3:M3"]) { cells.Style.Font.Bold = true; } //First add the headers for (var i = 0; i < comlumHeadrs.Count(); i++) { worksheet.Cells[3, i + 1].Value = comlumHeadrs[i]; } // result = package.GetAsByteArray(); package.Save(); } regimens = _regimenService.GetAllRegimens(); if (!regimens.Any()) { gVal.Code = -1; gVal.Message = "An error was encountered. Please contact the Admin to set up list of ARV Regimen"; return gVal; } var status = ProcessLists(path, 4, query); if(status > 0) { gVal.Code = status; gVal.Message = "File was successfully generated"; // gVal.Asset = excelName; gVal.Asset = URL; gVal.FileName = excelName; return gVal; } gVal.Code = -5; gVal.Message = "Query export failed. Please try again later"; gVal.Asset = ""; return gVal; } catch (Exception e) { return gVal; } }
public string AddAccount(string name, string pass, string per) { User A = new User(); A.Password = pass; A.Status = 1; A.Username = name; string[] Access = per.Split('#'); //List<Screen> LOUA = new List<Screen>(); List <UserAccess> LOUA = new List <UserAccess>(); foreach (string AP in Access) { if (LOUA.Any(p => p.ScreenID == Convert.ToInt32(AP.Replace("Opt1", "").Replace("Show", "").Replace("Edit", "").Replace("Delete", "")))) { var UA = LOUA.Where(p => p.ScreenID == Convert.ToInt32(AP.Replace("Opt1", "").Replace("Show", "").Replace("Edit", "").Replace("Delete", ""))).SingleOrDefault(); if (AP.Contains("Opt1")) { UA.ScreenID = int.Parse(AP.Replace("Opt1", "")); UA.Opt1 = true; LOUA.Add(UA); } else if (AP.Contains("Show")) { UA.ScreenID = int.Parse(AP.Replace("Show", "")); foreach (string item in Access.Where(p => p.Contains(UA.ScreenID.ToString())).ToList()) { if (item.Contains("Opt1")) { UA.Opt1 = true; } if (item.Contains("Edit")) { UA.CanEdit = true; } if (item.Contains("Delete")) { UA.CanDelete = true; } } LOUA.Add(UA); } else { if (AP.Contains("Edit")) { UA.ScreenID = int.Parse(AP.Replace("Edit", "")); UA.CanEdit = true; } else if (AP.Contains("Delete")) { UA.ScreenID = int.Parse(AP.Replace("Delete", "")); UA.CanDelete = true; } else { UA.ScreenID = int.Parse(AP); } LOUA.Add(UA); } } else { if (AP.Contains("Opt1")) { UserAccess UA = new UserAccess(); UA.ScreenID = int.Parse(AP.Replace("Opt1", "")); UA.Opt1 = true; LOUA.Add(UA); } else if (AP.Contains("Show")) { UserAccess UA = new UserAccess(); UA.ScreenID = int.Parse(AP.Replace("Show", "")); foreach (string item in Access.Where(p => p.Contains(UA.ScreenID.ToString())).ToList()) { if (item.Contains("Opt1")) { UA.Opt1 = true; } if (item.Contains("Edit")) { UA.CanEdit = true; } if (item.Contains("Delete")) { UA.CanDelete = true; } } LOUA.Add(UA); } else { UserAccess UA = new UserAccess(); if (AP.Contains("Edit")) { UA.ScreenID = int.Parse(AP.Replace("Edit", "")); UA.CanEdit = true; } else if (AP.Contains("Delete")) { UA.ScreenID = int.Parse(AP.Replace("Delete", "")); UA.CanDelete = true; } else { UA.ScreenID = int.Parse(AP); } LOUA.Add(UA); } } } Returner R = A.CreateAccount(LOUA); if (R.Message == Message.Username_Already_Exists) { return("false"); } else { return("true"); } }
private void btnStepOneNext_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(txtTargetPath.Text)) { MessageBox.Show("请输入安装矿机的有效路径", "提示"); return; } deploymentFolderPath = txtTargetPath.Text.Trim(); List <MinerMachine> machineList = dataGridMachines.GetAllMachines(); if (machineList.Count == 0) { MessageBox.Show("请输入机器名称", "提示"); return; } if ((machineList.Count > 1 || !machineList[0].IsLocalMachine()) && string.IsNullOrWhiteSpace(txtTargetUserName.Text)) { MessageBox.Show("请填写用于连接目标机器的用户名和密码信息", "提示"); return; } if (!string.IsNullOrWhiteSpace(txtTargetUserName.Text)) { string username = txtTargetUserName.Text.Trim(); if (string.IsNullOrEmpty(txtTargetUserPassword.Password)) { MessageBox.Show("请输入用户的密码", "提示"); return; } string password = txtTargetUserPassword.Password.Trim(); MachineCredential credential = new MachineCredential() { UserName = username, LoginPlainPassword = password }; // Consolidate the credentials foreach (MinerMachine m in machineList) { m.Credential = credential; } } createdClients.Clear(); for (int i = machineConnectivityCache.Count - 1; i >= 0; i--) { MachineConnectivity connectivity = machineConnectivityCache[i]; if (!machineList.Any(m => m.FullName.Equals(connectivity.Machine.FullName))) { machineConnectivityCache.RemoveAt(i); } } foreach (MinerMachine machine in machineList) { createdClients.Add(new MinerClient(machine, deploymentFolderPath)); if (!machineConnectivityCache.Any(conn => conn.Machine.FullName.Equals(machine.FullName))) { machineConnectivityCache.Add(new MachineConnectivity(machine)); } } SwitchUIToStep(2); }
public override void OnGUI(Rect rect) { if (elements == null) { return; } using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar, GUILayout.Height(12f))) { if (MasterController.CanEdit) { if (GUILayout.Button(toolbarPlusIcon, EditorStyles.toolbarButton, GUILayout.Width(25f))) { elements.Add(elementType.GetDefaultValue()); OnUpdateElements(); } } } using (var scrollViewScope = new EditorGUILayout.ScrollViewScope(scrollPosition)) { var removeIndexs = new List <int>(); for (var i = 0; i < elements.Count; i++) { using (new EditorGUILayout.HorizontalScope()) { EditorGUI.BeginChangeCheck(); var fieldRect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight); elements[i] = EditorRecordFieldUtility.DrawField(fieldRect, elements[i], elementType); if (EditorGUI.EndChangeCheck() && MasterController.CanEdit) { OnUpdateElements(); } if (MasterController.CanEdit) { if (GUILayout.Button(toolbarMinusIcon, EditorStyles.miniButton, GUILayout.Width(25f))) { removeIndexs.Add(i); } } } } if (removeIndexs.Any()) { foreach (var removeIndex in removeIndexs) { elements.RemoveAt(removeIndex); } OnUpdateElements(); } scrollPosition = scrollViewScope.scrollPosition; } }
public string UpdateUser(string name, string pass, string per) { string[] Access = per.Split('#'); //List<Screen> LOUA = new List<Screen>(); List <UserAccess> LOUA = new List <UserAccess>(); foreach (string AP in Access) { if (LOUA.Any(p => p.ScreenID == Convert.ToInt32(AP.Replace("Opt1", "").Replace("Show", "").Replace("Edit", "").Replace("Delete", "")))) { var UA = LOUA.Where(p => p.ScreenID == Convert.ToInt32(AP.Replace("Opt1", "").Replace("Show", "").Replace("Edit", "").Replace("Delete", ""))).FirstOrDefault(); if (AP.Contains("Opt1")) { UA.ScreenID = int.Parse(AP.Replace("Opt1", "")); UA.Opt1 = true; LOUA.Add(UA); } else if (AP.Contains("Show")) { UA.ScreenID = int.Parse(AP.Replace("Show", "")); foreach (string item in Access.Where(p => p.Contains(UA.ScreenID.ToString())).ToList()) { if (item.Contains("Opt1")) { UA.Opt1 = true; } if (item.Contains("Edit")) { UA.CanEdit = true; } if (item.Contains("Delete")) { UA.CanDelete = true; } } LOUA.Add(UA); } else { if (AP.Contains("Edit")) { UA.ScreenID = int.Parse(AP.Replace("Edit", "")); UA.CanEdit = true; } else if (AP.Contains("Delete")) { UA.ScreenID = int.Parse(AP.Replace("Delete", "")); UA.CanDelete = true; } else { UA.ScreenID = int.Parse(AP); } LOUA.Add(UA); } } else { if (AP.Contains("Opt1")) { UserAccess UA = new UserAccess(); UA.ScreenID = int.Parse(AP.Replace("Opt1", "")); UA.Opt1 = true; LOUA.Add(UA); } else if (AP.Contains("Show")) { UserAccess UA = new UserAccess(); UA.ScreenID = int.Parse(AP.Replace("Show", "")); foreach (string item in Access.Where(p => p.Contains(UA.ScreenID.ToString())).ToList()) { if (item.Contains("Opt1")) { UA.Opt1 = true; } if (item.Contains("Edit")) { UA.CanEdit = true; } if (item.Contains("Delete")) { UA.CanDelete = true; } } LOUA.Add(UA); } else { UserAccess UA = new UserAccess(); if (AP.Contains("Edit")) { UA.ScreenID = int.Parse(AP.Replace("Edit", "")); UA.CanEdit = true; } else if (AP.Contains("Delete")) { UA.ScreenID = int.Parse(AP.Replace("Delete", "")); UA.CanDelete = true; } else { UA.ScreenID = int.Parse(AP); } LOUA.Add(UA); } } } Returner R = new User { ID = (int)TempData["UID"], Username = name, Password = pass }.Update(LOUA); if (R.Message == Message.Username_Already_Exists) { TempData.Keep(); return("false"); } else { TempData.Keep(); return("true"); } }
/// <summary> /// Add new qr code to system /// </summary> private async void ToolbarItem_Activated(object sender, EventArgs e) { if (!App.AppSettings.QRCodeEnabled) { return; } if (Device.RuntimePlatform == Device.iOS) { var scanner = new ZXing.Mobile.MobileBarcodeScanner(); var result = await scanner.Scan(); if (result == null) { return; } try { var qrCodeId = result.Text.GetHashCode() + ""; if (_oListSource.Any(o => string.Compare(o.Id, qrCodeId, StringComparison.OrdinalIgnoreCase) == 0)) { App.ShowToast(AppResources.qrcode_exists); } else { AddNewRecord(qrCodeId); } } catch (Exception ex) { App.AddLog(ex.Message); } } else { const BarcodeFormat expectedFormat = BarcodeFormat.QR_CODE; var opts = new ZXing.Mobile.MobileBarcodeScanningOptions { PossibleFormats = new List <BarcodeFormat> { expectedFormat } }; System.Diagnostics.Debug.WriteLine("Scanning " + expectedFormat); var scanPage = new ZXingScannerPage(opts); scanPage.OnScanResult += (result) => { scanPage.IsScanning = false; Device.BeginInvokeOnMainThread(async() => { await Navigation.PopAsync(); try { var qrCodeId = result.Text.GetHashCode() + ""; if (_oListSource.Any( o => string.Compare(o.Id, qrCodeId, StringComparison.OrdinalIgnoreCase) == 0)) { App.ShowToast(AppResources.qrcode_exists); } else { AddNewRecord(qrCodeId); } } catch (Exception ex) { App.AddLog(ex.Message); } }); }; await Navigation.PushAsync(scanPage); } }
public int NewColumnId() { return(Columns.Any() ? Columns.Max(o => o.Id) + 1 : 1); }
public BreakpointList(Events events) { _events = events; InitializeComponent(); OwnerDraw = true; ShowGroups = false; Activation = ItemActivation.Standard; FullRowSelect = true; GridLines = true; View = View.Details; BorderStyle = BorderStyle.None; Columns.AddRange(new[] { new ColumnHeader { Text = "", Width = 25 }, new ColumnHeader { Text = "Address" }, new ColumnHeader { Text = "Type", Width = 40 } }); contextMenu.Opening += (s, a) => { var project = _events.GetCurrentProject(); addMenuItem.Enabled = project != null; clearAllMenuItem.Enabled = Items.Count > 0; goToMenuItem.Enabled = editMenuItem.Enabled = deleteMenuItem.Enabled = enableMenuItem.Enabled = SelectedBreakpoints.Any(); if (SelectedBreakpoints.Any(i => i.Breakpoint.File != null)) { editMenuItem.Enabled = false; } if (SelectedBreakpoints.Any(i => i.Breakpoint.File == null)) { goToMenuItem.Enabled = false; } enableMenuItem.CheckState = SelectedBreakpoints.Any() && SelectedBreakpoints.All(i => !i.Breakpoint.Disabled) ? CheckState.Checked : SelectedBreakpoints.All(i => i.Breakpoint.Disabled) ? CheckState.Unchecked : CheckState.Indeterminate; }; contextMenu.Closing += (s, a) => { goToMenuItem.Enabled = editMenuItem.Enabled = deleteMenuItem.Enabled = enableMenuItem.Enabled = clearAllMenuItem.Enabled = true; }; clearAllMenuItem.Click += (s, a) => { _events.RemoveBreakpoints(Items.OfType <BreakpointItem>().Select(b => b.Breakpoint)); }; deleteMenuItem.Click += (s, a) => { _events.RemoveBreakpoints(SelectedBreakpoints.Select(b => b.Breakpoint)); }; enableMenuItem.Click += (s, a) => { var targetStatus = SelectedBreakpoints.All(i => !i.Breakpoint.Disabled); foreach (var item in SelectedBreakpoints) { item.Breakpoint.Disabled = targetStatus; } _events.RemoveBreakpoints(new Breakpoint[] {}); Invalidate(); _events.UpdatedBreakpoints(); }; goToMenuItem.Click += (s, a) => JumpToBreakpoint(SelectedBreakpoints.FirstOrDefault()); editMenuItem.Click += (s, a) => ActivateBreakpoint(SelectedBreakpoints.FirstOrDefault()); addMenuItem.Click += (s, a) => AddNewBreakpoint(); Program.BindKey(Feature.RemoveFromList, (keys) => deleteMenuItem.ShortcutKeys = keys); Program.BindKey(Feature.ActivateItem, (keys) => editMenuItem.ShortcutKeys = keys); ContextMenuStrip = contextMenu; }
public override bool AppliesTo(object instance) { return(_values.Any(wr => wr.Target == instance)); }
private static T Open<T>(XmlReader reader) where T : SvgDocument, new() { if (!SkipGdiPlusCapabilityCheck) { EnsureSystemIsGdiPlusCapable(); //Validate whether the GDI+ can be loaded, this will yield an exception if not } var elementStack = new Stack<SvgElement>(); bool elementEmpty; SvgElement element = null; SvgElement parent; T svgDocument = null; var elementFactory = new SvgElementFactory(); var styles = new List<ISvgNode>(); while (reader.Read()) { try { switch (reader.NodeType) { case XmlNodeType.Element: // Does this element have a value or children // (Must do this check here before we progress to another node) elementEmpty = reader.IsEmptyElement; // Create element if (elementStack.Count > 0) { element = elementFactory.CreateElement(reader, svgDocument); } else { svgDocument = elementFactory.CreateDocument<T>(reader); element = svgDocument; } // Add to the parents children if (elementStack.Count > 0) { parent = elementStack.Peek(); if (parent != null && element != null) { parent.Children.Add(element); parent.Nodes.Add(element); } } // Push element into stack elementStack.Push(element); // Need to process if the element is empty if (elementEmpty) { goto case XmlNodeType.EndElement; } break; case XmlNodeType.EndElement: // Pop the element out of the stack element = elementStack.Pop(); if (element.Nodes.OfType<SvgContentNode>().Any()) { element.Content = (from e in element.Nodes select e.Content).Aggregate((p, c) => p + c); } else { element.Nodes.Clear(); // No sense wasting the space where it isn't needed } var unknown = element as SvgUnknownElement; if (unknown != null && unknown.ElementName == "style") { styles.Add(unknown); } break; case XmlNodeType.CDATA: case XmlNodeType.Text: element = elementStack.Peek(); element.Nodes.Add(new SvgContentNode() { Content = reader.Value }); break; case XmlNodeType.EntityReference: reader.ResolveEntity(); element = elementStack.Peek(); element.Nodes.Add(new SvgContentNode() { Content = reader.Value }); break; } } catch (Exception exc) { Trace.TraceError(exc.Message); } } if (styles.Any()) { var cssTotal = styles.Select((s) => s.Content).Aggregate((p, c) => p + Environment.NewLine + c); var cssParser = new Parser(); var sheet = cssParser.Parse(cssTotal); foreach (var rule in sheet.StyleRules) { try { var rootNode = new NonSvgElement(); rootNode.Children.Add(svgDocument); var elemsToStyle = rootNode.QuerySelectorAll(rule.Selector.ToString(), elementFactory); foreach (var elem in elemsToStyle) { foreach (var decl in rule.Declarations) { elem.AddStyle(decl.Name, decl.Term.ToString(), rule.Selector.GetSpecificity()); } } } catch (Exception ex) { Trace.TraceWarning(ex.Message); } } } svgDocument?.FlushStyles(true); return svgDocument; }
public static bool DuplicateHotKey(HotKey hk) { return(_hotkeys.Any(k => hk.Key == k.Key && hk.Modifiers == k.Modifiers)); }
private async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query, int attempts) { var releases = new List <ReleaseInfo>(); bool rssMode = string.IsNullOrEmpty(query.SanitizedSearchTerm); Uri siteLinkUri = new Uri(configData.SiteLink.Value); if (rssMode) { int pg = 1; while (pg <= _maxDailyPages) { Uri url = new Uri(siteLinkUri, string.Format(_dailyUrl, pg)); var results = await RequestStringWithCookies(url.AbsoluteUri); var items = ParseDailyContent(results.Content); if (items == null || !items.Any()) { break; } releases.AddRange(items); //Check if we need to go to next page bool recentFound = _mostRecentRelease != null && items.Any(r => r.Title == _mostRecentRelease.Title && r.Link.AbsoluteUri == _mostRecentRelease.Link.AbsoluteUri); if (pg == 1) { _mostRecentRelease = (ReleaseInfo)items.First().Clone(); } if (recentFound) { break; } pg++; } } else { //Only tv search supported. (newpct web search is useless) bool isTvSearch = query.Categories == null || query.Categories.Length == 0 || query.Categories.Any(c => _allTvCategories.Contains(c)); if (isTvSearch) { var newpctReleases = new List <ReleaseInfo>(); string seriesName = query.SanitizedSearchTerm; int? season = query.Season > 0 ? (int?)query.Season : null; int? episode = null; if (!string.IsNullOrWhiteSpace(query.Episode) && int.TryParse(query.Episode, out int episodeTemp)) { episode = episodeTemp; } //If query has no season/episode info, try to parse title if (season == null && episode == null) { Match searchMatch = _searchStringRegex.Match(query.SanitizedSearchTerm); if (searchMatch.Success) { seriesName = searchMatch.Groups[1].Value.Trim(); season = int.Parse(searchMatch.Groups[2].Value); episode = searchMatch.Groups[4].Success ? (int?)int.Parse(searchMatch.Groups[4].Value) : null; } } //Try to reuse cache bool cacheFound = false; lock (cache) { CleanCache(); var cachedResult = cache.FirstOrDefault(i => i.Query == seriesName.ToLower()); if (cachedResult != null && cachedResult.Results != null) { cacheFound = true; newpctReleases = cachedResult.Results.Where(r => (r as NewpctRelease) != null).ToList(); if (!newpctReleases.Any() && cachedResult.Results.Any()) { cacheFound = false; } } } if (!cacheFound) { IEnumerable <string> lettersUrl; if (!((BoolItem)configData.GetDynamic("IncludeVo")).Value) { lettersUrl = _seriesLetterUrls; } else { lettersUrl = _seriesLetterUrls.Concat(_seriesVOLetterUrls); } string seriesLetter = !char.IsDigit(seriesName[0]) ? seriesName[0].ToString() : "0-9"; //Search series url foreach (string urlFormat in lettersUrl) { Uri seriesListUrl = new Uri(siteLinkUri, string.Format(urlFormat, seriesLetter.ToLower())); var results = await RequestStringWithCookies(seriesListUrl.AbsoluteUri); //Episodes list string seriesEpisodesUrl = ParseSeriesListContent(results.Content, seriesName); if (!string.IsNullOrEmpty(seriesEpisodesUrl)) { int pg = 1; while (pg < _maxEpisodesListPages) { Uri episodesListUrl = new Uri(string.Format(_seriesUrl, seriesEpisodesUrl, pg)); results = await RequestStringWithCookies(episodesListUrl.AbsoluteUri); var items = ParseEpisodesListContent(results.Content); if (items == null || !items.Any()) { break; } newpctReleases.AddRange(items); pg++; } } } //Cache ALL episodes lock (cache) { cache.Add(new CachedQueryResult(seriesName.ToLower(), newpctReleases)); } } //Filter only episodes needed releases.AddRange(newpctReleases.Where(r => { NewpctRelease nr = r as NewpctRelease; return(nr.Season.HasValue != season.HasValue || //Can't determine if same season nr.Season.HasValue && season.Value == nr.Season.Value && //Same season and ... ( nr.Episode.HasValue != episode.HasValue || //Can't determine if same episode nr.Episode.HasValue && ( nr.Episode.Value == episode.Value || //Same episode nr.EpisodeTo.HasValue && episode.Value >= nr.Episode.Value && episode.Value <= nr.EpisodeTo.Value //Episode in interval ) )); })); } } return(releases); }
private bool IsFunction(string c) { return(AvailableOperations.Any(x => x.Semantic == c && x.Type == OperationType.Function)); }