private IEnumerable<IEnumerable<TextChange>> PartitionChangesForDocument(IEnumerable<TextChange> changes, SourceText originalSourceText) { var partitionedChanges = new List<IEnumerable<TextChange>>(); var currentPartition = new List<TextChange>(); currentPartition.Add(changes.First()); var currentPartitionEndLine = originalSourceText.Lines.GetLineFromPosition(changes.First().Span.End); foreach (var change in changes.Skip(1)) { // If changes are on adjacent lines, consider them part of the same change. var changeStartLine = originalSourceText.Lines.GetLineFromPosition(change.Span.Start); if (changeStartLine.LineNumber >= currentPartitionEndLine.LineNumber + 2) { partitionedChanges.Add(currentPartition); currentPartition = new List<TextChange>(); } currentPartition.Add(change); currentPartitionEndLine = originalSourceText.Lines.GetLineFromPosition(change.Span.End); } if (currentPartition.Any()) { partitionedChanges.Add(currentPartition); } return partitionedChanges; }
/// <summary> /// merge arguments /// </summary> /// <param name="arguments"></param> /// <param name="intoList"></param> /// <returns></returns> public static WorkingArguments Merge(IEnumerable <WorkingArguments> arguments, bool intoList) { WorkingArguments result = new WorkingArguments(); if (arguments?.Any() == true) { // merge ids if (arguments?.Select(x => x.WorkingCopyId)?.Distinct()?.Count() == 1) { result.WorkingCopyId = arguments?.First()?.WorkingCopyId; } if (arguments?.Select(x => x.WorkingStepId)?.Distinct()?.Count() == 1) { result.WorkingStepId = arguments?.First()?.WorkingStepId; } if (arguments?.Select(x => x.WorkingStepResultId)?.Distinct()?.Count() == 1) { result.WorkingStepResultId = arguments?.First()?.WorkingStepResultId; } if (arguments?.Select(x => x.ActionType)?.Distinct()?.Count() == 1) { result.ActionType = arguments?.First()?.ActionType; } result.PublicArguments = MergeDictionary(arguments?.Select(x => x.PublicArguments), intoList); result.PrivateArguments = MergeDictionary(arguments?.Select(x => x.PrivateArguments), intoList); } return(result); }
private int WriteWith(IEnumerable<TfsChangesetInfo> tfsParents, string refToWrite, Func<TfsChangesetInfo, string, int> write) { switch (tfsParents.Count()) { case 1: var changeset = tfsParents.First(); return write(changeset, refToWrite); case 0: _stdout.WriteLine("No TFS parents found!"); return GitTfsExitCodes.InvalidArguments; default: if (tfsParents.Select(x => x.Remote.IsSubtree ? x.Remote.OwningRemoteId : x.Remote.Id).Distinct().Count() == 1) { //this occurs when we have merged in a subtree, at the subtree merge commit there will be a tfsParent for the //subtree owner in addition to the one for the subtree itself. In this case, we will use the subtree owner, since //we are in the main history line and not a subtree line. var cs = tfsParents.First(); if(cs.Remote.IsSubtree) cs.Remote = _globals.Repository.ReadTfsRemote(cs.Remote.OwningRemoteId); _stdout.WriteLine(string.Format("Basing from parent '{0}', use -i to override", cs.Remote.Id)); return write(cs, refToWrite); } _stdout.WriteLine("More than one parent found! Use -i to choose the correct parent from: "); foreach (var parent in tfsParents) { _stdout.WriteLine(" " + parent.Remote.Id); } return GitTfsExitCodes.InvalidArguments; } }
private void InitializeVariables(IEnumerable<IVariable> variables) { ValidateInputProperties(); Index1Variable = variables.OfType<IVariable>().First(v => v.Name == Index1VariableName); Index2Variable = variables.OfType<IVariable>().First(v => v.Name == Index2VariableName); XVariable = variables.OfType<IVariable<double>>().First(v => v.Name == XVariableName); YVariable = variables.OfType<IVariable<double>>().First(v => v.Name == YVariableName); ValuesVariable = variables.First(v => v.Name == ValuesVariableName); if(!string.IsNullOrEmpty(TimeVariableName)) { TimeVariable = variables.First(v => v.Name == TimeVariableName); } /* if(!XVariable.Arguments.SequenceEqual(YVariable.Arguments)) { throw new NotSupportedException("Arguments used in X variable must be the same as in Y variable"); } if (!XVariable.Arguments.SequenceEqual(ValuesVariable.Arguments)) { throw new NotSupportedException("Arguments used in Values variable must be the same as in X and Y variables"); } */ }
public AxisAlignedBox3D(IEnumerable<Point3D> points) { if (points == null || !points.Any()) throw new ArgumentException(); // Compute minimal and maximal bounds. Min = points.First(); Max = points.First(); foreach (Point3D point in points) { if (point.X < Min.X) Min.X = point.X; else if (point.X > Max.X) Max.X = point.X; if (point.Y < Min.Y) Min.Y = point.Y; else if (point.Y > Max.Y) Max.Y = point.Y; if (point.Z < Min.Z) Min.Z = point.Z; else if (point.Z > Max.Z) Max.Z = point.Z; } }
private static void PrintMostProfitableCategory( IEnumerable<Order> allOrders, IEnumerable<Product> allProducts, IEnumerable<Category> allCategories) { // The most profitable category var category = allOrders.GroupBy(o => o.ProductId) .Select( ordersGroup => new { ProductOrderedId = allProducts.First(p => p.Id == ordersGroup.Key).CategoryId, PriceOrdered = allProducts.First(p => p.Id == ordersGroup.Key).UnitPrice, Quantities = ordersGroup.Sum(productsOrdered => productsOrdered.Quantity) }) .GroupBy(product => product.ProductOrderedId) .Select( productGroup => new { CategoryName = allCategories.First(c => c.Id == productGroup.Key).Name, TotalQuantity = productGroup.Sum(order => order.Quantities * order.PriceOrdered) }) .OrderByDescending(c => c.TotalQuantity) .First(); Console.WriteLine("{0}: {1}", category.CategoryName, category.TotalQuantity); }
public ForecastEntry Forecast(IEnumerable<DataEntry> dataEntries, int period, dynamic strategyParameters) { if (period - 1 < 0) return null; double alpha = strategyParameters.Alpha; double beta = strategyParameters.Beta; double value; if (dataEntries.Count() < 3 || period < 3) value = dataEntries.ElementAt(0).Value; else if (dataEntries.Count() > 1 && period <= dataEntries.Count() + 1) value = GenerateForecast(3, period, alpha, beta, dataEntries, dataEntries.First().Value, 0); else value = GenerateForecast(3, dataEntries.Count() + 1, alpha, beta, dataEntries, dataEntries.First().Value, 0); return new ForecastEntry { Period = period, DataEntry = period > dataEntries.Count() ? dataEntries.Last() : dataEntries.ElementAt(period - 1), ForecastValue = value, ConfidenceIntervalLow = value, ConfidenceIntervalHigh = value, IsHoldout = period > dataEntries.Count()*0.7 //holdout data is always 70 percent }; }
/// <summary> /// Gets whether a feature path is valid for the features in the feature set /// </summary> /// <param name="features">Top-level features</param> /// <param name="featurePath">Feature path to the highest-level feature</param> /// <returns>Value indicating whether the feature path is valid for a feature in <paramref name="features"/></returns> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="features"/> or <paramref name="featurePath"/> is null</exception> /// <exception cref="System.InvalidOperationException">Thrown when <paramref name="featurePath"/> is empty</exception> public static bool IsEnabled(IEnumerable<IFeature> features, IEnumerable<string> featurePath) { Ensure.Argument.NotNull(features, "features"); Ensure.Argument.NotNull(featurePath, "featurePath"); Ensure.That<InvalidOperationException>(featurePath.Any(), "Feature Path must contain at least one top-level feature"); // feature names are case insensitive IFeature current = FindFeature(features, featurePath.First()); // skip the first value featurePath = featurePath.Skip(1); // loop through the entire path while (featurePath.Any()) { // path was not found if (current == null) return false; // see if the feature has subfeatures (Complex) var asComplex = current as IComplexFeature; if (asComplex == null) // feature doesn't have subfeatures, it passes return true; current = FindFeature(asComplex.SubFeatures, featurePath.First()); featurePath = featurePath.Skip(1); } return current != null; }
public AirstrikePowerASEffect(World world, Player p, WPos pos, IEnumerable<Actor> planes, AirstrikePowerASInfo info) { this.info = info; this.world = world; this.Owner = p; this.pos = pos; this.planes = planes; if (info.DisplayBeacon) { var distance = (planes.First().OccupiesSpace.CenterPosition - pos).HorizontalLength; beacon = new Beacon( Owner, pos - new WVec(WDist.Zero, WDist.Zero, world.Map.DistanceAboveTerrain(pos)), info.BeaconPaletteIsPlayerPalette, info.BeaconPalette, info.BeaconImage, info.BeaconPoster, info.BeaconPosterPalette, info.ArrowSequence, info.CircleSequence, info.ClockSequence, () => 1 - ((planes.First().OccupiesSpace.CenterPosition - pos).HorizontalLength - info.BeaconDistanceOffset.Length) * 1f / distance); world.AddFrameEndTask(w => w.Add(beacon)); } }
public ActionResult Submit(IEnumerable<HttpPostedFileBase> files) { if (files != null) { var ext = Path.GetExtension(files.First().FileName); if (allowedFileExtensions.Contains(ext.Substring(1).ToLower())) { var username = User.Identity.Name; var fileName = username + ext; var fullPath = Server.MapPath("~/img/Avatars/") + fileName; files.First().SaveAs(fullPath); var user = this.Data.Users.All().FirstOrDefault(u => u.UserName == username); user.AvatarPath = "/img/Avatars/" + fileName; this.Data.SaveChanges(); } else { } } return RedirectToAction("ShowProfile"); }
/// <summary> /// Creates new friend relationships between a list of people /// All elements relate to the same player and game /// </summary> /// <param name="friends">A list of friends relationships</param> /// <returns>The result of the operation as a <see cref="T:Task{String}</returns> public async Task<string> AddFriends(IEnumerable<FriendLink> friends) { var friendList = friends.Select(fl => fl.FriendId).ToList(); var gameId = friends.First().GameId; var playerId = friends.First().PlayerId; return await _httpHelper.Post(_token, $"api/friend/{gameId}/{playerId}/batch", JsonConvert.SerializeObject(friendList)); ; }
public string GenerateMergeScript(IEnumerable<InsertRowDesc> rows, bool united = false) { var script = string.Empty; if (rows.Count() == 0) // 0 rows { script = string.Empty; } else if (rows.Count() == 1) // only 1 row { script = GenerateMergeScript(rows.First()); } else // above than 1 row { if (united == true) { CheckSchemaOnIdentity(rows); script = GenerateUnitedMergeScript(rows); } else { var sb = new StringBuilder(); foreach (var row in rows) { sb.AppendLine(GenerateMergeScript(rows.First())); } script = sb.ToString(); } } return script; }
public override IEnumerable<Item> Perform(IEnumerable<Item> items, IEnumerable<Item> modifierItems) { RTMTaskItem task = null; List<string> temp_tags = new List<string> (); string s = null; if (items.Any()) { if (items.First () is RTMTaskItem) task = (items.First () as RTMTaskItem); else if (items.First () is RTMTaskAttributeItem) task = (items.First () as RTMTaskAttributeItem).Parent; } if (modifierItems.Any () && task != null) { foreach (Item item in modifierItems) { s = GetText (item); if (!String.IsNullOrEmpty(s)) temp_tags.Add (s); } Services.Application.RunOnThread (() => { RTM.AddTags ((items.First () as RTMTaskItem).ListId, (items.First () as RTMTaskItem).TaskSeriesId, (items.First () as RTMTaskItem).Id, String.Join (",", temp_tags.ToArray ())); }); } yield break; }
public Task<HttpResponseMessage> SendMessageAsync(IEnumerable<string> lines, PayloadSettings settings) { dynamic json = JObject.FromObject(new { channel = settings.Channel, username = settings.Username, attachments = new[] { new { fallback = lines.First(), pretext = lines.First(), color = settings.Color, mrkdwn_in = new [] { "pretext", "text", "title", "fields", "fallback" }, fields = from line in lines.Skip(1) select new { value = line, @short = false } } } }); if (!String.IsNullOrEmpty(settings.IconUrl)) json.icon_url = settings.IconUrl; else if (!String.IsNullOrEmpty(settings.IconEmoji)) json.icon_emoji = settings.IconEmoji; //Logger.Log(json.ToString()); var content = new StringContent(json.ToString(), Encoding.UTF8, "application/json"); return PostAsync(settings.WebhookUrl, content); }
private void SaveEvents(Guid eventSourceId, IEnumerable<UncommittedEvent> events) { string eventSourceName = events.First().GetType().ToString(); long initialVersion = events.First().InitialVersionOfEventSource; long lastVersion = initialVersion + events.Count(); NcqrsEventStoreContext storeContext = new NcqrsEventStoreContext(eventSourceId, account, prefix); Guid commitId = storeContext.BeginCommit(); NcqrsEventSource lastSource = storeContext.LatestEventSource; if (lastSource == null) { lastSource = new NcqrsEventSource(eventSourceId, initialVersion, eventSourceName); } else if (lastSource.Version != initialVersion) { throw new ConcurrencyException(eventSourceId, initialVersion); } foreach (UncommittedEvent @event in events) { storeContext.Add(new NcqrsEvent(@event)); } lastSource.Version = lastVersion; storeContext.SaveSource(lastSource); storeContext.EndCommit(); }
protected override Expression InternalCall(IEnumerable<Expression> args) { var f = (Function)args.First(); args = PreProcessArguments(args.Skip(1)); var list = ((ListExpression)args.First()).Elements; return list.Aggregate((acc, x) => f.Call(new Expression[] { acc, x })); }
public static ICurrencyConvert GetCurrencyConverter(CurrencyEnum currencyType, IEnumerable<CurrencyExchange> theCurrencies) { ICurrencyConvert strategy = null; string currencyExchangeName = "GBP-"; switch (currencyType) { case CurrencyEnum.GBP: strategy = new PRCCurrencyConverter(CurrencyEnum.GBP, 1); break; case CurrencyEnum.USD: currencyExchangeName += "USD"; strategy = new PRCCurrencyConverter(CurrencyEnum.USD, (decimal)theCurrencies.First(x=>x.CurrencyExchangeName== currencyExchangeName).CurrencyExchangeRate); break; case CurrencyEnum.EUR: currencyExchangeName += "EUR"; strategy = new PRCCurrencyConverter(CurrencyEnum.EUR, (decimal)theCurrencies.First(x => x.CurrencyExchangeName == currencyExchangeName).CurrencyExchangeRate); break; case CurrencyEnum.CAD: currencyExchangeName += "CAD"; strategy = new PRCCurrencyConverter(CurrencyEnum.CAD, (decimal)theCurrencies.First(x => x.CurrencyExchangeName == currencyExchangeName).CurrencyExchangeRate); break; default: strategy = new PRCCurrencyConverter(CurrencyEnum.GBP, 1); break; } return strategy; }
private static int DoRandomCharacter(IEnumerable<string> args) { uint count = 1; if (args.Any()) { if (!uint.TryParse(args.First(), out count)) { Console.WriteLine("Invalid count: '{0}'", args.First()); PrintUsage(); return -1; } } RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider(); byte[] bytes = new byte[8]; for (uint i = 0; i < count; ++i) { crypto.GetBytes(bytes); long randomLong = BitConverter.ToInt64(bytes, 0); int randomIndex = (int)(Math.Abs(randomLong) % allowedCharacters.Length); char randomChar = allowedCharacters[randomIndex]; Console.Write(randomChar); } Console.WriteLine(); return 0; }
private void Assert_single_result(IEnumerable<TeamPicture> teamPictures, TeamPicture testData) { teamPictures.Count().ShouldBe(1); teamPictures.First().Message.ShouldBe(testData.Message); teamPictures.First().Picture.ShouldBe(testData.Picture); teamPictures.First().PictureHeight.ShouldBe(HEIGHT); teamPictures.First().PictureWidth.ShouldBe(WIDTH); }
// ReSharper restore InconsistentNaming #pragma warning restore 169 static void Verify(IEnumerable<Tuple<string, int>> tuples, string item1, int item2) { tuples.Count().ShouldEqual(item2); tuples.First().Item1.ShouldEqual("I"); tuples.First().Item2.ShouldEqual(1); tuples.Last().Item1.ShouldEqual(item1); tuples.Last().Item2.ShouldEqual(item2); }
public static void AssertResult(IEnumerable<IFolder> result) { Assert.That(result.Count(), Is.EqualTo(1)); var qualifiedPath = new DirectoryInfo(Path).FullName; Assert.That(result.First().Path, Is.EqualTo(qualifiedPath)); Assert.That(result.First().NumberOfFiles, Is.EqualTo(2)); Assert.That(result.First().TotalBytes, Is.EqualTo(16)); Assert.That(result.First().Depth, Is.EqualTo(0)); }
public override IEnumerable<Item> Perform(IEnumerable<Item> items, IEnumerable<Item> modifierItems) { Services.Application.RunOnThread (() => { RTM.CompleteTask ((items.First () as RTMTaskItem).ListId, (items.First () as RTMTaskItem).TaskSeriesId, (items.First () as RTMTaskItem).Id); }); yield break; }
public override IEnumerable<Item> Perform(IEnumerable<Item> items, IEnumerable<Item> modifierItems) { Services.Application.RunOnThread (() => { RTM.SetTaskPriority ((items.First () as RTMTaskItem).ListId, (items.First () as RTMTaskItem).TaskSeriesId, (items.First () as RTMTaskItem).Id, (modifierItems.First () as RTMPriorityItem).Priority); }); yield break; }
private void DisplayPictures(IEnumerable<Photo> savedPhotos) { LastImageUploaded.Source = null; //on peut en recevoir plusieurs => par défaut je n'en affiche qu'une. if (!savedPhotos.Any()) return; LastImageUploaded.Source = new BitmapImage( new Uri(savedPhotos.First().Uri, UriKind.Absolute)); LastImageUploadedUrl.Text = savedPhotos.First().Uri; }
public override IEnumerable<Item> Perform(IEnumerable<Item> items, IEnumerable<Item> modifierItems) { Services.Application.RunOnThread (() => { RTM.SetRecurrence ((items.First () as RTMTaskItem).ListId, (items.First () as RTMTaskItem).TaskSeriesId, (items.First () as RTMTaskItem).Id, (modifierItems.FirstOrDefault () as ITextItem).Text); }); yield break; }
public override IEnumerable<Item> Perform(IEnumerable<Item> items, IEnumerable<Item> modItems) { if (!modItems.Any ()) ShelfItemSource.RemoveFromAll (items.First ()); else { (modItems.First () as ShelfItem).RemoveItem (items.First ()); ShelfItemSource.Serialize(); } yield break; }
private ServerConfiguration FindResult(IEnumerable<DataRow> results) { if (results.Count() == 0) return ServerConfiguration.Error; if (DateTime.Now.Subtract(TimeSpan.FromHours(12)) > results.First().Field<DateTime>("CollectionTime")) return ServerConfiguration.ReportingError; if (PercentageChange(results.First().Field<string>("ServerName"), results) > 15) return ServerConfiguration.RapidChange; return ServerConfiguration.OK; }
static IEnumerable<IEnumerable<KeyValuePair<IASTNode, IASTNode>>> CrossJoinKeyValuePairList(IEnumerable<KeyValuePair<IASTNode, IASTNode[]>> input) { if (input.Count() == 1) { return ExpandKeyValuePair(input.First()); } return from headEntry in ExpandKeyValuePair(input.First()) from tailEntry in CrossJoinKeyValuePairList(input.Skip(1)) select headEntry.Union(tailEntry); }
public void ProcessPath(IEnumerable<String> path, TreeNodeCollection nodes) { if (!path.Any()) return; var node = nodes.Cast<TreeNode>().FirstOrDefault(n => n.Text == path.First()); if (node == null) { node = new TreeNode(text: path.First()); nodes.Add(node); } ProcessPath(path.Skip(1), node.Nodes); }
public ImageBrowser(IEnumerable<Meta<ICache>> caches) { ThumbCache = caches .First(CacheTypeChecker(ECacheType.Thumb)) .Value; ImageCache = caches .First(CacheTypeChecker(ECacheType.Image)) .Value; }
public override IEnumerable<Item> Perform(IEnumerable<Item> items, IEnumerable<Item> modItems) { string pattern; if (items.First () is ITextItem) pattern = (items.First () as ITextItem).Text; else pattern = items.First ().Name; Log<SearchCollectionAction>.Debug ("Searching collection for {0}", pattern); return Banshee.SearchMedia (pattern).Cast<Item> (); }
/// <summary> /// Create a BoxCastResponse based on the given HttpResponseMessage /// </summary> /// <param name="httpResponse"></param> /// <returns></returns> public static async Task <BoxCastResponse <T> > CreateResponse(HttpResponseMessage httpResponse) { var boxCastResponse = new BoxCastResponse <T>(); string json = await httpResponse.Content.ReadAsStringAsync(); //populate consistent response data boxCastResponse.ETag = httpResponse.Headers.ETag?.Tag; boxCastResponse.ResponseCode = httpResponse.StatusCode; boxCastResponse.ResponsePhrase = httpResponse.ReasonPhrase; IEnumerable <string> headerValues = null; httpResponse.Headers.TryGetValues("X-RateLimit-Limit", out headerValues); if (headerValues?.First() != null) { boxCastResponse.RateLimit.Limit = Convert.ToInt32(headerValues.First()); } httpResponse.Headers.TryGetValues("X-RateLimit-Remaining", out headerValues); if (headerValues?.First() != null) { boxCastResponse.RateLimit.Remaining = Convert.ToInt32(headerValues.First()); } httpResponse.Headers.TryGetValues("X-RateLimit-Reset", out headerValues); if (headerValues?.First() != null) { DateTime reset; DateTime.TryParse(headerValues.First(), out reset); boxCastResponse.RateLimit.Reset = reset; } httpResponse.Headers.TryGetValues("X-Pagination", out headerValues); if (headerValues?.First() != null) { string paginationJson = headerValues.First(); boxCastResponse.Pagination = JsonConvert.DeserializeObject <PaginationModel>(paginationJson); } //dump all header data into the headers dictionary. boxCastResponse.Headers = httpResponse.Headers.ToDictionary(x => x.Key, x => x.Value); //deserialize json content boxCastResponse.Content = JsonConvert.DeserializeObject <T>(json); return(boxCastResponse); }
protected async Task <QuickInfoContent> CreateContentAsync( Workspace workspace, ISyntaxToken token, SemanticModelBase semanticModel, IEnumerable <ISymbol> symbols, CancellationToken cancellationToken) { var descriptionService = workspace.Services.GetLanguageServices(token.Language).GetService <ISymbolDisplayService>(); var sections = await descriptionService.ToDescriptionGroupsAsync(workspace, semanticModel, token.FileSpan.Span.Start, symbols.ToImmutableArray(), cancellationToken).ConfigureAwait(false); var mainDescriptionBuilder = new List <TaggedText>(); if (sections.ContainsKey(SymbolDescriptionGroups.MainDescription)) { mainDescriptionBuilder.AddRange(sections[SymbolDescriptionGroups.MainDescription]); } var documentationContent = GetDocumentationContent(symbols, sections); return(new QuickInfoDisplayContent( semanticModel.Language, glyph: symbols?.First().GetGlyph() ?? Glyph.None, mainDescription: ImmutableArray.CreateRange(mainDescriptionBuilder), documentation: documentationContent)); }
/// <summary> /// Displays the help when <paramref name="unambiguousTemplateGroup"/> contains the invokable templates with ambiguous precedence. /// </summary> /// <param name="unambiguousTemplateGroup">resolved unambiguous template group to use based on the command input</param> /// <param name="environmentSettings"></param> /// <param name="commandInput">the command input</param> /// <param name="installUnitDescriptors">the list of install unit descriptors</param> /// <returns></returns> /// <exception cref="ArgumentNullException">when <paramref name="unambiguousTemplateGroup"/>is <see cref="null"/></exception> /// <exception cref="ArgumentNullException">when <paramref name="commandInput"/>is <see cref="null"/></exception> private static CreationResultStatus DisplayAmbiguousPrecedenceError( TemplateGroup unambiguousTemplateGroup, IEngineEnvironmentSettings environmentSettings, INewCommandInput commandInput, IEnumerable <IInstallUnitDescriptor> installUnitDescriptors) { _ = unambiguousTemplateGroup ?? throw new ArgumentNullException(paramName: nameof(unambiguousTemplateGroup)); _ = unambiguousTemplateGroup ?? throw new ArgumentNullException(paramName: nameof(commandInput)); Reporter.Error.WriteLine(LocalizableStrings.AmbiguousTemplatesHeader.Bold().Red()); List <AmbiguousTemplateDetails> ambiguousTemplateDetails = new List <AmbiguousTemplateDetails>(); foreach (ITemplateMatchInfo template in unambiguousTemplateGroup.GetHighestPrecedenceInvokableTemplates(true)) { ambiguousTemplateDetails.Add(new AmbiguousTemplateDetails { TemplateIdentity = template.Info.Identity, TemplateName = template.Info.Name, TemplateShortName = template.Info.ShortName, TemplateLanguage = template.Info.GetLanguage(), TemplatePrecedence = template.Info.Precedence, TemplateAuthor = template.Info.Author, InstallationDescriptor = installUnitDescriptors?.FirstOrDefault(descriptor => descriptor.MountPointId == template.Info.ConfigMountPointId) }); } HelpFormatter <AmbiguousTemplateDetails> formatter = HelpFormatter .For( environmentSettings, commandInput, ambiguousTemplateDetails, columnPadding: 2, headerSeparator: '-', blankLineBetweenRows: false) .DefineColumn(t => t.TemplateIdentity, LocalizableStrings.ColumnNameIdentity, showAlways: true) .DefineColumn(t => t.TemplateName, LocalizableStrings.ColumnNameTemplateName, shrinkIfNeeded: true, minWidth: 15, showAlways: true) .DefineColumn(t => t.TemplateShortName, LocalizableStrings.ColumnNameShortName, showAlways: true) .DefineColumn(t => t.TemplateLanguage, LocalizableStrings.ColumnNameLanguage, showAlways: true) .DefineColumn(t => t.TemplatePrecedence.ToString(), out object prcedenceColumn, LocalizableStrings.ColumnNamePrecedence, showAlways: true) .DefineColumn(t => t.TemplateAuthor, LocalizableStrings.ColumnNameAuthor, showAlways: true, shrinkIfNeeded: true, minWidth: 10) .DefineColumn(t => t.InstallationDescriptor != null ? t.InstallationDescriptor.Identifier : string.Empty, LocalizableStrings.ColumnNamePackage, showAlways: true) .OrderByDescending(prcedenceColumn, new NullOrEmptyIsLastStringComparer()); Reporter.Error.WriteLine(formatter.Layout().Bold().Red()); string hintMessage = LocalizableStrings.AmbiguousTemplatesMultiplePackagesHint; if (unambiguousTemplateGroup.Templates.AllAreTheSame(t => t.Info.ConfigMountPointId)) { IInstallUnitDescriptor descriptor = installUnitDescriptors?.First(descriptor => descriptor.MountPointId == unambiguousTemplateGroup.Templates.First().Info.ConfigMountPointId); if (descriptor?.Details?.ContainsKey("NuGetPackageId") ?? false) { hintMessage = string.Format(LocalizableStrings.AmbiguousTemplatesSamePackageHint, descriptor.Identifier); } } Reporter.Error.WriteLine(hintMessage.Bold().Red()); return(CreationResultStatus.NotFound); }
// See, if we get a nice link from entry private string GetLinkFromFeedEntry(IEnumerable <ISyndicationLink> links) { var link = links?.First(r => r.RelationshipType == "alternate")?.Uri.ToString(); if (string.IsNullOrWhiteSpace(link)) { link = links?.First()?.Uri.ToString(); } if (string.IsNullOrWhiteSpace(link)) { return(null); } return(link); }
/// <summary> /// /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="entities"></param> /// <returns></returns> public static DataTable ToDataTable <TEntity>(string tableName, IEnumerable <TEntity> entities) where TEntity : class { var table = new DataTable() { TableName = tableName ?? ClassMappedNameCache.Get <TEntity>() }; var properties = PropertyCache.Get(entities?.First()?.GetType() ?? typeof(TEntity)); // Columns foreach (var property in properties) { table.Columns.Add(property.PropertyInfo.Name, property.PropertyInfo.PropertyType.GetUnderlyingType()); } // Rows foreach (var entity in entities) { var row = table.NewRow(); foreach (var property in properties) { var value = property.PropertyInfo.GetValue(entity); row[property.PropertyInfo.Name] = value == null ? DBNull.Value : value; } table.Rows.Add(row); } // Return return(table); }
public override List <KinematicSolution> Kinematics(IEnumerable <Target> targets, IEnumerable <double[]> prevJoints = null) { var target = targets.First(); var prevJoint = prevJoints?.First(); var kinematics = new List <KinematicSolution>(); var kinematic = Robot.Kinematics(target, prevJoint, this.BasePlane); var planes = kinematic.Planes.ToList(); // Tool if (target.Tool != null) { Plane toolPlane = target.Tool.Tcp; toolPlane.Transform(planes[planes.Count - 1].ToTransform()); planes.Add(toolPlane); } else { planes.Add(planes[planes.Count - 1]); } kinematic.Planes = planes.ToArray(); kinematics.Add(kinematic); return(kinematics); }
public static (int, string) GetTimeZoneOffsetAndLabel(this IEnumerable <JToken> members, string user) { var match = members?.First(e => e.Value <string>("id") == user); return(match?.Value <int>("tz_offset") ?? 0, match?.Value <string>("tz_label") ?? string.Empty); }
public string GetTransmissionInformation(long datasetVersionId, TransmissionType type, string name, AttributeNames returnType = AttributeNames.value) { DatasetVersion datasetVersion = this.GetUnitOfWork().GetReadOnlyRepository <DatasetVersion>().Get(datasetVersionId); Dataset dataset = this.GetUnitOfWork().GetReadOnlyRepository <Dataset>().Get(datasetVersion.Dataset.Id); MetadataStructure metadataStructure = this.GetUnitOfWork().GetReadOnlyRepository <MetadataStructure>().Get(dataset.MetadataStructure.Id); // get MetadataStructure if (datasetVersion != null && dataset != null && metadataStructure != null && datasetVersion.Metadata != null && metadataStructure.Extra != null) { XDocument xDoc = XmlUtility.ToXDocument((XmlDocument)datasetVersion.Dataset.MetadataStructure.Extra); Dictionary <string, string> queryDic = new Dictionary <string, string>(); queryDic.Add(AttributeNames.name.ToString(), name); queryDic.Add(AttributeNames.type.ToString(), type.ToString()); IEnumerable <XElement> temp = XmlUtility.GetXElementsByAttribute(nodeNames.convertRef.ToString(), queryDic, xDoc); string value = temp?.First().Attribute(returnType.ToString()).Value; return(value); } return(string.Empty); }
static List <Contact> ReadExcelFileXml(string filename) { string[] strProperties = new string[5]; List <Contact> list = new List <Contact>(); Contact contact; int j = 0; using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open(filename, true)) { WorkbookPart workbookPart = myDoc.WorkbookPart; IEnumerable <Sheet> sheets = myDoc.WorkbookPart.Workbook.GetFirstChild <DocumentFormat.OpenXml.Spreadsheet.Sheets>().Elements <Sheet>(); string relationshipId = sheets?.First().Id.Value; WorksheetPart worksheetPart = (WorksheetPart)myDoc.WorkbookPart.GetPartById(relationshipId); SheetData sheetData = worksheetPart.Worksheet.GetFirstChild <SheetData>(); int i = 1; string value; foreach (DocumentFormat.OpenXml.Spreadsheet.Row r in sheetData.Elements <DocumentFormat.OpenXml.Spreadsheet.Row>()) { if (i != 1) { foreach (DocumentFormat.OpenXml.Spreadsheet.Cell c in r.Elements <DocumentFormat.OpenXml.Spreadsheet.Cell>()) { if (c == null) { continue; } value = c.InnerText; if (c.DataType != null) { var stringTable = workbookPart.GetPartsOfType <SharedStringTablePart>().FirstOrDefault(); if (stringTable != null) { value = stringTable.SharedStringTable. ElementAt(int.Parse(value)).InnerText; } } strProperties[j] = value; j = j + 1; } } j = 0; i = i + 1; if (strProperties.Any(p => p == null)) { continue; // checks all nulls } contact = new Contact(); contact.FullName = strProperties[0]; contact.CompanyName = strProperties[1]; contact.Position = strProperties[2]; contact.Country = strProperties[3]; contact.Email = strProperties[4]; list.Add(contact); } return(list); } }
public void Misc_Ok() { var cut = Context.RenderComponent <BootstrapBlazorRoot>(pb => { pb.AddChildContent <Table <Foo> >(pb => { pb.Add(a => a.Items, new List <Foo>() { new Foo() }); pb.Add(a => a.RenderMode, TableRenderMode.Table); pb.Add(a => a.ShowFilterHeader, true); pb.Add(a => a.TableColumns, new RenderFragment <Foo>(foo => builder => { var index = 0; builder.OpenComponent <TableColumn <Foo, DateTime?> >(index++); builder.AddAttribute(index++, nameof(TableColumn <Foo, DateTime?> .Field), foo.DateTime); builder.AddAttribute(index++, nameof(TableColumn <Foo, DateTime?> .FieldExpression), foo.GenerateValueExpression(nameof(Foo.DateTime), typeof(DateTime?))); builder.AddAttribute(index++, nameof(TableColumn <Foo, DateTime?> .Filterable), true); builder.CloseComponent(); })); }); }); var filter = cut.FindComponent <DateTimeFilter>(); var dt = filter.FindComponent <DateTimePicker <DateTime?> >(); IEnumerable <FilterKeyValueAction>?condtions = null; // Click ToDay Cell cut.InvokeAsync(() => { dt.Find(".current.today .cell").Click(); dt.FindAll(".is-confirm")[1].Click(); }); // OnFilterValueChanged var filterButton = cut.FindComponent <FilterButton <FilterAction> >(); var logics = filterButton.FindAll(".dropdown-item"); Assert.Equal(6, logics.Count); cut.InvokeAsync(() => { logics[1].Click(); condtions = filter.Instance.GetFilterConditions(); }); Assert.Single(condtions); Assert.Equal(FilterAction.LessThanOrEqual, condtions?.First().FilterAction); // OnClearFilter cut.InvokeAsync(() => { dt.Find(".is-confirm").Click(); condtions = filter.Instance.GetFilterConditions(); }); Assert.Empty(condtions); }
public SettingsContext(PrinterConfig printer, IEnumerable <PrinterSettingsLayer> layerCascade, NamedSettingsLayers viewFilter) { this.printer = printer; this.layerCascade = layerCascade; this.ViewFilter = viewFilter; // When editing presets, LayerCascade contains a filtered list of settings layers. If the list is null we're in the primarySettingsView this.IsPrimarySettingsView = layerCascade == null; // The last layer of the layerFilters is the target persistence this.persistenceLayer = layerCascade?.First() ?? printer.Settings.UserLayer; }
public static SyntaxNode FindInnermostCommonNode( this IEnumerable <SyntaxNode> nodes, Func <SyntaxNode, bool> predicate) { IEnumerable <SyntaxNode> blocks = null; foreach (var node in nodes) { blocks = blocks == null ? node.AncestorsAndSelf().Where(predicate) : blocks.Intersect(node.AncestorsAndSelf().Where(predicate)); } return(blocks?.First()); }
/// <summary> /// Получить рабочий лист по имени. /// </summary> /// <param name="document">Экземпляр типа SpreadsheetDocument.</param> /// <param name="sheetName">Наименование листа.</param> /// <returns>Рабочий лист.</returns> private static WorksheetPart GetWorksheetPartByName(SpreadsheetDocument document, string sheetName) { IEnumerable <Sheet> sheets = document.WorkbookPart.Workbook.GetFirstChild <Sheets>(). Elements <Sheet>().Where(s => s.Name == sheetName); if (sheets?.Count() == 0) { logger.Error(string.Format("В XLSX-файле не найден лист с именем \"{0}\".", sheetName)); return(null); } string relationshipId = sheets?.First().Id.Value; WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(relationshipId); return(worksheetPart); }
private WorksheetPart GetWorksheetPartByName(SpreadsheetDocument document, string sheetName) { IEnumerable <Sheet> sheets = document.WorkbookPart.Workbook.GetFirstChild <Sheets>(). Elements <Sheet>().Where(s => s.Name == sheetName); if (sheets?.Count() == 0) { // The specified worksheet does not exist. return(null); } string relationshipId = sheets?.First().Id.Value; WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(relationshipId); return(worksheetPart); }
/// <summary> /// Moves the files to destination. /// </summary> /// <param name="sourcesFilePaths">The sources file paths.</param> /// <param name="destinationFolderPaths">The destination folder paths.</param> private void MoveFilesToDestination(IEnumerable <string> sourcesFilePaths, IEnumerable <string> destinationFolderPaths) { try { foreach (var sourceFilePath in sourcesFilePaths) { var extension = Path.GetExtension(sourceFilePath); if (!string.IsNullOrWhiteSpace(extension)) { var destinationPath = destinationFolderPaths?.First(p => string.Equals(p?.Split('\\')?.Last(), extension?.Split('.')?.Last(), StringComparison.OrdinalIgnoreCase)); File.Move(sourceFilePath, Path.Combine(destinationPath, Path.GetFileName(sourceFilePath))); } } } catch (Exception) { throw; } }
public IEnumerable <TeamFeedModel> Get(HtmlNode matchContainer) { IEnumerable <string> names = ParseNames(matchContainer); if (!HasTeamNames(names)) { return(null); } IEnumerable <HtmlNode> scoreNodes = matchContainer.SelectNodes(TeamXPaths.SCORE); TeamFeedModel homeTeam = BuildTeam(names.First(), scoreNodes?.First(), matchContainer); TeamFeedModel awayTeam = BuildTeam(names.Last(), scoreNodes?.Last(), matchContainer); return(new List <TeamFeedModel>() { homeTeam, awayTeam }); }
public override void OnActionExecuting(ActionExecutingContext context) { if (context.ModelState.IsValid) { return; } IEnumerable <String> allErrors = context.ModelState.Values.SelectMany(v => v.Errors).Select(o => o.ErrorMessage); if (!string.IsNullOrEmpty(allErrors?.First())) { context.Result = new Microsoft.AspNetCore.Mvc.BadRequestObjectResult(new { message = allErrors }); } else { context.Result = new Microsoft.AspNetCore.Mvc.BadRequestObjectResult(new { message = "Could not validate modelstate" }); } base.OnActionExecuting(context); }
private void changePassword() { try { using (UnitOfWork unit = new UnitOfWork()) { IEnumerable <User> result = unit.UserRepository.Get(x => x.Id == DeserializedUser.deserializedUser.Id); User user = result?.First(); if (NewPassword == "" || OldPassword == "") { TextMessage = "Пустые поля!"; } else if (PasswordHash.ComputePasswordHash(OldPassword, int.Parse(user.Salt)).SequenceEqual(user.UserPassword) && Regex.IsMatch(NewPassword, "^([a-z]|[A-Z]|[0-9]){8,20}$")) { user.Salt = PasswordHash.GenerateSaltForPassword().ToString(); user.UserPassword = PasswordHash.ComputePasswordHash(NewPassword, int.Parse(user.Salt)); unit.UserRepository.Update(user); unit.Save(); TextMessage = "Смена пароля прошла успешно!"; OldPassword = ""; NewPassword = ""; } else if (!PasswordHash.ComputePasswordHash(OldPassword, int.Parse(user.Salt)).SequenceEqual(user.UserPassword)) { TextMessage = "Неверный старый пароль!"; } else if (!Regex.IsMatch(NewPassword, "^([a-z]|[A-Z]|[0-9]){8,20}$")) { TextMessage = "Неверный новый пароль! Можно вводить латинские символы и цифры. Длина пароля: 8-20 символов."; } else { TextMessage = "Пароль не может быть изменён на самого себя!"; } } } catch (Exception exception) { MessageBox.Show("Сообщение ошибки: " + exception.Message, "Произошла ошибка"); } }
public IActionResult Create(BookViewModel bvm) { var identity = (ClaimsIdentity)User.Identity; IEnumerable <Claim> claims = identity.Claims; var user = claims?.First(); var userId = user?.Value; var book = new Book() { Title = bvm.Title, AuthorId = bvm.AuthorId, EmployeeId = userId, Isbn = bvm.Isbn, PublishYear = bvm.PublishYear, PublisherId = bvm.PublisherId }; _context.Books.Add(book); _context.SaveChanges(); return(RedirectToAction("Index")); }
public async Task AddAttributesAsync(int id, IEnumerable <Attribute> attributes) { if (attributes?.First() == null) { return; } var user = await repository.GetByIdAsync(id); if (user == null) { throw new NotFoundException(); } foreach (var attribute in attributes) { user[attribute.Name] = attribute.Value; } await repository.CreateOrUpdateAsync(user); }
public override List <KinematicSolution> Kinematics(IEnumerable <Target> targets, IEnumerable <double[]> prevJoints = null, bool displayMeshes = false) { var target = targets.First(); var prevJoint = prevJoints?.First(); var kinematics = new List <KinematicSolution>(); var kinematic = Robot.Kinematics(target, prevJoint, displayMeshes, this.BasePlane); var planes = kinematic.Planes.ToList(); var meshes = (displayMeshes) ? kinematic.Meshes.ToList() : null; // Tool if (target.Tool != null) { Plane toolPlane = target.Tool.Tcp; toolPlane.Transform(planes[planes.Count - 1].ToTransform()); planes.Add(toolPlane); } else { planes.Add(planes[planes.Count - 1]); } if (displayMeshes) { if (target.Tool?.Mesh != null) { Mesh toolMesh = target.Tool.Mesh.DuplicateMesh(); toolMesh.Transform(Transform.PlaneToPlane(target.Tool.Tcp, planes[planes.Count - 1])); meshes.Add(toolMesh); } else { meshes.Add(null); } kinematic.Meshes = meshes.ToArray(); } kinematic.Planes = planes.ToArray(); kinematics.Add(kinematic); return(kinematics); }
// "Parse" the .xml trace file with Xml.Linq methods private IISFailedReqInfo ReadIISFailedReqTrace(string filePath) { IISFailedReqInfo info = new IISFailedReqInfo(); try { XNamespace frebNameSpace = ""; XDocument traceLog = XDocument.Load(filePath); XElement failedReqInfo = traceLog.Element("failedRequest"); if (failedReqInfo != null) { info.StatusCode = failedReqInfo.Attribute("statusCode")?.Value; info.RequestURL = failedReqInfo.Attribute("url")?.Value; info.TimeTaken = failedReqInfo.Attribute("timeTaken")?.Value; info.Verb = failedReqInfo.Attribute("verb")?.Value; frebNameSpace = failedReqInfo.Attribute(xmlns + "freb")?.Value; } IEnumerable <XElement> events = traceLog.Descendants(msNameSpace + "Event"); if (events != null) { IEnumerable <XElement> description = events.Descendants(msNameSpace + "RenderingInfo")?.Descendants(frebNameSpace + "Description")?.Where(elem => elem.Attribute("Data")?.Value == "ErrorCode" && (elem.PreviousNode as XElement)?.Value == "BEGIN_REQUEST"); if (description.Count() > 0) { info.ErrorCode = description?.First()?.Value; } IEnumerable <XElement> localAddress = events.Descendants(msNameSpace + "EventData")?.Descendants(msNameSpace + "Data")?.Where(elem => elem.Attribute("Name")?.Value == "LocalAddress"); if (localAddress.Count() > 0) { info.ClientIP = localAddress?.First()?.Value; } } } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(26011, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseEngine.GetEngineName(), "Could not read IIS failed request trace .xml document: " + e.Message, eMsgLevel.l1_Error)); } return(info); }
public T findItem <T>(string itemId) where T : HumanItem { IEnumerable <T> allItems = null; if (typeof(T) == typeof(HumanItem)) { allItems = new[] { ItemPack.shared.toolItems.Cast <T>(), ItemPack.shared.medicineItems.Cast <T>(), ItemPack.shared.battleItems.Cast <T>(), ItemPack.shared.equipmentItems.Cast <T>() }.SelectMany(item => item); } else if (typeof(T) == typeof(ToolItem)) { allItems = ItemPack.shared.toolItems.Cast <T>(); } else if (typeof(T) == typeof(MedicineItem)) { allItems = ItemPack.shared.medicineItems.Cast <T>(); } else if (typeof(T) == typeof(BattleItem)) { allItems = ItemPack.shared.battleItems.Cast <T>(); } else if (typeof(T) == typeof(HumanEquipment)) { allItems = ItemPack.shared.equipmentItems.Cast <T>(); } var selectedItem = allItems?.First((item) => { return(item.id == itemId); }); return(selectedItem); }
public override List <KinematicSolution> Kinematics(IEnumerable <Target> targets, IEnumerable <double[]?>?prevJoints = null) { var target = targets.First(); var prevJoint = prevJoints?.First(); string?error = null; if (prevJoint is not null && prevJoint.Length != 6) { error = $"Previous joints set but contain {prevJoint.Length} value(s), should contain 6 values."; prevJoint = null; } var kinematic = Robot.Kinematics(target, prevJoint, BasePlane); var planes = kinematic.Planes.ToList(); // Tool if (target.Tool is not null) { Plane toolPlane = target.Tool.Tcp; toolPlane.Orient(ref kinematic.Planes[planes.Count - 1]); planes.Add(toolPlane); } else { planes.Add(planes[planes.Count - 1]); } kinematic.Planes = planes.ToArray(); if (error is not null) { kinematic.Errors.Add(error); } return(new List <KinematicSolution> { kinematic }); }
private static object ConvertToMessageSystemProperty(string messagePropertyName, IEnumerable <string> messagePropertyValues) { string propertyValue = messagePropertyValues?.First(); switch (messagePropertyName) { case MessageSystemPropertyNames.LockToken: return(propertyValue.Trim('\"')); case MessageSystemPropertyNames.EnqueuedTime: case MessageSystemPropertyNames.ExpiryTimeUtc: return(DateTime.TryParse(propertyValue, out DateTime dateTime) ? dateTime : (object)null); case MessageSystemPropertyNames.SequenceNumber: return(propertyValue == null ? 0 : Convert.ToUInt64(propertyValue, CultureInfo.InvariantCulture)); case MessageSystemPropertyNames.DeliveryCount: return(byte.TryParse(propertyValue, out byte deliveryCount) ? deliveryCount : (object)null); default: return(propertyValue); } }
//public virtual object GetKey(object trade) //{ // //var type = trade.GetType().GetProperty(Key); // //var interfaces =type .GetInterfaces(); // //if (!type.IsAssignableFrom(typeof(IConvertible)) && !interfaces.Select(_=>_.Name).Any(_=>_.StartsWith("IEquatable"))) // // throw new Exception("Key of type "+ type.Name+ " does not inherit " + nameof(IConvertible) + " or "+ "IEquatable"); // //else // return null; //} public virtual string GetKey(IEnumerable _) { if (_.Count() > 0) { var type = _?.First()?.GetType(); if (type != null) { var xx = IdHelper.GetIdProperty(type); if (xx != null) { var sxx = IdHelper.CheckIdProperty(xx, type); if (sxx) { return(xx); } else { return(null); } } } } return(null); }
private static List <Contact> ReadExcelFileDOM(string filename) { string[] strRowValues = new string[5]; List <Contact> result = new List <Contact>(); Contact contact; try { using (SpreadsheetDocument document = SpreadsheetDocument.Open(filename, true)) { WorkbookPart workbookPart = document.WorkbookPart; IEnumerable <Sheet> Sheets = document.WorkbookPart.Workbook.GetFirstChild <Sheets>().Elements <Sheet>(); string relationshipId = Sheets?.First().Id.Value; WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(relationshipId); SheetData sheetData = worksheetPart.Worksheet.GetFirstChild <SheetData>(); int i = 1; int j = 0; string value; int[] valueIndexes = new int[5]; foreach (Row r in sheetData.Elements <Row>()) { foreach (Cell c in r.Elements <Cell>()) { if (c == null) { continue; } value = c.InnerText; if (c.DataType != null) { var stringTable = workbookPart.GetPartsOfType <SharedStringTablePart>().FirstOrDefault(); if (stringTable != null) { value = stringTable.SharedStringTable. ElementAt(int.Parse(value)).InnerText; } } strRowValues[j] = value; j = j + 1; } if (i == 1) { valueIndexes[0] = Array.IndexOf(strRowValues, "FullName"); valueIndexes[1] = Array.IndexOf(strRowValues, "CompanyName"); valueIndexes[2] = Array.IndexOf(strRowValues, "Position"); valueIndexes[3] = Array.IndexOf(strRowValues, "Country"); valueIndexes[4] = Array.IndexOf(strRowValues, "Email"); if (valueIndexes.Contains(-1)) { throw new FileNotFoundException("Wrong columns in Excel"); } j = 0; i = i + 1; continue; } j = 0; i = i + 1; if (strRowValues.Any(p => p == null)) { continue; } contact = new Contact(); contact.FullName = strRowValues[valueIndexes[0]]; contact.CompanyName = strRowValues[valueIndexes[1]]; contact.Position = strRowValues[valueIndexes[2]]; contact.Country = strRowValues[valueIndexes[3]]; contact.Email = strRowValues[valueIndexes[4]]; CheckContact(contact); result.Add(contact); } return(result); } } catch { throw; } }
/// <summary> /// Returns the target organisations groups details, based on the configuration of the funding output. /// eg will lookup /// - UKPRN and name for a Local Authority to pay /// - UKRPN and name of a multi academy trust to pay /// </summary> /// <param name="identifierValue">Identifier value of the Organisation Group</param> /// <param name="organisationGroupTypeCode">Organisation Group Type Code</param> /// <param name="providerVersionId">Provider version</param> /// <param name="providersInGroup">Providers in group</param> /// <returns></returns> private async Task <TargetOrganisationGroup> GetTargetProviderDetailsForPaymentOrContracting(string identifierValue, OrganisationGroupTypeCode?organisationGroupTypeCode, string providerVersionId, IEnumerable <Provider> providersInGroup) { if (!organisationGroupTypeCode.HasValue) { throw new Exception("Unable to lookup target provider, no OrganisationGroupTypeCode given"); } Provider targetProvider = null; // Always return a UKRPN, as we need to pay a LegalEntity if (organisationGroupTypeCode == OrganisationGroupTypeCode.AcademyTrust || organisationGroupTypeCode == OrganisationGroupTypeCode.LocalAuthority) { Dictionary <string, Provider> allProviders = await GetAllProviders(providerVersionId); if (organisationGroupTypeCode == OrganisationGroupTypeCode.LocalAuthority) { // Lookup the local authority by LACode and provider type and subtype targetProvider = allProviders.Values.SingleOrDefault(p => p.ProviderType == "Local Authority" && p.ProviderSubType == "Local Authority" && p.LACode == identifierValue); } else if (organisationGroupTypeCode == OrganisationGroupTypeCode.AcademyTrust) { // Lookup by multi academy trust. NOTE: actual data does not contain the multi academy trust entity targetProvider = allProviders.Values.SingleOrDefault(p => p.TrustCode == identifierValue && _academyTrustTypes.Any(_ => p.ProviderType.Equals(_, StringComparison.OrdinalIgnoreCase) || p.ProviderSubType.Equals(_, StringComparison.OrdinalIgnoreCase))); if (targetProvider == null && !providersInGroup.IsNullOrEmpty()) { targetProvider = new Provider { ProviderId = identifierValue, UKPRN = identifierValue, TrustCode = identifierValue, Name = providersInGroup?.First().TrustName, PaymentOrganisationIdentifier = providersInGroup?.First().ProviderId, PaymentOrganisationName = providersInGroup?.First().Name }; } } } else if (organisationGroupTypeCode == OrganisationGroupTypeCode.Provider) { targetProvider = providersInGroup.SingleOrDefault(p => p.UKPRN == identifierValue); } else { throw new Exception($"Unable to lookup target provider, unsupported OrganisationGroupTypeCode of '{organisationGroupTypeCode}'"); } if (targetProvider == null) { throw new Exception($"Unable to find target provider, given the OrganisationGroupTypeCode. Identifier = '{identifierValue}'. OrganisationGroupTypeCode= '{organisationGroupTypeCode}'"); } // Return the provider if found. IEnumerable <OrganisationIdentifier> identifiers = GenerateIdentifiersForProvider(GroupingReason.Payment, organisationGroupTypeCode.Value, targetProvider); return(new TargetOrganisationGroup() { Identifier = targetProvider.UKPRN, Name = targetProvider.Name, Identifiers = identifiers }); }
public static IEnumerable <TablesModel> ReadModelList(string filepath) { using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filepath, false)) { WorkbookPart wbPart = spreadsheetDocument.WorkbookPart; var theSheets = wbPart.Workbook; var tableData = new List <TablesModel> { }; var _sheet = new Dictionary <string, string>(); // sheet id, sheet name foreach (Sheet item in theSheets.Sheets) { System.Console.WriteLine($"Sheet Name: {item.Name}"); IEnumerable <Sheet> _sheets = wbPart.Workbook.GetFirstChild <Sheets>(). Elements <Sheet>().Where(s => s.Name == item.Name); if (_sheets?.Count() == 0) { //return null; } string relationshipId = _sheets?.First().Id.Value; WorksheetPart parts = (WorksheetPart)wbPart.GetPartById(relationshipId); var _parts = new List <WorksheetPart>(); _parts.Add(parts); foreach (WorksheetPart WSP in _parts) { //find sheet data IEnumerable <SheetData> sheetData = WSP.Worksheet.Elements <SheetData>(); // Iterate through every sheet inside Excel sheet foreach (SheetData SD in sheetData) { IEnumerable <Row> row = SD.Elements <Row>(); // Get the row IEnumerator var rowData = row.Where(o => !string.IsNullOrWhiteSpace(o.InnerText)); foreach (var r in rowData) { var _cell = r.Descendants <Cell>() .Select(o => GetCellText(o, wbPart.SharedStringTablePart.SharedStringTable)).ToList(); var t = new TablesModel { Key = (_cell[1] != null) ? _cell[1].Trim() : "", Column = (_cell[2] != null) ? _cell[2].Trim() : "", DataType = (_cell[3] != null) ? _cell[3].Trim() : "", IsNull = (_cell[4] != null) ? _cell[4].Trim() : "", ColumnName = (_cell[5] != null) ? _cell[5].Trim() : "", DefaultValue = (_cell[6] != null) ? _cell[6].Trim() : "", Comment = (_cell[7] != null) ? _cell[7].Trim() : "", }; tableData.Add(t); //Console.WriteLine(t); //Console.WriteLine(String.Join("\t", _cell)); } } } } return(tableData); } }