private IWebResponse GetTableResponse(string address) { var components = UrlHelpers.CrackUrl(address); Content content = components["content"].DescriptionToEnum <Content>(); var count = 1; var objIds = components.GetValues("filter_objid"); if (objIds != null) { count = objIds.Length; } switch (content) { case Content.Sensors: var type = components["filter_type"] ?? "aggregation"; if (type.StartsWith("@sub(")) { type = type.Substring(5, type.Length - 6); } return(new SensorResponse(Enumerable.Range(0, count).Select(i => new SensorItem(typeRaw: type)).ToArray())); case Content.Channels: return(new ChannelResponse(new ChannelItem())); default: throw new NotImplementedException($"Unknown content '{content}' requested from {nameof(SensorFactorySourceResponse)}"); } }
private string GetSystemInfo(string address) { var components = UrlHelpers.CrackUrl(address); switch (components["category"].DescriptionToEnum <SystemInfoType>()) { case SystemInfoType.System: return(GetResponse(SystemInfoType.System)); case SystemInfoType.Hardware: return(GetResponse(SystemInfoType.Hardware)); case SystemInfoType.Software: return(GetResponse(SystemInfoType.Software)); case SystemInfoType.Processes: return(GetResponse(SystemInfoType.Processes)); case SystemInfoType.Services: return(GetResponse(SystemInfoType.Services)); case SystemInfoType.Users: return(GetResponse(SystemInfoType.Users)); default: throw new NotImplementedException(); } }
private IWebResponse GetTableResponse(string address) { var components = UrlHelpers.CrackUrl(address); Content content = components["content"].ToEnum <Content>(); switch (content) { case Content.Sensors: if (components["filter_objid"] == "1") { return(new SensorResponse()); } if (countOverride != null && countOverride[Content.Sensors] == 0) { return(new SensorResponse()); } return(new SensorResponse(new SensorItem())); case Content.Channels: return(new ChannelResponse(new ChannelItem())); case Content.Triggers: return(new NotificationTriggerResponse(NotificationTriggerItem.StateTrigger())); case Content.Notifications: return(new NotificationActionResponse(new NotificationActionItem("301"))); default: throw new NotImplementedException($"Unknown content '{content}' requested from {nameof(SetNotificationTriggerResponse)}"); } }
private string GetTableText(string address) { var components = UrlHelpers.CrackUrl(address); var content = MultiTypeResponse.GetContent(address); switch (content) { case Content.Triggers: return(base.GetResponseText(ref address)); case Content.Channels: if (Convert.ToInt32(components["id"]) >= 4000) { return(new ChannelResponse(channels).GetResponseText(ref address)); } return(new ChannelResponse().GetResponseText(ref address)); case Content.Notifications: return(new NotificationActionResponse(new NotificationActionItem("301"), new NotificationActionItem("302"), new NotificationActionItem("303")).GetResponseText(ref address)); case Content.Schedules: return(new ScheduleResponse(new ScheduleItem()).GetResponseText(ref address)); default: throw new NotImplementedException($"Unknown content '{content}' requested from {nameof(NotificationTriggerResponse)}"); } }
private void ValidateHttpResponse(HttpResponseMessage response, string responseText) { if (response.StatusCode == HttpStatusCode.BadRequest) { var xDoc = XDocument.Parse(responseText); var errorMessage = xDoc.Descendants("error").First().Value; throw new PrtgRequestException($"PRTG was unable to complete the request. The server responded with the following error: {errorMessage}"); } else if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new HttpRequestException("Could not authenticate to PRTG; the specified username and password were invalid."); } response.EnsureSuccessStatusCode(); if (response.RequestMessage?.RequestUri?.AbsolutePath == "/error.htm") { var errorUrl = response.RequestMessage.RequestUri.ToString(); var queries = UrlHelpers.CrackUrl(errorUrl); var errorMsg = queries["errormsg"]; throw new PrtgRequestException($"PRTG was unable to complete the request. The server responded with the following error: {errorMsg}"); } }
private string GetSetObjectPropertyResponse(string address) { var queries = UrlHelpers.CrackUrl(address); PropertyInfo info; if (typeof(TObjectProperty) == typeof(ObjectProperty)) { info = BaseSetObjectPropertyParameters <TObjectProperty> .GetPropertyInfoViaTypeLookup((Enum)(object)property); } else if (typeof(TObjectProperty) == typeof(ChannelProperty)) { info = BaseSetObjectPropertyParameters <TObjectProperty> .GetPropertyInfoViaPropertyParameter <Channel>((Enum)(object)property); } else { throw new NotImplementedException($"Handler for object property type {nameof(TObjectProperty)} is not implemented"); } var queryName = BaseSetObjectPropertyParameters <TObjectProperty> .GetParameterNameStatic((Enum)(object)property, info); if (typeof(TObjectProperty) == typeof(ChannelProperty)) { queryName += "1"; //Channel ID used for tests } var val = queries[queryName]; Assert.IsTrue(val == expectedValue, $"The value of property '{property.ToString().ToLower()}' did not match the expected value. Expected '{expectedValue}', received: '{val}'"); return("OK"); }
protected override IWebResponse GetResponse(ref string address, string function) { if (function == nameof(XmlFunction.TableData)) { var components = UrlHelpers.CrackUrl(address); Content content = components["content"].ToEnum <Content>(); if (content == Content.Messages) { if (components["columns"] != "objid,name") { components.Remove("content"); components.Remove("columns"); components.Remove("username"); components.Remove("passhash"); if (components["start"] != null) { components.Remove("start"); } var filtered = HttpUtility.UrlDecode(components.ToString()); if (filtered != str) { Assert.Fail($"Address was '{filtered}' instead of '{str}'"); } } } } return(base.GetResponse(ref address, function)); }
public static Content GetContent(string address) { var components = UrlHelpers.CrackUrl(address); Content content = components["content"].ToEnum <Content>(); return(content); }
public IWebResponse GetResponse(string address, string function) { var components = UrlHelpers.CrackUrl(address); Content content = components["content"].DescriptionToEnum <Content>(); requestNum++; return(GetResponse(address, content)); }
private IWebResponse GetTableResponse(ref string address, string function) { var components = UrlHelpers.CrackUrl(address); Content content = components["content"].DescriptionToEnum <Content>(); IncrementCount(content); return(base.GetResponse(ref address, function)); }
private string GetResponseText(ref string address, List <T> list) { var queries = UrlHelpers.CrackUrl(address); List <XElement> xmlList; var count = list.Count; if (queries["count"] != null && queries["count"] != "*") { var c = Convert.ToInt32(queries["count"]); var streaming = queries["start"] != null && Convert.ToInt32(queries["start"]) % 500 == 0 || IsStreaming(); var streamingLogs = queries["start"] != null && queries["content"] == "messages" && Convert.ToInt32(queries["start"]) % 500 == 1 || IsStreaming(); if ((c < list.Count && c > 0 || c == 0 || !streaming && !streamingLogs) && !(queries["content"] == "messages" && c == 1) || IsStreaming()) { count = c; var skip = 0; if (queries["start"] != null) { skip = Convert.ToInt32(queries["start"]); if (queries["content"] == "messages") { skip--; } } xmlList = list.Skip(skip).Take(count).Select(GetItem).ToList(); } else { xmlList = list.Select(GetItem).ToList(); } } else { xmlList = list.Select(GetItem).ToList(); } var xml = new XElement(rootName, new XAttribute("listend", 1), new XAttribute("totalcount", list.Count), new XElement("prtg-version", "1.2.3.4"), xmlList ); return(xml.ToString()); }
private string GetUrlInternal(string u, int i, Enum[] streamOrder) { var parts = UrlHelpers.CrackUrl(u); var keys = GetKeys(parts); var firstIndexCandidates = GetFirstIndexCandidates(keys, streamOrder); var firstIndex = firstIndexCandidates.Cast <int?>().FirstOrDefault(ix => ix > -1) ?? -1; var newKeys = keys.Select((k, ix) => SwapUrl(keys, firstIndex, parts, k, ix, streamOrder)).Where(p => p != null).ToList(); var joined = string.Join("&", newKeys); return($"https://prtg.example.com/api/table.xml?{joined}"); }
private IWebResponse GetTableResponse(ref string address, string function) { var components = UrlHelpers.CrackUrl(address); Content c; Content?content = null; if (Enum.TryParse(components["content"], true, out c)) { content = c; } var count = GetCount(components, content); //Hack to make test "forces streaming with a date filter and returns no results" work if (content == Content.Messages && count == 0 && components["columns"] == "objid,name") { count = 501; address = address.Replace("count=1", "count=501"); } if (function == nameof(XmlFunction.HistoricData)) { return(new SensorHistoryResponse(GetItems(i => new SensorHistoryItem(), count))); } switch (content) { case Content.Sensors: return(Sensors(i => new SensorItem(name: $"Volume IO _Total{i}", type: "Sensor Factory", objid: (4000 + i).ToString()), count)); case Content.Devices: return(Devices(i => new DeviceItem(name: $"Probe Device{i}", objid: (3000 + i).ToString()), count)); case Content.Groups: return(Groups(i => new GroupItem(name: $"Windows Infrastructure{i}", totalsens: "2", groupnum: "0", objid: (2000 + i).ToString()), count)); case Content.ProbeNode: return(Probes(i => new ProbeItem(name: $"127.0.0.1{i}", objid: (1000 + i).ToString()), count)); case Content.Messages: return(Messages(i => new MessageItem($"WMI Remote Ping{i}"), count)); case Content.Notifications: return(new NotificationActionResponse(new NotificationActionItem())); case Content.Schedules: return(Schedules(i => new ScheduleItem(), count)); case Content.Channels: return(new ChannelResponse(new ChannelItem())); default: throw new NotImplementedException($"Unknown content '{content}' requested from {nameof(MultiTypeResponse)}"); } }
private IWebResponse GetRawObjectProperty(string address) { var components = UrlHelpers.CrackUrl(address); if (components["name"] == "name") { return(new RawPropertyResponse("testName")); } if (components["name"] == "active") { return(new RawPropertyResponse("1")); } if (components["name"] == "tags") { return(new RawPropertyResponse("tag1 tag2")); } if (components["name"] == "accessgroup") { return(new RawPropertyResponse("1")); } if (components["name"] == "intervalgroup") { return(new RawPropertyResponse(null)); } if (components["name"] == "comments") { return(new RawPropertyResponse("Do not turn off!")); } if (components["name"] == "banana") { return(new RawPropertyResponse("(Property not found)")); } components.Remove("username"); components.Remove("passhash"); components.Remove("id"); throw new NotImplementedException($"Unknown raw object property '{components[0]}' passed to {GetType().Name}"); }
private IWebResponse GetTableResponse(string address) { var components = UrlHelpers.CrackUrl(address); Content content = components["content"].DescriptionToEnum <Content>(); switch (content) { case Content.Probes: return(GetProbeResponse()); case Content.Logs: return(GetMessageResponse()); default: throw new NotImplementedException($"Unknown content '{content}' requested from {nameof(RestartProbeResponse)}"); } }
private IWebResponse GetObjectDataResponse(string address) { var components = UrlHelpers.CrackUrl(address); var objectType = components["objecttype"].ToEnum <ObjectType>(); switch (objectType) { case ObjectType.Notification: return(new NotificationActionResponse(new NotificationActionItem())); case ObjectType.Schedule: return(new ScheduleResponse()); default: throw new NotImplementedException($"Unknown object type '{objectType}' requested from {nameof(MultiTypeResponse)}"); } }
private IWebResponse GetObjectDataResponse(string address) { var components = UrlHelpers.CrackUrl(address); var objectType = components["objecttype"].ToEnum <ObjectType>(); switch (objectType) { case ObjectType.Sensor: return(new SensorSettingsResponse()); case ObjectType.Device: return(new DeviceSettingsResponse()); default: throw new NotImplementedException($"Unknown object type '{objectType}' requested from {nameof(MultiTypeResponse)}"); } }
protected override IWebResponse GetResponse(ref string address, string function) { if (function == nameof(JsonFunction.GetStatus)) { return(new ServerStatusResponse(new ServerStatusItem())); } var queries = UrlHelpers.CrackUrl(address); queries.Remove("id"); queries.Remove("username"); queries.Remove("passhash"); if (property == ChannelProperty.LimitsEnabled) { if (Convert.ToBoolean(value)) { AssertCollectionLength(address, queries, 1); KeyExistsWithCorrectValue(queries, "limitmode", Convert.ToInt32(value)); } else { KeyExistsWithCorrectValue(queries, "limitmode", Convert.ToInt32(value)); KeyExistsWithCorrectValue(queries, "limitmaxerror", string.Empty); KeyExistsWithCorrectValue(queries, "limitmaxwarning", string.Empty); KeyExistsWithCorrectValue(queries, "limitminerror", string.Empty); KeyExistsWithCorrectValue(queries, "limitminwarning", string.Empty); KeyExistsWithCorrectValue(queries, "limiterrormsg", string.Empty); KeyExistsWithCorrectValue(queries, "limitwarningmsg", string.Empty); } } else if (property == ChannelProperty.UpperErrorLimit) { AssertCollectionLength(address, queries, 2); KeyExistsWithCorrectValue(queries, "limitmode", "1"); KeyExistsWithCorrectValue(queries, "limitmaxerror", value); } else { throw new NotImplementedException($"Test code for property '{property}' is not implemented."); } return(new BasicResponse(string.Empty)); }
private void ValidateHttpResponse(HttpResponseMessage response, string responseText) { if (response.StatusCode == HttpStatusCode.BadRequest) { var xDoc = XDocument.Parse(responseText); var errorMessage = xDoc.Descendants("error").First().Value; throw new PrtgRequestException($"PRTG was unable to complete the request. The server responded with the following error: {errorMessage}"); } else if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new HttpRequestException("Could not authenticate to PRTG; the specified username and password were invalid."); } response.EnsureSuccessStatusCode(); if (response.RequestMessage?.RequestUri?.AbsolutePath == "/error.htm") { var errorUrl = response.RequestMessage.RequestUri.ToString(); var queries = UrlHelpers.CrackUrl(errorUrl); var errorMsg = queries["errormsg"]; errorMsg = errorMsg.Replace("<br/><ul><li>", " ").Replace("</li></ul><br/>", " "); throw new PrtgRequestException($"PRTG was unable to complete the request. The server responded with the following error: {errorMsg}"); } if (responseText.StartsWith("<div class=\"errormsg\">")) //Example: GetProbeProperties specifying a content type of Probe instead of ProbeNode { var msgEnd = responseText.IndexOf("</h3>"); var substr = responseText.Substring(0, msgEnd); var substr1 = Regex.Replace(substr, "\\.</.+?><.+?>", ". "); var regex = new Regex("<.+?>"); var newStr = regex.Replace(substr1, ""); throw new PrtgRequestException($"PRTG was unable to complete the request. The server responded with the following error: {newStr}"); } }
private string GetResponseText(ref string address, List <T> list) { var queries = UrlHelpers.CrackUrl(address); List <XElement> xmlList = null; var count = list.Count; if (queries["count"] != null && queries["count"] != "*") { var c = Convert.ToInt32(queries["count"]); if (c < list.Count && c > 0 || c == 0) { count = c; xmlList = list.Take(count).Select(GetItem).ToList(); if (c == 0) { count = list.Count; } } else { xmlList = list.Select(GetItem).ToList(); } } else { xmlList = list.Select(GetItem).ToList(); } var xml = new XElement(rootName, new XAttribute("listend", 1), new XAttribute("totalcount", count), new XElement("prtg-version", "1.2.3.4"), xmlList ); return(xml.ToString()); }
internal static void ValidateSensorTargetProgressResult(SensorTargetProgress p) { if (p.TargetUrl.StartsWith("addsensorfailed")) { var parts = UrlHelpers.CrackUrl(p.TargetUrl); var message = parts["errormsg"]; if (message != null) { if (message.StartsWith("Incomplete connection settings")) { throw new PrtgRequestException("Failed to retrieve data from device; required credentials for sensor type may be missing. See PRTG UI for further details."); } throw new PrtgRequestException($"An exception occurred while trying to resolve sensor targets: {message}"); } throw new PrtgRequestException("An unspecified error occurred while trying to resolve sensor targets. Check the Device Host is still valid or try adding targets with the PRTG UI"); } }
public string GetResponseText(string address) { var queries = UrlHelpers.CrackUrl(address); queries.Remove("id"); queries.Remove("username"); queries.Remove("passhash"); if (property == ChannelProperty.LimitsEnabled) { if (Convert.ToBoolean(value)) { AssertCollectionLength(address, queries, 1); KeyExistsWithCorrectValue(queries, "limitmode", Convert.ToInt32(value)); } else { KeyExistsWithCorrectValue(queries, "limitmode", Convert.ToInt32(value)); KeyExistsWithCorrectValue(queries, "limitmaxerror", string.Empty); KeyExistsWithCorrectValue(queries, "limitmaxwarning", string.Empty); KeyExistsWithCorrectValue(queries, "limitminerror", string.Empty); KeyExistsWithCorrectValue(queries, "limitminwarning", string.Empty); KeyExistsWithCorrectValue(queries, "limiterrormsg", string.Empty); KeyExistsWithCorrectValue(queries, "limitwarningmsg", string.Empty); } } else if (property == ChannelProperty.UpperErrorLimit) { AssertCollectionLength(address, queries, 2); KeyExistsWithCorrectValue(queries, "limitmode", "1"); KeyExistsWithCorrectValue(queries, "limitmaxerror", value); } else { throw new NotImplementedException($"Test code for property '{property}' is not implemented."); } return("OK"); }
private IWebResponse GetTableResponse(string address, string function, bool async) { var components = UrlHelpers.CrackUrl(address); Content?content; try { content = components["content"].DescriptionToEnum <Content>(); } catch { content = null; } var count = GetCount(components, content); //Hack to make test "forces streaming with a date filter and returns no results" work if (content == Content.Logs && count == 0 && components["columns"] == "objid,name") { count = 501; address = address.Replace("count=1", "count=501"); } if (function == nameof(XmlFunction.HistoricData)) { return(new SensorHistoryResponse(GetItems(i => new SensorHistoryItem(), count))); } var columns = components["columns"]?.Split(','); switch (content) { case Content.Sensors: return(Sensors(CreateSensor, count, columns, address, async)); case Content.Devices: return(Devices(CreateDevice, count, columns, address, async)); case Content.Groups: return(Groups(CreateGroup, count, columns, address, async)); case Content.Probes: return(Probes(CreateProbe, count, columns, address, async)); case Content.Logs: if (IsGetTotalLogs(address)) { return(TotalLogsResponse()); } return(Messages(i => new MessageItem($"WMI Remote Ping{i}"), count)); case Content.History: return(new ModificationHistoryResponse(new ModificationHistoryItem())); case Content.Notifications: return(Notifications(CreateNotification, count)); case Content.Schedules: return(Schedules(CreateSchedule, count)); case Content.Channels: return(new ChannelResponse(GetItems(Content.Channels, i => new ChannelItem(), 1))); case Content.Objects: return(Objects(address, function, components)); default: throw new NotImplementedException($"Unknown content '{content}' requested from {nameof(MultiTypeResponse)}"); } }
protected virtual IWebResponse GetResponse(ref string address, string function) { switch (function) { case nameof(XmlFunction.TableData): case nameof(XmlFunction.HistoricData): return(GetTableResponse(ref address, function)); case nameof(CommandFunction.Pause): case nameof(CommandFunction.PauseObjectFor): return(new BasicResponse("<a data-placement=\"bottom\" title=\"Resume\" href=\"#\" onclick=\"var self=this; _Prtg.objectTools.pauseObject.call(this,'1234',1);return false;\"><i class=\"icon-play icon-dark\"></i></a>")); case nameof(HtmlFunction.ChannelEdit): return(new ChannelResponse(new ChannelItem())); case nameof(CommandFunction.DuplicateObject): address = "https://prtg.example.com/public/login.htm?loginurl=/object.htm?id=9999&errormsg="; return(new BasicResponse(string.Empty)); case nameof(HtmlFunction.EditSettings): return(new BasicResponse(string.Empty)); case nameof(JsonFunction.GetStatus): return(new ServerStatusResponse(new ServerStatusItem())); case nameof(JsonFunction.Triggers): return(new TriggerOverviewResponse()); case nameof(JsonFunction.SensorTypes): return(new SensorTypeResponse()); case nameof(HtmlFunction.ObjectData): return(GetObjectDataResponse(address)); case nameof(XmlFunction.GetObjectProperty): case nameof(XmlFunction.GetObjectStatus): return(GetRawObjectProperty(address)); case nameof(CommandFunction.AddSensor2): newSensorType = UrlHelpers.CrackUrl(address)["sensortype"].ToEnum <SensorType>(); address = "http://prtg.example.com/controls/addsensor3.htm?id=9999&tmpid=2"; return(new BasicResponse(string.Empty)); case nameof(HtmlFunction.EditNotification): return(new NotificationActionResponse(new NotificationActionItem())); case nameof(JsonFunction.GetAddSensorProgress): var progress = hitCount[function] % 2 == 0 ? 100 : 50; return(new BasicResponse($"{{\"progress\":\"{progress}\",\"targeturl\":\" /addsensor4.htm?id=4251&tmpid=119\"}}")); case nameof(HtmlFunction.AddSensor4): return(GetSensorTargetResponse()); case nameof(CommandFunction.AcknowledgeAlarm): case nameof(CommandFunction.AddSensor5): case nameof(CommandFunction.AddDevice2): case nameof(CommandFunction.AddGroup2): case nameof(CommandFunction.ClearCache): case nameof(CommandFunction.DeleteObject): case nameof(HtmlFunction.RemoveSubObject): case nameof(CommandFunction.DiscoverNow): case nameof(CommandFunction.LoadLookups): case nameof(CommandFunction.MoveObjectNow): case nameof(CommandFunction.RecalcCache): case nameof(CommandFunction.Rename): case nameof(CommandFunction.RestartServer): case nameof(CommandFunction.RestartProbes): case nameof(CommandFunction.ReloadFileLists): case nameof(CommandFunction.SaveNow): case nameof(CommandFunction.ScanNow): case nameof(CommandFunction.SetPosition): case nameof(CommandFunction.Simulate): case nameof(CommandFunction.SortSubObjects): return(new BasicResponse(string.Empty)); default: throw GetUnknownFunctionException(function); } }
private IWebResponse GetTableResponse(ref string address, string function) { var components = UrlHelpers.CrackUrl(address); Content content = components["content"].DescriptionToEnum <Content>(); totalRequestCount++; if (skip != null) { if (skip.Any(i => i == totalRequestCount)) { return(base.GetResponse(ref address, function)); } } else { if (start > 1) { start--; return(base.GetResponse(ref address, function)); } } requestCount++; var leading = LeadingSpace ? " " : ""; int count; //1: Before //2: After //3: Before //4: After //5: Before //6: After //Every odd request (the first request) returns 2; the second request returns 2 if (requestCount % 2 != 0) { count = 2; if (flip) { LeadingSpace = true; flip = false; } } else { count = multiple ? 4 : 3; if (LeadingSpace) { flip = true; LeadingSpace = false; } } switch (content) { case Content.Sensors: return(new SensorResponse(GetItems(i => new SensorItem(name: $"{leading}Volume IO _Total{i}", objid: (1000 + i).ToString()), count))); case Content.Devices: return(new DeviceResponse(GetItems(i => new DeviceItem(name: $"Probe Device{i}", objid: (1000 + i).ToString()), count))); case Content.Groups: return(new GroupResponse(GetItems(i => new GroupItem(name: $"Windows Infrastructure{i}", objid: (1000 + i).ToString()), count))); case Content.Notifications: totalRequestCount--; requestCount--; return(new NotificationActionResponse(new NotificationActionItem("301"))); case Content.Triggers: return(new NotificationTriggerResponse( GetItems( i => NotificationTriggerItem.StateTrigger(onNotificationAction: $"301|Email to all members of group PRTG Users Group {i}", subId: i.ToString(), parentId: "1001"), count ) )); case Content.Schedules: totalRequestCount--; requestCount--; return(new ScheduleResponse(new ScheduleItem())); default: throw new NotImplementedException($"Unknown content '{content}' requested from {nameof(DiffBasedResolveResponse)}"); } }