Exemplo n.º 1
0
        private static async Task <string> RequestAsync(HttpRequestMessage request, RequestVersion requestVersion)
        {
            var shortUrl = request.RequestUri.OriginalString; //get FULL url

            request.RequestUri = new Uri(GetFullUrl(shortUrl, requestVersion));

            logger.InfoStartRequest(request);                              //logging

            request.Headers.Add("User-Agent", AppName + " %40" + DevName); //%40 - @
            if (IsAuthorized)
            {
                if (AutoRefreshToken && IsTokenExpired)
                {
                    await RefreshTokenAsync().ConfigureAwait(false);
                }
                request.Headers.Add("Authorization", "Bearer " + OAuth2Token.AccessToken);
            }

            HttpResponseMessage response;

            using (client = new HttpClient())
            {
                response = await client.SendAsync(request).ConfigureAwait(false);
            }

            if (response.IsSuccessStatusCode)
            {
                logger.InfoDoneRequest(request); //logging
                return(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
            }

            logger.WarnNotOkResponse(request, response); //logging

            return(null);
        }
Exemplo n.º 2
0
        private async Task AddSensorAsync(RequestVersion version)
        {
            var builder = new StringBuilder();

            builder.Append("https://prtg.example.com/addsensor5.htm?name_=XML+Custom+EXE%2FScript+Sensor&priority_=3&inherittriggers_=1&intervalgroup=1&interval_=60%7C60+seconds");
            builder.Append("&errorintervalsdown_=1&tags_=xmlexesensor&exefile_=test.ps1%7Ctest.ps1%7C%7C&exeparams_=&environment_=0");
            builder.Append("&usewindowsauthentication_=0&mutexname_=&timeout_=60&writeresult_=0&sensortype=exexml&id=1001&");

            var auth = version == RequestVersion.v18_1 ? "tmpid=2" : "username=username&passhash=12345678";

            builder.Append(auth);

            var urls = new List <string>
            {
                ////We don't request status since we already injected our version
                UnitRequest.BeginAddSensorQuery(1001, "exexml"),
                builder.ToString()
            };

            if (version == RequestVersion.v18_1)
            {
                urls.Add(UnitRequest.AddSensorProgress(1001, 2, true));
            }

            var parameters = new ExeXmlSensorParameters("test.ps1");

            await ExecuteAsync(
                async c => await c.AddSensorAsync(1001, parameters, false),
                urls.ToArray(),
                version : version
                );
        }
Exemplo n.º 3
0
        internal static PrtgClient Initialize_Client(IWebResponse response, RequestVersion version)
        {
            var client = Initialize_Client(response);

            SetVersion(client, version);

            return(client);
        }
Exemplo n.º 4
0
        internal VersionClient GetVersionClient(RequestVersion version)
        {
            switch (version)
            {
            case RequestVersion.v18_1:
                return(new VersionClient18_1(this));

            case RequestVersion.v17_4:
                return(new VersionClient17_4(this));

            default:
                return(new VersionClient(version, this));
            }
        }
Exemplo n.º 5
0
        internal VersionClient GetVersionClient()
        {
            RequestVersion max = RequestVersion.v14_4;

            foreach (var pair in VersionMap.Map)
            {
                if (Version >= pair.Value)
                {
                    max = pair.Key;
                }
            }

            return(GetVersionClient(max));
        }
Exemplo n.º 6
0
        internal static async Task <T> PutAsync <T>(string url, string args = null, RequestVersion requestVersion = RequestVersion.API_V1)
        {
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, url);

            if (args != null)
            {
                httpRequestMessage.Content = new StringContent(args, Encoding.UTF8, "application/json");
            }
            //httpRequestMessage.Headers.Add("Content-Type", "application/json"); (need?)

            var response = await RequestAsync(httpRequestMessage, requestVersion).ConfigureAwait(false);

            return(HandleResponse <T>(response, "PutAsync", url, args));
        }
Exemplo n.º 7
0
        private async Task AddSensorWithExcessiveItemsAsync(RequestVersion version)
        {
            var servicesClient = Initialize_Client(new WmiServiceTargetResponse());
            var services       = await servicesClient.Targets.GetWmiServicesAsync(1001);

            Assert.IsTrue(services.Count > 30);

            var client = GetAddExcessiveSensorClient(services, version);

            var parameters = new WmiServiceSensorParameters(services);

            await client.Item1.AddSensorAsync(1001, parameters, false);

            client.Item2.AssertFinished();
        }
Exemplo n.º 8
0
        private static string GetFullUrl(string shortUrl, RequestVersion requestVersion)
        {
            switch (requestVersion)
            {
            case RequestVersion.API_V1:
                return(API_DOMAIN + shortUrl);

            case RequestVersion.API_V2:
                return(API_DOMAIN + "/v2" + shortUrl);

            case RequestVersion.SITE:
                return(SITE_DOMAIN + shortUrl);

            default:
                return(null);
            }
        }
Exemplo n.º 9
0
        public void ParseFirstLine()
        {
            if (this.FirstHeader.Length == 0)
            {
                throw new HttpHeaderException("HTTP Header is empty");
            }

            String lHeaderLine          = this.FirstHeader;
            var    lRequestHeaderValues = lHeaderLine.Split(" ");

            if (lRequestHeaderValues.Count < 3)
            {
                throw new HttpHeaderException("Invalid HTTP Header Line \"" + lHeaderLine + "\"");
            }

            if (lHeaderLine.StartsWith("HTTP/"))
            {
                // HTTP Response
                try
                {
                    //this.HttpCode = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), lRequestHeaderValues[1], true);
                    this.HttpCode = (HttpStatusCode)Convert.ToInt32(lRequestHeaderValues[1]);
                }
                catch (ArgumentException)
                {
                    this.HttpCode = HttpStatusCode.OK;
                }
            }
            else
            {
                // HTTP Request
                this.RequestType    = lRequestHeaderValues[0];
                this.RequestPath    = lRequestHeaderValues[1];
                this.RequestVersion = lRequestHeaderValues[2];

                if (this.RequestVersion.StartsWith("HTTP/"))
                {
                    this.RequestVersion = RequestVersion.Substring(5);
                }
            }
        }
Exemplo n.º 10
0
        private static void SetVersion(PrtgClient client, RequestVersion version)
        {
            var f = client.GetInternalFieldInfo("version");

            f.SetValue(client, new Version(version.ToString().TrimStart('v').Replace('_', '.')));
        }
Exemplo n.º 11
0
 internal VersionClient(RequestVersion version, PrtgClient client)
 {
     Version     = version;
     this.client = client;
 }
Exemplo n.º 12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="VersionAttribute"/> class.
 /// </summary>
 /// <param name="version">The PRTG version this attribute pertains to.</param>
 internal VersionAttribute(string version)
 {
     Version = version.ToEnum <RequestVersion>();
 }
Exemplo n.º 13
0
        internal static async Task <T> DeleteAsync <T>(string url, RequestVersion requestVersion = RequestVersion.API_V1)
        {
            var response = await RequestAsync(new HttpRequestMessage(HttpMethod.Delete, url), requestVersion).ConfigureAwait(false);

            return(HandleResponse <T>(response, "DeleteAsync", url));
        }
Exemplo n.º 14
0
        private Tuple <PrtgClient, AddressValidatorResponse> GetAddExcessiveSensorClient(List <WmiServiceTarget> services, RequestVersion version)
        {
            var formats = services.Select(s => "service__check=" + WebUtility.UrlEncode(((ISerializable)s).GetSerializedFormat())).ToList();

            var urls = new List <string>();

            //We don't request status since we already injected our version
            urls.Add(UnitRequest.BeginAddSensorQuery(1001, "wmiservice"));

            for (int i = 0; i < formats.Count; i += 30)
            {
                var thisRequest = formats.Skip(i).Take(30);

                var str = string.Join("&", thisRequest);

                var auth = version == RequestVersion.v18_1 ? "tmpid=2" : "username=username&passhash=12345678";

                var url = $"https://prtg.example.com/addsensor5.htm?name_=Service&priority_=3&inherittriggers_=1&intervalgroup=1&interval_=60%7C60+seconds&errorintervalsdown_=1&tags_=wmiservicesensor+servicesensor&restart_=0&monitorchange_=1&monitorextended_=0&service_=1&sensortype=wmiservice&{str}&id=1001&{auth}";

                urls.Add(url);

                if (i == 0 && version == RequestVersion.v18_1)
                {
                    urls.Add(UnitRequest.AddSensorProgress(1001, 2, true));
                }
            }

#pragma warning disable 618
            var response = new AddressValidatorResponse(urls.ToArray(), true);

            var client = Initialize_Client(response, version);
#pragma warning restore 618

            return(Tuple.Create(client, response));
        }
Exemplo n.º 15
0
 internal VersionClient17_4(RequestVersion version, PrtgClient client) : base(version, client)
 {
 }
Exemplo n.º 16
0
        private void SetChannelProperty(Tuple <ChannelProperty, object, int?[][]> config, RequestVersion version, string[] addresses)
        {
            var property = config.Item1;
            var val      = config.Item2;
            var matrix   = config.Item3;

            var channels = matrix.Select(CreateChannel).ToList();

            var client = Initialize_Client(new AddressValidatorResponse(addresses.Select(a => $"https://prtg.example.com/editsettings?{a}&username=username&passhash=12345678").ToArray(), true));

            SetVersion(client, version);

            client.GetVersionClient(new object[] { property }).SetChannelProperty(channels.Select(c => c.SensorId).ToArray(), 2, channels, new [] { new ChannelParameter(property, val) });
        }
Exemplo n.º 17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="VersionAttribute"/> class.
 /// </summary>
 /// <param name="version">The PRTG version this attribute pertains to.</param>
 internal VersionAttribute(RequestVersion version)
 {
     Version = version;
 }
Exemplo n.º 18
0
        public static ESPPacket getPacket(PacketId _id)
        {
            ESPPacket rc = null;

            if (_id != null)
            {
                switch (_id)
                {
                //basic data
                case PacketId.reqVersion:
                    rc = new RequestVersion(Devices.UNKNOWN, Devices.UNKNOWN);
                    break;

                case PacketId.respVersion:
                    rc = new ResponseVersion(Devices.UNKNOWN);
                    break;

                case PacketId.reqSerialNumber:
                    rc = new RequestSerialNumber(Devices.UNKNOWN, Devices.UNKNOWN);
                    break;

                case PacketId.respSerialNumber:
                    rc = new ResponseSerialNumber(Devices.UNKNOWN);
                    break;

                case PacketId.reqUserBytes:
                    rc = new RequestUserBytes(Devices.UNKNOWN);
                    break;

                case PacketId.respUserBytes:
                    rc = new ResponseUserBytes(Devices.UNKNOWN);
                    break;

                case PacketId.reqWriteUserBytes:
                    rc = new RequestWriteUserBytes(null, Devices.UNKNOWN);
                    break;

                case PacketId.reqFactoryDefault:
                    rc = new RequestFactoryDefault(Devices.UNKNOWN, Devices.UNKNOWN);
                    break;

                case PacketId.reqDefaultSweepDefinitions:
                    rc = new RequestDefaultSweepDefinitions(Devices.UNKNOWN);
                    break;

                case PacketId.respDefaultSweepDefinition:
                    rc = new ResponseDefaultSweepDefinitions(Devices.UNKNOWN);
                    break;

                //custom sweep data
                case PacketId.reqWriteSweepDefinition:
                    rc = new RequestWriteSweepDefinition(null, Devices.UNKNOWN);
                    break;

                case PacketId.reqAllSweepDefinitions:
                    rc = new RequestAllSweepDefinitions(Devices.UNKNOWN);
                    break;

                case PacketId.respSweepDefinition:
                    rc = new ResponseSweepDefinitions(Devices.UNKNOWN);
                    break;

                case PacketId.reqSetSweepsToDefault:
                    rc = new RequestSetSweepsToDefault(Devices.UNKNOWN);
                    break;

                case PacketId.reqMaxSweepIndex:
                    rc = new RequestMaxSweepIndex(Devices.UNKNOWN);
                    break;

                case PacketId.respMaxSweepIndex:
                    rc = new ResponseMaxSweepIndex(Devices.UNKNOWN);
                    break;

                case PacketId.respSweepWriteResult:
                    rc = new ResponseSweepWriteResult(Devices.UNKNOWN);
                    break;

                case PacketId.reqSweepSections:
                    rc = new RequestSweepSections(Devices.UNKNOWN);
                    break;

                case PacketId.respSweepSections:
                    rc = new ResponseSweepSections(Devices.UNKNOWN);
                    break;

                //informational packets
                case PacketId.infDisplayData:
                    rc = new InfDisplayData(Devices.UNKNOWN);
                    break;

                case PacketId.reqTurnOffMainDisplay:
                    rc = new RequestTurnOffMainDisplay(Devices.UNKNOWN);
                    break;

                case PacketId.reqTurnOnMainDisplay:
                    rc = new RequestTurnOnMainDisplay(Devices.UNKNOWN);
                    break;

                case PacketId.reqMuteOn:
                    rc = new RequestMuteOn(Devices.UNKNOWN);
                    break;

                case PacketId.reqMuteOff:
                    rc = new RequestMuteOff(Devices.UNKNOWN);
                    break;

                case PacketId.reqChangeMode:
                    rc = new RequestChangeMode((byte)0, Devices.UNKNOWN);
                    break;

                case PacketId.reqStartAlertData:
                    rc = new RequestStartAlertData(Devices.UNKNOWN);
                    break;

                case PacketId.reqStopAlertData:
                    rc = new RequestStopAlertData(Devices.UNKNOWN);
                    break;

                case PacketId.respAlertData:
                    rc = new ResponseAlertData(Devices.UNKNOWN);
                    break;

                case PacketId.respDataReceived:
                    rc = new ResponseDataReceived(Devices.UNKNOWN);
                    break;

                case PacketId.reqBatteryVoltage:
                    rc = new RequestBatteryVoltage(Devices.UNKNOWN);
                    break;

                case PacketId.respBatteryVoltage:
                    rc = new ResponseBatteryVoltage(Devices.UNKNOWN);
                    break;

                //unspported and error
                case PacketId.respUnsupportedPacket:
                    rc = new ResponseUnsupported(Devices.UNKNOWN);
                    break;

                case PacketId.respRequestNotProcessed:
                    rc = new ResponseRequestNotProcessed(Devices.UNKNOWN);
                    break;

                case PacketId.infV1Busy:
                    rc = new InfV1Busy(Devices.UNKNOWN);
                    break;

                case PacketId.respDataError:
                    rc = new ResponseDataError(Devices.UNKNOWN);
                    break;

                //Savvy
                case PacketId.reqSavvyStatus:
                    rc = new RequestSavvyStatus(Devices.UNKNOWN, Devices.UNKNOWN);
                    break;

                case PacketId.respSavvyStatus:
                    rc = new ResponseSavvyStatus(Devices.UNKNOWN);
                    break;

                case PacketId.reqVehicleSpeed:
                    rc = new RequestVehicleSpeed(Devices.UNKNOWN, Devices.UNKNOWN);
                    break;

                case PacketId.respVehicleSpeed:
                    rc = new ResponseVehicleSpeed(Devices.UNKNOWN);
                    break;

                case PacketId.reqOverrideThumbwheel:
                    rc = new RequestOverrideThumbwheel(Devices.UNKNOWN, (byte)0, Devices.UNKNOWN);
                    break;

                case PacketId.reqSetSavvyUnmuteEnable:
                    rc = new RequestSetSavvyUnmute(Devices.UNKNOWN, false, Devices.UNKNOWN);
                    break;

                default:
                    rc = new UnknownPacket(Devices.UNKNOWN);
                    break;
                }
            }
            return(rc);
        }