/// <summary> /// Convert the XML file to a data service. /// </summary> /// <param name="file">XML file.</param> /// <returns>Returns a PoiService if successfull, null otherwise.</returns> public PoiService ProcessXml(string filename) { var poiService = new PoiService { Name = Path.GetFileNameWithoutExtension(filename), Id = Guid.NewGuid(), IsFileBased = true, Folder = Path.GetDirectoryName(filename), StaticService = false }; poiService.InitPoiService(); //poiService.Settings.BaseStyles = new List<PoIStyle> //{ // new PoIStyle // { // Name = "default", // FillColor = Colors.White, // StrokeColor = Color.FromArgb(255,128,128,128), // CallOutOrientation = CallOutOrientation.Right, // FillOpacity = 0.3, // TitleMode = TitleModes.Bottom, // NameLabel = "Name", // DrawingMode = DrawingModes.Image, // StrokeWidth = 2, // IconWidth = 48, // IconHeight = 48, // CallOutFillColor = Colors.White, // CallOutForeground = Colors.Black, // TapMode = TapMode.CallOut // } //}; //var defaultPoiType = new PoI //{ // Name = "Default", // ContentId = "Default", // Style = new PoIStyle // { // Name = "default", // FillColor = Colors.White, // StrokeColor = Color.FromArgb(255, 128, 128, 128), // CallOutOrientation = CallOutOrientation.Right, // FillOpacity = 0.3, // TitleMode = TitleModes.Bottom, // NameLabel = "Name", // DrawingMode = DrawingModes.Image, // StrokeWidth = 2, // IconWidth = 48, // IconHeight = 48, // CallOutFillColor = Colors.White, // CallOutForeground = Colors.Black, // TapMode = TapMode.CallOut // }, // Id = Guid.NewGuid(), // DrawingMode = DrawingModes.Image, // MetaInfo = new List<MetaInfo>() //}; return poiService; }
public ActionResult Login() { var authToken = Request.QueryString["SSO_AUTH_TOKEN"]; var ssoOvreiden = false; bool.TryParse(ConfigurationManager.AppSettings[@"SSOveriden"], out ssoOvreiden); if (ssoOvreiden) { var user = new UserData { UserID = ConfigurationManager.AppSettings[@"User_id"], Username = ConfigurationManager.AppSettings[@"Username"] }; Session[nameof(UserData)] = user; return(RedirectToAction(nameof(Index), @"Home")); } if (!string.IsNullOrEmpty(authToken)) { _poiService = new PoiService(); var user = _poiService.ValidateUser(authToken); Session[nameof(UserData)] = user; } var vm = GetPois(); return(View(vm)); }
public static IOResult<FileLocation> BrowseAndSaveFile(PoiService content, bool saveMetaData = true, Window owner = null, IEnumerable<string> excludedExtensions = null, string nameFormatString = "") { IOResult<FileLocation> browseFile = BrowseFile(content, owner, excludedExtensions); if (browseFile == null || !browseFile.Successful) { return browseFile; } var extension = Path.GetExtension(browseFile.Result.LocationString); if (extension == null || (string.IsNullOrEmpty(nameFormatString) || !extension.Equals(".json", StringComparison.InvariantCultureIgnoreCase))) return PoiServiceExporters.Instance.Export(content, browseFile.Result, saveMetaData); if (string.IsNullOrEmpty(nameFormatString)) return PoiServiceExporters.Instance.Export(content, browseFile.Result, saveMetaData); var poiType = content.PoITypes.FirstOrDefault(); if (poiType != null) { poiType.MetaInfo.Insert(0, new MetaInfo { Label = "Name", Title = "Name", IsEditable = false, IsSearchable = true, VisibleInCallOut = true, Type = MetaTypes.stringFormat, StringFormat = nameFormatString }); } content.PoIs.ForEach(p => p.Labels.Remove("Name")); return PoiServiceExporters.Instance.Export(content, browseFile.Result, saveMetaData); }
public JsonResult GetPoiByID(int id) { var vm = new GetPOIVM(); _poiService = new PoiService(); vm = _poiService.GetPoiByID(id); return(Json(vm?.CusPoi ?? null, JsonRequestBehavior.AllowGet)); }
public static IOResult<FileLocation> ExportPoiService(PoiService data, IExporter<PoiService, string> exporter, FileLocation destination = null, bool includeGuid = false) { if (destination == null) { destination = GetOutputFileLocation(data, exporter.DataFormatExtension, includeGuid); } return ConvertFile(null, data, exporter, destination, includeGuid); }
public System.Threading.Tasks.Task Execute(PoiService poiService, PoI poi, List<Point> zone) { return System.Threading.Tasks.Task.Run(() => { if (Items == null || Items.Count == 0) return; foreach (var sqlQuery in Items.OfType<SqlQuery>()) { sqlQuery.Execute(poiService, poi, zone); } }); }
public JsonResult GetPoiList(string keywords) { var vm = new GetPOIVM(); _poiService = new PoiService(); var user = new UserData(); user = Session[nameof(UserData)] as UserData; var userID = 0; int.TryParse(user.UserID, out userID); vm = _poiService.GetAvailablePoiByDescription(keywords, userID); return(Json(vm?.CusPoiList ?? null, JsonRequestBehavior.AllowGet)); }
public dsLayer(PoiService s, DataServerPlugin p) { if (s == null) { csCommon.Logging.LogCs.LogMessage(String.Format("dsLayer: Create PoiService '{0}'", "empty")); s = new PoiService(); } Service = s; ID = Service.Name; plugin = p; PoiLayers = new Dictionary<string, dsPoiLayer>(); OverlayLayers = new Dictionary<string, dsOverlayLayer>(); Children = new ObservableCollection<Layer>(); s.PropertyChanged += s_PropertyChanged; }
public dsStaticLayer(PoiService s, DataServerPlugin p) { if (s == null) { csCommon.Logging.LogCs.LogMessage(String.Format("dsStaticLayer: Create PoiService '{0}'", "empty")); s = new PoiService(); } Service = s; Visible = false; ID = Service.Name; plugin = p; subLayers = new Dictionary<string, dsStaticSubLayer>(); Children = new ObservableCollection<Layer>(); s.AllPoisRefreshed += (delegate { RefreshAllVisiblePois(); }); }
GetPOIVM GetPois() { var lang = (string)ControllerContext.RouteData.Values[@"lang"]; var vm = new GetPOIVM(); _poiService = new PoiService(); vm = _poiService.GetStartupData(); var defaultLang = vm.LanguageList.FirstOrDefault(l => l.Name.Equals(lang)); if (defaultLang == null) { defaultLang = vm.LanguageList.FirstOrDefault(); } vm.Langugae = defaultLang; return(vm); }
public bool StartRecording(Media ppt, Event e, PoiService ps) { //media = ppt; //service = ps; //pptEvent = e; if (Active) return false; //_stream = new MemoryStream(); //_stream.Seek(0, SeekOrigin.Begin); //_microphone = Microphone.Default; //_microphone.BufferReady -= microphone_BufferReady; //_microphone.BufferReady += microphone_BufferReady; //_microphone.BufferDuration = TimeSpan.FromMilliseconds(300); //_buffer = new byte[_microphone.GetSampleSizeInBytes(_microphone.BufferDuration)]; //_microphone.Start(); return true; }
public PoiService CreateService(string name, string folder, string relativeFolder) { LogCs.LogMessage(String.Format("SaveService: Create PoiService '{0}'", name)); var ss = new PoiService() { IsLocal = true, Name = name, Id = Guid.NewGuid(), IsFileBased = true, StaticService = StaticService, IsVisible = false, Folder = folder, RelativeFolder = RelativeFolder }; ss.Init(Mode.client, AppStateSettings.Instance.DataServer); ss.RelativeFolder = relativeFolder; ss.InitPoiService(); ss.SettingsList = new ContentList { Service = ss, ContentType = typeof(ServiceSettings), Id = "settings", IsRessetable = false }; ss.SettingsList.Add(new ServiceSettings()); ss.AllContent.Add(ss.SettingsList); ss.Settings.OpenTab = false; ss.Settings.TabBarVisible = false; ss.Settings.Icon = "layer.png"; ss.AutoStart = false; return ss; }
private static void CompressColumns(Dictionary<string, AggregationPolicy> aggregationPolicies, PoiService aggregate) { // Compress all keyword columns to a single column (this may be a setting later). var labelsWithKeywordAggregation = aggregationPolicies.Where(kv => kv.Value.IsKeywordAggregation).Select(kv => kv.Key); foreach (BaseContent poi in aggregate.PoIs) { WordHistogram sumHistogram = null; foreach (string label in labelsWithKeywordAggregation) { string labelValue; if (poi.Labels.TryGetValue(label, out labelValue)) { WordHistogram wordHistogram = new WordHistogram(); wordHistogram.Append(labelValue); if (sumHistogram == null) { sumHistogram = wordHistogram.Clone(); } else { sumHistogram.Merge(wordHistogram); } } } if (sumHistogram != null) { poi.Keywords = sumHistogram; } } // Remove all columns that have been compressed to keywords. foreach (BaseContent poI in aggregate.PoIs) { foreach (KeyValuePair<string, AggregationPolicy> kv in aggregationPolicies) { if (!kv.Value.DataIsNumeric && kv.Value.NonNumericAggregationPolicy == AggregationPolicy.NonNumericAggregation.Keywords) { poI.Labels.Remove(kv.Key); } } } // Remove obsolete labels; only in the PoiTypes; they are already gone from the Pois. foreach (BaseContent baseContent in aggregate.PoITypes) { List<string> toOmit = new List<string>(); foreach (string label in baseContent.Labels.Keys) { AggregationPolicy policy; bool remove = true; if (aggregationPolicies.TryGetValue(label, out policy)) { if (!policy.IsOmit && !(policy.DataIsNumeric && policy.NonNumericAggregationPolicy == AggregationPolicy.NonNumericAggregation.Keywords)) { remove = false; } } if (remove) { toOmit.Add(label); } } foreach (string label in toOmit) { baseContent.Labels.Remove(label); } } }
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; }
public static PoiService Aggregate(PoiService source, string aggregationLabel, Dictionary<string, AggregationPolicy> aggregationPolicies) { // Make sure the aggregation label itself is not erased or compromised in any way. AggregationPolicy aggregationLabelPolicy; if (aggregationPolicies.TryGetValue(aggregationLabel, out aggregationLabelPolicy)) { if (aggregationLabelPolicy.DataIsNumeric) { aggregationLabelPolicy.NumericAggregationPolicy = AggregationPolicy.NumericAggregation.KeepFirst; } else { aggregationLabelPolicy.NonNumericAggregationPolicy = AggregationPolicy.NonNumericAggregation.KeepFirst; } } // Master dictionary: aggregation label -> all other labels -> values for those labels Dictionary<string, Dictionary<string, List<string>>> aggregations = new Dictionary<string, Dictionary<string, List<string>>>(); // Counter dictionary: aggregation label value -> number of PoIs having that value Dictionary<string, int> count = new Dictionary<string, int>(); // Gather data. foreach (BaseContent poi in source.PoIs) { string aggregationLabelValue; if (!poi.Labels.TryGetValue(aggregationLabel, out aggregationLabelValue)) { continue; } if (! aggregations.ContainsKey(aggregationLabelValue)) { aggregations[aggregationLabelValue] = new Dictionary<string, List<string>>(); } foreach (KeyValuePair<string, string> kv in poi.Labels) { string poiLabelName = kv.Key; string poiLabelValue = kv.Value; if (!aggregations[aggregationLabelValue].ContainsKey(poiLabelName)) { aggregations[aggregationLabelValue][poiLabelName] = new List<string>(); } aggregations[aggregationLabelValue][poiLabelName].Add(poiLabelValue); } if (!count.ContainsKey(aggregationLabelValue)) { count[aggregationLabelValue] = 1; } else { count[aggregationLabelValue]++; } } // Aggregate. var aggregate = new PoiService { PoITypes = ClonePoiTypes(source) }; foreach (var kv in aggregations) { var labelsWithValues = kv.Value; var newPoI = new PoI {PoiType = aggregate.PoITypes.FirstOrDefault()}; foreach (var kw in labelsWithValues) { ApplyAggregation(aggregationPolicies, kw, newPoI); } aggregate.PoIs.Add(newPoI); } // Handle keyword aggregation and remove obsolete columns. CompressColumns(aggregationPolicies, aggregate); // Add count information. foreach (BaseContent poi in aggregate.PoIs) { string aggregationLabelValue; if (poi.Labels.TryGetValue(aggregationLabel, out aggregationLabelValue)) { int aggregationLabelValueFrequency; if (count.TryGetValue(aggregationLabelValue, out aggregationLabelValueFrequency)) { poi.Labels[AggregationCountLabel] = "" + aggregationLabelValueFrequency; } } } // Return. return aggregate; }
public virtual void CalculateMax(PoiService service) { if (UsesMultipleCriteria) { maxValue = service.PoIs.Where(p => p.PoiTypeId == PoiType).Max(p => CalculateResultUsingMultipleCriteria(p)); //maxValue = double.MinValue; //foreach (var result in service.PoIs.Where(p => p.PoiTypeId == PoiType).Select(CalculateResultUsingMultipleCriteria).Where(result => result > curMax)) // curMax = result; //maxValue = curMax; } else { switch (SelectionType) { case SelectionTypes.Selected: maxValue = 1; break; case SelectionTypes.Label: maxValue = double.MinValue; foreach ( var p in service.PoIs.Where( p => p.PoiTypeId == PoiType && p.Labels.ContainsKey(SelectionCriteria))) { double v; if ( !double.TryParse(p.Labels[SelectionCriteria], NumberStyles.Any, CultureInfo.InvariantCulture, out v)) continue; if (v > maxValue && v != -99999997) maxValue = v; } if (maxValue <= double.MinValue) maxValue = 1; // No element found break; case SelectionTypes.Sensor: //maxValue = service.PoIs.Where(p => p.Sensors.ContainsKey(SelectionCriteria)).Max(p => p.Sensors[SelectionCriteria].Data.Max(k => k.Value)); maxValue = double.MinValue; foreach ( var v in service.PoIs.Where( p => p.Sensors.ContainsKey(SelectionCriteria) && p.Sensors[SelectionCriteria].Data.Count > 0) .Select(p => p.Sensors[SelectionCriteria].Data.Max(k => k.Value))) { maxValue = v; } break; } } if (!string.IsNullOrEmpty(StringFormat)) { double result; if (double.TryParse(string.Format(CultureInfo.InvariantCulture, StringFormat, maxValue), NumberStyles.Number, CultureInfo.InvariantCulture, out result)) maxValue = result; } NotifyOfPropertyChange(() => MaxValue); }
public static IOResult<FileLocation> BrowseFile(PoiService content = null, Window owner = null, IEnumerable<string> excludedExtensions = null) { if (owner == null) { owner = Application.Current.MainWindow; } StringBuilder allFileFilterBuilder = new StringBuilder("All supported formats|"); StringBuilder fileFilterBuilder = new StringBuilder(); IEnumerable<string> supportedExtensions = PoiServiceExporters.Instance.GetSupportedExtensions(excludedExtensions); bool first = true; string defaultExt = ""; foreach (var supportedExtension in supportedExtensions) { IExporter<PoiService, FileLocation> exporter = PoiServiceExporters.Instance.GetExporter(supportedExtension); if (first) { defaultExt = "." + supportedExtension; } else { fileFilterBuilder.Append('|'); allFileFilterBuilder.Append(';'); } fileFilterBuilder.Append(exporter.DataFormat) .Append(" (*.") .Append(supportedExtension) .Append(")") .Append("|*.") .Append(supportedExtension); allFileFilterBuilder.Append("*.").Append(supportedExtension); first = false; } if (fileFilterBuilder.Length == 0) { MessageBox.Show(owner, "Cannot find any exporters in the assembly!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return null; } var sfd = new SaveFileDialog { AddExtension = true, CheckFileExists = false, CheckPathExists = true, DefaultExt = defaultExt, Filter = allFileFilterBuilder.Append('|').Append(fileFilterBuilder).ToString() }; if (content != null && !string.IsNullOrEmpty(content.Folder)) { sfd.InitialDirectory = content.Folder; } if (sfd.ShowDialog(owner) == true) { return new IOResult<FileLocation>(new FileLocation(sfd.FileName)); } return null; }
public void CleanUp(PoiService service) { // Remove the metainfo in the popup var pt = service.PoITypes.FirstOrDefault(p => string.Equals(p.ContentId, PoiType)); if (pt == null) return; RemoveMetaInfo(pt); // Remove the labels that were added var key = LabelTitle; foreach (var p in service.PoIs.Where(p => string.Equals(p.PoiTypeId, PoiType))) p.Labels.Remove(key); }
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); } }
/// <summary> /// delete a service /// </summary> /// <param name="s"></param> public void DeleteService(PoiService s){ if (s == null) return; if (s.IsSubscribed) UnSubscribe(s); if (s.Layer != null) s.Layer.Stop(); if (s.Layer != null && s.Layer.Parent != null && s.Layer.Parent.ChildLayers.Contains(s.Layer)) { s.Layer.Parent.ChildLayers.Remove(s.Layer); AppStateSettings.Instance.ViewDef.UpdateLayers(); } Services.Remove(s); if (!s.IsLocal || s.Mode != Mode.client) return; try { if (File.Exists(s.FileName) && s.IsFileBased) { File.Delete(s.FileName); } } catch (Exception e){ Logger.Log("DataService", "Error delete dataservice at: " + s.FileName, e.Message, Logger.Level.Error); } NotifyOfPropertyChange(() => DynamicServices); }
public void UpdateLayerTabs(PoiService service, dsLayer layer) { var tabVisible = true; if (service.Settings != null) { tabVisible = service.Settings.TabBarVisible; } // check if it already exists Execute.OnUIThread(() => { var inst = AppState.StartPanelTabItems.FirstOrDefault( k => k.ModelInstance is TabItemViewModel && ((TabItemViewModel)k.ModelInstance).Service == service); if (inst == null && service.IsInitialized && tabVisible) { var ptvm = new TabItemViewModel { Plugin = this, Service = service, Layer = layer }; var s = new StartPanelTabItem { Name = service.Name }; ptvm.TabItem = s; if (!service.IsLocal || service.Mode == Mode.server) { s.SupportImage = new BitmapImage( new Uri("pack://application:,,,/csCommon;component/Resources/Icons/online.png")); } s.ModelInstance = ptvm; AppState.AddStartPanelTabItem(s); } else if ((!service.IsInitialized || !tabVisible) && inst != null) { AppState.RemoveStartPanelTabItem(inst); } }); }
/// <summary> /// /// </summary> /// <param name="pSharedServiceGuid">The ID of the service that is being shared by remote IMB client</param> /// <param name="PImbHandleSharingService">The IMB handle of the remote IMB client that is sharing</param> /// <returns></returns> private PoiService CreateShadowServiceForSharedService(string pSharedServiceName, Guid pSharedServiceGuid, int pImbHandleSharingService) { if (!FileStore.FolderExists("Services")) FileStore.CreateFolder("Services"); if (!FileStore.FolderExists("Services\\" + pSharedServiceGuid)) FileStore.CreateFolder("Services\\" + pSharedServiceGuid); var shadowPoiService = new PoiService { Id = pSharedServiceGuid, Name = pSharedServiceName, IsShared = true, IsLocal = false, StaticService = false, /* could be true of false: don't known is static of dynamic service */ Server = pImbHandleSharingService, RelativeFolder = "Shared Layers", Mode = Mode.client, Folder = Path.Combine(Path.Combine(FileStore.GetLocalFolder() , "Services"), pSharedServiceGuid.ToString()), dsb = this }; Services.Add(shadowPoiService); shadowPoiService.InitPoiService(); LogCs.LogMessage(String.Format("Added shared service '{0}' (GUID: {1}) to local servicelist, the orginal service is hosted on IMB client with handle {2}.", pSharedServiceName, pSharedServiceGuid, pImbHandleSharingService)); LogCs.LogMessage(String.Format("Shared service '{0}' stores persistent data in folder '{1}'.", pSharedServiceName, shadowPoiService.Folder)); NotifyOfPropertyChange(() => DynamicServices); return shadowPoiService; }
private void JoinSharedService(bool pServiceAlreadyExsisted, PoiService pSharedService) { if (pServiceAlreadyExsisted) { // Request the sharing service IMB client to add this client to subscribtion list Subscribe(pSharedService); } else pSharedService.Start(); }
private double CalculateMinLabelValue(PoiService service) { var min = double.MaxValue; foreach (var p in service.PoIs.Where(p => p.PoiTypeId == PoiType && p.Labels.ContainsKey(SelectionCriteria))) { double v; if (!double.TryParse(p.Labels[SelectionCriteria], NumberStyles.Any, CultureInfo.InvariantCulture, out v)) continue; if (v < min && v != -99999997) min = v; } return min >= double.MaxValue ? 0 : min; }
/// <summary> /// The change poi service. /// </summary> /// <param name="pOldPoiService"> /// The p old poi service. /// </param> /// <param name="pNewPoiService"> /// The p new poi service. /// </param> private void ChangePoiService(PoiService pOldPoiService, PoiService pNewPoiService) { this.mPoiService = pNewPoiService; // Remove old subscriptions if (this.AvaliablePoITypesInService != null) { this.ServicePoITypes = null; this.AvaliablePoITypesInService = null; this.SelectedPoiType = null; } // Create new subscriptions if ((pNewPoiService != null) && (pNewPoiService.PoITypes != null)) { this.AvaliablePoITypesInService = new ReadOnlyObservableCollection<BaseContent>(pNewPoiService.PoITypes); this.ServicePoITypes = this.CreateCollectionView(); (this.AvaliablePoITypesInService as INotifyCollectionChanged).CollectionChanged += (sender, e) => { if (this.mPoiTypesCollectionView != null) { this.mPoiTypesCollectionView.Refresh(); } }; } }
private double CalculateMinSensorValue(PoiService service) { var min = double.MaxValue; foreach (var v in service.PoIs.Where(p => p.PoiTypeId == PoiType && p.Sensors.ContainsKey(SelectionCriteria) && p.Sensors[SelectionCriteria].Data.Count > 0).Select(p => p.Sensors[SelectionCriteria].Data.Min(k => k.Value))) { //foreach (var p in service.PoIs.Where(p => p.Sensors.ContainsKey(SelectionCriteria))) { //var v = p.Sensors[SelectionCriteria].Data.Min(k => k.Value); if (v < min && v != -99999997) min = v; } return min; }
public virtual void CalculateMin(PoiService service) { if (UsesMultipleCriteria) { minValue = service.PoIs.Where(p => p.PoiTypeId == PoiType).Min(p => CalculateResultUsingMultipleCriteria(p)); //minValue = double.MaxValue; //foreach (var result in service.PoIs.Where(p => p.PoiTypeId == PoiType).Select(CalculateResultUsingMultipleCriteria).Where(result => result < curMin)) // curMin = result; //minValue = curMin; } else { switch (SelectionType) { case SelectionTypes.Selected: minValue = 0; break; case SelectionTypes.Label: minValue = CalculateMinLabelValue(service); break; case SelectionTypes.Sensor: //minValue = service.PoIs.Where(p => p.Sensors.ContainsKey(SelectionCriteria)).Min(p => p.Sensors[SelectionCriteria].Data.Min(k => k.Value)); minValue = CalculateMinSensorValue(service); break; } if (minValue < 0.000001 && minValue > 0) minValue = 0.0; } if (!string.IsNullOrEmpty(StringFormat)) { double result; if (double.TryParse(string.Format(CultureInfo.InvariantCulture, StringFormat, minValue), NumberStyles.Number, CultureInfo.InvariantCulture, out result)) minValue = result; } NotifyOfPropertyChange(() => MinValue); }
/// <summary> /// Execute the SQL query and update the service. /// </summary> /// <param name="service"></param> /// <param name="refPoi"></param> /// <param name="zone"></param> /// <param name="isQueueAble"></param> /// <param name="forceExecute"></param> /// <returns></returns> public async void Execute(PoiService service, PoI refPoi, List<Point> zone, bool isQueueAble = false, bool forceExecute = false) { Caliburn.Micro.Execute.OnUIThread(() => { var layer = service.Layer as dsStaticLayer; if (layer == null) return; var l = layer.GetSubLayer(Layer); if (l != null) IsEnabled = l.Visible; }); if (!IsEnabled && !forceExecute) return; lock (myLock) { // Cancel the last task, if any. if (cts != null) { if (refPoi != null && isQueueAble) { if (queue.ContainsKey(refPoi) && queue[refPoi] != null) queue[refPoi].Cancel(); } else cts.Cancel(); } // Create Cancellation Token for this task. cts = new CancellationTokenSource(); if (isQueueAble && refPoi != null) queue[refPoi] = cts; } var token = cts.Token; try { await System.Threading.Tasks.Task.Run(() => { while (isExecuting) { token.ThrowIfCancellationRequested(); Thread.Sleep(100); } isExecuting = true; var query = DefineParametrizedQuery(refPoi, zone); token.ThrowIfCancellationRequested(); var poiList = new List<PoI>(); using (var conn = new NpgsqlConnection(ConnectionString)) { try { token.ThrowIfCancellationRequested(); conn.Open(); var command = new NpgsqlCommand(query, conn); // EV Specify in connection string. {CommandTimeout = 30}; var dr = command.ExecuteReader(); token.ThrowIfCancellationRequested(); InitializeFieldNames(dr); #region Processing an iterative SQL query if (Options != null && refPoi != null) { try { var tries = 0; var maxTries = (int)Math.Round(refPoi.LabelToDouble(InputParameters[Options.MaxTriesInputParameterIndex].LabelName), 0); var desiredResult = Options.ComputeDesiredResult(refPoi, InputParameters); var desiredAccurcy = refPoi.LabelToDouble(InputParameters[Options.DesiredAccuracyInputParameterIndex].LabelName); var acceptableDiff = desiredResult * desiredAccurcy / 100; var outputName = OutputParameters[Options.ActualResultOutputParameterIndex].Name; var currentResult = refPoi.LabelToDouble(outputName); var success = Math.Abs(currentResult - desiredResult) <= acceptableDiff; if (success) { dr.Close(); return; } var controlLabelName = InputParameters[Options.ControlInputParameterIndex].LabelName; var control = refPoi.LabelToDouble(controlLabelName); var origControl = control; do { var actualResult = 0.0; while (dr.Read()) { token.ThrowIfCancellationRequested(); var result = dr[outputName].ToString(); if (string.IsNullOrEmpty(result)) continue; actualResult = double.Parse(result, NumberStyles.Any, CultureInfo.InvariantCulture); success = Math.Abs(actualResult - desiredResult) <= acceptableDiff; } if (success) continue; switch (Options.Relationship) { case SqlInputOutputRelationship.Linear: // actual = control * alpha var alpha1 = actualResult / (control.IsZero() ? 0.0001 : control); control = alpha1.IsZero() ? 2 * control : desiredResult / alpha1; break; case SqlInputOutputRelationship.Quadratic: // actual = control^2 * alpha var alpha2 = actualResult / Math.Pow(control.IsZero() ? 0.0001 : control, 2); control = alpha2.IsZero() ? 2 * control : Math.Sqrt(desiredResult / alpha2); break; } refPoi.Labels[controlLabelName] = control.ToString(CultureInfo.InvariantCulture); query = DefineParametrizedQuery(refPoi, zone); command = new NpgsqlCommand(query, conn) { CommandTimeout = 30 }; dr = command.ExecuteReader(); if (++tries > maxTries) { Logger.Log("SqlProcessing.SqlQuery", refPoi.Name + ": " + "Could not resolve query", refPoi.Name + ": Max tries exceeded", Logger.Level.Warning, true); return; } tries++; } while (!success); if (Math.Abs(origControl - control) > 0.001) Caliburn.Micro.Execute.OnUIThread(() => refPoi.TriggerLabelChanged(controlLabelName)); // NOTE I need to redo the same query again to be able to continue, // as I cannot find a way to reset dr. dr = command.ExecuteReader(); } catch (SystemException e) { Logger.Log("SqlProcessing.SqlQuery", refPoi.Name + ": " + "Error running iterative query", e.Message, Logger.Level.Error, true); } } #endregion Processing an iterative SQL query while (dr.Read()) { token.ThrowIfCancellationRequested(); var contentId = RetreiveId(dr); var position = RetreivePosition(dr); var geometry = String.IsNullOrEmpty(pointsField) ? null : dr[pointsField].ToString().ConvertFromWkt(); if (position == null && geometry == null) { AddOutputsAsLabel(refPoi, dr); conn.Close(); isExecuting = false; return; } if (refPoi != null && !String.IsNullOrEmpty(refPoi.ContentId)) contentId = refPoi.ContentId + "_" + contentId; var poi = new PoI { ContentId = contentId, Service = service, Name = RetreiveName(dr), PoiTypeId = PoiTypeId, UserId = Id.ToString(), Layer = Layer, Position = position, Style = PoiType == null ? null : PoiType.Style, Geometry = geometry, WktText = dr[pointsField].ToString(), }; SetGeometry(poi); AddOutputsAsLabel(poi, dr); poi.UpdateEffectiveStyle(); poiList.Add(poi); } var currPois = service.PoIs.Where(k => k.PoiTypeId == PoiTypeId).ToList(); Caliburn.Micro.Execute.OnUIThread(() => { service.PoIs.StartBatch(); switch (UpdateType) { case UpdateTypes.Add: poiList.ForEach(p => service.PoIs.Add(p)); break; case UpdateTypes.AutoClear: currPois.ForEach(p => service.PoIs.Remove(p)); poiList.ForEach(p => service.PoIs.Add(p)); break; case UpdateTypes.Diff: //Remove Pois that are no longer needed var poicheck = ""; if (refPoi != null && !String.IsNullOrEmpty(refPoi.ContentId)) poicheck = refPoi.ContentId + "_"; var remlist = currPois.Where(k => k.ContentId.StartsWith(poicheck) && poiList.All(g => g.ContentId != k.ContentId)).ToList(); remlist.ForEach(p => service.RemovePoi((PoI)p)); poiList.ForEach( p => { if (currPois.All(c => c.ContentId != p.ContentId)) service.PoIs.Add(p); }); break; case UpdateTypes.DiffGeo: var addDiffGeo = new List<PoI>(); foreach (var p in poiList) { var first = currPois.FirstOrDefault(k => k.ContentId.ToString() == p.ContentId.ToString()); if (first == null || first.WktText == p.WktText) continue; addDiffGeo.Add(p); } var rem = currPois.Where(k => !string.IsNullOrEmpty(k.UserId) && addDiffGeo.Any(g => g.ContentId == k.ContentId)).ToList(); foreach (var r in rem) { service.RemovePoi((PoI)r); } foreach (var a in addDiffGeo) { service.PoIs.Add(a); } //Remove pois wich are no longer needed poicheck = ""; if (refPoi != null && !String.IsNullOrEmpty(refPoi.ContentId)) poicheck = refPoi.ContentId + "_"; remlist = currPois.Where(k => k.ContentId.StartsWith(poicheck) && poiList.All(g => g.ContentId != k.ContentId)).ToList(); remlist.ForEach(p => service.RemovePoi((PoI)p)); //Add pois which are new poiList.ForEach(p => { if (currPois.All(c => c.ContentId != p.ContentId)) service.PoIs.Add(p); }); break; } UpdateMinMax(service); service.PoIs.FinishBatch(); //if (refPoi != null && !String.IsNullOrEmpty(refPoi.ContentId)) // poicheck = refPoi.ContentId + "_"; //var remlist =currPoi.Where(k =>k.ContentId.StartsWith(poicheck) && poiList.All(g => g.ContentId != k.ContentId)).ToList(); }); } catch (OperationCanceledException) { } catch (SystemException e) { Logger.Log("SqlProcessing.SqlQuery", refPoi.Name + ": " + "Error accessing PostgreSQL server", e.Message, Logger.Level.Error, true); } finally { lock (myLock) { if (isQueueAble && refPoi != null) queue[refPoi] = null; } isExecuting = false; } } }, token); } catch (OperationCanceledException) { isExecuting = false; } }
public void Open(PoI p, PoiService service) // REVIEW TODO fix: async removed { var f = p.Id + ".t"; string folder = service.Folder + "\\tracks\\"; if (!service.store.HasFile(folder, f)) return; var his = service.store.GetString(folder + "\\" + f); // REVIEW TODO fix: await removed foreach (var ln in his.Split('\n')) { try { if (!ln.StartsWith("#")) { var pos = new Position(ln); History.Add(pos); } } catch (Exception e) { // FIXME TODO Deal with exception! //Logger.Log("DataService","Error opening track file",e.Message,Logger.Level.Error); } } }
private void UpdateMinMax(PoiService service) { //Todo: Find better way of updating min/max Caliburn.Micro.Execute.OnUIThread(() => { if (PoiType == null) return; foreach (var hl in PoiType.Style.Analysis.Highlights) { if (!hl.IsDynamic) continue; hl.CalculateMax(service); hl.CalculateMin(service); } }); }
/// <summary> /// Remove all PoIs created by this service (checks whether the UserId == SqlQuery.Id). /// </summary> /// <param name="poiService"></param> /// <param name="currPois"></param> private void RemoveExistingPoIs(PoiService poiService, IEnumerable<BaseContent> currPois) { poiService.PoIs.StartBatch(); lock (myLock) { foreach (var rp in currPois) poiService.PoIs.Remove(rp); } Caliburn.Micro.Execute.OnUIThread(() => poiService.PoIs.FinishBatch()); }
public static PoiService Aggregate(PoiService source, PoiService shapes, string shapeIdLabel, Dictionary<string, AggregationPolicy> aggregationPolicies, bool addLabelsFromShapeFile) { // Build a dictionary of shape -> labels -> values. Dictionary<BaseGeometry, Dictionary<string, List<string>>> aggregations = new Dictionary<BaseGeometry, Dictionary<string, List<string>>>(); // Copy the shape PoIs to the aggregate PoI. Dictionary<BaseGeometry, PoI> aggregatePois = new Dictionary<BaseGeometry, PoI>(); // Allows to look up PoIs by geometry. PoiService aggregate = new PoiService { PoITypes = ClonePoiTypes(source, shapeIdLabel) }; // TODO BUG Note that we omit metadata for the shape layer. foreach (BaseContent shapePoi in shapes.PoIs) { if (shapePoi.Geometry == null) { continue; } var newPoI = new PoI {Geometry = shapePoi.Geometry}; aggregate.PoIs.Add(newPoI); aggregatePois[newPoI.Geometry] = newPoI; aggregations[newPoI.Geometry] = new Dictionary<string, List<string>>(); if (addLabelsFromShapeFile) { foreach (KeyValuePair<string, string> kv in shapePoi.Labels) { newPoI.Labels[kv.Key] = kv.Value; aggregations[newPoI.Geometry][kv.Key] = new List<string>() {kv.Value}; } } else { // Remember at least the ID of the shape layer, if possible. string shapeIdLabelValue; if (!shapePoi.Labels.TryGetValue(shapeIdLabel, out shapeIdLabelValue)) continue; newPoI.Labels[shapeIdLabel] = shapeIdLabelValue; aggregations[newPoI.Geometry][shapeIdLabel] = new List<string> { shapeIdLabelValue }; } } // Counter dictionary: aggregation shape -> number of PoIs within that shape Dictionary<BaseGeometry, int> count = new Dictionary<BaseGeometry, int>(); // Fill the dictionary. foreach (BaseContent poi in source.PoIs) { Point pos = poi.Geometry as Point; // NOTE: The following is wrong, because 'Position' is not in sync! -- new Point(poi.Position.Longitude, poi.Position.Latitude); if (pos == null) { continue; } foreach (var kv in aggregations) { BaseGeometry geometry = kv.Key; Dictionary<string, List<string>> labels = kv.Value; if (! geometry.Contains(pos)) continue; foreach (KeyValuePair<string, string> kw in poi.Labels) { string poiLabel = kw.Key; string poiLabelValue = kw.Value; List<string> labelValues; if (!labels.TryGetValue(poiLabel, out labelValues)) { labelValues = new List<string>(); labels[poiLabel] = labelValues; } labels[poiLabel].Add(poiLabelValue); } if (!count.ContainsKey(geometry)) { count[geometry] = 1; } else { count[geometry]++; } } } // Aggregate and add count information. foreach (KeyValuePair<BaseGeometry, Dictionary<string, List<string>>> kv in aggregations) { PoI poi; if (aggregatePois.TryGetValue(kv.Key, out poi)) { foreach (KeyValuePair<string, List<string>> kw in kv.Value) { ApplyAggregation(aggregationPolicies, kw, poi); } int numPoisInRegion; if (count.TryGetValue(kv.Key, out numPoisInRegion)) { poi.Labels[AggregationCountLabel] = "" + numPoisInRegion; } } } // Handle keyword aggregation and remove obsolete columns. CompressColumns(aggregationPolicies, aggregate); // Return. return aggregate; }
// TODO This (legacy) code is used in multiple spots in the code; we now have more than one way to load a data service. // Load .ds file and creates a service fot this ds file public PoiService AddLocalDataService(string folder, Mode _mode, string file, string originFolder = "", bool autoStart = false){ if (string.IsNullOrEmpty(originFolder)) originFolder = Path.Combine(Directory.GetCurrentDirectory(), AppState.Config.Get("Poi.LocalFolder", "PoiLayers")); // Use GUID in filename is ID for service (important when file is cloned!) var f = file.Split('\\').Last(); var stat = (f.StartsWith("~")); if (stat) f = f.Remove(0, 1); var idname = f.Substring(0, f.Length - 3).Split('.'); // p.Name.Substring(0, p.Name.Length - 3).Split('.'); var guid = idname.Length > 1 && !string.IsNullOrEmpty(idname[1]) ? Guid.Parse(idname[0]) : Guid.NewGuid(); if (idname.Length != 2) return null; var name = idname[1].Replace("_", ""); var ps = new PoiService { IsLocal = true, Folder = folder, Id = guid, Name = name, StaticService = stat, RelativeFolder = folder.Replace(originFolder, string.Empty), AutoStart = autoStart }; ps.InitPoiService(); AddService(ps, _mode); if (_mode != Mode.server) return ps; Subscribe(ps); if (ps.Settings != null) ps.Settings.ShareOnline = true; return ps; }
//Todo: Add function to partition string into categories public virtual void CalculateCategories(PoiService service) { var res = new Dictionary<object, int>(); foreach (var p in service.PoIs) { if (p.Labels.ContainsKey(selectionCriteria)) { if (res.ContainsKey(p.Labels[selectionCriteria])) { res[p.Labels[selectionCriteria]]++; } else { res[p.Labels[selectionCriteria]] = 0; } } } Histogram = res; if (Histogram.Count < 9) CreatePallette(Histogram.Count, "Diverging", "BrBG", false); }