Example #1
0
 private Location Create(LocationData locationData)
 {
     return new Location
     {
         Building = locationData.Building,
         Description = locationData.Description,
     };
 }
Example #2
0
        public Int32 AddProfile(LocationData request)
        {
            Int32 response = -1;

            using (var context = new TICPuppyLoveDbContext())
            {
                using (var dbTran = context.Database.BeginTransaction())
                {
                    try
                    {
                        var oParm = new SqlParameter
                        {
                            ParameterName = "@TotalCount",
                            DbType = DbType.Int32,
                            Direction = ParameterDirection.Output
                        };
                        context.Database.ExecuteSqlCommand(
                            "EXEC SP_AddUpdateLocation @UserID, @Latitude, @Longitude, @Accuracy, @TimeStamp, @TotalCount OUTPUT",
                            new SqlParameter("@UserID", request.UserID),
                            new SqlParameter("@Latitude", request.Latitude),
                            new SqlParameter("@Longitude", request.Longitude),
                            new SqlParameter("@Accuracy", request.Accuracy),
                            new SqlParameter("@TimeStamp", request.Timestamp),
                            oParm
                            );
                        context.SaveChanges();
                        response = Convert.ToInt32(oParm.Value);
                        dbTran.Commit();
                    }

                    catch (Exception ex)
                    {
                        dbTran.Rollback();
                        throw;
                    }
                }
            }

            return response;
        }
Example #3
0
        /// <summary>
        /// Gets all current locations via ORM.  Used for getting all locations with no distance calculation.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public List<LocationData> GetCurrentLocations(LocationData request)
        {
            List<LocationData> response = new List<LocationData>();

            using (var dbEntities = new TICPuppyLoveDbContext())
            {
                response = (from loc in dbEntities.Locations
                            //WHERE blah blah blah - Currently we are not filtering based on the request - return all
                            orderby loc.UserID
                            select new LocationData
                            {
                                UserID = loc.UserID,
                                Latitude = loc.Latitude,
                                Longitude = loc.Longitude,
                                Accuracy = loc.Accuracy,
                                Timestamp = loc.TimeStamp
                            }
                                ).ToList();
            }

            return response;
        }
Example #4
0
            private List<Connection> getLegalConnections(
			LocationData[,] map, int tileFrom,
			bool isBombPassable, bool isDestructiblePassable)
            {
                List<Connection> connections = new List<Connection> ();

                int mapWidth = this.gs.Width;
                int mapHeight = this.gs.Height;

                Coords coords = Coords.coordsTileNum (mapWidth, mapHeight, tileFrom);

                List<Coords> possibleCoords = this.gs.GetAdjacentAccessibleTiles (
                tileFrom, isBombPassable, isDestructiblePassable);

                foreach (Coords possibleCoord in possibleCoords) {
                    Node from = new MapLocation (coords);
                    Node to = new MapLocation (possibleCoord);
                    Connection conn = new Connection (from, to, MOVEMENT_COST + this.gs.tacticalCost(possibleCoord));
                    connections.Add (conn);
                }

                return connections;
            }
Example #5
0
        private List <Location> GetResidentLocations()
        {
            LocationData ld = new LocationData();

            return(ld.GetList("SELECT * FROM vw_Locations WHERE IsRollCall=true"));
        }
Example #6
0
        /// <summary>
        /// Attempts to update the travel distance and time info for the specified locations,
        /// relative to the current location, and raises an alert for each flagged location
        /// if traffic is currently increasing the travel time by 10 minutes or more; also
        /// updates the network status message depending on the results.
        /// </summary>
        private async Task <bool> TryUpdateLocationsTravelInfoAsync(IEnumerable <LocationData> locations, LocationData currentLocation)
        {
            bool isNetworkAvailable = await LocationHelper.TryUpdateLocationsTravelInfoAsync(this.Locations, currentLocation);

            this.UpdateNetworkStatus(isNetworkAvailable);
            return(isNetworkAvailable);
        }
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.FollowGPS)
            {
                if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) != Permission.Granted)
                {
                    return(false);
                }

                Android.Locations.Location location = null;

                if (WearableHelper.IsGooglePlayServicesInstalled && !WearableHelper.HasGPS)
                {
                    var mFusedLocationClient = new FusedLocationProviderClient(this);
                    location = await mFusedLocationClient.GetLastLocationAsync();
                }
                else
                {
                    LocationManager locMan       = GetSystemService(Context.LocationService) as LocationManager;
                    bool            isGPSEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.GpsProvider);
                    bool            isNetEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.NetworkProvider);

                    if (isGPSEnabled || isNetEnabled)
                    {
                        Criteria locCriteria = new Criteria()
                        {
                            Accuracy = Accuracy.Coarse, CostAllowed = false, PowerRequirement = Power.Low
                        };
                        string provider = locMan.GetBestProvider(locCriteria, true);
                        location = locMan.GetLastKnownLocation(provider);
                    }
                    else
                    {
                        Toast.MakeText(this, Resource.String.error_retrieve_location, ToastLength.Short).Show();
                    }
                }

                if (location != null)
                {
                    LocationData lastGPSLocData = await Settings.GetLastGPSLocData();

                    // Check previous location difference
                    if (lastGPSLocData.query != null &&
                        Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                      location.Latitude, location.Longitude)) < 1600)
                    {
                        return(false);
                    }

                    LocationQueryViewModel view = null;

                    await Task.Run(async() =>
                    {
                        view = await wm.GetLocation(location);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    });

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        return(false);
                    }

                    // Save location as last known
                    lastGPSLocData.SetData(view, location);
                    Settings.SaveHomeData(lastGPSLocData);

                    locationChanged = true;
                }
            }

            return(locationChanged);
        }
Example #8
0
        private static Order ConvertToOrderFromPlanner(DataRow row, PlannerDataSet.PlannerAssignmentsDataTable table)
        {
            Order          order   = new Order();
            PlannerDataSet dataset = new PlannerDataSet();

            order.Id = Convert.ToInt64(row[table.OrderIdColumn.ColumnName]);

            order.Reference = row[table.ReferenceColumn.ColumnName].ToString();

            order.StartDate    = (DateTime)row[table.StartDateColumn.ColumnName];
            order.FinalDate    = (DateTime)row[table.FinalDateColumn.ColumnName];
            order.CreatedDate  = (DateTime)row[table.CreatedDateColumn.ColumnName];
            order.ModifiedDate = (DateTime)row[table.ModifiedDateColumn.ColumnName];

            if (string.IsNullOrEmpty(row[table.TripIdColumn.ColumnName].ToString()))
            {
                order.TripId = 0;
            }
            else
            {
                order.TripId = Convert.ToInt32(row[table.TripIdColumn.ColumnName].ToString());
            }


            order.HexColor = GetColorLoaded(Convert.ToInt32(order.TripId.ToString()));


            LocationData location = new LocationData();

            location.Address  = row[table.AddressColumn.ColumnName].ToString();
            location.City     = row[table.CityColumn.ColumnName].ToString();
            location.PostCode = row[table.PostCodeColumn.ColumnName].ToString();
            location.Province = row[table.ProvinceColumn.ColumnName].ToString();
            location.Country  = row[table.CountryColumn.ColumnName].ToString();


            float.TryParse(row[table.LatitudeColumn.ColumnName].ToString(), out float loc);
            location.Latitude = loc;

            float.TryParse(row[table.LongitudeColumn.ColumnName].ToString(), out loc);
            location.Longitude = loc;

            order.Location = location;

            Int32.TryParse(row[table.VehicleSizeColumn.ColumnName].ToString(), out int num);
            order.VehicleType = num;

            Int32.TryParse(row[table.RequestedAmountColumn.ColumnName].ToString(), out num);
            order.RequestedAmount = num;

            Int32.TryParse(row[table.ReceivedAmountColumn.ColumnName].ToString(), out num);
            order.ReceivedAmount = num;

            //si la cantidad recivida no tiene valor se coje la que se espera requestedAmount
            if (order.ReceivedAmount == 0)
            {
                Int32.TryParse(row[table.RequestedAmountColumn.ColumnName].ToString(), out num);
                order.ReceivedAmount = num;
            }

            //aqui
            order.TankNum    = row[table.TankNumColumn.ColumnName].ToString();
            order.TankVolume = row[table.TankVolumeColumn.ColumnName].ToString();
            order.TankLevel  = row[table.TankLevelColumn.ColumnName].ToString();
            order.Status     = row[table.StatusColumn.ColumnName] as int? ?? 0;
            //order.Description = row[table.DescriptionColumn.ColumnName].ToString();
            //order.Observations = row[table.ObservationsColumn.ColumnName].ToString();


            //operadores


            PlannerDataSetTableAdapters.OperatorsTableAdapter operatoradapter = new PlannerDataSetTableAdapters.OperatorsTableAdapter();
            PlannerDataSet.OperatorsDataTable dataTableOperators = operatoradapter.GetDataByOperatorId(Convert.ToInt32(row[table.OperatorIdColumn.ColumnName]));



            order.Operator = new Operator()
            {
                Id   = Convert.ToInt32(row[table.OperatorIdColumn.ColumnName]),
                Code = dataTableOperators.Rows[0]["Code"].ToString(),
                Name = dataTableOperators.Rows[0]["Name"].ToString(),
                Cif  = dataTableOperators.Rows[0]["Cif"].ToString(),

                Location = new LocationData()
                {
                    Address  = dataTableOperators.Rows[0]["Address"].ToString(),
                    City     = dataTableOperators.Rows[0]["City"].ToString(),
                    PostCode = dataTableOperators.Rows[0]["PostCode"].ToString(),
                    Province = dataTableOperators.Rows[0]["Province"].ToString(),
                    Country  = dataTableOperators.Rows[0]["Country"].ToString(),
                },

                Contact = new ContactData()
                {
                    Name        = dataTableOperators.Rows[0]["Name"].ToString(),
                    Phone       = dataTableOperators.Rows[0]["Phone"].ToString(),
                    Phone2      = dataTableOperators.Rows[0]["Phone2"].ToString(),
                    PhoneMobile = dataTableOperators.Rows[0]["PhoneMobile"].ToString(),
                    Fax         = dataTableOperators.Rows[0]["Fax"].ToString(),
                    Email       = dataTableOperators.Rows[0]["Email"].ToString()
                },


                Enabled = (bool)dataTableOperators.Rows[0]["Enabled"],
                //Observations = row[table.ClientObservationsColumn.ColumnName].ToString(),
            };


            //clientes

            PlannerDataSetTableAdapters.ClientsTableAdapter adapter = new PlannerDataSetTableAdapters.ClientsTableAdapter();
            PlannerDataSet.ClientsDataTable dataTableClients        = adapter.GetDataByIdClient(Convert.ToInt32(row[table.ClientIdColumn.ColumnName]));

            order.Client = new Client()
            {
                Id   = Convert.ToInt32(dataTableClients.Rows[0]["Id"].ToString()),
                Code = dataTableClients.Rows[0]["Code"].ToString(),
                Name = dataTableClients.Rows[0]["Name"].ToString(),
                Cif  = dataTableClients.Rows[0]["Cif"].ToString(),

                Location = new LocationData()
                {
                    Address  = dataTableClients.Rows[0]["Address"].ToString(),
                    City     = dataTableClients.Rows[0]["City"].ToString(),
                    PostCode = dataTableClients.Rows[0]["PostCode"].ToString(),
                    Province = dataTableClients.Rows[0]["Province"].ToString(),
                    Country  = dataTableClients.Rows[0]["Country"].ToString(),

                    Latitude  = (float)dataTableClients.Rows[0]["Latitude"],
                    Longitude = (float)dataTableClients.Rows[0]["Longitude"],
                },

                Contact = new ContactData()
                {
                    Name        = dataTableClients.Rows[0]["Name"].ToString(),
                    Phone       = dataTableClients.Rows[0]["Phone"].ToString(),
                    Phone2      = dataTableClients.Rows[0]["Phone2"].ToString(),
                    PhoneMobile = dataTableClients.Rows[0]["PhoneMobile"].ToString(),
                    Fax         = dataTableClients.Rows[0]["Fax"].ToString(),
                    Email       = dataTableClients.Rows[0]["Email"].ToString()
                },


                Enabled = (bool)dataTableClients.Rows[0]["Enabled"],
                //Observations = row[table.ClientObservationsColumn.ColumnName].ToString(),
            };


            //factorias

            PlannerDataSetTableAdapters.FactoriesTableAdapter factoryadapter = new PlannerDataSetTableAdapters.FactoriesTableAdapter();
            PlannerDataSet.FactoriesDataTable factory = factoryadapter.GetDataByIdFactory(Convert.ToInt32(row[table.FactoryIdColumn.ColumnName]));


            order.Factory = new Factory()
            {
                Id   = Convert.ToInt32(factory.Rows[0]["Id"].ToString()),
                Code = factory.Rows[0]["Code"].ToString(),
                Name = factory.Rows[0]["Name"].ToString(),

                HexColor = GetColorFactory(Convert.ToInt32(row[table.FactoryIdColumn.ColumnName].ToString())),

                Location = new LocationData()
                {
                    Address  = factory.Rows[0]["Address"].ToString(),
                    City     = factory.Rows[0]["City"].ToString(),
                    PostCode = factory.Rows[0]["PostCode"].ToString(),
                    Province = factory.Rows[0]["Province"].ToString(),
                    Country  = factory.Rows[0]["Country"].ToString(),

                    Latitude  = (float)factory.Rows[0]["Latitude"],
                    Longitude = (float)factory.Rows[0]["Longitude"],
                },


                Enabled = (bool)factory.Rows[0]["Enabled"],
                //Observations = row[table.FactoryObservationsColumn.ColumnName].ToString(),
            };

            //producto
            PlannerDataSetTableAdapters.ProductsTableAdapter productsadapter = new PlannerDataSetTableAdapters.ProductsTableAdapter();
            PlannerDataSet.ProductsDataTable product = productsadapter.GetDataProductId(Convert.ToInt32(row[table.ProductIdColumn.ColumnName]));

            order.Product = new Product()
            {
                Id   = Convert.ToInt32(product.Rows[0]["Id"].ToString()),
                Code = product.Rows[0]["Code"].ToString(),
                Name = product.Rows[0]["Name"].ToString(),

                Density     = 4,
                MeasureUnit = 4,
            };


            order.SizeName = VehicleType.GetVehicleSizeName((int)order.VehicleType);

            //actualizamos el estado del pedido a planificado
            //UpdateStatusOrders(order.Id);


            return(order);
        }
Example #9
0
        public void Activate(LocationData l)
        {
            tileEngine.LoadMap(l.Map, 50, 50);
            Game.PushScreen(this);
            Game.ScriptEngine.ExecuteScript(EntrySequence);
            cursorX = 0;
            cursorY = 0;
            cursor.BoundingRectangle = tileEngine.BoundingRectangle(cursorX, cursorY);
            setupIndex = 0;

            enemies = EnemyGenerator.Generate();
            State = BattleState.NOTIF;
            positions.Clear();

            foreach (Character c in Player.Party)
            {
                c.CurrMovementPoints = c.MaxMovementPoints;
            }

            Game.ScriptEngine.ExecuteScript(AI.Stupid);
        }
        private async void Location_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
        {
            LocationQueryViewModel query_vm = null;

            if (args.ChosenSuggestion != null)
            {
                // User selected an item from the suggestion list, take an action on it here.
                var theChosenOne = args.ChosenSuggestion as LocationQueryViewModel;

                if (!String.IsNullOrEmpty(theChosenOne.LocationQuery))
                {
                    query_vm = theChosenOne;
                }
                else
                {
                    query_vm = new LocationQueryViewModel();
                }
            }
            else if (!String.IsNullOrEmpty(args.QueryText))
            {
                if (cts.Token.IsCancellationRequested)
                {
                    EnableControls(true);
                    return;
                }

                // Use args.QueryText to determine what to do.
                var result = (await wm.GetLocations(args.QueryText)).First();

                if (cts.Token.IsCancellationRequested)
                {
                    EnableControls(true);
                    return;
                }

                if (result != null && !String.IsNullOrWhiteSpace(result.LocationQuery))
                {
                    sender.Text = result.LocationName;
                    query_vm    = result;
                }
                else
                {
                    query_vm = new LocationQueryViewModel();
                }
            }
            else if (String.IsNullOrWhiteSpace(args.QueryText))
            {
                // Stop since there is no valid query
                return;
            }

            if (String.IsNullOrWhiteSpace(query_vm.LocationQuery))
            {
                // Stop since there is no valid query
                return;
            }

            // Cancel other tasks
            cts.Cancel();
            cts = new CancellationTokenSource();
            var ctsToken = cts.Token;

            LoadingRing.IsActive = true;

            if (ctsToken.IsCancellationRequested)
            {
                EnableControls(true);
                return;
            }

            // Weather Data
            var location = new LocationData(query_vm);

            if (!location.IsValid())
            {
                await Toast.ShowToastAsync(App.ResLoader.GetString("WError_NoWeather"), ToastDuration.Short);

                EnableControls(true);
                return;
            }
            Weather weather = await Settings.GetWeatherData(location.query);

            if (weather == null)
            {
                try
                {
                    weather = await wm.GetWeather(location);
                }
                catch (WeatherException wEx)
                {
                    weather = null;
                    await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short);
                }
            }

            if (weather == null)
            {
                EnableControls(true);
                return;
            }

            // We got our data so disable controls just in case
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                EnableControls(false);
                sender.IsSuggestionListOpen = false;
            });

            // Save weather data
            await Settings.DeleteLocations();

            await Settings.AddLocation(location);

            if (wm.SupportsAlerts && weather.weather_alerts != null)
            {
                await Settings.SaveWeatherAlerts(location, weather.weather_alerts);
            }
            await Settings.SaveWeatherData(weather);

            // If we're using search
            // make sure gps feature is off
            Settings.FollowGPS     = false;
            Settings.WeatherLoaded = true;

            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                this.Frame.Navigate(typeof(Shell), location);
            });
        }
Example #11
0
        private void AddSearchFragment()
        {
            if (mSearchFragment != null)
            {
                return;
            }

            FragmentTransaction    ft             = ChildFragmentManager.BeginTransaction();
            LocationSearchFragment searchFragment = new LocationSearchFragment();

            searchFragment.SetClickListener(async(object sender, RecyclerClickEventArgs e) =>
            {
                if (mSearchFragment == null)
                {
                    return;
                }

                LocationQueryAdapter adapter = sender as LocationQueryAdapter;
                LocationQuery v = (LocationQuery)e.View;
                LocationQueryViewModel query_vm = null;

                try
                {
                    if (!String.IsNullOrEmpty(adapter.Dataset[e.Position].LocationQuery))
                    {
                        query_vm = adapter.Dataset[e.Position];
                    }
                }
                catch (Exception)
                {
                    query_vm = null;
                }
                finally
                {
                    if (query_vm == null)
                    {
                        query_vm = new LocationQueryViewModel();
                    }
                }

                if (String.IsNullOrWhiteSpace(query_vm.LocationQuery))
                {
                    // Stop since there is no valid query
                    return;
                }

                // Cancel other tasks
                mSearchFragment.CtsCancel();
                var ctsToken = mSearchFragment.GetCancellationTokenSource().Token;

                ShowLoading(true);

                if (ctsToken.IsCancellationRequested)
                {
                    ShowLoading(false);
                    return;
                }

                // Check if location already exists
                var locData = await Settings.GetLocationData();
                if (locData.Exists(l => l.query == query_vm.LocationQuery))
                {
                    ShowLoading(false);
                    ExitSearchUi();
                    return;
                }

                if (ctsToken.IsCancellationRequested)
                {
                    ShowLoading(false);
                    return;
                }

                var location = new LocationData(query_vm);
                if (!location.IsValid())
                {
                    Toast.MakeText(App.Context, App.Context.GetString(Resource.String.werror_noweather), ToastLength.Short).Show();
                    ShowLoading(false);
                    return;
                }
                Weather weather = await Settings.GetWeatherData(location.query);
                if (weather == null)
                {
                    try
                    {
                        weather = await wm.GetWeather(location);
                    }
                    catch (WeatherException wEx)
                    {
                        weather = null;
                        Toast.MakeText(App.Context, wEx.Message, ToastLength.Short).Show();
                    }
                }

                if (weather == null)
                {
                    ShowLoading(false);
                    return;
                }

                // We got our data so disable controls just in case
                mAdapter.Dataset.Clear();
                mAdapter.NotifyDataSetChanged();

                if (mSearchFragment?.View != null &&
                    mSearchFragment?.View?.FindViewById(Resource.Id.recycler_view) is RecyclerView recyclerView)
                {
                    recyclerView.Enabled = false;
                }

                // Save data
                await Settings.AddLocation(location);
                if (wm.SupportsAlerts && weather.weather_alerts != null)
                {
                    await Settings.SaveWeatherAlerts(location, weather.weather_alerts);
                }
                await Settings.SaveWeatherData(weather);

                var panel = new LocationPanelViewModel(weather)
                {
                    LocationData = location
                };

                // Set properties if necessary
                if (EditMode)
                {
                    panel.EditMode = true;
                }

                int index = mAdapter.Dataset.Count;
                mAdapter.Add(panel);

                // Update shortcuts
                Task.Run(Shortcuts.ShortcutCreator.UpdateShortcuts);

                // Hide dialog
                ShowLoading(false);
                ExitSearchUi();
            });
            searchFragment.UserVisibleHint = false;
            ft.Add(Resource.Id.search_fragment_container, searchFragment);
            ft.CommitAllowingStateLoss();
        }
Example #12
0
        public Int32 RemoveLocation(LocationData request)
        {
            Int32 response = -1;

            using (var dbEntities = new TICPuppyLoveDbContext())
            {
                dbEntities.Locations.RemoveRange(
                    dbEntities.Locations.Where(x => x.UserID == request.UserID));
                response = dbEntities.SaveChanges();
            }

            return response;
        }
Example #13
0
        public LocationData GetLocationByUserID(LocationData request)
        {
            LocationData response = new LocationData();
            using (var dbEntities = new TICPuppyLoveDbContext())
            {
                response = (from loc in dbEntities.Locations
                            where loc.UserID == request.UserID
                            select new LocationData
                            {
                                UserID = loc.UserID,
                                Latitude = loc.Latitude,
                                Longitude = loc.Longitude,
                                Accuracy = loc.Accuracy,
                                Timestamp = loc.TimeStamp
                            }
                            ).SingleOrDefault();
            }

            return response;
        }
Example #14
0
        public List<LocationData> GetCurrentLocationsWithDistance(LocationData request)
        {
            List<LocationData> response = new List<LocationData>();

            using (var context = new TICPuppyLoveDbContext())
            {
                var UserID = new SqlParameter("@UserID", request.UserID);
                var Latitude = new SqlParameter("@Latitude",
                    (request.Latitude > 0 && request.Longitude < 0) ? request.Latitude : SqlDecimal.Null);
                var Longitude = new SqlParameter("@Longitude",
                    (request.Latitude > 0 && request.Longitude < 0) ? request.Longitude : SqlDecimal.Null);

                response = context.Database
                    .SqlQuery<LocationData>("SP_GetAllLocationsWithDistance @UserID, @Latitude, @Longitude",
                    UserID, Latitude, Longitude)
                    .ToList();
            }

            //EF not mapping UserID to the data contract but was able to map it to an alternate name.
            //Map it back

            response = GetLocBaseProperties(response);

            return response;
        }
Example #15
0
 public LocationUI(MiGame game, int x, int y, int width, int height, LocationData location)
 {
     this.game = game;
     Neighbors = new Dictionary<MiControl, LocationUI>();
     allyButtonBase = new MiAnimatingComponent(game, x, y, width, height);
     enemyButtonBase = new MiAnimatingComponent(game, x, y, width, height);
     neutralButtonBase = new MiAnimatingComponent(game, x, y, width, height);
     this.location = location;
 }
        // actual controller methods:
        public IActionResult setLocation()
        {
            var ViewModel = new LocationData();

            return(View(ViewModel));
        }
Example #17
0
        /// <summary>
        /// Creates a new PipConstructionHelper
        /// </summary>
        /// <remarks>
        /// Ideally this function would take ModuleId, FullSymbol QualifierId and compute uniqueOutputLocation itself. Unfortunately today the data is not yet
        /// exposed via IPipGraph, therefore the responsibility is on the call site for now.
        /// </remarks>
        public static PipConstructionHelper Create(
            PipExecutionContext context,
            AbsolutePath objectRoot,
            AbsolutePath redirectedRoot,
            AbsolutePath tempRoot,
            IMutablePipGraph pipGraph,
            ModuleId moduleId,
            string moduleName,
            RelativePath specRelativePath,
            FullSymbol symbol,
            LocationData thunkLocation,
            QualifierId qualifierId)
        {
            var stringTable = context.StringTable;
            var pathTable   = context.PathTable;

            // We have to manually compute the pipPipUniqueString here, Ideally we pass PackageId, SpecFile, FullSymbol and qualiferId and have it computed inside, but the IPipGraph does not allow querying it for now.
            string hashString;
            long   semiStableHashSeed = 0;

            using (var builderWrapper = Pools.GetStringBuilder())
            {
                var builder = builderWrapper.Instance;

                builder.Append(moduleName);
                builder.Append('/');
                semiStableHashSeed = HashCodeHelper.GetOrdinalHashCode64(moduleName);

                if (specRelativePath.IsValid)
                {
                    string specPath = specRelativePath.ToString(stringTable);
                    builder.Append(specPath);
                    builder.Append('/');
                    semiStableHashSeed = HashCodeHelper.Combine(semiStableHashSeed, HashCodeHelper.GetOrdinalHashCode64(specPath));
                }

                var symbolName = symbol.ToStringAsCharArray(context.SymbolTable);
                builder.Append(symbolName);
                builder.Append('/');
                semiStableHashSeed = HashCodeHelper.Combine(semiStableHashSeed, HashCodeHelper.GetOrdinalHashCode64(symbolName));

                var qualifierDisplayValue = context.QualifierTable.GetCanonicalDisplayString(qualifierId);
                builder.Append(qualifierDisplayValue);
                semiStableHashSeed = HashCodeHelper.Combine(semiStableHashSeed, HashCodeHelper.GetOrdinalHashCode64(qualifierDisplayValue));

                var pipPipUniqueString = builder.ToString();
                hashString = Hash(pipPipUniqueString);
            }

            var pipRelativePath = RelativePath.Create(
                PathAtom.Create(stringTable, hashString.Substring(0, 1)),
                PathAtom.Create(stringTable, hashString.Substring(1, 1)),
                PathAtom.Create(stringTable, hashString.Substring(2)));

            var valuePip = new ValuePip(symbol, qualifierId, thunkLocation);

            return(new PipConstructionHelper(
                       context,
                       objectRoot,
                       redirectedRoot,
                       tempRoot,
                       pipGraph,
                       moduleId,
                       moduleName,
                       valuePip,
                       pipRelativePath,
                       semiStableHashSeed));
        }
        private static void ReportDesignInternal(
            string eventId,
            float? value = null,
            LocationData? location = null,
            bool logFailure = true)
        {
            if (!m_enabled)
                return;

            Debug.Assert(!string.IsNullOrWhiteSpace(eventId));
            var json = CreateWriter();
            json.AppendProperty("event_id", eventId);
            if (location.HasValue)
                location.Value.Write(json);
            if (value.HasValue)
                json.AppendProperty("value", value.Value);
            Report("design", json, logFailure);
        }
Example #19
0
        public void OnWeatherLoaded(LocationData location, Weather weather)
        {
            // Save index before update
            int index = TextForecastControl.SelectedIndex;

            if (weather?.IsValid() == true)
            {
                wm.UpdateWeather(weather);
                WeatherView.UpdateView(weather);

                if (wm.SupportsAlerts)
                {
                    if (weather.weather_alerts != null && weather.weather_alerts.Count > 0)
                    {
                        // Alerts are posted to the user here. Set them as notified.
                        Task.Run(async() =>
                        {
                            await WeatherAlertHandler.SetasNotified(location, weather.weather_alerts);
                        });
                    }

                    // Show/Hide Alert panel
                    if (WeatherView.Extras.Alerts.Count > 0)
                    {
                        FrameworkElement alertButton = AlertButton;
                        if (alertButton == null)
                        {
                            alertButton = FindName(nameof(AlertButton)) as FrameworkElement;
                        }

                        ResizeAlertPanel();
                        alertButton.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        FrameworkElement alertButton = AlertButton;
                        if (alertButton != null)
                        {
                            alertButton.Visibility = Visibility.Collapsed;
                        }
                    }
                }
                else
                {
                    FrameworkElement alertButton = AlertButton;
                    if (alertButton != null)
                    {
                        alertButton.Visibility = Visibility.Collapsed;
                    }
                }

                // Update home tile if it hasn't been already
                if (Settings.HomeData.Equals(location) &&
                    (TimeSpan.FromTicks(DateTime.Now.Ticks - Settings.UpdateTime.Ticks).TotalMinutes > Settings.RefreshInterval) ||
                    !WeatherTileCreator.TileUpdated)
                {
                    Task.Run(async() => await WeatherUpdateBackgroundTask.RequestAppTrigger());
                }
                else if (SecondaryTileUtils.Exists(location.query))
                {
                    WeatherTileCreator.TileUpdater(location, weather);
                }

                // Shell
                Shell.Instance.HamburgerButtonColor = WeatherView.PendingBackgroundColor;
                if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
                {
                    // Mobile
                    StatusBar.GetForCurrentView().BackgroundColor = WeatherView.PendingBackgroundColor;
                }
                else
                {
                    // Desktop
                    var titlebar = ApplicationView.GetForCurrentView().TitleBar;
                    titlebar.BackgroundColor       = WeatherView.PendingBackgroundColor;
                    titlebar.ButtonBackgroundColor = titlebar.BackgroundColor;
                }
            }

            // Set saved index from before update
            // Note: needed since ItemSource is cleared and index is reset
            if (index == 0) // Note: UWP Mobile Bug
            {
                TextForecastControl.SelectedIndex = index + 1;
            }
            TextForecastControl.SelectedIndex = index;

            if (WeatherView.Extras.HourlyForecast.Count >= 1)
            {
                HourlyForecastPanel.Visibility = Visibility.Visible;
            }
            else
            {
                HourlyForecastPanel.Visibility = Visibility.Collapsed;
            }

            if (WeatherView.Extras.TextForecast.Count >= 1)
            {
                ForecastSwitch.Visibility = Visibility.Visible;
            }
            else
            {
                ForecastSwitch.Visibility = Visibility.Collapsed;
            }

            if (!String.IsNullOrWhiteSpace(WeatherView.Extras.Chance))
            {
                if (!Settings.API.Equals(WeatherAPI.MetNo))
                {
                    if (!DetailsWrapGrid.Children.Contains(PrecipitationPanel))
                    {
                        DetailsWrapGrid.Children.Insert(0, PrecipitationPanel);
                        ResizeDetailItems();
                    }

                    PrecipitationPanel.Visibility = Visibility.Visible;
                }
                else
                {
                    DetailsWrapGrid.Children.Remove(PrecipitationPanel);
                    ResizeDetailItems();
                }

                int precipCount = PrecipitationPanel.Children.Count;
                int atmosCount  = AtmospherePanel.Children.Count;

                if (Settings.API.Equals(WeatherAPI.OpenWeatherMap) || Settings.API.Equals(WeatherAPI.MetNo))
                {
                    if (ChanceItem != null)
                    {
                        PrecipitationPanel.Children.Remove(ChanceItem);
                    }

                    FrameworkElement cloudinessItem = CloudinessItem;
                    if (cloudinessItem == null)
                    {
                        cloudinessItem = FindName(nameof(CloudinessItem)) as FrameworkElement;
                    }

                    if (cloudinessItem != null && !AtmospherePanel.Children.Contains(cloudinessItem))
                    {
                        AtmospherePanel.Children.Insert(2, cloudinessItem);
                    }
                }
                else
                {
                    FrameworkElement chanceItem = ChanceItem;
                    if (chanceItem == null)
                    {
                        chanceItem = FindName(nameof(ChanceItem)) as FrameworkElement;
                    }

                    if (chanceItem != null && !PrecipitationPanel.Children.Contains(chanceItem))
                    {
                        PrecipitationPanel.Children.Insert(2, chanceItem);
                    }

                    if (CloudinessItem != null)
                    {
                        AtmospherePanel.Children.Remove(CloudinessItem);
                    }
                }

                if (precipCount != PrecipitationPanel.Children.Count || atmosCount != AtmospherePanel.Children.Count)
                {
                    ResizeDetailItems();
                }
            }
            else
            {
                DetailsWrapGrid.Children.Remove(PrecipitationPanel);
                if (CloudinessItem != null)
                {
                    AtmospherePanel.Children.Remove(CloudinessItem);
                }
                ResizeDetailItems();
            }

            LoadingRing.IsActive = false;
        }
        private static void ReportErrorInternal(
            ErrorEventData error,
            LocationData? location = null,
            bool logFailure = false)
        {
            if (!m_enabled)
                return;

            var json = CreateWriter();
            error.Write(json);
            if (location.HasValue)
                location.Value.Write(json);
            Report("error", json, logFailure);
        }
Example #21
0
        /**************************************************** OTHER METHODS ******************************************************/

        /// <summary>
        ///     <para>parses and returns the FeedData in the form of list</para>
        /// </summary>
        /// <param name="ParsedJson"></param>
        /// <returns></returns>
        private List <FeedData> ParseFeeds(dynamic ParsedJson)
        {
            // CREATE FEEDDATA LIST
            List <FeedData> Data = new List <FeedData>();

            foreach (dynamic Post in ParsedJson.data)
            {
                // CREATE FEEDDATA OBJECT
                FeedData Feed = new FeedData();

                // CREATE ATTRIBUTION OBJECT;
                if (Post.attribution == null)
                {
                    Feed.Attribution = null;
                }
                else
                {
                    AttributionData Attribution = new AttributionData();
                    Attribution.Website   = Post.Attribution.website;
                    Attribution.ItunesUrl = Post.Attribution.itunes_url;
                    Attribution.Name      = Post.Attribution.name;
                    Feed.Attribution      = Attribution;
                }

                // SET TAGS
                List <String> Tags = new List <String>();
                foreach (dynamic Tag in Post.tags)
                {
                    Tags.Add(Tag.ToString());
                }
                Feed.Tags = Tags;

                // SET TYPE
                Feed.Type = Post.type;

                // SET LOCATION
                if (Post.location == null)
                {
                    Feed.Location = null;
                }
                else
                {
                    LocationData Location = new LocationData();
                    Location.Id        = Post.location.id;
                    Location.Latitude  = Post.location.latitude;
                    Location.Longitude = Post.location.longitude;
                    Location.Name      = Post.location.name;
                    Feed.Location      = Location;
                }

                // SET COMMENTS
                CommentData Comments = new CommentData();
                Comments.Count = Post.comments.count;
                List <Comment> CommentData = new List <Comment>();
                foreach (dynamic EachComment in Post.comments.data)
                {
                    // CREATE COMMENT OBJECT
                    Comment Comment = new Comment();
                    Comment.CreatedTime = new DateTime(long.Parse(EachComment.created_time.ToString()));
                    Comment.Id          = EachComment.id;
                    Comment.Text        = EachComment.text;

                    // CREATE USER OBJECT
                    User CommentedBy = new User();
                    CommentedBy.UserName       = EachComment.from.username;
                    CommentedBy.ProfilePicture = EachComment.from.profile_pciture;
                    CommentedBy.Id             = EachComment.from.id;
                    CommentedBy.FullName       = EachComment.from.full_name;

                    // ASSOCIATE COMMENT WITH USER
                    Comment.From = CommentedBy;

                    // ADD COMMENT TO THE LIST
                    CommentData.Add(Comment);
                }
                Comments.Data = CommentData;
                Feed.Comments = Comments;

                // SET FILTER
                Feed.Filter = Post.filter;

                // SET CREATED TIME
                Feed.CreatedTime = new DateTime(long.Parse(Post.created_time.ToString()));

                // SET LINK
                Feed.Link = Post.link;

                // SET LIKES
                LikesData Likes = new LikesData();
                Likes.Count = Post.likes.count;
                List <User> LikedByUsers = new List <User>();
                foreach (dynamic EachLike in Post.likes.data)
                {
                    // CREATE USER OBJECT
                    User LikedBy = new User();
                    LikedBy.UserName       = EachLike.username;
                    LikedBy.ProfilePicture = EachLike.profile_picture;
                    LikedBy.Id             = EachLike.id;
                    LikedBy.FullName       = EachLike.full_name;

                    // ADD USER TO THE LIST
                    LikedByUsers.Add(LikedBy);
                }
                Likes.Data = LikedByUsers;
                Feed.Likes = Likes;

                // SET VIDEO
                if (Feed.Type.Equals("video"))
                {
                    VideosData         VideoData = new VideosData();
                    LowResolutionVideo LRVideo   = new LowResolutionVideo();
                    LRVideo.url             = Post.videos.low_resolution.url;
                    LRVideo.width           = Post.videos.low_resolution.width;
                    LRVideo.height          = Post.videos.low_resolution.height;
                    VideoData.LowResolution = LRVideo;
                    StandardResolutionVideo SRVideo = new StandardResolutionVideo();
                    SRVideo.url    = Post.videos.standard_resolution.url;
                    SRVideo.width  = Post.videos.standard_resolution.width;
                    SRVideo.height = Post.videos.standard_resolution.height;
                    VideoData.StandardResolution = SRVideo;

                    Feed.Videos = VideoData;
                }
                else
                {
                    Feed.Videos = null;
                }

                // SET IMAGES
                ImagesData Images = new ImagesData();
                StandardResolutionImage SRImage = new StandardResolutionImage();
                SRImage.url               = Post.images.standard_resolution.url;
                SRImage.width             = Post.images.standard_resolution.width;
                SRImage.height            = Post.images.standard_resolution.height;
                Images.StandardResolution = SRImage;
                ThumbnailImage TImage = new ThumbnailImage();
                TImage.url       = Post.images.thumbnail.url;
                TImage.width     = Post.images.thumbnail.width;
                TImage.height    = Post.images.thumbnail.height;
                Images.Thumbnail = TImage;
                LowResolutionImage LRImage = new LowResolutionImage();
                LRImage.url          = Post.images.low_resolution.url;
                LRImage.width        = Post.images.low_resolution.width;
                LRImage.height       = Post.images.low_resolution.height;
                Images.LowResolution = LRImage;
                Feed.Images          = Images;

                // SET CAPTIONS
                CaptionData Caption = new CaptionData();
                if (Post.caption != null)
                {
                    Caption.CreratedTime = new DateTime(long.Parse(Post.caption.created_time.ToString()));
                    Caption.Text         = Post.caption.text;
                    Caption.Id           = Post.caption.id;
                    User CaptionedBy = new User();
                    CaptionedBy.UserName       = Post.caption.from.username;
                    CaptionedBy.ProfilePicture = Post.caption.from.profile_pciture;
                    CaptionedBy.Id             = Post.caption.from.id;
                    CaptionedBy.FullName       = Post.caption.from.full_name;
                    Caption.From = CaptionedBy;
                }
                Feed.Caption = Caption;

                // SET TAGGED USER
                List <TaggedUser> UserInPhotos = new List <TaggedUser>();
                if (Post.users_in_photo != null)
                {
                    foreach (dynamic UserTag in Post.users_in_photo)
                    {
                        // CREATE TAGGED USER OBJECT
                        TaggedUser TUser = new TaggedUser();

                        // SET USER
                        User TaggedUser = new User();
                        TaggedUser.UserName       = UserTag.user.username;
                        TaggedUser.FullName       = UserTag.user.full_name;
                        TaggedUser.Id             = UserTag.user.id;
                        TaggedUser.ProfilePicture = UserTag.user.profile_picture;
                        TUser.User = TaggedUser;

                        // SET POSITION
                        Position TagPosition = new Position();
                        TagPosition.x  = float.Parse(UserTag.position.x.ToString());
                        TagPosition.y  = float.Parse(UserTag.position.y.ToString());
                        TUser.Position = TagPosition;

                        // ADD TO LIST
                        UserInPhotos.Add(TUser);
                    }
                }
                Feed.UsersInPhoto = UserInPhotos;

                // SET USER LIKE
                Feed.UserHasLiked = Post.user_has_liked;

                // SET ID
                Feed.Id = Post.id;

                // SET USER
                User FeedBy = new User();
                FeedBy.UserName       = Post.user.username;
                FeedBy.Website        = Post.user.webste;
                FeedBy.ProfilePicture = Post.user.profile_picture;
                FeedBy.FullName       = Post.user.full_name;
                FeedBy.Bio            = Post.user.bio;
                FeedBy.Id             = Post.user.id;
                Feed.User             = FeedBy;

                // ADD FEED TO LIST
                Data.Add(Feed);
            }

            return(Data);
        }
Example #22
0
 private void _buttonAdd_Click(object sender, EventArgs e)
 {
     LocationData newLocation = new LocationData(_data);
     _data.Add(newLocation);
     _locationsControl.Rows.Add(new LocationControl(newLocation, this, 
         WebProvider.ActiveProvider.DataSet.Properties));
 }
Example #23
0
 /**<summary> Called when response is got from image based Location API server </summary>*/
 private void OnLocationResponse(bool locationFound, LocationData locationData)
 {
     //TODO: Fix this
     //locationIcon.iconVectorImageData = locationFound ? this.locationFound : locationNotFound;
 }
Example #24
0
            internal LocationControl(LocationData data, Redirect parent, IEnumerable<Property> properties)
            {
                _data = data;
                _parent = parent;

                _tableFilters = new Table();
                _panelEnabled = new Panel();
                _panelMatchExpression = new Panel();
                _panelProperty = new Panel();
                _panelValue = new Panel();
                _textBoxName = new TextBox();
                _textBoxUrl = new TextBox();
                _textBoxMatchExpression = new TextBox();
                _buttonAdd = new Button();
                _buttonRemove = new Button();
                _buttonToggle = new Button();
                _customValidatorMatchExpression = new CustomValidator();
                _requiredFieldValidatorName = new RequiredFieldValidator();
                _regularExpressionValidatorUrl = new RegularExpressionValidator();

                _textBoxName.Text = _data.Name;
                _textBoxUrl.Text = _data.Url;
                _textBoxMatchExpression.Text = _data.MatchExpression;

                _requiredFieldValidatorName.EnableClientScript =
                    _regularExpressionValidatorUrl.EnableClientScript = false;

                _requiredFieldValidatorName.ValidationGroup =
                    _customValidatorMatchExpression.ValidationGroup =
                    _regularExpressionValidatorUrl.ValidationGroup = VALIDATION_GROUP;

                _requiredFieldValidatorName.Display =
                    _customValidatorMatchExpression.Display =
                    _regularExpressionValidatorUrl.Display = ValidatorDisplay.None;

                _regularExpressionValidatorUrl.ValidationExpression = REGEX_URL;

                TableHeaderRow rowHeader = new TableHeaderRow();
                rowHeader.Cells.Add(NewCell(_panelProperty));
                rowHeader.Cells.Add(NewCell(_panelValue));
                rowHeader.Cells.Add(NewCell(_panelMatchExpression));
                rowHeader.Cells.Add(NewCell(_panelEnabled));
                _tableFilters.Rows.Add(rowHeader);

                foreach (FilterData filter in _data)
                    _tableFilters.Rows.Add(new FilterControl(filter, _parent, properties));
            }
Example #25
0
        private static Order ConvertToOrder(DataRow row, PlannerDataSet.PlannerOrdersDataTable table)
        {
            Order  order             = new Order();
            string putEmergencycolor = "";

            order.Id        = Convert.ToInt64(row[table.IdColumn.ColumnName]);
            order.Reference = row[table.ReferenceColumn.ColumnName].ToString();

            order.StartDate    = (DateTime)row[table.StartDateColumn.ColumnName];
            order.FinalDate    = (DateTime)row[table.FinalDateColumn.ColumnName];
            order.CreatedDate  = (DateTime)row[table.CreatedDateColumn.ColumnName];
            order.ModifiedDate = (DateTime)row[table.ModifiedDateColumn.ColumnName];



            order.TripId = Convert.ToInt32(row[table.TripIdColumn.ColumnName].ToString());

            LocationData location = new LocationData();

            location.Address  = row[table.AddressColumn.ColumnName].ToString();
            location.City     = row[table.CityColumn.ColumnName].ToString();
            location.PostCode = row[table.PostCodeColumn.ColumnName].ToString();
            location.Province = row[table.ProvinceColumn.ColumnName].ToString();
            location.Country  = row[table.CountryColumn.ColumnName].ToString();


            //float.TryParse(row[table.LatitudeColumn.ColumnName].ToString(), out float loc);
            location.Latitude = (float)Convert.ToDouble(row[table.LatitudeColumn.ColumnName].ToString());

            //float.TryParse(row[table.LongitudeColumn.ColumnName].ToString(), out loc);
            location.Longitude = (float)Convert.ToDouble(row[table.LongitudeColumn.ColumnName].ToString().ToString());

            order.Location = location;

            Int32.TryParse(row[table.VehicleSizeColumn.ColumnName].ToString(), out int num);
            order.VehicleType = num;

            Int32.TryParse(row[table.RequestedAmountColumn.ColumnName].ToString(), out num);
            order.RequestedAmount = num;

            Int32.TryParse(row[table.ReceivedAmountColumn.ColumnName].ToString(), out num);
            order.ReceivedAmount = num;


            //aqui
            order.TankNum      = row[table.TankNumColumn.ColumnName].ToString();
            order.TankVolume   = row[table.TankVolumeColumn.ColumnName].ToString();
            order.TankLevel    = row[table.TankLevelColumn.ColumnName].ToString();
            order.Status       = row[table.StatusColumn.ColumnName] as int? ?? 0;
            order.Description  = row[table.DescriptionColumn.ColumnName].ToString();
            order.Observations = row[table.ObservationsColumn.ColumnName].ToString();

            order.Operator = new Operator()
            {
                Id   = Convert.ToInt32(row[table.OperatorIdColumn.ColumnName]),
                Code = row[table.OperatorCodeColumn.ColumnName].ToString(),
                Name = row[table.OperatorNameColumn.ColumnName].ToString(),
                Cif  = row[table.OperatorCifColumn.ColumnName].ToString(),

                Location = new LocationData()
                {
                    Address  = row[table.OperatorAddressColumn.ColumnName].ToString(),
                    City     = row[table.OperatorCityColumn.ColumnName].ToString(),
                    PostCode = row[table.OperatorPostCodeColumn.ColumnName].ToString(),
                    Province = row[table.OperatorProvinceColumn.ColumnName].ToString(),
                    Country  = row[table.OperatorCountryColumn.ColumnName].ToString(),
                },

                Contact = new ContactData()
                {
                    Name        = row[table.OperatorContactColumn.ColumnName].ToString(),
                    Phone       = row[table.OperatorPhoneColumn.ColumnName].ToString(),
                    Phone2      = row[table.OperatorPhone2Column.ColumnName].ToString(),
                    PhoneMobile = row[table.OperatorPhoneMobileColumn.ColumnName].ToString(),
                    Fax         = row[table.OperatorFaxColumn.ColumnName].ToString(),
                    Email       = row[table.OperatorEmailColumn.ColumnName].ToString()
                },


                Enabled = (bool)row[table.OperatorEnabledColumn.ColumnName],
                //Observations = row[table.OperatorObservationsColumn.ColumnName].ToString(),
            };

            order.Client = new Client()
            {
                Id   = Convert.ToInt32(row[table.ClientIdColumn.ColumnName]),
                Code = row[table.ClientCodeColumn.ColumnName].ToString(),
                Name = row[table.ClientNameColumn.ColumnName].ToString(),
                Cif  = row[table.ClientCifColumn.ColumnName].ToString(),

                Location = new LocationData()
                {
                    Address  = row[table.ClientAddressColumn.ColumnName].ToString(),
                    City     = row[table.ClientCityColumn.ColumnName].ToString(),
                    PostCode = row[table.ClientPostCodeColumn.ColumnName].ToString(),
                    Province = row[table.ClientProvinceColumn.ColumnName].ToString(),
                    Country  = row[table.ClientCountryColumn.ColumnName].ToString(),

                    Latitude  = (float)row[table.ClientLatitudeColumn.ColumnName],
                    Longitude = (float)row[table.ClientLongitudeColumn.ColumnName],
                },

                Contact = new ContactData()
                {
                    Name        = row[table.ClientContactColumn.ColumnName].ToString(),
                    Phone       = row[table.ClientPhoneColumn.ColumnName].ToString(),
                    Phone2      = row[table.ClientPhone2Column.ColumnName].ToString(),
                    PhoneMobile = row[table.ClientPhoneMobileColumn.ColumnName].ToString(),
                    Fax         = row[table.ClientFaxColumn.ColumnName].ToString(),
                    Email       = row[table.ClientEmailColumn.ColumnName].ToString()
                },


                Enabled = (bool)row[table.ClientEnabledColumn.ColumnName],
                //Observations = row[table.ClientObservationsColumn.ColumnName].ToString(),
            };

            order.Factory = new Factory()
            {
                Id       = Convert.ToInt32(row[table.FactoryIdColumn.ColumnName]),
                Code     = row[table.FactoryCodeColumn.ColumnName].ToString(),
                Name     = row[table.FactoryNameColumn.ColumnName].ToString(),
                HexColor = row[table.FactoryColorColumn.ColumnName].ToString(),


                Location = new LocationData()
                {
                    Address  = row[table.FactoryAddressColumn.ColumnName].ToString(),
                    City     = row[table.FactoryCityColumn.ColumnName].ToString(),
                    PostCode = row[table.FactoryPostCodeColumn.ColumnName].ToString(),
                    Province = row[table.FactoryProvinceColumn.ColumnName].ToString(),
                    Country  = row[table.FactoryCountryColumn.ColumnName].ToString(),

                    Latitude  = (float)row[table.FactoryLatitudeColumn.ColumnName],
                    Longitude = (float)row[table.FactoryLongitudeColumn.ColumnName],
                },


                Enabled = (bool)row[table.FactoryEnabledColumn.ColumnName],
                //Observations = row[table.FactoryObservationsColumn.ColumnName].ToString(),
            };

            order.Product = new Product()
            {
                Id   = Convert.ToInt32(row[table.ProductIdColumn.ColumnName]),
                Code = row[table.ProductCodeColumn.ColumnName].ToString(),
                Name = row[table.ProductNameColumn.ColumnName].ToString(),

                Density     = (float)Convert.ToDouble(row[table.ProductDensityColumn.ColumnName]),
                MeasureUnit = (short)row[table.ProductMeasureUnitColumn.ColumnName],

                Enabled = (bool)row[table.ProductEnabledColumn.ColumnName],
                //Observations = row[table.ProductObservationsColumn.ColumnName].ToString(),
            };



            order.SizeName = VehicleType.GetVehicleSizeName((int)order.VehicleType);

            return(order);
        }
Example #26
0
        private bool Applychk(BinaryReader br)
        {
            CHKToken cHKToken = GetNextCHK(br);

            br.BaseStream.Position = cHKToken.start;



            //Byte로부터 에디터로 넣는 함수
            switch (cHKToken.tokentype)
            {
            case TOKENTYPE.ENCD:
                SetEncoding(br.ReadInt32());

                break;

            case TOKENTYPE.IOWN:
                IOWN = br.ReadBytes(12);

                break;

            case TOKENTYPE.OWNR:
                //넘기기
                OWNR = br.ReadBytes(12);

                break;

            case TOKENTYPE.SIDE:
                SIDE = br.ReadBytes(12);

                break;

            case TOKENTYPE.ERA:
                ushort tile = br.ReadUInt16();
                if (tile > 7)
                {
                    throw new Exception("");
                }
                TILETYPE = (TileType)tile;


                break;

            case TOKENTYPE.COLR:
                COLR = br.ReadBytes(8);
                for (int i = 0; i < 8; i++)
                {
                    if (COLR[i] >= ColorName.Count())
                    {
                        COLR[i] = 0;
                    }


                    CRGB[i] = new Microsoft.Xna.Framework.Color(0, 0, COLR[i]);
                }


                break;

            case TOKENTYPE.CRGB:
                for (int i = 0; i < 8; i++)
                {
                    byte[] colors = br.ReadBytes(3);
                    CRGB[i] = new Microsoft.Xna.Framework.Color(colors[0], colors[1], colors[2]);
                }
                CRGBIND = br.ReadBytes(8);

                break;

            case TOKENTYPE.UNIT:
                UNIT.Clear();
                for (int i = 0; i < cHKToken.size / 36; i++)
                {
                    CUNIT cUNIT = new CUNIT(br);
                    cUNIT.SetMapEditor(mapEditor);
                    UNIT.Add(cUNIT);
                }

                break;

            case TOKENTYPE.DIM:
                WIDTH  = br.ReadUInt16();
                HEIGHT = br.ReadUInt16();
                break;

            case TOKENTYPE.TILE:
                TILE = new ushort[cHKToken.size / 2];
                for (int i = 0; i < cHKToken.size / 2; i++)
                {
                    TILE[i] = br.ReadUInt16();
                }

                break;

            case TOKENTYPE.MTXM:
                MTXM = new ushort[cHKToken.size / 2];
                for (int i = 0; i < cHKToken.size / 2; i++)
                {
                    MTXM[i] = br.ReadUInt16();
                }

                break;

            case TOKENTYPE.DD2:
                for (int i = 0; i < cHKToken.size / 8; i++)
                {
                    CDD2 cDD2 = new CDD2(br, this);

                    DD2.Add(cDD2);
                }
                break;

            case TOKENTYPE.THG2:
                for (int i = 0; i < cHKToken.size / 10; i++)
                {
                    CTHG2 cTHG2 = new CTHG2(br);

                    THG2.Add(cTHG2);
                }

                break;

            case TOKENTYPE.MASK:
                MASK = br.ReadBytes((int)cHKToken.size);

                break;

            case TOKENTYPE.STR:
            {
                long startpoint = br.BaseStream.Position;

                LOADSTR = new string[br.ReadUInt16()];
                BYTESTR = new List <byte[]>();

                ushort[] ptrs = new ushort[LOADSTR.Length];
                for (int i = 0; i < ptrs.Length; i++)
                {
                    ptrs[i] = br.ReadUInt16();
                }


                for (int i = 0; i < ptrs.Length; i++)
                {
                    br.BaseStream.Position = startpoint + ptrs[i];

                    List <byte> strs     = new List <byte>();
                    byte        readbyte = br.ReadByte();


                    if (readbyte != 0)
                    {
                        strs.Add(readbyte);
                        while (true)
                        {
                            readbyte = br.ReadByte();
                            if (readbyte == 0)
                            {
                                break;
                            }
                            strs.Add(readbyte);
                        }
                    }


                    BYTESTR.Add(strs.ToArray());

                    //LOADSTR[i] = System.Text.Encoding.GetEncoding(949).GetString(strs.ToArray());
                }
            }
            break;

            case TOKENTYPE.STRx:
            {
                long startpoint = br.BaseStream.Position;

                LOADSTRx = new string[br.ReadUInt32()];
                BYTESTRx = new List <byte[]>();

                uint[] ptrs = new uint[LOADSTRx.Length];
                for (int i = 0; i < ptrs.Length; i++)
                {
                    ptrs[i] = br.ReadUInt32();
                }


                for (int i = 0; i < ptrs.Length; i++)
                {
                    br.BaseStream.Position = startpoint + ptrs[i];

                    List <byte> strs     = new List <byte>();
                    byte        readbyte = br.ReadByte();

                    if (readbyte != 0)
                    {
                        strs.Add(readbyte);
                        while (true)
                        {
                            readbyte = br.ReadByte();
                            if (readbyte == 0)
                            {
                                break;
                            }
                            strs.Add(readbyte);
                        }
                    }


                    BYTESTRx.Add(strs.ToArray());

                    //LOADSTRx[i] = System.Text.Encoding.UTF8.GetString(strs.ToArray());
                }
            }
            break;

            case TOKENTYPE.SPRP:
                SCEARIONAME = new StringData(this, br.ReadUInt16());
                SCEARIODES  = new StringData(this, br.ReadUInt16());


                break;

            case TOKENTYPE.FORC:
                FORCE = br.ReadBytes(8);

                FORCENAME    = new StringData[4];
                FORCENAME[0] = new StringData(this, br.ReadUInt16());
                FORCENAME[1] = new StringData(this, br.ReadUInt16());
                FORCENAME[2] = new StringData(this, br.ReadUInt16());
                FORCENAME[3] = new StringData(this, br.ReadUInt16());

                FORCEFLAG = br.ReadBytes(4);
                break;

            case TOKENTYPE.MRGN:
                LocationDatas.Clear();
                LocationDatas.Add(new LocationData(mapEditor));
                for (int i = 0; i < 255; i++)
                {
                    LocationData locationData = new LocationData(mapEditor);

                    locationData.INDEX = i + 1;

                    locationData.L      = br.ReadUInt32();
                    locationData.T      = br.ReadUInt32();
                    locationData.R      = br.ReadUInt32();
                    locationData.B      = br.ReadUInt32();
                    locationData.STRING = new StringData(this, br.ReadUInt16());
                    locationData.FLAG   = br.ReadUInt16();

                    if (locationData.L == 0 & locationData.T == 0 & locationData.L == 0 & locationData.T == 0 &
                        locationData.STRING.LoadedIndex == -1 & locationData.FLAG == 0)
                    {
                        continue;
                    }


                    LocationDatas.Add(locationData);
                }
                //u32: Left(X1) coordinate of location, in pixels(usually 32 pt grid aligned)
                //u32: Top(Y1) coordinate of location, in pixels
                //u32: Right(X2) coordinate of location, in pixels
                //u32: Bottom(Y2) coordinate of location, in pixels
                //u16: String number of the name of this location
                //u16: Location elevation flags.If an elevation is disabled in the location, it's bit will be on (1)
                //Bit 0 - Low elevation
                //Bit 1 - Medium elevation
                //Bit 2 - High elevation
                //Bit 3 - Low air
                //Bit 4 - Medium air
                //Bit 5 - High air
                //Bit 6 - 15 - Unused


                break;

            case TOKENTYPE.UPRP:
                UPRP = new CUPRP[64];
                for (int i = 0; i < 64; i++)
                {
                    CUPRP cUPRP = new CUPRP();
                    cUPRP.STATUSVALID = br.ReadUInt16();
                    cUPRP.POINTVALID  = br.ReadUInt16();

                    cUPRP.PLAYER      = br.ReadByte();
                    cUPRP.HITPOINT    = br.ReadByte();
                    cUPRP.SHIELDPOINT = br.ReadByte();
                    cUPRP.ENERGYPOINT = br.ReadByte();


                    cUPRP.RESOURCE   = br.ReadUInt32();
                    cUPRP.HANGAR     = br.ReadUInt16();
                    cUPRP.STATUSFLAG = br.ReadUInt16();
                    cUPRP.UNUSED     = br.ReadUInt32();

                    UPRP[i] = cUPRP;
                }
                break;

            case TOKENTYPE.UPUS:
                UPUS = br.ReadBytes(64);
                break;

            case TOKENTYPE.WAV:
                WAV = new StringData[512];
                for (int i = 0; i < 512; i++)
                {
                    WAV[i] = new StringData(this, br.ReadInt32());
                }
                break;

            case TOKENTYPE.SWNM:
                SWNM = new StringData[256];
                for (int i = 0; i < 256; i++)
                {
                    SWNM[i] = new StringData(this, br.ReadInt32());
                }
                break;

            case TOKENTYPE.PUNI:
                PUNI = new CPUNI();
                for (int i = 0; i < 12; i++)
                {
                    PUNI.UNITENABLED[i] = br.ReadBytes(228);
                }
                PUNI.DEFAULT = br.ReadBytes(228);
                for (int i = 0; i < 12; i++)
                {
                    PUNI.USEDEFAULT[i] = br.ReadBytes(228);
                }

                break;

            case TOKENTYPE.PUPx:
                PUPx = new CPUPx();
                for (int i = 0; i < 12; i++)
                {
                    PUPx.MAXLEVEL[i] = br.ReadBytes(61);
                }
                for (int i = 0; i < 12; i++)
                {
                    PUPx.STARTLEVEL[i] = br.ReadBytes(61);
                }
                PUPx.DEFAULTMAXLEVEL   = br.ReadBytes(61);
                PUPx.DEFAULTSTARTLEVEL = br.ReadBytes(61);
                for (int i = 0; i < 12; i++)
                {
                    PUPx.USEDEFAULT[i] = br.ReadBytes(61);
                }

                break;

            case TOKENTYPE.PTEx:
                PTEx = new CPTEx();
                for (int i = 0; i < 12; i++)
                {
                    PTEx.MAXLEVEL[i] = br.ReadBytes(44);
                }
                for (int i = 0; i < 12; i++)
                {
                    PTEx.STARTLEVEL[i] = br.ReadBytes(44);
                }
                PTEx.DEFAULTMAXLEVEL   = br.ReadBytes(44);
                PTEx.DEFAULTSTARTLEVEL = br.ReadBytes(44);
                for (int i = 0; i < 12; i++)
                {
                    PTEx.USEDEFAULT[i] = br.ReadBytes(44);
                }

                break;

            case TOKENTYPE.UNIx:
                UNIx = new CUNIx();
                for (int i = 0; i < 228; i++)
                {
                    UNIx.USEDEFAULT[i] = br.ReadByte();
                }

                for (int i = 0; i < 228; i++)
                {
                    UNIx.HIT[i] = br.ReadUInt32();
                }
                for (int i = 0; i < 228; i++)
                {
                    UNIx.SHIELD[i] = br.ReadUInt16();
                }
                for (int i = 0; i < 228; i++)
                {
                    UNIx.ARMOR[i] = br.ReadByte();
                }
                for (int i = 0; i < 228; i++)
                {
                    UNIx.BUILDTIME[i] = br.ReadUInt16();
                }
                for (int i = 0; i < 228; i++)
                {
                    UNIx.MIN[i] = br.ReadUInt16();
                }
                for (int i = 0; i < 228; i++)
                {
                    UNIx.GAS[i] = br.ReadUInt16();
                }
                for (int i = 0; i < 228; i++)
                {
                    UNIx.STRING[i] = new StringData(this, br.ReadUInt16());
                }
                for (int i = 0; i < 130; i++)
                {
                    UNIx.DMG[i] = br.ReadUInt16();
                }
                for (int i = 0; i < 130; i++)
                {
                    UNIx.BONUSDMG[i] = br.ReadUInt16();
                }

                break;

            case TOKENTYPE.UPGx:
                UPGx = new CUPGx();
                for (int i = 0; i < 61; i++)
                {
                    UPGx.USEDEFAULT[i] = br.ReadByte();
                }
                br.ReadByte();
                for (int i = 0; i < 61; i++)
                {
                    UPGx.BASEMIN[i] = br.ReadUInt16();
                }
                for (int i = 0; i < 61; i++)
                {
                    UPGx.BONUSMIN[i] = br.ReadUInt16();
                }
                for (int i = 0; i < 61; i++)
                {
                    UPGx.BASEGAS[i] = br.ReadUInt16();
                }
                for (int i = 0; i < 61; i++)
                {
                    UPGx.BONUSGAS[i] = br.ReadUInt16();
                }
                for (int i = 0; i < 61; i++)
                {
                    UPGx.BASETIME[i] = br.ReadUInt16();
                }
                for (int i = 0; i < 61; i++)
                {
                    UPGx.BONUSTIME[i] = br.ReadUInt16();
                }

                break;

            case TOKENTYPE.TECx:
                TECx = new CTECx();
                for (int i = 0; i < 44; i++)
                {
                    TECx.USEDEFAULT[i] = br.ReadByte();
                }
                for (int i = 0; i < 44; i++)
                {
                    TECx.MIN[i] = br.ReadUInt16();
                }
                for (int i = 0; i < 44; i++)
                {
                    TECx.GAS[i] = br.ReadUInt16();
                }
                for (int i = 0; i < 44; i++)
                {
                    TECx.BASETIME[i] = br.ReadUInt16();
                }
                for (int i = 0; i < 44; i++)
                {
                    TECx.ENERGY[i] = br.ReadUInt16();
                }

                break;

            case TOKENTYPE.TRIG:
                TRIG.Clear();

                for (int i = 0; i < cHKToken.size / 2400; i++)
                {
                    RAWTRIGMBRF trig = new RAWTRIGMBRF(br);

                    TRIG.Add(trig);
                }


                break;

            case TOKENTYPE.MBRF:
                MBRF.Clear();

                for (int i = 0; i < cHKToken.size / 2400; i++)
                {
                    RAWTRIGMBRF mbrf = new RAWTRIGMBRF(br);

                    MBRF.Add(mbrf);
                }


                break;
            }



            for (int i = 0; i < cHKTokens.Count; i++)
            {
                if (cHKTokens[i].code == cHKToken.code)
                {
                    cHKTokens.RemoveAt(i);
                    break;
                }
            }
            cHKTokens.Add(cHKToken);
            br.BaseStream.Position = cHKToken.end;
            return(true);
        }
Example #27
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void loadProfile() throws Exception
        private void loadProfile()
        {
            DatabaseDBUtil.currentSession().beginTransaction();
            LocalizationProfileTable localizationProfileTable = new LocalizationProfileTable();

            localizationProfileTable.SupportsState = false;
            localizationProfileTable.ProfileName   = "Richardson Base";
            localizationProfileTable.CreateDate    = DateTime.Now;
            localizationProfileTable.LastUpdate    = DateTime.Now;
            localizationProfileTable.CreateUserId  = "richardson";
            localizationProfileTable.EditorId      = "richardson";
            localizationProfileTable.FromCountry   = "US";
            localizationProfileTable.FromState     = "US AVERAGE";
            long?long = (long?)DatabaseDBUtil.currentSession().save(localizationProfileTable);

            localizationProfileTable = (LocalizationProfileTable)DatabaseDBUtil.currentSession().load(typeof(LocalizationProfileTable), long);
            if (localizationProfileTable.Factors == null)
            {
                localizationProfileTable.Factors = new List <object>();
            }
            string            str = "SELECT * FROM CRAFT";
            PreparedStatement preparedStatement = this.con.prepareStatement(str);
            ResultSet         resultSet         = preparedStatement.executeQuery();
            sbyte             b = 0;

            while (resultSet.next())
            {
                int?   integer = Convert.ToInt32(resultSet.getInt(1));
                string str1    = resultSet.getString(2);
                string str2    = resultSet.getString(3);
                string str3    = resultSet.getString(4);
                double?double1;
                double?double2 = (double1 = Convert.ToDouble(resultSet.getDouble(5))).valueOf(resultSet.getDouble(6));
                string str4    = resultSet.getString(7);
                if (str1.Equals("0RICH0"))
                {
                    continue;
                }
                double?                 double3        = (double?)this.averagesMap[str3];
                RichardsonCity          richardsonCity = (RichardsonCity)this.citiesMap[str1];
                double                  d = (double1.Value + double2.Value) / double3.Value;
                LocalizationFactorTable localizationFactorTable = new LocalizationFactorTable();
                localizationFactorTable.AssemblyFactor      = BigDecimalMath.ONE;
                localizationFactorTable.EquipmentFactor     = BigDecimalMath.ONE;
                localizationFactorTable.Online              = true;
                localizationFactorTable.EditorId            = "richardson";
                localizationFactorTable.SubcontractorFactor = BigDecimalMath.ONE;
                localizationFactorTable.LaborFactor         = new BigDecimalFixed("" + d);
                localizationFactorTable.MaterialFactor      = BigDecimalMath.ONE;
                localizationFactorTable.ConsumableFactor    = BigDecimalMath.ONE;
                string str5 = richardsonCity.CountryCode;
                if (str5.Equals("USA"))
                {
                    str5 = "US";
                }
                else if (str5.Equals("CAN"))
                {
                    str5 = "CA";
                }
                LocationData locationData = LocationDataRetriever.Instance.retrieveForNorthAmericaData(richardsonCity.ZipCode, richardsonCity.StateCode, richardsonCity.City, str5);
                if (locationData == null)
                {
                    Console.WriteLine("NO LOCATION DATA FOUND FOR: " + richardsonCity);
                    continue;
                }
                localizationFactorTable.ToCountry                = locationData.Country;
                localizationFactorTable.ToState                  = locationData.State;
                localizationFactorTable.ToCity                   = locationData.City;
                localizationFactorTable.ToZipCode                = locationData.ZipCode;
                localizationFactorTable.GroupCodeName            = "";
                localizationFactorTable.ParentCode               = str3;
                localizationFactorTable.GeoPolygon               = locationData.GeoPolygon;
                localizationFactorTable.LocalizationProfileTable = localizationProfileTable;
                localizationProfileTable.Factors.Add(localizationFactorTable);
                Console.WriteLine("I AM SAVING: " + localizationFactorTable.ToCountry + ", " + localizationFactorTable.ToState + ", " + localizationFactorTable.ToCity + ", " + localizationFactorTable.ToZipCode);
                DatabaseDBUtil.currentSession().save(localizationFactorTable);
                if (++b % 'Ǵ' == 'dz')
                {
                    DatabaseDBUtil.currentSession().Transaction.commit();
                    DatabaseDBUtil.currentSession().beginTransaction();
                    Console.WriteLine("\n\n\n\n\n\nCommitted " + b + " factors");
                }
            }
            preparedStatement.close();
            DatabaseDBUtil.currentSession().Transaction.commit();
            DatabaseDBUtil.closeSession();
        }
Example #28
0
 private static string CreateString(LocationData value)
 {
     return(value.IsValid ? string.Format(CultureInfo.InvariantCulture, "({0},{1})", value.Line, value.Position) : null);
 }
Example #29
0
        /// <summary>
        /// Gets the UI element that represents the specified location;
        /// used to access the attached editor flyout.
        /// <param name="location">The location to edit.</param>
        /// <returns>The element that represents the location.</returns>
        private FrameworkElement GetTemplateRootForLocation(LocationData location)
        {
            var item = this.LocationsView.ContainerFromItem(location) as ListViewItem;

            return(item.ContentTemplateRoot as FrameworkElement);
        }
        private async Task UpdateLocationMeta(List <LocationMetadata> LocationMeta, string Userid, LocationData loc, int?LocConfigID, int CompanyID, int LocId, bool isActive)
        {
            List <LocationMetadata> metadata = new List <LocationMetadata>();
            var LocationName = LocationMeta.FirstOrDefault(x => x.Key == "LocationName");

            LocationName.Value      = loc.LocationName;
            LocationName.ModifiedBy = Userid;
            LocationName.ModifiedOn = DateTime.Now;
            await context.SaveChangesAsync();

            //
            var FirstContactName = LocationMeta.FirstOrDefault(x => x.Key == "FirstContactName");

            FirstContactName.Value      = loc.FirstContactName;
            FirstContactName.ModifiedBy = Userid;
            FirstContactName.ModifiedOn = DateTime.Now;
            await context.SaveChangesAsync();

            //
            var FirstContactEmail = LocationMeta.FirstOrDefault(x => x.Key == "FirstContactEmail");

            FirstContactEmail.Value      = loc.FirstContactEmail;
            FirstContactEmail.ModifiedBy = Userid;
            FirstContactEmail.ModifiedOn = DateTime.Now;
            await context.SaveChangesAsync();

            //
            if (!string.IsNullOrEmpty(loc.SecondContactName))
            {
                var SecondContactName = LocationMeta.FirstOrDefault(x => x.Key == "SecondContactName");
                if (SecondContactName == null)
                {
                    metadata.Add(SetMeta(CompanyID, LocConfigID ?? 0, "SecondContactName", loc.SecondContactName, 5, loc.Tags, Userid, DateTime.Now, LocId, isActive));
                }
                else
                {
                    SecondContactName.Value      = loc.SecondContactName;
                    SecondContactName.ModifiedBy = Userid;
                    SecondContactName.ModifiedOn = DateTime.Now;
                    await context.SaveChangesAsync();
                }
            }
            //
            if (!string.IsNullOrEmpty(loc.SecondContactEmail))
            {
                var SecondContactEmail = LocationMeta.FirstOrDefault(x => x.Key == "SecondContactEmail");
                if (SecondContactEmail == null)
                {
                    metadata.Add(SetMeta(CompanyID, LocConfigID ?? 0, "SecondContactEmail", loc.SecondContactEmail, 4, loc.Tags, Userid, DateTime.Now, LocId, isActive));
                }
                else
                {
                    SecondContactEmail.Value      = loc.SecondContactEmail;
                    SecondContactEmail.ModifiedBy = Userid;
                    SecondContactEmail.ModifiedOn = DateTime.Now;
                    await context.SaveChangesAsync();
                }
            }

            //
            if (!string.IsNullOrEmpty(loc.ThirdContactName))
            {
                var ThirdContactName = LocationMeta.FirstOrDefault(x => x.Key == "ThirdContactName");
                if (ThirdContactName == null)
                {
                    metadata.Add(SetMeta(CompanyID, LocConfigID ?? 0, "ThirdContactName", loc.ThirdContactName, 7, loc.Tags, Userid, DateTime.Now, LocId, isActive));
                }
                else
                {
                    ThirdContactName.Value      = loc.ThirdContactName;
                    ThirdContactName.ModifiedBy = Userid;
                    ThirdContactName.ModifiedOn = DateTime.Now;
                    await context.SaveChangesAsync();
                }
            }
            //
            if (!string.IsNullOrEmpty(loc.ThirdContactEmail))
            {
                var ThirdContactEmail = LocationMeta.FirstOrDefault(x => x.Key == "ThirdContactEmail");
                if (ThirdContactEmail == null)
                {
                    metadata.Add(SetMeta(CompanyID, LocConfigID ?? 0, "ThirdContactEmail", loc.ThirdContactEmail, 6, loc.Tags, Userid, DateTime.Now, LocId, isActive));
                }
                else
                {
                    ThirdContactEmail.Value      = loc.ThirdContactEmail;
                    ThirdContactEmail.ModifiedBy = Userid;
                    ThirdContactEmail.ModifiedOn = DateTime.Now;
                    await context.SaveChangesAsync();
                }
            }
            context.LocationMetadatas.AddRange(metadata);
            await context.SaveChangesAsync();
        }
Example #31
0
 public MercuryModel(double jd, LocationData location) : base(jd, location)
 {
 }
Example #32
0
 /// <summary>
 /// Helper to create a token with given text.
 /// </summary>
 private static LocationData CreateToken(BuildXLContext context)
 {
     return(LocationData.Create(AbsolutePath.Create(context.PathTable, AssemblyHelper.GetAssemblyLocation(typeof(MountsTable).GetTypeInfo().Assembly))));
 }
        /// <summary>
        /// Constructs an object used to create a <see cref="NetworkInterface"/>.
        /// </summary>
        /// <param name="ip"> The public IP address of the <see cref="NetworkInterface"/>. </param>
        /// <param name="subnetId"> The resource identifier of the subnet attached to this <see cref="NetworkInterface"/>. </param>
        /// <param name="location"> The <see cref="LocationData"/> that will contain the <see cref="NetworkInterface"/>. </param>
        /// <returns>An object used to create a <see cref="NetworkInterface"/>. </returns>
        public ArmBuilder <NetworkInterface, NetworkInterfaceData> Construct(string subnetId, PublicIPAddressData ip = default, LocationData location = null)
        {
            var parent = GetParentResource <ResourceGroup, ResourceGroupOperations>();
            var nic    = new Azure.ResourceManager.Network.Models.NetworkInterface()
            {
                Location         = location ?? parent.Data.Location,
                IpConfigurations = new List <NetworkInterfaceIPConfiguration>()
                {
                    new NetworkInterfaceIPConfiguration()
                    {
                        Name    = "Primary",
                        Primary = true,
                        Subnet  = new Azure.ResourceManager.Network.Models.Subnet()
                        {
                            Id = subnetId
                        },
                        PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
                    }
                }
            };

            if (ip != null)
            {
                nic.IpConfigurations[0].PublicIPAddress = new PublicIPAddress()
                {
                    Id = ip.Id
                }
            }
            ;

            return(new ArmBuilder <NetworkInterface, NetworkInterfaceData>(this, new NetworkInterfaceData(nic)));
        }
Example #34
0
 public XElement CreateRow(string key, LocationData value)
 {
     return(CreateRow(key, string.Format(CultureInfo.InvariantCulture, " ({0},{1})", value.Line, value.Position)));
 }
Example #35
0
        private async Task <LocationData> UpdateLocation()
        {
            LocationData locationData = null;

            if (Settings.FollowGPS)
            {
                if (AppCompatActivity != null && ContextCompat.CheckSelfPermission(AppCompatActivity, Manifest.Permission.AccessFineLocation) != Permission.Granted &&
                    ContextCompat.CheckSelfPermission(AppCompatActivity, Manifest.Permission.AccessCoarseLocation) != Permission.Granted)
                {
                    ActivityCompat.RequestPermissions(AppCompatActivity, new String[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessFineLocation },
                                                      PERMISSION_LOCATION_REQUEST_CODE);
                    return(null);
                }

                LocationManager locMan       = (LocationManager)AppCompatActivity.GetSystemService(Context.LocationService);
                bool            isGPSEnabled = locMan.IsProviderEnabled(LocationManager.GpsProvider);
                bool            isNetEnabled = locMan.IsProviderEnabled(LocationManager.NetworkProvider);

                Android.Locations.Location location = null;

                if (isGPSEnabled || isNetEnabled)
                {
                    Criteria locCriteria = new Criteria()
                    {
                        Accuracy = Accuracy.Coarse, CostAllowed = false, PowerRequirement = Power.Low
                    };
                    string provider = locMan.GetBestProvider(locCriteria, true);
                    location = locMan.GetLastKnownLocation(provider);

                    if (location == null)
                    {
                        locMan.RequestSingleUpdate(provider, mLocListnr, null);
                    }
                    else
                    {
                        LocationQueryViewModel view = null;

                        await Task.Run(async() =>
                        {
                            view = await wm.GetLocation(location);

                            if (String.IsNullOrEmpty(view.LocationQuery))
                            {
                                view = new LocationQueryViewModel();
                            }
                        });

                        if (String.IsNullOrWhiteSpace(view.LocationQuery))
                        {
                            // Stop since there is no valid query
                            AppCompatActivity?.RunOnUiThread(() =>
                            {
                                gpsPanelViewModel         = null;
                                gpsPanelLayout.Visibility = ViewStates.Gone;
                            });
                            return(null);
                        }

                        // Save location as last known
                        locationData = new LocationData(view, location);
                    }
                }
                else
                {
                    AppCompatActivity?.RunOnUiThread(() =>
                    {
                        Toast.MakeText(AppCompatActivity, Resource.String.error_retrieve_location, ToastLength.Short).Show();
                        gpsPanelViewModel         = null;
                        gpsPanelLayout.Visibility = ViewStates.Gone;
                    });
                }
            }

            return(locationData);
        }
Example #36
0
        public TestEnv(
            string name,
            string rootPath,
            bool enableLazyOutputMaterialization = false,
            int maxRelativeOutputDirectoryLength = 260,
            List <IMount> mounts = null,
            PathTable pathTable  = null)
        {
            Contract.Requires(name != null);
            Contract.Requires(!string.IsNullOrEmpty(rootPath));

            LoggingContext = new LoggingContext("TestLogger." + name);
            PathTable      = pathTable ?? new PathTable();

            PipDataBuilderPool = new ObjectPool <PipDataBuilder>(() => new PipDataBuilder(PathTable.StringTable), _ => { });

            // The tests that use TestEnv need to be modernized to take a filesystem
            var fileSystem = new PassThroughFileSystem(PathTable);

            Context = EngineContext.CreateNew(CancellationToken.None, PathTable, fileSystem);

            // Add some well-known paths with fixed casing to the Context.PathTable
            AbsolutePath.Create(Context.PathTable, rootPath.ToLowerInvariant());
            var root = AbsolutePath.Create(Context.PathTable, rootPath);

            var configuration = ConfigHelpers.CreateDefaultForXml(Context.PathTable, root);

            configuration.Layout.SourceDirectory = root.Combine(PathTable, PathAtom.Create(PathTable.StringTable, "src")); // These tests have non-standard src folder
            configuration.Engine.MaxRelativeOutputDirectoryLength   = maxRelativeOutputDirectoryLength;
            configuration.Schedule.EnableLazyOutputMaterialization  = enableLazyOutputMaterialization;
            configuration.Schedule.UnsafeDisableGraphPostValidation = false;
            configuration.Schedule.ComputePipStaticFingerprints     = true;
            configuration.Sandbox.FileAccessIgnoreCodeCoverage      = true;

            BuildXLEngine.PopulateFileSystemCapabilities(configuration, configuration, Context.PathTable, LoggingContext);
            BuildXLEngine.PopulateLoggingAndLayoutConfiguration(configuration, Context.PathTable, bxlExeLocation: null, inTestMode: true);
            BuildXLEngine.PopulateAndValidateConfiguration(configuration, configuration, Context.PathTable, LoggingContext);

            Configuration = configuration;

            var mountsTable = MountsTable.CreateAndRegister(LoggingContext, Context, Configuration, null);

            if (mounts != null)
            {
                foreach (var mount in mounts)
                {
                    mountsTable.AddResolvedMount(mount);
                }
            }

            AbsolutePath specFile = SourceRoot.CreateRelative(Context.PathTable, "TestSpecFile.dsc");

            var graph = TestSchedulerFactory.CreateEmptyPipGraph(Context, configuration, mountsTable.MountPathExpander);

            PipTable = graph.PipTable;
            PipGraph = graph;

            var locationData = new LocationData(specFile, 0, 0);
            var modulePip    = ModulePip.CreateForTesting(Context.StringTable, specFile);

            PipGraph.AddModule(modulePip);
            PipGraph.AddSpecFile(new SpecFilePip(FileArtifact.CreateSourceFile(specFile), locationData, modulePip.Module));

            PipConstructionHelper = PipConstructionHelper.CreateForTesting(
                Context,
                ObjectRoot,
                redirectedRoot: Configuration.Layout.RedirectedDirectory,
                pipGraph: PipGraph,
                moduleName: modulePip.Identity.ToString(Context.StringTable),
                symbol: name,
                specPath: specFile);

            Paths = new Paths(PathTable);

            mountsTable.CompleteInitialization();
        }
Example #37
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (e.Parameter != null)
            {
                string arg = e.Parameter.ToString();

                switch (arg)
                {
                case "view-alerts":
                    GotoAlertsPage();
                    break;

                default:
                    break;
                }
            }

            LocationData LocParameter = e.Parameter as LocationData;

            if (e.NavigationMode == NavigationMode.New)
            {
                // Reset loader if new page instance created
                location = null;
                wLoader  = null;
                MainViewer.ChangeView(null, 0, null);

                // New page instance created, so restore
                if (LocParameter != null)
                {
                    location = LocParameter;
                    wLoader  = new WeatherDataLoader(location, this, this);
                }

                await Restore();
            }
            else
            {
                LocationData homeData = Settings.HomeData;

                // Did home change?
                bool homeChanged = false;
                if (location != null && Frame.BackStack.Count == 0)
                {
                    if (!location.Equals(homeData))
                    {
                        location    = homeData;
                        homeChanged = true;
                    }
                }

                if (wLoader != null)
                {
                    var userlang = GlobalizationPreferences.Languages.First();
                    var culture  = new CultureInfo(userlang);
                    var locale   = wm.LocaleToLangCode(culture.TwoLetterISOLanguageName, culture.Name);

                    // Reset loader if source, query or locale is different
                    bool resetLoader = WeatherView.WeatherSource != Settings.API || homeChanged;
                    if (wm.SupportsWeatherLocale && !resetLoader)
                    {
                        resetLoader = WeatherView.WeatherLocale != locale;
                    }

                    if (resetLoader)
                    {
                        wLoader = null;
                    }
                }

                // Update view on resume
                // ex. If temperature unit changed
                if ((wLoader != null) && !homeChanged)
                {
                    await Resume();

                    if (location.query == homeData.query)
                    {
                        // Clear backstack since we're home
                        Frame.BackStack.Clear();
                        SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
                    }
                }
                else
                {
                    await Restore();
                }
            }
        }
Example #38
0
        static async void TrackingLoop()
        {
            Trkr.RestServices.RestService _restService;
            _restService = new Trkr.RestServices.RestService();

            CustomMap iCustomMap   = new CustomMap();
            CustomMap havetoListTo = new CustomMap();

            while (true)
            {
                LocationData locationParameter = null;


                try
                {
                    var      request  = new GeolocationRequest(GeolocationAccuracy.Best);
                    Location location = await Geolocation.GetLocationAsync(request);

                    if (location != null)
                    {
                        Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
                        locationParameter = new LocationData
                        {
                            Guid      = Guid.NewGuid(),
                            Latitude  = location.Latitude,
                            Longitude = location.Longitude,
                            Velocity  = (double)location.Speed,
                            Timestamp = DateTime.Now.ToString(),
                            UserId    = App.logedInUser.Email
                        };
                    }


                    // chechs if i moving faster than 1 m/s^
                    if (locationParameter.Velocity > 1)
                    {
                        LocationData locationData = await _restService.CreateLocation(GenerateLocationUri(Constants.locationAdress), locationParameter);

                        iCustomMap.RouteCoordinates.Add(new Position(locationParameter.Latitude, locationParameter.Longitude));
                        iCustomMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(locationParameter.Latitude, locationParameter.Longitude), Distance.FromKilometers(1.5)));

                        havetoListTo.RouteCoordinates.Add(new Position(locationParameter.Latitude, locationParameter.Longitude));
                    }
                }

                catch (FeatureNotSupportedException fnsEx)
                {
                    // Handle not supported on device exception
                }
                catch (FeatureNotEnabledException fneEx)
                {
                    // Handle not enabled on device exception
                }
                catch (PermissionException pEx)
                {
                    // Handle permission exception
                }
                catch (Exception ex)
                {
                    // Unable to get location
                }

                await Task.Delay(10000);
            }


            string GenerateLocationUri(string endpoint)
            {
                string requestUri = endpoint;

                requestUri += $"?apiKey={Constants.APIKey}";

                return(requestUri);
            }
        }
Example #39
0
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.FollowGPS && (location == null || location.locationType == LocationType.GPS))
            {
                Geoposition newGeoPos = null;

                try
                {
                    newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10));
                }
                catch (Exception)
                {
                    var geoStatus = GeolocationAccessStatus.Unspecified;

                    try
                    {
                        geoStatus = await Geolocator.RequestAccessAsync();
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteLine(LoggerLevel.Error, ex, "WeatherNow: GetWeather error");
                    }
                    finally
                    {
                        if (geoStatus == GeolocationAccessStatus.Allowed)
                        {
                            try
                            {
                                newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10));
                            }
                            catch (Exception ex)
                            {
                                Logger.WriteLine(LoggerLevel.Error, ex, "WeatherNow: GetWeather error");
                            }
                        }
                        else if (geoStatus == GeolocationAccessStatus.Denied)
                        {
                            // Disable gps feature
                            Settings.FollowGPS = false;
                        }
                    }

                    if (!Settings.FollowGPS)
                    {
                        return(false);
                    }
                }

                // Access to location granted
                if (newGeoPos != null)
                {
                    LocationData lastGPSLocData = await Settings.GetLastGPSLocData();

                    // Check previous location difference
                    if (lastGPSLocData.query != null &&
                        geoPos != null && ConversionMethods.CalculateGeopositionDistance(geoPos, newGeoPos) < geolocal.MovementThreshold)
                    {
                        return(false);
                    }

                    if (lastGPSLocData.query != null &&
                        Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                      newGeoPos.Coordinate.Point.Position.Latitude, newGeoPos.Coordinate.Point.Position.Longitude)) < geolocal.MovementThreshold)
                    {
                        return(false);
                    }

                    LocationQueryViewModel view = null;

                    await Task.Run(async() =>
                    {
                        view = await wm.GetLocation(newGeoPos);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    });

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        return(false);
                    }

                    // Save oldkey
                    string oldkey = lastGPSLocData.query;

                    // Save location as last known
                    lastGPSLocData.SetData(view, newGeoPos);
                    Settings.SaveLastGPSLocData(lastGPSLocData);

                    // Update tile id for location
                    if (oldkey != null && SecondaryTileUtils.Exists(oldkey))
                    {
                        await SecondaryTileUtils.UpdateTileId(oldkey, lastGPSLocData.query);
                    }

                    location        = lastGPSLocData;
                    geoPos          = newGeoPos;
                    locationChanged = true;
                }
            }

            return(locationChanged);
        }
Example #40
0
 private void Start()
 {
     m_CurrentLocation = m_StartLocation;
     LoadLocationInternal();
 }
        private async void GPS_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button button = sender as Button;
                button.IsEnabled     = false;
                LoadingRing.IsActive = true;

                // Cancel other tasks
                cts.Cancel();
                cts = new CancellationTokenSource();
                var ctsToken = cts.Token;

                ctsToken.ThrowIfCancellationRequested();

                var geoStatus = GeolocationAccessStatus.Unspecified;

                try
                {
                    // Catch error in case dialog is dismissed
                    geoStatus = await Geolocator.RequestAccessAsync();
                }
                catch (Exception ex)
                {
                    Logger.WriteLine(LoggerLevel.Error, ex, "SetupPage: error requesting location permission");
                    System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                }

                ctsToken.ThrowIfCancellationRequested();

                Geolocator geolocal = new Geolocator()
                {
                    DesiredAccuracyInMeters = 5000, ReportInterval = 900000, MovementThreshold = 1600
                };
                Geoposition geoPos = null;

                // Setup error just in case
                MessageDialog error = null;

                switch (geoStatus)
                {
                case GeolocationAccessStatus.Allowed:
                    try
                    {
                        geoPos = await geolocal.GetGeopositionAsync();
                    }
                    catch (Exception ex)
                    {
                        if (Windows.Web.WebError.GetStatus(ex.HResult) > Windows.Web.WebErrorStatus.Unknown)
                        {
                            error = new MessageDialog(App.ResLoader.GetString("WError_NetworkError"), App.ResLoader.GetString("Label_Error"));
                        }
                        else
                        {
                            error = new MessageDialog(App.ResLoader.GetString("Error_Location"), App.ResLoader.GetString("Label_ErrorLocation"));
                        }
                        await error.ShowAsync();

                        Logger.WriteLine(LoggerLevel.Error, ex, "SetupPage: error getting geolocation");
                    }
                    break;

                case GeolocationAccessStatus.Denied:
                    error = new MessageDialog(App.ResLoader.GetString("Msg_LocDeniedSettings"), App.ResLoader.GetString("Label_ErrLocationDenied"));
                    error.Commands.Add(new UICommand(App.ResLoader.GetString("Label_Settings"), async(command) =>
                    {
                        await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location"));
                    }, 0));
                    error.Commands.Add(new UICommand(App.ResLoader.GetString("Label_Cancel"), null, 1));
                    error.DefaultCommandIndex = 0;
                    error.CancelCommandIndex  = 1;
                    await error.ShowAsync();

                    break;

                case GeolocationAccessStatus.Unspecified:
                default:
                    error = new MessageDialog(App.ResLoader.GetString("Error_Location"), App.ResLoader.GetString("Label_ErrorLocation"));
                    await error.ShowAsync();

                    break;
                }

                // Access to location granted
                if (geoPos != null)
                {
                    LocationQueryViewModel view = null;

                    ctsToken.ThrowIfCancellationRequested();

                    button.IsEnabled = false;

                    await Task.Run(async() =>
                    {
                        ctsToken.ThrowIfCancellationRequested();

                        view = await wm.GetLocation(geoPos);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    });

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        EnableControls(true);
                        return;
                    }

                    ctsToken.ThrowIfCancellationRequested();

                    // Weather Data
                    var location = new LocationData(view, geoPos);
                    if (!location.IsValid())
                    {
                        await Toast.ShowToastAsync(App.ResLoader.GetString("WError_NoWeather"), ToastDuration.Short);

                        EnableControls(true);
                        return;
                    }

                    ctsToken.ThrowIfCancellationRequested();

                    Weather weather = await Settings.GetWeatherData(location.query);

                    if (weather == null)
                    {
                        ctsToken.ThrowIfCancellationRequested();

                        try
                        {
                            weather = await wm.GetWeather(location);
                        }
                        catch (WeatherException wEx)
                        {
                            weather = null;
                            await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short);
                        }
                    }

                    if (weather == null)
                    {
                        EnableControls(true);
                        return;
                    }

                    ctsToken.ThrowIfCancellationRequested();

                    // We got our data so disable controls just in case
                    EnableControls(false);

                    // Save weather data
                    Settings.SaveLastGPSLocData(location);
                    await Settings.DeleteLocations();

                    await Settings.AddLocation(new LocationData(view));

                    if (wm.SupportsAlerts && weather.weather_alerts != null)
                    {
                        await Settings.SaveWeatherAlerts(location, weather.weather_alerts);
                    }
                    await Settings.SaveWeatherData(weather);

                    Settings.FollowGPS     = true;
                    Settings.WeatherLoaded = true;

                    this.Frame.Navigate(typeof(Shell), location);
                }
                else
                {
                    EnableControls(true);
                }
            }
            catch (OperationCanceledException)
            {
                // Restore controls
                EnableControls(true);
                Settings.FollowGPS     = false;
                Settings.WeatherLoaded = false;
            }
        }
Example #42
0
    //SAVE GAME TO JSON IN TXT FILE
    public static void save(LocationsMap locationsMap)
    {
        //GameState data
        GameStateData gameStateData = new GameStateData();

        gameStateData.finishedTutorial = GameState.finishedTutorial;

        List <ItemData> idl = new List <ItemData>();

        foreach (Item qi in GameState.questItemsCollected)
        {
            ItemData id = new ItemData();
            id.name     = qi.name;
            id.position = new float[] { 0, 0, 0 };
        }

        gameStateData.questItemsCollected = idl.ToArray();

        Player _player = GameState.player;

        //PLAYER DATA
        PlayerData playerData = new PlayerData();

        playerData.health    = _player.health;
        playerData.maxHealth = _player.maxHealth;
        if (_player.weapon != null)
        {
            playerData.weapon = _player.weapon.name;
        }
        if (_player.shield != null)
        {
            playerData.shield = _player.shield.name;
        }

        List <ItemData> ids = new List <ItemData>();

        foreach (Item s in _player.getInventoryItems())
        {
            ItemData id = new ItemData();

            id.name     = s.name;
            id.position = new float[] { 0, 0, 0 };
            ids.Add(id);
        }

        playerData.inventory = ids.ToArray();

        gameStateData.currentLocation = locationsMap.getLocationName();

        playerData.gold = _player.gold;

        gameStateData.player = playerData;

        //LOCATION DATA
        Locations locations = new Locations();

        Location[]          locationsFromMap = locationsMap.getAllLocations();
        List <LocationData> lds = new List <LocationData>();

        foreach (Location l in locationsFromMap)
        {
            if (l.playerVisited)
            {
                LocationData ld = new LocationData();
                ld.locationName = l.name;

                ids = new List <ItemData>();

                foreach (ItemOBJ s in l.getInventoryItems())
                {
                    if (s.GetComponent <SpriteRenderer>().enabled)
                    {
                        ItemData id = new ItemData();

                        id.name     = s.name;
                        id.position = new float[] { s.transform.position.x, s.transform.position.y, s.transform.position.z };
                        ids.Add(id);
                    }
                }

                ld.items = ids.ToArray();

                List <EnemyData> edList = new List <EnemyData>();

                foreach (EnemyOBJ e in l.getEnemies())
                {
                    EnemyData ed = new EnemyData();
                    ed.name      = e.name;
                    ed.maxHealth = e.maxHealth;
                    if (e.weapon != null)
                    {
                        ed.weapon = e.weapon.name;
                    }
                    if (e.shield != null)
                    {
                        ed.shield = e.shield.name;
                    }
                    ed.sprite = e.sprite.name;

                    ed.position = new float[] { e.transform.position.x, e.transform.position.y, e.transform.position.z };

                    edList.Add(ed);
                }
                ld.enemies = edList.ToArray();


                if (l.trader != null)
                {
                    TraderData td     = new TraderData();
                    TraderOBJ  trader = l.getTraderOBJ();

                    td.name      = trader.name;
                    td.maxHealth = trader.maxHealth;
                    td.weapon    = trader.weapon.name;
                    td.sprite    = trader.sprite.name;
                    td.gold      = trader.trader.gold;
                    td.position  = new float[] { trader.transform.position.x, trader.transform.position.y, trader.transform.position.z };

                    idl.Clear();

                    foreach (Item i in trader.stock)
                    {
                        ItemData id = new ItemData();
                        id.name     = i.name;
                        id.position = new float[] { 0, 0, 0 };
                        idl.Add(id);
                    }

                    td.stock = idl.ToArray();

                    ld.trader = td;
                }
                lds.Add(ld);
            }
        }
        locations.locations = lds.ToArray();

        string JsonGameState       = JsonUtility.ToJson(gameStateData);
        string JsonStringLocations = JsonUtility.ToJson(locations);

        if (!Directory.Exists("Gamesave/"))
        {
            try
            {
                Directory.CreateDirectory("Gamesave/");
            }
            catch (System.Exception e)
            {
                Debug.Log("Creation failed: " + e.ToString());
            }
        }

        using (StreamWriter writer = new StreamWriter(@"Gamesave/save.json"))
        {
            writer.WriteLine(JsonGameState);
            writer.WriteLine(JsonStringLocations);
        }
    }
        /// <summary>
        /// cstor which extracts the data from the XML feed and push it into
        /// the strongly typed class which is then available in the razor script
        /// files
        /// </summary>
        /// <param name="xmlData"></param>
        public WeatherModel(string xmlData)
        {
            data = xmlData;

            //load all the data
            using (var reader = new StringReader(data))
            {
                var xPath = new XPathDocument(reader);
                var nav   = xPath.CreateNavigator();

                XmlNamespaceManager ns = new XmlNamespaceManager(nav.NameTable);
                ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
                ns.AddNamespace("geo", "http://www.w3.org/2003/01/geo/wgs84_pos#");

                Title       = nav.SelectSingleNode("//item/title").Value;
                PublishDate = nav.SelectSingleNode("//lastBuildDate").Value;

                var location = new LocationData()
                {
                    City    = nav.SelectSingleNode("//yweather:location/@city", ns).Value,
                    Region  = nav.SelectSingleNode("//yweather:location/@region", ns).Value,
                    Country = nav.SelectSingleNode("//yweather:location/@country", ns).Value,
                    Lat     = decimal.Parse(nav.SelectSingleNode("//geo:lat", ns).Value),
                    Long    = decimal.Parse(nav.SelectSingleNode("//geo:long", ns).Value)
                };
                Location = location;


                var units = new UnitData()
                {
                    Temperature = nav.SelectSingleNode("//yweather:units/@temperature", ns).Value,
                    Distance    = nav.SelectSingleNode("//yweather:units/@distance", ns).Value,
                    Pressure    = nav.SelectSingleNode("//yweather:units/@pressure", ns).Value,
                    Speed       = nav.SelectSingleNode("//yweather:units/@speed", ns).Value
                };
                Units = units;


                var wind = new WindData()
                {
                    Chill     = decimal.Parse(nav.SelectSingleNode("//yweather:wind/@chill", ns).Value),
                    Direction = int.Parse(nav.SelectSingleNode("//yweather:wind/@direction", ns).Value),
                    Speed     = decimal.Parse(nav.SelectSingleNode("//yweather:wind/@speed", ns).Value)
                };
                Wind = wind;


                var atmos = new AtmosphereData()
                {
                    Humidity   = decimal.Parse(nav.SelectSingleNode("//yweather:atmosphere/@humidity", ns).Value),
                    Visibility = decimal.Parse(nav.SelectSingleNode("//yweather:atmosphere/@visibility", ns).Value),
                    Pressure   = decimal.Parse(nav.SelectSingleNode("//yweather:atmosphere/@pressure", ns).Value),
                    Rising     = decimal.Parse(nav.SelectSingleNode("//yweather:atmosphere/@rising", ns).Value)
                };
                Atmosphere = atmos;


                var astro = new AstronomyData()
                {
                    SunRise = DateTime.Parse(nav.SelectSingleNode("//yweather:astronomy/@sunrise", ns).Value),
                    SunSet  = DateTime.Parse(nav.SelectSingleNode("//yweather:astronomy/@sunset", ns).Value)
                };
                Astronomy = astro;


                var conditions = new ConditionData()
                {
                    Caption     = nav.SelectSingleNode("//yweather:condition/@text", ns).Value,
                    Code        = int.Parse(nav.SelectSingleNode("//yweather:condition/@code", ns).Value),
                    Temperature = int.Parse(nav.SelectSingleNode("//yweather:condition/@temp", ns).Value),
                    Date        = DateTime.Parse(nav.SelectSingleNode("//yweather:condition/@date", ns).Value.Substring(0, nav.SelectSingleNode("//yweather:condition/@date", ns).Value.Length - 3))
                };
                CurrentCondition = conditions;

                var forecasts = new List <ForecastData>();
                foreach (XPathNavigator item in nav.Select("//yweather:forecast", ns))
                {
                    forecasts.Add(new ForecastData()
                    {
                        Day      = item.SelectSingleNode("@day", ns).Value,
                        Date     = DateTime.Parse(item.SelectSingleNode("@date", ns).Value),
                        TempLow  = int.Parse(item.SelectSingleNode("@low", ns).Value),
                        TempHigh = int.Parse(item.SelectSingleNode("@high", ns).Value),
                        Code     = int.Parse(item.SelectSingleNode("@code", ns).Value),
                        Caption  = item.SelectSingleNode("@text", ns).Value
                    });
                }
                Forecast = forecasts;
            }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            /**
             * 使用地图sdk前需先初始化BMapManager.
             * BMapManager是全局的,可为多个MapView共用,它需要地图模块创建前创建,
             * 并在地图地图模块销毁后销毁,只要还有地图模块在使用,BMapManager就不应该销毁
             */
            DemoApplication app = (DemoApplication)this.Application;
            if (app.mBMapManager == null)
            {
                app.mBMapManager = new BMapManager(ApplicationContext);
                /**
                 * 如果BMapManager没有初始化则初始化BMapManager
                 */
                app.mBMapManager.Init(new DemoApplication.MyGeneralListener());
            }
            SetContentView(Resource.Layout.activity_locationoverlay);
            ICharSequence titleLable = new String("定位功能");
            Title = titleLable.ToString();

            myListener = new MyLocationListenner(this);

            requestLocButton = FindViewById<Button>(Resource.Id.button1);
            mCurBtnType = E_BUTTON_TYPE.LOC;
            Android.Views.View.IOnClickListener btnClickListener = new BtnClickListenerImpl(this);

            requestLocButton.SetOnClickListener(btnClickListener);

            RadioGroup group = this.FindViewById<RadioGroup>(Resource.Id.radioGroup);
            radioButtonListener = new RadioButtonListenerImpl(this);
            group.SetOnCheckedChangeListener(radioButtonListener);

            //地图初始化
            mMapView = FindViewById<MyLocationMapView>(Resource.Id.bmapView);
            mMapController = mMapView.Controller;
            mMapView.Controller.SetZoom(14);
            mMapView.Controller.EnableClick(true);
            mMapView.SetBuiltInZoomControls(true);
            //创建 弹出泡泡图层
            CreatePaopao();

            //定位初始化
            mLocClient = new LocationClient(this);
            locData = new LocationData();
            mLocClient.RegisterLocationListener(myListener);
            LocationClientOption option = new LocationClientOption();
            option.OpenGps = true;//打开gps
            option.CoorType = "bd09ll";     //设置坐标类型
            option.ScanSpan = 1000;
            mLocClient.LocOption = option;
            mLocClient.Start();

            //定位图层初始化
            myLocationOverlay = new LocationOverlay(this, mMapView);
            //设置定位数据
            myLocationOverlay.SetData(locData);
            //添加定位图层
            mMapView.Overlays.Add(myLocationOverlay);
            myLocationOverlay.EnableCompass();
            //修改定位数据后刷新图层生效
            mMapView.Refresh();

        }