Beispiel #1
0
        /// <inheritdoc />
        public async Task <SolarInfo> GetSolarInfoAsync(GeoInfo geoInfo)
        {
            var lat      = geoInfo.Latitude.ToString(CultureInfo.InvariantCulture);
            var lng      = geoInfo.Longitude.ToString(CultureInfo.InvariantCulture);
            var response =
                await _httpService.GetStringAsync($"https://api.sunrise-sunset.org/json?lat={lat}&lng={lng}&formatted=0");

            if (response.IsBlank())
            {
                return(null);
            }

            try
            {
                // Parse
                var parsed = JToken.Parse(response);

                // Extract data
                var sunrise = parsed["results"]["sunrise"].Value <DateTime>();
                var sunset  = parsed["results"]["sunset"].Value <DateTime>();

                // Populate
                var result = new SolarInfo(sunrise.TimeOfDay, sunset.TimeOfDay);

                return(result);
            }
            catch
            {
                Debug.WriteLine("Could not deserialize solar info", GetType().Name);
                return(null);
            }
        }
Beispiel #2
0
        public async Task <IHttpActionResult> CreateGeoInfo([FromBody] string ip)
        {
            if (!ModelState.IsValid)
            {
                return(JsonResult.BadRequest("IP address has to be a string"));
            }
            if (!ValidateIPv4(ip))
            {
                return(JsonResult.BadRequest("Provided IP address is in a wrong format!"));
            }
            try
            {
                var exists = await GeoInfoExists(ip);

                if (exists)
                {
                    return(JsonResult.BadRequest("IP address already exists in the DB!"));
                }

                GeoInfo geoInfo = new GeoInfo();
                geoInfo = await FillWithDetails(ip);

                db.GeoInfos.Add(geoInfo);
                await db.SaveChangesAsync();

                return(JsonResult.Success(Mapper.Map <GeoInfo, GeoInfoDto>(geoInfo)));
            }
            catch (Exception e)
            {
                return(JsonResult.Error(string.Format("Could not create GeoInfo with ip:{0} due to error: {1}", ip, e.Message)));
            }
        }
Beispiel #3
0
        public HttpResponseMessage Post([FromBody] GeoInfo data)
        {
            bool result = false;

            try
            {
                // Encolamos si tiene distinto de null la info
                data.Ip = HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : "";
                string QueueName  = ConfigurationManager.AppSettings["GeoInfoQueue"];
                string dataString = JsonConvert.SerializeObject(data);
                QueueManager.InsertMessage(dataString, QueueName);
                result = true;
            }
            catch (Exception e)
            {
                var messageException = telemetria.MakeMessageException(e, System.Reflection.MethodBase.GetCurrentMethod().Name);
                telemetria.Critical(messageException);
            }


            if (result)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, result));
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, result));
            }
        }
Beispiel #4
0
        /// <inheritdoc />
        public async Task <GeoInfo> GetGeoInfoAsync()
        {
            var response = await _httpService.GetStringAsync("https://geoip.nekudo.com/api");

            if (response.IsBlank())
            {
                return(null);
            }

            try
            {
                // Parse
                var parsed = JToken.Parse(response);

                // Extract data
                var countryName = parsed["country"]["name"].Value <string>().NullIfBlank();
                var countryCode = parsed["country"]["code"].Value <string>().NullIfBlank();
                var city        = parsed["city"].Value <string>().NullIfBlank();
                var lat         = parsed["location"]["latitude"].Value <double>();
                var lng         = parsed["location"]["longitude"].Value <double>();

                // Populate
                var result = new GeoInfo(countryName, countryCode, city, lat, lng);

                return(result);
            }
            catch
            {
                Debug.WriteLine("Could not deserialize geo info", GetType().Name);
                return(null);
            }
        }
        private async Task UpdateCards_WhereIsThisRegionAsync(Guid userId, GeoInfo geoInfo)
        {
            var cardsToUpdate = await dbContext.Cards
                                .Where(card => card.VersionCreator.Id == userId && card.FrontSide.StartsWith("Où est la région"))
                                .ToListAsync();

            foreach (var cardToUpdate in cardsToUpdate)
            {
                var additionalInfoLines = cardToUpdate.AdditionalInfo.Split(Environment.NewLine).Select(line => line.Trim()).ToList();
                if (!additionalInfoLines[0].StartsWith("Elle est constituée de ces"))
                {
                    throw new Exception($"Unexpected card additional info first line: '{additionalInfoLines[0]}'");
                }
                if (additionalInfoLines[1].StartsWith("-"))
                {
                    logger.LogInformation($"Card is already Markdown ({cardToUpdate.BackSide})");
                }
                else
                {
                    var lineIndex = 1;
                    while (!string.IsNullOrEmpty(additionalInfoLines[lineIndex]))
                    {
                        var department = geoInfo.DepartmentsFromName[additionalInfoLines[lineIndex]];
                        additionalInfoLines[lineIndex] = $"- {department.FullName} ({department.DepartmentCode})";
                        lineIndex++;
                    }
                    var result = string.Join(Environment.NewLine, additionalInfoLines);
                    cardToUpdate.AdditionalInfo = result.Trim();
                }
            }
        }
Beispiel #6
0
        private void OutputPlayerJoined(GeoInfo geoInfo)
        {
            string outputString   = $"* Joined: {geoInfo.player.Name}#FF6464";
            string locationString = "";
            // Build valid info list, while honoring settings
            List <string> validInfo = new List <string>();

            if (!String.IsNullOrEmpty(geoInfo.CityName) && ShowCity)
            {
                validInfo.Add(geoInfo.CityName);
            }
            if (!String.IsNullOrEmpty(geoInfo.RegionName) && ShowRegion)
            {
                validInfo.Add(geoInfo.RegionName);
            }
            if (!String.IsNullOrEmpty(geoInfo.CountryName) && ShowCountry)
            {
                validInfo.Add(geoInfo.CountryName);
            }
            if (validInfo.Count > 0)
            {
                string joined = String.Join(", ", validInfo.ToArray());
                locationString = " (" + joined + ")";
            }
            ChatBox.WriteLine(outputString + locationString, new Color(0xFF6464), true);
            Console.WriteLine(StripColors(outputString + locationString));
        }
 void InitMap()
 {
     geo = new GeoInfo(lat, lon, rad);
     InitWeather();
     InitBuildings();
     generating.SetTrigger("Hide");
 }
 public void SaveCache(GeoInfo geoInfo)
 {
     if (HasConnection() && geoInfo.FromFetch)
     {
         db.Exec("REPLACE INTO cache (ipAddress, countryCode, cityName, regionName, insertDate) VALUES(?,?,?,?,date('now'))", geoInfo.IP, geoInfo.CountryCode, geoInfo.CityName, geoInfo.RegionName);
     }
 }
        public async Task <GeoInfo> GetGeoInfo(GeoInfo geoInfo)
        {
            // Concat int in string, unsafe i know
            var results = await db.Query($"SELECT `countryCode`, `regionName`, `cityName` FROM cache WHERE `ipAddress` = ? AND `insertDate` >= date('now', '-{CacheTTL} day')", geoInfo.IP);

            if (results.Length > 0)
            {
                var fetchedResults = results[0];

                foreach (var item in fetchedResults)
                {
                    // Implicit ToString
                    string value = item.Value;
                    switch (item.Key)
                    {
                    case "countryCode":
                        // Only set from database when countryCode gets fetched
                        geoInfo.FromDatabase = true;
                        geoInfo.CountryCode  = value;
                        break;

                    case "cityName":
                        geoInfo.CityName = value;
                        break;

                    case "regionName":
                        geoInfo.RegionName = value;
                        break;
                    }
                }
            }
            return(geoInfo);
        }
Beispiel #10
0
        public override void Use(Player p, string message, CommandData data) {
            if (message.Length == 0) {
                if (p.IsSuper) { SuperRequiresArgs(p, "player name or IP"); return; }
                message = p.name;
            }
            
            string name, ip = ModActionCmd.FindIP(p, message, "Location", out name);
            if (ip == null) return;
            
            if (HttpUtil.IsPrivateIP(ip)) {
                p.Message("%WPlayer has an internal IP, cannot trace"); return;
            }

            JsonContext ctx = new JsonContext();
            using (WebClient client = HttpUtil.CreateWebClient()) {
                ctx.Val = client.DownloadString(https://geoip.pw/" + ip);
            }
            
            JsonObject obj = (JsonObject)Json.ParseStream(ctx);
            GeoInfo info = new GeoInfo();
            if (obj == null || !ctx.Success) {
                p.Message("%WError parsing GeoIP info"); return;
            }
            
            if (elems == null) elems = ConfigElement.GetAll(typeof(GeoInfo));
            obj.Deserialise(elems, info);
            
            string target = name == null ? ip : "of " + PlayerInfo.GetColoredName(p, name);
            p.Message("The IP {0} %Shas been traced to: &b{1}%S/&b{2}", 
                      target, info.region, info.country);
        }
Beispiel #11
0
        public async Task <IActionResult> Index(string token)
        {
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                Link l = _context.Links.FirstOrDefault(a => a.Token == token);

                if (l != null)
                {
                    Statistic statistic = new Statistic();
                    statistic.IP       = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.ToString();
                    statistic.DateTime = DateTime.Now;
                    var    userAgent = Request.Headers["User-Agent"];
                    string uaString  = Convert.ToString(userAgent[0]);

                    var        uaParser = Parser.GetDefault();
                    ClientInfo c        = uaParser.Parse(uaString);

                    statistic.Browser = c.UA.ToString();
                    statistic.OS      = c.OS.ToString();

                    try
                    {
                        var response = await _httpClient.GetAsync($"http://ip-api.com/json/{statistic.IP}");

                        if (response.IsSuccessStatusCode)
                        {
                            var json = await response.Content.ReadAsStringAsync();

                            GeoInfo f = JsonConvert.DeserializeObject <GeoInfo>(json);

                            statistic.City    = f.City;
                            statistic.Country = f.Country;
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex.Message);
                    }
                    try
                    {
                        if (l.Notification)
                        {
                            await SendEmailAsync(HttpContext.User.Identity.Name, $"Following a link: Link - {l.Url} | LinkToken - {l.Token} | IP - {statistic.IP} | Country - {statistic.Country} | City - {statistic.City}");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex.Message);
                    }
                    l.Statistics.Add(statistic);
                    await _context.SaveChangesAsync();
                }

                return(Redirect(l.Url));
            }
            else
            {
                return(RedirectToAction("Login", new { redirect = token }));
            }
        }
 public async Task <GeoData> getAsync(IPAddress ip)
 {
     return(await Task <GeoData> .Factory.StartNew(() =>
     {
         GeoInfo info = new GeoInfo(ip);
         return info.Get();
     }));
 }
Beispiel #13
0
        public override void Use(Player p, string message, CommandData data)
        {
            if (message.Length == 0)
            {
                if (p.IsSuper)
                {
                    SuperRequiresArgs(p, "player name or IP"); return;
                }
                message = p.name;
            }

            string name, ip = ModActionCmd.FindIP(p, message, "Location", out name);

            if (ip == null)
            {
                return;
            }

            if (HttpUtil.IsPrivateIP(ip))
            {
                p.Message("%WPlayer has an internal IP, cannot trace"); return;
            }

            JsonContext ctx = new JsonContext();

            using (WebClient client = HttpUtil.CreateWebClient())
            {
                ctx.Val = client.DownloadString("http://geoip.pw/api/" + ip);
            }

            JsonObject obj  = (JsonObject)Json.ParseStream(ctx);
            GeoInfo    info = new GeoInfo();

            if (obj == null || !ctx.Success)
            {
                p.Message("%WError parsing GeoIP info"); return;
            }

            if (elems == null)
            {
                elems = ConfigElement.GetAll(typeof(GeoInfo));
            }
            obj.Deserialise(elems, info);

            string target = name == null ? ip : "of " + PlayerInfo.GetColoredName(p, name);

            p.Message("The IP {0} %Shas been traced to: ", target);
            p.Message("  Continent: &f{1}&S ({0})", info.continent_abbr, info.continent);
            p.Message("  Country: &f{1}&S ({0})", info.country_abbr, info.country);
            p.Message("  Region/State: &f{0}", info.subdivision);
            p.Message("  City: &f{0}", info.city);
            p.Message("  Time Zone: &f{0}", info.timezone);
            p.Message("  Hostname: &f{0}", info.host);
            p.Message("  Is using proxy: &f{0}", info.proxy);
            p.Message("Geoip information by: &9http://geoip.pw/");
        }
Beispiel #14
0
        // This function will get triggered/executed when a new message is written
        // on an Azure Queue called queue.
        public static void ProcessQueueMessage([QueueTrigger("%GeoInfoQueue%")] string message, TextWriter log)
        {
            KindAdsTelemetryManager manager = new KindAdsTelemetryManager();
            string DatabaseName             = ConfigurationManager.AppSettings["CosmosDatabaseName"];
            string CollectionName           = ConfigurationManager.AppSettings["CosmosGeoCollectionName"];

            GeoInfo info = manager.GetInfo <GeoInfo>(message);

            manager.SendToCosmos(info, DatabaseName, CollectionName);
        }
Beispiel #15
0
    public GeoInfo Clone()
    {
        GeoInfo newGeoInfo = new GeoInfo();

        newGeoInfo.GeoType      = GeoType;
        newGeoInfo.Position     = Position;
        newGeoInfo.Rotation     = Rotation;
        newGeoInfo.Color        = Color;
        newGeoInfo.Size         = Size;
        newGeoInfo.SortingOrder = SortingOrder;
        return(newGeoInfo);
    }
        async public Task RunAsync(MemCheckDbContext dbContext)
        {
            var geoInfo = new GeoInfo();
            var user    = await dbContext.Users.Where(u => u.UserName == "VoltanBot").SingleAsync();

            await UpdateCards_WhatIsThisRegionAsync(user.Id, geoInfo);
            await UpdateCards_WhereIsThisRegionAsync(user.Id, geoInfo);
            await UpdateCards_HowManyDepartmentsInThisRegionAsync(user.Id, geoInfo);
            await UpdateCards_WhatAreTheDepartmentsInThisRegionAsync(user.Id, geoInfo);

            await dbContext.SaveChangesAsync();

            logger.LogInformation($"Generation finished");
        }
Beispiel #17
0
        public override void Use(Player p, string message, CommandData data)
        {
            if (message.Length == 0)
            {
                if (p.IsSuper)
                {
                    SuperRequiresArgs(p, "player name or IP"); return;
                }
                message = p.name;
            }

            string name, ip = ModActionCmd.FindIP(p, message, "Location", out name);

            if (ip == null)
            {
                return;
            }

            if (HttpUtil.IsPrivateIP(ip))
            {
                p.Message("%WPlayer has an internal IP, cannot trace"); return;
            }

            bool   success;
            string ipInfo;

            using (WebClient client = HttpUtil.CreateWebClient()) {
                ipInfo = client.DownloadString("http://ipinfo.io/" + ip + "/geo");
            }

            JsonObject obj  = (JsonObject)Json.Parse(ipInfo, out success);
            GeoInfo    info = new GeoInfo();

            if (obj == null || !success)
            {
                p.Message("%WError parsing GeoIP info"); return;
            }

            if (elems == null)
            {
                elems = ConfigElement.GetAll(typeof(GeoInfo));
            }
            obj.Deserialise(elems, info);

            string suffix = HasExtraPerm(p, data.Rank, 1) ? "&b{1}%S/&b{2}" : "&b{2}";
            string nick   = name == null ? ip : "of " + p.FormatNick(name);

            p.Message("The IP {0} %Straces to: " + suffix, nick, info.region, info.country);
        }
Beispiel #18
0
        public virtual List <T> QueryNearBy(Expression <Func <T, bool> > where, int page, int pagesize,
                                            Expression <Func <T, object> > field, GeoInfo point,
                                            double?max_distance = null, double?min_distance = null)
        {
            var condition = Builders <T> .Filter.Empty;

            condition &= Builders <T> .Filter.Near(field, point.Lat, point.Lon, max_distance, min_distance);

            if (where != null)
            {
                condition &= Builders <T> .Filter.Where(where);
            }

            return(this._collection.Find(condition).QueryPage(page, pagesize).ToList());
        }
Beispiel #19
0
        private async Task <GeoInfo> FillWithDetails(string ip)
        {
            var apiKey   = ConfigurationManager.AppSettings["apiKey"];
            var url      = String.Format("http://api.ipstack.com/{0}&access_key={1}", ip, apiKey);
            var response = await new HttpClient().GetAsync(url);

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Fetching ip details from external source failed! Please try again later.");
            }
            JObject jsonBody = JObject.Parse(await response.Content.ReadAsStringAsync());
            GeoInfo geoInfo  = jsonBody.ToObject <GeoInfo>();

            return(geoInfo);
        }
Beispiel #20
0
    void Start()
    {
        client  = ServicePropertiesClass.GetGapslabsService(ServicePropertiesClass.ServiceUri);
        geoinfo = transform.GetComponent <GeoInfo>();

        var go = GameObject.Find("AramGISBoundaries");

        mapBoundaries = go.GetComponent <MapBoundaries>();
        wcfCon        = mapBoundaries.OverrideDatabaseConnection ? mapBoundaries.GetOverridenConnectionString() : ServicePropertiesClass.ConnectionPostgreDatabase;

        boundsTemp = client.GetBounds(wcfCon);
        // Temporary - it appears the data for sweden includes some data that go to the north pole and it ruins all interpolations.
        boundsTemp.maxlon = 32;

        MinMaxLat = new float[2];
        MinMaxLon = new float[2];
        // Setting local values for target boundaries (Openstreetmap database). Used in interpolation as destination boundary.
        MinMaxLat[0] = (float)boundsTemp.minlat;
        MinMaxLat[1] = (float)boundsTemp.maxlat;
        MinMaxLon[0] = (float)boundsTemp.minlon;
        MinMaxLon[1] = (float)boundsTemp.maxlon;



        // Setting local values for 3d world boundaries. Used in interpolation as source boundary
        GameBoundaries        = new BoundsWCF();
        GameBoundaries.minlat = mapBoundaries.minMaxX[0];
        GameBoundaries.maxlat = mapBoundaries.minMaxX[1];
        GameBoundaries.minlon = mapBoundaries.minMaxY[0];
        GameBoundaries.maxlon = mapBoundaries.minMaxY[1];
        GameBoundLat          = new float[2];
        GameBoundLat[0]       = (float)GameBoundaries.minlat;
        GameBoundLat[1]       = (float)GameBoundaries.maxlat;
        GameBoundLon          = new float[2];
        GameBoundLon[0]       = (float)GameBoundaries.minlon;
        GameBoundLon[1]       = (float)GameBoundaries.maxlon;



        float[] MinPointOnArea =
            Interpolations.SimpleInterpolation(
                (float)mapBoundaries.minLat,
                (float)mapBoundaries.minLon,
                boundsTemp,
                GameBoundLat, GameBoundLon);
        MinPointOnMap = new Vector3(MinPointOnArea[0], 0, MinPointOnArea[1]);
    }
Beispiel #21
0
    public static GeoGroupInfo GenerateGeoGroupInfoFromXML(XmlNode creatureElement)
    {
        GeoGroupInfo ggi = new GeoGroupInfo();

        ggi.Name = creatureElement.Attributes["name"].Value;

        XmlNode creatureInfo = creatureElement.ChildNodes[0];

        ggi.FertilityRate        = int.Parse(creatureInfo.Attributes["FertilityRate"].Value);
        ggi.OffspringSizePercent = int.Parse(creatureInfo.Attributes["OffspringSizePercent"].Value);
        ggi.MatureSizePercent    = int.Parse(creatureInfo.Attributes["MatureSizePercent"].Value);
        ggi.MinSizePercent       = int.Parse(creatureInfo.Attributes["MinSizePercent"].Value);
        ggi.MaxSizePercent       = int.Parse(creatureInfo.Attributes["MaxSizePercent"].Value);
        ggi.GrowUpRate           = float.Parse(creatureInfo.Attributes["GrowUpRate"].Value);
        ggi.StartNumber          = int.Parse(creatureInfo.Attributes["StartNumber"].Value);
        ggi.MaxNumber            = int.Parse(creatureInfo.Attributes["MaxNumber"].Value);

        List <string> diets     = creatureInfo.Attributes["Diets"].Value.Split(',').ToList();
        List <string> predators = creatureInfo.Attributes["Predators"].Value.Split(',').ToList();

        foreach (string diet in diets)
        {
            if (!string.IsNullOrWhiteSpace(diet))
            {
                ggi.Diets.Add(diet);
            }
        }

        foreach (string p in predators)
        {
            if (!string.IsNullOrWhiteSpace(p))
            {
                ggi.Predators.Add(p);
            }
        }

        XmlNode geoInfos_element = creatureElement.ChildNodes[1];

        for (int i = 0; i < geoInfos_element.ChildNodes.Count; i++)
        {
            XmlNode geoInfo_element = geoInfos_element.ChildNodes[i];
            GeoInfo gi = GeoInfo.GenerateGeoInfoFromXML(geoInfo_element);
            ggi.GeoInfos.Add(gi);
        }

        return(ggi);
    }
Beispiel #22
0
        public async Task <GeoInfo> FetchGeoInfo(GeoInfo geoInfo)
        {
            // If geoInfo is local ip, fetch without ip query
            string formattedFetchURL            = geoInfo.IsLocalIP ? FetchURL : $"{FetchURL}?ip={geoInfo.IP}";
            HttpResponseMessage geoFetchResults = await client.GetAsync(formattedFetchURL);

            if (geoFetchResults.IsSuccessStatusCode == true)
            {
                HttpContent content       = geoFetchResults.Content;
                string      stringContent = content.ToString();
                Dictionary <string, dynamic> parsedJson = Json.Deserialize <Dictionary <string, dynamic> >(stringContent);
                bool jsonStatusCodeOk = (parsedJson.ContainsKey("geoplugin_status") && parsedJson["geoplugin_status"] != 404) ? true : false;
                if (jsonStatusCodeOk)
                {
                    foreach (var item in parsedJson)
                    {
                        switch (item.Key)
                        {
                        case "geoplugin_countryCode":
                            // Only set from fetch when we have a country code
                            geoInfo.FromFetch   = true;
                            geoInfo.CountryCode = item.Value;
                            break;

                        case "geoplugin_city":
                            geoInfo.CityName = item.Value;
                            break;

                        case "geoplugin_region":
                            geoInfo.RegionName = item.Value;
                            break;
                        }
                    }
                }
                else
                {
                    // Should be a debug message (currently broken)
                    ChatBox.WriteLine("Status 404");
                }
            }
            else
            {
                // Should be a debug message (currently broken)
                ChatBox.WriteLine("Could not fetch geo data. Error code: " + geoFetchResults.StatusCode.ToString());
            }
            return(geoInfo);
        }
Beispiel #23
0
        private async void HandlePlayerJoined(Player player)
        {
            GeoInfo geoInfo = new GeoInfo(player);

            // Fetch player geoloc
            if (database.HasConnection() == true)
            {
                geoInfo = await database.GetGeoInfo(geoInfo);
            }
            if (!geoInfo.FromDatabase)
            {
                geoInfo = await fetch.FetchGeoInfo(geoInfo);
            }
            database.SaveCache(geoInfo);
            geoInfo.OutputDebug();
            OutputPlayerJoined(geoInfo);
        }
Beispiel #24
0
    public void RefreshInfo()
    {
        if (Cur_GGI == null)
        {
            Cur_GGI = new GeoGroupInfo();
        }
        Cur_GGI.GeoInfos.Clear();
        foreach (GeoElement geo in GeoElements)
        {
            GeoInfo gi = geo.ExportGeoInfo();
            Cur_GGI.GeoInfos.Add(gi);
        }

        Cur_GGI.RefreshInfo();
        UIManager.Instance.GetBaseUIForm <CreatureEditorPanel>().RefreshLeftPanelInfo(Cur_GGI);
        UIManager.Instance.GetBaseUIForm <CreatureEditorPanel>().GetLeftPanelManualInfo(Cur_GGI);
    }
Beispiel #25
0
    public static GeoInfo GenerateGeoInfoFromXML(XmlNode geo_ele)
    {
        GeoInfo geoInfo = new GeoInfo();

        geoInfo.GeoType = (GeoTypes)Enum.Parse(typeof(GeoTypes), geo_ele.Attributes["GeoType"].Value);

        string[] Position_Str    = geo_ele.Attributes["Position"].Value.Split(',');
        float[]  Position_values = new float[Position_Str.Length];
        for (int i = 0; i < Position_Str.Length; i++)
        {
            Position_values[i] = float.Parse(Position_Str[i]);
        }

        geoInfo.Position = new Vector2(Position_values[0], Position_values[1]);

        string[] Rotation_Str    = geo_ele.Attributes["Rotation"].Value.Split(',');
        float[]  Rotation_values = new float[Rotation_Str.Length];
        for (int i = 0; i < Rotation_Str.Length; i++)
        {
            Rotation_values[i] = float.Parse(Rotation_Str[i]);
        }

        geoInfo.Rotation = new Quaternion(Rotation_values[0], Rotation_values[1], Rotation_values[2], Rotation_values[3]);

        string[] Color_Str    = geo_ele.Attributes["Color"].Value.Split(',');
        float[]  Color_values = new float[Color_Str.Length];
        for (int i = 0; i < Color_Str.Length; i++)
        {
            Color_values[i] = float.Parse(Color_Str[i]);
        }

        geoInfo.Color = new Color(Color_values[0], Color_values[1], Color_values[2], Color_values[3]);

        string[] Size_Str    = geo_ele.Attributes["Size"].Value.Split(',');
        float[]  Size_values = new float[Size_Str.Length];
        for (int i = 0; i < Size_Str.Length; i++)
        {
            Size_values[i] = float.Parse(Size_Str[i]);
        }

        geoInfo.Size         = new Vector2(Size_values[0], Size_values[1]);
        geoInfo.SortingOrder = int.Parse(geo_ele.Attributes["SortingOrder"].Value);

        return(geoInfo);
    }
Beispiel #26
0
        public async Task <IHttpActionResult> DeleteGeoInfo(int id)
        {
            try
            {
                GeoInfo geoInfo = await db.GeoInfos.FindAsync(id);

                if (geoInfo == null)
                {
                    return(JsonResult.NotFound(string.Format("GeoInfo with id:{0} could not be found!", id)));
                }

                db.GeoInfos.Remove(geoInfo);
                await db.SaveChangesAsync();

                return(JsonResult.Success(string.Format("GeoInfo with id:{0} was removed successfully!", id)));
            }
            catch (Exception e)
            {
                return(JsonResult.Error(string.Format("Error: could not delete GeoInfo with id:{0} due to error :{1}", id, e.Message)));
            }
        }
Beispiel #27
0
        public async Task <IHttpActionResult> GetGeoInfo(int id)
        {
            logger.Info(string.Format("Trying to find GeoInfo with id:{0}", id));
            try
            {
                GeoInfo geoInfo = await db.GeoInfos.Include(gi => gi.Location.Languages).Where(gi => gi.Id == id).SingleOrDefaultAsync();

                if (geoInfo == null)
                {
                    logger.Info(string.Format("GeoInfo with id:{0} could not be found!", id));
                    return(JsonResult.NotFound(string.Format("GeoInfo with id:{0} could not be found!", id)));
                }
                var geoInfoDto = Mapper.Map <GeoInfo, GeoInfoDto>(geoInfo);
                logger.Info(string.Format("Returning GeoInfo with id:{0}", id));
                return(JsonResult.Success(geoInfoDto));
            }
            catch (Exception e)
            {
                logger.Error(e.Message);
                logger.Error(e.StackTrace);
                return(JsonResult.Error(string.Format("Could not fetch GeoInfo with id:{0} due to error: {1}", id, e.Message)));
            }
        }
Beispiel #28
0
        public GeoInfo GetGeoInfoLocal(string ip)
        {
            if (string.IsNullOrEmpty(ip))
            {
                return(default(GeoInfo));
            }

            try
            {
                CityResponse city;
                if (reader.TryCity(ip, out city))
                {
                    var result = new GeoInfo(city.Country.Name, city.City.Name);
                    return(result);
                }
                return(default(GeoInfo));
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return(default(GeoInfo));
            }
        }
Beispiel #29
0
        /// <summary>以给定的点位为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素</summary>
        /// <param name="member"></param>
        /// <param name="radius"></param>
        /// <param name="unit"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public GeoInfo[] GetRadius(String member, Double radius, String unit = null, Int32 count = 0)
        {
            if (unit.IsNullOrEmpty())
            {
                unit = "m";
            }

            var rs = count > 0 ?
                     Execute(rc => rc.Execute <Object[]>("GEORADIUSBYMEMBER", Key, member, radius, unit, "WITHDIST", "WITHCOORD", "COUNT", count), false) :
                     Execute(rc => rc.Execute <Object[]>("GEORADIUSBYMEMBER", Key, member, radius, unit, "WITHDIST", "WITHCOORD"), false);

            if (rs == null || rs.Length == 0)
            {
                return(null);
            }

            var list = new List <GeoInfo>();

            for (var i = 0; i < rs.Length; i++)
            {
                var inf = new GeoInfo();
                if (rs[i] is Object[] vs)
                {
                    inf.Name     = (vs[0] as Packet).ToStr();
                    inf.Distance = (vs[1] as Packet).ToStr().ToDouble();
                    if (vs[2] is Object[] vs2)
                    {
                        inf.Longitude = (vs2[0] as Packet).ToStr().ToDouble();
                        inf.Latitude  = (vs2[1] as Packet).ToStr().ToDouble();
                    }
                }

                list.Add(inf);
            }

            return(list.ToArray());
        }
Beispiel #30
0
        /// <summary>获取一批点的坐标</summary>
        /// <param name="members"></param>
        /// <returns></returns>
        public GeoInfo[] GetPosition(params String[] members)
        {
            var args = new List <Object> {
                Key
            };

            foreach (var item in members)
            {
                args.Add(item);
            }

            var rs = Execute(rc => rc.Execute <Object[]>("GEOPOS", args.ToArray()), false);

            if (rs == null || rs.Length == 0)
            {
                return(null);
            }

            var list = new List <GeoInfo>();

            for (var i = 0; i < rs.Length; i++)
            {
                var inf = new GeoInfo {
                    Name = members[i]
                };
                if (rs[i] is Object[] vs)
                {
                    inf.Longitude = (vs[0] as Packet).ToStr().ToDouble();
                    inf.Latitude  = (vs[1] as Packet).ToStr().ToDouble();
                }

                list.Add(inf);
            }

            return(list.ToArray());
        }
 private void GeoIpReceived(ServerRow server, GeoInfo geoInfo)
 {
     server.GeoInfo = geoInfo;
       Interlocked.Exchange(ref this.geoIpModified, 1);
 }
Beispiel #32
0
        private void Upload_Geo_Click(object sender, EventArgs e)
        {
            openFileDialog1.Multiselect = false;
            openFileDialog1.Title = "几何信息导入数据库";
            openFileDialog1.FileName = "几何信息模板.xlsx";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                ExcelCmd excelcmd = new ExcelCmd();
                excelcmd.CreateOrOpenExcelFile(false, openFileDialog1.FileName);
                excelcmd.SetActiveSheet(1);

                string[] column = Enum.GetNames(typeof(ColName_VehicleGeo));

                int ExcelRow = excelcmd.GetLastRow(1);

                progressBar.Minimum = 0;
                progressBar.Value = 0;
                progressBar.Maximum = ExcelRow - 1;

                for (int iLoop = 2; iLoop <= ExcelRow; ++iLoop)
                {
                    progressBar.Value++;
                    GeoInfo UpdataGeoInfo = new GeoInfo();

                    UpdataGeoInfo.视图 = (string)excelcmd.GetCell(iLoop, 6);
                    string path = (string)excelcmd.GetCell(iLoop, 5);
                    string filter = Path.GetExtension(path).Substring(1, Path.GetExtension(path).Length - 1);

                    UpdataGeoInfo.Ext = filter;
                    if (UpdataGeoInfo.Ext.ToUpper() == "TMPLT" ||
                            UpdataGeoInfo.Ext.ToUpper() == "LQB" ||
                            UpdataGeoInfo.Ext.ToUpper() == "BWF" ||
                            UpdataGeoInfo.Ext.ToUpper() == "PRT" ||
                            UpdataGeoInfo.Ext.ToUpper() == "STL" ||
                            UpdataGeoInfo.Ext.ToUpper() == "JPG")
                    {
                        UpdataGeoInfo.汽车ID = (string)excelcmd.GetCell(iLoop, 1);
                        UpdataGeoInfo.Car = (string)excelcmd.GetCell(iLoop, 2);
                        UpdataGeoInfo.Band = (string)excelcmd.GetCell(iLoop, 3);
                        UpdataGeoInfo.Factory = (string)excelcmd.GetCell(iLoop, 4);

                        string str = "select top 1 版本 from GeoInfo_" + UpdataGeoInfo.Ext +
                            " where 汽车ID = '" + UpdataGeoInfo.汽车ID + "' and 视图= '" + UpdataGeoInfo.视图 +
                            " 'order by 版本 desc";
                        DatabaseCmd datacmd = new DatabaseCmd();
                        MySqlDataReader myreader;
                        datacmd.SqlExecuteReader(str, out myreader);

                        UpdataGeoInfo.Version = (myreader.Read()) ? (UpdataGeoInfo.Version = myreader.GetInt32(0) + 1) : (1);
                        datacmd.SqlReaderClose();

                        UserFunction.FileToBinary(path, out UpdataGeoInfo.ByteData);
                        UpdataGeoInfo.IsModel = ((string)excelcmd.GetCell(iLoop, 7) == "是") ? (true) : (false);
                        UpdataGeoInfo.UpdateDate = UserFunction.GetServerDateTime();
                        UpdataGeoInfo.信息更新者工号 = ManagementMain.UserNum;
                        UpdataGeoInfo.信息更新者姓名 = ManagementMain.UserName;

                        if (UpdataGeoInfo.ByteData != null)
                        {
                            SqlUploadGeoInfo(column, UpdataGeoInfo, 5);
                        }
                    }
                    else
                    {
                        MessageBox.Show("请上传正确的数据文件");
                    }
                }
                excelcmd.ExitExcelApp();
                MessageBox.Show("导入成功");
                ManagementMain.refreshgeoinfo("", 1);
            }
        }
Beispiel #33
0
        public bool SqlUploadGeoInfo(string[] Column, GeoInfo GeoInfoStruct, int ReserveNum)
        {
            DatabaseCmd SelectCmd = new DatabaseCmd();
            string sqlstr = "select count(汽车ID) from GeoInfo_" + GeoInfoStruct.Ext +
                " where 汽车ID = '" + GeoInfoStruct.汽车ID + "' and 视图 = '" + GeoInfoStruct.视图 + "'";
            try
            {
                MySqlDataReader myreader;
                SelectCmd.SqlExecuteReader(sqlstr, out myreader);
                if (myreader.Read())
                {
                    if (myreader.GetInt32(0) >= ReserveNum)
                    {
                        string delStr = "delete from GeoInfo_" + GeoInfoStruct.Ext + " where 汽车ID = '" + GeoInfoStruct.汽车ID +
                            "' and 视图 = '" + GeoInfoStruct.视图 + "' and 版本 not in (select top " + (ReserveNum - 1) + " (版本) from [GeoInfo_" +
                            GeoInfoStruct.Ext + "] where 汽车ID = '" + GeoInfoStruct.汽车ID + "' order by 版本 desc) ";
                        DatabaseCmd deleteCmd = new DatabaseCmd();
                        deleteCmd.SqlExecuteNonQuery(delStr);
                    }
                }
            }
            catch (Exception ex){MessageBox.Show(ex.Message);}
            finally{SelectCmd.SqlReaderClose();}

            DatabaseCmd datacmd = new DatabaseCmd();
            datacmd.GetConnection().Open();
            MySqlTransaction myTran = datacmd.GetConnection().BeginTransaction();
            try
            {
                datacmd.GetCommand().Connection = datacmd.GetConnection();
                datacmd.GetCommand().Transaction = myTran;
                datacmd.GetCommand().CommandType = CommandType.Text;
                datacmd.GetCommand().CommandText = "insert into GeoInfo_" + GeoInfoStruct.Ext + " (";
                for (int iLoop = 0; iLoop < Column.Length - 2; ++iLoop)
                {
                    datacmd.GetCommand().CommandText = datacmd.GetCommand().CommandText + Column[iLoop] + ",";
                }
                datacmd.GetCommand().CommandText += "信息更新者姓名) values (@str1, @str2, @str3, @str4,@byte1, @str5, @int1" +
                    ", @bool1, @date1, @str6, @str7)";

                SqlParameter str1 = new SqlParameter("@str1", SqlDbType.NVarChar);
                SqlParameter str2 = new SqlParameter("@str2", SqlDbType.NVarChar);
                SqlParameter str3 = new SqlParameter("@str3", SqlDbType.NVarChar);
                SqlParameter str4 = new SqlParameter("@str4", SqlDbType.NVarChar);
                SqlParameter byte1 = new SqlParameter("@byte1", SqlDbType.Image);
                SqlParameter str5 = new SqlParameter("@str5", SqlDbType.NVarChar);
                SqlParameter int1 = new SqlParameter("@int1", SqlDbType.Int);
                SqlParameter bool1 = new SqlParameter("@bool1", SqlDbType.Bit);
                SqlParameter date1 = new SqlParameter("@date1", SqlDbType.DateTime);
                SqlParameter str6 = new SqlParameter("@str6", SqlDbType.NVarChar);
                SqlParameter str7 = new SqlParameter("@str7", SqlDbType.NVarChar);

                str1.Value = GeoInfoStruct.汽车ID;
                str2.Value = GeoInfoStruct.Car;
                str3.Value = GeoInfoStruct.Factory;
                str4.Value = GeoInfoStruct.Band;

                if (GeoInfoStruct.ByteData != null) { byte1.Value = GeoInfoStruct.ByteData; }
                else { byte1.Value = System.DBNull.Value; }

                str5.Value = GeoInfoStruct.视图;

                int1.Value = GeoInfoStruct.Version;
                bool1.Value = GeoInfoStruct.IsModel;
                date1.Value = GeoInfoStruct.UpdateDate;
                str6.Value = GeoInfoStruct.信息更新者工号;
                str7.Value = GeoInfoStruct.信息更新者姓名;

                datacmd.GetCommand().Parameters.Add(str1);
                datacmd.GetCommand().Parameters.Add(str2);
                datacmd.GetCommand().Parameters.Add(str3);
                datacmd.GetCommand().Parameters.Add(str4);
                datacmd.GetCommand().Parameters.Add(byte1);
                datacmd.GetCommand().Parameters.Add(str5);
                datacmd.GetCommand().Parameters.Add(int1);
                datacmd.GetCommand().Parameters.Add(bool1);
                datacmd.GetCommand().Parameters.Add(date1);
                datacmd.GetCommand().Parameters.Add(str6);
                datacmd.GetCommand().Parameters.Add(str7);

                datacmd.GetCommand().ExecuteNonQuery();
                myTran.Commit();

                if (GeoInfoStruct.IsModel == true)
                {
                    string updatestr = "update GeoInfo_" + GeoInfoStruct.Ext + " set 是否模板 = 'false' where 汽车ID = '" +
                        GeoInfoStruct.汽车ID + "' and 视图 = '" + GeoInfoStruct.视图 + "'  and 版本 <>" + GeoInfoStruct.Version;
                    DatabaseCmd updatedatabase = new DatabaseCmd();
                    updatedatabase.SqlExecuteNonQuery(updatestr);
                }

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                myTran.Rollback();
                return false;
            }
            finally
            {
                myTran.Dispose();
                datacmd.GetCommand().Transaction = null;
                datacmd.GetConnection().Close();
            }
        }