Inheritance: ModuleRules
        // Main constructor that initializes everything except window
        public Algorithm(CitiesLocations _citiesLocations, CitiesConnections _citiesConnectios, 
            City _startCity, City _finalCity, Alg_Speed _algSpeed, Heuristic _algHeuristic,
            ref GraphLayoutCity _graphLayout, ref TextBox _textBoxLog,
            ResourceDictionary _resourceDictionary, GraphManager _graphManager)
        {
            citiesLocations = _citiesLocations;
            citiesConnecitons = _citiesConnectios;

            StartCity = _startCity;
            FinalCity = _finalCity;

            AlgSpeed = _algSpeed;
            AlgHeuristic = _algHeuristic;

            graphLayout = _graphLayout;
            textBoxLog = _textBoxLog;
            resourceDictionary = _resourceDictionary;

            IsRunning = false;

            Window = null;

            CanContinue = false;

            graphManager = _graphManager;
        }
        public void CalculateDistance_with_a_valid_route_should_return_the_distance()
        {
            RoutesCalculator routesCalculator = new RoutesCalculator();

            City A = new City('A');
            City B = new City('B');
            City C = new City('C');
            City D = new City('D');
            City E = new City('E');

            A.Connections.Add(B, 5);
            B.Connections.Add(C, 4);
            C.Connections.Add(D, 8);
            D.Connections.Add(C, 8);
            D.Connections.Add(E, 6);
            A.Connections.Add(D, 5);
            C.Connections.Add(E, 2);
            E.Connections.Add(B, 3);
            A.Connections.Add(E, 7);

            Assert.IsTrue(9 == routesCalculator.CalculateDistance(A, B, C));
            Assert.IsTrue(5 == routesCalculator.CalculateDistance(A, D));
            Assert.IsTrue(13 == routesCalculator.CalculateDistance(A, D, C));
            Assert.IsTrue(22 == routesCalculator.CalculateDistance(A, E, B, C, D));
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.IsSecureConnection)
        {
            string serverName = HttpUtility.UrlEncode(Request.ServerVariables["SERVER_NAME"]);
            string filePath = Request.FilePath;
            Response.Redirect("http://" + serverName + filePath);
        }

        if (!TerritorySite.BL.Linq.Territory.IsCurrentTerritoryAssigned())
        {

            if (!Page.IsPostBack)
            {
                DoDataBind();
                City thisCity = new City(CurrentUser.CurrentAccount.CityId);
                this.address.Value = thisCity.Description + ", " + thisCity.StateProvince.Description;
                LiteralHiddenId.Text = HiddenFieldMemory.ClientID;
                LiteralHiddenCenterId.Text = HiddenFieldCenterMemory.ClientID;
                this.ButtonDone.Attributes.Add("onmousedown", "javascript:savePoints();");

            }
            this.LiteralKey.Text = System.Web.Configuration.WebConfigurationManager.AppSettings["GMAPKEY"];
            this.Form.Attributes.Add("onload", "LoadMap()");
            ShowScript = true;

        }
        else
        {
            LabelMessage.Text = "You cannot modify the map while the territory is assigned";
            tableContent.Visible = false;
            ShowScript = false;
        }
    }
        protected void Page_Load(object sender, EventArgs e)
        {
            DBConnection bindComboBox = new DBConnection();
            City cities = new City();
            DataTable DT = new DataTable();
            DT = bindComboBox.BindDropdown(cities.SearchCities(), "City_Name", "City_Number");
            CityDDL.DataSource = DT;
            CityDDL.DataValueField = "City_Number";
            CityDDL.DataTextField = "City_Name";

            CityDDL.DataBind();

            GenderDDL.Items.Add("Male");
            GenderDDL.Items.Add("Female");

            //EmployeeType
            EmployeeType empType = new EmployeeType();
            DT = bindComboBox.BindDropdown(empType.SearchEmployeeTypes(), "Employee_Type_Name", "Employee_Type_Number");

            EmployeeTypeDDL.DataSource = DT;
            EmployeeTypeDDL.DataValueField = "Employee_Type_Name";
            EmployeeTypeDDL.DataTextField = "Employee_Type_Number";

            EmployeeTypeDDL.DataBind();
        }
Exemple #5
0
partial         void Cities_Inserting(City entity)
        {
            entity.InsertDate = DateTime.Now;
            entity.InsertUser = Application.User.Name;
            entity.UpdateDate = DateTime.Now;
            entity.UpdateUser = Application.User.Name;
        }
Exemple #6
0
 public IList<City> Load()
 {
     using (MySqlConnection conn = new MySqlConnection("server = localhost; user id = root; password = ; database = test"))
     {
         conn.Open();
         var cmd = conn.CreateCommand();
         cmd.CommandText = "set character set 'utf8'";
         cmd.ExecuteNonQuery();
         var cmdText = @"select * from dol_city";
         cmd = conn.CreateCommand();
         cmd.CommandText = cmdText;
         var reader = cmd.ExecuteReader();
         var cityList = new List<City>();
         while (reader.Read())
         {
             var city = new City()
             {
                 ID = reader.GetInt32("id"),
                 Name = reader.GetString("city_name"),
                 X = reader.GetFloat("x"),
                 Y = reader.GetFloat("y")
             };
             cityList.Add(city);
         }
         reader.Close();
         return cityList;
     }
 }
        public void WriteToFile(String fileName, City from, City to, List<Link> links)
        {
            var excel = new Excel.Application();
            excel.DisplayAlerts = false;
            excel.Workbooks.Add();

            excel.Range["A1", "D1"].Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
            excel.Range["A1", "D1"].Font.Size = 14;
            excel.Range["A1", "D1"].Font.Bold = true;
            excel.Range["A1"].Value = "From";
            excel.Range["B1"].Value = "To";
            excel.Range["C1"].Value = "Distance";
            excel.Range["D1"].Value = "Transport Mode";

            int row = 2;
            foreach (var l in links)
            {
                excel.Range["A" + row.ToString()].Value = l.FromCity.Name;
                excel.Range["B" + row.ToString()].Value = l.ToCity.Name;
                excel.Range["C" + row.ToString()].Value = l.Distance;
                excel.Range["D" + row.ToString()].Value = l.TransportMode.ToString();
                row++;
            }

            excel.Columns.AutoFit();

            Excel._Workbook doc = excel.ActiveWorkbook;

            doc.SaveAs(fileName);
            doc.Close();
        }
Exemple #8
0
        IEnumerable<City> GetCitiesFromPageHtml(String html)
        {
            var startRegionMarker = "<select id=\"filterAddressTown\"";
            var endRegionMarker = "</select>";

            var startIndex = html.IndexOf(startRegionMarker);
            var endIndex = html.IndexOf(endRegionMarker, startIndex) + endRegionMarker.Length;

            var citiesXml = html.Substring(startIndex, endIndex - startIndex);

            var cities = new List<City>();

            var parsed = XDocument.Parse(citiesXml);
            foreach (var elem in parsed.Elements().First().Elements())
            { 
                var city = new City()
                {
                    Id = elem.Attribute("value").Value.Trim(),
                    Name = elem.Value.Trim()
                };

                if (city.Id == "0")
                    continue;

                cities.Add(city);
            }

            return cities;
        }
Exemple #9
0
 public Car(int xPos, int yPos, City city, Passenger passenger)
 {
     XPos = xPos;
     YPos = yPos;
     City = city;
     Passenger = passenger;
 }
Exemple #10
0
        public void WriteToFile(String fileName, City from, City to, List<Link> links)
        {
            var workbook = _excelApp.Workbooks.Add();
            var worksheet = workbook.Worksheets[1];

            worksheet.Cells[1, 1] = "From";
            worksheet.Cells[1, 2] = "To";
            worksheet.Cells[1, 3] = "Distance";
            worksheet.Cells[1, 4] = "Transport Mode";

            Range range;
            range = worksheet.get_Range("A1", "D1");
            range.Font.Size = 14;
            range.Font.Bold = true;
            range.BorderAround2(XlLineStyle.xlContinuous, XlBorderWeight.xlThin);

            int row = 2;
            foreach (var l in links)
            {
                worksheet.Cells[row, 1] = l.FromCity.Name;
                worksheet.Cells[row, 2] = l.ToCity.Name;
                worksheet.Cells[row, 3] = l.Distance;
                worksheet.Cells[row, 4] = l.TransportMode;
                ++row;
            }

            workbook.SaveAs(fileName, XlFileFormat.xlOpenXMLWorkbook);
            workbook.Close();
            return ;
        }
Exemple #11
0
        public int Insert(City city)
        {
            hotelContext.Cities.Add(city);
            Save();

            return city.ID;
        }
Exemple #12
0
        public void WriteToFile(String fileName, City from, City to, List<Link> links)
        {
            Application app = new Application();
            Workbook wb = app.Workbooks.Add();
            Worksheet ws = wb.Worksheets.Add();
            ws.Range["A1"].Value = "From";
            ws.Range["B1"].Value = "To";
            ws.Range["C1"].Value = "Distance";
            ws.Range["D1"].Value = "Transport Mode";

            Range formatRange;
            formatRange = ws.Range["A1", "D1"];
            formatRange.EntireRow.Font.Bold = true;
            formatRange.EntireRow.Font.Size = 14;

            formatRange.BorderAround2(XlLineStyle.xlContinuous, XlBorderWeight.xlThin);

            int row = 2;
            links.ForEach( l => {
                int localRow = row;
                ws.Range["A" + localRow].Value = l.FromCity.Name;
                ws.Range["B" + localRow].Value = l.ToCity.Name;
                ws.Range["C" + localRow].Value = l.Distance;
                ws.Range["D" + localRow].Value = l.TransportMode;
            });

            wb.SaveAs(fileName, XlFileFormat.xlOpenXMLWorkbook);
            wb.Close();
        }
        public bool CreateCity(string name)
        {
            if (!String.IsNullOrEmpty(name)){
                if (name.Length > 50)
                {
                    return false;
                }

                City city = this.CityRepository.Get(s => s.Name == name).FirstOrDefault();

                if (city == null)
                {
                    City newCity = new City();
                    newCity.Name = name;
                    newCity.IsDeleted = false;
                    this.CityRepository.Insert(newCity);
                    this.Save();

                    return true;
                }
                else if (city.IsDeleted == true)
                {
                    city.IsDeleted = false;
                    this.CityRepository.Update(city);
                    this.Save();

                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }
Exemple #14
0
        public override void Execute(params string[] commandParams)
        {
            string name = commandParams[0];
            string houseName = commandParams[1];
            int defense = int.Parse(commandParams[2]);
            decimal upgradeCost = decimal.Parse(commandParams[3]);
            double initialFoodStorage = double.Parse(commandParams[4]);
            double foodProduction = double.Parse(commandParams[5]);
            decimal taxBase = decimal.Parse(commandParams[6]);
            string cityType = commandParams[7];

            var controllingHouse = this.Engine.Continent.GetHouseByName(houseName);

            if (controllingHouse == null)
            {
                throw new ArgumentNullException("controllingHouse");
            }

            ICity city;
            if (cityType == "default")
            {
                city = new City(name, controllingHouse, defense, upgradeCost, initialFoodStorage, foodProduction, taxBase);
            }
            else
            {
                var type = (CityType)Enum.Parse(typeof(CityType), cityType);
                city = new City(name, controllingHouse, defense, upgradeCost, initialFoodStorage, foodProduction, taxBase, type);
            }

            this.Engine.Continent.AddCity(city);
            this.Engine.Continent.CityNeighborsAndDistances.Add(city, new Dictionary<ICity, double>());
            controllingHouse.AddCityToHouse(city);

            this.Engine.Render("Successfully created city {0}", city.Name);
        }
    protected void uploadMiasta_Click(object sender, EventArgs e)
    {
        if(fileMiasta.HasFile)
        {
            MemoryStream stream = new MemoryStream(fileMiasta.FileBytes);
            XmlReaderSettings settings = new XmlReaderSettings();

            int i = 0;
            Repository<City, Guid> cityrep = new Repository<City, Guid>();
            using (XmlReader r = XmlReader.Create(stream, settings))
            {
                XPathDocument xpathDoc = new XPathDocument(r);
                XPathNavigator xpathNav = xpathDoc.CreateNavigator();

                string xpathQuery = "/teryt/catalog/row/col[attribute::name='NAZWA']";

                XPathExpression xpathExpr = xpathNav.Compile(xpathQuery);

                XPathNodeIterator xpathIter = xpathNav.Select(xpathExpr);

                while (xpathIter.MoveNext())
                {
                    City city = new City();
                    city.Name = xpathIter.Current.Value;

                    cityrep.SaveOrUpdate(city);
                    if (i % 500 == 0)
                        HBManager.Instance.GetSession().Flush();
                    i++;
                    //AddressManager.InsertCity(new City { Name = xpathIter.Current.Value });
                }
            }
            HBManager.Instance.GetSession().Flush();
        }
    }
Exemple #16
0
 public static City GetCityByID(int id)
 {
     City city = new City();
     SqlCityProvider sqlCityProvider = new SqlCityProvider();
     city = sqlCityProvider.GetCityByID(id);
     return city;
 }
Exemple #17
0
        /// <summary>
        /// 添加数据
        /// </summary>
        public void AddData()
        {
            var city = new City();
            object obj = CityCollection.Instance.Add(city);

            // obj就是数据库返回自动增长列
        }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        bool canContinue = false;
        try
        {
            double.Parse(TextBoxHeight.Text);
            double.Parse(TextBoxWidth.Text);
            LabelSizeError.Visible = false;
            canContinue = true;
        }
        catch
        {
            LabelSizeError.Visible = true;
        }

        if (canContinue)
        {
            if (int.Parse(DropDownListLanguages.SelectedValue) > 509)
            {
                Account newAccount = CurrentUser.CurrentAccount;
                bool isEditing = !newAccount.IsNew;
                newAccount.Description = TextBoxDescription.Text;
                newAccount.CountryId = int.Parse(DropDownCountry.SelectedValue);
                newAccount.LanguageId = int.Parse(DropDownListLanguages.SelectedValue);
                newAccount.CityId = int.Parse(DropDownListCityList.SelectedValue);
                newAccount.TrackNames = CheckBoxNames.Checked;
                newAccount.TrackPhoneNumbers = CheckBoxPhoneNumbers.Checked;
                newAccount.PrintHeight = double.Parse(TextBoxHeight.Text);
                newAccount.PrintUnit = DropDownListUnit.SelectedValue;
                newAccount.PrintWidth = double.Parse(TextBoxWidth.Text);
                newAccount.IsForeignLanguage = CheckBoxIsForeignLanguage.Checked;
                newAccount.Save();
                CurrentUser.SetAccountCookie(newAccount);
                if (!isEditing)
                {
                    if (AccountUserMap.GetForCurrentUser() == null)
                    {
                        AccountUserMap newMap = new AccountUserMap();
                        newMap.AccountId = newAccount.AccountId;
                        newMap.UserId = CurrentUser.UserName;
                        newMap.Save();

                    }
                    Language defaultLanguage = new Language(509);
                    defaultLanguage.AddLanguageToCurrentAccount();
                    defaultLanguage = new Language(int.Parse(DropDownListLanguages.SelectedValue));
                    defaultLanguage.AddLanguageToCurrentAccount();
                    City selectedCity = new City(int.Parse(this.DropDownListCityList.SelectedValue));
                    selectedCity.AssociateWithCurrentAccount();
                }
                LabelMessage.Text = "Saved.";
                Saved();
                CurrentUser.Refresh();
            }
            else
            {
                LabelMessage.Text = "Please select a valid language";
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Request.QueryString["Action"] == "delete")
            {
                string x = Request.QueryString["x"].ToString();
                string y = Request.QueryString["y"].ToString();
                var db = new TerritorySite.BL.Linq.TerritoryDBDataContext();
                var addressToDelete = (from deleteAddress in db.Addresses
                                       where deleteAddress.TerritoryId == TerritoryId
                                       & deleteAddress.Long.Contains(x)
                                       & deleteAddress.Lat.Contains(y)
                                       select deleteAddress).FirstOrDefault();
                if (addressToDelete != null)
                {
                    Address.Delete(addressToDelete.AddressId);
                }

            }

            DoDataBind();

            City thisCity = new City(CurrentUser.CurrentAccount.CityId);

        }
        this.LiteralKey.Text = System.Web.Configuration.WebConfigurationManager.AppSettings["GMAPKEY"];
    }
Exemple #20
0
		public GuardCaptain(City city) : base(AIType.AI_Vendor, FightMode.None, 10, 1, 0.2, 0.4)
		{
			City = city;
            Female = Utility.RandomDouble() > 0.75;
            Blessed = true;

            Name = Female ? NameList.RandomName("female") : NameList.RandomName("male");
            Title = "the guard captain";

            Body = Female ? 0x191 : 0x190;
            HairItemID = Race.RandomHair(Female);
            FacialHairItemID = Race.RandomFacialHair(Female);
            HairHue = Race.RandomHairHue();
            Hue = Race.RandomSkinHue();

            SetStr(150);
            SetInt(50);
            SetDex(150);

            SetWearable(new ShortPants(1508));

            if (Female)
                SetWearable(new FemaleStuddedChest());
            else
                SetWearable(new PlateChest());

            SetWearable(new BodySash(1326));
            SetWearable(new Halberd());

            CantWalk = true;
		}
Exemple #21
0
        static void Main(string[] args)
        {
            TestMap tm = new TestMap();
            City city1 = new City(2, 2, tm);
            Console.WriteLine(city1);
            city1.CollectResources();
            city1.CollectResources();
            Console.WriteLine(city1);

            City city2 = new City(3, 2, tm);
            //Console.WriteLine(city2);
            //city2.CollectResources();
            //City2.CollectResources();
            //Console.WriteLine(city2);

            Corner c = new Corner(2, 2, tm);
            foreach (Tile t in c.GetAdjacentTiles(2))
                Console.WriteLine(t);

            //var unit = new TestUnit(0, 0, tm);
            //foreach (Tile t in unit.AvailableTiles())
             //   Console.WriteLine(t);

            //Console.WriteLine(unit);

            //Console.WriteLine(unit.MoveTo(new Tile(1, 2, tm)));
            //Console.WriteLine(unit);

            Console.Read();
        }
Exemple #22
0
        public static void MakeNodeList(Node root,int DummyCount)
        {
            AllNodesButRoot.Clear();
            foreach (City c in cities)
            {
                if (c != null && c.id != 0 && c.id != root.id&& c.isLarge==true )
                {
                    AllNodesButRoot.Add(c);
                }
            }
            foreach (Resort r in resorts)
            {
                if (r != null)
                {
                    AllNodesButRoot.Add(r);
                }
            }
            for(int i = 1; i <= DummyCount; i++)
            {
                City dummy = new City();
                //          dummy.id = AllNodesButRoot.Count + 1+i;
                dummy.id = root.id  ;
                dummy.name = root.name;
                dummy.isDummy = true;
                AllNodesButRoot.Add(dummy);

            }
            return;
        }
Exemple #23
0
        private static int GetMinDistance(Map map, City currentCity, Stack<City> visited)
        {
            int? minDistance = null;

            var currentDistance = 0;
            if (currentCity != null && visited.Any())
            {
                currentDistance = visited.Peek().Roads.Single(x => x.City.Name == currentCity.Name).Distance;
            }

            var unvisited = map.Cities.Except(visited).Where(x => !Equals(x, currentCity));
            if (currentCity != null)
            {
                visited.Push(currentCity);
                unvisited = unvisited.Intersect(currentCity.Roads.Select(x => x.City));
            }
            foreach (var city in unvisited)
            {
                int distance = GetMinDistance(map, city, visited);
                if (minDistance == null || distance < minDistance)
                {
                    minDistance = distance;
                }
            }
            if (currentCity != null)
            {
                visited.Pop();
            }
            currentDistance += minDistance ?? 0;
            return currentDistance;
        }
Exemple #24
0
        public string WriteToFile(String fileName, City from, City to, List<Link> links)
        {
            object misValue = System.Reflection.Missing.Value; 
            Application excelApplication = new Application();
            Workbook excelWorkBook = excelApplication.Workbooks.Add(misValue);
            Worksheet excelWorkSheet = excelWorkBook.Worksheets.get_Item(1);

            excelWorkSheet.Cells[1, 1] = "From";
            excelWorkSheet.Cells[1, 2] = "To";
            excelWorkSheet.Cells[1, 3] = "Distance";
            excelWorkSheet.Cells[1, 4] = "Transport Mode";

            Range _range;
            _range = excelWorkSheet.get_Range("A1", "D1");
            _range.Font.Size = 14;
            _range.Font.Bold = true;
            Borders borders = _range.Borders;
            borders.LineStyle = XlLineStyle.xlContinuous;
            borders.Weight = 2d;

            int j = 2;
            foreach (var l in links)
            {
                excelWorkSheet.Cells[j, 1] = l.FromCity.Name + " (" + l.FromCity.Country + ")";
                excelWorkSheet.Cells[j, 2] = l.ToCity.Name + " (" + l.ToCity.Country + ")";
                excelWorkSheet.Cells[j, 3] = l.Distance;
                excelWorkSheet.Cells[j, 4] = l.TransportMode.ToString();
                ++j;
            }
            excelWorkBook.SaveAs(fileName);
            excelWorkBook.Close();
            return "Ok";
        }
        public void Initialize()
        {
            inventory = new Inventory();

            city = new City("Madrid", 800);
            city.Prices.Add("Vieiras", 500);
            city.Prices.Add("Centollos", 450);
        }
Exemple #26
0
 public CityApi(City c)
 {
     if (c != null)
     {
         Id = c.Id;
         Name = c.Name;
     }           
 }
        private static City getCity()
        {
            City cityForMock = new City(10000, "Zagreb");
            Mock<ICitiesRepository> citiesRepositoryMock = new Mock<ICitiesRepository>();
            citiesRepositoryMock.Setup(x => x.GetCityByPostalCode(10000)).Returns(cityForMock);

            return citiesRepositoryMock.Object.GetCityByPostalCode(10000);
        }
 internal void Load(City city)
 {
     idBox.Value = (decimal)city.Id;
     nameBox.Text = city.Name;
     ccBox.Text = city.CountryCode;
     isEnabledBox.Checked = city.Enabled;
     displayOrderBox.Value = city.__isset.displayOrder ? (decimal)city.DisplayOrder : 0M;
 }
 internal static City createCityFromDALCity(CarpoolingDAL.City city)
 {
     City nc = new City();
     nc.Id = city.idCity;
     nc.Name = city.name;
     nc.PostalNumer = city.postalNumber;
     return nc;
 }
Exemple #30
0
 void OnDestroy()
 {
     instance = null;
 }
Exemple #31
0
        public void GetName(string name)
        {
            City c = City.GetMyCity();

            City.name = name;
        }
Exemple #32
0
 public void Update(City pt)
 {
     pt.ObjectState = ObjectState.Modified;
     _unitOfWork.Repository <City>().Update(pt);
 }
Exemple #33
0
        public City GetCityById(int cityId)
        {
            City city = _context.Cities.Include(c => c.Photos).FirstOrDefault(c => c.Id == cityId);

            return(city);
        }
Exemple #34
0
 public City Add(City model)
 {
     throw new NotImplementedException();
 }
Exemple #35
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            //Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            //Create the context
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            tracingService.Trace("Loaded UpsertSupplierWorkflow");
            tracingService.Trace("CREATING Contact object with the input values");
            tracingService.Trace("Checkpoint 1");

            Contact contact = new Contact();

            int partyid = PartyID.Get <int>(executionContext);


            tracingService.Trace("Starting assigning attribute variables.");

            contact.First_Name = FirstName.Get <string>(executionContext).ToString();
            tracingService.Trace("First Name Populated");

            tracingService.Trace(string.Format("Setting party id = {0}", partyid));
            contact.Party_Id = partyid;
            tracingService.Trace("Party ID populated");

            contact.Last_Name = LastName.Get <string>(executionContext).ToString();
            tracingService.Trace("Last Name Populated");

            contact.Payment_Method = PaymentMethod.Get <string>(executionContext).ToString();
            tracingService.Trace("Payment Method Populated");

            contact.SIN = SIN.Get <string>(executionContext).ToString();
            tracingService.Trace("SIN Populated");

            contact.Address1 = Address1.Get <string>(executionContext).ToString();
            tracingService.Trace("Address1 Populated");

            contact.Country_Code = Country.Get <string>(executionContext).ToString();
            tracingService.Trace("Country Populated");

            contact.City = City.Get <string>(executionContext).ToString();
            tracingService.Trace("City Populated");

            contact.Province_Code = Province.Get <string>(executionContext).ToString();
            tracingService.Trace("Province Populated");

            contact.Postal_Code = PostalCode.Get <string>(executionContext).ToString();
            tracingService.Trace("Postal Code Populated");
            tracingService.Trace("Checkpoint 2");


            EntityReference contactRef = ContactReference.Get <EntityReference>(executionContext);

            contact.ID = contactRef.Id;

            tracingService.Trace("Fetching the Configs");
            ////Get the configuration record for Oracle_T4A group from the configs entity and get the connection value from the record.
            var configs = Helper.GetSystemConfigurations(service, ConfigEntity.Group.ORACLE_T4A, string.Empty);

            tracingService.Trace("Fetching Connection");
            string connection = Helper.GetConfigKeyValue(configs, ConfigEntity.Key.CONNECTION, ConfigEntity.Group.ORACLE_T4A);

            try
            {
                tracingService.Trace("Fetching Oracle Response by making call to Helper.UpsertSupplierInOracle()");
                OracleResponse response = Helper.UpsertSupplierInOracle(contact, connection, tracingService);

                if (response.TransactionCode == OracleResponse.T4A_STATUS.OK)
                {
                    tracingService.Trace("Inside OracleResponse.T4A_STATUS.OK \nRetriving and setting response values to output");
                    PartyID.Set(executionContext, response.PartyId);
                    tracingService.Trace("Party ID Output Param is set");
                }

                tracingService.Trace("Setting up transaction code and transaction message");
                TransactionCode.Set(executionContext, response.TransactionCode.Trim());
                TransactionMessage.Set(executionContext, response.TransactionMessage);
            }
            catch (InvalidWorkflowException ex)
            {
                Helper.LogIntegrationError(service, ErrorType.CONTACT_ERROR, IntegrationErrorCodes.UPSERT_SUPPLIER.GetIntValue(), Strings.T4A_FER_ERROR,
                                           string.Format("Error Description: {0} ", ex.Message), contactRef);
            }
            catch (Exception ex)
            {
                Helper.LogIntegrationError(service, ErrorType.CONTACT_ERROR, IntegrationErrorCodes.UPSERT_SUPPLIER.GetIntValue(), Strings.T4A_FER_ERROR,
                                           string.Format("Error Description: {0} ", ex.Message), contactRef);
            }
        }
 public ActionResult Add([FromBody] City city)
 {
     _appRepository.Add(city);
     _appRepository.SaveAll();
     return(Ok(city));
 }
Exemple #37
0
 public override int GetHashCode()
 {
     return(PostalCode.GetHashCodeIgnoreCase() ^ Address1.GetHashCodeIgnoreCase() ^ City.GetHashCodeIgnoreCase());
 }
    public static void Main()
    {
        int         option;
        List <City> cities = new List <City>();

        do
        {
            Console.WriteLine("Menu");
            Console.WriteLine("1. Add a city");
            Console.WriteLine("2. View all cities");
            Console.WriteLine("3. Edit a city");
            Console.WriteLine("4. Search");
            Console.WriteLine("5. Delete");
            Console.WriteLine("6. Insert in position");
            Console.WriteLine("0. Exit");
            Console.Write("Enter option: ");
            option = Convert.ToInt32(Console.ReadLine());

            switch (option)
            {
            case 0:
                break;

            case 1:     // Add a new city
                City newCity;
                Console.Write("Enter name of city: ");
                newCity.name = Console.ReadLine();

                Console.Write("Enter population of city: ");
                newCity.population = Convert.ToInt32(
                    Console.ReadLine());

                cities.Add(newCity);
                break;

            case 2:     // View all the cities
                for (int i = 0; i < cities.Count; i++)
                {
                    Console.WriteLine("City {0}:", i + 1);
                    Console.WriteLine("Name: {0}",
                                      cities[i].name);
                    Console.WriteLine("Population: {0}",
                                      cities[i].population);
                }
                break;

            case 3:     // Edit a city
                Console.WriteLine("Which city do you want to edit?");
                int  cityToEdit = Convert.ToInt32(Console.ReadLine()) - 1;
                City cityData   = cities[cityToEdit];

                Console.Write("Enter name of city (it was {0}): ",
                              cityData.name);
                string newName = Console.ReadLine();
                if (newName != "")
                {
                    cityData.name = newName;
                }

                Console.Write("Enter population of city (it was {0}): ",
                              cityData.population);
                string newPopulationAsString = Console.ReadLine();
                if (newPopulationAsString != "")
                {
                    cityData.population = Convert.ToInt32(
                        newPopulationAsString);
                }

                cities[cityToEdit] = cityData;
                break;

            case 4:     // Search in cities
                Console.WriteLine("Which text do you want to find?");
                string search = Console.ReadLine().ToUpper();
                for (int i = 0; i < cities.Count; i++)
                {
                    if (cities[i].name.ToUpper().Contains(search))
                    {
                        Console.WriteLine("City {0}:", i + 1);
                        Console.WriteLine("Name: {0}",
                                          cities[i].name);
                        Console.WriteLine("Population: {0}",
                                          cities[i].population);
                    }
                }
                break;

            case 5:      // Delete a city
                Console.Write("Enter the position of delete: ");
                int positionToDelete =
                    Convert.ToInt32(Console.ReadLine()) - 1;
                cities.RemoveAt(positionToDelete);
                break;

            case 6:       // Insert in a certain position
                Console.Write("Enter the position of insert: ");
                int positionToInsert =
                    Convert.ToInt32(Console.ReadLine()) - 1;

                City cityToInsert;
                Console.Write("Enter name of city: ");
                cityToInsert.name = Console.ReadLine();

                Console.Write("Enter population of city: ");
                cityToInsert.population = Convert.ToInt32(
                    Console.ReadLine());

                cities.Insert(positionToInsert,
                              cityToInsert);
                break;

            default:
                Console.WriteLine("Option no valid. Repeat please");
                break;
            }
        }while (option != 0);
    }
 public void DeleteCity(City city)
 {
     db.Cities.Remove(city);
     db.SaveChanges();
 }
Exemple #40
0
        public IActionResult Post([FromBody] City body)
        {
            var entity = _manager.Add(body);

            return(ResponseJson(entity));
        }
Exemple #41
0
 public City Add(City pt)
 {
     _unitOfWork.Repository <City>().Insert(pt);
     return(pt);
 }
Exemple #42
0
 public City Create(City pt)
 {
     pt.ObjectState = ObjectState.Added;
     _unitOfWork.Repository <City>().Insert(pt);
     return(pt);
 }
Exemple #43
0
        // compare to for property class
        public virtual int CompareTo(Object alpha) //virtual so that derived class Apartment can also compare units
        {
            // Always check for null
            if (alpha == null)
            {
                throw new Exception("ERROR: CompareTo argument is null.");
            }

            Property rightOp = alpha as Property;

            // Next, check if the typecast was successful or not
            if (rightOp != null)
            {
                string[] splitSting;
                string   nameStreetleft;
                string   houseNumleft;
                string   nameStreetright;
                string   houseNumright;

                // split address to find street name and number of house for both right and left objects
                //     left side
                splitSting     = StreetAddr.Split();
                houseNumleft   = splitSting[0];
                nameStreetleft = String.Join(" ", splitSting, 1, splitSting.Length - 1);
                //     right side
                splitSting      = rightOp.StreetAddr.Split();
                houseNumright   = splitSting[0];
                nameStreetright = String.Join(" ", splitSting, 1, splitSting.Length - 1);

                // compare state
                if (State.CompareTo(rightOp.State) < 0)
                {
                    return(-1);
                }
                else if (State.CompareTo(rightOp.State) > 0)
                {
                    return(1);
                }
                // compare city
                else if (City.CompareTo(rightOp.City) < 0)
                {
                    return(-1);
                }
                else if (City.CompareTo(rightOp.City) > 0)
                {
                    return(1);
                }
                // compare street name
                else if (nameStreetleft.CompareTo(nameStreetright) < 0)
                {
                    return(-1);
                }
                else if (nameStreetleft.CompareTo(nameStreetright) > 0)
                {
                    return(1);
                }
                // compare street house number
                else if (houseNumleft.CompareTo(houseNumright) < 0)
                {
                    return(-1);
                }
                else if (houseNumleft.CompareTo(houseNumright) > 0)
                {
                    return(1);
                }
                else if (this is House)
                {
                    // ensoure there are no duplicate house addresses that have diffrent amount of floors
                    return(0);
                }
                else
                {
                    return(1);
                }
                // compare subclasses next
            }
            // else they are not a Property object
            else
            {
                throw new Exception("ERROR: Property object compared to non-Property object.");
            }
        }
        public async Task <CurrentBuilding> InsertCurrentBuilding(CurrentBuilding currentBuilding, City city)
        {
            _dbContext.CurrentBuildings.Add(currentBuilding);
            city.CurrentBuilding = currentBuilding;
            await _dbContext.SaveChangesAsync();

            return(currentBuilding);
        }
Exemple #45
0
    void FixedUpdate()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            userPaused = !userPaused;
        }

        if (userPaused)
        {
            return;
        }

        //CalcBorderStuff();


        civilizaitons.CopyTo(civsCopy, 0);
        foreach (Civilization civ in civsCopy)
        {
            if (civ == null)
            {
                continue;                          // skip empty civs;
            }
            Profiler.BeginSample("City Expansion");
            foreach (City city in civ.Cities)
            {
                if (Random.value > 0.2f)
                {
                    continue;
                }

                HexRef xref;
                int    maxDistance = Mathf.CeilToInt(Mathf.Pow(Random.value, 3) * 2.99f);
                maxDistance = Mathf.Max(maxDistance, 1);
                bool foundTile = TryGetNewCityTileLocation(city, out xref, maxDistance);
                if (foundTile)
                {
                    float tileValue = CalcCityTileValue(xref, city);
                    if (tileValue > tileValueTreshold)
                    {
                        SetOwnership(xref.Index, civ.civID);
                    }
                }
            }            // end for each city
            Profiler.EndSample();
            //Conquest
            if (Random.value < 0.005f)
            {
                Profiler.BeginSample("Conquest");
                int roffset = Random.Range(0, civ.Cities.Count);
                for (int i = 0; i < civ.Cities.Count; i++)
                {
                    City sourceCity = civ.Cities[(i + roffset) % civ.Cities.Count];
                    int  dist;
                    City targetCity = GetNearestCityWithCondition(sourceCity.Hex, out dist, o => o.ownerID != civ.civID);
                    if (dist <= 6)
                    {
                        Civilization targetCiv = GetCiv(targetCity.ownerID);
                        Debug.LogFormat(" {0} captured {1} from {2}", civ.name, targetCity.name, GetCiv(targetCity.ownerID));

                        if (targetCiv == null)
                        {
                            Debug.Log("OwnerID: " + targetCity.ownerID);
                            Debug.LogFormat(" {0} captured {1} from {2}", civ.civIndex, targetCity.name, GetCiv(targetCity.ownerID).civIndex);

                            Debug.LogError("Target City's Civ is Null");
                            break;
                        }

                        CaptureCity(targetCity, civ);
                        break;
                    }
                }
                Profiler.EndSample();
            }

            // ChanceForRebellion
            else if (CanSpawnNewCivs() && civ.Cities.Count >= 6 && Random.value < 0.004f)
            {
                Profiler.BeginSample("Rebellion");
                City rebelCity = civ.Cities[Random.Range(1, civ.Cities.Count - 1)];
                Debug.LogFormat("Rebellion at {0}!", rebelCity.name);
                Civilization newCiv = StartNewCiv(rebelCity);
                TransferCityTerritory(rebelCity, newCiv, civ);
                Profiler.EndSample();
            }

            else if (civ.Cities.Count < maxCitiesPerCiv && Random.value < 0.005f)            // spawn new city
            {
                Profiler.BeginSample("Spawning Civs");
                HexRef xref;
                bool   foundCityLocation = TryGetNewCityLocation(civ, out xref);
                if (foundCityLocation)                // if true cell is valid
                {
                    float cityValue = CalcCityValue(xref);
                    if (cityValue > cityValueTreshold)
                    {
                        City newCity = spawnCity(xref);
                        civ.AddCity(newCity);
                    }
                }
                Profiler.EndSample();
            }
        }

        // Spawn New Civ

        if (CanSpawnNewCivs() && Random.value < 0.0003f)
        {
            SpawnCivs(1, 20);
        }

        // remove dead civilizations
        RemoveDeadCivs();

//		if(Input.GetMouseButtonUp(0))
//		{
//			Hex mouseHex = gameGrid.MouseHex();
//			Hex[] circle = Hex.HexCircle(mouseHex,3);
//			circle = gameGrid.ValidHexes(circle);
//			foreach(Hex h in circle)
//			{
//				int index = gameGrid.HexToIndex(h);
//				SetOwnership(index, 5);
//			}
//		}
    }     // end fixed Update
Exemple #46
0
    public void CaptureCity(City city, Civilization newOwner)
    {
        Civilization oldOwner = GetCiv(city.ownerID);

        CaptureCity(city, newOwner, oldOwner);
    }
        public ActionResult Results()
        {
            List <City> newCities = City.GetAllCities();

            return(View(newCities));
        }
Exemple #48
0
 public void CaptureCity(City city, Civilization newOwner, Civilization oldOwner)
 {
     newOwner.AddCity(city);
     TransferCityTerritory(city, newOwner, oldOwner);
 }
Exemple #49
0
        public async Task <ActionResult> Import()
        {
            var path = Path.Combine(
                _env.ContentRootPath,
                String.Format("Data/Source/worldcities.xlsx"));

            using (var stream = new FileStream(
                       path,
                       FileMode.Open,
                       FileAccess.Read))
            {
                using (var ep = new ExcelPackage(stream))
                {
                    // get the first worksheet

                    var ws = ep.Workbook.Worksheets[0];

                    // initialize the record counters
                    var nCountries = 0;
                    var nCities    = 0;

                    #region Import all Countries
                    // create a list containing all the countries already existing
                    // into the Database (it will be empty on first run).
                    var lstCountries = _context.Countries.ToList();

                    // iterates through all rows, skipping the first one
                    for (int nRow = 2;
                         nRow <= ws.Dimension.End.Row;
                         nRow++)
                    {
                        var row  = ws.Cells[nRow, 1, nRow, ws.Dimension.End.Column];
                        var name = row[nRow, 5].GetValue <string>();

                        // Did we already created a country with that name?
                        if (lstCountries.Where(c => c.Name == name).Count() == 0)
                        {
                            // create the Country entity and fill it with xlsx data
                            var country = new Country();
                            country.Name = name;
                            country.ISO2 = row[nRow, 6].GetValue <string>();
                            country.ISO3 = row[nRow, 7].GetValue <string>();

                            // save it into the Database
                            _context.Countries.Add(country);
                            await _context.SaveChangesAsync();

                            // store the country to retrieve its Id later on
                            lstCountries.Add(country);

                            // increment the counter
                            nCountries++;
                        }
                    }

                    #endregion

                    #region Import all Cities
                    // iterates through all rows, skipping the first one
                    for (int nRow = 2;
                         nRow <= ws.Dimension.End.Row;
                         nRow++)
                    {
                        var row = ws.Cells[nRow, 1, nRow, ws.Dimension.End.Column];

                        // create the City entity and fill it with xlsx data
                        var city = new City();
                        city.Name       = row[nRow, 1].GetValue <string>();
                        city.Name_ASCII = row[nRow, 2].GetValue <string>();
                        city.Lat        = row[nRow, 3].GetValue <decimal>();
                        city.Lon        = row[nRow, 4].GetValue <decimal>();

                        // retrieve CountryId
                        var countryName = row[nRow, 5].GetValue <string>();
                        var country     = lstCountries.Where(c => c.Name == countryName)
                                          .FirstOrDefault();
                        city.CountryId = country.Id;

                        // save the city into the Database
                        _context.Cities.Add(city);
                        await _context.SaveChangesAsync();

                        // increment the counter
                        nCities++;
                    }
                    #endregion

                    return(new JsonResult(new {
                        Cities = nCities,
                        Countries = nCountries
                    }));
                }
            }
        }
Exemple #50
0
 // Use this for initialization
 void Start()
 {
     city = GetComponent <City>();
 }
        private void BindAllComboBoxes()
        {
            try
            {
                //countries combobox
                countryList = countryRepo.GetAll().ToList();

                Utilities.Validation.BindComboBox(cmbCountryOnState, countryList, "Name", "Id", true);
                Utilities.Validation.BindComboBox(cmbCountryOnDistrict, countryList, "Name", "Id", true);
                Utilities.Validation.BindComboBox(cmbCountryOnCity, countryList, "Name", "Id", true);
                Utilities.Validation.BindComboBox(cmbCountryOnArea, countryList, "Name", "Id", true);
                Utilities.Validation.BindComboBox(cmbCountryOnSociety, countryList, "Name", "Id", true);

                country = countryList.SingleOrDefault(c => c.IsSelected == true);

                if (country != null)
                {
                    cmbCountryOnState.SelectedValue    = country.Id;
                    cmbCountryOnDistrict.SelectedValue = country.Id;
                    cmbCountryOnCity.SelectedValue     = country.Id;
                    cmbCountryOnArea.SelectedValue     = country.Id;
                    cmbCountryOnSociety.SelectedValue  = country.Id;

                    //state combobox
                    stateList = stateRepo.GetAll().Where(s => s.CountryId == country.Id).ToList();

                    Utilities.Validation.BindComboBox(cmbStateOnDistrict, stateList, "Name", "Id", true);
                    Utilities.Validation.BindComboBox(cmbStateOnCity, stateList, "Name", "Id", true);
                    Utilities.Validation.BindComboBox(cmbStateOnArea, stateList, "Name", "Id", true);
                    Utilities.Validation.BindComboBox(cmbStateOnSociety, stateList, "Name", "Id", true);

                    state = stateList.SingleOrDefault(s => s.IsSelected == true);

                    if (state != null)
                    {
                        cmbStateOnDistrict.SelectedValue = state.Id;
                        cmbStateOnCity.SelectedValue     = state.Id;
                        cmbStateOnArea.SelectedValue     = state.Id;
                        cmbStateOnSociety.SelectedValue  = state.Id;

                        //district combobox
                        districtList = districtRepo.GetAll().Where(s => s.StateId == state.Id).ToList();

                        Utilities.Validation.BindComboBox(cmbDistrictOnCity, districtList, "Name", "Id", true);
                        Utilities.Validation.BindComboBox(cmbDistrictOnArea, districtList, "Name", "Id", true);
                        Utilities.Validation.BindComboBox(cmbDistrictOnSociety, districtList, "Name", "Id", true);

                        district = districtList.SingleOrDefault(s => s.IsSelected == true);

                        if (district != null)
                        {
                            cmbDistrictOnCity.SelectedValue    = district.Id;
                            cmbDistrictOnArea.SelectedValue    = district.Id;
                            cmbDistrictOnSociety.SelectedValue = district.Id;

                            //city combobox
                            cityList = cityRepo.GetAll().Where(d => d.DistrictId == district.Id).ToList();

                            Utilities.Validation.BindComboBox(cmbCityOnArea, cityList, "Name", "Id", true);
                            Utilities.Validation.BindComboBox(cmbCityOnSociety, cityList, "Name", "Id", true);

                            city = cityList.SingleOrDefault(c => c.IsSelected == true);

                            if (city != null)
                            {
                                cmbCityOnArea.SelectedValue    = city.Id;
                                cmbCityOnSociety.SelectedValue = city.Id;

                                //area combobox
                                areaList = areaRepo.GetAll().Where(c => c.CityId == city.Id).ToList();

                                Utilities.Validation.BindComboBox(cmbAreaOnSociety, areaList, "Name", "Id", true);

                                area = areaList.SingleOrDefault(a => a.IsSelected == true);

                                if (area != null)
                                {
                                    cmbAreaOnSociety.SelectedValue = area.Id;
                                }
                            }
                        }
                    }
                }
                Utilities.Validation.BindComboBox(cmbCategory, categoryRepo.GetAll(), "Name", "Id", true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #52
0
 public void Dispose()
 {
     City.DeleteAll();
 }
    public void GenerateCity()
    {
        // use our seed for generation
        Random.State currentRNGState = Random.state;
        Random.InitState(citySeed);

        myCity                 = new City();
        myCity.thisCity        = new GameObject("NewCity");
        myCity.cityNoiseOffset = new Vector2(Random.Range(-10000, 10000), Random.Range(-10000, 10000));

        GK.VoronoiDiagram cityDiagram = new GK.VoronoiDiagram();
        //generate points
        List <Vector2> points = CreateCityPoint(myCity.cityNoiseOffset);// calulate voroni fracture sites

        //calculate city
        cityDiagram = new GK.VoronoiCalculator().CalculateDiagram(points);//calculate vorino diagram (ie roads seperating suburbs) using out sites

        //bounding
        List <Vector2> Polygon = new List <Vector2>();

        Polygon.Add(new Vector2(0, 0));
        Polygon.Add(new Vector2(citySize.x, 0));
        Polygon.Add(new Vector2(citySize.x, citySize.y));
        Polygon.Add(new Vector2(0, citySize.y));


        List <Vector2> clippedSite = new List <Vector2>();

        for (int siteIndex = 0; siteIndex < cityDiagram.Sites.Count; siteIndex++)
        {
            new GK.VoronoiClipper().ClipSite(cityDiagram, Polygon, siteIndex, ref clippedSite);// clip each of our suburbs

            if (clippedSite.Count > 0)
            {
                // assign and create a suburb object

                Suburb newSuburb = new Suburb();
                myCity.suburbs.Add(newSuburb);

                newSuburb.thisSuburb   = new GameObject("Suburb");
                newSuburb.sitePosition = cityDiagram.Sites[siteIndex];
                newSuburb.thisSuburb.transform.position = new Vector3(newSuburb.sitePosition.x, 0, newSuburb.sitePosition.y);
                newSuburb.thisSuburb.transform.SetParent(myCity.thisCity.transform);
                newSuburb.borders = new List <Vector2>(clippedSite);

                float xCoord     = myCity.cityNoiseOffset.x + newSuburb.sitePosition.x / citySize.x * noiseScale;
                float yCoord     = myCity.cityNoiseOffset.x + newSuburb.sitePosition.y / citySize.y * noiseScale;
                float noiseValue = curve.Evaluate(Mathf.PerlinNoise(xCoord, yCoord));
                for (int i = 0; i < curve.keys.Length; i++)//set which type of suburb will be generated bassed off our noise weight at the suburbs position
                {
                    if (noiseValue == curve.keys[i].value)
                    {
                        switch (i)
                        {
                        case 0:
                        {
                            newSuburb.suburbType = residentialSettings;
                            break;
                        }

                        case 1:
                        {
                            newSuburb.suburbType = urbanSettings;
                            break;
                        }

                        default:
                        {
                            newSuburb.suburbType = citySettings;
                            break;
                        }
                        }
                    }
                }

                newSuburb.seed = Random.Range(int.MinValue, int.MaxValue);
            }
        }
        Random.state = currentRNGState;
    }
Exemple #54
0
        public IActionResult Put([FromBody] City body)
        {
            var entity = _manager.Update(body);

            return(ResponseJson(_manager.Update(entity)));
        }
Exemple #55
0
 public void Delete(City pt)
 {
     _unitOfWork.Repository <City>().Delete(pt);
 }
Exemple #56
0
        public void Sample()
        {
            using (var store = NewDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    #region lazy_operations_querying_1
                    IEnumerable <User> users = session
                                               .Query <User>()
                                               .Where(x => x.Name == "john");

                    #endregion
                }

                using (var session = store.OpenSession())
                {
                    #region lazy_operations_querying_2
                    Lazy <IEnumerable <User> > lazyUsers = session
                                                           .Query <User>()
                                                           .Where(x => x.Name == "John")
                                                           .Lazily();

                    #endregion

                    #region lazy_operations_querying_3
                    IEnumerable <User> users = lazyUsers.Value;

                    #endregion
                }

                using (var session = store.OpenSession())
                {
                    #region lazy_operations_querying_4
                    IEnumerable <User> users  = null;
                    IEnumerable <City> cities = null;

                    session
                    .Query <User>()
                    .Where(x => x.Name == "John")
                    .Lazily(x => users = x);

                    session
                    .Query <City>()
                    .Where(x => x.Name == "New York")
                    .Lazily(x => cities = x);

                    session.Advanced.Eagerly.ExecuteAllPendingLazyOperations();

                    #endregion
                }

                using (var session = store.OpenSession())
                {
                    #region lazy_operations_querying_5
                    Lazy <IEnumerable <User> > users = session.Advanced
                                                       .LuceneQuery <User>()
                                                       .WhereEquals("Name", "John")
                                                       .Lazily();

                    #endregion
                }

                using (var session = store.OpenSession())
                {
                    #region lazy_operations_loading_1
                    User user = session.Load <User>("users/1");

                    #endregion
                }

                using (var session = store.OpenSession())
                {
                    #region lazy_operations_loading_2
                    Lazy <User> lazyUser = session.Advanced.Lazily.Load <User>("users/1");

                    #endregion

                    #region lazy_operations_loading_3
                    User user = lazyUser.Value;

                    #endregion
                }

                using (var session = store.OpenSession())
                {
                    #region lazy_operations_loading_4
                    User user = null;

                    session.Advanced.Lazily.Load <User>("users/1", x => user = x);
                    session.Advanced.Eagerly.ExecuteAllPendingLazyOperations();

                    #endregion
                }

                using (var session = store.OpenSession())
                {
                    #region lazy_operations_loading_5
                    var users = session.Advanced.Lazily.LoadStartingWith <User>("users/1");

                    #endregion
                }

                #region lazy_operations_loading_7
                using (var session = store.OpenSession())
                {
                    var user = new User
                    {
                        Id     = "users/1",
                        Name   = "John",
                        CityId = "cities/1"
                    };

                    var city = new City
                    {
                        Id   = "cities/1",
                        Name = "New York"
                    };

                    session.Store(user);
                    session.Store(city);
                    session.SaveChanges();
                }

                #endregion

                using (var session = store.OpenSession())
                {
                    #region lazy_operations_loading_8
                    var lazyUser = session.Advanced.Lazily
                                   .Include("CityId")
                                   .Load <User>("users/1");

                    var user         = lazyUser.Value;
                    var isCityLoaded = session.Advanced.IsLoaded("cities/1");                     // will be true

                    #endregion
                }

                using (var session = store.OpenSession())
                {
                    #region lazy_operations_facets_1
                    Lazy <FacetResults> lazyFacetResults = session
                                                           .Query <Camera>("CameraCost")
                                                           .Where(x => x.Cost >= 100 && x.Cost <= 300)
                                                           .ToFacetsLazy("facets/CameraFacets");

                    FacetResults facetResults = lazyFacetResults.Value;

                    #endregion
                }

                using (var session = store.OpenSession())
                {
                    #region lazy_operations_suggest_1
                    Lazy <SuggestionQueryResult> lazySuggestionResult = session
                                                                        .Query <User>()
                                                                        .Where(x => x.Name == "John")
                                                                        .SuggestLazy();

                    SuggestionQueryResult suggestionResult = lazySuggestionResult.Value;

                    #endregion
                }
            }
        }
        public static void Access(Parahuman parahuman)
        {
            Console.Clear();
            String welcomeText = "You are accessing the editor for " + parahuman.name + ".\n";

            Console.WriteLine(welcomeText);
            String input;

            String[] keys;

            while (true)
            {
                Console.Write("> ");
                input = Console.ReadLine();
                keys  = input.Split(' ');

                switch (keys[0].ToLower())
                {
                case "printall":
                    parahuman.Query();
                    break;

                case "rename":
                    if (keys.Length >= 2)
                    {
                        if (keys.Length >= 3 && keys[1] == "civilian")
                        {
                            parahuman.civilian_name = LanguageTools.GetWordsStarting(keys, 2);
                            Console.WriteLine(LanguageTools.Possessive(parahuman.name) + " civilian name is now " + parahuman.civilian_name + ".\n");
                            break;
                        }
                        else
                        {
                            parahuman.name = LanguageTools.GetWordsStarting(keys, 1);
                            Console.WriteLine(LanguageTools.Possessive(parahuman.civilian_name) + " cape name is now " + parahuman.name + ".\n");
                            break;
                        }
                    }
                    ConsoleTools.PrintInvalidSyntax();
                    break;

                case "health":
                    if (keys.Length == 2)
                    {
                        if (Enum.TryParse(keys[1], true, out Health health))
                        {
                            parahuman.health = health;
                            Console.WriteLine(LanguageTools.Possessive(parahuman.name) + " state of health is now " + parahuman.health.ToString().ToLower() + ".\n");
                            break;
                        }
                        if (int.TryParse(keys[1], out int healthint))
                        {
                            parahuman.health = (Health)healthint;
                            Console.WriteLine(LanguageTools.Possessive(parahuman.name) + " state of health is now " + parahuman.health.ToString().ToLower() + ".\n");
                            break;
                        }
                        Console.WriteLine("\"" + keys[1] + "\" is not a valid health setting.\nOptions: Deceased, Down, Injured, Healthy OR 0, 1, 2, 3.\n");
                        break;
                    }
                    ConsoleTools.PrintInvalidSyntax();
                    break;

                case "alignment":
                    if (keys.Length == 1)
                    {
                        parahuman.alignment = ConsoleTools.RequestAlignment("> Enter new alignment: ");
                    }
                    ConsoleTools.PrintInvalidSyntax();
                    break;

                case "pid":
                    if (keys.Length == 1)
                    {
                        parahuman.ID = ConsoleTools.RequestInt("> Enter new PID: ");
                    }
                    ConsoleTools.PrintInvalidSyntax();
                    break;

                case "threshold":

                    if (keys.Length == 2)
                    {
                        if (Enum.TryParse(keys[1], out Threat threshold))
                        {
                            parahuman.reveal_threshold = threshold;
                            Console.WriteLine(LanguageTools.Possessive(parahuman.name) + " escalation threshold has been set to " + threshold + ".\n");
                            break;
                        }
                        else
                        {
                            Console.WriteLine("\"" + keys[1] + "\" is not a valid escalation threshold. It must be an integer from 0-4 (inclusive).\n");
                            break;
                        }
                    }
                    ConsoleTools.PrintInvalidSyntax();
                    break;

                case "set":
                    if (keys.Length % 2 == 1)
                    {
                        Rating parentRating = null;
                        bool   writesub     = false;
                        if (keys[1] == "subrating")
                        {
                            if (!Enum.TryParse(keys[2], true, out Classification parentClssf))
                            {
                                Console.WriteLine("\"" + keys[2] + "\" is not a valid rating wrapper.\nOptions: Master, Breaker, Tinker.\n");
                                break;
                            }
                            if (parentClssf != Classification.Master && parentClssf != Classification.Breaker && parentClssf != Classification.Tinker)
                            {
                                Console.WriteLine("\"" + keys[2] + "\" is not a valid rating wrapper.\nOptions: Master, Breaker, Tinker.\n");
                                break;
                            }
                            parentRating = parahuman.ratings.Find(rat => rat.clssf == parentClssf);
                            if (parentRating == null)
                            {
                                Console.WriteLine(parahuman.name + "does not have a " + keys[2] + "rating.\n");
                                break;
                            }
                            writesub = true;
                        }
                        for (int i = (writesub ? 3 : 1); i < keys.Length; i += 2)
                        {
                            if (!Enum.TryParse(keys[i], true, out Classification clssf))
                            {
                                PrintInvalidWrapper(keys[i]);
                                break;
                            }
                            if (!int.TryParse(keys[i + 1], out int num))
                            {
                                Console.WriteLine("\"" + keys[i + 1] + "\" is not an integer.");
                                break;
                            }
                            if (num < 0 || num > 12)
                            {
                                Console.WriteLine("Requested " + clssf.ToString() + " rating number out of range. Must be within 0-12 (inclusive).");
                                break;
                            }
                            if (writesub)                                       //Write to subrating of parentRating
                            {
                                Rating subrating = parentRating.subratings.Find(rat => rat.clssf == clssf);
                                if (subrating == null)
                                {
                                    subrating = new Rating(clssf, num);
                                    parentRating.subratings.Add(new Rating(clssf, num));
                                    Console.WriteLine(parahuman.name + " has gained a " + clssf.ToString() + " subrating of " + num.ToString() + " under " + parentRating.clssf.ToString());
                                }
                                else
                                {
                                    subrating.num = num;
                                    Console.WriteLine(parahuman.name + "'s " + clssf.ToString() + " subrating (under " + parentRating.clssf.ToString() + ") has been changed to " + num.ToString());
                                }
                            }
                            else                                         //Write to rating
                            {
                                Rating rating = parahuman.ratings.Find(rat => rat.clssf == clssf);
                                if (rating == null)
                                {
                                    rating = new Rating(clssf, num);
                                    parahuman.ratings.Add(new Rating(clssf, num));
                                    Console.WriteLine(parahuman.name + " has gained a " + clssf.ToString() + " rating of " + num.ToString());
                                }
                                else
                                {
                                    rating.num = num;
                                    Console.WriteLine(LanguageTools.Possessive(parahuman.name) + " " + clssf.ToString() + " rating has been changed to " + num.ToString());
                                }
                            }
                        }
                        Console.WriteLine("");
                        break;
                    }
                    ConsoleTools.PrintInvalidSyntax();
                    break;

                case "trueform":
                    if (keys.Length >= 2)
                    {
                        String    name = LanguageTools.GetWordsStarting(keys, 1);
                        Parahuman para = City.Get <Parahuman>(name);
                        if (para == null)
                        {
                            ConsoleTools.PrintNotFound <Parahuman>(name);
                            break;
                        }
                        Console.WriteLine("");
                        para.Query();
                        Console.WriteLine("");
                        if (ConsoleTools.Confirms(LanguageTools.Possessive(parahuman.name) + " true form will be set to the above. Confirm?", true))
                        {
                            parahuman.true_form = para;
                            Console.WriteLine(LanguageTools.Possessive(parahuman.name) + " true form has been set.\n");
                            City.Delete(para);
                            para.ID = parahuman.ID;
                            break;
                        }
                        else
                        {
                            Console.WriteLine("Operation cancelled");
                            break;
                        }
                    }
                    ConsoleTools.PrintInvalidSyntax();
                    break;

                case "edit":
                    if (keys.Length == 2 && keys[1] == "trueform")
                    {
                        Access(parahuman.true_form);
                        Console.WriteLine(welcomeText);
                    }
                    break;

                case "delete":
                    if (keys.Length == 2)
                    {
                        if (keys[1] == "trueform")
                        {
                            parahuman.true_form = null;
                            Console.WriteLine("The true form of " + parahuman.name + " has been deleted.\n");
                            break;
                        }

                        int index = -1;
                        if (!Enum.TryParse(keys[1], true, out Classification clssf))
                        {
                            PrintInvalidPower(keys[1]);
                            break;
                        }
                        index = parahuman.ratings.FindIndex(rating => rating.clssf == clssf);
                        if (index == -1)
                        {
                            Console.WriteLine(parahuman.name + " does not have a " + clssf.ToString() + " rating.\n");
                            break;
                        }
                        parahuman.ratings.RemoveAt(index);
                        Console.WriteLine(LanguageTools.Possessive(parahuman.name) + " " + clssf.ToString() + " rating has been removed.\n");
                        break;
                    }
                    if (keys.Length == 3)
                    {
                        Rating parentRating;
                        int    index = -1;
                        if (!Enum.TryParse(keys[1], true, out Classification parentClssf))
                        {
                            PrintInvalidWrapper(keys[1]);
                            break;
                        }
                        if (parentClssf != Classification.Master && parentClssf != Classification.Breaker && parentClssf != Classification.Tinker)
                        {
                            PrintInvalidWrapper(keys[1]);
                            break;
                        }
                        parentRating = parahuman.ratings.Find(rat => rat.clssf == parentClssf);
                        if (parentRating == null)
                        {
                            Console.WriteLine(parahuman.name + " does not have a " + keys[1] + " rating.\n");
                            break;
                        }

                        if (!Enum.TryParse(keys[2], true, out Classification subClssf))
                        {
                            PrintInvalidPower(keys[2]);
                            break;
                        }
                        index = parentRating.subratings.FindIndex(rat => rat.clssf == subClssf);
                        if (index == -1)
                        {
                            Console.WriteLine(parahuman.name + " does not have a " + keys[2] + " subrating under " + keys[1] + ".\n");
                            break;
                        }
                        parentRating.subratings.RemoveAt(index);
                        Console.WriteLine(LanguageTools.Possessive(parahuman.name) + " " + subClssf.ToString() + " subrating under " + parentClssf.ToString() + " has been removed.\n");
                        break;
                    }
                    ConsoleTools.PrintInvalidSyntax();
                    break;

                case "exit":
                    Console.Clear();
                    return;

                default:
                    ConsoleTools.PrintInvalidCommand();
                    break;
                }
            }
        }
Exemple #58
0
 internal void TransferCity(City city)
 {
     cities.Add(city);
 }
 public bool Delete(City entity)
 {
     _db.Cities.Remove(entity);
     return(Save());
 }