public static BuiltComponents BuildStandardSinkSet(IStandardSinkSetConfiguration simpleConfig, IEnumerable<ISnapshotProvider> source) { var sources = new List<ISnapshotProvider>(); sources.AddRange(source); var bufferElement = new SinkElement(simpleConfig); var storeElement = new StoreElement(simpleConfig); var plotterElement = new PlotterElement(simpleConfig); var bufferConfig = new CircularDataSinkConfiguration(new[] {bufferElement}); var storeConfig = new FileSystemDataStoreConfiguration(new[] {storeElement}); var plotterConfig = new PlotterConfiguration(new[] {plotterElement}); var sinks = new List<ISnapshotConsumer>(); var buffers = CircularDataSinkBuilder.Build(bufferConfig); sinks.AddRange(buffers); sources.AddRange(buffers); var stores = FileSystemDataStoreBuilder.Build(storeConfig); sinks.AddRange(stores); sources.AddRange(stores); var multiSinks = new List<IMultipleSnapshotConsumer>(); multiSinks.AddRange(MultiPlotterBuilder.Build(plotterConfig)); var bufferChainElement = new ChainElement( simpleConfig.Id + " Buffer Chain", simpleConfig.Name, simpleConfig.Id + " Source", simpleConfig.Id + " Buffer", ""); var sinkChainElement = new ChainElement( simpleConfig.Id + " Sink Chain", simpleConfig.Name, simpleConfig.Id + " Buffer", simpleConfig.Id + " Store", simpleConfig.Id + " Plotter"); var preloadChainElement = new ChainElement( simpleConfig.Id + " Preload Chain", simpleConfig.Name, simpleConfig.Id + " Store", simpleConfig.Id + " Buffer", ""); var chainConfig = new ChainConfiguration(new[] {bufferChainElement, sinkChainElement, preloadChainElement}); var preloadScheduleElement = new ScheduleElement(simpleConfig.Id + " Preload Schedule", simpleConfig.Delay, preloadChainElement.Id); var preloadScheduleConfig = new ScheduleConfiguration(new[] {preloadScheduleElement}); var chainNames = String.Join(",", new[] {sinkChainElement.Id, bufferChainElement.Id}); var scheduleElement = new ScheduleElement(simpleConfig.Id + " Schedule", simpleConfig.Delay, chainNames); var scheduleConfig = new ScheduleConfiguration(new[] {scheduleElement}); return new BuiltComponents(sources, sinks, multiSinks, chainConfig, preloadScheduleConfig, scheduleConfig); }
public void StatC5CX(List<DwNumber> numbers, string dbName) { string[] dmNames = new string[] { "Peroid", "He" }; string[] numberTypes = new string[] { "A2", "A3", "A4", "A6", "A7", "A8" }; DwC5CXSpanBiz spanBiz = new DwC5CXSpanBiz(dbName); foreach (var numberType in numberTypes) { Dictionary<string, Dictionary<string, int>> lastSpanDict = new Dictionary<string, Dictionary<string, int>>(16); List<DwC5CXSpan> c5cxSpans = new List<DwC5CXSpan>(numbers.Count * 20); string newNumberType = numberType.Replace("A", "C"); string tableName = string.Format("{0}{1}", "C5", newNumberType); spanBiz.DataAccessor.TableName = ConfigHelper.GetDwSpanTableName(tableName); long lastP = spanBiz.DataAccessor.SelectLatestPeroid(string.Empty); foreach (DwNumber number in numbers) { var cxNumbers = NumberCache.Instance.GetC5CXNumbers(number.C5, newNumberType); var c5cxSpanList = this.GetC5CXSpanList(lastSpanDict, cxNumbers, number, dmNames); if (number.P > lastP) c5cxSpans.AddRange(c5cxSpanList); } spanBiz.DataAccessor.Insert(c5cxSpans, SqlInsertMethod.SqlBulkCopy); Console.WriteLine("{0} {1} Finished", dbName, tableName); } Console.WriteLine("{0} {1} Finished", dbName, "ALL C5CX Span"); }
public static List<UserProfile> GetFarFromOneRelations(Guid userId) { // On cherche nos relations. On cherche les relations de nos relations => récursif List<UserProfile> listUserRelations = GetRelations(userId); List<UserProfile> listLoggedUserRelation = GetRelations((Guid)(Membership.GetUser(System.Web.HttpContext.Current.User.Identity.Name, false).ProviderUserKey)); List<UserProfile> listFarFromOneRelations = new List<UserProfile>(); // We search all the directly connected users to the actual logged user relations foreach (UserProfile userRelation in listUserRelations) { listFarFromOneRelations.AddRange(GetRelations((Guid)(Membership.GetUser(userRelation.UserName, false).ProviderUserKey))); } UserProfile actualUser = UserProfile.GetUserProfile(System.Web.HttpContext.Current.User.Identity.Name); while(listFarFromOneRelations.Contains(actualUser)) { // We delete all the occurences of the actual user listFarFromOneRelations.Remove(actualUser); } // On supprime les utilisateurs qui sont déjà directement connectés avec l'utilisateur foreach (UserProfile user in listLoggedUserRelation) { if (listFarFromOneRelations.Contains(user)) { listFarFromOneRelations.Remove(user); } } return listFarFromOneRelations; }
List<ConnectionInfo> GetConnectionInfosForSelectedServers(string[] hostnames) { // TODO: support for wildcards var connectionInfosApplicable = new List<ConnectionInfo>(); if (hostnames.Any()) connectionInfosApplicable.AddRange(hostnames.SelectMany(hostname => ConnectionData.Entries.Where(connData => 0 == string.Compare(connData.Host, hostname, StringComparison.OrdinalIgnoreCase)))); else connectionInfosApplicable = ConnectionData.Entries; return connectionInfosApplicable; }
IEnumerable<IEsxiVirtualMachine> GetMachinesFromServer(IEnumerable<ConnectionInfo> connectionInfos) { var vms = new List<IEsxiVirtualMachine>(); var codeRunner = new CrossHostCodeRunner(); Func<PlainTextDataConverter, string, string, List<IEsxiVirtualMachine>> runnerFunc = (runner, textData, server) => runner.GetMachines(textData, server); foreach (var connInfo in connectionInfos) // TODO: error handling vms.AddRange(codeRunner.Run<PlainTextDataConverter, List<IEsxiVirtualMachine>>(connInfo, Commands.GetVirtualMachines, runnerFunc)); return vms; }
public static List<movimiento_caja> getAllEstadoCaja(edificio edificio, DateTime periodo) { DateTime p = DateTime.Parse("1/" + periodo.Month + "/" + periodo.Year); List<movimiento_caja> movimientos = new List<movimiento_caja>(); movimiento_caja mc = new movimiento_caja(); mc.fecha = p; mc.concepto = "Saldo mes anterior"; mc.importe = getSaldoMesAnterior(edificio, p); movimientos.Add(mc); movimientos.AddRange(CatalogoCajaEdificio.getMovmientosEdificio(edificio, p)); return movimientos; }
static Category CreateCategory() { var fd1 = new FieldDefinition { Id = new Guid("00000000-0000-0000-0000-000000000001"), Name = "Val1", FieldType = typeof(int) }; var fd2 = new FieldDefinition { Id = new Guid("00000000-0000-0000-0000-000000000002"), Name = "Val2", FieldType = typeof(string) }; var fd3 = new FieldDefinition { Id = new Guid("00000000-0000-0000-0000-000000000003"), Name = "Val3", FieldType = typeof(long) }; var blueprint = new List<FieldDefinition>(3); blueprint.AddRange(new[] { fd1, fd2, fd3 }); return new Category { //Id = Guid.NewGuid(), Name = "Category 1", Fields = blueprint }; }
public static List<LeagueSharpAssembly> GetAssemblies(string directory, string url = "") { var projectFiles = new List<string>(); var foundAssemblies = new List<LeagueSharpAssembly>(); try { projectFiles.AddRange(Directory.GetFiles(directory, "*.csproj", SearchOption.AllDirectories)); foundAssemblies.AddRange(from projectFile in projectFiles let name = Path.GetFileNameWithoutExtension(projectFile) select new LeagueSharpAssembly(name, projectFile, url)); } catch (Exception e) { Utility.Log(LogStatus.Error, "Updater", e.ToString(), Logs.MainLog); } return foundAssemblies; }
static Factor CreateFactor(Category category, int iterator) { var f1 = new FieldValue<int>(new Guid("00000000-0000-0000-0000-000000000001"), iterator); var f2 = new FieldValue<string>(new Guid("00000000-0000-0000-0000-000000000002"), "Ahoj " + iterator); var f3 = new FieldValue<long>(new Guid("00000000-0000-0000-0000-000000000003"), 1000000000L + iterator); var construct = new List<FieldValue>(3); construct.AddRange(new FieldValue[] { f1, f2, f3 }); return new Factor { //Id = Guid.NewGuid(), Name = "Factor " + iterator, Category = category, Fields = construct }; }
private void btnGenerar_Click(object sender, EventArgs e) { if (cmbEdificios.CheckedItems.Count > 0) { var output = new List<edificio>(cmbEdificios.CheckedItems.Count); output.AddRange(cmbEdificios.CheckedItems.Cast<edificio>()); LoadingForm loading = new LoadingForm(); (new Thread(() => loading.ShowDialog())).Start(); Business.ControladorInformes.generarInformeUnidadesEdificio(output); Invoke(new Action(() => loading.Close())); if (MessageBox.Show("Desea abrir la carpeta con los archivos generados?", "Sistema", MessageBoxButtons.YesNo) == DialogResult.Yes) //System.Diagnostics.Process.Start(@"Liquidaciones\" + edi.direccion + periodo.Month + "-" + periodo.Year + ".pdf"); System.Diagnostics.Process.Start("Listados unidades\\"); this.Close(); } else MessageBox.Show("Seleccione al menos un edificio", "Sistema"); }
/// <summary> /// Processes the children. /// </summary> /// <param name="rootItem">The root item.</param> /// <param name="itemsRedirectsList">The items redirects list.</param> /// <param name="sectionsRedirectList">The sections redirect list.</param> /// <param name="regExList">The reg ex list.</param> /// <param name="itemsRedirectsListOut">The items redirects list out.</param> /// <param name="sectionsRedirectListOut">The sections redirect list out.</param> /// <param name="regExListOut">The reg ex list out.</param> private static void ProcessChildren(Item rootItem, List<RedirectItem> itemsRedirectsList, List<RedirectItem> sectionsRedirectList, List<RegExItem> regExList, out List<RedirectItem> itemsRedirectsListOut, out List<RedirectItem> sectionsRedirectListOut, out List<RegExItem> regExListOut) { itemsRedirectsListOut = itemsRedirectsList; sectionsRedirectListOut = sectionsRedirectList; regExListOut = regExList; foreach (var item in rootItem.GetChildren().ToArray()) { if (!item.Publishing.IsPublishable(System.DateTime.Now, true)) { continue; } List<RedirectItem> bufItemsRedirectsList; List<RedirectItem> bufSectionsRedirectList; List<RegExItem> bufRegExRedirectList; CheckRedirectType(item, out bufItemsRedirectsList, out bufSectionsRedirectList, out bufRegExRedirectList); if (bufItemsRedirectsList != null) { itemsRedirectsListOut.AddRange(bufItemsRedirectsList); } if (bufSectionsRedirectList != null) { sectionsRedirectListOut.AddRange(bufSectionsRedirectList); } if (bufRegExRedirectList != null) { regExListOut.AddRange(bufRegExRedirectList); } ProcessChildren(item, itemsRedirectsList, sectionsRedirectList, regExList, out itemsRedirectsList, out sectionsRedirectList, out regExList); } }
public void MainWindow_OnClosing(object sender, CancelEventArgs e) { if (AssembliesWorker.IsBusy && e != null) { AssembliesWorker.CancelAsync(); e.Cancel = true; Hide(); return; } try { Utility.MapClassToXmlFile(typeof(Config), Config.Instance, Directories.ConfigFilePath); } catch { MessageBox.Show(Utility.GetMultiLanguageText("ConfigWriteError")); } InjectThread?.Abort(); var allAssemblies = new List<LeagueSharpAssembly>(); foreach (var profile in Config.Instance.Profiles) { allAssemblies.AddRange(profile.InstalledAssemblies.ToList()); } Utility.ClearDirectory(Directories.AssembliesDir); Utility.ClearDirectory(Directories.LogsDir); GitUpdater.ClearUnusedRepos(allAssemblies); }
public string SearchForIssues(string[] tags) { // If there are no tags provided, the action returns There are no tags provided if (tags.Length < 0) { return "There are no tags provided"; } var issues = new List<Issue>(); foreach (var tag in tags) { issues.AddRange(this.Data.Tag_Issues[tag]); } // If there are no matching issues, the action returns There are no issues matching the tags provided if (!issues.Any()) { return "There are no issues matching the tags provided"; } // If an issue matches several tags, it is included only once in the search results. var uniqueIssues = issues.Distinct(); // In case of success, the action returns the issues sorted by priority (in descending order) first, and by title (in alphabetical order) next. return string.Join( Environment.NewLine, uniqueIssues.OrderByDescending(x => x.Priority).ThenBy(x => x.Title)); }
/// <summary> /// Initializes the view model meta data. /// <para /> /// This method only initializes the meta data once per view model type. If a type is already initialized, /// this method will immediately return. /// </summary> /// <param name="viewModelType">Type of the view model.</param> /// <returns>ViewModelMetadata.</returns> /// <exception cref="ArgumentNullException">The <paramref name="viewModelType" /> is <c>null</c>.</exception> private static ViewModelMetadata InitializeViewModelMetaData(Type viewModelType) { if (_metaData.ContainsKey(viewModelType)) { return _metaData[viewModelType]; } var properties = new List<PropertyInfo>(); var bindingFlags = BindingFlagsHelper.GetFinalBindingFlags(true, false, true); properties.AddRange(viewModelType.GetPropertiesEx(bindingFlags)); var modelObjectsInfo = new Dictionary<string, ModelInfo>(); var viewModelToModelMap = new Dictionary<string, ViewModelToModelMapping>(); var validationSummaries = new Dictionary<string, ValidationToViewModelAttribute>(); foreach (var propertyInfo in properties) { #region Model attributes var modelAttribute = propertyInfo.GetCustomAttributeEx(typeof(ModelAttribute), true) as ModelAttribute; if (modelAttribute != null) { modelObjectsInfo.Add(propertyInfo.Name, new ModelInfo(propertyInfo.Name, modelAttribute)); } #endregion #region ViewModelToModel attributes var viewModelToModelAttribute = propertyInfo.GetCustomAttributeEx(typeof(ViewModelToModelAttribute), true) as ViewModelToModelAttribute; if (viewModelToModelAttribute != null) { if (string.IsNullOrEmpty(viewModelToModelAttribute.Property)) { // Assume the property name in the model is the same as in the view model viewModelToModelAttribute.Property = propertyInfo.Name; } if (!viewModelToModelMap.ContainsKey(propertyInfo.Name)) { viewModelToModelMap.Add(propertyInfo.Name, new ViewModelToModelMapping(propertyInfo.Name, viewModelToModelAttribute)); } } #endregion #region ValidationToViewModel attributes var validationToViewModelAttribute = propertyInfo.GetCustomAttributeEx(typeof(ValidationToViewModelAttribute), true) as ValidationToViewModelAttribute; if (validationToViewModelAttribute != null) { if (propertyInfo.PropertyType != typeof(IValidationSummary)) { throw Log.ErrorAndCreateException<InvalidOperationException>("A property decorated with the ValidationToViewModel attribute must be of type IValidationSummary, but '{0}' is not", propertyInfo.Name); } validationSummaries.Add(propertyInfo.Name, validationToViewModelAttribute); Log.Debug("Registered property '{0}' as validation summary", propertyInfo.Name); } #endregion } _metaData.Add(viewModelType, new ViewModelMetadata(viewModelType, modelObjectsInfo, viewModelToModelMap, validationSummaries)); return _metaData[viewModelType]; }
/// <summary> /// Returns the sequence of properties of the specified type. /// </summary> /// <param name="type">The type.</param> /// <param name="schema">The schema.</param> /// <param name="schemaSet">The schema set.</param> /// <param name="serializationManager">The serialization manager.</param> /// <returns>Sequence containing all properties.</returns> private static XmlSchemaSequence GetPropertiesSequence(Type type, XmlSchema schema, XmlSchemaSet schemaSet, ISerializationManager serializationManager) { Argument.IsNotNull("type", type); Argument.IsNotNull("schema", schema); Argument.IsNotNull("schemaSet", schemaSet); var propertiesSequence = new XmlSchemaSequence(); if (typeof(ModelBase).IsAssignableFromEx(type)) { var typeNs = GetTypeNamespaceForSchema(type); var members = new List<MemberInfo>(); members.AddRange(from field in serializationManager.GetFieldsToSerialize(type) select type.GetFieldEx(field)); members.AddRange(from property in serializationManager.GetPropertiesToSerialize(type) select type.GetPropertyEx(property)); foreach (var member in members) { var propertySchemaElement = new XmlSchemaElement(); propertySchemaElement.Name = member.Name; var memberType = typeof(object); var fieldInfo = member as FieldInfo; if (fieldInfo != null) { memberType = fieldInfo.FieldType; } var propertyInfo = member as PropertyInfo; if (propertyInfo != null) { memberType = propertyInfo.PropertyType; } if (memberType.ImplementsInterfaceEx(typeof(IEnumerable)) && memberType != typeof(string)) { propertySchemaElement.SchemaTypeName = new XmlQualifiedName(string.Format("{0}", member.Name), typeNs); var collectionPropertyType = new XmlSchemaComplexType(); collectionPropertyType.Name = string.Format("{0}", member.Name); schema.Items.Add(collectionPropertyType); foreach (var genericArgument in memberType.GetGenericArguments()) { AddTypeToSchemaSet(genericArgument, schemaSet, serializationManager); } } else { propertySchemaElement.SchemaTypeName = AddTypeToSchemaSet(memberType, schemaSet, serializationManager); propertySchemaElement.IsNillable = TypeHelper.IsTypeNullable(memberType); propertySchemaElement.MinOccurs = 0; } propertiesSequence.Items.Add(propertySchemaElement); } } return propertiesSequence; }
public List<SensiumResultPhrase> GetInteresstingPhrasesFromActualContext() { SensiumConnector conn = new SensiumConnector(); List<SensiumResultPhrase> results = new List<SensiumResultPhrase>(); List<ContextSet> actualContextSets = GetContext(); for (int i = 0; i < actualContextSets.Count; i++) { if (actualContextSets[i].Type.ToLower() == "url") { List<SensiumResultPhrase> phrases = conn.GetInteressingPhrasesFromUrl(actualContextSets[i].Value); results.AddRange(phrases); } else { List<SensiumResultPhrase> phrases = conn.GetInteressingPhrases(actualContextSets[i].Value); results.AddRange(phrases); } } //filter fillwords like Und here results = contextHelper_.FilterWordsWithoutInformation(results); double scoresum = 0; foreach(SensiumResultPhrase phrase in results) { scoresum += phrase.Score; } double mean = scoresum / results.Count; List<SensiumResultPhrase> normalized = new List<SensiumResultPhrase>(); foreach(SensiumResultPhrase ph in results) { //if(ph.Type == "url") //{ // //double highermean = mean + mean / 2; // //while(highermean >= 1) // //{ // // highermean = highermean - highermean / 4; // //} // //if (ph.Score > highermean) // //{ // normalized.Add(ph); // //} //} //else //{ if (ph.Score > mean) { normalized.Add(ph); } //} } //filter fillwords like Und here normalized = contextHelper_.FilterWordsWithoutInformation(normalized); return normalized; }
/// <summary> /// Initializes the view model meta data. /// <para /> /// This method only initializes the meta data once per view model type. If a type is already initialized, /// this method will immediately return. /// </summary> /// <param name="viewModelType">Type of the view model.</param> /// <returns>ViewModelMetadata.</returns> /// <exception cref="ArgumentNullException">The <paramref name="viewModelType" /> is <c>null</c>.</exception> private static ViewModelMetadata InitializeViewModelMetaData(Type viewModelType) { if (_metaData.ContainsKey(viewModelType)) { return _metaData[viewModelType]; } var properties = new List<PropertyInfo>(); var bindingFlags = BindingFlagsHelper.GetFinalBindingFlags(true, false, true); properties.AddRange(viewModelType.GetPropertiesEx(bindingFlags)); var modelObjectsInfo = new Dictionary<string, ModelInfo>(); var viewModelToModelMap = new Dictionary<string, ViewModelToModelMapping>(); var validationSummaries = new Dictionary<string, ValidationToViewModelAttribute>(); var modelNames = (from propertyInfo in properties where propertyInfo.IsDecoratedWithAttribute<ModelAttribute>() select propertyInfo.Name).ToList(); foreach (var propertyInfo in properties) { #region Model attributes var modelAttribute = propertyInfo.GetCustomAttributeEx(typeof(ModelAttribute), true) as ModelAttribute; if (modelAttribute != null) { modelObjectsInfo.Add(propertyInfo.Name, new ModelInfo(propertyInfo.Name, modelAttribute)); } #endregion #region ViewModelToModel attributes var viewModelToModelAttribute = propertyInfo.GetCustomAttributeEx(typeof(ViewModelToModelAttribute), true) as ViewModelToModelAttribute; if (viewModelToModelAttribute != null) { if (string.IsNullOrEmpty(viewModelToModelAttribute.Property)) { // Assume the property name in the model is the same as in the view model viewModelToModelAttribute.Property = propertyInfo.Name; } if (string.IsNullOrWhiteSpace(viewModelToModelAttribute.Model)) { Log.Debug("ViewToViewModel is missing the Model name, searching for the right model automatically"); if (modelNames.Count != 1) { throw Log.ErrorAndCreateException<InvalidOperationException>("It is only possible to automatically select the right model if there is 1 model. There are '{0}' models, so please specify the model name explicitly.", modelNames.Count); } viewModelToModelAttribute.Model = modelNames[0]; } if (!viewModelToModelMap.ContainsKey(propertyInfo.Name)) { viewModelToModelMap.Add(propertyInfo.Name, new ViewModelToModelMapping(propertyInfo.Name, viewModelToModelAttribute)); } } #endregion #region ValidationToViewModel attributes var validationToViewModelAttribute = propertyInfo.GetCustomAttributeEx(typeof(ValidationToViewModelAttribute), true) as ValidationToViewModelAttribute; if (validationToViewModelAttribute != null) { if (propertyInfo.PropertyType != typeof(IValidationSummary)) { throw Log.ErrorAndCreateException<InvalidOperationException>("A property decorated with the ValidationToViewModel attribute must be of type IValidationSummary, but '{0}' is not", propertyInfo.Name); } validationSummaries.Add(propertyInfo.Name, validationToViewModelAttribute); Log.Debug("Registered property '{0}' as validation summary", propertyInfo.Name); } #endregion } _metaData.Add(viewModelType, new ViewModelMetadata(viewModelType, modelObjectsInfo, viewModelToModelMap, validationSummaries)); return _metaData[viewModelType]; }
/// <summary> /// Adds the items to list. /// </summary> /// <param name="items">The items.</param> /// <param name="list">The list.</param> /// <returns> /// The list with added items. /// </returns> private static List<RedirectItem> AddItemsToList(IEnumerable<RedirectItem> items, List<RedirectItem> list) { if (items != null) { if (Configuration.CheckDuplicates) { foreach (var sectionItem in items) { if (!CheckDuplicates(sectionItem.Base, list)) { list.Add(sectionItem); } } } else { list.AddRange(items); } } return list; }
/// <summary> /// Determines the interesting view properties. /// </summary> /// <returns>A list of names with view properties to subscribe to.</returns> private List<string> DetermineInterestingViewProperties() { var targetViewType = TargetViewType; var finalProperties = new List<string>(); if ((_viewPropertySelector == null) || (_viewPropertySelector.MustSubscribeToAllViewProperties(targetViewType))) { var viewProperties = TargetView.GetProperties(); finalProperties.AddRange(viewProperties); } else { var propertiesToSubscribe = new HashSet<string>(_viewPropertySelector.GetViewPropertiesToSubscribeTo(targetViewType)); if (!propertiesToSubscribe.Contains("DataContext")) { propertiesToSubscribe.Add("DataContext"); } foreach (var propertyToSubscribe in propertiesToSubscribe) { if (propertiesToSubscribe.Contains(propertyToSubscribe)) { finalProperties.Add(propertyToSubscribe); } } } return finalProperties; }
public string SearchForIssues(string[] tags) { if (tags.Length <= 0) { return "There are no tags provided"; } var issues = new List<Issue>(); foreach (var tag in tags) { issues.AddRange(this.Data.IssuesByTag[tag]); } if (!issues.Any()) { return "There are no issues matching the tags provided"; } var distinctIssues = issues.Distinct(); if (!distinctIssues.Any()) { return "No issues"; } var orderedDistinctIssues = distinctIssues .OrderByDescending(i => i.Priority) .ThenBy(i => i.Title) .Select(i => i.ToString()); return string.Join(Environment.NewLine, orderedDistinctIssues); }
static async void Run() { //var extractPath = ExtractingFromZip(); var xmlPath = @"E:\TWs\Database-2015-Team-Flerovium-\ImportingReports\ImportingReports\XmlImportFile\Books.xml"; XDocument doc = XDocument.Load(xmlPath); var zipFilePath = @"E:\TWs\Database-2015-Team-Flerovium-\ImportingReports\ImportingReports\ZipFile\Sales-Reports.zip"; var extractedFolderPath = ExtractZip(zipFilePath); var dateNamedFolders = GetDateNamedFolders(extractedFolderPath); var allSales = new List<Sale>(); foreach (var folder in dateNamedFolders) { foreach (var file in folder.GetFiles()) { var salesForFile = ExtractExcelData(file.FullName, file.Name, folder.Name); allSales.AddRange(salesForFile); } } allSales.ForEach(Console.WriteLine); var root = doc.Root; var books = root.Elements().AsQueryable().Select(BookMongo.FromXElement).ToList(); var client = new MongoClient("mongodb://localhost"); var db = client.GetDatabase("books-db"); var booksCollection = db.GetCollection<BsonDocument>("books"); var bsonBooks = books.AsQueryable().Select(BookMongo.ToBsonDocument); await booksCollection.InsertManyAsync(bsonBooks); var dbContext = new BooksDbContext(); var mongoBooks = await booksCollection.Find(new BsonDocument()).ToListAsync(); var bookModels = mongoBooks.Select(bookBson => { var authorIdToString = bookBson["AuthorId"].ToString(); var author = dbContext.Authors.FirstOrDefault(a => a.AuthorId.ToString() == authorIdToString); if (author == null) { author = new Author { AuthorId = int.Parse(bookBson["AuthorId"].ToString()), AuthorName = bookBson["Author"].ToString() }; dbContext.Authors.AddOrUpdate(a => a.AuthorName, author); dbContext.SaveChanges(); } var publisherIdToString = bookBson["PublisherId"].ToString(); var publisher = dbContext.BookPublishers.FirstOrDefault( b => b.BookPublisherId.ToString() == publisherIdToString); if (publisher == null) { publisher = new BookPublisher { BookPublisherId = int.Parse(bookBson["PublisherId"].ToString()), BookPublisherName = bookBson["Publisher"].ToString() }; dbContext.BookPublishers.AddOrUpdate(p => p.BookPublisherName, publisher); dbContext.SaveChanges(); } var book = new Book { BookId = int.Parse(bookBson["BookId"].ToString()), AuthorId = int.Parse(bookBson["AuthorId"].ToString()), BookPublisherId = int.Parse(bookBson["PublisherId"].ToString()), Title = bookBson["Title"].ToString(), BasePrice = decimal.Parse(bookBson["BasePrice"].ToString()), Author = author, Publisher = publisher }; return book; }); Console.WriteLine("--------------- {0} Saving Books", bookModels.Count()); dbContext.Books.AddOrUpdate(b => b.Title, bookModels.ToArray()); dbContext.SaveChanges(); Console.WriteLine("---------------Books saved!"); allSales.ForEach(sale => dbContext.Sales.Add(sale)); dbContext.SaveChanges(); Console.WriteLine("HERE"); var products = MySQLReadProductsTable(); WriteExcelSheet(products, "Products.xlsx"); var towns = MySQLReadTownsTable(); WriteExcelSheet(towns, "Towns.xlsx"); var couriers = MySQLReadCouriersTable(); WriteExcelSheet(couriers, "Couriers.xlsx"); Console.ReadKey(); //booksCollection.InsertManyAsync(bsonBooks); //Console.ReadKey(); /* In order to create a PDF report, use this: var db = new dbEntities(); // or whatever we use var testPdf = new PDFReporter(db); // creating an instance var data = db.Sales.ToList(); // or something more precise testPdf.GeneratePdfSalesReport("Sales", data); */ }
private void MainWindow_OnActivated(object sender, EventArgs e) { if (FirstTimeActivated) { FirstTimeActivated = false; //Try to login with the saved credentials. if (!Auth.Login(Config.Instance.Username, Config.Instance.Password).Item1) { ShowLoginDialog(); } else { OnLogin(Config.Instance.Username); } var allAssemblies = new List<LeagueSharpAssembly>(); foreach (var profile in Config.Instance.Profiles) { allAssemblies.AddRange(profile.InstalledAssemblies); } allAssemblies = allAssemblies.Distinct().ToList(); GitUpdater.ClearUnusedRepos(allAssemblies); PrepareAssemblies(allAssemblies, Config.Instance.FirstRun || Config.Instance.UpdateOnLoad, true, true); Remoting.Init(); } var text = Clipboard.GetText(); if (text.StartsWith(LSUriScheme.FullName)) { Clipboard.SetText(""); LSUriScheme.HandleUrl(text, this); } }
/// <summary> /// Adds the section descendants. /// </summary> /// <param name="targetItemId">The target item id.</param> /// <param name="baseSectionUrl">The base section URL.</param> /// <param name="targetSectionUrl">The target section URL.</param> /// <param name="itemId">The item id.</param> /// <param name="redirectCode">The redirect code.</param> /// <param name="multisites">The multisites.</param> /// <param name="useOnDefaultSite">if set to <c>true</c> [use on default site].</param> /// <returns> /// list of items redirects /// </returns> private static IEnumerable<RedirectItem> AddSectionDescendants( string targetItemId, string baseSectionUrl, string targetSectionUrl, ID itemId, int redirectCode, string multisites, bool useOnDefaultSite) { var sectionItem = Factory.GetDatabase(Configuration.Database).GetItem(targetItemId); if (sectionItem == null) { return null; } var list = new List<RedirectItem>(); if (CheckPresentation(sectionItem)) { var sectionRedirectItem = new RedirectItem { ItemId = itemId, Target = targetSectionUrl, Base = UrlNormalizer.CheckPageExtension(baseSectionUrl), RedirectCode = redirectCode, Multisites = multisites, UseOnDefault = useOnDefaultSite }; list.Add(sectionRedirectItem); } baseSectionUrl = UrlNormalizer.Normalize(baseSectionUrl); targetSectionUrl = UrlNormalizer.RemovePageExtension(targetSectionUrl); if (targetSectionUrl == "/") { list.AddRange( from item in sectionItem.Axes.GetDescendants().Where(CheckPresentation) select UrlNormalizer.GetItemUrl(item) into targetUrl let baseUrl = string.Format("{0}{1}", baseSectionUrl, targetUrl) select new RedirectItem { ItemId = itemId, Target = targetUrl, Base = baseUrl, External = false, RedirectCode = redirectCode, Multisites = multisites, UseOnDefault = useOnDefaultSite }); } else { list.AddRange( from item in sectionItem.Axes.GetDescendants().Where(CheckPresentation) select UrlNormalizer.GetItemUrl(item) into targetUrl let baseUrl = targetUrl.Replace(targetSectionUrl, baseSectionUrl) select new RedirectItem { ItemId = itemId, Target = targetUrl, Base = baseUrl, External = false, RedirectCode = redirectCode, Multisites = multisites, UseOnDefault = useOnDefaultSite }); } return list; }
private IEnumerable<TypeSpecification> OnGetImplementations(TypeSpecification typeSpecification) { Argument.IsNotNull(() => typeSpecification); var result = new List<TypeSpecification>(); foreach (var node in Assemblies) { result.AddRange(node.GetImplementations(typeSpecification.FullName).Cast<TypeSpecification>()); } return result; }
//jlg bad logic private void UpdateAdCacheFromPaper(Newspaper entity) { List<Advertisement> deletedAds = new List<Advertisement>(); foreach (var ad in entity.Advertisements) { switch (entity.DbStatus) { case DbModificationState.Unchanged: case DbModificationState.Added: case DbModificationState.Modified: if(!_advertisementCache.ContainsKey(ad.UKey)) _advertisementCache.Add(ad.UKey,ad); deletedAds.AddRange(entity.Advertisements.Where(a=>a.DbStatus==DbModificationState.Deleted)); break; case DbModificationState.Deleted: foreach (var cacheAd in _advertisementCache.Values.ToList()) { cacheAd.Newspapers.Remove(entity); } break; } } deletedAds.ForEach(a=>_advertisementCache.Remove(a.UKey)); }
/// <summary> /// Determines the interesting dependency properties. /// </summary> /// <returns>A list of names with dependency properties to subscribe to.</returns> private List<DependencyPropertyInfo> DetermineInterestingDependencyProperties() { var targetControlType = TargetControlType; return _dependencyPropertiesToSubscribe.GetFromCacheOrFetch(targetControlType, () => { var controlDependencyProperties = TargetControl.GetDependencyProperties(); var dependencyProperties = new List<DependencyPropertyInfo>(); if ((_dependencyPropertySelector == null) || (_dependencyPropertySelector.MustSubscribeToAllDependencyProperties(targetControlType))) { dependencyProperties.AddRange(controlDependencyProperties); } else { var dependencyPropertiesToSubscribe = _dependencyPropertySelector.GetDependencyPropertiesToSubscribeTo(targetControlType); if (!dependencyPropertiesToSubscribe.Contains("DataContext")) { dependencyPropertiesToSubscribe.Add("DataContext"); } foreach (var gatheredDependencyProperty in controlDependencyProperties) { if (dependencyPropertiesToSubscribe.Contains(gatheredDependencyProperty.PropertyName)) { dependencyProperties.Add(gatheredDependencyProperty); } } } return dependencyProperties; }); }
public override void Handle() { string queryLayers = this.context.Request.Params["LAYERS"]; string styles = this.context.Request.Params["STYLES"]; string crs = this.context.Request.Params["CRS"]; string queryBBOX = this.context.Request.Params["BBOX"]; string queryWidth = this.context.Request.Params["WIDTH"]; string queryHeight = this.context.Request.Params["HEIGHT"]; string format = this.context.Request.Params["FORMAT"]; string transparent = this.context.Request.Params["TRANSPARENT"]; string background = this.context.Request.Params["BGCOLOR"]; if (queryLayers == null) { WmsException.ThrowWmsException("Required parameter LAYERS not specified"); return; } if (styles == null) { WmsException.ThrowWmsException("Required parameter STYLES not specified"); return; } if (crs == null) { WmsException.ThrowWmsException("Required parameter CRS not specified"); return; } if (!this.Check(String.Format("EPSG:{0}", this.map.Layers[0].SRID), crs)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidCRS, "CRS not supported"); return; } if (queryBBOX == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter BBOX not specified"); return; } if (queryWidth == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter WIDTH not specified"); return; } if (queryHeight == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter HEIGHT not specified"); return; } if (format == null) { WmsException.ThrowWmsException("Required parameter FORMAT not specified"); return; } //Set background color of map if (!this.Check("TRUE", transparent)) { if (background != null) { try { this.map.BackColor = ColorTranslator.FromHtml(background); } catch { WmsException.ThrowWmsException("Invalid parameter BGCOLOR"); return; } } else this.map.BackColor = Color.White; } else this.map.BackColor = Color.Transparent; //Parse map size int width; if (!Int32.TryParse(queryWidth, out width)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter WIDTH"); return; } if (this.description.MaxWidth > 0 && width > this.description.MaxWidth) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter WIDTH too large"); return; } int height; if (!Int32.TryParse(queryHeight, out height)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter HEIGHT"); return; } if (this.description.MaxHeight > 0 && height > this.description.MaxHeight) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter HEIGHT too large"); return; } this.map.Size = new Size(width, height); BoundingBox bbox = this.ParseBBOX(queryBBOX); if (bbox == null) { WmsException.ThrowWmsException("Invalid parameter BBOX"); return; } this.map.PixelAspectRatio = (width / (double)height) / (bbox.Width / bbox.Height); this.map.Center = bbox.GetCentroid(); this.map.Zoom = bbox.Width; //Set layers on/off if (!String.IsNullOrEmpty(queryLayers)) //If LAYERS is empty, use default layer on/off settings { string[] layers = queryLayers.Split(new[] { ',' }); if (this.description.LayerLimit > 0) { if (layers.Length == 0 && this.map.Layers.Count > this.description.LayerLimit || layers.Length > this.description.LayerLimit) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Too many layers requested"); return; } } foreach (ILayer layer in this.map.Layers) layer.Enabled = false; foreach (string layer in layers) { ILayer lay = this.map.GetLayerByName(layer); if (lay == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.LayerNotDefined, String.Format("Unknown layer '{0}'", layer)); return; } lay.Enabled = true; } } bool json = this.Check("text/json", format); if (json) { List<GeoJSON> items = new List<GeoJSON>(); //Only queryable data! IQueryable<ICanQueryLayer> collection = this.map.Layers.AsQueryable() .OfType<ICanQueryLayer>().Where(l => l.Enabled && l.IsQueryEnabled); foreach (ICanQueryLayer layer in collection) { //Query for data FeatureDataSet ds = new FeatureDataSet(); layer.ExecuteIntersectionQuery(bbox, ds); IEnumerable<GeoJSON> data = GeoJSONHelper.GetData(ds); //Filter only visible items //double f = bbox.GetArea() / (width * height); //data = data.Where(i => //{ // Geometry g = i.Geometry; // BoundingBox p = g.GetBoundingBox(); // double area = p.GetArea(); // return area == 0 || area > f; //}); //Reproject geometries if needed IMathTransform transform = null; if (layer is VectorLayer) { ICoordinateTransformation transformation = (layer as VectorLayer).CoordinateTransformation; transform = transformation == null ? null : transformation.MathTransform; } if (transform != null) { data = data.Select(d => { Geometry converted = GeometryTransform.TransformGeometry(d.Geometry, transform); d.SetGeometry(converted); return d; }); } items.AddRange(data); } StringWriter writer = new StringWriter(); GeoJSONWriter.Write(items, writer); string buffer = writer.ToString(); this.context.Response.Clear(); this.context.Response.ContentType = "text/json"; this.context.Response.BufferOutput = true; this.context.Response.Write(buffer); this.context.Response.End(); } else { //Get the image format requested ImageCodecInfo imageEncoder = this.GetEncoderInfo(format); if (imageEncoder == null) { WmsException.ThrowWmsException("Invalid MimeType specified in FORMAT parameter"); return; } //Render map Image img = this.map.GetMap(); //Png can't stream directy. Going through a memorystream instead MemoryStream ms = new MemoryStream(); img.Save(ms, imageEncoder, null); img.Dispose(); byte[] buffer = ms.ToArray(); this.context.Response.Clear(); this.context.Response.ContentType = imageEncoder.MimeType; this.context.Response.BufferOutput = true; this.context.Response.BinaryWrite(buffer); this.context.Response.End(); } }
/// <summary> /// Returns the sequence of properties of the specified type. /// </summary> /// <param name="type">The type.</param> /// <param name="schema">The schema.</param> /// <param name="schemaSet">The schema set.</param> /// <param name="serializationManager">The serialization manager.</param> /// <param name="exportedTypes">The exported types.</param> /// <returns>Sequence containing all properties.</returns> private static XmlSchemaSequence GetPropertiesSequence(Type type, XmlSchema schema, XmlSchemaSet schemaSet, ISerializationManager serializationManager, HashSet<string> exportedTypes) { Argument.IsNotNull("type", type); Argument.IsNotNull("schema", schema); Argument.IsNotNull("schemaSet", schemaSet); var propertiesSequence = new XmlSchemaSequence(); if (type.IsModelBase()) { var members = new List<MemberMetadata>(); members.AddRange(from field in serializationManager.GetFieldsToSerialize(type) select field.Value); members.AddRange(from property in serializationManager.GetCatelPropertiesToSerialize(type) select property.Value); members.AddRange(from property in serializationManager.GetRegularPropertiesToSerialize(type) select property.Value); foreach (var member in members) { var propertySchemaElement = new XmlSchemaElement(); propertySchemaElement.Name = member.MemberName; var memberType = member.MemberType; propertySchemaElement.IsNillable = memberType.IsNullableType(); propertySchemaElement.MinOccurs = 0; var exporter = new XsdDataContractExporter(schemaSet); var alreadyExported = IsAlreadyExported(schemaSet, memberType, exporter, exportedTypes); if (!alreadyExported) { if (!exportedTypes.Contains(memberType.FullName)) { exportedTypes.Add(memberType.FullName); } try { if (exporter.CanExport(memberType)) { exporter.Export(memberType); } } catch (Exception) { // Ignore } } propertySchemaElement.SchemaType = exporter.GetSchemaType(memberType); propertySchemaElement.SchemaTypeName = exporter.GetSchemaTypeName(memberType); propertiesSequence.Items.Add(propertySchemaElement); } } return propertiesSequence; }
public string SearchForIssues(string[] tags) { if (tags.Length <= 0) { return Constants.NoTagsProvidedMsg; } var issues = new List<Issue>(); foreach (var t in tags) { issues.AddRange(this.Data.IssuesByTag[t]); } if (!issues.Any()) { return Constants.NoIssuesMatchingTheTagProvidedMsg; } var uniqueIssues = issues.Distinct(); if (!uniqueIssues.Any()) { return Constants.NoIssuesMsg; } return string.Join(Environment.NewLine, uniqueIssues.OrderByDescending(x => x.Priority).ThenBy(x => x.Title)); }
public static List<CatalogoExpensas.Pagos> registrarPagosAutomaticos(DateTime periodo, List<Pagos> pagos) { try { admEntities db = new admEntities(); //Si alguien paga por automatico, queda totalmente al dia. Sumar recargos cobrados de meses anteriores o si pago en 2 vto List<expensas> expensas = new List<expensas>(); List<Recargo> gastosExclusivos = new List<Recargo>(); List<recargos> recargos = new List<recargos>(); foreach (var p in pagos) { var exp = db.expensas.Where(x => x.nro_referencia == p.nroReferencia).OrderByDescending(x => x.fecha).First(); var uni = new unidad(); uni.dir_edificio = exp.dir_edificio; uni.id_unidad = exp.id_unidad; p.Edificio = uni.dir_edificio; p.Unidad = uni.id_unidad; p.Periodo = exp.fecha.Month + "/" + exp.fecha.Year; var expensasMismaUnidad = db.expensas.Where(x => x.dir_edificio == uni.dir_edificio && x.id_unidad == uni.id_unidad && x.pagado == 0).ToList(); var exclusivosMismaUnidad = CatalogoGastosExclusivos.getAllRecargos(uni); expensas.AddRange(expensasMismaUnidad); gastosExclusivos.AddRange(exclusivosMismaUnidad); } var expGrouped = expensas.GroupBy(x => new { x.dir_edificio, x.id_unidad }) .Select(x => new expensas { dir_edificio = x.Key.dir_edificio, id_unidad = x.Key.id_unidad }) .Cast<expensas>() .ToList(); foreach (expensas e in expensas) { e.pagado = 1; db.Entry(e).State = System.Data.EntityState.Modified; } foreach (expensas e in expGrouped) { recargos r = new recargos(); var uni = new unidad(); uni.dir_edificio = e.dir_edificio; uni.id_unidad = e.id_unidad; r.dir_edificio = e.dir_edificio; r.periodo = DateTime.Parse("1/" + DateTime.Now.Month + "/" + DateTime.Now.Year); var detalles = CatalogoDeudores.getDetalleDeudaUnidad(uni); r.importe = detalles.Sum(x => x.Recargo); var rExistente = recargos.Where(x => x.dir_edificio == r.dir_edificio && x.periodo == r.periodo).SingleOrDefault(); if (rExistente != null) rExistente.importe += r.importe; else recargos.Add(r); } db.SaveChanges(); foreach (var excl in gastosExclusivos) { switch (excl.Tipo) { case "Exclusivos": CatalogoGastosExclusivos.pagarRecargoExclusivo(excl.Edificio, excl.Unidad, excl.Concepto, excl.Fecha); break; case "Legales": CatalogoGastosExclusivos.pagarRecargoLegales(excl.Edificio, excl.Unidad, excl.Concepto, excl.Fecha); break; case "Varios": CatalogoGastosExclusivos.pagarRecargoVarios(excl.Edificio, excl.Unidad, excl.Concepto, excl.Fecha); break; } } CatalogoRecargos.addRecargos(recargos); return pagos; } catch (Exception e) { Logger.Log.write(e.InnerException == null ? e.Message : e.InnerException.Message); var str = ""; str = e.InnerException?.InnerException?.Message; Logger.Log.write("Otro error: " + str); throw e; } }