Example #1
0
        public void TestValidateAddress()
        {
            var shippingAddress = GetDefaultShippingAddress();

            var validateAddress = new ValidateAddress()
            {
                ShippingAddress = shippingAddress,
                DeviceType      = SkuName.DataBox
            };
            var addressValidation = this.Client.Service.ValidateAddressMethod(TestConstants.DefaultResourceLocation,
                                                                              validateAddress);

            Assert.NotNull(addressValidation);
            Assert.NotNull(addressValidation.AlternateAddresses);
            Assert.NotNull(addressValidation.ValidationStatus);
            var validatedAddress = addressValidation.AlternateAddresses[0];

            Assert.Equal(AddressValidationStatus.Valid, addressValidation.ValidationStatus);
            Assert.Equal(shippingAddress.City, validatedAddress.City, true);
            Assert.Equal(shippingAddress.Country, validatedAddress.Country, true);
            Assert.Equal(shippingAddress.PostalCode, validatedAddress.PostalCode, true);
            Assert.Equal(shippingAddress.StateOrProvince, validatedAddress.StateOrProvince, true);
            Assert.Equal(shippingAddress.StreetAddress1, validatedAddress.StreetAddress1, true);
            Assert.Equal(shippingAddress.StreetAddress2, validatedAddress.StreetAddress2, true);
        }
Example #2
0
        public ActionResult Index()
        {
            var model = new ValidateAddress();

            model.RemoveExistingLop(DbUtil.Db, 0, ValidateAddress.Op);
            return(View(model));
        }
    public async Task Valid_Standardized_Resedintial_Address_Remove_StreetLine1_Successfully()
    {
        var request = new ValidateAddress(
            Guid.NewGuid().ToString(),
            new EasyKeys.Shipping.Abstractions.Address(
                "5 Hood Road",
                "Derry, NH 03038",
                "Derry",
                "IL",
                "03038",
                "US",
                false));

        var result = await _validator.ValidateAddressAsync(request);

        var proposed = result.ProposedAddress;

        Assert.NotNull(proposed);
        Assert.Equal("5 HOOD RD", proposed?.StreetLine);
        Assert.Equal(string.Empty, proposed?.StreetLine2);
        Assert.Equal("03038-2012", proposed?.PostalCode);

        // BUSINESS, RESIDENTIAL
        // MIXED (If it is a multi-tenant based address and contains both business and residential units.)
        // UNKNOWN (If just a zip code is provided, Address Validation Service returns 'unknown' for the business/residential classification)
        Assert.Equal("BUSINESS", result.ValidationBag.GetValueOrDefault("Classification"));

        // If the address returned includes the address state of "Standardized" and also if the attributes of Resolved = True,
        // DPV = True are present, then the address is likely a valid one.
        Assert.Equal("STANDARDIZED", result.ValidationBag.GetValueOrDefault("State"));
        Assert.True(Convert.ToBoolean(result.ValidationBag.GetValueOrDefault("Resolved")));
        Assert.True(Convert.ToBoolean(result.ValidationBag.GetValueOrDefault("DPV")));
    }
    public async Task NORMALIZED_Unknown_Address_Successfully()
    {
        var request = new ValidateAddress(
            Guid.NewGuid().ToString(),
            new EasyKeys.Shipping.Abstractions.Address(
                "ATTN John Smith 1800 ISLE PKWY",
                string.Empty,
                "BETTENDORF",
                "IA",
                "52722",
                "US",
                false));

        var result = await _validator.ValidateAddressAsync(request);

        var proposed = result.ProposedAddress;

        Assert.NotNull(proposed);
        Assert.Equal(string.Empty, proposed?.StreetLine);
        Assert.Equal(string.Empty, proposed?.StreetLine2);
        Assert.Equal("52722", proposed?.PostalCode);

        // BUSINESS, RESIDENTIAL
        // MIXED (If it is a multi-tenant based address and contains both business and residential units.)
        // UNKNOWN (If just a zip code is provided, Address Validation Service returns 'unknown' for the business/residential classification)
        Assert.Equal("UNKNOWN", result.ValidationBag.GetValueOrDefault("Classification"));

        // If the address returned includes the address state of "Standardized" and also if the attributes of Resolved = True,
        // DPV = True are present, then the address is likely a valid one.
        Assert.Equal("NORMALIZED", result.ValidationBag.GetValueOrDefault("State"));
        Assert.False(Convert.ToBoolean(result.ValidationBag.GetValueOrDefault("Resolved")));
        Assert.False(Convert.ToBoolean(result.ValidationBag.GetValueOrDefault("DPV")));
    }
Example #5
0
        public void StreetTypeValidation()
        {
            string st = "way";

            ValidateAddress.ValidateStreetTypes(st);

            Assert.IsTrue(ValidateAddress.ValidateStreetTypes(st), "Not properly validating street type");
        }
Example #6
0
    public async Task <int> RunAsync()
    {
        _logger.LogInformation("Main executed");

        // use this token for stopping the services
        _applicationLifetime.ApplicationStopping.ThrowIfCancellationRequested();

        // var address2 = new ValidateAddress(
        //                Guid.NewGuid().ToString(),
        //                new Shipping.Abstractions.Address(
        //                "One Microsoft Way",
        //                "",
        //                "Redmond",
        //                "Washington",
        //                "98052",
        //                "US",
        //                false));

        // var address2 = new ValidateAddress(
        //            Guid.NewGuid().ToString(),
        //            new Shipping.Abstractions.Address(
        //            "Mauerberger  Building",
        //            "2nd floor",
        //            "Technion City",
        //            "Haifa",
        //            "3200003",
        //            "IL",
        //            false));

        // var address2 = new ValidateAddress(
        //        Guid.NewGuid().ToString(),
        //        new Shipping.Abstractions.Address(
        //        "100 East Capitol Street",
        //        "Suite 1000",
        //        "Jackson",
        //        "MS",
        //        "39201",
        //        "US",
        //        false));
        var address2 = new ValidateAddress(
            Guid.NewGuid().ToString(),
            new Shipping.Abstractions.Address(
                "1500 S STRONG DR",
                "Apartment, suite, unit, etc. (optional)",
                "BLOOMINGTON",
                "IL",
                "47403-8741",
                "US",
                false));

        var result2 = await _validationClient.ValidateAddressAsync(address2);

        result2.ValidationBag.TryGetValue("State", out var v);
        _logger.LogInformation("{isVerified}", v);

        return(await Task.FromResult(0));
    }
 public ValidateAddress ValidateAddress()
 {
     if (!string.IsNullOrWhiteSpace(Url))
     {
         using (var client = new WebClient())
         {
             string          json            = client.DownloadString(Url);
             ValidateAddress validateAddress = JsonConvert.DeserializeObject <ValidateAddress>(json);
             return(validateAddress);
         }
     }
     else
     {
         throw new InvalidOperationException();
     }
 }
    private v4.AddressValidationRequest CreateRequest(ValidateAddress request)
    {
        var address = request.ProposedAddress;

        return(new v4.AddressValidationRequest
        {
            WebAuthenticationDetail = new v4.WebAuthenticationDetail
            {
                UserCredential = new v4.WebAuthenticationCredential
                {
                    Key = _options.FedExKey,
                    Password = _options.FedExPassword
                }
            },

            ClientDetail = new v4.ClientDetail
            {
                AccountNumber = _options.FedExAccountNumber,
                MeterNumber = _options.FedExMeterNumber
            },

            TransactionDetail = new v4.TransactionDetail
            {
                CustomerTransactionId = nameof(FedExAddressValidationProvider)
            },

            Version = new v4.VersionId(),
            AddressesToValidate = new v4.AddressToValidate[1]
            {
                new v4.AddressToValidate
                {
                    ClientReferenceId = request.Id,
                    Address = new v4.Address
                    {
                        StreetLines = address?.GetStreetLines(),
                        PostalCode = address?.PostalCode,
                        City = address?.City,
                        StateOrProvinceCode = address?.StateOrProvince,
                        CountryCode = address?.CountryCode
                    }
                }
            },

            InEffectAsOfTimestamp = DateTime.Now,
            InEffectAsOfTimestampSpecified = true
        });
    }
Example #9
0
        /// <summary>
        /// This method validates the customer shipping address and provide alternate addresses
        /// if any.
        /// </summary>
        private static void ValidateShippingAddress()
        {
            AddressType addressType     = AddressType.None;
            string      companyName     = "<company-name>";
            string      streetAddress1  = "<street-address-1>";
            string      streetAddress2  = "<street-address-2>";
            string      streetAddress3  = "<street-address-3>";
            string      postalCode      = "<postal-code>";
            string      city            = "<city>";
            string      stateOrProvince = "<state-or-province>";
            CountryCode countryCode     = CountryCode.US;

            ShippingAddress shippingAddress = new ShippingAddress()
            {
                AddressType     = addressType,
                CompanyName     = companyName,
                StreetAddress1  = streetAddress1,
                StreetAddress2  = streetAddress2,
                StreetAddress3  = streetAddress3,
                City            = city,
                StateOrProvince = stateOrProvince,
                PostalCode      = postalCode,
                Country         = countryCode.ToString(),
            };

            // Set location of the resource
            string location = "<location>";

            // Initializes a new instance of the DataBoxManagementClient class
            DataBoxManagementClient dataBoxManagementClient = InitializeDataBoxClient();

            dataBoxManagementClient.Location = location;

            ValidateAddress         validateAddress         = new ValidateAddress(shippingAddress, DeviceType.Pod);
            AddressValidationOutput addressValidationOutput = ServiceOperationsExtensions.ValidateAddressMethod(dataBoxManagementClient.Service, validateAddress);

            // Verify shipping address validation status
            CheckShippingAddressValidationResult(addressValidationOutput);
        }
Example #10
0
        public ActionResult Process(ValidateAddress model)
        {
            model.Validate(ModelState);

            if (!ModelState.IsValid) // show validation errors
            {
                return(View("Index", model));
            }

            model.UpdateLongRunningOp(DbUtil.Db, ValidateAddress.Op);
            if (model.ShowCount(DbUtil.Db))
            {
                return(View("Index", model)); // let them confirm by seeing the count and the tagname
            }
            if (!model.Started.HasValue)
            {
                DbUtil.LogActivity("Validate Address");
                model.Process(DbUtil.Db);
            }

            return(View(model));
        }
Example #11
0
 public AddressValidatedResponse(ValidateAddress message)
 {
     _message = message;
 }
        /// <summary>
        /// This method validates the customer shipping address and provide alternate
        /// addresses if any.
        /// </summary>
        /// <param name='location'>
        /// The location of the resource
        /// </param>
        /// <param name='shippingAddress'>
        /// Shipping address of the customer.
        /// </param>
        /// <param name='deviceType'>
        /// Device type to be used for the job. Possible values include: 'DataBox',
        /// 'DataBoxDisk', 'DataBoxHeavy'
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <AddressValidationOutput> > ValidateAddressMethodWithHttpMessagesAsync(string location, ShippingAddress shippingAddress, SkuName deviceType, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (location == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "location");
            }
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (shippingAddress == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "shippingAddress");
            }
            if (shippingAddress != null)
            {
                shippingAddress.Validate();
            }
            ValidateAddress validateAddress = new ValidateAddress();

            if (shippingAddress != null)
            {
                validateAddress.ShippingAddress = shippingAddress;
                validateAddress.DeviceType      = deviceType;
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("location", location);
                tracingParameters.Add("validateAddress", validateAddress);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "ValidateAddressMethod", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.DataBox/locations/{location}/validateAddress").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
            List <string> _queryParameters = new List <string>();

            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (validateAddress != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(validateAddress, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <AddressValidationOutput>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <AddressValidationOutput>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
 public static async Task <AddressValidationOutput> ValidateAddressMethodAsync(this IServiceOperations operations, string location, ValidateAddress validateAddress, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.ValidateAddressMethodWithHttpMessagesAsync(location, validateAddress, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 public static AddressValidationOutput ValidateAddressMethod(this IServiceOperations operations, string location, ValidateAddress validateAddress)
 {
     return(operations.ValidateAddressMethodAsync(location, validateAddress).GetAwaiter().GetResult());
 }
    public async Task <ValidateAddress> ValidateAddressAsync(ValidateAddress request, CancellationToken cancellationToken = default)
    {
        try
        {
            // don't waste resources
            if (!AddressAttributes.SupportedCountries.ContainsKey(request.OriginalAddress.CountryCode))
            {
                return(request);
            }

            var client = new v4.AddressValidationPortTypeClient(
                v4.AddressValidationPortTypeClient.EndpointConfiguration.AddressValidationServicePort,
                _options.Url);

            var wrap = CreateRequest(request);

            var serviceRequest = new v4.addressValidationRequest1(wrap);

            var reply = await client.addressValidationAsync(serviceRequest);

            if (reply.AddressValidationReply.HighestSeverity == v4.NotificationSeverityType.SUCCESS ||
                reply.AddressValidationReply.HighestSeverity == v4.NotificationSeverityType.NOTE ||
                reply.AddressValidationReply.HighestSeverity == v4.NotificationSeverityType.WARNING)
            {
                var result           = reply.AddressValidationReply;
                var addressResults   = result.AddressResults[0];
                var effectiveAddress = addressResults.EffectiveAddress;
                var parsedAddress    = addressResults.ParsedAddressPartsDetail;
                var lines            = effectiveAddress?.StreetLines ?? new string[1] {
                    string.Empty
                };

                request.ProposedAddress = new Address(
                    lines[0],
                    effectiveAddress?.City ?? string.Empty,
                    effectiveAddress?.StateOrProvinceCode ?? string.Empty,
                    effectiveAddress?.PostalCode ?? string.Empty,
                    effectiveAddress?.CountryCode ?? string.Empty,
                    effectiveAddress?.Residential ?? true);

                if (lines.Length == 2)
                {
                    request.ProposedAddress.StreetLine2 = lines[1];
                }

                request.ProposedAddress.IsResidential = addressResults.Classification switch
                {
                    v4.FedExAddressClassificationType.MIXED => false,
                    v4.FedExAddressClassificationType.BUSINESS => false,
                    _ => true,
                };

                if (!request.ValidationBag.ContainsKey("Classification"))
                {
                    request.ValidationBag.Add("Classification", addressResults.Classification.ToString());
                }

                if (!request.ValidationBag.ContainsKey("State"))
                {
                    request.ValidationBag.Add("State", addressResults.State.ToString());
                }

                foreach (var a in addressResults.Attributes)
                {
                    if (!request.ValidationBag.ContainsKey(a.Name))
                    {
                        request.ValidationBag.Add(a.Name, a.Value);
                    }
                }
            }
            else
            {
                var exMsg = string.Empty;
                foreach (var notification in reply.AddressValidationReply.Notifications)
                {
                    exMsg += notification.Message;
                    request.Errors.Add(new Error
                    {
                        Source      = notification.Source,
                        Number      = notification.Code,
                        Description = notification.Message
                    });
                }
            }
        }
        catch (Exception ex)
        {
            var exMsg = "FedExValidation client failed";
            _logger.LogError(ex, exMsg);
            request.InternalErrors.Add(ex?.Message ?? exMsg);
        }

        return(request);
    }
Example #16
0
File: p2t.cs Project: vsoul-km/p2t
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                DisplayHelp();
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Application is running without any arguments. Starting an interactive mode.");
                Console.ResetColor();
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.WriteLine("Please enter parameters following this step-by-step procedure:");
                Console.ResetColor();
                Console.WriteLine();

                while (true)
                {
                    Console.Write("Enter the IP address or the hostname to ping: ");
                    string pingAddress = Console.ReadLine();
                    if (string.IsNullOrEmpty(pingAddress))
                    {
                        continue;
                    }
                    if (pingAddress.Contains(" "))
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Wrong address.");
                        Console.ResetColor();
                        continue;
                    }

                    if (!ValidateAddress.Ip(pingAddress))
                    {
                        if (!ValidateAddress.HostName(pingAddress))
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Cannot resolve the address to IP address.");
                            Console.ResetColor();
                            continue;
                        }
                    }

                    CommandLineArguments.Address = pingAddress;
                    break;
                }

                while (true)
                {
                    Console.Write("Enter the interval between RTT in ms (default is 500 ms): ");
                    string pingInterval = Console.ReadLine();
                    if (string.IsNullOrEmpty(pingInterval))
                    {
                        break;
                    }
                    if (int.TryParse(pingInterval, out int result))
                    {
                        CommandLineArguments.PingRttInterval = result;
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Wrong interval between RTT.");
                        Console.ResetColor();
                        continue;
                    }
                    break;
                }

                while (true)
                {
                    Console.Write("Do you want to log ping to file (y/n)?: ");
                    string enableLogAnswer = Console.ReadLine();
                    if (enableLogAnswer != "y" && enableLogAnswer != "n")
                    {
                        continue;
                    }
                    if (enableLogAnswer == "y")
                    {
                        CommandLineArguments.LogEnabled = true;
                    }
                    break;
                }
            }

            if (args.Length > 0)
            {
                UtilityArguments arguments = new UtilityArguments(args);

                if (args[0].StartsWith("/?") || args[0].StartsWith("?"))
                {
                    DisplayHelp();
                    Environment.Exit(0);
                }

                if (args[0].StartsWith("-"))
                {
                    DisplayHelp();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Wrong address. Please use the correct address.");
                    Console.ResetColor();
                    Environment.Exit(0);
                }
                else
                {
                    CommandLineArguments.Address = args[0];
                }

                if (!string.IsNullOrEmpty(arguments.L))
                {
                    if (int.TryParse(arguments.L, out int result))
                    {
                        CommandLineArguments.PacketSize = result;
                    }
                    else
                    {
                        DisplayHelp();
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Error parsing argument -l");
                        Console.WriteLine(" Wrong packet payload size.");
                        Console.ResetColor();
                        Environment.Exit(0);
                    }
                }

                if (!string.IsNullOrEmpty(arguments.C))
                {
                    if (int.TryParse(arguments.C, out int result))
                    {
                        CommandLineArguments.PingCount = result;
                    }
                    else
                    {
                        DisplayHelp();
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Error parsing argument -c");
                        Console.WriteLine(" Wrong number of ping echo requests.");
                        Console.ResetColor();
                        Environment.Exit(0);
                    }
                }

                if (!string.IsNullOrEmpty(arguments.W))
                {
                    if (int.TryParse(arguments.W, out int result))
                    {
                        CommandLineArguments.PingTimeout = result;
                    }
                    else
                    {
                        DisplayHelp();
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Error parsing argument -w");
                        Console.WriteLine(" Wrong timeout.");
                        Console.ResetColor();
                        Environment.Exit(0);
                    }
                }

                if (!string.IsNullOrEmpty(arguments.I))
                {
                    if (int.TryParse(arguments.I, out int result))
                    {
                        CommandLineArguments.PingRttInterval = result;
                    }
                    else
                    {
                        DisplayHelp();
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Error parsing argument -i");
                        Console.WriteLine(" Wrong RTT interval.");
                        Console.ResetColor();
                        Environment.Exit(0);
                    }
                }

                if (arguments.T & (string.IsNullOrEmpty(arguments.Tt) || string.IsNullOrEmpty(arguments.Tc)))
                {
                    DisplayHelp();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Telegram Bot access token and Telegram Chat ID are not defined! Please define them using -tt and -tc arguments.");
                    Console.ResetColor();
                    Environment.Exit(0);
                }

                if (!string.IsNullOrEmpty(arguments.Tt) & string.IsNullOrEmpty(arguments.Tc))
                {
                    DisplayHelp();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Telegram Chat ID is not defined! Please define it using -tc argument.");
                    Console.ResetColor();
                    Environment.Exit(0);
                }

                if (!string.IsNullOrEmpty(arguments.Tc) & string.IsNullOrEmpty(arguments.Tt))
                {
                    DisplayHelp();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Telegram Bot access token is not defined! Please define it using -tt argument.");
                    Console.ResetColor();
                    Environment.Exit(0);
                }

                if ((arguments.Ta || arguments.Te) & (string.IsNullOrEmpty(arguments.Tt) || string.IsNullOrEmpty(arguments.Tc)))
                {
                    DisplayHelp();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Telegram Bot access token or Telegram Chat ID is not defined! Please define them using -tt and -tc arguments.");
                    Console.ResetColor();
                    Environment.Exit(0);
                }

                CommandLineArguments.DoNotFragment = arguments.F;
                CommandLineArguments.FollowTheName = arguments.Follow;
                CommandLineArguments.LogEnabled    = arguments.Log;
                CommandLineArguments.AddDate       = arguments.D;

                if (!string.IsNullOrEmpty(arguments.Tt) & !string.IsNullOrEmpty(arguments.Tc))
                {
                    CommandLineArguments.UsingTelegram = true;
                }

                CommandLineArguments.TelegramBotToken = arguments.Tt;
                CommandLineArguments.TelegramChatId   = arguments.Tc;

                if (arguments.Ta)
                {
                    CommandLineArguments.TelegramSendAll    = arguments.Ta;
                    CommandLineArguments.TelegramSendErrors = false;
                }

                if (arguments.Te)
                {
                    CommandLineArguments.TelegramSendErrors = arguments.Te;
                }
            }

            //validate the address
            //logic: if address is IP address - continue pinging using the IP address;
            //       if address is name - try to resolve it to IP address and continue pinging using the first IP address from the resolved array of IP's;
            //       if both unsuccessful - terminate the program with the error code -1
            bool addressIsIp = ValidateAddress.Ip(CommandLineArguments.Address);

            if (addressIsIp)
            {
                Variables.Address = CommandLineArguments.Address;
                //disable FollowTheName option and set hostname to empty because using an ip address
                CommandLineArguments.FollowTheName = false;
                Variables.HostName = "";
            }
            else
            {
                bool addressIsHostName = ValidateAddress.HostName(CommandLineArguments.Address);

                if (addressIsHostName)
                {
                    Variables.Address  = CommandLineArguments.Address;
                    Variables.HostName = CommandLineArguments.Address;

                    //change the global input address (from Command Line arguments) to the ip address => do not allow the ping module to resolve the hostname to an ip address
                    if (!CommandLineArguments.FollowTheName)
                    {
                        string singleIp = ResolveHostname.GetSingleIp(CommandLineArguments.Address);
                        if (!string.IsNullOrEmpty(singleIp))
                        {
                            Variables.Address = singleIp;
                        }
                    }
                }
                else
                {
                    string textHostNotFound = "Can't resolve the hostname '" + CommandLineArguments.Address + "' to an IP address.";
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(textHostNotFound);
                    Console.ResetColor();
                    Environment.Exit(-1);
                }
            }

            //save a reference so it does not get GC'd
            _consoleHandler = ConsoleCtrlCheck;

            //set handler that will trap exit
            SetConsoleCtrlHandler(_consoleHandler, true);

            Ping ping = new Ping(CommandLineArguments);

            ping.StartPing();

            Result();
            Console.WriteLine();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey(true);
        }
Example #17
0
        public ActionResult Index()
        {
            var model = new ValidateAddress();

            return(View(model));
        }