public static short[] DropManyU( IVisio.Page page, IList<IVisio.Master> masters, IEnumerable<VA.Drawing.Point> points) { if (masters == null) { throw new System.ArgumentNullException("masters"); } if (masters.Count < 1) { return new short[0]; } if (points == null) { throw new System.ArgumentNullException("points"); } // NOTE: DropMany will fail if you pass in zero items to drop var masters_obj_array = masters.Cast<object>().ToArray(); var xy_array = VA.Drawing.Point.ToDoubles(points).ToArray(); System.Array outids_sa; page.DropManyU(masters_obj_array, xy_array, out outids_sa); short[] outids = (short[])outids_sa; return outids; }
public IList<object> CreateInsert(IList<object> list) { IList<SampleSQLData> convertedList = list.Cast<SampleSQLData>().ToList(); IList<object> insertList = new List<object>(); foreach (SampleSQLData sample in convertedList) { foreach (var fk in sample.FK_References) { SampleSQLData sampleDataFiltered = convertedList.Where(l => !_tablesLoaded.ContainsKey(fk.Table) && l.Table == fk.Table).SingleOrDefault(); if (sampleDataFiltered != null) { TSQLProcessor.Execute(new CreateInsertSQL(), sampleDataFiltered, insertList); _tablesLoaded.Add(fk.Table, true); } } if (!_tablesLoaded.ContainsKey(sample.Table)) { TSQLProcessor.Execute(new CreateInsertSQL(), sample, insertList); _tablesLoaded.Add(sample.Table, true); } } return insertList; }
public IList TransformList(IList collection) { if (_listTransformation == null) { return collection; } IEnumerable<object> toTransform; if (collection.Count > 0 && collection[0] is object[]) { if (((object[])collection[0]).Length != 1) { // We only expect single items throw new NotSupportedException(); } toTransform = collection.Cast<object[]>().Select(o => o[0]); } else { toTransform = collection.Cast<object>(); } object transformResult = _listTransformation.DynamicInvoke(toTransform); var resultList = transformResult as IList; return resultList ?? new List<object> { transformResult }; }
public IList<object> CreateDelete(IList<object> list, IDictionary<string, string> dynamicParameters) { IList<SampleMongoData> convertedList = list.Cast<SampleMongoData>().ToList(); IList<object> deleteList = new List<object>(); foreach (var sample in convertedList) { IDictionary<string, IList<BsonElement>> data = new Dictionary<string, IList<BsonElement>>(); IList<BsonElement> elementList = new List<BsonElement>(); foreach (var row in sample.Rows) { foreach (var key in sample.Keys) { Common.Schema schema = sample.Schema.SingleOrDefault(s => s.Column == key); string value = JSON.DeserializeDynamic(row.ToString())[schema.Column]; if (dynamicParameters.ContainsKey(value)) { value = dynamicParameters[value]; } elementList.Add(new BsonElement(schema.Column, ParserDataType.ParseMongo((ParserDataType.DataType)Enum.Parse(typeof(ParserDataType.DataType), schema.Type, true), value))); } } data.Add(sample.Collection, elementList); deleteList.Add(data); } return deleteList; }
private void AddSongsToPlayListExecute(IList songs) { if (songs != null) { PlayerObserver.NotifyAddToPlayList(new ObservableCollection<Song>(songs.Cast<Song>())); } }
void IProfileSelector.FillNames(IList<string> profiles) { profileComboBox.Items.Clear(); profileComboBox.Items.AddRange(Filter == null ? profiles.Cast<object>().ToArray() : profiles.Where(x => Filter(x)).Cast<object>().ToArray()); }
private void SetExecReportOrders(IList orders) { if (orders == null) return; ExecutionStatsGenerator.SetOrders(orders.Cast<Order>().ToList()); var window = new ExecutionReportWindow(ExecutionStatsGenerator); window.Show(); }
public IList TransformList(IList collection) { if (_listTransformation == null) { return collection; } object transformResult = collection; //if (collection.Count > 0) { if (collection.Count > 0 && collection[0] is object[]) { if ( ((object[])collection[0]).Length != 1) { // We only expect single items throw new NotSupportedException(); } transformResult = _listTransformation.DynamicInvoke(collection.Cast<object[]>().Select(o => o[0])); } else { transformResult = _listTransformation.DynamicInvoke(collection); } } if (transformResult is IList) { return (IList) transformResult; } var list = new ArrayList {transformResult}; return list; }
private void AddToIgnoreList(IList itemsToHide) { var items = itemsToHide.Cast<ShortcutViewModel>().ToList(); shortcuts.RemoveAll(items); var entries = items.Select(shortcut => new IgnoreEntry(path: shortcut.ShortcutPath)).ToArray(); tilesDavis.AddToIgnoreList(entries); }
public static IList groupByKey(IList list, IList keys) { return list.Cast<object>().Zip(keys.Cast<object>(), (item, key) => new { item, key }) .GroupBy(x => x.key) .Select(x => x.Select(y => y.item).ToList()) .ToList(); }
public override SqlString Render(IList args, ISessionFactoryImplementor factory) { return SqlString.Parse( args.Cast<object>() .Select(x => x.ToString()) .ToString(x => "ISNULL(" + x + ", '')", " + ' ' + ") ); }
private void AddAndNotify(IList items) { if (items.Count > 0) { filteredCollection.AddRange(items.Cast<object>()); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, items)); } }
public void SetColumns(IList<string> nameList, IList<bool> checkedList) { checkedListBox1.Items.Clear(); checkedListBox1.Items.AddRange(nameList.Cast<object>().ToArray()); for (int i = 0; i < checkedList.Count; i++) { checkedListBox1.SetItemChecked(i, checkedList[i]); } }
/// <summary> /// Create a polygon from a list of at least 3 points with no duplicates. /// </summary> /// <param name="points">A list of unique points</param> public Polygon( IList<PolygonPoint> points ) { if (points.Count < 3) throw new ArgumentException("List has fewer than 3 points", "points"); // Lets do one sanity check that first and last point hasn't got same position // Its something that often happen when importing polygon data from other formats if (points[0].Equals(points[points.Count - 1])) points.RemoveAt(points.Count - 1); _points.AddRange(points.Cast<TriangulationPoint>()); }
private void RunUserScripts(IList trades) { if (trades == null || trades.Count == 0) return; Parent.ScriptRunner.RunTradeScripts(trades.Cast<Trade>().ToList(), Context.Strategies.ToList(), Context.Tags.ToList(), Context); foreach(Trade trade in trades) { trade.TagStringUpdated(); } }
public MenuItemWrapper(RumpsRunner parent, string text, Duplicati.GUI.TrayIcon.MenuIcons icon, Action callback, IList<Duplicati.GUI.TrayIcon.IMenuItem> subitems) { m_parent = parent; Key = Guid.NewGuid().ToString("N"); m_text = text ?? ""; Callback = callback; m_enabled = true; m_default = false; if (subitems != null) Subitems = subitems.Cast<MenuItemWrapper>().ToList(); }
private static void DoInitialSync(IList sourceList, ICollection<object> items, ICollection<object> selectedItems) { var toRemove = sourceList.Cast<object>().Where(item => !items.Contains(item)).ToList(); foreach (var item in toRemove) { sourceList.Remove(item); } foreach (var item in sourceList) { selectedItems.Add(item); } }
public IList<CounterDescriptor> UpdateCounterItems(IList<CounterDescriptor> counterItems) { ServerManager iisManager = new ServerManager(); var processes = iisManager.WorkerProcesses; //remove old var oldIds = new List<int>(); foreach (var counterDescriptor in counterItems.Cast<IisWorkerProcessCpuCounterDescriptor>()) { if (!processes.Any(proc => proc.ProcessId == counterDescriptor.ProcessId) || !Process.GetProcesses().Any(process => process.Id == counterDescriptor.ProcessId)) { oldIds.Add(counterDescriptor.ProcessId); } else { //fix names var correctProcessName = PerformanceCounterProcessHelper.GetPerformanceCounterProcessName(counterDescriptor.ProcessId); if (!String.Equals(counterDescriptor.SystemCounter.InstanceName, correctProcessName, StringComparison.InvariantCulture)) { counterDescriptor.SystemCounter.InstanceName = correctProcessName; } } } counterItems = counterItems.Cast<IisWorkerProcessCpuCounterDescriptor>().Where(counter => !oldIds.Contains(counter.ProcessId)).Cast<CounterDescriptor>().ToList(); //add new foreach (var w3wp in processes) { if (!counterItems.Cast<IisWorkerProcessCpuCounterDescriptor>().Any(rd => rd.ProcessId == w3wp.ProcessId) && Process.GetProcesses().Any(process => process.Id == w3wp.ProcessId)) { counterItems.Add(CreateDescriptor(w3wp)); } } return counterItems; }
/// <summary> /// Create a polygon from a list of at least 3 points with no duplicates. /// </summary> /// <param name="points">A list of unique points</param> public Polygon( IList<PolygonPoint> points ) { if (points.Count < 3) throw new ArgumentException("List has fewer than 3 points", "points"); #if DOTNET2 _points.Capacity = System.Math.Max (_points.Capacity,_points.Count + points.Count); for (int i=0;i<points.Count;i++) _points.Add (points[i]); #else _points.AddRange(points.Cast<TriangulationPoint>()); #endif // Lets do one sanity check that first and last point hasn't got same position // Its something that often happen when importing polygon data from other formats // Note: Removing from internal list since the argument "points" should not be modified if (points[0].Equals(points[points.Count - 1])) _points.RemoveAt(_points.Count - 1); }
private void DeleteMapping(IList selectedList) { if (selectedList == null || selectedList.Count == 0) return; var itemsToDelete = selectedList.Cast<TestCaseOldNewMapping>().ToList(); App.Current.Dispatcher.Invoke(() => { foreach (TestCaseOldNewMapping map in itemsToDelete) { DuplicatedTestCase.Remove(map); } }); Settings.Default.Mappings = JsonConvert.SerializeObject(DuplicatedTestCase); Settings.Default.Save(); }
public async Task MessagesDeliveredAsync(IList<IBatchContainer> messages) { try { var queueRef = _queue; // store direct ref, in case we are somehow asked to shutdown while we are receiving. if (messages.Count == 0 || queueRef == null) return; var cloudQueueMessages = messages.Cast<RabbitMessageQueueBatchContainer>().Select(b => b.QueueMessage).ToList(); _outstandingTask = Task.WhenAll(cloudQueueMessages.Select(queueRef.DeleteQueueMessage)); await _outstandingTask; } finally { _outstandingTask = null; } }
/// <summary> /// Creates a new <see cref="IDataItem"/> instance using the specified parameters. /// </summary> /// <param name="etpAdapter">The ETP adapter.</param> /// <param name="channelId">The channel identifier.</param> /// <param name="value">The channel data value.</param> /// <param name="indexes">The channel index values.</param> /// <param name="attributes">The data attributes.</param> /// <returns>A new <see cref="IDataItem"/> instance.</returns> public static IDataItem CreateDataItem(this IEtpAdapter etpAdapter, long channelId, object value = null, IList <object> indexes = null, IList <object> attributes = null) { if (etpAdapter.SupportedVersion == EtpVersion.v11) { return(new Energistics.Etp.v11.Datatypes.ChannelData.DataItem { ChannelId = channelId, Indexes = indexes?.Cast <long>().ToArray() ?? new long[0], Value = new Energistics.Etp.v11.Datatypes.DataValue { Item = value }, ValueAttributes = attributes? .Select((x, i) => new Energistics.Etp.v11.Datatypes.DataAttribute { AttributeId = i, AttributeValue = new Energistics.Etp.v11.Datatypes.DataValue { Item = x } }) .ToArray() ?? new Energistics.Etp.v11.Datatypes.DataAttribute[0] }); } return(new Energistics.Etp.v12.Datatypes.ChannelData.DataItem { ChannelId = channelId, Indexes = indexes?.Select(i => new Energistics.Etp.v12.Datatypes.IndexValue { Item = i }).ToList() ?? new List <Energistics.Etp.v12.Datatypes.IndexValue>(), Value = new Energistics.Etp.v12.Datatypes.DataValue { Item = value }, ValueAttributes = attributes? .Select((x, i) => new Energistics.Etp.v12.Datatypes.DataAttribute { AttributeId = i, AttributeValue = new Energistics.Etp.v12.Datatypes.DataValue { Item = x } }) .ToArray() ?? new Energistics.Etp.v12.Datatypes.DataAttribute[0] }); }
static IDictionary<string, object> NarrowAssets(IList<object> assets, IList<Tuple<string,string>> query) { if (assets.Count == 1) { return assets[0] as IDictionary<string, object>; } var matches = new List<IDictionary<string, object>>(); foreach (var asset in assets.Cast<IDictionary<string, object>>()) { var match = true; foreach (var pair in query) { var pattern = pair.Item2; var inverted = false; if (pattern.StartsWith("!")) { pattern = pattern.Substring(1); inverted = true; } var value = asset[pair.Item1] as string; var isLike = value.Like(pattern); if (inverted) { isLike = !isLike; } match = match && isLike; } if (match) { matches.Add(asset); } } if (matches.Count > 1) { throw new Exception("Could not decide from available assets, add a filter"); } if (matches.Count == 0) { throw new Exception("Expected to find at least one asset"); } return matches[0]; }
public IList<object> CreateDelete(IList<object> list, IDictionary<string, string> dynamicParameters) { IList<SampleSQLData> convertedList = list.Cast<SampleSQLData>().ToList(); IList<object> deleteList = new List<object>(); IList<SampleSQLData> childData = SetDeletionPriority(convertedList.Where(l => l.FK_References.Count > 0).ToList()); IList<SampleSQLData> parentData = convertedList.Where(l => l.FK_References.Count == 0).ToList(); foreach (var child in childData) { TSQLProcessor.Execute(new CreateDeleteSQL(), child, deleteList, dynamicParameters); } foreach (var parent in parentData) { TSQLProcessor.Execute(new CreateDeleteSQL(), parent, deleteList, dynamicParameters); } return deleteList; }
private async void DeleteOrders(IList orders) { if (orders == null || orders.Count == 0) return; var selectedOrders = orders.Cast<Order>().ToList(); var res = await DialogService.ShowMessageAsync(Parent, "Delete Order(s)", string.Format("Are you sure you want to delete {0} order(s)?", selectedOrders.Count), MessageDialogStyle.AffirmativeAndNegative); if (res != MessageDialogResult.Affirmative) return; foreach (Order o in selectedOrders) { //remove executions first if(o.Executions != null) { List<Execution> toRemove = o.Executions.ToList(); foreach(Execution exec in toRemove) { Context.Executions.Remove(exec); } o.Executions.Clear(); } //if the order belongs to a trade, remove it if (o.Trade != null) { TradesRepository.RemoveOrder(o.Trade, o); } //finally delete the order Context.Orders.Remove(o); } Context.SaveChanges(); }
/// <summary> /// Sends a ChannelData message to a consumer. /// </summary> /// <param name="request">The request.</param> /// <param name="dataItems">The list of <see cref="IDataItem" /> objects.</param> /// <param name="messageFlag">The message flag.</param> /// <returns>The message identifier.</returns> long IStreamingProducer.ChannelData(IMessageHeader request, IList <IDataItem> dataItems, MessageFlags messageFlag) { return(ChannelData(request, dataItems.Cast <DataItem>().ToList(), messageFlag)); }
/// <summary> /// Sends a ChannelMetadata message to a consumer. /// </summary> /// <param name="request">The request.</param> /// <param name="channelMetadataRecords">The list of <see cref="IChannelMetadataRecord" /> objects.</param> /// <param name="messageFlag">The message flag.</param> /// <returns>The message identifier.</returns> long IStreamingProducer.ChannelMetadata(IMessageHeader request, IList <IChannelMetadataRecord> channelMetadataRecords, MessageFlags messageFlag) { return(ChannelMetadata(request, channelMetadataRecords.Cast <ChannelMetadataRecord>().ToList(), messageFlag)); }
protected override IEnumerable <T> GetObjects <T>() { var objectType = typeof(T); if (objectType == typeof(INation)) { return(_nations.Cast <T>()); } if (objectType == typeof(IBranch)) { return(_branches.Cast <T>()); } if (objectType == typeof(IVehicle)) { return(_vehicles.Cast <T>()); } if (objectType == typeof(IVehicleSubclasses)) { return(_vehicleSubclasses.Cast <T>()); } if (objectType == typeof(IAircraftTags)) { return(_aircraftTags.Cast <T>()); } if (objectType == typeof(IGroundVehicleTags)) { return(_groundVehicleTags.Cast <T>()); } if (objectType == typeof(IVehicleResearchTreeData)) { return(_vehicleResearchTreeData.Cast <T>()); } if (objectType == typeof(IVehicleEconomyData)) { return(_vehicleEconomyData.Cast <T>()); } if (objectType == typeof(IVehiclePerformanceData)) { return(_vehiclePerformanceData.Cast <T>()); } if (objectType == typeof(IVehicleCrewData)) { return(_vehicleCrewData.Cast <T>()); } if (objectType == typeof(IVehicleWeaponsData)) { return(_vehicleWeaponsData.Cast <T>()); } if (objectType == typeof(IVehicleModificationsData)) { return(_vehicleModificationsData.Cast <T>()); } if (objectType == typeof(IVehicleGraphicsData)) { return(_vehicleGraphicsData.Cast <T>()); } if (objectType == typeof(IVehicleGameModeParameterSetBase)) { return(_vehicleGameModeParameterSets.Cast <T>()); } if (objectType == typeof(ILocalisation)) { return(_localizationRecords.Cast <T>()); } if (objectType == typeof(IVehicleImages)) { return(_vehicleImages.Cast <T>()); } return(new List <T>()); }
/// <summary> /// Override this in a derived class to provide logic for when members other than the bot /// leave the channel, such as your bot's good-bye logic. /// </summary> /// <param name="teamsMembersRemoved">A list of all the members removed from the channel, as /// described by the conversation update activity.</param> /// <param name="teamInfo">The team info object representing the team.</param> /// <param name="turnContext">A strongly-typed context object for this turn.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A task that represents the work queued to execute.</returns> protected virtual Task OnTeamsMembersRemovedAsync(IList <TeamsChannelAccount> teamsMembersRemoved, TeamInfo teamInfo, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken) { return(OnMembersRemovedAsync(teamsMembersRemoved.Cast <ChannelAccount>().ToList(), turnContext, cancellationToken)); }
public static List <object> ConvertForBinding(IList <T> list) { return(list.Cast <object>().ToList()); }
public override SyntaxNode CreateSwitchStatement(SyntaxNode expression, IList <SyntaxNode> switchSections) { return(SyntaxFactory.SwitchStatement( (ExpressionSyntax)expression, switchSections.Cast <SwitchSectionSyntax>().ToSyntaxList())); }
public static StringScalar join(object seperator, IList objects) { return(new StringScalar(string.Join((string)str(seperator).Value, objects?.Cast <object>().Select(o => o?.ToString() ?? "") ?? new string[] { "" }))); }
private List <T> CloneListAs <T>(IList <object> source) { // Here we can do anything we want with T // T == source[0].GetType() return(source.Cast <T>().ToList()); }
public override object ExecuteScalar(IDbConnection connection, string cmdText, IList<IDbDataParameter> parameter) { return DbMySqlHelper.ExecuteScalar((MySqlConnection)connection, CommandType.Text, cmdText, parameter == null ? null : parameter.Cast<MySqlParameter>().ToArray()); }
public void ExportPages(IList selectedItems) { ExportPages(selectedItems.Cast <NoteBookPage>().ToList()); }
public static Packet CreateUsersAlreadyHerePacket(IList <UserThread> users) { return(new Packet(NetConstants.PacketTypes.UserAlreadyHere, ConcatPackets(users.Cast <NetSerializable>().ToList()))); }
public void MutateRows(byte[] tableName, IList<IHBaseMutation> mutations, long? timestamp = null) { Connection.MutateRows(tableName, mutations.Cast<Protocols.IHBaseMutation>().ToList(), timestamp); }
protected override void TaksitOlustur() { if (_faturaPlaniKartlari != null) { TopluFaturaPlani(); return; } var tahakkukId = _alinanHizmetlerSource.Select(x => x.TahakkukId).First(); var alinanHizmetler = _alinanHizmetlerSource.Select(x => x.HizmetAdi).ToList(); var hizmetlerToplami = _alinanHizmetlerSource.Sum(x => x.BrutUcret); var indirimlerToplami = _alinanHizmetlerSource.Sum(x => x.Indirim); var ilkFaturaTarih = txtIlkFaturaTarih.DateTime.Date; var faturaAdet = (int)txtAdet.Value; var sabitTutar = txtSabitTutar.Value; var ozelTahakkuk = txtOzetTahakkuk.Text.GetEnum <EvetHayir>(); var ozetAciklama = txtOzetTahakkukAciklama.Text; var girilenBrutTutarToplami = _faturaPlaniSource.Cast <FaturaPlaniL>().Where(x => !x.Delete).Sum(x => x.PlanTutar); var girilenIndirimTutarToplami = _faturaPlaniSource.Cast <FaturaPlaniL>().Where(x => !x.Delete).Sum(x => x.PlanIndirimTutar); var girilecekBrutTutar = sabitTutar > 0 ? sabitTutar : Math.Round((hizmetlerToplami - girilenBrutTutarToplami) / faturaAdet, AnaForm.DonemParametreleri.FaturaTahakkukKurusKullan ? 2 : 0); var girilecekIndirimTutar = sabitTutar > 0 ? 0 : Math.Round((indirimlerToplami - girilenIndirimTutarToplami) / faturaAdet, AnaForm.DonemParametreleri.FaturaTahakkukKurusKullan ? 2 : 0); var girilecekNetTutar = (girilecekBrutTutar - girilecekIndirimTutar); if (girilecekBrutTutar <= 0) { Messages.UyariMesaji("Verilen Hizmetler Toplamı Kadar Fatura Planı Zaten Oluşturulmuş."); return; } for (int i = 0; i < faturaAdet; i++) { var row = new FaturaPlaniL { TahakkukId = tahakkukId, Aciklama = ozelTahakkuk == EvetHayir.Evet ? ozetAciklama : AlinanHizmetler(alinanHizmetler) + " Bedeli", PlanTarih = ilkFaturaTarih.AddMonths(i), PlanTutar = girilecekBrutTutar, PlanIndirimTutar = girilecekIndirimTutar, PlanNetTutar = girilecekNetTutar, Insert = true, }; if (txtOzetTahakkuk.Text.GetEnum <EvetHayir>() == EvetHayir.Evet) { row.Aciklama = ozetAciklama; } if (txtAyBilgisi.Text.GetEnum <EvetHayir>() == EvetHayir.Evet) { var ay = (Aylar)row.PlanTarih.Month; row.Aciklama = ay.ToName() + "-" + row.PlanTarih.Year + " Ayı" + row.Aciklama; } if (i + 1 == faturaAdet && sabitTutar == 0) { row.PlanTutar = hizmetlerToplami - _faturaPlaniSource.Cast <FaturaPlaniL>().Where(x => !x.Delete).Sum(x => x.PlanTutar); row.PlanIndirimTutar = indirimlerToplami - _faturaPlaniSource.Cast <FaturaPlaniL>().Where(x => !x.Delete).Sum(x => x.PlanIndirimTutar); row.PlanNetTutar = row.PlanTutar - row.PlanIndirimTutar; } _faturaPlaniSource.Add(row); } DialogResult = DialogResult.OK; Close(); }
/// <summary> /// Sends a ChannelDataChange message to a consumer. /// </summary> /// <param name="channelId">The channel identifier.</param> /// <param name="startIndex">The start index.</param> /// <param name="endIndex">The end index.</param> /// <param name="dataItems">The data items.</param> /// <returns>The message identifier.</returns> long IStreamingProducer.ChannelDataChange(long channelId, long startIndex, long endIndex, IList <IDataItem> dataItems) { return(ChannelDataChange(channelId, startIndex, endIndex, dataItems.Cast <DataItem>().ToList())); }
public void Save(Stream output, IList <IArchiveFileInfo> files, bool isCompressed) { var simpleHash = new SimpleHash(_sfatHeader.hashMultiplier); using var bw = new BinaryWriterX(output, true, _byteOrder); var sortedFiles = files.Cast <SarcArchiveFileInfo>().OrderBy(x => _sfntHeader == null ? x.Entry.nameHash : simpleHash.ComputeValue(x.FilePath.ToRelative().FullName)).ToArray(); // Calculate offsets var sfatOffset = HeaderSize; var sfntOffset = sfatOffset + SfatHeaderSize + files.Count * SfatEntrySize; var dataOffset = _sfntHeader == null ? sfntOffset + SfntHeaderSize : sfntOffset + SfntHeaderSize + files.Sum(x => (x.FilePath.ToRelative().FullName.Length + 4) & ~3); var alignment = sortedFiles.Max(x => SarcSupport.DetermineAlignment(x, _byteOrder, isCompressed)); var alignedDataOffset = (dataOffset + alignment - 1) & ~(alignment - 1); // Write files var entries = new List <SfatEntry>(); var strings = new List <string>(); var stringPosition = 0; var dataPosition = alignedDataOffset; foreach (var file in sortedFiles) { // Write file data alignment = SarcSupport.DetermineAlignment(file, _byteOrder, isCompressed); var alignedDataPosition = (dataPosition + alignment - 1) & ~(alignment - 1); output.Position = alignedDataPosition; var writtenSize = file.SaveFileData(output); // Add entry entries.Add(new SfatEntry { startOffset = alignedDataPosition - alignedDataOffset, endOffset = (int)(alignedDataPosition + writtenSize - alignedDataOffset), Flags = (short)(_sfntHeader == null ? 0 : 0x100), FntOffset = (short)(_sfntHeader == null ? 0 : stringPosition), nameHash = _sfntHeader == null ? file.Entry.nameHash : simpleHash.ComputeValue(file.FilePath.ToRelative().FullName) }); // Add string strings.Add(file.FilePath.ToRelative().FullName); dataPosition = (int)(alignedDataPosition + writtenSize); stringPosition += (file.FilePath.ToRelative().FullName.Length + 4) & ~3; } // Write SFNT output.Position = sfntOffset; bw.WriteType(new SfntHeader()); if (_sfntHeader != null) { foreach (var s in strings) { bw.WriteString(s, Encoding.ASCII, false); bw.WriteAlignment(4); } } // Write SFAT output.Position = sfatOffset; bw.WriteType(new SfatHeader { entryCount = (short)files.Count, hashMultiplier = _sfatHeader.hashMultiplier }); bw.WriteMultiple(entries); // Write header output.Position = 0; bw.WriteType(new SarcHeader { byteOrder = _byteOrder, dataOffset = alignedDataOffset, fileSize = (int)output.Length, unk1 = _header.unk1 }); }
private void SelectedItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { bool changeActive = (bool)IsSelectionChangeActiveProperty.GetValue(this, null); if (!changeActive) { IsSelectionChangeActiveProperty.SetValue(this, true, null); } switch (e.Action) { case NotifyCollectionChangedAction.Reset: var selectedItems = new HashSet <object> (SelectedItems.Cast <object> ()); TraverseTree((o, i) => { i.IsSelected = selectedItems.Remove(o); return(true); }); foreach (object item in SelectedItems) { GetTreeItem(item).IsSelected = true; } break; default: if (!changeActive && SelectionMode == System.Windows.Controls.SelectionMode.Single) { if (SelectedItems.Count > 0) { SelectedItems.Clear(); } if (e.NewItems != null && e.NewItems.Count > 0) { SelectedItems.Add(e.NewItems [0]); } } if (e.NewItems != null || e.OldItems != null) { HashSet <object> newItems = (e.NewItems != null) ? new HashSet <object> (e.NewItems.Cast <object> ()) : new HashSet <object> (); HashSet <object> oldItems = (e.OldItems != null) ? new HashSet <object> (e.OldItems.Cast <object> ()) : new HashSet <object> (); TraverseTree((o, ti) => { if (newItems.Remove(o)) { ti.IsSelected = true; } else if (SelectionMode == SWC.SelectionMode.Single || oldItems.Remove(o)) { ti.IsSelected = false; } return(newItems.Count + oldItems.Count > 0); }); } break; } OnSelectedItemsChanged(EventArgs.Empty); if (!changeActive) { IsSelectionChangeActiveProperty.SetValue(this, changeActive, null); } }
public void Save(IList <IResourcePerformanceCounter> counters) { var path = EnvironmentVariables.ServerResourcePerfmonSettingsFile; Save(counters.Cast <IPerformanceCounter>().ToList(), path); }
public override SyntaxNode CreateSwitchSection(SyntaxNode switchLabel, IList <SyntaxNode> statements) { return(SyntaxFactory.SwitchSection( SyntaxFactory.SingletonList((SwitchLabelSyntax)switchLabel), statements.Cast <StatementSyntax>().ToSyntaxList())); }
public static void Update( [CanBeNull] string whereClause, [NotNull] IList <IObjectClass> targetExceptionClasses, [NotNull] IList <IObjectClass> updateExceptionClasses, [NotNull] string updateOriginValue, DateTime updateDate, bool requireOriginalVersionExists = true) { IIssueTableFields updateFields = GetUpdateFields(updateExceptionClasses); IIssueTableFields targetFields = GetTargetFields(targetExceptionClasses); var editableAttributes = new[] { IssueAttribute.ExceptionStatus, IssueAttribute.ExceptionCategory, IssueAttribute.ExceptionNotes, IssueAttribute.ExceptionOrigin, IssueAttribute.ExceptionDefinitionDate, IssueAttribute.ExceptionLastRevisionDate, IssueAttribute.ExceptionRetirementDate, IssueAttribute.IssueAssignment }; using (_msg.IncrementIndentation( "Updating exceptions based on exported exception datasets...")) { foreach (ITable updateTable in updateExceptionClasses.Cast <ITable>()) { using (_msg.IncrementIndentation("from {0}...", DatasetUtils.GetName(updateTable))) { ITable targetTable = GetTargetTable(updateTable, targetExceptionClasses); if (targetTable == null) { _msg.Warn( "No matching table in target workspace, ignoring import table"); continue; } var targetExceptionFactory = new ManagedExceptionVersionFactory( targetTable, targetFields, editableAttributes); var updateExceptionFactory = new ManagedExceptionVersionFactory( updateTable, updateFields, editableAttributes); ExceptionUpdateDetector updateDetector = GetUpdateDetector( targetTable, targetExceptionFactory, editableAttributes); var replacedOids = new HashSet <int>(); var updatedRowsCount = 0; var rowsWithConflictsCount = 0; using (var exceptionWriter = new ExceptionWriter(updateTable, updateFields, targetTable, targetFields)) { foreach (IRow updateRow in GdbQueryUtils.GetRows( updateTable, GetQueryFilter(whereClause), recycle: true)) { ManagedExceptionVersion updateExceptionVersion = updateExceptionFactory.CreateExceptionVersion(updateRow); ManagedExceptionVersion mergedException; ManagedExceptionVersion replacedExceptionVersion; IList <ExceptionAttributeConflict> conflicts; if (updateDetector.HasChange(updateExceptionVersion, out mergedException, out replacedExceptionVersion, out conflicts)) { if (replacedExceptionVersion == null) { string message = string.Format( "Exception version {0} not found in lineage {1} (target table: {2})", ExceptionObjectUtils.FormatGuid( updateExceptionVersion.VersionUuid), ExceptionObjectUtils.FormatGuid( updateExceptionVersion.LineageUuid), DatasetUtils.GetName(targetTable)); if (requireOriginalVersionExists) { throw new InvalidDataException(message); } _msg.WarnFormat( "{0}. Creating new version with attributes from update row.", message); } updatedRowsCount++; string versionImportStatus; if (conflicts.Count == 0) { versionImportStatus = null; } else { versionImportStatus = FormatConflicts(conflicts, targetFields); rowsWithConflictsCount++; LogConflicts(conflicts, targetFields); } exceptionWriter.Write(updateRow, updateDate, mergedException, FormatOriginValue(updateOriginValue, replacedExceptionVersion), updateOriginValue, versionImportStatus); if (replacedExceptionVersion != null) { replacedOids.Add(replacedExceptionVersion.ObjectID); } } } } _msg.InfoFormat("{0:N0} exception(s) updated", updatedRowsCount); if (rowsWithConflictsCount > 0) { _msg.WarnFormat("{0:N0} exception(s) with conflicts", rowsWithConflictsCount); } if (replacedOids.Count > 0) { int fixedStatusCount; int updateCount = ProcessReplacedExceptions(targetTable, targetFields, updateDate, replacedOids, out fixedStatusCount); _msg.DebugFormat("{0:N0} replaced exception version(s) updated", updateCount); if (fixedStatusCount > 0) { _msg.WarnFormat( "Status value of {0:N0} old exception version(s) fixed", fixedStatusCount); } } } } } }
private BlockSyntax CreateBlock(IList <SyntaxNode> statements) { return(SyntaxFactory.Block(SyntaxFactory.List(statements.Cast <StatementSyntax>()))); }
public static void Import( [CanBeNull] string importWhereClause, [NotNull] IList <IObjectClass> targetExceptionClasses, [NotNull] IList <IObjectClass> importExceptionClasses, [NotNull] string importOriginValue, DateTime importDate) { IIssueTableFields importFields = GetImportFields(importExceptionClasses); IIssueTableFields targetFields = GetTargetFields(targetExceptionClasses); IDictionary <Guid, QualityConditionExceptions> targetExceptionsByConditionVersion; using (_msg.IncrementIndentation( "Reading existing exceptions in target workspace")) { targetExceptionsByConditionVersion = ReadTargetExceptions(targetExceptionClasses, targetFields); } var replacedExceptionObjects = new Dictionary <esriGeometryType, HashSet <int> >(); using (_msg.IncrementIndentation("Importing new exceptions from issue datasets...") ) { foreach (ITable importTable in importExceptionClasses.Cast <ITable>()) { using (_msg.IncrementIndentation("from {0}...", DatasetUtils.GetName(importTable))) { ITable targetTable = GetTargetTable(importTable, targetExceptionClasses); if (targetTable == null) { _msg.Warn( "No matching table in target workspace, ignoring import table"); continue; } var factory = new ExceptionObjectFactory( importTable, importFields, defaultStatus: ExceptionObjectStatus.Inactive); var newCount = 0; var updateCount = 0; var ignoredCount = 0; using (var writer = new ExceptionWriter(importTable, importFields, targetTable, targetFields)) { foreach (IRow row in GdbQueryUtils.GetRows(importTable, GetQueryFilter( importWhereClause), recycle: true)) { int matchCount; bool added = ImportException(row, importOriginValue, importDate, factory, targetExceptionsByConditionVersion, replacedExceptionObjects, writer, out matchCount); if (!added) { ignoredCount++; } else if (matchCount == 0) { newCount++; } else { updateCount++; } } } _msg.InfoFormat("{0:N0} exception(s) imported as new", newCount); _msg.InfoFormat("{0:N0} exception(s) imported as updates", updateCount); if (ignoredCount > 0) { _msg.InfoFormat("{0:N0} exception(s) ignored", ignoredCount); } } } } using (_msg.IncrementIndentation("Processing replaced exceptions...")) { foreach (ITable targetTable in targetExceptionClasses.Cast <ITable>()) { using (_msg.IncrementIndentation("Target table {0}...", DatasetUtils.GetName(targetTable))) { int fixedStatusCount; int updateCount = ProcessReplacedExceptions(targetTable, targetFields, replacedExceptionObjects, importDate, out fixedStatusCount); _msg.InfoFormat("{0:N0} replaced exception(s) updated", updateCount); if (fixedStatusCount > 0) { _msg.InfoFormat("Status value of {0:N0} old exception version(s) fixed", fixedStatusCount); } } } } }
public IEnumerable <Table> Enumerable2Dand3D() { return(list2D.Cast <Table> ().Concat(list3D.Cast <Table> ())); }
public static IEnumerable <object> CastPlatform(this IList self) { return(self.Cast <object>()); }
/// <summary> /// Converts a generic, interface-based list to a non-generic collection of the concrete type. /// </summary> /// <param name="etpAdapter">The ETP adapter.</param> /// <param name="channels">The channel metadata.</param> /// <returns>A non-generic collection.</returns> public static IList ToList(this IEtpAdapter etpAdapter, IList <IChannelMetadataRecord> channels) { return(etpAdapter is Energistics.Etp.v11.Etp11Adapter ? channels.Cast <Energistics.Etp.v11.Datatypes.ChannelData.ChannelMetadataRecord>().ToList() : channels.Cast <Energistics.Etp.v12.Datatypes.ChannelData.ChannelMetadataRecord>().ToList() as IList); }
public void Save(Stream output, IList <IArchiveFileInfo> files) { using var bw = new BinaryWriterX(output); // Calculate offsets var nameOffset = 8; // Build string tree var fileNames = files.Select(x => x.FilePath.ToRelative().FullName).ToArray(); var rootNode = new StringNode(); rootNode.AddRange(fileNames); // Assign offsets to nodes var nodeOffsetMap = new Dictionary <StringNode, int>(); var nameTableOffset = AssignOffsets(rootNode, nameOffset, nodeOffsetMap); nameTableOffset = (nameTableOffset + 1) & ~1; // Write node tree output.Position = nameTableOffset; var fileId = 0; WriteNodes(rootNode, bw, nodeOffsetMap, ref fileId); var entryOffset = bw.BaseStream.Length; var fileOffset = entryOffset + files.Count * EntrySize; // Write files var entries = new List <PakEntry>(); var filePosition = fileOffset; foreach (var file in files.Cast <ArchiveFileInfo>()) { output.Position = filePosition; var writtenSize = file.SaveFileData(output); entries.Add(new PakEntry { offset = (int)filePosition, size = (int)writtenSize }); filePosition += writtenSize; } // Write entries output.Position = entryOffset; bw.WriteMultiple(entries); // Write strings foreach (var pair in nodeOffsetMap) { output.Position = pair.Value; bw.WriteString(pair.Key.Text, Encoding.ASCII, false); } // Write header output.Position = 0; bw.WriteType(new PakHeader { fileCount = (short)files.Count, entryOffset = (int)entryOffset, nameTable = (short)nameTableOffset }); }
private HashSet<object> initLookupDictionary(IList collection) { HashSet<object> dictionary; if (collection != null) { dictionary = new HashSet<object>(collection.Cast<object>()/*.ToList()*/); } else { dictionary = new HashSet<object>(); } return dictionary; }
/// <summary> /// Converts a generic, interface-based list to a non-generic collection of the concrete type. /// </summary> /// <param name="etpAdapter">The ETP adapter.</param> /// <param name="indexes">The index metadata.</param> /// <returns>A non-generic collection.</returns> public static IList ToList(this IEtpAdapter etpAdapter, IList <IIndexMetadataRecord> indexes) { return(etpAdapter is Energistics.Etp.v11.Etp11Adapter ? indexes.Cast <Energistics.Etp.v11.Datatypes.ChannelData.IndexMetadataRecord>().ToList() : indexes.Cast <Energistics.Etp.v12.Datatypes.ChannelData.IndexMetadataRecord>().ToList() as IList); }
public short[] DropManyU( IList<IVisio.Master> masters, IEnumerable<Point> points) { if (masters == null) { throw new System.ArgumentNullException(nameof(masters)); } if (masters.Count < 1) { return new short[0]; } if (points == null) { throw new System.ArgumentNullException(nameof(points)); } // NOTE: DropMany will fail if you pass in zero items to drop var masters_obj_array = masters.Cast<object>().ToArray(); var xy_array = Point.ToDoubles(points).ToArray(); System.Array outids_sa; if (this.Target.Master != null) { this.Target.Master.DropManyU(masters_obj_array, xy_array, out outids_sa); } else if (this.Target.Page != null) { this.Target.Page.DropManyU(masters_obj_array, xy_array, out outids_sa); } else if (this.Target.Shape != null) { this.Target.Shape.DropManyU(masters_obj_array, xy_array, out outids_sa); } else { throw new System.ArgumentException("Unhandled Drawing Surface"); } short[] outids = (short[]) outids_sa; return outids; }
private void WriteFieldMask(StringBuilder builder, IMessage value) { IList paths = (IList)value.Descriptor.Fields[FieldMask.PathsFieldNumber].Accessor.GetValue(value); AppendEscapedString(builder, string.Join(",", paths.Cast <string>().Select(ToCamelCase))); }
private bool ShouldRunCategories(IList categories) { var stringCategories = categories.Cast<string>().ToList(); if (_isRunOnly) // only run test if categories intersect (a category is present in both lists) return (_categories.Intersect(stringCategories).Any()); else // only run tests if categories DO NOT intersect (test has no categories that are present in _categories) return (!_categories.Intersect(stringCategories).Any()); }
/// <summary> /// Creates a new box. /// </summary> /// <param name="points"></param> public GeoCoordinateBox(IList <GeoCoordinate> points) : base(points.Cast <PointF2D>().ToArray <PointF2D>()) { }
public override int ExecuteNonQuery(IDbTransaction trans, string cmdText, IList<IDbDataParameter> parameter) { return DbMySqlHelper.ExecuteNonQuery(trans as MySqlTransaction, CommandType.Text, cmdText, parameter == null ? null : parameter.Cast<MySqlParameter>().ToArray()); }
protected virtual bool CanRemoveRange(IList items) { return(items == null ? false : CanRemoveRange(items.Cast <MediaItem>())); }
private static IEnumerable <ConfigurationNodeViewModel> SelectNodes(IList items) => items?.Cast <ConfigurationStatViewModel>().Select(x => x.Node) ?? Enumerable.Empty <ConfigurationNodeViewModel>();
public IList <RankableAction> GetActions(bool useTextAnalytics) { return(useTextAnalytics ? _actionsWithTextAnalytics.Cast <RankableAction>().ToList() : _actions.Cast <RankableAction>().ToList()); }