public AnteprimaReportRiparto(IList<ReportRipartizioneBilancioDTO> dataSource, CondominioDTO condominio, EsercizioDTO esercizio, BilancioConsuntivoReportParameters parameters, ImpostazioneReportDTO impostazioneReportDTO) { InitializeComponent(); _dataSource = dataSource; _condominio = condominio; _esercizio = esercizio; _parameters = parameters; _impostazioneReportDTO = impostazioneReportDTO; Text = $"Riparto {_impostazioneReportDTO.Descrizione}"; try { _importoTotale = getBilancioService().GetTotale(dataSource.ToList()); _importoPreventivo = getBilancioService().GetTotalePreventivo(dataSource.ToList()); IReportProvider document; if(_impostazioneReportDTO.MultiPageOrdered) document = new RipartoMerge(dataSource, _condominio, _esercizio, _parameters, _impostazioneReportDTO, _importoTotale, _importoPreventivo); else document = new RipartoSubreport(dataSource, _condominio, _esercizio, _parameters, _impostazioneReportDTO, _importoTotale, _importoPreventivo); SetDataSource(document.GetReport(), _impostazioneReportDTO); } catch (Exception ex) { _log.ErrorFormat("Errore nell'apertura della maschera di anteprima per riparto - {0} - condominio:{1} - azienda:{2}", ex, Utility.GetMethodDescription(), _condominio?.ID.ToString(CultureInfo.InvariantCulture) ?? "<NULL>", Login.Instance.CurrentLogin().Azienda); Close(); } }
public AnteprimaReportRipartoPersona(IList<ReportRipartizioneBilancioDTO> dataSource, CondominioDTO condominio, EsercizioDTO esercizio, IList<PersonaContattoDTO> personeRiparto, Dictionary<int, IList<IList<UnitaImmobiliareListaDTO>>> listaUnitaImmobiliare, BilancioConsuntivoReportParameters parameters, ImpostazioneReportDTO impostazioneReportDTO, string reportKey, string note) { InitializeComponent(); _dataSource = dataSource; _condominio = condominio; _esercizio = esercizio; _parameters = parameters; _personeRiparto = personeRiparto; _impostazioneReportDTO = impostazioneReportDTO; _note = note; Text = $"Riparto {_impostazioneReportDTO.Descrizione}"; try { _importoTotale = getBilancioService().GetTotale(dataSource.ToList()); _importoPreventivo = getBilancioService().GetTotalePreventivo(dataSource.ToList()); IReportProvider document = new RipartoAnnualePersona(dataSource, _condominio, _esercizio, personeRiparto, listaUnitaImmobiliare, _parameters, _impostazioneReportDTO, reportKey, _note); SetDataSource(document.GetReport(), _impostazioneReportDTO); } catch (Exception ex) { _log.ErrorFormat("Errore nell'apertura della maschera di anteprima per riparto - {0} - condominio:{1} - azienda:{2}", ex, Utility.GetMethodDescription(), _condominio?.ID.ToString(CultureInfo.InvariantCulture) ?? "<NULL>", Login.Instance.CurrentLogin().Azienda); throw; } }
private static IList<SignatureHelpItem> Filter(IList<SignatureHelpItem> items, IEnumerable<string> parameterNames) { if (parameterNames == null) { return items.ToList(); } var filteredList = items.Where(i => Include(i, parameterNames)).ToList(); return filteredList.Count == 0 ? items.ToList() : filteredList; }
/// <summary> /// Accepts a collection of frames and returns the total score /// </summary> /// <param name="scores"></param> /// <returns></returns> public int CalculateTotalScore(IList<IFrame> scores) { ValidateFrames(scores.ToList()); var totalScore = 0; scores.ToList().ForEach(sc => totalScore += sc.Score); return totalScore; }
public long Run(IList<int> numbers) { long total = 0; int amount = this.maximum; int k; var rest = numbers.ToList(); for (k = 0; k < numbers.Count - 1; k++) { int move = this.Decide(amount, rest); total += (long)move * numbers[k]; amount -= move; amount += this.reload; if (amount > this.maximum) amount = this.maximum; rest = rest.Skip(1).ToList(); } total += (long)amount * numbers[k]; return total; }
public Validation CreatePackage(ref Package package, IList<long> items) { var val = _validator.ValidateNewPackage(package, null); var trans = _factory.BuildTransaction("InsertPackage"); try { //validate if (val.IsValid) { _repo.Insert(ref package, ref trans); long packageId = package.Id; items.ToList().ForEach(i => _itemRepo.SetItemPackage(i, packageId, ref trans)); } trans.Commit(); } catch (Exception e) { trans.Rollback(); val.AddError(string.Format("Unable to create package: {0}", e.Message)); } finally { trans.Dispose(); } return val; }
/// <summary> /// Initializes a new instance of the <see cref="ListController"/> class. /// </summary> /// <param name="list"> /// The list. /// </param> /// <param name="dialogTitle"> /// The dialog title. /// </param> public ListController(IList<string> list, string dialogTitle) { // Clone the list. That way, if the close button is used // the original list won't be affected. this.List = new BindingList<string>(list.ToList()); this.Title = dialogTitle; }
/// <summary> /// When the activity is created /// </summary> /// <param name="bundle">Any data passed to the activity</param> protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); //Allow this inbox to be retrieved by other classes //This allows the inbox to be updated when a new message arrives MainActivity.references.Put ("Inbox", this); SetContentView(Resource.Layout.messaging_inbox); taskListView = (ListView)FindViewById (Resource.Id.listView); //Get all the users that this user has had a conversation with users = MessageRepository.GetMessagedUsers().ToArray<string>(); tasks = new List<Message>(); //Get the most recent message from each user to display in the "main" messaging list foreach (string s in users) { tasks.Add(MessageRepository.GetMostRecentMessageFrom(s)); } // create our adapter taskList = new MsgListAdapterInbox(this, users.ToList()); //Hook up our adapter to our ListView taskListView.Adapter = taskList; }
public void Execute(IList<IAggregateCommand> commands, int expectedVersion) { if (commands.Count == 0) { return; } // readModelBuilderBus will publish events to a bus that will build read models and then pass events off to // the real eventBus var readModelBuilderBus = new ReadModelBuildingEventBus(this.registration.ImmediateReadModels(this.scope), this.eventBus); // holds the events that were raised from the aggregate and will push them to the read model building bus var aggregateEvents = new UnitOfWorkEventBus(readModelBuilderBus); // subscribe to the changes in the aggregate and publish them to aggregateEvents var aggregateRepo = new AggregateRepository(registration.New, this.scope.GetRegisteredObject<IEventStore>(), scope.GetRegisteredObject<ISnapshotRepository>()); var subscription = aggregateRepo.Changes.Subscribe(aggregateEvents.Publish); this.scope.Add(new UnitOfWorkDisposable(subscription)); // add them in this order so that aggregateEvents >> readModelBuilderBus >> read model builder >> eventBus this.scope.Add(aggregateEvents); this.scope.Add(readModelBuilderBus); var cmd = new CommandExecutor(aggregateRepo); cmd.Execute(commands.ToList(), expectedVersion); // enqueue pending commands this.EnqueueCommands(this.scope.GetRegisteredObject<IPendingCommandRepository>(), commands); // enqueue read models to be built - for non-immediate read models var typeName = AggregateRootBase.GetAggregateTypeDescriptor(registration.AggregateType); this.EnqueueReadModels(this.scope.GetRegisteredObject<IReadModelQueueProducer>(), typeName, aggregateEvents.GetEvents().Select(x => x.Event).OfType<IAggregateEvent>().ToList()); }
private void setupElems(IList<Profile.ElementComponent> elements) { if (elements == null) throw Error.ArgumentNull("elements"); _elements = elements.ToList(); // make a *shallow* copy of the list of elements OrdinalPosition = null; }
public static SyncOptions OptionsForSyncUp(IList<string> fieldList, MergeModeOptions mergeMode) { var nativeMergeMode = JsonConvert.SerializeObject(mergeMode); var nativeSyncOptions = SDK.SmartSync.Model.SyncOptions.OptionsForSyncUp(fieldList.ToList(), JsonConvert.DeserializeObject<SDK.SmartSync.Model.SyncState.MergeModeOptions>(nativeMergeMode)); var syncOptions = JsonConvert.SerializeObject(nativeSyncOptions); return JsonConvert.DeserializeObject<SyncOptions>(syncOptions); }
/// <summary> /// Get the ToolbarItem reference by it's name. /// </summary> /// <returns>The ToolbarItem object that references the UIBarButtonInfo.</returns> /// <param name="items">The list of Items.</param> /// <param name="title">The button title.</param> ToolbarItem GetToolbarItem(IList<ToolbarItem> items, string title) { if (string.IsNullOrEmpty(title) || items == null) return null; return items.ToList().FirstOrDefault(itemData => title.Equals(itemData.Text)); }
public void UpdateMarkers(IList<MediaMarker> markers, bool forceRefresh) { var markersHash = markers.ToDictionary(i => i.Id, i => i); List<MediaMarker> newMarkers; List<MediaMarker> removedMarkers; if (forceRefresh) { newMarkers = markers.ToList(); removedMarkers = _previousMarkers.Values.ToList(); } else { newMarkers = markers.Where(i => !_previousMarkers.ContainsKey(i.Id)).ToList(); removedMarkers = _previousMarkers.Values.Where(i => !markersHash.ContainsKey(i.Id)).ToList(); } if (removedMarkers.Any() && MarkersRemoved != null) { MarkersRemoved(removedMarkers); } if (newMarkers.Any() && NewMarkers != null) { NewMarkers(newMarkers); } _previousMarkers = markersHash; }
public SeriesData(int seriesId, SeriesMetadata myMeta, IList<DataValue> dataValues, Variable variable, List<Source> sources, List<Method> methods, List<QualityControlLevel> qualityControlLevels) : this() { myMetadata = myMeta; SeriesID = seriesId; HasConfirmedTimeStamp = true; TimeStampMessage = string.Empty; myVariable = variable; values = dataValues.ToList(); ontology = new List<OntologyItem>(); tags = new List<HydroTag>(); if (null != sources) { mySources = sources; } if (null != methods) { myMethods = methods; } if (null != qualityControlLevels) { myQualityControlLevels = qualityControlLevels; } }
public static Message CreateBindingRequest(IList <MessageAttribute>?attributes, byte[]?customTransactionId) { byte[] transactionId; if (customTransactionId == null) { transactionId = new byte[12]; RNG.GetBytes(transactionId); } else { if (customTransactionId.Length != 12) { throw new ArgumentOutOfRangeException(nameof(customTransactionId), customTransactionId, "TransactionID must be 12 bytes"); } transactionId = customTransactionId; } var attributeList = attributes?.ToList().AsReadOnly(); var messageLength = attributeList?.Sum(a => a.Bytes.Count) ?? 0; return(new Message { Header = new MessageHeader { Type = MessageType.BindingRequest, MessageLength = (ushort)messageLength, MagicCookie = 0x2112A442, TransactionId = transactionId }, Attributes = attributeList }); }
/// <summary> /// Sql parameter constructor /// </summary> /// <param name="conditions"> /// List of conditions, would be applied in order of list item. Could be cases like 'Not In', or join as 'Or Not' e.t.c /// if parameter is first in WHERE statement or in ORDER BY Name ASC, Name2 DESC /// </param> /// <param name="parameterName"> /// Name of column /// </param> /// <param name="comparisonOperator"> /// >, >=, !=, =, IS, In - Name In Value, Value is: (v1, v2, ....v3), Between - Name Between Value, Value is: v1 and v2, Like /// </param> /// <param name="parameterValue"> /// a) for where parameter is actual value but for IN should be string 'v1, v2, v3' for BETWEEN - string 'v1 AND v2' /// b) for order by parameters ASC or DESC /// </param> public DbQueryParameter(IList <JoinCondition> conditions, string parameterName, string comparisonOperator, string parameterValue) { Conditions = conditions?.ToList(); ParameterName = parameterName; ComparisonOperator = comparisonOperator; ParameterValue = parameterValue; }
public void ListarEventos(IList<EventoDTO> eventos) { dgListaEventos.DataSource = eventos.ToList(); dgListaEventos.Columns["Comentario"].Visible = false; dgListaEventos.Columns["Pruebas"].Visible = false; dgListaEventos.Columns["EstaHabilitado"].Visible = false; }
public ConsoleManager(IList<Command> allCommands, TextReader consoleReader, TextWriter consoleWriter) { _allCommands = allCommands; _consoleReader = consoleReader; _consoleWriter = consoleWriter; _commandParser = new CommandParser(_allCommands.ToList()); }
/// <summary> /// Search for notification status with search and filter criteria /// </summary> /// <param name="paging"></param> /// <param name="filterCriteria"></param> /// <param name="sortCriteria"></param> /// <returns></returns> public ICollection <NotificationStatusDomain> SearchNotificationStatus(Paging paging, IList <FilterCriteria> filterCriteria, IList <SortCriteria> sortCriteria) { paging.ValidatePagingCriteria(); filterCriteria?.ToList().ForEach(x => x.ValidateFilterCriteria()); sortCriteria?.ToList().ForEach(x => x.ValidateSortCriteria()); return(_notificationStatusRepository.SearchNotificationStatus(paging, filterCriteria, sortCriteria)); }
public async Task<Route> CalcuteRouteAsync(IList<AddressSearch> addressSearches, RouteType routeType) { var routeStops = new List<RouteStop>(); addressSearches.ToList().ForEach(x => { var routeStop = Mapper.Map<AddressSearch, RouteStop>(x); var point = Mapper.Map<AddressSearch, Point>(x); routeStop.point = point; routeStops.Add(routeStop); }); var options = _config.GetRouteOptions(routeType); using (var routeSoapClient = new RouteSoapClient()) { var response = await routeSoapClient.getRouteAsync(routeStops.ToArray(), options, _token.Tokenvalue); if (response.Body.getRouteResult.routeTotals != null) { var route = Mapper.Map<RouteTotals, Route>(response.Body.getRouteResult.routeTotals); return route; } } return null; }
public static float ApplyFilter(IList<float> buffered, int indexOfSource, int dropSize, int takeSize) { var list = buffered.ToList(); list.Sort(); return list.Skip(dropSize).Take(takeSize).Average(); }
public async void Add(IList<ITableEntity> notes) { var batchOperation = new TableBatchOperation(); notes.ToList().ForEach(n => batchOperation.Insert(n)); await _table.ExecuteBatchAsync(batchOperation); }
public ElementNavigator(IList<ElementDefinition> elements) { if (elements == null) throw Error.ArgumentNull("elements"); Elements = elements.ToList(); // make a *shallow* copy of the list of elements OrdinalPosition = null; }
public SessionFactoryBuilder(IDatabasePlatform platform, string connStr, IList<Assembly> assemblies, bool updateSchema, string defaultSchema, ILinqToHqlGeneratorsRegistry linqRegistry, bool showSql, Action<global::NHibernate.Cfg.Configuration> exposedConfig) { var configurer = platform.AsNHibernateConfiguration(connStr) as IPersistenceConfigurer; global::NHibernate.Cfg.Configuration configuration = null; _sessionFactory = Fluently.Configure() .Database(configurer) .Mappings(m => assemblies.ToList().ForEach(asm=> m.FluentMappings.AddFromAssembly(asm))) .ExposeConfiguration(cfg => { configuration = cfg; cfg.SetProperty(global::NHibernate.Cfg.Environment.CollectionTypeFactoryClass, typeof(List<>).AssemblyQualifiedName); cfg.SetProperty(global::NHibernate.Cfg.Environment.PrepareSql, false.ToString()); cfg.SetProperty(global::NHibernate.Cfg.Environment.ShowSql, showSql.ToString()); cfg.SetProperty(global::NHibernate.Cfg.Environment.TransactionStrategy, "NHibernate.Transaction.AdoNetTransactionFactory"); if(!String.IsNullOrEmpty(defaultSchema)) cfg.SetProperty(global::NHibernate.Cfg.Environment.DefaultSchema, defaultSchema); if (null != linqRegistry) cfg.SetProperty(global::NHibernate.Cfg.Environment.LinqToHqlGeneratorsRegistry, linqRegistry.GetType().AssemblyQualifiedName); if(exposedConfig != null) exposedConfig(cfg); }) .BuildSessionFactory(); if (updateSchema) UpdateSchema(configuration); }
public Task <IList <MandrillSendMessageResponse> > SendTemplateAsync(MandrillMessage message, string templateName, IList <MandrillTemplateContent> templateContent = null, bool async = false, string ipPool = null, DateTime?sendAtUtc = null) { if (message == null) { throw new ArgumentNullException(nameof(message)); } if (templateName == null) { throw new ArgumentNullException(nameof(templateName)); } if (sendAtUtc != null && sendAtUtc.Value.Kind != DateTimeKind.Utc) { throw new ArgumentException("date must be in utc", nameof(sendAtUtc)); } return (MandrillApi.PostAsync <MandrillSendMessageRequest, IList <MandrillSendMessageResponse> >( "messages/send-template.json", new MandrillSendTemplateRequest { Message = message, TemplateName = templateName, TemplateContent = templateContent?.ToList(), Async = async, IpPool = ipPool, SendAt = sendAtUtc?.ToString(SendAtDateFormat) })); }
public void Add(IList<HandlerTypeInfo> typeInfos) { if (!_set) { if (typeInfos.Count == 1) { _single = typeInfos[0]; } else { _list = new List<HandlerTypeInfo>(typeInfos); } _set = true; } else { if (_single != null) { _list = typeInfos as List<HandlerTypeInfo> ?? typeInfos.ToList(); _list.Insert(0, _single); _single = null; } else { _list.AddRange(typeInfos); } } }
private static void GenerateChains(IList<int> chain, int n) { var count = chain.Count; if (count >= n) return; var last = chain.Last(); var nextElems = _dict[last].Where(k => !chain.Contains(k)).ToList(); if (nextElems.Any() && count < n) { foreach (var next in nextElems) { var deeper = chain.ToList(); deeper.Add(next); GenerateChains(deeper, n); } } else if (IsPrime(last + 1) && count == n - 1) { _nrOfChains++; /*foreach (var elem in chain) { Console.Write(elem+" "); } Console.WriteLine(1);*/ } }
private ToolbarItem GetButtonInfo(IList<ToolbarItem> items, string name) { if (string.IsNullOrEmpty(name) || items == null) return null; return items.ToList().Where(itemData => name.Equals(itemData.Name)).FirstOrDefault(); }
public PocoSettings( bool makePartial, string nameSpace, IList<string> nameSpaceComments, bool createDefaultConstructor, bool createAllPropertiesConstructor, bool createAllPropertiesSansPrimaryKeyConstructor, bool createCopyConstructor, bool createMethodEquals, string createMethodEqualsRegex, string outputFolder, string projectPath, string xmlOutputFilename) { this.MakePartial = makePartial; this.NameSpace = nameSpace; this.NameSpaceComments = nameSpaceComments.ToList(); this.CreateDefaultConstructor = createDefaultConstructor; this.CreateAllPropertiesConstructor = createAllPropertiesConstructor; this.CreateAllPropertiesSansPrimaryKeyConstructor = createAllPropertiesSansPrimaryKeyConstructor; this.CreateCopyConstructor = createCopyConstructor; this.CreateMethodEquals = createMethodEquals; this.CreateMethodEqualsRegex = createMethodEqualsRegex; this.OutputFolder = outputFolder; this.ProjectPath = projectPath; this.XmlOutputFilename = xmlOutputFilename; }
public ActionResult Create(decimal valor, Pessoa pessoa, IList<Lancamento> lancamentos) { try { Caixa caixa = new Caixa() { Valor = valor, DataPagamento = DateTime.Now, Pessoa = pessoa, Lancamentos = new List<Lancamento>() }; lancamentos.ToList().ForEach(x => caixa.Lancamentos.Add(new Lancamento() { LancamentoId = x.LancamentoId, Valor = x.Valor, DataVencimento = x.DataVencimento, Pago = true })); _caixaServicos.Salva(caixa); return Json(new { Success = true }, "application/json", JsonRequestBehavior.AllowGet); } catch { return Json(new { Success = false }, "application/json", JsonRequestBehavior.AllowGet); } return View(); }
public IList <ClaimHistory> GetClaimHistoryByPolicyNumber(string policynumber, DateTime Start, DateTime end) { IList <ClaimHistory> all = NewMethod(policynumber, Start, end); IList <Claim> allfromclaims = _session.QueryOver <Claim>().WhereRestrictionOn(x => x.enrolleePolicyNumber).IsInsensitiveLike(policynumber, MatchMode.End).Where(y => y.ServiceDate >= Start).Where(z => z.ServiceDate <= end).List <Claim>(); //convert the claimhistory to shiit List <ClaimHistory> collection = new List <ClaimHistory>(); foreach (Claim item in allfromclaims) { ClaimHistory nobj = new ClaimHistory(); Provider provider = _providersvc.GetProvider(item.ProviderId); nobj.PROVIDER = provider != null?provider.Name.ToUpper() : "Unknown"; nobj.PROVIDERID = provider != null ? provider.Id : -1; nobj.POLICYNUMBER = item.enrolleePolicyNumber; nobj.ENCOUNTERDATE = Convert.ToDateTime(item.ServiceDate); nobj.DATERECEIVED = item.CreatedOn; nobj.DIAGNOSIS = item.Diagnosis.ToUpper(); nobj.AMOUNTSUBMITTED = Convert.ToDecimal(item.DrugList.Sum(x => x.InitialAmount) + item.ServiceList.Sum(x => x.InitialAmount)); nobj.AMOUNTPROCESSED = Convert.ToDecimal(item.DrugList.Sum(x => x.VettedAmount) + item.ServiceList.Sum(x => x.VettedAmount)); nobj.CLASS = Enum.GetName(typeof(ClaimsTAGS), item.Tag); nobj.CLIENTNAME = item.enrolleeFullname; //added ? after collection, collection and all collection?.Add(nobj); } collection?.AddRange(all?.ToList()); return(collection); }
/// <summary> /// Search Tenants /// </summary> /// <param name="paging, filterCriteria, sortCriteria"></param> /// <returns><see cref="ICollection{TenantDomain}"/></returns> public ICollection <TenantDomain> SearchTenants(Paging paging, IList <FilterCriteria> filterCriteria, IList <SortCriteria> sortCriteria) { paging.ValidatePagingCriteria(); filterCriteria?.ToList().ForEach(x => x.ValidateFilterCriteria()); sortCriteria?.ToList().ForEach(x => x.ValidateSortCriteria()); return(_tenantRepository.SearchTenants(paging, filterCriteria, sortCriteria)); }
public void AppendToStream(IIdentity id, long expectedVersion, IList<IEvent> newEvents) { var server = this.client.GetServer(); var db = server.GetDatabase("EventStore"); var query = Query<MongoEventDocument>.EQ(s => s.id, id); var events = db.GetCollection<MongoEventDocument>("Events",_commitSettings); //events.Insert<MongoEventDocument>(new MongoEventDocument //{ // events = newEvents.ToList<IEvent>(), // id = id, // version = 1 //}); var doc = events.FindOneAs<MongoEventDocument>(query); if (doc == null) events.Insert<MongoEventDocument>(new MongoEventDocument { events = newEvents.ToList<IEvent>(), id = id, version = 1 }); if (doc != null) { doc.events.AddRange(newEvents); doc.version += 1; events.Save(doc); } }
/// <summary> /// Initializes a new instance of UITableView. /// </summary> /// <param name="data">Source Data.</param> /// <param name="cellHeight">cellHeight, use 0 for default.</param> /// <param name="fSize">Cell Font size.</param> /// <param name="cellSelectedBackgroundColor">Cell selected background color, Use Clear for default</param> /// <param name="cellSelectedTextColor">Cell selected text color, Use Clear for default</param> public DropDownTable(IList<string> data, nfloat cellHeight, nfloat fSize, UIColor cellSelectedBackgroundColor, UIColor cellSelectedTextColor, string selectedText = "") : base() { CellLayoutMarginsFollowReadableWidth = false; this.MultipleTouchEnabled = true; this._FontSize = fSize; this._CellHeight = cellHeight; this._CellSBackgroundColor = cellSelectedBackgroundColor; this._CellSTextColor = cellSelectedTextColor; Source = new DropDownSource (data, this._FontSize, this._CellHeight, this._CellSBackgroundColor, this._CellSTextColor, selectedText); //ContentInset = new UIEdgeInsets(0, -10, 0, 0); LayoutMargins = UIEdgeInsets.Zero; SeparatorInset = UIEdgeInsets.Zero; // select default row var idx = data.ToList().FindIndex(x => x == selectedText); System.Diagnostics.Debug.WriteLine (idx); if (idx >= 0) { this.SelectRow (Foundation.NSIndexPath.FromItemSection (idx, 0), false, UITableViewScrollPosition.Top); } (Source as DropDownSource).OnSelected += RowSelected; }
public CompletedItemReviewer(IList<SuspiciousPhrase> basicSuspiciousPhrases) { if (basicSuspiciousPhrases == null) throw new ArgumentNullException(nameof(basicSuspiciousPhrases)); _basicSuspiciousPhrases = basicSuspiciousPhrases.ToList(); }
public SolutionWriter(ProjectVersion projectVersion, IList<Project> projects, string filename) { this.projectVersion = projectVersion; this.projects = projects.ToList(); this.projects.Sort((a, b) => { // Sort exes first since VS picks the first file in the solution to be the // "StartUp Project". int ae = (a.Module.Characteristics & Characteristics.Dll) == 0 ? 0 : 1; int be = (b.Module.Characteristics & Characteristics.Dll) == 0 ? 0 : 1; int c = ae.CompareTo(be); if (c != 0) return c; return StringComparer.OrdinalIgnoreCase.Compare(a.Filename, b.Filename); }); this.filename = filename; this.configs = new List<string>(); this.configs.Add("Debug"); this.configs.Add("Release"); var hash = new HashSet<string>(projects.Select(a => a.Platform)); this.platforms = new List<string>(hash.Count); this.platforms.Add("Any CPU"); hash.Remove("AnyCPU"); if (hash.Count > 0) this.platforms.Add("Mixed Platforms"); foreach (var p in hash) this.platforms.Add(p); }
public AddPurchase() { InitializeComponent(); ChangeHeightWidth(); ClearData(); myResourceDictionary = new ResourceDictionary(); myResourceDictionary.Source = new Uri("/ResourceFiles/En.xaml", UriKind.RelativeOrAbsolute); new ObservableCollection <PurchaseStockModel>().Clear(); // purchase_deliveryDate.se =DateTime.Now; ResponseVm responseTax = taxController.GetTax(); if (responseTax.FaultData == null) { TaxModel objTaxModel = new TaxModel(0, "Select", 0, "", "", "", ""); _taxdetails = responseTax.Response.Cast <TaxModel>().ToList(); _taxdetails.Insert(0, objTaxModel); this.cmbTax.ItemsSource = _taxdetails; this.cmbTax.DisplayMemberPath = "TaxDetail"; this.cmbTax.SelectedValuePath = "TaxCode"; this.cmbTax.SelectedIndex = 0; } ResponseVm responce = productController.GetProductsByCompanyAndBranch(); if (responce.FaultData == null) { _products = responce.Response.Cast <ProductModel>().ToList(); if (_products != null && _products.Count > 0) { _products?.ToList().ForEach(x => { int currentStock = OpeningStockController.GetCurrentStockByProductCode(Convert.ToInt64(x.Id)); //ProductModel product = new ProductModel(x.Id, x.ItemCode, x.ItemName, x.RetailPrice.Value, x.TradePrice.Value, x.CategoryCode.Value, x.ItemType, x.BarCode, x.TaxPercentage.Value, x.CategoryName); x.CurrentStock = currentStock; }); dgPurchases.ItemsSource = _products; dgPurchases.Visibility = Visibility.Visible; } else { dgPurchases.Visibility = Visibility.Collapsed; brd_exp.Visibility = Visibility.Visible; } } if (purchaseStocks == null) { additems(); } btn_AddRow.IsEnabled = true; btn_Save.IsEnabled = true; btn_remove.IsEnabled = false; btn_remove.Background = Brushes.Gray; _supliers = controller.GetSuppliersByCompanyAndBrach(UserModelVm.CompanyId, UserModelVm.BranchId).ToList(); lstPurchase.ItemsSource = purchaseStocks; }
/// <summary> /// Sets the current user values. /// </summary> /// <param name="userId"><see cref="UserId"/></param> /// <param name="tenantId"><see cref="TenantId"/></param> /// <param name="tenantName"><see cref="TenantName"/></param> /// <param name="email"><see cref="Email"/></param> /// <param name="givenName"><see cref="GivenName"/></param> /// <param name="products"><see cref="Products"/></param> /// <exception cref="InvalidOperationException"> /// Thrown when method is called on an already populated IdentityUser. /// Since this data is for the current user of the request it cannot be changed as the source of a request cannot change. /// </exception> /// <exception cref="ArgumentException">Thrown if UserId or TenantId is a default guid (all 0s).</exception> /// <exception cref="ArgumentNullException">Thrown if TenantName, Email, or GivenName is null or empty.</exception> public void SetUser( Guid userId, Guid tenantId, string tenantName, string tenantDisplayName, string email, string givenName, string firstName, string lastName, IList <UserProduct> products, IList <Guid> roles, Dictionary <string, List <string> > permissions) { if (userId == default) { throw new ArgumentException(nameof(userId)); } if (tenantId == default) { throw new ArgumentException(nameof(tenantId)); } if (string.IsNullOrEmpty(tenantName)) { throw new ArgumentNullException(nameof(tenantName)); } if (string.IsNullOrEmpty(tenantDisplayName)) { throw new ArgumentNullException(nameof(tenantDisplayName)); } if (string.IsNullOrEmpty(email)) { throw new ArgumentNullException(nameof(email)); } if (string.IsNullOrEmpty(givenName)) { throw new ArgumentNullException(givenName); } if (string.IsNullOrEmpty(firstName)) { throw new ArgumentNullException(firstName); } if (string.IsNullOrEmpty(lastName)) { throw new ArgumentNullException(lastName); } UserId = userId; TenantId = tenantId; TenantName = tenantName; TenantDisplayName = tenantDisplayName; Email = email; GivenName = givenName; FirstName = firstName; LastName = lastName; Products = new ReadOnlyCollection <UserProduct>(products); Roles = roles?.ToList(); Permissions = permissions; IsLoaded = true; }
/// <summary> /// 添加错误信息列表 /// </summary> /// <param name="errors"></param> public virtual void AddErrors(IList <ErrorInfo> errors) { Errors = Errors ?? new List <ErrorInfo>(); errors?.ToList().ForEach(error => { Errors.Add(error); }); }
public IEnumerable <DocumentDomain> Search(Paging paging, IList <FilterCriteria> filterCriteria, IList <SortCriteria> sortCriteria) { paging.ValidatePagingCriteria(); filterCriteria?.ToList().ForEach(x => x.ValidateFilterCriteria()); sortCriteria?.ToList().ForEach(x => x.ValidateSortCriteria()); return(_documentRepository.Search(paging, filterCriteria, sortCriteria)); }
public TemplateHandler(IList <ITypeMapping> typeMappings) { typeMappingsField = typeMappings?.ToList() ?? new List <ITypeMapping>(); templateContextHandlerProvider = new TemplateContextHandlerPackageProvider <AbstractTemplateContextHandler>(this, typeMappings); templateValidator = new TemplateValidator(this, typeMappings); contextVisitor = new ContextVisitor <AbstractTemplateContextHandler>(templateContextHandlerProvider); templateContextProcessor = new TemplateContextProcessor(this, typeMappings); toQualifiedTemplateContextConverter = new ToQualifiedTemplateContextConverter(this, typeMappings); }
public void Notify(IList <ModStatus> statuses) { this.notified = true; this.originalStatuses = statuses?.ToList(); this.displayIndex = 0; this.currentSortColumn = 1; this.currentSortDirection = 1; this.UpdateComponents(); }
public TemplateContextProcessor(ITemplateHandler templateHandlerNew, IList <ITypeMapping> typeMappings) { typeMappingsField = typeMappings?.ToList() ?? new List <ITypeMapping>(); databaseTemplateContextHandlerProvider = new TemplateContextHandlerPackageProvider <AbstractDatabaseTemplateContextHandler>(templateHandlerNew, typeMappings); tableTemplateContextHandlerProvider = new TemplateContextHandlerPackageProvider <AbstractTableTemplateContextHandler>(templateHandlerNew, typeMappings); columnTemplateContextHandlerProvider = new TemplateContextHandlerPackageProvider <AbstractColumnTemplateContextHandler>(templateHandlerNew, typeMappings); constraintTemplateContextHandlerProvider = new TemplateContextHandlerPackageProvider <AbstractConstraintTemplateContextHandler>(templateHandlerNew, typeMappings); functionTemplateContextHandlerProvider = new TemplateContextHandlerPackageProvider <AbstractFunctionTemplateContextHandler>(templateHandlerNew, typeMappings); databaseContextCopier = new DatabaseContextCopier(); }
private DebuggerEngines(bool isLazy, bool isAutomatic, IList <DebuggerEngine> manualSelection) { this.isLazy = isLazy; this.IsAutomatic = isAutomatic; this.manualSelection = manualSelection?.ToList() ?? throw new ArgumentNullException(nameof(ManualSelection)); foreach (var debuggerEngine in this.manualSelection) { debuggerEngine.PropertyChanged += OnChildPropertyChanged; } }
public static IList <T> Generate <T>(IList <T> seed, Func <IList <T>, T> function, Func <IList <T>, bool> continueSeries) { var result = seed?.ToList() ?? new List <T>(); while (continueSeries(result)) { result.Add(function(result)); } return(result); }
private void CollectCurrentMonth() { _groupItem = 0; for (DateTime[] day = { _firstDayCurrent }; day[0] <= _lastDayCurrent; day[0] = day[0].AddDays(1)) { var selected = _listDateTimeCalendar?.ToList().Exists(x => x.Date == day[0].Date) ?? false; Calendar.CurrentMonthDay.Add(ModificationOrdin(new DateInfoCell(), day[0], _groupItem, selected)); Counter(day[0]); } if (Calendar.CurrentMonthDay.Count(x => x.LineGroupGrid == 0) != 7) { CollectPrevMonth(); } CollectNextMonth(); }
public static Polygon3D ToSAM_Polygon3D(this Wire wire) { IList <Vertex> vertices = wire.Vertices; if (vertices == null || vertices.Count < 3) { return(null); } return(Spatial.Create.Polygon3D(vertices?.ToList().ConvertAll(x => x.ToSAM()))); }
// ReSharper restore MemberCanBePrivate.Global /// <summary> /// Execute a block node /// </summary> /// <param name="tree">Tree to be executed</param> private void Block(KermitAST tree) { if (tree.Type != KermitParser.BLOCK) { ThrowHelper.InterpreterException("Not a block!: " + tree.ToStringTree()); } IList <ITree> children = tree.Children; children?.ToList().ForEach(x => Execute((KermitAST)x)); }
public async Task <ActionResult> Index() { IList <ApplicationFeatureFlag> applicationFeatureFlags = null; HttpResponseMessage response = await _httpClient.GetAsync(ApplicationFeatureFlagResourceName); if (response.IsSuccessStatusCode) { applicationFeatureFlags = await response.Content.ReadAsAsync <IList <ApplicationFeatureFlag> >(); } return(View(applicationFeatureFlags?.ToList())); }
/// <summary> /// Run the middlewares. /// </summary> /// <param name="hubContext">DotNetify hub context.</param> private void RunMiddlewares(IDotNetifyHubContext hubContext) { try { _middlewareFactories?.ToList().ForEach(factory => factory().Invoke(hubContext)); } catch (Exception ex) { Response_VM(Context.ConnectionId, hubContext.VMId, SerializeException(ex)); throw new OperationCanceledException($"Middleware threw {ex.GetType().Name}: {ex.Message}", ex); } }
IList <T> getn() { lock (o) { if (n == c) { n = c?.ToList() ?? new List <T>(); c = null; } return(n); } }
public IEnumerable <DevicePingDomain> Search(int tenantId, Paging paging, IList <FilterCriteria> filterCriteria, IList <SortCriteria> sortCriteria) { if (paging == null) { throw new ArgumentNullException("paging cannot be null"); } paging.ValidatePagingCriteria(); filterCriteria?.ToList().ForEach(x => x.ValidateFilterCriteria()); sortCriteria?.ToList().ForEach(x => x.ValidateSortCriteria()); return(_devicePingRepository.Search(tenantId, paging, filterCriteria, sortCriteria)); }
public JsonWebToken CreateToken(string userId, string role = null, IList <Claim> claims = null) { if (string.IsNullOrWhiteSpace(userId)) { throw new ArgumentException("User id claim can not be empty.", nameof(userId)); } var now = DateTime.UtcNow; var jwtClaims = new List <Claim> { new Claim(JwtClaimsTypes.Sub, userId), new Claim(JwtClaimsTypes.UniqueName, userId), new Claim(JwtClaimsTypes.Name, userId), new Claim(JwtClaimsTypes.Jti, Guid.NewGuid().ToString()), new Claim(JwtClaimsTypes.Iat, now.ToTimestamp().ToString()) }; if (!string.IsNullOrWhiteSpace(role)) { jwtClaims.Add(new Claim(JwtClaimsTypes.Role, role)); } var customClaims = claims?.ToList() ?? new List <Claim>(); jwtClaims.AddRange(customClaims); var expires = now.AddMinutes(_options.ExpiryMinutes); var jwt = new JwtSecurityToken( issuer: _options.Issuer, claims: jwtClaims, notBefore: now, expires: expires, signingCredentials: _signingCredentials ); var token = new JwtSecurityTokenHandler(); token.InboundClaimTypeMap.Clear(); var jwtToken = token.WriteToken(jwt); customClaims.Add(new Claim(JwtClaimsTypes.AccessToken, jwtToken)); return(new JsonWebToken { AccessToken = jwtToken, RefreshToken = string.Empty, Expires = expires, Id = userId, Role = role ?? string.Empty, Claims = customClaims.ToDictionary(c => c.Type, c => c.Value) }); }
public async Task <IActionResult> Customers() { IList <ApplicationUser> users = await _userManager.GetUsersInRoleAsync(Roles.User.ToString()); // Manter os usuarios (clientes) na sessao HttpContext.Session.SetSession("Customers", users); var customerModel = new CustomersViewModel() { Customers = users?.ToList(), Registration = new CustomerRegistrationViewModel() }; return(View(customerModel)); }
public Task <IList <MandrillMessageTimeSeries> > SearchTimeSeriesAsync(string query, DateTime?dateFrom = null, DateTime?dateTo = null, IList <string> tags = null, IList <string> senders = null) { return (MandrillApi.PostAsync <MandrillMessageSearchRequest, IList <MandrillMessageTimeSeries> >( "messages/search-time-series.json", new MandrillMessageSearchRequest { DateFrom = dateFrom?.ToString(SearchDateFormat), DateTo = dateTo?.ToString(SearchDateFormat), Query = query, Tags = tags?.ToList(), Senders = senders?.ToList() })); }
public virtual IDbCommand GetCommand(string commandtext = "", CommandType commandtype = CommandType.Text, IList <SqlParameter> parameters = null) { var command = _dbcreator?.Command; command.CommandText = commandtext; command.CommandType = commandtype; parameters?.ToList()?.ForEach(p => { command.Parameters.Add(GetParameter(p.Name, p.Type, p.Value, p.Direction)); }); command.Connection = _dbcreator?.Connection; return(command); }
public Task <IList <MandrillMessageInfo> > SearchAsync(string query, DateTime?dateFrom = null, DateTime?dateTo = null, IList <string> tags = null, IList <string> senders = null, IList <string> apiKeys = null, int?limit = null) { return (MandrillApi.PostAsync <MandrillMessageSearchRequest, IList <MandrillMessageInfo> >("messages/search.json", new MandrillMessageSearchRequest { DateFrom = dateFrom?.ToString(SearchDateFormat), DateTo = dateTo?.ToString(SearchDateFormat), Query = query, Tags = tags?.ToList(), Senders = senders?.ToList(), ApiKeys = apiKeys?.ToList(), Limit = limit })); }
private List <ForecastObject> GetForecastsObjects() { IList <ForecastObject> forecastObjects = null; try { forecastObjects = _forecastObjectProvider.GetDataFromServer(); } catch (Exception e) { ExceptionLogger.Log(e); ConnectionError(); Application.Current.Dispatcher.BeginInvoke(new ThreadStart(SetUpAfterError)); } return(forecastObjects?.ToList()); }
private void CreateMarketDataProcessingDataFlow() { _source = new BufferBlock <MarketDataUpdate>(new DataflowBlockOptions() { BoundedCapacity = DataAggregatorAppSettings.BufferBoundedCapacity }); _batchBlock = new BatchBlock <MarketDataUpdate>(batchSize: DataAggregatorAppSettings.BatchSize, new GroupingDataflowBlockOptions() { Greedy = true }); _writer = new ActionBlock <List <MarketDataUpdate> >(cd => { Console.WriteLine("-------------------------------------------------------"); cd.ForEach(d => Console.WriteLine(d)); Console.WriteLine("*******************************************************"); // snapshot work with current copy data - thread safe. _watchers?.ToList().ForEach(watcher => watcher.OnUpdate(cd.ToArray())); }); _transformBlock = new TransformBlock <MarketDataUpdate[], List <MarketDataUpdate> >(e => { var helper = new MergeDataHelper(); return(helper.MergeData(e)); }); _source.LinkTo(_batchBlock, new DataflowLinkOptions() { PropagateCompletion = true }); _batchBlock.LinkTo(_transformBlock, new DataflowLinkOptions() { PropagateCompletion = true }); _transformBlock.LinkTo(_writer, new DataflowLinkOptions() { PropagateCompletion = true }); _timer = new Timer(x => { _batchBlock.TriggerBatch(); }); _timer.Change(DataAggregatorAppSettings.TimerDueTimeMiliseconds, DataAggregatorAppSettings.TimerPeriodMiliseconds); }
private static List <Field> GetListFromCache(int contentId) { IList <Field> result = null; var cache = QPContext.GetFieldCache(); var cache2 = QPContext.GetContentFieldCache(); if (cache != null && cache2 != null && cache2.ContainsKey(contentId)) { var fieldIds = cache2[contentId]; var tempFieldIds = fieldIds.Select(n => cache.ContainsKey(n) ? cache[n] : null).ToList(); if (tempFieldIds.All(n => n != null)) { result = tempFieldIds; } } return(result?.ToList()); }