Ejemplo n.º 1
0
        public static bool IsDisposable(string email, string apiKey)
        {
            try {
                var response = new RestClient {
                    BaseUrl = new Uri("http://check.block-disposable-email.com/"),
                    Timeout = 5000
                }.Execute(new RestRequest {
                    Resource = "easyapi/json/" + apiKey + "/" + email,
                    Method   = Method.GET,
                    //RequestFormat = RestSharp.DataFormat.Json
                });
                var     content = response.Content;
                dynamic json    = Newtonsoft.Json.Linq.JObject.Parse(content);

                //{"request_status":"success","domain_status":"block","version":"0.1","servertime":"2013-01-14 22:37:39","server_id":"mirror2_chicago"}
                var request_status = json.request_status.Value;
                var domain_status  = json.domain_status.Value;

                var disposable = (request_status == "success") && (domain_status == "block");

                //consider fallback plan if/when we run out of queries... ie use the static list.

                return(disposable);
            } catch (Exception ex) {
                LogIt.E(ex);
                return(false);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// account for possbility of ELB sheilding the public ip
        /// </summary>
        /// <returns></returns>
        public static string Execute(bool elbIsInUse = true)
        {
            try {
#if DEBUG
#else
#endif
                //LogIt.D(string.Join("|", new List<object> { HttpContext.Current.Request.UserHostAddress, HttpContext.Current.Request.Headers["X-Forwarded-For"], HttpContext.Current.Request.Headers["REMOTE_ADDR"] }));
                if ((HttpContext.Current == null) || (HttpContext.Current.Request == null))
                {
                    return(null);
                }

                var ip = HttpContext.Current.Request.UserHostAddress;
                if (HttpContext.Current.Request.Headers["X-Forwarded-For"] != null)
                {
                    ip = HttpContext.Current.Request.Headers["X-Forwarded-For"];
                    //LogIt.D(ip + "|X-Forwarded-For");
                }
                else if (HttpContext.Current.Request.Headers["REMOTE_ADDR"] != null)
                {
                    ip = HttpContext.Current.Request.Headers["REMOTE_ADDR"];
                    //LogIt.D(ip + "|REMOTE_ADDR");
                }

                //ip = string.IsNullOrEmpty(ip) ? ip : ip.Split()
                return(ip);
            } catch (Exception ex) {
                LogIt.E(ex);
            }
            return(null);
        }
Ejemplo n.º 3
0
 public static bool Execute(
     string AWSAccessKey,
     string AWSSecretKey,
     string bucketName,
     string objectKey,
     out string url,
     int numberOfMinutes = 30
     )
 {
     url = "";
     try {
         using (var s3Client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1)) {
             var gpsur = new GetPreSignedUrlRequest {
                 BucketName = bucketName,
                 Key        = objectKey,
                 Expires    = DateTime.UtcNow.AddMinutes(numberOfMinutes)
             };
             url = s3Client.GetPreSignedURL(gpsur);
         }
         return(true);
     } catch (Exception ex) {
         LogIt.E(ex);
         return(false);
     }
 }
Ejemplo n.º 4
0
        public static List <AreaCode> AcquireFromResources()
        {
            try {
                var content = Properties.Resources.area_codes;
                var lol     = content.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                //skip header: Area Code,Region
                lol.RemoveAt(0);
                _loac = new List <AreaCode> {
                };
                foreach (var l in lol)
                {
                    var los = l.Split(new char[] { ',' });
                    //var location = los[1];
                    //if (location.Length == 2) {
                    //  if (States.GetStateName(location) != null) {
                    //    location = States.GetStateName(location);
                    //  }
                    //}
                    //do I include non us/ca states?
                    _loac.Add(new AreaCode {
                        numberCode = los[0], stateCode = los[1]
                    });
                }

                return(_loac);
            } catch (Exception ex) {
                LogIt.E(ex);
                return(null);
            }
        }
Ejemplo n.º 5
0
        private static string StringToCSVCell(string str)
        {
            try {
                bool mustQuote = (str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n"));
                if (mustQuote)
                {
                    var sb = new StringBuilder();
                    sb.Append("\"");
                    foreach (char nextChar in str)
                    {
                        sb.Append(nextChar);
                        if (nextChar == '"')
                        {
                            sb.Append("\"");
                        }
                    }
                    sb.Append("\"");
                    return(sb.ToString());
                }

                return(str);
            } catch (Exception ex) {
                LogIt.E(ex);
                throw ex;
            }
        }
Ejemplo n.º 6
0
        public static string Execute <T>(List <T> data, bool addHeaderRow = false)
        {
            try {
                var properties = typeof(T).GetProperties();
                var result     = new StringBuilder();

                if (addHeaderRow)
                {
                    var methods = properties
                                  .Select(p => p.GetMethod)
                                  .Select(v => StringToCSVCell(
                                              ((v == null) ? "" : v.ToString())
                                              ))
                                  .Select(m => m.Substring(m.IndexOf("get_") + 4).Replace("()", ""));
                    result.AppendLine(string.Join(",", methods));
                }

                foreach (var row in data)
                {
                    var values = properties.Select(p => p.GetValue(row, null))
                                 .Select(v => StringToCSVCell(
                                             ((v == null) ? "" : v.ToString())
                                             ));
                    var line = string.Join(",", values);
                    result.AppendLine(line);
                }

                return(result.ToString());
            } catch (Exception ex) {
                LogIt.E(ex);
                throw ex;
            }
        }
Ejemplo n.º 7
0
 public static bool Execute(
     string AWSAccessKey,
     string AWSSecretKey,
     string fileKey,
     string bucketName,
     RegionEndpoint re,
     out string url
     )
 {
     url = "";
     try {
         using (var s3c = new AmazonS3Client(
                    awsAccessKeyId: AWSAccessKey,
                    awsSecretAccessKey: AWSSecretKey,
                    region: re
                    )) {
             var s3FileInfo = new Amazon.S3.IO.S3FileInfo(s3c, bucketName, fileKey);
             url = "https://s3.amazonaws.com/" + bucketName + "/" + fileKey;
             return(s3FileInfo.Exists);
         }
     } catch (Exception ex) {
         LogIt.E(ex);
         return(false);
     }
 }
        public static bool IsValidNorthAmericanNumber(string number)
        {
            bool isValid = false;

            try {
                string numbersOnly = StripNonNumericCharacters(number);

                //dnw: 2402164320
                //Regex regexObj = new Regex(@"(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]‌​)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]‌​|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})");
                //http://www.asiteaboutnothing.net/regex/regex-quickstart.html
                Regex regexObj = new Regex(@"^1?([0-9]{3})([0-9]{3})([0-9]{4})$");
                if (regexObj.IsMatch(numbersOnly))
                {
                    string formattedPhoneNumber = regexObj.Replace(numbersOnly, "($1) $2-$3");
                    isValid = true;
                }
                else
                {
                    // Invalid phone number
                }
            } catch (Exception ex) {
                LogIt.E(ex);
            }
            return(isValid);
        }
Ejemplo n.º 9
0
 public static bool Execute(
     string AWSAccessKey,
     string AWSSecretKey,
     string bucketName,
     string fileKey,
     RegionEndpoint re,
     out MemoryStream ms
     )
 {
     ms = null;
     try {
         using (var s3c = new AmazonS3Client(AWSAccessKey, AWSSecretKey, re)) {
             var response = s3c.GetObject(
                 new GetObjectRequest {
                 BucketName = bucketName,
                 Key        = fileKey
             });
             using (var rs = response.ResponseStream) {
                 ms = new MemoryStream();
                 rs.CopyTo(ms);
                 return(true);
             }
         }
     } catch (Exception ex) {
         LogIt.E(ex);
         return(false);
     }
 }
Ejemplo n.º 10
0
        public static bool Execute(
            string AWSAccessKey,
            string AWSSecretKey,
            string bucketName,
            byte[] ba,
            string toPath,
            out string url,
            RegionEndpoint re,
            S3CannedACL s3ca
            )
        {
            url = "";
            try {
                using (var ms = new MemoryStream(ba)) {
                    var uploadMultipartRequest = new TransferUtilityUploadRequest {
                        BucketName  = bucketName,
                        Key         = toPath,
                        CannedACL   = s3ca,
                        InputStream = ms,
                        //PartSize = 123?
                    };

                    using (var tu = new TransferUtility(AWSAccessKey, AWSSecretKey, re)) {
                        tu.Upload(uploadMultipartRequest);
                    }
                    url = S3_BASE + bucketName + "/" + toPath;
                    return(true);
                }
            } catch (Exception ex) {
                LogIt.E(ex);
                return(false);
            }
        }
Ejemplo n.º 11
0
 public static bool Execute(
     string AWSAccessKey,
     string AWSSecretKey,
     string bucketName,
     string filePath,
     string toPath,
     RegionEndpoint re,
     out string url,
     S3CannedACL s3ca
     )
 {
     url = "";
     try {
         using (var tu = new TransferUtility(AWSAccessKey, AWSSecretKey, re)) {
             var tuur = new TransferUtilityUploadRequest {
                 FilePath   = filePath,
                 BucketName = bucketName,
                 Key        = toPath,
                 CannedACL  = s3ca
             };
             tu.Upload(tuur);
             url = S3_BASE + bucketName + "/" + toPath;
         }
         return(true);
     } catch (Exception ex) {
         LogIt.E(ex);
         return(false);
     }
 }
Ejemplo n.º 12
0
        //TODO: do i really want all these to be public read?! are we locking down elsewhre w/ cors or bucket policy?
        public static bool Execute(
            string AWSAccessKey,
            string AWSSecretKey,
            string bucketName,
            MemoryStream ms,
            string key,
            RegionEndpoint re,
            out string url
            )
        {
            url = "";
            try {
                var uploadMultipartRequest = new TransferUtilityUploadRequest {
                    BucketName  = bucketName,
                    Key         = key,
                    CannedACL   = S3CannedACL.PublicRead,
                    InputStream = ms,
                };

                using (var tu = new TransferUtility(AWSAccessKey, AWSSecretKey, re)) {
                    tu.Upload(uploadMultipartRequest);
                }
                url = S3_BASE + bucketName + "/" + key;
                return(true);
            } catch (Exception ex) {
                LogIt.E(ex);
                return(false);
            }
        }
Ejemplo n.º 13
0
//this does not return state name... wonder why ic ommited
        public static string GetStateName(string areaCode)
        {
            try {
                return(loacUsCa.Where(ac => ac.numberCode == areaCode).Select(ac => ac.stateCode).FirstOrDefault());
            } catch (Exception ex) {
                LogIt.E(ex);
                return(null);
            }
        }
Ejemplo n.º 14
0
 public static string Execute(object o)
 {
     try {
         return(JsonConvert.SerializeObject(o));
     } catch (Exception ex) {
         LogIt.E(ex);
     }
     return("");
 }
Ejemplo n.º 15
0
 public static bool IsDisposable(string email)
 {
     try {
         var disposableDomain = loDomains.Where(d => email.EndsWith(d, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
         return(disposableDomain != null);
     } catch (Exception ex) {
         LogIt.E(ex);
         return(false);
     }
 }
Ejemplo n.º 16
0
 public static void Execute(
     out HttpStatusCode hsc,
     out string status,
     out string url,
     string awsAccessKey,
     string awsSecretKey,
     Amazon.RegionEndpoint re,
     string bucketName,
     byte[] ba,
     string key,
     S3CannedACL acl,
     string contentType = null
     )
 {
     hsc    = HttpStatusCode.BadRequest;
     status = "";
     url    = "";
     try {
         using (var ms = new MemoryStream(ba)) {
             var uploadMultipartRequest = new TransferUtilityUploadRequest {
                 BucketName  = bucketName,
                 Key         = key,
                 CannedACL   = acl,
                 InputStream = ms,
                 //PartSize = 123?
             };
             if (!string.IsNullOrWhiteSpace(contentType))
             {
                 uploadMultipartRequest.ContentType = contentType;
             }
             using (var tu = new TransferUtility(awsAccessKey, awsSecretKey, re)) {
                 tu.Upload(uploadMultipartRequest);
             }
             //why encoding?
             url = HttpUtility.UrlDecode(Constants.S3_BASE + bucketName + "/" + HttpUtility.UrlEncode(key));
             hsc = HttpStatusCode.OK;
             return;
         }
     } catch (Exception ex) {
         LogIt.E(ex);
         hsc    = HttpStatusCode.InternalServerError;
         status = "unexecpected error";
         return;
     } finally {
         LogIt.I(JsonConvert.SerializeObject(
                     new {
             hsc,
             status,
             url,
             //ipAddress = GetPublicIpAddress.Execute(hc),
             //executedBy = GetExecutingUsername.Execute()
         }, Formatting.Indented));
     }
 }
Ejemplo n.º 17
0
 public static void Execute()
 {
     try {
         foreach (var rh in HttpContext.Current.Request.Headers)
         {
             LogIt.D(rh.ToString() + "|" + HttpContext.Current.Request.Headers[rh.ToString()]);
         }
     } catch (Exception ex) {
         LogIt.E(ex);
     }
 }
Ejemplo n.º 18
0
        /// <summary>
        /// On success save refresh and authtoken
        /// </summary>
        /// <param name="code"></param>
        /// <param name="clientId"></param>
        /// <param name="clientSecret"></param>
        /// <param name="redirectUrl"></param>
        /// <returns></returns>
        public static OAuth2TokenResponse Execute(string code, string clientId, string clientSecret, string redirectUrl)
        {
            try {
                //POST /o/oauth2/token HTTP/1.1
                //Host: accounts.google.com
                //Content-length: 250
                //content-type: application/x-www-form-urlencoded
                //user-agent: google-oauth-playground

                //code=XXX&redirect_uri=https%3A%2F%2Fdevelopers.google.com%2Foauthplayground&client_id=XXX.apps.googleusercontent.com&scope=&client_secret=************&grant_type=authorization_code

                var request = new RestRequest("o/oauth2/token", Method.POST);
                request.AddParameter("Content-Type", "application/x-www-form-urlencoded");
                request.AddParameter("code", code);
                request.AddParameter("redirect_uri", redirectUrl);
                request.AddParameter("client_id", clientId);
                request.AddParameter("scope", "");
                request.AddParameter("client_secret", clientSecret);
                request.AddParameter("grant_type", "authorization_code");

                var response = (new RestClient("https://accounts.google.com/")).Execute(request);
                var content  = response.Content;

                //valid response:
                //{
                //  "access_token" : "XXX",
                //  "token_type" : "Bearer",
                //  "expires_in" : 3600,
                //  "refresh_token" : "XXX"
                //}

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    LogIt.W(response.StatusCode.ToString() + "|" + response.Content);
                    return(new OAuth2TokenResponse {
                    });
                }
                else
                {
                    //LogIt.D(content);
                    dynamic json = Newtonsoft.Json.Linq.JObject.Parse(content);
                    var     tr   = new OAuth2TokenResponse {
                        access_token  = json.access_token,
                        expires_in    = json.expires_in,
                        refresh_token = json.refresh_token,
                        token_type    = json.token_type
                    };
                    return(tr);
                }
            } catch (Exception ex) {
                LogIt.E(ex);
                throw ex;
            }
        }
Ejemplo n.º 19
0
 public static void Execute()
 {
     try {
         foreach (var ci in CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures).OrderBy(ci => ci.Name))
         {
             LogIt.D(ci.Name + "|" + ci.EnglishName);
         }
     } catch (Exception ex) {
         LogIt.E(ex);
     }
 }
Ejemplo n.º 20
0
        public static Coordinate Execute(string address)
        {
            var c = new Coordinate {
                g = Geocoder.Esri
            };

            try {
                if (!string.IsNullOrEmpty(address) && !address.Equals("0"))
                {
                    var uea = HttpUtility.UrlEncode(address.Trim());

                    //http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/find?text=1700 Penny ave washingtn dc&f=pjson&forStorage=false&maxLocations=1
                    var client   = new RestClient("http://geocode.arcgis.com/");
                    var request  = new RestRequest("/arcgis/rest/services/World/GeocodeServer/find?text=" + uea + "&f=pjson&forStorage=false&maxLocations=1", Method.GET);
                    var response = client.Execute(request);

                    if (response.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        LogIt.D(response.StatusCode + "|" + address);
                    }
                    else
                    {
                        var     content = response.Content;
                        dynamic json    = Newtonsoft.Json.Linq.JObject.Parse(content);

                        if (json.locations.Count > 0)
                        {
                            var geometry = json.locations[0].feature.geometry;
                            if (geometry != null)
                            {
                                var lng = Convert.ToDecimal(geometry.x.Value);
                                var lat = Convert.ToDecimal(geometry.y.Value);
                                if ((lat != 0) && (lng != 0))
                                {
                                    c.lng = lng;
                                    c.lat = lat;
                                }
                            }
                            var precision = json.locations[0].feature.attributes;
                            if (precision != null)
                            {
                                var pc = precision.Score.Value;
                                c.precision = Convert.ToString(pc);
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                LogIt.W(address);
                LogIt.E(ex);
            }

            return(c);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// account for possbility of ELB sheilding the public ip
        /// </summary>
        /// <returns></returns>
        public static string Execute(
            HttpContext hc
            )
        {
            var remoteIpAddress = "";
            var xForwardedFor   = "";
            var remoteAddr      = "";
            var ip     = "";
            var status = "";

            try {
                //https://stackoverflow.com/questions/38571032/how-to-get-httpcontext-current-in-asp-net-core
                //TODO: get if not passed

                if ((hc == null) || (hc.Request == null))
                {
                    status = "http context was null";
                    return(null);
                }

                remoteIpAddress = hc.Features.Get <IHttpConnectionFeature>()?.RemoteIpAddress.ToString();
                if (!string.IsNullOrEmpty(hc.Request.Headers["X-Forwarded-For"]))
                {
                    xForwardedFor = hc.Request.Headers["X-Forwarded-For"];
                }
                if (!string.IsNullOrEmpty(hc.Request.Headers["REMOTE_ADDR"]))
                {
                    remoteAddr = hc.Request.Headers["REMOTE_ADDR"];
                }

                var loIp = new List <string> {
                    xForwardedFor, remoteAddr, remoteIpAddress
                };
                loIp = loIp.Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
                ip   = loIp.FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(ip) && ip.Contains(","))
                {
                    ip = ip.Split(",").First();
                }

                return(ip);
            } catch (Exception ex) {
                LogIt.E(ex);
            } finally {
                LogIt.D(JsonConvert.SerializeObject(new {
                    ip,
                    status,
                    remoteIpAddress,
                    xForwardedFor,
                    remoteAddr
                }, Formatting.Indented));
            }
            return(null);
        }
Ejemplo n.º 22
0
 public static City GetCity(string ip)
 {
     try {
         var cr = maxmindDr.City(ip);
         //LogIt.D(cr.Country.IsoCode + "|" + cr.City.Name);
         return(cr.City);
     } catch (Exception ex) {
         LogIt.E(ex);
         LogIt.W(ip);
         throw ex;
     }
 }
Ejemplo n.º 23
0
        public static bool Execute(
            ref string phoneNumber,
            ref string phoneNumberCountryCode
            )
        {
            try {
                if (string.IsNullOrEmpty(phoneNumber) || string.IsNullOrEmpty(phoneNumberCountryCode))
                {
                    return(false);
                }

                //validate country code
                try {
                    var ri = new RegionInfo(phoneNumberCountryCode.ToLower());
                } catch (ArgumentException ae) {
                    if (!IsValidCountryCode.Execute(phoneNumberCountryCode.ToLower()))
                    {
                        LogIt.W(ae);
                        LogIt.W("unrecognized country code (ISO 3166 expected)");
                        return(false);
                    }
                }

                //why dont we try validating as supplied first and if that succeeds then proceed: validate it first before updating by removing non-numerics
                //validate on phone numbers
                var pnu = PhoneNumberUtil.GetInstance();
                var pn  = pnu.Parse(phoneNumber, phoneNumberCountryCode.ToUpper());
                if (pnu.IsValidNumber(pn))
                {
                    phoneNumber = pnu.Format(pn, PhoneNumberFormat.E164);
                }
                else
                {
                    //normalize phone number
                    phoneNumber = StripNonNumericCharacters.Execute(phoneNumber);
                    pn          = pnu.Parse(phoneNumber, phoneNumberCountryCode.ToUpper());
                    if (!pnu.IsValidNumber(pn))
                    {
                        LogIt.W("unrecognized phone number format");
                        return(false);
                    }
                    phoneNumber = pnu.Format(pn, PhoneNumberFormat.E164);
                }

                //we stroe in DB as lower
                phoneNumberCountryCode = phoneNumberCountryCode.ToLower();
                return(true);
            } catch (Exception ex) {
                LogIt.E(ex);
                return(false);
            }
        }
        /// <summary>
        /// if successed, should save accesstoken and expire and use until expires
        /// if fails shoudl consider clearing refresh token
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="clientSecret"></param>
        /// <param name="refreshToken"></param>
        /// <param name="tr"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public static bool Execute(string clientId, string clientSecret, string refreshToken, out OAuth2TokenResponse tr, out string errorMsg)
        {
            tr       = null;
            errorMsg = null;

            try {
                //https://developers.google.com/accounts/docs/OAuth2WebServer
                //#Using a Refresh Token

                var request = new RestRequest("o/oauth2/token", Method.POST);
                request.AddParameter("client_id", clientId);
                request.AddParameter("client_secret", clientSecret);
                request.AddParameter("refresh_token", refreshToken);
                request.AddParameter("grant_type", "refresh_token");
                request.AddParameter("Content-Type", "application/x-www-form-urlencoded");

                var response = (new RestClient("https://accounts.google.com")).Execute(request);
                //valid response: { "access_token":"1/XXX", "expires_in":3920, "token_type":"Bearer",}
                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    errorMsg = "Unable to get new access token: " + response.StatusCode.ToString() + "|" + response.Content;
                    LogIt.W(errorMsg);
                    return(false);
                }
                else
                {
                    var content = response.Content;
                    //LogIt.D(content);

                    dynamic json = Newtonsoft.Json.Linq.JObject.Parse(content);
                    tr = new OAuth2TokenResponse {
                        access_token  = json.access_token,
                        expires_in    = json.expires_in,
                        token_type    = json.token_type,
                        refresh_token = json.refresh_token
                    };

                    //if (string.IsNullOrEmpty(tr.access_token)) {
                    //  //should I clear out refesh token?
                    //  LogIt.E("access token was null");
                    //  //} else {
                    //  //  icalgenie.lib.Db.Credential.AddOrUpdateUserCredentials(new credential_element { name = CredentialElementName.GoogleAccessToken.ToString(), value = tr.access_token }, u, SourceType.GmailAccount);
                    //  //}
                    //}
                    return(true);
                }
            } catch (Exception ex) {
                errorMsg = ex.Message;
                LogIt.E(ex);
                return(false);
            }
        }
Ejemplo n.º 25
0
        public static List <WebProxy> GetUsableWebProxies(
            string apiKey,
            string apiHost,
            int minimumUptimePercentage = defaultMinimumUptimePercentage,
            int maxResults         = 10,
            int minLatencySeconds  = 4,
            bool anonymous         = false,
            string limitProxyTypes = "https"
            )
        {
            try {
                Utils.Cert.IgnoreInvalidCerts(); //only req while self signed
                var rc = new RestClient(apiHost);
                var rr = rc.Execute(
                    new RestRequest {
                    Resource = "api/Proxy/get?apiKey=" + apiKey
                               + "&limitProxyTypes=" + limitProxyTypes
                               + "&minUptime=" + minimumUptimePercentage
                               + "&pageSize=" + maxResults
                               + "&sortBy=latestTest"
                               + "&active=true"
                               + "&minLatency=" + minLatencySeconds
                               + (!anonymous ? "" : "&anonymous=true"),
                    Method        = Method.GET,
                    RequestFormat = DataFormat.Json,
                });
                if (rr.ErrorException != null)
                {
                    throw rr.ErrorException;
                }
                if (rr.StatusCode != HttpStatusCode.OK)
                {
                    throw new Exception(rr.StatusCode.ToString() + "|" + rr.Content);
                }
                var     content = rr.Content;
                dynamic json    = Newtonsoft.Json.Linq.JObject.Parse(content);
                string  status  = json.status.Value;

                var lowp = new List <WebProxy>();
                foreach (var p in json.proxies)
                {
                    lowp.Add(new WebProxy {
                        Address = new Uri("http://" + p.host.Value)
                    });
                }
                return(lowp);
            } catch (Exception ex) {
                LogIt.E(ex);
                throw ex;
            }
        }
Ejemplo n.º 26
0
 public static InsightsResponse GetOmniResponse(string ip)
 {
     try {
         using (WebServiceClient wsc = new MaxMind.GeoIP2.WebServiceClient(MAXMIND_WS_USER_ID, MAXMIND_WS_KEY)) {
             var ir = wsc.Insights(ip);
             LogIt.D(ir.Country.IsoCode + "|" + ir.City.Name);
             return(ir);
         }
     } catch (Exception ex) {
         LogIt.E(ex);
         LogIt.W(ip);
         throw ex;
     }
 }
Ejemplo n.º 27
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="kml"></param>
 /// <param name="kmzFileNameWithoutExtension"></param>
 /// <param name="outPath">full out path, should end in .kmz</param>
 public static void SaveKmz(List <Coordinate> loc, string outPath)
 {
     try {
         using (ZipFile zf = new ZipFile()) {
             using (MemoryStream kml = SaveKmz(loc, true, true, true)) {
                 ZipEntry oZipEntry = zf.AddEntry("doc.kml", kml);
                 zf.Save(outPath);
             }
         }
     } catch (Exception ex) {
         LogIt.E(ex);
         throw;
     }
 }
Ejemplo n.º 28
0
        //http://www.mapquestapi.com/geocoding/v1/address?key=KEY_HERE&location=lancaster%20pa
        //http://www.mapquestapi.com/geocoding/v1/address?key=KEY_HERE&callback=renderOptions&inFormat=kvp&outFormat=json&location=Lancaster,PA

        public static Coordinate Execute(string address, string key)
        {
            var c = new Coordinate {
                g = Geocoder.MapQuest
            };

            try {
                if (!string.IsNullOrEmpty(address))
                {
                    var uea = HttpUtility.UrlEncode(address.Trim());

                    var client   = new RestClient("http://www.mapquestapi.com/");
                    var request  = new RestRequest("/geocoding/v1/address?key=" + key + "&location=" + uea, Method.GET);
                    var response = client.Execute(request);
                    var content  = response.Content;

                    dynamic json = Newtonsoft.Json.Linq.JObject.Parse(content);
                    var     sc   = (json.info.statuscode == null) ? -1 : json.info.statuscode.Value;

                    if (sc != 0)
                    {
                        var msg = (json.info.messages == null) ? "" : json.info.messages[0].Value;
                        LogIt.W(msg);

                        //temp
                        //var js = json.results[0].locations[0].ToString();
                        //LogIt.D(js);
                    }
                    else
                    {
                        var lng = Convert.ToDecimal(json.results[0].locations[0].latLng.lng.Value);
                        var lat = Convert.ToDecimal(json.results[0].locations[0].latLng.lat.Value);
                        var pc  = json.results[0].locations[0].geocodeQualityCode.Value; //A1XAX and A3XAX are bad country level precision

                        if ((lat != 0) && (lng != 0) && (pc != "A1XAX") && (pc != "A3XAX"))
                        {
                            c.lng       = lng;
                            c.lat       = lat;
                            c.precision = pc;
                            //c.sGeocodePrecision = json.results[0].locations[0].geocodeQuality;
                        }
                    }
                }
            } catch (Exception ex) {
                LogIt.E(ex);
            }

            return(c);
        }
Ejemplo n.º 29
0
        public static void Execute(
            string numberE164,
            out HttpStatusCode hsc,
            out string status
            )
        {
            hsc    = HttpStatusCode.BadRequest;
            status = "";

            try {
                if (string.IsNullOrWhiteSpace(numberE164))
                {
                    hsc    = HttpStatusCode.BadRequest;
                    status = "number not found";
                    return;
                }

                if (numberE164[0] != '+')
                {
                    hsc    = HttpStatusCode.BadRequest;
                    status = "e164 format number should start with +";
                    return;
                }

                var pnu = PhoneNumberUtil.GetInstance();
                var pn  = pnu.Parse(numberE164, null);
                if (!pnu.IsValidNumber(pn))
                {
                    hsc    = HttpStatusCode.BadRequest;
                    status = "number is not valid";
                    return;
                }

                hsc = HttpStatusCode.OK;
                return;
            } catch (Exception ex) {
                hsc = HttpStatusCode.InternalServerError;
                //status = "unexpected error"; //maybe pass the ex.message here
                status = ex.Message;
                LogIt.E(ex);
            } finally {
                LogIt.I(JsonConvert.SerializeObject(new {
                    hsc,
                    status,
                    numberE164
                }));
            }
        }
Ejemplo n.º 30
0
        public static bool Detect(
            string googe_service_account_json,
            string applicationName,
            string base64Image,
            out string summary
            )
        {
            summary = "";

            try {
                var vs = GetVisionServiceByServiceAccount(
                    googe_service_account_json: googe_service_account_json,
                    applicationName: applicationName

                    );
                var loair = DetectLabels(vs, base64Image);
                // Check if label annotations were found
                if (loair != null)
                {
                    // Loop through and output label annotations for the image
                    var lod = new List <string> {
                    };
                    foreach (var air in loair)
                    {
                        foreach (var ea in air.LabelAnnotations)
                        {
                            var p = ((decimal)ea.Score).ToString("P1", CultureInfo.InvariantCulture);
                            lod.Add(ea.Description + " (" + p + ")");
                        }
                    }
                    //var lod = loair.Select(
                    // air => air.LabelAnnotations.Select(
                    //    ea=> ea.Description + " (" + (Math.Round((decimal)ea.Score,2) * 100).ToString() + "%)"
                    //   )
                    //   ).ToList();
                    summary = string.Join(", ", lod);
                }
                else
                {
                    LogIt.D("No labels found.");
                }
                return(true);
            } catch (Exception ex) {
                LogIt.E(ex);
            }
            return(false);
        }