private static List <TimePeriodClosingInfo> syncTimePeriodClosing <C>(List <TimePeriodClosingInfo> result, SortedBindingList <C> sortedList) where C : BusinessBase, ITimePeriodeCloser { bool first = true; C lastItem = null; foreach (C listItem in sortedList) { if (first) { first = false; lastItem = listItem; if (lastItem.EftvTo.HasValue) { setEftvTo <C>(result, listItem, null); } } else { DateTime?newEftvTo = lastItem.EftvFrom.Value.AddDays(-1); if (isDifferent(listItem.EftvTo, newEftvTo)) { setEftvTo <C>(result, listItem, newEftvTo); } lastItem = listItem; } } return(result); }
public void RemoveAt() { var cut = new SortedBindingList <Data>(); var raisedEvents = new List <ListChangedEventArgs>(); cut.ListChanged += (s, e) => raisedEvents.Add(e); var datas = AddData(cut, 3); const int at = 1; cut.RemoveAt(at); var last = raisedEvents.Last(); Assert.AreEqual(datas.Length - 1, cut.Count); for (int i = 0, j = 0; i < datas.Length; i++) { if (i == at) { continue; } Assert.AreEqual(datas[i], cut[j]); j++; } Assert.AreEqual(ListChangedType.ItemDeleted, last.ListChangedType); Assert.AreEqual(at, last.NewIndex); }
public void AddThenSort() { var cut = new SortedBindingList <Data>(); var raisedEvents = new List <ListChangedEventArgs>(); cut.ListChanged += (s, e) => raisedEvents.Add(e); var datas = AddData(cut, 5); const string propertyName = nameof(Data.Name); const ListSortDirection direction = ListSortDirection.Ascending; cut.ApplySort(propertyName, direction); var sorted = datas.OrderBy(d => d.Name).ToArray(); var last = raisedEvents.Last(); Assert.AreEqual(datas.Length, cut.Count); for (var i = 0; i < datas.Length; i++) { Assert.AreEqual(sorted[i], cut[i]); } Assert.IsTrue(cut.IsSorted); Assert.AreEqual(propertyName, cut.SortProperty.Name); Assert.AreEqual(direction, cut.SortDirection); Assert.AreEqual(ListChangedType.Reset, last.ListChangedType); }
protected void UpdateImporte() { decimal _asignado = 0; SortedBindingList <OutputInvoiceInfo> facturas = Datos_Facturas.DataSource as SortedBindingList <OutputInvoiceInfo>; if (facturas != null) { foreach (OutputInvoiceInfo item in facturas) { _asignado += item.Asignado; } if (_entity.Importe >= 0) { _entity.Importe = (_entity.Importe) > _asignado ? _entity.Importe : _asignado; } else { _entity.Importe = (_entity.Importe) < _asignado ? _entity.Importe : _asignado; } UpdateAsignado(); } }
protected override void GetFormSourceData(object[] parameters) { if (parameters[0] != null) { List = (SortedBindingList <FestivoInfo>)parameters[0]; } }
private void PriceSetForm_Load(object sender, EventArgs e) { WorkPriceConfig priceConfig = PriceConfigWorker.LoadData(); SortedBindingList < WorkPriceItem > bindList = new SortedBindingList<WorkPriceItem>(priceConfig.PriceList); workPriceItemBindingSource.DataSource = bindList; textBox1.Text = priceConfig.WorkPriceName; }
protected override void UpdateAllocated() { decimal _asignado = 0; SortedBindingList <NominaInfo> gastos = Datos_Lineas.DataSource as SortedBindingList <NominaInfo>; foreach (NominaInfo item in gastos) { _asignado += item.Asignado; } if (_entity.EMedioPago != EMedioPago.CompensacionFactura) { _deallocated = _entity.Importe - _asignado; if (_entity.Importe >= 0) { _deallocated = (_deallocated < 0) ? 0 : _deallocated; } else { _deallocated = (_deallocated > 0) ? 0 : _deallocated; } } else { _deallocated = -_asignado; _entity.Importe = _asignado; } NoAsignado_TB.Text = _deallocated.ToString("N2"); MarkControl(NoAsignado_TB); }
public static SortedBindingList <TicketInfo> GetSortedList(string sortProperty, ListSortDirection sortDirection, bool childs) { SortedBindingList <TicketInfo> sortedList = new SortedBindingList <TicketInfo>(GetList(childs)); sortedList.ApplySort(sortProperty, sortDirection); return(sortedList); }
/// <summary> /// Devuelve una lista ordenada de todos los elementos y sus hijos /// </summary> /// <param name="sortProperty">Campo de ordenación</param> /// <param name="sortDirection">Sentido de ordenación</param> /// <param name="childs">Traer hijos</param> /// <returns>Lista ordenada de elementos</returns> public static SortedBindingList <RegistroDisponibilidadInfo> GetSortedList(DateTime fecha_inicio, string sortProperty, ListSortDirection sortDirection, bool childs) { SortedBindingList <RegistroDisponibilidadInfo> sortedList = new SortedBindingList <RegistroDisponibilidadInfo>(GetList(fecha_inicio, childs)); sortedList.ApplySort(sortProperty, sortDirection); return(sortedList); }
/// <summary> /// Devuelve el siguiente Serial de Alumno. /// </summary> /// <returns>Código de 9 cifras</returns> public static Int64 GetNewSerial(Respuestas lista) { // Obtenemos la lista de clientes ordenados por serial SortedBindingList <RespuestaInfo> respuestas = RespuestaList.GetSortedList("Serial", ListSortDirection.Ascending); // Obtenemos el último serial de servicio Int64 lastcode; if (respuestas.Count > 0) { lastcode = respuestas[respuestas.Count - 1].Serial; } else { lastcode = Convert.ToInt64(Resources.Defaults.RESPUESTA_CODE_FORMAT); } if (lista != null) { foreach (Respuesta item in lista) { if (item.Serial > lastcode) { lastcode = item.Serial; } } } lastcode++; return(lastcode); }
public static SortedBindingList <OutputDeliveryInfo> GetSortedList(string sortProperty, ListSortDirection sortDirection, bool childs) { SortedBindingList <OutputDeliveryInfo> sortedList = new SortedBindingList <OutputDeliveryInfo>(GetList(childs, ETipoEntidad.Cliente)); sortedList.ApplySort(sortProperty, sortDirection); return(sortedList); }
protected override void UpdateAllocated() { SortedBindingList <NominaInfo> lines = Datos_Lineas.DataSource as SortedBindingList <NominaInfo>; decimal asignado = lines.Sum(item => item.Asignado); if (_entity.EMedioPago != EMedioPago.CompensacionFactura) { _deallocated = _entity.Importe - asignado; if (_entity.Importe >= 0) { _deallocated = (_deallocated < 0) ? 0 : _deallocated; } else { _deallocated = (_deallocated > 0) ? 0 : _deallocated; } } else { _deallocated = -asignado; _entity.Importe = asignado; } NoAsignado_TB.Text = _deallocated.ToString("N2"); MarkControl(NoAsignado_TB); }
public SortedBindingList <C> GetSortedSubList(FCriteria criteria, string sortProperty, ListSortDirection sortDirection) { SortedBindingList <C> sortedList = GetSortedSubList(criteria); sortedList.ApplySort(sortProperty, sortDirection); return(sortedList); }
/// <summary> /// Asigna el objeto principal al origen de datos /// <returns>void</returns> /// </summary> protected override void RefreshMainData() { if (_pregunta != null) { Datos.DataSource = _pregunta; } PgMng.Grow(); Images.Show(_pregunta.ImagenWithPath, Imagen_PictureBox); PgMng.Grow(); if (_lista_preguntas != null && _lista_preguntas.Count > 0) { PreguntaInfo item = _lista_preguntas.GetItem(_pregunta.OidPregunta); Numero_TB.Text = item.Codigo; } SortedBindingList <RespuestaExamen> ordenadas = RespuestaExamens.SortList(_pregunta.RespuestaExamens, "Opcion", ListSortDirection.Ascending); List <RespuestaExamen> lista = new List <RespuestaExamen>(); foreach (RespuestaExamen item in ordenadas) { if ((_pregunta.Tipo == "Test") || (item.Texto != string.Empty && item.Texto != ".")) { lista.Add(item); } } Datos_Respuestas.DataSource = lista; }
/// <summary> /// Devuelve una lista ordenada y filtrada a partir de los datos de la lista /// actual /// </summary> /// <param name="criteria">Filtro</param> /// <param name="sortProperty">Campo de ordenación</param> /// <param name="sortDirection">Sentido de ordenación</param> /// <returns>Lista ordenada</returns> public SortedBindingList <C> GetSortedSubList(FCriteria criteria, string sortProperty, ListSortDirection sortDirection) { List <C> list = new List <C>(); SortedBindingList <C> sortedList = new SortedBindingList <C>(list); if (Items.Count == 0) { return(sortedList); } PropertyDescriptor property = TypeDescriptor.GetProperties(Items[0]).Find(criteria.GetProperty(), false); foreach (C item in Items) { foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(item)) { if (prop.Name == property.Name) { object value = prop.GetValue(item); if (value.ToString().ToLower().Contains(criteria.GetValue().ToString().ToLower())) { sortedList.Add(item); } break; } } } sortedList.ApplySort(sortProperty, sortDirection); return(sortedList); }
public ClasesPracticasDisponiblesRpt GetDetailReport(CompanyInfo empresa, PromocionInfo promocion, SortedBindingList <ClasePracticaInfo> registros) { if (registros == null) { return(null); } ClasesPracticasDisponiblesRpt doc = new ClasesPracticasDisponiblesRpt(); List <PromocionInfo> pList = new List <PromocionInfo>(); List <ClasePracticaInfo> clases = new List <ClasePracticaInfo>(); foreach (ClasePracticaInfo info in registros) { clases.Add(info); } //Si no existen conceptos, no tiene sentido un informe detallado. Además, falla en Crystal Reports if (clases.Count <= 0) { return(null); } pList.Add(promocion); doc.SetDataSource(pList); ((TextObject)doc.Section5.ReportObjects["Empresa"]).Text = empresa.Name; doc.Subreports["PracticasNoImpartidasListSubRpt"].SetDataSource(registros); //FormatReport(doc); return(doc); }
public void AscendingSort() { int[] intArr = { 45, 23, 57, 56, 11, 87, 94, 44 }; SortedBindingList <int> sortedList = new SortedBindingList <int>(intArr); sortedList.ListChanged += new ListChangedEventHandler(sortedList_ListChanged); Assert.AreEqual(false, sortedList.IsSorted); Assert.AreEqual(56, intArr[3]); sortedList.ApplySort("", ListSortDirection.Ascending); Assert.AreEqual(44, sortedList[2]); Assert.AreEqual(8, sortedList.Count); Assert.AreEqual(true, sortedList.Contains(56)); Assert.AreEqual(4, sortedList.IndexOf(56)); Assert.AreEqual(true, sortedList.IsReadOnly); Assert.AreEqual(true, sortedList.IsSorted); foreach (int item in sortedList) { Console.WriteLine(item.ToString()); } sortedList.RemoveSort(); Assert.AreEqual(false, sortedList.IsSorted); Assert.AreEqual(56, sortedList[3]); // This list dowes not support searching Assert.IsFalse(sortedList.SupportsSearching); // and Find should return -1 because underlying list dows not implement IBindingList Assert.AreEqual(-1, sortedList.Find("", 56)); }
/// <summary> /// Devuelve el siguiente Serial de PlanAnual /// </summary> /// <returns></returns> private static Int64 GetNewSerial(InformeDiscrepancia parent) { // Obtenemos la lista de clientes ordenados por serial SortedBindingList <DiscrepanciaInfo> Discrepancias = DiscrepanciaList.GetSortedList("Serial", ListSortDirection.Ascending); // Obtenemos el último serial de servicio Int64 lastcode; if (Discrepancias.Count > 0) { lastcode = Discrepancias[Discrepancias.Count - 1].Serial; } else { lastcode = Convert.ToInt64(Resources.Defaults.DISCREPANCIA_CODE_FORMAT); } foreach (Discrepancia item in parent.Discrepancias) { if (item.Serial > lastcode) { lastcode = item.Serial; } } lastcode++; return(lastcode); }
/// <summary> /// Devuelve el siguiente Serial de Empresa. /// </summary> /// <returns>Código de 9 cifras</returns> protected static Int64 GetNewSerial() { // Obtenemos la lista de empresas ordenadas por serial SortedBindingList <SchemaInfo> emps = SchemaList.GetSortedList("Serial", ListSortDirection.Ascending); // Obtenemos el último código de empresa Int64 lastcode = 0; if (emps.Count > 0) { for (int i = 1; i < 11; i++) { if (emps.Find("Serial", i) == -1) { lastcode = i; return(i); } } } else { lastcode = 1; } return(lastcode); }
public static SortedBindingList <C> AscendingSortedList(FilteredBindingList <C> list, string sortPropertyName) { var _sortedList = new SortedBindingList <C>(list); _sortedList.ApplySort(sortPropertyName, ListSortDirection.Ascending); return(_sortedList); }
protected new SortedBindingList <ClaseAuditoriaInfo> Localize(object value, string column_name) { SortedBindingList <ClaseAuditoriaInfo> list = null; ClaseAuditoriaList sourceList = null; switch (FilterType) { case IFilterType.None: if (List == null) { MessageBox.Show(moleQule.Face.Resources.Messages.NO_RESULTS); return(null); } sourceList = List; break; case IFilterType.Filter: if (FilteredList == null) { MessageBox.Show(moleQule.Face.Resources.Messages.NO_RESULTS); return(null); } sourceList = FilteredList; break; } FCriteria criteria = null; string related = "none"; switch (column_name) { default: { criteria = GetCriteria(column_name, value, _operation); } break; } switch (related) { case "none": { list = sourceList.GetSortedSubList(criteria); } break; } if (list.Count == 0) { MessageBox.Show(moleQule.Face.Resources.Messages.NO_RESULTS); return(sourceList.GetSortedList()); } DatosSearch.DataSource = list; DatosSearch.MoveFirst(); AddFilterLabel(column_name, value); Tabla.Focus(); return(list); }
public void Find_ThrowException_WhenPropertyNameNotFound() { int[] intArray = { 5, 7, 1, 3, 5, 44, 32 }; SortedBindingList <int> sortedList = new SortedBindingList <int>(intArray); sortedList.Find("NotAProperty", 7); }
public CuentasContablesListRpt GetListReport(ResumenCuentasContablesList list) { if (list.Count == 0) { return(null); } CuentasContablesListRpt doc = new CuentasContablesListRpt(); List <ResumenCuentasContablesInfo> pList = new List <ResumenCuentasContablesInfo>(); //Los ordena por número de cuenta contable antes de mostrarlo SortedBindingList <ResumenCuentasContablesInfo> sorted = list.ToSortedList("CuentaContable", ListSortDirection.Ascending); foreach (ResumenCuentasContablesInfo item in sorted) { pList.Add(item); } doc.SetDataSource(pList); FormatHeader(doc); return(doc); }
/// <summary> /// Devuelve el siguiente Serial de ActaComite /// </summary> /// <returns></returns> private static Int64 GetNewSerial(ActaComite parent) { // Obtenemos la lista de clientes ordenados por serial SortedBindingList <PuntoActaInfo> Puntos = PuntoActaList.GetSortedList("Serial", ListSortDirection.Ascending); // Obtenemos el último serial de servicio Int64 lastcode; if (Puntos.Count > 0) { lastcode = Puntos[Puntos.Count - 1].Serial; } else { lastcode = Convert.ToInt64(Resources.Defaults.PUNTO_ACTA_CODE_FORMAT); } foreach (PuntoActa item in parent.PuntosActas) { if (lastcode < item.Serial) { lastcode = item.Serial; } } lastcode++; return(lastcode); }
protected override void UpdateAllocated() { decimal _allocated = 0; SortedBindingList <ExpenseInfo> expenses = Expenses_BS.DataSource as SortedBindingList <ExpenseInfo>; foreach (ExpenseInfo item in expenses) { _allocated += item.Asignado; } if (_entity.EMedioPago != EMedioPago.CompensacionFactura) { _no_asignado = _entity.Importe - _allocated; if (_entity.Importe >= 0) { _no_asignado = (_no_asignado < 0) ? 0 : _no_asignado; } else { _no_asignado = (_no_asignado > 0) ? 0 : _no_asignado; } } else { _no_asignado = -_allocated; _entity.Importe = _allocated; } NoAsignado_TB.Text = _no_asignado.ToString("N2"); MarkControl(NoAsignado_TB); }
public static SortedBindingList <ExpedientInfo> GetSortedList(string sortProperty, ListSortDirection sortDirection, bool childs, ETipoExpediente t) { SortedBindingList <ExpedientInfo> sortedList = new SortedBindingList <ExpedientInfo>(GetList(t, childs)); sortedList.ApplySort(sortProperty, sortDirection); return(sortedList); }
public SortedBindingList <C> GetSortedList(string sortProperty, ListSortDirection sortDirection) { SortedBindingList <C> sorted_list = new SortedBindingList <C>(this); sorted_list.ApplySort(sortProperty, sortDirection); return(sorted_list); }
public void ApplySort_ThrowException_WhenPropertyNameNotFound() { int[] intArray = { 5, 7, 1, 3, 5, 44, 32 }; SortedBindingList <int> sortedList = new SortedBindingList <int>(intArray); sortedList.ApplySort("NotAProperty", ListSortDirection.Ascending); }
/// <summary> /// Devuelve una lista ordenada de todos los elementos /// </summary> /// <param name="sortProperty">Campo de ordenación</param> /// <param name="sortDirection">Sentido de ordenación</param> /// <returns>Lista ordenada de elementos</returns> public static SortedBindingList <AgenteInfo> GetSortedList(string sortProperty, ListSortDirection sortDirection) { SortedBindingList <AgenteInfo> sortedList = new SortedBindingList <AgenteInfo>(GetList()); sortedList.ApplySort(sortProperty, sortDirection); return(sortedList); }
public static DateTime[] GetBoldedList(SortedBindingList <FestivoInfo> list) { Dictionary <DateTime, DateTime> fechas = new Dictionary <DateTime, DateTime>(); for (int i = 0; i < list.Count; i++) { for (int j = 0; list[i].FechaInicio.Date.AddDays(j) <= list[i].FechaFin.Date; j++) { if (!fechas.ContainsKey(list[i].FechaInicio.Date.AddDays(j))) { fechas.Add(list[i].FechaInicio.Date.AddDays(j), list[i].FechaInicio.Date.AddDays(j)); } } } DateTime[] bolded = new DateTime[fechas.Count]; int index = 0; foreach (DateTime date in fechas.Values) { bolded[index++] = date; } return(bolded); }
public void AscendingSort() { int[] intArr = { 45, 23, 57, 56, 11, 87, 94, 44 }; SortedBindingList<int> sortedList = new SortedBindingList<int>(intArr); sortedList.ListChanged += new ListChangedEventHandler(sortedList_ListChanged); Assert.AreEqual(false, sortedList.IsSorted); Assert.AreEqual(56, intArr[3]); sortedList.ApplySort("", ListSortDirection.Ascending); Assert.AreEqual(44, sortedList[2]); Assert.AreEqual(8, sortedList.Count); Assert.AreEqual(true, sortedList.Contains(56)); Assert.AreEqual(4, sortedList.IndexOf(56)); Assert.AreEqual(true, sortedList.IsReadOnly); Assert.AreEqual(true, sortedList.IsSorted); foreach (int item in sortedList) { Console.WriteLine(item.ToString()); } sortedList.RemoveSort(); Assert.AreEqual(false, sortedList.IsSorted); Assert.AreEqual(56, sortedList[3]); // This list dowes not support searching Assert.IsFalse(sortedList.SupportsSearching); // and Find should return -1 because underlying list dows not implement IBindingList Assert.AreEqual(-1, sortedList.Find("", 56)); }
/// <summary> /// Devuelve el siguiente Serial de PlanAnual /// </summary> /// <returns></returns> private static Int64 GetNewSerial(InformeAmpliacion parent) { // Obtenemos la lista de clientes ordenados por serial SortedBindingList <AmpliacionInfo> Ampliaciones = AmpliacionList.GetSortedList("Serial", ListSortDirection.Ascending); // Obtenemos el último serial de servicio Int64 lastcode; if (Ampliaciones.Count > 0) { lastcode = Ampliaciones[Ampliaciones.Count - 1].Serial; } else { lastcode = Convert.ToInt64(Resources.Defaults.AMPLIACION_CODE_FORMAT); } foreach (Ampliacion item in parent.Ampliaciones) { if (item.Serial > lastcode) { lastcode = item.Serial; } } lastcode++; return(lastcode); }
private void button1_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "Выберите файл"; dlg.Filter = "Текстовые файлы|*.txt"; if (dlg.ShowDialog() != DialogResult.OK) return; IEnumerable<WorkPriceItem> list = PriceConfigWorker.ImportData(dlg.FileName); SortedBindingList<WorkPriceItem> bindList = new SortedBindingList<WorkPriceItem>(list); workPriceItemBindingSource.DataSource = bindList; }
private void SaveAttack() { using (SqlConnection cn = new SqlConnection( Database.AphelionTriggerConnection )) { cn.Open(); ATConfiguration config = ATConfiguration.Instance; #region 4. Save Casualties foreach (Unit unit in _defenderForces) { if (unit.Casualties > 0) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "AddCasualties"; cm.Parameters.AddWithValue( "@HouseID", _defenderHouse.ID ); cm.Parameters.AddWithValue( "@UnitID", unit.ID ); cm.Parameters.AddWithValue( "@Casualties", unit.Casualties ); cm.ExecuteNonQuery(); _description.Add( "You killed " + unit.Casualties.ToString() + " " + (unit.Casualties > 1 ? Pluralize( unit.Name ) : unit.Name) + "." ); } } } foreach (Unit unit in _attackerForces) { if (unit.Casualties > 0) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "AddCasualties"; cm.Parameters.AddWithValue( "@HouseID", _attackerHouse.ID ); cm.Parameters.AddWithValue( "@UnitID", unit.ID ); cm.Parameters.AddWithValue( "@Casualties", unit.Casualties ); cm.ExecuteNonQuery(); _description.Add( "You lost " + unit.Casualties.ToString() + " " + (unit.Casualties > 1 ? Pluralize( unit.Name ) : unit.Name) + "." ); } } } #endregion #region 5. Calculate plundered credits int totalPlunder = 0; int plunder = 0; foreach (Unit unit in _attackerForces) { // subtract casualties to make sure only surviving units plunder totalPlunder += ((unit.Plunder + unit.PlunderTech) * (unit.Count - unit.Casualties)); } // only calculate plunder if necessary if ( totalPlunder > 0 ) { // if attacker is a faction leader, add appropirate bonus if ( _attackerHouse.FactionLeaderHouseID == _attackerHouse.ID ) { totalPlunder += Convert.ToInt32( totalPlunder * config.FactionLeaderBonus ); } // modify stat totals on the basis of house contingency characteristics Random plunderRandom = new Random(); int attackerContingencyRange = (int)( config.ContingencyFactor * ( _attackerHouse.Contingency / 100 ) ); int attackerContingency = plunderRandom.Next( -attackerContingencyRange, attackerContingencyRange ); totalPlunder += ( totalPlunder * ( attackerContingency / 100 ) ); double percentPlundered = ( (double)totalPlunder / 40 ) * 0.01; // modify total plunder total by the attacker house's ambition percentPlundered = ( percentPlundered * ( ( _attackerHouse.Ambition * 0.0025 ) + 0.75 ) ); // cap the ammount of credits that can be plundered at 10% if ( percentPlundered > 0.1 ) percentPlundered = 0.1; using ( SqlCommand cm = cn.CreateCommand() ) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "Plunder"; cm.Parameters.AddWithValue( "@PlundererHouseID", _attackerHouse.ID ); cm.Parameters.AddWithValue( "@PlunderedHouseID", _defenderHouse.ID ); cm.Parameters.AddWithValue( "@PlunderPercent", percentPlundered ); SqlParameter param = new SqlParameter( "@Plunder", SqlDbType.Int ); param.Direction = ParameterDirection.Output; cm.Parameters.Add( param ); cm.ExecuteNonQuery(); plunder = (int)cm.Parameters["@Plunder"].Value; } _description.Add( "You seized " + plunder.ToString() + " credits." ); } #endregion #region 6. Calculate captured militia int totalCapture = 0; int totalCaptured = 0; foreach (Unit unit in _attackerForces) { // subtract casualties to make sure only surviving units capture totalCapture += ((unit.Capture + unit.CaptureTech) * (unit.Count - unit.Casualties)); } // only calculate capture if necessary if ( totalCapture > 0 ) { // if attacker is a faction leader, add appropirate bonus totalCapture = (int)_attackerHouse.ApplyFactionLeaderBonus( totalCapture ); // modify stat totals on the basis of house contingency characteristics Random captureRandom = new Random(); int attackerContingencyRange = (int)( config.ContingencyFactor * ( _attackerHouse.Contingency / 100 ) ); int attackerContingency = captureRandom.Next( -attackerContingencyRange, attackerContingencyRange ); totalCapture += ( totalCapture * ( attackerContingency / 100 ) ); double percentCaptured = ( (double)totalCapture / config.CaptureDivisor ) * config.CaptureFactor; // finally, modify total capture total by the attacker house's ambition percentCaptured = (int)( percentCaptured * ( ( _attackerHouse.Ambition * 0.0025 ) + 0.75 ) ); // cap the ammount of militia that can be captured at CaptureCap if ( percentCaptured > config.CaptureCap ) percentCaptured = config.CaptureCap; int totalCaptureableUnits = 0; foreach ( Unit unit in _defenderForces ) { // substract casualties to make sure only surviving units are capture if ( unit.UnitClassID == 1 ) totalCaptureableUnits += ( unit.Count - unit.Casualties ); } int captureCount = (int)( percentCaptured * totalCaptureableUnits ); // ensure that if any percentage of units is to be captured, at least one will always be captured if ( percentCaptured > 0 && captureCount == 0 ) captureCount = 1; SortedBindingList<Unit> sortedList = new SortedBindingList<Unit>( _defenderForces ); sortedList.ApplySort( "Cost", ListSortDirection.Ascending ); int cheapestMilitiaId = GetCheapestMilitiaID( _attackerForces ); // go through defender forces until all captures are made foreach ( Unit unit in sortedList ) { // skip non-militia if ( unit.UnitClassID != 1 ) continue; // capture as many units as possible each iteration of the loop int captured = captureCount; if ( captured > unit.Count - unit.Casualties ) captured = ( unit.Count - unit.Casualties ); using ( SqlCommand cm = cn.CreateCommand() ) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "Capture"; cm.Parameters.AddWithValue( "@CapturerHouseID", _attackerHouse.ID ); cm.Parameters.AddWithValue( "@CapturedHouseID", _defenderHouse.ID ); cm.Parameters.AddWithValue( "@CapturedUnitID", unit.ID ); cm.Parameters.AddWithValue( "@Captured", captured ); cm.ExecuteNonQuery(); if ( captured > 0 ) _description.Add( "You captured " + captured.ToString() + " " + unit.Name + "." ); captureCount -= captured; totalCaptured += captured; } if ( captureCount <= 0 ) break; } } #endregion #region 7. Calculate Stun int totalStun = 0; int stun = 0; foreach ( Unit unit in _attackerForces ) { // subtract casualties to make sure only surviving units stun totalStun += ( ( unit.Stun + unit.StunTech ) * ( unit.Count - unit.Casualties ) ); } // only calculate stun if necessary if ( totalStun > 0 ) { // if attacker is a faction leader, add appropirate bonus if ( _attackerHouse.FactionLeaderHouseID == _attackerHouse.ID ) { totalStun += Convert.ToInt32( totalStun * config.FactionLeaderBonus ); } // modify stat totals on the basis of house contingency characteristics Random stunRandom = new Random(); int attackerContingencyRange = (int)( config.ContingencyFactor * ( _attackerHouse.Contingency / 100 ) ); int attackerContingency = stunRandom.Next( -attackerContingencyRange, attackerContingencyRange ); totalStun += ( totalStun * ( attackerContingency / 100 ) ); double percentStunned = ( (double)totalStun / 40 ) * 0.001; // cap the ammount of turns that can be stunned at 8% if ( percentStunned > 0.08 ) percentStunned = 0.08; using ( SqlCommand cm = cn.CreateCommand() ) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "Stun"; cm.Parameters.AddWithValue( "@HouseID", _defenderHouse.ID ); cm.Parameters.AddWithValue( "@StunPercent", percentStunned ); SqlParameter param = new SqlParameter( "@Stun", SqlDbType.Int ); param.Direction = ParameterDirection.Output; cm.Parameters.Add( param ); cm.ExecuteNonQuery(); stun = (int)cm.Parameters["@Stun"].Value; } _description.Add( "You stunned your enemy for " + stun.ToString() + " turns." ); } #endregion #region 8. Update Ambition // the attacker gains or looses ambition based on how much of a percentage lower // or higher the defender is ranked vs. the attacker. int lowestRank = HouseList.GetHouseList().LowestRank; double attackerRankPercent = 100.0 - ( ( _attackerHouse.Rank / (double)lowestRank ) * 100.0 ); double defenderRankPercent = 100.0 - ( ( _defenderHouse.Rank / (double)lowestRank ) * 100.0 ); //// no attacker may gain or loose more than 25% ambition in one attack int ambitionChangeValue = (int)( defenderRankPercent - attackerRankPercent ) / 4; if ( _attackerHouse.Ambition + ambitionChangeValue > 100 ) ambitionChangeValue = 0; if ( _attackerHouse.Ambition + ambitionChangeValue < 1 ) ambitionChangeValue = 0; if (ambitionChangeValue != 0) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.Text; cm.CommandText = "UPDATE bbgHouses SET Ambition = Ambition + " + ambitionChangeValue.ToString() + " WHERE ID = " + _attackerHouse.ID.ToString(); cm.ExecuteNonQuery(); } if (Math.Abs( ambitionChangeValue ) == ambitionChangeValue) { _description.Add( "Your ambition improved by " + ambitionChangeValue.ToString() + "." ); } else { _description.Add( "Your ambition worsened by " + ambitionChangeValue.ToString() + "." ); } } #endregion #region 9. Update Experience int experience = 0; foreach (Unit unit in _defenderForces) { if ( unit.Casualties > 0 ) experience += ( ( unit.Experience + unit.ExperienceTech ) * unit.Casualties ); } // only advance if experience was gained AND user isn't already at level the level cap if (experience > 0 && _attackerHouse.Level.Rank < config.LevelCap) { Level.UpdateExperience( _attackerHouse, experience ); _description.Add( "You gained " + experience + " experience." ); // TODO: right now this will cause weird problems if enough exp to advance more than one level is gained at once if (_attackerHouse.Experience + experience >= _attackerHouse.NextLevel.Experience) { _description.Add( "You advanced to level " + _attackerHouse.NextLevel.Rank.ToString() + "." ); // add level advancement Advancement advancement = Advancement.NewAdvancement(); advancement.HouseID = _attackerHouse.ID; advancement.LevelID = _attackerHouse.NextLevel.ID; advancement.Save(); // add leveling report AphelionTrigger.Library.Report report = Report.NewReport(); report.FactionID = _attackerHouse.FactionID; report.GuildID = _attackerHouse.GuildID; report.HouseID = _attackerHouse.ID; report.Message = "House " + _attackerHouse.Name + " gained a level."; report.ReportLevelID = 1 + House.GetSecrecyBonus( _attackerHouse.Intelligence ); report.Save(); } } #endregion #region 10. Add Attack int totalAttackerCasualties = 0; foreach (Unit unit in _attackerForces) totalAttackerCasualties += unit.Casualties; int totalDefenderCasualties = 0; foreach (Unit unit in _defenderForces) totalDefenderCasualties += unit.Casualties; Attack attack = AphelionTrigger.Library.Attack.NewAttack(); attack.AttackerHouseID = _attackerHouse.ID; attack.DefenderHouseID = _defenderHouse.ID; attack.Captured = totalCaptured; attack.Plundered = plunder; attack.Stunned = stun; attack.AttackerCasualties = totalAttackerCasualties; attack.DefenderCasualties = totalDefenderCasualties; StringBuilder description = new StringBuilder(); foreach (string s in _description) description.AppendFormat( "{0}<br/>", s ); attack.Description = description.ToString(); attack.Save(); AttackID = attack.ID; // decrement the attacker's turns that were expended in the attack House.UpdateTurns( _attackerHouse.ID, -1 ); #endregion } }
private Csla.SortedBindingList<Challenge> GetChallengeList() { object businessObject = Session["CurrentObject"]; if ( businessObject == null || !( businessObject is ChallengeList ) ) { businessObject = ChallengeList.GetChallengeList( ViewingGladiatorId, ChallengeList.ChallengeFilter.All ); Session["CurrentObject"] = businessObject; } Master.SortExpression = "ChallengeDate"; Master.SortDirection = System.ComponentModel.ListSortDirection.Descending; SortedBindingList<Challenge> list = new SortedBindingList<Challenge>( (ChallengeList)businessObject ); list.ApplySort( Master.SortExpression, Master.SortDirection ); return list; }
public void IndexOf() { List<string> list = new List<string>(); string barney = "Barney"; string charlie = "Charlie"; string zeke = "Zeke"; list.AddRange(new string[] { charlie, barney, zeke }); SortedBindingList<string> sortedList = new SortedBindingList<string>(list); Assert.AreEqual(1, sortedList.IndexOf(barney), "Unsorted index should be 1"); sortedList.ApplySort(string.Empty, System.ComponentModel.ListSortDirection.Ascending); Assert.AreEqual(1, sortedList.IndexOf(charlie), "Sorted index should be 1"); }
public void DescendingSort() { string[] strArr = { "zandy", "alex", "Chris", "bert", "alfred", "Bert", "Jimmy", "chris", "chris", "mobbit", "myper", "Corey", "Monkey" }; SortedBindingList<string> sortedList = new SortedBindingList<string>(strArr); Assert.AreEqual("Bert", sortedList[5]); sortedList.ApplySort("", ListSortDirection.Descending); foreach (string item in sortedList) { Console.WriteLine(item); } for (int i = 0; i < sortedList.Count; i++) { Console.WriteLine("regular loop: " + sortedList[i]); } Assert.AreEqual("Corey", sortedList[5]); Console.WriteLine(); Console.WriteLine(sortedList.Count); }
public void SourceList() { List<string> list = new List<string>(); string barney = "Barney"; string charlie = "Charlie"; string zeke = "Zeke"; list.AddRange(new string[] { charlie, barney, zeke }); SortedBindingList<string> sortedList = new SortedBindingList<string>(list); Assert.IsTrue(ReferenceEquals(list, sortedList.SourceList), "List references should match"); }
public void CopyTo() { int[] intArray = { 5, 7, 1, 3, 5, 44, 32 }; SortedBindingList<int> sortedList = new SortedBindingList<int>(intArray); int[] intArray2 = { 3, 75, 1222, 3333, 511, 443, 332 }; Assert.AreEqual(1222, intArray2[2]); sortedList.ApplySort("", ListSortDirection.Descending); Assert.AreEqual(44, sortedList[0], "Sorted values incorrect"); sortedList.CopyTo(intArray2, 0); Assert.AreEqual(44, intArray2[0], "Copied values incorrect"); Assert.AreEqual(7, intArray2[2], "Copied values incorrect"); foreach (int item in intArray2) { Console.WriteLine(item.ToString()); } }
public void Find_ThrowException_WhenPropertyNameNotFound() { int[] intArray = { 5, 7, 1, 3, 5, 44, 32 }; SortedBindingList<int> sortedList = new SortedBindingList<int>(intArray); sortedList.Find("NotAProperty", 7); }
public void ApplySort_ThrowException_WhenPropertyNameNotFound() { int[] intArray = { 5, 7, 1, 3, 5, 44, 32 }; SortedBindingList<int> sortedList = new SortedBindingList<int>(intArray); sortedList.ApplySort("NotAProperty", ListSortDirection.Ascending); }
private void InitializeAppList() { AsyncManager.StartTask(() => { appLookup.Clear(); var list = new List<AppWrapper>(); var cnt = 0; foreach (var app in core.Config.Apps) { cnt++; app.LoadCachedValues(); var wrapper = new AppWrapper(app, cnt); list.Add(wrapper); appLookup[app.ID] = wrapper; } var bindingList = new SortedBindingList<AppWrapper>(list); BeginInvoke((ThreadStart)(() => { var selectedRow = gridApps.SelectedRows.Count > 0 ? gridApps.SelectedRows[0].Index : -10; var firstVisibleRow = gridApps.FirstDisplayedScrollingRowIndex; gridApps.SuspendLayout(); gridApps.DataSource = bindingList; if (sortedColumn != null) { gridApps.Sort(sortedColumn, sortDirection); } if (selectedRow >= 0 && gridApps.Rows.Count >= selectedRow + 1) { gridApps.Rows[selectedRow].Selected = true; } if (firstVisibleRow >= 0) { gridApps.FirstDisplayedScrollingRowIndex = firstVisibleRow; } gridApps.ResumeLayout(); })); }); }