Beispiel #1
0
        public void IterateTest()
        {
            ContentList contentList = new ContentList();

            contentList.Add("0");
            contentList.Add("1");
            contentList.Add("2");
            int expectedItem = 0;

            foreach (string actualValue in contentList)
            {
                Assert.Equal(expectedItem++.ToString(), actualValue);
            }
        }
        // Update the ContentList list of files with all files and directories in the currently selected directory
        public void UpdateContentList()
        {
            if (SelectedDirectory != null)
            {
                FileFilter = string.Empty;
                ContentList.Clear();

                SelectedDirectory.UpdateFileList(ref _userMessage);
                SelectedDirectory.UpdateSubFolderList();

                foreach (UserDirectory folder in SelectedDirectory.Subfolders)
                {
                    ContentList.Add(folder);
                }

                foreach (UserFile file in SelectedDirectory.Files)
                {
                    //file.UpdateFileStatus();
                    ContentList.Add(file);
                    file.CheckFile(ref _userMessage);
                }

                SelectedDirectory.UpdatePerforceStatus();
                RaisePropertyChanged("UserMessage");
            }

            if (ContentList != null)
            {
                UserMessage = ContentList.Any(x => x.P4Success == false) ? P4ErrorMessage : UserMessage;
            }
        }
Beispiel #3
0
        private void SearchContent(string sPage, string sName, string sCategory)
        {
            ContentList.Clear();

            DataSet dsContsResult = callQuery.S_MA_CTS_SRCH_LIST(sPage, sName, sCategory);

            UdtContentItem udtResult;

            for (int i = 0; i < dsContsResult.Tables[0].Rows.Count; i++)
            {
                udtResult = new UdtContentItem();

                udtResult.ContentID      = dsContsResult.Tables[0].Rows[i]["CONS_ID"].ToString();
                udtResult.ContentTitle   = dsContsResult.Tables[0].Rows[i]["CONS_NM"].ToString();
                udtResult.ContentDesc    = dsContsResult.Tables[0].Rows[i]["CONS_DOC"].ToString();
                udtResult.CopyWriterName = dsContsResult.Tables[0].Rows[i]["COPY_NM"].ToString();
                udtResult.DownloadRate   = dsContsResult.Tables[0].Rows[i]["DOWN_RATE"].ToString();
                udtResult.Price          = dsContsResult.Tables[0].Rows[i]["CONS_PRICE"].ToString();
                udtResult.StarRate       = dsContsResult.Tables[0].Rows[i]["STAR_RATE"].ToString();
                System.Drawing.Image thumbnailImg = IMRUtils.TypeParser.ByteArrayToImage(Convert.FromBase64String(dsContsResult.Tables[0].Rows[i]["CONS_THUMB_PATH"].ToString()));
                udtResult.Thumbnail = StaticUtils.ImageToImageSource(thumbnailImg);

                ContentList.Add(udtResult);
            }
        }
        public void AddNewContent(string contentName)
        {
            var contentType = service.GetTypeOfContent(contentName);
            var newContent  = new ContentIconAndName(ContentIconAndName.GetContentTypeIcon(contentType),
                                                     contentName);

            ContentList.Add(newContent);
        }
        public void RefrechData(DbViewModel db)
        {
            ContentList.Clear();

            ContentList.Add(new AdditionalDbInfoViewModel("Trigger", db.Triggers.Cast <IAddtionalDbInfo>().ToList()));
            ContentList.Add(new AdditionalDbInfoViewModel("Index", db.Indexes.Cast <IAddtionalDbInfo>().ToList()));
            ContentList.Add(new AdditionalDbInfoViewModel("Domain", db.Domains.Cast <IAddtionalDbInfo>().ToList()));

            CurrentContent = ContentList;
        }
Beispiel #6
0
        public void WhenAddThenGettableTest()
        {
            const string expectedItem1 = "a.b.c.d";
            const string expectedItem2 = "e.f.g.h";

//            var substUtil = Substitute.For<IUtil>();
//            substUtil.WriteToFile(Arg.Any<string>(), Arg.Any<string>(), false).Returns(true);

            ContentList contentList = new ContentList();

            contentList.IsSubList = false;
            contentList.Name      = "testlist";
            contentList.Version   = "1";

            contentList.Add(expectedItem1);
            contentList.Add(expectedItem2);

            Assert.Equal(expectedItem1, contentList.Get(0));
            Assert.Equal(expectedItem2, contentList.Get(1));
        }
        public void AddContentToContentList(ContentType type, string name)
        {
            RemoveContentFromContentLists(name);
            var newContent = new ContentIconAndName(ContentIconAndName.GetContentTypeIcon(type), name);

            DisplayContentList.Add(newContent);
            ContentList.Add(newContent);
            SubContentManager.AddSubContentAndRemoveDuplicateContent(DisplayContentList, service,
                                                                     newContent);
            RaisePropertyChanged("ContentList");
        }
Beispiel #8
0
        public void SerializeTest()
        {
            const string addedItem1            = "a.b.c.d";
            const string addedItem2            = "e.f.g.h";
            const string expectedSerialization = @"{""IsSubList"":false,""Name"":""testlist"",""Version"":""1"",""_content"":[""a.b.c.d"",""e.f.g.h""]}";

//            var substUtil = Substitute.For<IUtil>();
//            substUtil.WriteToFile(Arg.Any<string>(), Arg.Any<string>(), false).Returns(true);

            ContentList contentList = new ContentList();

            contentList.IsSubList = false;
            contentList.Name      = "testlist";
            contentList.Version   = "1";

            contentList.Add(addedItem1);
            contentList.Add(addedItem2);
            string actualSerialization = contentList.Serialize();

            Assert.Equal(expectedSerialization, actualSerialization);
        }
Beispiel #9
0
        private void DoRequest()
        {
            Plugin.IsLoading = true;
            //var bagResult = Plugin.CreatePoiTypeResult("BAG", Colors.CornflowerBlue);

            var result = Plugin.CreatePoiTypeResult("MGRS", Colors.CornflowerBlue);
            result.Style.InnerTextColor = Colors.Black;
            Plugin.SearchService.PoITypes.Add(result);


            ThreadPool.QueueUserWorkItem(delegate
            {
                try
                {
                    string mgrsInput = Key;
                    var pois = new ContentList();

                    double[] latLonResult = csCommon.Converters.MgrsConversion.convertMgrsToLatLon(mgrsInput);
                    double lat = latLonResult[0];  
                    double lon = latLonResult[1];   

                    var p = new PoI
                    {
                        Service = Plugin.SearchService,
                        InnerText = "1",
                        Name = mgrsInput,
                        Position = new Position(lon, lat),
                    };

                    p.UpdateEffectiveStyle();
                    pois.Add(p);

                    Application.Current.Dispatcher.Invoke(
                        delegate
                        {
                            lock (Plugin.ServiceLock)
                            {
                                foreach (var q in pois) {
                                    Plugin.SearchService.PoIs.Add(q);
                                }
                            }
                            Plugin.IsLoading = false;
                        });

                }
                catch (Exception e)
                {
                    Logger.Log("MGRS search", "Error finding MGRS location", e.Message, Logger.Level.Error, true);
                    Plugin.IsLoading = false;
                }
            });
        }
Beispiel #10
0
        private void ReportOrphans(XElement container, XElement notebooks)
        {
            // orphaned backup folders...

            progress.SetMessage("Orphans...");
            progress.Increment();

            var knowns = notebooks.Elements(ns + "Notebook")
                         .Select(e => e.Attribute("name").Value)
                         .ToList();

            knowns.Add(Resx.AnalyzeCommand_OpenSections);
            knowns.Add(Resx.AnalyzeCommand_QuickNotes);

            var orphans = Directory.GetDirectories(backupPath)
                          .Select(d => Path.GetFileNameWithoutExtension(d))
                          .Except(knowns);

            container.Add(
                new Paragraph("Orphans").SetQuickStyle(heading2Index),
                new Paragraph(Resx.AnalyzeCommand_OrphanSummary)
                );

            if (!orphans.Any())
            {
                container.Add(
                    new Paragraph(string.Empty),
                    new Paragraph(Resx.AnalyzeCommand_NoOrphans),
                    new Paragraph(string.Empty)
                    );

                return;
            }

            var list = new ContentList(ns);

            container.Add(
                new Paragraph(ns,
                              new XElement(ns + "T", new XCData(string.Empty)),
                              list)
                );

            foreach (var orphan in orphans)
            {
                var dir  = new DirectoryInfo(Path.Combine(backupPath, orphan));
                var size = dir.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(f => f.Length);

                list.Add(new Bullet($"{orphan} ({size.ToBytes(1)})"));
            }

            container.Add(new Paragraph(string.Empty));
        }
Beispiel #11
0
 public Media(XmlElement element)
 {
     Title = Util.ChildValue(element, "title");
     Player = Util.ChildValue(element, "player");
     Link = Util.ChildValue(element, "link");
     Thumbnails = new ThumbnailList();
     foreach (XmlElement child in element.GetElementsByTagName("thumbnail"))
     {
         Thumbnails.Add(new Thumbnail(child));
     }
     Content = new ContentList();
     foreach (XmlElement child in element.GetElementsByTagName("content"))
     {
         Content.Add(new Content(child));
     }
 }
Beispiel #12
0
        public bool AddList(string key, string value)
        {
            if (ContentList == null)
            {
                ContentList = new ObservableDictionary <string, string>();
            }

            if (!string.IsNullOrEmpty(key) && !string.IsNullOrWhiteSpace(key) &&
                !string.IsNullOrEmpty(value) && !string.IsNullOrWhiteSpace(value) &&
                ContentList != null && !ContentList.ContainsKey(key))
            {
                ContentList.Add(key, value);
                return(true);
            }
            return(false);
        }
        // Searches all files and directories in the directory tree starting at the selected directory for any that match
        // the FileFilter string
        public void GetFilteredFilesFromSelected()
        {
            ContentList.Clear();

            List <UserFile> FilteredFileList = SelectedDirectory.GetFilteredFiles(FileFilter);

            UpdatePerforceStatus(FilteredFileList);
            foreach (UserFile file in SelectedDirectory.GetFilteredFiles(FileFilter))
            {
                file.UpdateFileStatus();
                ContentList.Add(file);
                file.CheckFile(ref _userMessage);
                RaisePropertyChanged("UserMessage");
            }

            if (ContentList != null)
            {
                UserMessage = ContentList.Any(x => x.P4Success == false) ? P4ErrorMessage : UserMessage;
            }
        }
Beispiel #14
0
        public void TestMethod1()
        {
            string assemblyPath = Assembly.GetExecutingAssembly().Location;
            string workDirPath  = Path.GetDirectoryName(assemblyPath);
            string dbPath       = Path.Combine(workDirPath, "testdb.sqlite");
            var    contentList  = new ContentList(dbPath);

            contentList.Clear();
            string testPath      = assemblyPath;
            var    testTimestamp = File.GetLastWriteTime(testPath).ToUnixTimestamp();

            contentList.Add(testPath, testTimestamp, removed: false);
            Assert.IsTrue(contentList.ContainsKey(testPath));
            Assert.AreEqual(1, contentList.Count);
            Assert.AreEqual(contentList.Keys.First(), testPath);
            Assert.IsTrue(contentList.TryGetValue(testPath, out int storedTimestamp, out bool removed));
            Assert.AreEqual(testTimestamp, storedTimestamp);
            contentList.Remove(testPath);
            Assert.AreEqual(0, contentList.Count);
            contentList.Dispose();
            File.Delete(dbPath);
        }
Beispiel #15
0
        private void DoRequest()
        {
            Plugin.IsLoading = true;
            var bagResult = Plugin.CreatePoiTypeResult("BAG", Colors.CornflowerBlue);
            bagResult.Style.InnerTextColor = Colors.Black;
            bagResult.AddMetaInfo("Adres", "Adres");
            bagResult.AddMetaInfo("Postcode", "Postcode");
            bagResult.AddMetaInfo("Woonplaats", "Woonplaats");
            bagResult.AddMetaInfo("Gemeente", "Gemeente");
            bagResult.AddMetaInfo("Provincie", "Provincie");
            Plugin.SearchService.PoITypes.Add(bagResult);

            ThreadPool.QueueUserWorkItem(delegate
            {
                try
                {
                    string cmdString;
                    if (ZipCodeAndHouseNumberRegex.IsMatch(Key))
                    {
                        // Search for a zip code
                        var ms = ZipCodeAndHouseNumberRegex.Match(Key);

                        var zipNumbers  = ms.Groups["zipNumber"]       .Value.Trim();
                        var zipLetters  = ms.Groups["zipLetter"]       .Value.Trim().ToUpper();
                        var houseNumber = ms.Groups["houseNumberStart"].Value.Trim();

                        if (string.IsNullOrEmpty(houseNumber)) houseNumber = ms.Groups["houseNumberEnd"].Value.Trim();
                        cmdString = string.IsNullOrEmpty(houseNumber)
                            ? string.Format(ZipCodeLookupCommand,          zipNumbers, zipLetters)
                            : string.Format(ZipCodeAndNumberLookupCommand, zipNumbers, zipLetters, houseNumber);
                    }
                    else
                    {
                        // Search for a generic address
                        var input = substitutions.Keys.Aggregate(Key, (current, key) => current.Replace(key, substitutions[key]));
                        var keywords = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        cmdString = string.Format(AddresLookupCommand, string.Join("&", keywords));
                    }

                    var pois = new ContentList();
                    using (var conn = new NpgsqlConnection(ConnectionString))
                    {
                        conn.Open();

                        using (var command = new NpgsqlCommand(cmdString, conn))
                        {
                            using (var dr = command.ExecuteReader())
                            {
                                var count = 0;
                                while (dr.Read())
                                {
                                    count++;

                                    var position = ConvertPointZToPosition(dr.GetString(dr.GetOrdinal("location")));

                                    var p = new PoI
                                    {
                                        Service = Plugin.SearchService,
                                        InnerText = count.ToString(CultureInfo.InvariantCulture),
                                        PoiTypeId = bagResult.ContentId,
                                        PoiType = bagResult,
                                        Position = position
                                    };
                                    AddAddress(p, dr);
                                    p.UpdateEffectiveStyle();
                                    pois.Add(p);
                                }
                            }
                        }
                    }

                    Application.Current.Dispatcher.Invoke(
                        delegate
                        {
                            lock (Plugin.ServiceLock)
                            {
                                pois.ForEach(p => Plugin.SearchService.PoIs.Add(p));
                            }
                            Plugin.IsLoading = false;
                        });
                }
                catch (NpgsqlException e)
                {
                    Logger.Log("BAG Geocoding", "Error finding location", e.Message, Logger.Level.Error, true);
                    Plugin.IsLoading = false;
                }
            });
        }
Beispiel #16
0
 public void Add(string content)
 {
     ContentList.Add(content);
 }
 public void LoadRaw(string rawContent)
 {
     ContentList.Add(rawContent);
 }
        public async void openFileExplorerBtn_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List;
            picker.FileTypeFilter.Add(".xml");
            picker.FileTypeFilter.Add(".csv");
            picker.FileTypeFilter.Add(".json");
            picker.FileTypeFilter.Add(".txt");

            StorageFile file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                if (file.FileType == ".txt")
                {
                    string text = await Windows.Storage.FileIO.ReadTextAsync(file);

                    try
                    {
                        contentList.Add(new Content($"{text}"));
                    }
                    catch { }
                }
                else if (file.FileType == ".csv")
                {
                    string text = await Windows.Storage.FileIO.ReadTextAsync(file);

                    try
                    {
                        contentList.Add(new Content($"{text}"));
                    }
                    catch { }
                }

                else if (file.FileType == ".xml")
                {
                    string text = await Windows.Storage.FileIO.ReadTextAsync(file);

                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(text);

                    foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
                    {
                        try
                        {
                            foreach (XmlNode child in node.ChildNodes)
                            {
                                contentList.Add(new Content(node.InnerText));
                            }
                        }
                        catch { }
                    }
                }
                else if (file.FileType == ".json")
                {
                    string text = await Windows.Storage.FileIO.ReadTextAsync(file);

                    var obj = JsonConvert.DeserializeObject <dynamic>(text);
                    try
                    {
                        contentList.Add(new Content($"My Name is {obj.Name}, I am: {obj.Age} years old and live in {obj.City}"));
                    }
                    catch { }
                }
                else
                {
                    this.textblock.Text = "Operation cancelled.";
                }
            }
        }
        private async void openFileExplorerBtn_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List;
            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            picker.FileTypeFilter.Add(".xml");
            picker.FileTypeFilter.Add(".csv");
            picker.FileTypeFilter.Add(".json");
            picker.FileTypeFilter.Add(".txt");

            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();



            if (file != null)
            {
                if (file.ContentType == "application/vnd.ms-excel")
                {
                    string text = await Windows.Storage.FileIO.ReadTextAsync(file);


                    try
                    {
                        contentList.Add(new Content($"Texten i filen är följande: {text}"));
                    }
                    catch { }
                }

                else if (file.ContentType == "text/xml")
                {
                    string text = await Windows.Storage.FileIO.ReadTextAsync(file);

                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(text);


                    foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
                    {
                        string textoutput = node.InnerText;
                        try
                        {
                            contentList.Add(new Content($"{textoutput}"));
                        }
                        catch { }
                    }
                }

                else if (file.ContentType == "application/json")
                {
                    var path = file.Path;

                    string text = await Windows.Storage.FileIO.ReadTextAsync(file);

                    var obj = JsonConvert.DeserializeObject <dynamic>(text);

                    try
                    {
                        contentList.Add(new Content($"Texten i filen är följande: {obj.message}"));
                    }
                    catch { }
                }
            }
            else
            {
                this.textblock.Text = "Operation cancelled.";
            }
        }
Beispiel #20
0
        public static void Merge(PoiService mainDataService, string mainKey, PoiService secondaryDataService,
            string secKey,
            bool includeSecondaryPois,
            bool excludeNonExistentSecondaryPois,
            bool includeSecondaryColumns,
            bool overwriteDuplicateLabels, bool stopOnFirstHit, bool includeMetaData, FileLocation destination = null,
            TextBox txtMergeDebugOutput = null) {
            if (txtMergeDebugOutput != null)
                txtMergeDebugOutput.Text = "Merging files on [" + mainKey + " = " + secKey + "]";

            // Determine whether to use well-known text.
            var mainPoiType = mainDataService.PoITypes.FirstOrDefault();
            if (mainPoiType == null) {
                mainPoiType                = new PoI {
                    Name                   = "Default",
                    ContentId              = "Default",
                    Service                = mainDataService,
                    Style                  = new PoIStyle {
                        Name               = "default",
                        FillColor          = Colors.Transparent,
                        StrokeColor        = Color.FromArgb(255, 128, 128, 128),
                        CallOutOrientation = CallOutOrientation.Right,
                        FillOpacity        = 0.3,
                        TitleMode          = TitleModes.Bottom,
                        NameLabel          = "Name",
                        DrawingMode        = DrawingModes.Image,
                        StrokeWidth        = 2,
                        IconWidth          = 24,
                        IconHeight         = 24,
                        Icon               = "images/missing.png",
                        CallOutFillColor   = Colors.White,
                        CallOutForeground  = Colors.Black,
                        TapMode            = TapMode.CallOut
                    },
                    Id                     = Guid.NewGuid(),
                    DrawingMode            = DrawingModes.Image,
                    MetaInfo               = new List<MetaInfo>()
                };
                mainDataService.PoITypes.Add(mainPoiType);
            }

            if (mainPoiType != null && string.IsNullOrEmpty(mainPoiType.ContentId)) mainPoiType.ContentId = "Default";
            BaseContent secondaryPoiType = null;
            if (secondaryDataService.PoITypes != null && secondaryDataService.PoITypes.Any()) {
                secondaryPoiType = secondaryDataService.PoITypes.FirstOrDefault();
            }
            ;
            bool useWKT = mainPoiType != null && mainPoiType.Style != null && mainPoiType.Style.Name == "WKT";
            useWKT = (useWKT || secondaryPoiType != null && secondaryPoiType.Style != null) &&
                     secondaryPoiType.Style.Name == "WKT" && includeSecondaryColumns;
            if (useWKT) {
                if (mainPoiType != null) {
                    mainPoiType.ContentId = "WKT"; // We directly set the main PoI's "PoiId" to WKT.                    
                }
                mainDataService.StaticService = true; // Make sure we save the file as static.
                if (txtMergeDebugOutput != null)
                    txtMergeDebugOutput.AppendText(
                        "\nOne of the files uses well-known text; the output will be a static layer.");
            }

            // Merge the meta info. 
            if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\nMerging meta info.");
            if (secondaryPoiType != null && secondaryPoiType.MetaInfo.Count == 0) {
                //if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\nSecondary file has no meta info; nothing to merge.");
            }
            if (secondaryPoiType != null && includeSecondaryColumns)
                foreach (MetaInfo secMetaInfo in secondaryPoiType.MetaInfo) {
                    string secMetaInfoLabel = secMetaInfo.Label;
                    bool doAdd = true;
                    if (secMetaInfoLabel == secKey) {
                        //if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\nLabel " + secMetaInfo.Label + " is the one we merge on, so we skip it.");
                        doAdd = false;
                    }
                    if (doAdd) {
                        if (mainPoiType != null) {
                            if (mainPoiType.MetaInfo.Any(mainMetaInfo => mainMetaInfo.Label == secMetaInfoLabel)) {
                                doAdd = false; // label already there.
                            }
                        }
                    }
                    if (!doAdd) continue;
                    if (mainPoiType != null)
                        mainPoiType.MetaInfo.Add(secMetaInfo);
                    //if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\nInserted meta-info from secondary file into main file: " + secMetaInfo.Label + ".");
                }

            // Merge the Style info. If the right file has WKT, set the drawing mode to MultiPolygon.
            // TODO For now we completely ignore some important aspects of poitypes:
            // 1. Multiple PoITypes.
            // 2. Different PoiId attributes.
            if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\nMerging styles.");
            if ((secondaryPoiType != null && secondaryPoiType.Style != null && (mainPoiType.Style == null))) {
                // We need to overwrite, or the main does not have something yet.                
                mainPoiType.Style = secondaryPoiType.Style;
                //if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\nInserted style from secondary file into main file.");
            }
            else {
                //if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\nMain file already has a style definition.");
            }
            if (useWKT) {
                mainPoiType.Style.DrawingMode = DrawingModes.MultiPolygon;
//                if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText(
//                    "\nEnsuring main file uses drawing mode 'multi polygon' given the fact that well-known text is used.");
            }

            // Remember which PoIs were found in the main as well as secondary file.
            HashSet<BaseContent> unvisitedMainPois = new HashSet<BaseContent>();
            foreach (var poI in mainDataService.PoIs) {
                unvisitedMainPois.Add(poI);
            }

            // Merge data.
            if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\n\nMerging data.");
            foreach (var secPoi in secondaryDataService.PoIs) {
                if (!secPoi.Labels.ContainsKey(secKey)) {
//                    if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\n" + secPoi.Id + " does not have label " + secKey +
//                                                   " and will be skipped.");
                    continue;
                }
                var mainPoiFound = false;
                //var mainPoi = mainDataService.PoIs.FirstOrDefault(p => p.Labels.ContainsKey(mainKey) 
                //    && string.Equals(p.Labels[mainKey], secPoi.Labels[secKey], StringComparison.InvariantCultureIgnoreCase));
                foreach (var mainPoi in mainDataService.PoIs.Where(mainPoi =>
                    mainPoi.Labels.ContainsKey(mainKey)
                    &&
                    string.Equals(mainPoi.Labels[mainKey], secPoi.Labels[secKey],
                        StringComparison.InvariantCultureIgnoreCase)))
                    if (mainPoi != null) {
                        mainPoiFound = true;
                        if (mainPoi.PoiType == null) {
                            mainPoi.PoiType = mainPoiType;
                            mainPoi.ContentId = mainPoiType.ContentId;
                        }
                        unvisitedMainPois.Remove(mainPoi); // We visited this PoI! :)

                        if (!includeSecondaryColumns)
                            continue; // Do not copy information from the secondary to the first.
                        //if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\nAdding new data to " + mainPoi.Labels[mainKey] + ".");
                        //GetShortFriendlyName(mainPoi.Name) + "." + mainKey + " = " + GetShortFriendlyName(secPoi.Name) + "." + secKey + "] = " + );

                        // Merge the labels part.
                        if (overwriteDuplicateLabels) {
                            //if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\nCopying label/values with overwrite: ");
                            foreach (var label in secPoi.Labels) {
                                if (label.Key != secKey) {
                                    //if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\n->" + label.Key + "=" + label.Value + ", ");
                                    mainPoi.Labels[label.Key] = label.Value;
                                }
                            }
                        }
                        else {
                            //if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\nCopying label/values without overwrite: ");
                            foreach (var label in secPoi.Labels.Where(l => l.Key != secKey)) {
                                string value;
                                if (mainPoi.Labels.TryGetValue(label.Key, out value)) {
                                    //if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\n->" + label.Key + " skipped (value already set to " + value + "), ");
                                    continue;
                                }
                                //if (label.Key == secKey)
                                //{
                                //    //if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\n->" + label.Key + " is the label on which we merge; skipped (value " + mainPoi.Labels[mainKey] + "), ");
                                //    continue;
                                //}
                                //if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\n->Setting " + label.Key + " to " + label.Value);
                                mainPoi.Labels[label.Key] = label.Value;
                            }
                        }

                        // Also merge WKT information there may be.
                        if (useWKT) {
                            mainPoi.PoiTypeId = "WKT";
                        }
                        if (!string.IsNullOrWhiteSpace(secPoi.WktText)) {
                            if (overwriteDuplicateLabels || string.IsNullOrWhiteSpace(mainPoi.WktText)) {
                                //if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\nAlso merged well-known text elements.");
                                mainPoi.WktText = secPoi.WktText;
                            }
                        }

                        // Stop if needed.
                        if (!stopOnFirstHit) continue;
                        if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\nStopping on first hit!");
                        break;

                        // And that's it.
                        //if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\n");
                    }

                if (mainPoiFound) continue;
                if (includeSecondaryPois) {
                    var copyPoI = new PoI();
                    copyPoI.FromXml(secPoi.ToXml());
                    if (useWKT) {
                        copyPoI.PoiTypeId = "WKT";
                    }
                    else {
                        copyPoI.PoiType = mainPoiType;
                        copyPoI.PoiTypeId = mainPoiType.PoiId;
                    }
                    copyPoI.Labels[mainKey] = copyPoI.Labels[secKey]; // Rename the merge label.
                    copyPoI.Labels.Remove(secKey);
                    mainDataService.PoIs.Add(copyPoI);
                    if (txtMergeDebugOutput != null)
                        txtMergeDebugOutput.AppendText("\nMain file does not have PoI with label " + mainKey +
                                                       " set to " + secPoi.Labels[secKey] +
                                                       ", including PoI from secondary file.");
                }
                else {
                    if (txtMergeDebugOutput != null)
                        txtMergeDebugOutput.AppendText("\nMain file does not have PoI with label " + mainKey +
                                                       " set to " + secPoi.Labels[secKey] +
                                                       " and will be skipped.");
                }
            }

            // Report on unvisited PoIs in main file.
            // Remove any PoIs in the main file that are not in the secondary file (if the user selected this option).
            if (txtMergeDebugOutput != null) {
                if (unvisitedMainPois.Any()) {
                    if (txtMergeDebugOutput != null)
                        txtMergeDebugOutput.AppendText(
                            "\nSome PoIs in the main file were not matched with a PoI in the secondary file.");
                    if (excludeNonExistentSecondaryPois && txtMergeDebugOutput != null)
                        txtMergeDebugOutput.AppendText(" These PoIs will be removed from the main file.");
                }
                foreach (BaseContent unvisitedMainPoi in unvisitedMainPois) {
                    if (txtMergeDebugOutput != null) {
                        string unvisitedMainPoiValue;
                        bool found = unvisitedMainPoi.Labels.TryGetValue(mainKey, out unvisitedMainPoiValue);
                        if (!found) {
                            unvisitedMainPoiValue = "UNDEFINED";
                        }
                        txtMergeDebugOutput.AppendText("\n" + unvisitedMainPoi + ", " + mainKey + " = " +
                                                       unvisitedMainPoiValue + ".");
                    }
                }
                if (excludeNonExistentSecondaryPois) {
                    // Annoyingly, calling "remove" on a ContentList throws an exception.
                    // Therefore, we construct a new list of PoIs that should be kept, instead of removing the PoIs we should remove.
                    ContentList newMainPoIs = new ContentList();
                    foreach (BaseContent poI in mainDataService.PoIs.Where(poI => !unvisitedMainPois.Contains(poI))) {
                        newMainPoIs.Add(poI);
                    }
                    mainDataService.PoIs = newMainPoIs;
                }
            }

            // We are done.
            if (txtMergeDebugOutput != null) txtMergeDebugOutput.AppendText("\nMerge completed!");

            if (destination == null) {
                mainDataService.SaveXml();
            }
            else {
                PoiServiceExporters.Instance.Export(mainDataService, destination, includeMetaData);
            }
        }
Beispiel #21
0
        public static ContentList Query(Query query, string[] groups, string[] permissions)
        {
            if (groups != null && groups.Length > 0 && permissions != null && permissions.Length > 0)
            {
                foreach (string permission in permissions)
                {
                    BooleanClause bc = new BooleanClause(true, false);
                    foreach (string role in groups)
                    {
                        bc.AddClause(
                            new TermClause(
                                string.Format("GroupWith{0}Permissions", permission),
                                role,
                                false,
                                false)
                          );
                    }
                    query.Add(bc);
                }
            }

            if (query.OrderBy == null) query.OrderBy = "PublishDate DESC";
            if (query.DefaultField == null) query.DefaultField = "Text";

            ContentList results = new ContentList();
            try
            {

                IndexDocument[] docs = Engine.Search(query);
                Dictionary<Guid, bool> usedResults = new Dictionary<Guid, bool>(docs.Length);

                results.StartIndex = query.StartResultIndex;
                results.EndIndex = query.EndResultIndex;
                results.TotalResults = query.TotalResults;

                for (int i = 0; i < docs.Length; i++)
                {
                    Guid id = new Guid(docs[i].Get("ActiveObjectsID"));
                    if (!usedResults.ContainsKey(id))
                    {
                        usedResults.Add(id, true);
                        results.Add(new Content(docs[i]));
                    }
                    else
                    {
                        LogDuplicate(id, docs[i].Get("Title"));
                    }
                }
                usedResults.Clear();
            }
            catch { }

            return results;
        }
 public void LoadFromFile(string filePath)
 {
     ContentList.Add(File.ReadAllText(filePath));
 }
Beispiel #23
0
 private static ContentList ClonePoiTypes(PoiService source, string shapeIdLabel = null)
 {
     var clonedPoiTypes = new ContentList();
     // Add all other PoI types.
     foreach (var baseContent in source.PoITypes)
     {
         var clone = new PoI(); // Important that this is a PoI! Otherwise we have a casting problem elsewhere.
         clone.FromXml(baseContent.ToXml()); // Deep clone.
         // Add a MetaInfo for the counter.
         if (clone.MetaInfo == null)
         {
             clone.MetaInfo = new List<MetaInfo>();
         }
         clone.MetaInfo.Add(new MetaInfo()
         {
             Label       = AggregationCountLabel,
             Description = "The number of features belonging to this aggregation",
             IsEditable  = false,
             Type        = MetaTypes.number
         });
         if (shapeIdLabel != null) clone.MetaInfo.Add(new MetaInfo()
         {
             Label      = "Shape_Name",
             IsEditable = false,
             Type       = MetaTypes.text
         });
         clonedPoiTypes.Add(clone);
     }
     return clonedPoiTypes;
 }
Beispiel #24
0
 private void PoICollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
 {
     var cl = new ContentList();
     switch (e.Action)
     {
         case NotifyCollectionChangedAction.Add:
             foreach (var item in e.NewItems.Cast<BaseContent>()) cl.Add(item);
             AddPoIsToViewModelCollection(cl);
             break;
         case NotifyCollectionChangedAction.Remove:
             foreach (var item in e.OldItems.Cast<BaseContent>()) cl.Add(item);
             RemovePoIsFromViewModelCollection(cl);
             break;
     }
 }