public static void Main() { var db = new ApplicationDbContext(); var configuration = Configuration.Default.WithDefaultLoader(); var browsingContext = BrowsingContext.New(configuration); var url = "https://countrycode.org/"; var document = browsingContext.OpenAsync(url).Result; var countryTable = document.QuerySelectorAll("tbody tr"); foreach (var row in countryTable) { var country = new Country { Name = row.Children[0].TextContent.Trim(), CountryCode = row.Children[2].TextContent.Trim().Substring(5) }; db.Countries.Add(country); } db.SaveChanges(); }
/// <summary> /// Initializes a new instance of the <see cref="RadioWebStreamChannel"/> class. /// </summary> public RadioWebStreamChannel() { CountryCollection collection = new CountryCollection(); _country = collection.GetTunerCountryFromID(31); Name = String.Empty; Url = String.Empty; }
private static Country MaakCountry(string lijn) { try { String[] stukken = lijn.Split(new char[] { ';' }); if (stukken.Length != 16) return null; Country c = new Country() { Code = stukken[0].Trim(), Name = stukken[1].Trim(), Continent = stukken[2].Trim(), Region = stukken[3].Trim(), SurfaceArea = stukken[4].ToNDouble().Value , IndepYear= stukken[4].ToNInt() , Population = stukken[6].ToNInt().Value , LifeExpectancy = stukken[7].ToNDouble() , GNP = stukken[8].ToNDouble().Value , GNPOld = stukken[9].ToNDouble() , LocalName = stukken[10].Trim() , GovernmentForm = stukken[11].Trim() , HeadOfState = stukken[12].Trim() , Capital = stukken[13].ToNInt() , Code2 = stukken[14].Trim() }; return c; } catch (Exception ex) { return null; } }
// Update is called once per frame void Update() { if (GameManager.instance.gameState == GameVariableManager.GameState.Management) { chosenCountry = GameObject.Find ("Player").GetComponent<PlayerScript> ().country; sentMetal = chosenCountry.metalToShip + chosenCountry.metalToFE + chosenCountry.metalToOF + chosenCountry.metalToUAT + chosenCountry.metalToRN + (int)chosenCountry.metalToMilitary; sentOil = chosenCountry.oilToShip + chosenCountry.oilToFE + chosenCountry.oilToOF + chosenCountry.oilToUAT + chosenCountry.oilToRN + (int)chosenCountry.oilToMilitary; mtLabel.text = chosenCountry.metalToMilitary.ToString(); fuLabel.text = chosenCountry.oilToMilitary.ToString(); if (mtUP.hold & chosenCountry.stockMetal > 0 & sentMetal < chosenCountry.stockMetal) { chosenCountry.metalToMilitary += 1.0f; } if (mtDN.hold & chosenCountry.metalToMilitary > 0) { chosenCountry.metalToMilitary -= 1.0f; } if (fuUP.hold & chosenCountry.stockOil > 0 & sentOil < chosenCountry.stockOil) { chosenCountry.oilToMilitary += 1.0f; } if (fuDN.hold & chosenCountry.oilToMilitary > 0) { chosenCountry.oilToMilitary -= 1.0f; } } }
public void TestCreateAndGetAll() { ICountryDao countryDao = new CountryDao(_graphClient); Country country = new Country() {Name = "D"}; countryDao.Create(country); IRoutesDao routeDao = new RouteDao(_graphClient); Route route = new Route() {Name = "Route1"}; routeDao.CreateIn(country, route); IDifficultyLevelScaleDao scaleDao = new DifficultyLevelScaleDao(_graphClient); DifficultyLevelScale scale = new DifficultyLevelScale() {Name = "sächsisch"}; scaleDao.Create(scale); IDifficultyLevelDao levelDao = new DifficultyLevelDao(_graphClient); DifficultyLevel level = new DifficultyLevel() {Name = "7b"}; levelDao.Create(scale, level); IVariationDao variationDao = new VariationDao(_graphClient); Variation variation = new Variation() {Name = "Ein Weg der Route1 als 7b"}; Variation created = variationDao.Create(variation, route, level); IList<Variation> variationsOnRoute = variationDao.GetAllOn(route); Assert.AreEqual(1, variationsOnRoute.Count); Assert.AreEqual(variation.Name, variationsOnRoute.First().Name); Assert.AreEqual(variation.Id, variationsOnRoute.First().Id); Assert.AreEqual(created.Id, variationsOnRoute.First().Id); }
internal static Country createCoutryFromDALCoutry(CarpoolingDAL.Coutry co) { Country nc = new Country(); nc.Id = co.idCoutry; nc.Name = co.name; return nc; }
private SCountry(HttpContextBase context, Country country, Culture culture = Culture.En) { Id = country.Id; Name = country.GetName(culture); Image = DefineImagePath(context, country.Image); Rating = country.Rating; }
public bool is_satisfied_by(Quantity item_quantity, Country country) { if (item_quantity.contains_more_than(quantity_threshold)) return false; else return true; }
public void GoToCheckout_UpdatesCountry() { var country = new Country{ Id = 5 }; basketController.GoToCheckout(country); basketService.GetCurrentBasketForCurrentUser().Country.ShouldBeTheSameAs(country); }
public List<Question> GetAll(Category category , int count , Country country) { string catId = "Agreeableness_us"; if (string.IsNullOrEmpty(catId)) throw new ArgumentNullException(); switch (country) { case Country.us: catId = category + "_" + country.ToString(); break; default: break; } var ques = qctx.GetAllForPartition(catId); var posQues = ques.Where(q => q.IsPositive == true).Take(count/2); var posNeg = ques.Where(q => q.IsPositive == false).Take(count / 2); List<Question> questions = new List<Question>(); questions.AddRange(posQues); questions.AddRange(posNeg); return questions; }
protected void Page_Load (object sender, EventArgs e) { if (_authority.HasPermission(Permission.CanEditMemberships, Organization.PPFIid, Geography.FinlandId, Authorization.Flag.ExactGeographyExactOrganization)) { loadCntry = Country.FromCode("FI"); geotree = loadCntry.Geography.GetTree(); nowValue = DateTime.Now; if (!IsPostBack) { foreach (Organization org in Organizations.GetAll()) { if (org.DefaultCountryId == loadCntry.Identity) { DropDownListOrgs.Items.Add(new ListItem(org.Name, "" + org.Identity)); } } } else { currentOrg = Organization.FromIdentity(Convert.ToInt32(DropDownListOrgs.SelectedValue)); } } else { Response.Write("Access not allowed"); Response.End(); } }
private void AppendCountry(Country? country) { if (country.HasValue && country.Value != Country.Undefined) { this.builder.AppendFormat("&cr={0}", this.location.GetCountry(country.Value)); } }
public AbstractYahooMarketServer(Country country) { this.country = country; this.stockServer = getStockServer(country); /* Hack on Malaysia Market! The format among Yahoo and CIMB are difference. */ if (country == Country.Malaysia) { List<Index> tmp = new List<Index>(); foreach (Index index in Utils.getStockIndices(country)) { if (IndexHelper.Instance().GetIndexCode(index).toString().StartsWith("^")) { tmp.Add(index); } } this.indicies = tmp; } else { this.indicies = Utils.getStockIndices(country); } if (this.indicies.Count == 0) { throw new ArgumentException(country.ToString()); } foreach (Index index in indicies) { Code curCode = IndexHelper.Instance().GetIndexCode(index); codes.Add(curCode); codeToIndexMap.Add(curCode, index); } }
public HttpResponseMessage add(Country post, Int32 languageId = 0) { // Check for errors if (post == null) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null"); } else if (Language.MasterPostExists(languageId) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The language does not exist"); } // Make sure that the data is valid post.country_code = AnnytabDataValidation.TruncateString(post.country_code, 2); post.name = AnnytabDataValidation.TruncateString(post.name, 50); // Add the post Int64 insertId = Country.AddMasterPost(post); post.id = Convert.ToInt32(insertId); Country.AddLanguagePost(post, languageId); // Return the success response return Request.CreateResponse<string>(HttpStatusCode.OK, "The post has been added"); } // End of the add method
public HttpResponseMessage update(Country post, Int32 languageId = 0) { // Check for errors if (post == null) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null"); } else if (Language.MasterPostExists(languageId) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The language does not exist"); } // Make sure that the data is valid post.country_code = AnnytabDataValidation.TruncateString(post.country_code, 2); post.name = AnnytabDataValidation.TruncateString(post.name, 50); // Get the saved post Country savedPost = Country.GetOneById(post.id, languageId); // Check if the post exists if(savedPost == null) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The record does not exist"); } // Update the post Country.UpdateMasterPost(post); Country.UpdateLanguagePost(post, languageId); // Return the success response return Request.CreateResponse<string>(HttpStatusCode.OK, "The update was successful"); } // End of the update method
public static void Run() { Country country = new Country(); /// the get_Cities property has been removed. /// Client has to use Iterator. for (IIterator it = country.CreateIterator() ; !it.IsDone ; it.Next()) { Console.Write(it.CurrentItem as string + ", "); } /// This demonstrates the abililty to create many iterators /// and to iterate on them simultaniously IIterator it1 = country.CreateIterator(); IIterator it2 = country.CreateIterator(); it1.Next(); it1.Next(); Console.WriteLine(it1.CurrentItem + Environment.NewLine); Console.WriteLine("Two simultaneous iterations:"); while (it1.Next() && it2.Next()) { Console.Write("[" + it1.CurrentItem + "]" + " " + it2.CurrentItem + " "); } }
public void CanAddCountriesToCollection() { var c = new Country("MEE"); var collection = new CountryCollection(); collection.Add(c); Assert.That(collection.Count(), Is.EqualTo(1)); }
public ScenarioPassengerDemand(double factor, DateTime enddate, Country country, Airport airport) { this.Country = country; this.Factor = factor; this.EndDate = enddate; this.Airport = airport; }
// return the "true" strength of a territory including incoming transfers private int adjustedStrength(Country c, int attackBias) { int strength = c.getStrength(); int attackers = attackBias; int transfers = 0; foreach (Movement m in gScreen.movements) { if (m.dest == c) { if (m.origin.getOwner() == this) transfers++; else attackers++; } if (m.origin == c) attackers++; } // only count incoming transfers if there are more of them than outgoing transfers if (transfers >= attackers && transfers >= 0) { foreach (Movement m in gScreen.movements) { if (m.dest == c && m.origin.getOwner() == this) strength += m.origin.getStrength() - 1; } } return strength; }
/// <summary> /// Determines whether the country instance is equal to the specified other country instance. /// </summary> /// <param name="country">The country instance.</param> /// <param name="other">The other country instance to be compared to.</param> /// <returns>True, if both countries are equal; otherwise, false.</returns> public static bool IsEqualTo(this Country? country, Country? other) { if(country == null) return other == null; return other != null && country.Value.IsEqualTo(other.Value); }
public static void should_return_country() { //arrange Team team2 = null; UnitOfWork.Do(uow => { var country1 = new Country { Name = "USA", Language = "English" }; uow.Repo<Country>().Insert(country1); var country2 = new Country { Name = "Mexico", Language = "Spanish" }; uow.Repo<Country>().Insert(country2); Team team1 = new Team() { Name = "Super", Description = "SuperBg", Country = country1 }; uow.Repo<Team>().Insert(team1); team2 = new Team() { Name = "Awesome", Description = "AwesomeBg", Country = country2 }; uow.Repo<Team>().Insert(team2); }); UnitOfWork.Do(uow => { //act var result = uow.Repo<Team>().AsQueryable().Include(t => t.Country).First(t => t.Country.Name == "Mexico"); //assert result.Id.Should().Be(team2.Id); result.Name.Should().Be("Awesome"); result.Description.Should().Be("AwesomeBg"); result.Country.Name.Should().Be("Mexico"); }); }
public static Country GetCountryByID(int id) { Country country = new Country(); SqlCountryProvider sqlCountryProvider = new SqlCountryProvider(); country = sqlCountryProvider.GetCountryByID(id); return country; }
public Country GetCountry() { Country country = new Country(); int id = Convert.ToInt32(ConfigurationManager.AppSettings["CountryId"]); OleDbConnection connection = new OleDbConnection(DatabaseData.Instance.AccessConnectionString); using (connection) { connection.Open(); OleDbCommand command = new OleDbCommand(@"Select Country.ID, DisplayName, aspnet_Users.UserName, Country.UpdatedAt, Country.TaskForceName FROM ((Country INNER JOIN AdminLevels on Country.AdminLevelId = AdminLevels.ID) INNER JOIN aspnet_Users on Country.UpdatedById = aspnet_Users.UserId) WHERE AdminLevels.ID = @id", connection); command.Parameters.Add(new OleDbParameter("@id", id)); using (OleDbDataReader reader = command.ExecuteReader()) { if (reader.HasRows) { reader.Read(); country = new Country { Id = reader.GetValueOrDefault<int>("ID"), Name = reader.GetValueOrDefault<string>("DisplayName"), UpdatedBy = GetAuditInfoUpdate(reader), TaskForceName = reader.GetValueOrDefault<string>("TaskForceName"), }; } reader.Close(); } } return country; }
public void UpdateCountry(Country country, int byUserId) { OleDbConnection connection = new OleDbConnection(DatabaseData.Instance.AccessConnectionString); using (connection) { connection.Open(); try { OleDbCommand command = new OleDbCommand(@"Update Country set MonthYearStarts=1, UpdatedById=@updatedby, UpdatedAt=@updatedat, TaskForceName=@TaskForceName WHERE ID = @id", connection); command.Parameters.Add(new OleDbParameter("@updatedby", byUserId)); command.Parameters.Add(OleDbUtil.CreateDateTimeOleDbParameter("@updatedat", DateTime.Now)); command.Parameters.Add(new OleDbParameter("@TaskForceName", country.TaskForceName)); command.Parameters.Add(new OleDbParameter("@id", country.Id)); command.ExecuteNonQuery(); command = new OleDbCommand(@"Update AdminLevels set DisplayName=@DisplayName, UpdatedById=@updatedby, UpdatedAt=@updatedat WHERE ID = @id", connection); command.Parameters.Add(new OleDbParameter("@DisplayName", country.Name)); command.Parameters.Add(new OleDbParameter("@updatedby", byUserId)); command.Parameters.Add(OleDbUtil.CreateDateTimeOleDbParameter("@updatedat", DateTime.Now)); command.Parameters.Add(new OleDbParameter("@id", country.Id)); command.ExecuteNonQuery(); } catch (Exception) { throw; } } }
public State(Country country, string name, string shortname,Boolean overseas) { this.Country = country; this.Name = name; this.ShortName = shortname; this.IsOverseas = overseas; }
protected Country CaptureData() { Country obj = new Country(); obj.Country_ID = txtID.Text.Trim(); obj.Country_Name = txtName.Text.Trim(); return obj; }
public void GetCurrentBasket_should_throw_when_the_default_country_is_not_in_the_database() { var country = new Country { Name = "France" }; // expect the default country to be UK. countryRepository.Stub(r => r.GetAll()).Return(new[] { country }.AsQueryable()); basketService.GetCurrentBasketForCurrentUser(); }
public TransitState(Country country, CompetentAuthority competentAuthority, EntryOrExitPoint entryPoint, EntryOrExitPoint exitPoint, int ordinalPosition) { Guard.ArgumentNotNull(() => country, country); Guard.ArgumentNotNull(() => competentAuthority, competentAuthority); Guard.ArgumentNotNull(() => entryPoint, entryPoint); Guard.ArgumentNotNull(() => exitPoint, exitPoint); Guard.ArgumentNotZeroOrNegative(() => OrdinalPosition, ordinalPosition); if (country.Id != competentAuthority.Country.Id || country.Id != entryPoint.Country.Id || country.Id != exitPoint.Country.Id) { throw new InvalidOperationException(string.Format("Transit State Competent Authority, Entry and Exit Point must all have the same country. Competent Authority: {0}. Entry: {1}. Exit: {2}. Country: {3}", competentAuthority.Id, entryPoint.Id, exitPoint.Id, country.Name)); } Country = country; CompetentAuthority = competentAuthority; ExitPoint = exitPoint; EntryPoint = entryPoint; OrdinalPosition = ordinalPosition; }
partial void Countries_Inserting(Country entity) { entity.InsertDate = DateTime.Now; entity.InsertUser = Application.User.Name; entity.UpdateDate = DateTime.Now; entity.UpdateUser = Application.User.Name; }
public Product(string name, Category category, double unitPrice, Country country) { this.Name = name; this.Category = category; this.UnitPrice = unitPrice; this.Country = country; }
public Client(string name, Country country) { Name = name; Country = country; }
private async Task <List <Route> > PostKmlToDatabase(StreamReader stream, string fileName, int userId) { var body = stream.ReadToEnd(); var parser = new Parser(); parser.ParseString(body, false); var kml = parser.Root as Kml; var placeMarks = kml.Flatten().Where(e => e.GetType() == typeof(Placemark)).Select(p => (Placemark)p).ToList(); var routes = new List <Route>(); foreach (Placemark placeMark in placeMarks.Where(pl => pl.Geometry is LineString)) { var child = (LineString)placeMark.Flatten().Single(e => e.GetType() == typeof(LineString)); var coordinates = child.Coordinates.Select(c => "" + c.Longitude.ToString(CultureInfo.InvariantCulture) + "," + c.Latitude.ToString(CultureInfo.InvariantCulture)).ToList(); var name = placeMark.Name; if (string.Equals(name, "Tessellated", StringComparison.OrdinalIgnoreCase)) { name = fileName; if (name.EndsWith(".kml")) { name = name.Substring(0, name.Length - 4); } } var route = new Route { Coordinates = string.Join('\n', coordinates), Name = name, RouteMaps = new List <RouteMap>(), Share = Guid.NewGuid(), RouteInstances = new List <RouteInstance>() }; if (placeMark.Description != null) { route.Description = placeMark.Description.Text; } var types = await _context.RouteTypes.Where(r => r.UserId == userId).ToListAsync(); if (placeMark.ExtendedData != null) { var extendedData = placeMark.ExtendedData.Data; if (extendedData.Any(d => d.Name == "firstDateTime")) { route.RouteInstances.Add(new RouteInstance { Date = DateTime.ParseExact(extendedData.Single(d => d.Name == "firstDateTime").Value, "yyyy-MM-dd", CultureInfo.InvariantCulture) }); } if (extendedData.Any(d => d.Name == "type")) { var typeString = extendedData.Single(d => d.Name == "type").Value; var type = types.SingleOrDefault(t => string.Compare(t.Name, typeString.Trim(), true) == 0 || string.Compare(t.NameNL, typeString.Trim(), true) == 0); if (type != null) { route.RouteTypeId = type.TypeId; } else { var newRouteType = new RouteType { Colour = "#ff0000", UserId = userId, Name = typeString.Trim() }; route.RouteType = newRouteType; } } if (extendedData.Any(d => d.Name == "line")) { route.LineNumber = extendedData.Single(d => d.Name == "line").Value; } if (extendedData.Any(d => d.Name == "nameNL")) { route.NameNL = extendedData.Single(d => d.Name == "nameNL").Value; } if (extendedData.Any(d => d.Name == "descriptionNL")) { route.DescriptionNL = extendedData.Single(d => d.Name == "descriptionNL").Value; } if (extendedData.Any(d => d.Name == "color")) { route.OverrideColour = extendedData.Single(d => d.Name == "color").Value; } if (extendedData.Any(d => d.Name == "company")) { route.OperatingCompany = extendedData.Single(d => d.Name == "company").Value; } if (extendedData.Any(d => d.Name == "from")) { route.From = extendedData.Single(d => d.Name == "from").Value; } if (extendedData.Any(d => d.Name == "to")) { route.To = extendedData.Single(d => d.Name == "to").Value; } if (extendedData.Any(d => d.Name == "countries")) { route.RouteCountries = new List <RouteCountry>(); var dbCountries = await _context.Countries.Where(r => r.UserId == userId).ToListAsync(); var countries = extendedData.Single(d => d.Name == "countries").Value.Split(',').ToList(); countries.ForEach(inputCountry => { var county = dbCountries.SingleOrDefault(c => string.Compare(c.Name, inputCountry.Trim(), true) == 0 || string.Compare(c.NameNL, inputCountry.Trim(), true) == 0); if (county != null) { route.RouteCountries.Add(new RouteCountry { CountryId = county.CountryId }); } else { var newCountry = new Country { Name = inputCountry.Trim(), UserId = userId }; route.RouteCountries.Add(new RouteCountry { Country = newCountry }); } }); } if (extendedData.Any(d => d.Name == "maps")) { route.RouteMaps = new List <RouteMap>(); var dbMaps = await _context.Maps.Where(r => r.UserId == userId).ToListAsync(); var inputMaps = extendedData.Single(d => d.Name == "maps").Value.Split(',').ToList(); inputMaps.ForEach(inputMap => { var map = dbMaps.SingleOrDefault(c => string.Compare(c.Name, inputMap.Trim(), true) == 0); if (map != null) { route.RouteMaps.Add(new RouteMap { MapId = map.MapId }); } else { var newMap = new Map { Name = inputMap.Trim(), MapGuid = Guid.NewGuid(), UserId = userId, Default = false }; route.RouteMaps.Add(new RouteMap { Map = newMap }); } }); } } if (!route.RouteMaps.Any()) { var maps = await _context.Maps.Where(m => m.UserId == userId).ToListAsync(); var defaultMap = maps.Where(m => m.Default == true).FirstOrDefault(); if (defaultMap == null) { defaultMap = maps.First(); } route.RouteMaps.Add(new RouteMap { MapId = defaultMap.MapId }); } DistanceCalculationHelper.ComputeDistance(route); routes.Add(route); _context.Routes.Add(route); await _context.SaveChangesAsync(); } return(routes); }
public async Task <CreateSeatResponse> CreateFreeSeat(CreateFreeSeatRequest request, ClaimsPrincipal claim) { var response = new CreateSeatResponse(); var isAllowed = await authService.IsUserAllowedToEditConference(request.ConferenceId, claim); if (!isAllowed) { response.AddNoPermissionError(); return(response); } var conference = context.Conferences.FirstOrDefault(n => n.ConferenceId == request.ConferenceId); if (conference == null) { response.AddNotFoundError(nameof(request.ConferenceId)); } Country country = null; if (request.CountryId != -1) { country = context.Countries.FirstOrDefault(n => n.CountryId == request.CountryId); if (country == null) { response.AddNotFoundError(nameof(request.CountryId)); } } Delegation delegation = null; if (!string.IsNullOrEmpty(request.DelegationId)) { delegation = context.Delegations.FirstOrDefault(n => n.DelegationId == request.DelegationId); if (delegation == null) { response.AddNotFoundError(nameof(request.DelegationId)); } } if (response.HasError) { return(response); } var role = new ConferenceDelegateRole() { Committee = null, Conference = conference, DelegateCountry = country, DelegateType = request.Subtype, Delegation = delegation, RoleName = request.RoleName, RoleFullName = request.RoleName, Title = request.RoleName }; context.Delegates.Add(role); await context.SaveChangesAsync(); response.CreatedRoleId = role.RoleId; return(response); }
protected internal override string GetStringValue(RandomTextColumnInfo columnInfo, Country country) { int wordCount = columnInfo.WordCount > 0 ? columnInfo.WordCount : StaticRandom.Instance.Next(16); string text = RepoFactory.GetRepo <RandomText>().GetRandom().Text.Trim(); int maxLength = columnInfo.MaxLength; return(text.GetExactWordCount(wordCount, maxLength)); }
void DoSomething() { Country country1 = new Country(); Country country2 = new Country("Nepal"); }
protected override void CreateCup(Country country) { }
public static Country ToEntity(this CountryModel model, Country destination) { return(model.MapTo(destination)); }
/// <summary> /// Method for returning CSV file in sorted format. /// </summary> /// <param name="csvFilePath">Path Of CSV File.</param> /// <param name="fileHeaders">Headers Of CSV File.</param> /// <param name="sortType">Enum For knowing what type of sorting is to be done on which column.</param> /// <param name="country">Country Of Which The File Is.</param> /// <returns>Returns object of csv file in sorted format.</returns> public object GetSortedCSVDataInJsonFormat(string csvFilePath, string fileHeaders, SortBy sortType, Country country) { var censusData = this.LoadCSVFileData(csvFilePath, fileHeaders, country); List <dynamic> sortedList = SortType.SortIndianCensusData(censusData.Values.ToList(), sortType); return(JsonConvert.SerializeObject(sortedList)); }
/// <summary> /// Common MEthod For Loading CSV Files. /// </summary> /// <param name="csvFilePath">Path Of CSV File.</param> /// <param name="fileHeaders">Headers Of CSV File.</param> /// <param name="country">Country Of Which The File Is.</param> /// <returns>Loaded CSV File In Dictionary.</returns> public Dictionary <string, dynamic> LoadCSVFileData(string csvFilePath, string fileHeaders, Country country) { return(CensusAdapterFactory.LoadCsvData(csvFilePath, fileHeaders, country)); }
private void processNewOrderNotification(string xmlData) { try { NewOrderNotification newOrderNotification = (NewOrderNotification)EncodeHelper.Deserialize(xmlData, typeof(NewOrderNotification)); string googleOrderNumber = newOrderNotification.googleordernumber; XmlNode CustomerInfo = newOrderNotification.shoppingcart.merchantprivatedata.Any[0]; int CustomerID = Convert.ToInt32(CustomerInfo.Attributes["CustomerID"].Value); int CustomerLanguageID = Convert.ToInt32(CustomerInfo.Attributes["CustomerLanguageID"].Value); int CustomerCurrencyID = Convert.ToInt32(CustomerInfo.Attributes["CustomerCurrencyID"].Value); Customer customer = IoC.Resolve <ICustomerService>().GetCustomerById(CustomerID); NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCart Cart = IoC.Resolve <IShoppingCartService>().GetCustomerShoppingCart(customer.CustomerId, ShoppingCartTypeEnum.ShoppingCart); if (customer == null) { logMessage("Could not load a customer"); return; } NopContext.Current.User = customer; if (Cart.Count == 0) { logMessage("Cart is empty"); return; } //validate cart foreach (NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCartItem sci in Cart) { bool ok = false; foreach (Item item in newOrderNotification.shoppingcart.items) { if (!String.IsNullOrEmpty(item.merchantitemid)) { if ((Convert.ToInt32(item.merchantitemid) == sci.ShoppingCartItemId) && (item.quantity == sci.Quantity)) { ok = true; break; } } } if (!ok) { logMessage(string.Format("Shopping Cart item has been changed. {0}. {1}", sci.ShoppingCartItemId, sci.Quantity)); return; } } string[] billingFullname = newOrderNotification.buyerbillingaddress.contactname.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); string billingFirstName = billingFullname[0]; string billingLastName = string.Empty; if (billingFullname.Length > 1) { billingLastName = billingFullname[1]; } string billingEmail = newOrderNotification.buyerbillingaddress.email.Trim(); string billingAddress1 = newOrderNotification.buyerbillingaddress.address1.Trim(); string billingAddress2 = newOrderNotification.buyerbillingaddress.address2.Trim(); string billingPhoneNumber = newOrderNotification.buyerbillingaddress.phone.Trim(); string billingCity = newOrderNotification.buyerbillingaddress.city.Trim(); int billingStateProvinceID = 0; StateProvince billingStateProvince = IoC.Resolve <IStateProvinceService>().GetStateProvinceByAbbreviation(newOrderNotification.buyerbillingaddress.region.Trim()); if (billingStateProvince != null) { billingStateProvinceID = billingStateProvince.StateProvinceId; } string billingZipPostalCode = newOrderNotification.buyerbillingaddress.postalcode.Trim(); int billingCountryID = 0; Country billingCountry = IoC.Resolve <ICountryService>().GetCountryByTwoLetterIsoCode(newOrderNotification.buyerbillingaddress.countrycode.Trim()); if (billingCountry != null) { billingCountryID = billingCountry.CountryId; } NopSolutions.NopCommerce.BusinessLogic.CustomerManagement.Address billingAddress = customer.BillingAddresses.FindAddress( billingFirstName, billingLastName, billingPhoneNumber, billingEmail, string.Empty, string.Empty, billingAddress1, billingAddress2, billingCity, billingStateProvinceID, billingZipPostalCode, billingCountryID); if (billingAddress == null) { billingAddress = new BusinessLogic.CustomerManagement.Address() { CustomerId = CustomerID, IsBillingAddress = true, FirstName = billingFirstName, LastName = billingLastName, PhoneNumber = billingPhoneNumber, Email = billingEmail, Address1 = billingAddress1, Address2 = billingAddress2, City = billingCity, StateProvinceId = billingStateProvinceID, ZipPostalCode = billingZipPostalCode, CountryId = billingCountryID, CreatedOn = DateTime.UtcNow, UpdatedOn = DateTime.UtcNow }; IoC.Resolve <ICustomerService>().InsertAddress(billingAddress); } //set default billing address customer.BillingAddressId = billingAddress.AddressId; IoC.Resolve <ICustomerService>().UpdateCustomer(customer); NopSolutions.NopCommerce.BusinessLogic.CustomerManagement.Address shippingAddress = null; customer.LastShippingOption = null; bool shoppingCartRequiresShipping = IoC.Resolve <IShippingService>().ShoppingCartRequiresShipping(Cart); if (shoppingCartRequiresShipping) { string[] shippingFullname = newOrderNotification.buyershippingaddress.contactname.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); string shippingFirstName = shippingFullname[0]; string shippingLastName = string.Empty; if (shippingFullname.Length > 1) { shippingLastName = shippingFullname[1]; } string shippingEmail = newOrderNotification.buyershippingaddress.email.Trim(); string shippingAddress1 = newOrderNotification.buyershippingaddress.address1.Trim(); string shippingAddress2 = newOrderNotification.buyershippingaddress.address2.Trim(); string shippingPhoneNumber = newOrderNotification.buyershippingaddress.phone.Trim(); string shippingCity = newOrderNotification.buyershippingaddress.city.Trim(); int shippingStateProvinceID = 0; StateProvince shippingStateProvince = IoC.Resolve <IStateProvinceService>().GetStateProvinceByAbbreviation(newOrderNotification.buyershippingaddress.region.Trim()); if (shippingStateProvince != null) { shippingStateProvinceID = shippingStateProvince.StateProvinceId; } int shippingCountryID = 0; string shippingZipPostalCode = newOrderNotification.buyershippingaddress.postalcode.Trim(); Country shippingCountry = IoC.Resolve <ICountryService>().GetCountryByTwoLetterIsoCode(newOrderNotification.buyershippingaddress.countrycode.Trim()); if (shippingCountry != null) { shippingCountryID = shippingCountry.CountryId; } shippingAddress = customer.ShippingAddresses.FindAddress( shippingFirstName, shippingLastName, shippingPhoneNumber, shippingEmail, string.Empty, string.Empty, shippingAddress1, shippingAddress2, shippingCity, shippingStateProvinceID, shippingZipPostalCode, shippingCountryID); if (shippingAddress == null) { shippingAddress = new BusinessLogic.CustomerManagement.Address() { CustomerId = CustomerID, IsBillingAddress = false, FirstName = shippingFirstName, LastName = shippingLastName, PhoneNumber = shippingPhoneNumber, Email = shippingEmail, Address1 = shippingAddress1, Address2 = shippingAddress2, City = shippingCity, StateProvinceId = shippingStateProvinceID, ZipPostalCode = shippingZipPostalCode, CountryId = shippingCountryID, CreatedOn = DateTime.UtcNow, UpdatedOn = DateTime.UtcNow }; IoC.Resolve <ICustomerService>().InsertAddress(shippingAddress); } //set default shipping address customer.ShippingAddressId = shippingAddress.AddressId; IoC.Resolve <ICustomerService>().UpdateCustomer(customer); string shippingMethod = string.Empty; decimal shippingCost = decimal.Zero; if (newOrderNotification.orderadjustment != null && newOrderNotification.orderadjustment.shipping != null && newOrderNotification.orderadjustment.shipping.Item != null) { FlatRateShippingAdjustment ShippingMethod = (FlatRateShippingAdjustment)newOrderNotification.orderadjustment.shipping.Item; shippingMethod = ShippingMethod.shippingname; shippingCost = ShippingMethod.shippingcost.Value; ShippingOption shippingOption = new ShippingOption(); shippingOption.Name = shippingMethod; shippingOption.Rate = shippingCost; customer.LastShippingOption = shippingOption; } } //customer.LastCalculatedTax = decimal.Zero; PaymentMethod googleCheckoutPaymentMethod = IoC.Resolve <IPaymentService>().GetPaymentMethodBySystemKeyword("GoogleCheckout"); PaymentInfo paymentInfo = new PaymentInfo(); paymentInfo.PaymentMethodId = googleCheckoutPaymentMethod.PaymentMethodId; paymentInfo.BillingAddress = billingAddress; paymentInfo.ShippingAddress = shippingAddress; paymentInfo.CustomerLanguage = IoC.Resolve <ILanguageService>().GetLanguageById(CustomerLanguageID); paymentInfo.CustomerCurrency = IoC.Resolve <ICurrencyService>().GetCurrencyById(CustomerCurrencyID); paymentInfo.GoogleOrderNumber = googleOrderNumber; int orderID = 0; string result = IoC.Resolve <IOrderService>().PlaceOrder(paymentInfo, customer, out orderID); if (!String.IsNullOrEmpty(result)) { logMessage("new-order-notification received. CreateOrder() error: Order Number " + orderID + ". " + result); return; } Order order = IoC.Resolve <IOrderService>().GetOrderById(orderID); if (order != null) { logMessage("new-order-notification received and saved: Order Number " + orderID); } } catch (Exception exc) { logMessage("processNewOrderNotification Exception: " + exc.Message + ": " + exc.StackTrace); } }
public void Search_GetResultWithLanguageAndCountry(string term, Language language, Country country) { var results = this.engine.Search(new Query { Term = term, Language = language, Country = country, MaxResults = 10 }); results.Count.Should().Be.GreaterThan(0); }
public static string GetName(this Country value) => GetCountryInfoAttribute(value).Name;
public bool DeleteCountry(Country country) { _countryContext.Remove(country); return(Save()); }
public static CountryModel ToModel(this Country entity) { return(entity.MapTo <Country, CountryModel>()); }
//adds data from linked tables public void EditForDisplay(PolicyRouting policyRouting) { if (policyRouting.FromCityCode != null) { CityRepository cityRepository = new CityRepository(); City city = new City(); city = cityRepository.GetCity(policyRouting.FromCityCode); policyRouting.FromName = city.Name; } if (policyRouting.FromCountryCode != null) { CountryRepository countryRepository = new CountryRepository(); Country country = new Country(); country = countryRepository.GetCountry(policyRouting.FromCountryCode); policyRouting.FromName = country.CountryName; } if (policyRouting.FromGlobalSubRegionCode != null) { HierarchyRepository hierarchyRepository = new HierarchyRepository(); GlobalSubRegion globalSubRegion = new GlobalSubRegion(); globalSubRegion = hierarchyRepository.GetGlobalSubRegion(policyRouting.FromGlobalSubRegionCode); policyRouting.FromName = globalSubRegion.GlobalSubRegionName; } if (policyRouting.FromGlobalRegionCode != null) { HierarchyRepository hierarchyRepository = new HierarchyRepository(); GlobalRegion globalRegion = new GlobalRegion(); globalRegion = hierarchyRepository.GetGlobalRegion(policyRouting.FromGlobalRegionCode); policyRouting.FromName = globalRegion.GlobalRegionName; } if (policyRouting.FromGlobalFlag) { policyRouting.FromName = "Global"; } if (policyRouting.ToCityCode != null) { CityRepository cityRepository = new CityRepository(); City city = new City(); city = cityRepository.GetCity(policyRouting.ToCityCode); policyRouting.ToName = city.Name; } if (policyRouting.ToCountryCode != null) { CountryRepository countryRepository = new CountryRepository(); Country country = new Country(); country = countryRepository.GetCountry(policyRouting.ToCountryCode); policyRouting.ToName = country.CountryName; } if (policyRouting.ToGlobalSubRegionCode != null) { HierarchyRepository hierarchyRepository = new HierarchyRepository(); GlobalSubRegion globalSubRegion = new GlobalSubRegion(); globalSubRegion = hierarchyRepository.GetGlobalSubRegion(policyRouting.ToGlobalSubRegionCode); policyRouting.ToName = globalSubRegion.GlobalSubRegionName; } if (policyRouting.ToGlobalRegionCode != null) { HierarchyRepository hierarchyRepository = new HierarchyRepository(); GlobalRegion globalRegion = new GlobalRegion(); globalRegion = hierarchyRepository.GetGlobalRegion(policyRouting.ToGlobalRegionCode); policyRouting.ToName = globalRegion.GlobalRegionName; } if (policyRouting.ToGlobalFlag) { policyRouting.ToName = "Global"; } }
// Update is called once per frame void OnGUI() { // Do autoresizing of GUI layer GUIResizer.AutoResize(); // Check whether a country or city is selected, then show a label with the entity name and its neighbours (new in V4.1!) if (map.countryHighlighted != null || map.cityHighlighted != null || map.provinceHighlighted != null) { string text; if (map.cityHighlighted != null) { if (!map.cityHighlighted.name.Equals(map.cityHighlighted.province)) // show city name + province & country name { text = "City: " + map.cityHighlighted.name + " (" + map.cityHighlighted.province + ", " + map.countries [map.cityHighlighted.countryIndex].name + ")"; } else // show city name + country name (city is a capital with same name as province) { text = "City: " + map.cityHighlighted.name + " (" + map.countries [map.cityHighlighted.countryIndex].name + ")"; } } else if (map.provinceHighlighted != null) { text = map.provinceHighlighted.name + ", " + map.countryHighlighted.name; List <Province> neighbours = map.ProvinceNeighboursOfCurrentRegion(); if (neighbours.Count > 0) { text += "\n" + EntityListToString <Province> (neighbours); } } else if (map.countryHighlighted != null) { text = map.countryHighlighted.name + " (" + map.countryHighlighted.continent + ")"; List <Country> neighbours = map.CountryNeighboursOfCurrentRegion(); if (neighbours.Count > 0) { text += "\n" + EntityListToString <Country> (neighbours); } } else { text = ""; } float x, y; if (minimizeState) { x = Screen.width - 130; y = Screen.height - 140; } else { x = Screen.width / 2.0f; y = Screen.height - 40; } // shadow GUI.Label(new Rect(x - 1, y - 1, 0, 10), text, labelStyleShadow); GUI.Label(new Rect(x + 1, y + 2, 0, 10), text, labelStyleShadow); GUI.Label(new Rect(x + 2, y + 3, 0, 10), text, labelStyleShadow); GUI.Label(new Rect(x + 3, y + 4, 0, 10), text, labelStyleShadow); // texst face GUI.Label(new Rect(x, y, 0, 10), text, labelStyle); } // Assorted options to show/hide frontiers, cities, Earth and enable country highlighting GUI.Box(new Rect(0, 0, 150, 200), ""); map.showFrontiers = GUI.Toggle(new Rect(10, 20, 150, 30), map.showFrontiers, "Toggle Frontiers"); map.showEarth = GUI.Toggle(new Rect(10, 50, 150, 30), map.showEarth, "Toggle Earth"); map.showCities = GUI.Toggle(new Rect(10, 80, 150, 30), map.showCities, "Toggle Cities"); map.showCountryNames = GUI.Toggle(new Rect(10, 110, 150, 30), map.showCountryNames, "Toggle Labels"); map.enableCountryHighlight = GUI.Toggle(new Rect(10, 140, 170, 30), map.enableCountryHighlight, "Enable Highlight"); // buttons background color GUI.backgroundColor = new Color(0.1f, 0.1f, 0.3f, 0.95f); // Add button to toggle Earth texture if (GUI.Button(new Rect(10, 170, 160, 30), " Change Earth style", buttonStyle)) { map.earthStyle = (EARTH_STYLE)(((int)map.earthStyle + 1) % 4); } // Add buttons to show the color picker and change colors for the frontiers or fill if (GUI.Button(new Rect(10, 210, 160, 30), " Change Frontiers Color", buttonStyle)) { colorPicker.showPicker = true; changingFrontiersColor = true; } if (GUI.Button(new Rect(10, 250, 160, 30), " Change Fill Color", buttonStyle)) { colorPicker.showPicker = true; changingFrontiersColor = false; } if (colorPicker.showPicker) { if (changingFrontiersColor) { map.frontiersColor = colorPicker.setColor; } else { map.fillColor = colorPicker.setColor; } } // Add a button which demonstrates the navigateTo functionality -- pass the name of a country // For a list of countries and their names, check map.Countries collection. if (GUI.Button(new Rect(10, 290, 180, 30), " Fly to Australia (Country)", buttonStyle)) { FlyToCountry("Australia"); } if (GUI.Button(new Rect(10, 325, 180, 30), " Fly to Mexico (Country)", buttonStyle)) { FlyToCountry("Mexico"); } if (GUI.Button(new Rect(10, 360, 180, 30), " Fly to San Francisco (City)", buttonStyle)) { FlyToCity("New York", "United States of America"); } if (GUI.Button(new Rect(10, 395, 180, 30), " Fly to Madrid (City)", buttonStyle)) { FlyToCity("Madrid", "Spain"); } // Slider to show the new set zoom level API in V4.1 GUI.Button(new Rect(10, 430, 85, 30), " Zoom Level", buttonStyle); float prevZoomLevel = zoomLevel; GUI.backgroundColor = Color.white; zoomLevel = GUI.HorizontalSlider(new Rect(100, 445, 80, 85), zoomLevel, 0, 1, sliderStyle, sliderThumbStyle); GUI.backgroundColor = new Color(0.1f, 0.1f, 0.3f, 0.95f); if (zoomLevel != prevZoomLevel) { prevZoomLevel = zoomLevel; map.SetZoomLevel(zoomLevel); } // Add a button to colorize countries if (GUI.Button(new Rect(GUIResizer.authoredScreenWidth - 190, 20, 180, 30), " Colorize Europe", buttonStyle)) { for (int countryIndex = 0; countryIndex < map.countries.Length; countryIndex++) { if (map.countries [countryIndex].continent.Equals("Europe")) { Color color = new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f)); map.ToggleCountrySurface(countryIndex, true, color); } } } // Colorize random country and fly to it if (GUI.Button(new Rect(GUIResizer.authoredScreenWidth - 190, 60, 180, 30), " Colorize Random", buttonStyle)) { int countryIndex = Random.Range(0, map.countries.Length); Color color = new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f)); map.ToggleCountrySurface(countryIndex, true, color); map.BlinkCountry(countryIndex, Color.green, Color.black, 0.8f, 0.2f); } // Add a button to colorize countries if (GUI.Button(new Rect(GUIResizer.authoredScreenWidth - 190, 100, 180, 30), " Colorize Continents", buttonStyle)) { Dictionary <string, Color> continentColors = new Dictionary <string, Color>(); for (int countryIndex = 0; countryIndex < map.countries.Length; countryIndex++) { Country country = map.countries[countryIndex]; Color continentColor; if (continentColors.ContainsKey(country.continent)) { continentColor = continentColors[country.continent]; } else { continentColor = new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), 0.5f); continentColors.Add(country.continent, continentColor); } map.ToggleCountrySurface(countryIndex, true, continentColor); } } // Button to clear colorized countries if (GUI.Button(new Rect(GUIResizer.authoredScreenWidth - 190, 140, 180, 30), " Reset countries", buttonStyle)) { map.HideCountrySurfaces(); } // Tickers sample if (GUI.Button(new Rect(GUIResizer.authoredScreenWidth - 190, 180, 180, 30), " Tickers Sample", buttonStyle)) { TickerSample(); } // Decorator sample if (GUI.Button(new Rect(GUIResizer.authoredScreenWidth - 190, 220, 180, 30), " Texture Sample", buttonStyle)) { TextureSample(); } // Moving the Earth sample if (GUI.Button(new Rect(GUIResizer.authoredScreenWidth - 190, 260, 180, 30), " Toggle Minimize", buttonStyle)) { ToggleMinimize(); } // Add marker sample if (GUI.Button(new Rect(GUIResizer.authoredScreenWidth - 190, 300, 180, 30), " Add Marker", buttonStyle)) { AddMarkerOnRandomCity(); } if (GUI.Button(new Rect(GUIResizer.authoredScreenWidth - 190, 340, 180, 30), " Add Trajectories", buttonStyle)) { AddTrajectories(); } if (GUI.Button(new Rect(GUIResizer.authoredScreenWidth - 190, 380, 180, 30), " Locate Mount Point", buttonStyle)) { LocateMountPoint(); } }
private int count_nb_bytes() { /* All the ASCII strings in the VCard must be separated by 0x0D0A, which represent 2 characters */ int NbBytes = 0; NbBytes = "BEGIN:VCARD".Length + 2 + "VERSION:3.0".Length + 2; NbBytes += "FN:".Length + First_name.Length + 1 + Family_name.Length + 2; /* 1 is for "space" */ if (!Nickname.Equals("")) { NbBytes += "NICKNAME:".Length + Nickname.Length + 2; } /* Birthday with 8 characters: yyyymmdd */ DateTime dateBirthday; if ((!Birthday.Equals("")) && (DateTime.TryParse(Birthday, out dateBirthday))) { NbBytes += "BDAY:".Length + 8 + 2; } /* Home address in 6 fields, separated by a ';' */ /* The PO Box is discarded, which explains the first ';' */ if (!(Address1.Equals("")) || !(Address2.Equals("")) || !(Town.Equals("")) || !(Region_State.Equals("")) || !(Post_Code.Equals("")) || !(Country.Equals("")) ) { NbBytes += "ADR:;".Length + Address1.Length + 1 + Address2.Length + 1 + Town.Length + 1 + Region_State.Length + 1 + Post_Code.Length + 1 + Country.Length + 2; } /* Work address in 6 fields, separated by a ';' */ /* The PO Box is discarded, which explains the first ';' */ if (!(Pro_Address1.Equals("")) || !(Pro_Address2.Equals("")) || !(Pro_Town.Equals("")) || !(Pro_Region_State.Equals("")) || !(Pro_Post_Code.Equals("")) || !(Pro_Country.Equals("")) ) { NbBytes += "ADR;TYPE=work:;".Length + Pro_Address1.Length + 1 + Pro_Address2.Length + 1 + Pro_Town.Length + 1 + Pro_Region_State.Length + 1 + Pro_Post_Code.Length + 1 + Pro_Country.Length + 2; } if (!Home_phone.Equals("")) { NbBytes += "TEL;TYPE=home:".Length + Home_phone.Length + 2; } if (!Business_phone.Equals("")) { NbBytes += "TEL;TYPE=work:".Length + Business_phone.Length + 2; } if (!Cell_phone.Equals("")) { NbBytes += "TEL;TYPE=cell:".Length + Cell_phone.Length + 2; } if (!Fax.Equals("")) { NbBytes += "TEL;TYPE=fax:".Length + Fax.Length + 2; } if (!Pager.Equals("")) { NbBytes += "TEL;TYPE=pager:".Length + Pager.Length + 2; } if (!Email.Equals("")) { if (Email_alternative.Equals("")) { NbBytes += "EMAIL:".Length + Email.Length + 2; } else { /* TWO EMAILS : PREF=1 and PREF=2 */ NbBytes += "EMAIL;PREF=1:".Length + Email.Length + 2 + "EMAIL;PREF=2:".Length + Email_alternative.Length + 2; } } if (!Title.Equals("")) { NbBytes += "TITLE:".Length + Title.Length + 2; } if (!Role.Equals("")) { NbBytes += "ROLE:".Length + Role.Length + 2; } if (!Company.Equals("")) { NbBytes += "ORG:".Length + Company.Length + 2; } if (!_photo.Equals("")) { NbBytes += "PHOTO;ENCODING=BASE64;TYPE=JPEG:".Length + _photo.Length + 2; } NbBytes += "END:VCARD".Length + 2; return(NbBytes); }
public override bool Encode(ref byte[] buffer) { /* First : determine the total number of characters */ int NbBytes = count_nb_bytes(); /* Second : create the whole byte array */ int index = 0; int new_index; byte[] pl = new byte[NbBytes]; new_index = AddLine(pl, pl.Length, index, "BEGIN:VCARD", ""); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'BEGIN'"); return(false); } index = new_index; new_index = AddLine(pl, pl.Length, index, "VERSION:3.0", ""); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'VERSION'"); return(false); } index = new_index; string name = _first_name + " " + _family_name; new_index = AddLine(pl, pl.Length, index, "FN:", name); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'FN'"); return(false); } index = new_index; if (!Nickname.Equals("")) { new_index = AddLine(pl, pl.Length, index, "NICKNAME:", Nickname); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'Nickname'"); return(false); } index = new_index; } DateTime dateBirthday; if ((!Birthday.Equals("")) && (DateTime.TryParse(Birthday, out dateBirthday))) { string Bday = convert_into_vcard_date(Birthday); new_index = AddLine(pl, pl.Length, index, "BDAY:", Bday); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'Birthday'"); return(false); } index = new_index; } if (!(Address1.Equals("")) || !(Address2.Equals("")) || !(Town.Equals("")) || !(Region_State.Equals("")) || !(Post_Code.Equals("")) || !(Country.Equals("")) ) { string addr_line = Address1 + ";" + Address2 + ";" + Town + ";" + Region_State + ";" + Post_Code + ";" + Country; new_index = AddLine(pl, pl.Length, index, "ADR:;", addr_line); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'Address'"); return(false); } index = new_index; } if (!(Pro_Address1.Equals("")) || !(Pro_Address2.Equals("")) || !(Pro_Town.Equals("")) || !(Pro_Region_State.Equals("")) || !(Pro_Post_Code.Equals("")) || !(Pro_Country.Equals("")) ) { string pro_addr_line = Pro_Address1 + ";" + Pro_Address2 + ";" + Pro_Town + ";" + Pro_Region_State + ";" + Pro_Post_Code + ";" + Pro_Country; new_index = AddLine(pl, pl.Length, index, "ADR;TYPE=work:;", pro_addr_line); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'Professional Address'"); return(false); } index = new_index; } if (!Home_phone.Equals("")) { new_index = AddLine(pl, pl.Length, index, "TEL;TYPE=home:", Home_phone); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'TEL;TYPE=home'"); return(false); } index = new_index; } if (!Business_phone.Equals("")) { new_index = AddLine(pl, pl.Length, index, "TEL;TYPE=work:", Business_phone); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'TEL;TYPE=work'"); return(false); } index = new_index; } if (!Cell_phone.Equals("")) { new_index = AddLine(pl, pl.Length, index, "TEL;TYPE=cell:", Cell_phone); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'TEL;TYPE=cell'"); return(false); } index = new_index; } if (!Pager.Equals("")) { new_index = AddLine(pl, pl.Length, index, "TEL;TYPE=pager:", Pager); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'TEL;TYPE=pager'"); return(false); } index = new_index; } if (!Fax.Equals("")) { new_index = AddLine(pl, pl.Length, index, "TEL;TYPE=fax:", Fax); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'TEL;TYPE=fax'"); return(false); } index = new_index; } if (!Email.Equals("")) { if (Email_alternative.Equals("")) { new_index = AddLine(pl, pl.Length, index, "EMAIL:", Email); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'EMAIL'"); return(false); } index = new_index; } else { /* Two E-mails to add */ new_index = AddLine(pl, pl.Length, index, "EMAIL;PREF=1:", Email); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'EMAIL;PREF=1'"); return(false); } index = new_index; new_index = AddLine(pl, pl.Length, index, "EMAIL;PREF=2:", Email_alternative); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'EMAIL;PREF=2'"); return(false); } index = new_index; } } if (!Title.Equals("")) { new_index = AddLine(pl, pl.Length, index, "TITLE:", Title); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'TITLE'"); return(false); } index = new_index; } if (!Role.Equals("")) { new_index = AddLine(pl, pl.Length, index, "ROLE:", Role); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'ROLE'"); return(false); } index = new_index; } if (!Company.Equals("")) { new_index = AddLine(pl, pl.Length, index, "ORG:", Company); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'ORG'"); return(false); } index = new_index; } if (!_photo.Equals("")) { new_index = AddLine(pl, pl.Length, index, "PHOTO;ENCODING=BASE64;TYPE=JPEG:", _photo); if (new_index < 0) { Trace.WriteLine("Error generating 'VCard' object: after 'PHOTO'"); return(false); } index = new_index; } new_index = AddLine(pl, pl.Length, index, "END:VCARD", ""); _payload = pl; return(base.Encode(ref buffer)); }
public async Task Init() { if (CountryList.Count == 0) { var anyCountry = new Country { CountryId = -1, Name = "Any" }; CountryList.Add(anyCountry); var countryList = await _countryService.GetAll <List <Country> >(); foreach (var country in countryList) { CountryList.Add(country); } SelectedCountry = anyCountry; } if (StatusList.Count == 0) { var anyStatus = new Model.Status { StatusId = -1, Name = "Any" }; StatusList.Add(anyStatus); var statusList = await _statusService.GetAll <List <Model.Status> >(); foreach (var status in statusList) { StatusList.Add(status); } SelectedStatus = anyStatus; } int?maximumRoomsInt = null; int?minimumPriceInt = null; try { maximumRoomsInt = int.Parse(MaximumRooms); } catch (System.Exception) {} try { minimumPriceInt = int.Parse(MinimumPrice); } catch (System.Exception) { } var searchRequest = new RequestSearchRequest { MaximumRooms = maximumRoomsInt, MinimumPrice = minimumPriceInt, ShowInactive = false }; if (SelectedCountry != null && SelectedCountry.CountryId != -1) { searchRequest.CountryId = SelectedCountry.CountryId; } if (SelectedStatus != null && SelectedStatus.StatusId != -1) { searchRequest.StatusId = SelectedStatus.StatusId; } var requestList = await _requestService.GetAll <List <Request> >(searchRequest); RequestList.Clear(); foreach (var request in requestList) { var user = await _authService.GetById(request.ClientId); var userAddress = await _addressService.GetById <Address>((int)user.AddressId); var userCountry = await _countryService.GetById <Country>((int)userAddress.CountryId); var requestAddress = await _addressService.GetById <Address>(request.DeliveryAddress); var requestCountry = await _countryService.GetById <Country>((int)requestAddress.CountryId); var newRequest = new RequestModel { FromCountry = userCountry.Name, FullName = user.FirstName + " " + user.LastName, Price = request.Price, RequestId = request.RequestId, ToCountry = requestCountry.Name }; RequestList.Add(newRequest); } if (RequestList.Count > 0) { ShowList = true; HideList = false; } else { ShowList = false; HideList = true; } }
public async Task <PagedResultOutput <FillLotListDto> > GetFillLots(GetFillLotsInput input) { //FillLotAppService.<>c__DisplayClass8_1 variable = null; //FillLotAppService.<>c__DisplayClass8_0 variable1 = null; //FillLotAppService.<>c__DisplayClass8_2 variable2 = null; int fillLotId; IQueryable <FillLot> all = _fillLotRepository.GetAll(); var fillLots = all.Where(p => p.TenantId == AbpSession.TenantId && p.Id == 0); // Really? var listAsync = await fillLots.Select(s => new { FillLotId = s.Id }).ToListAsync(); var collection = listAsync; List <long> foundFillLotIdsFromInputFilter = ( from s in collection select s.FillLotId).ToList(); bool foundUsingIdFilter = false; if (input.Filter.ToLower().StartsWith("id:")) { try { string lower = input.Filter.ToLower(); char[] chrArray = new char[] { ':' }; int.TryParse(lower.Split(chrArray)[1].ToString(), out fillLotId); IQueryable <FillLot> all1 = _fillLotRepository.GetAll(); var fillLots1 = all1.Where(p => p.TenantId == AbpSession.TenantId && p.Id == fillLotId); var listAsync1 = await fillLots1.Select(s => new { FillLotId = s.Id }).ToListAsync(); foundUsingIdFilter = true; foundFillLotIdsFromInputFilter = foundFillLotIdsFromInputFilter.Union( from s in listAsync1 select s.FillLotId).ToList(); } catch (Exception) { } } if (!foundUsingIdFilter) { IQueryable <FillLot> all2 = _fillLotRepository.GetAll(); var fillLots2 = all2.WhereIf(!input.Filter.IsNullOrEmpty(), p => p.Label.Contains(input.Filter) || p.ShortLabel.Contains(input.Filter) || p.Description.Contains(input.Filter)); var listAsync2 = await fillLots2.Select(s => new { FillLotId = s.Id }).ToListAsync(); foundFillLotIdsFromInputFilter = foundFillLotIdsFromInputFilter.Union( from s in listAsync2 select s.FillLotId).ToList(); } IQueryable <FillLot> all3 = this._fillLotRepository.GetAll(); var fillLots3 = all3.Where(m => foundFillLotIdsFromInputFilter.Contains(m.Id)); int resultCount = await fillLots3.CountAsync(); List <FillLot> orderedResult = await fillLots3.OrderBy(input.Sorting, new object[0]).PageBy(input).ToListAsync(); List <FillLotListDto> fillLotListDtos = orderedResult.MapTo <List <FillLotListDto> >(); foreach (FillLotListDto countryDto in fillLotListDtos) { FillLotListDto fillLotListDto = countryDto; int tankTotal = await _fillLotTankRepository.CountAsync(m => m.FillLotId == countryDto.Id); fillLotListDto.TankTotal = tankTotal; fillLotListDto = null; if (countryDto.AddressId > 0) { Address async = await _addressRepository.GetAsync(countryDto.AddressId); countryDto.Address = async.MapTo <AddressDto>(); if (countryDto.Address.CountryId <= 0) { countryDto.Address.Country = new CountryDto(); } else { Country country = await this._countryRepository.GetAsync(countryDto.Address.CountryId); countryDto.Address.Country = country.MapTo <CountryDto>(); } if (!countryDto.Address.CountryRegionId.HasValue) { countryDto.Address.CountryRegion = new CountryRegionDto(); } else { IRepository <CountryRegion> repository1 = this._countryRegionRepository; int? countryRegionId = countryDto.Address.CountryRegionId; CountryRegion countryRegion = await repository1.GetAsync(countryRegionId.Value); countryDto.Address.CountryRegion = countryRegion.MapTo <CountryRegionDto>(); } } } return(new PagedResultOutput <FillLotListDto>(resultCount, fillLotListDtos)); }
public bool Update(Country country) { return(_countryGetway.Update(country)); }
public ActionResult Index() { List <Country> allcountries = Country.GetAll(); return(View(allcountries)); }
protected override void Seed(SportsEventsDbContext context) { base.Seed(context); if (!context.Events.Any()) { var usermanager = new ApplicationUserManager(new UserStore <ApplicationUser>(context)); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); roleManager.Create(new IdentityRole("Organizer")); var rand = new Random(DateTime.Now.Second); var advertisements = new List <Advertisement>(); var countries = new List <Country>(); var cities = new List <City>(); var events = new List <Event>(); for (int i = 0; i < 20; i++) { var country = new Country() { Name = Ipsum.GetWord() }; ; for (int j = 0; j < 20; j++) { cities.Add(new City() { Name = Ipsum.GetWord(), Country = country, CountryName = country.Name }); } } for (int i = 0; i < 20; i++) { advertisements.Add(new Advertisement() { Image = "https://placehold.it/600x600?text=Ad+" + Ipsum.GetWord(), Priority = rand.Next(1, 11), Prelogin = rand.Next(0, 2) == 1, Keywords = Ipsum.GetWord() }); } for (int i = 0; i < 30; i++) { var user = new ApplicationUser() { UserName = Ipsum.GetWord(), Email = Ipsum.GetWord() + "@" + Ipsum.GetWord() + ".com", Address = new Address() }; usermanager.Create(user, "idkwmpsb"); } context.Advertisements.AddRange(advertisements); var organizers = context.Users.ToList(); for (var i = 0; i < 20; i++) { var sport = new Sport { Name = Ipsum.GetPhrase(rand.Next(1, 4)) }; var eventType = new EventType { Name = Ipsum.GetPhrase(rand.Next(1, 4)) }; context.Sports.Add(sport); context.EventTypes.Add(eventType); for (var j = 0; j < 20; j++) { var pictures = new List <Picture>(); for (int k = 0; k < rand.Next(1, 5); k++) { pictures.Add(new Picture() { Url = "https://placehold.it/1000x800?text=" + Ipsum.GetWord() }); } var description = Ipsum.GetPhrase(rand.Next(1, 10)); var beginDate = DateTime.Now.Date + TimeSpan.FromDays(rand.Next(1, 15)); var detail = Ipsum.GetPhrase(rand.Next(40, 200)); var endDate = beginDate + TimeSpan.FromDays(rand.Next(1, 15)); var organizer = organizers[rand.Next(organizers.Count)]; var address = new Address { LineOne = Ipsum.GetPhrase(rand.Next(1, 10)), LineTwo = Ipsum.GetPhrase(rand.Next(1, 10)) }; if (!String.IsNullOrEmpty(description)) { description = description.Substring(0, 1).ToUpper() + description.Substring(1); } if (!String.IsNullOrEmpty(detail)) { detail = detail.Substring(0, 1).ToUpper() + detail.Substring(1); } var @event = new Event { BeginDate = beginDate, BeginTime = DateTime.Now, EndTime = DateTime.Now, Address = address, Description = description, Details = detail, EndDate = endDate, StartingPrice = rand.Next(0, 1000), VideoLink = "https://placehold.it/600x400?text=" + Ipsum.GetWord(), Pictures = pictures, Sport = sport, SportName = sport.Name, EventType = eventType, EventTypeName = eventType.Name, Organizer = organizer, City = cities[rand.Next(cities.Count)], OrganizerName = organizer.UserName, IsFeatured = rand.Next(2) == 1, }; events.Add(@event); } } context.Events.AddRange(events); } }
public bool Add(Country country) { return(_countryGetway.Add(country)); }
public void AddCountry(Country country) { db.Countries.Add(country); db.SaveChanges(); }
protected override List <Competition> CreateCompetition(Country country) { //All League Competitions List <Competition> divisions = new List <Competition>() { Context.Competitions.Add( new Competition() { Name = "Premier League", Country = country, RelegateToChildCompetition = 3 }).Entity, Context.Competitions.Add( new Competition() { Name = "Sky Bet Championship", Country = country, PromoteToParentCompetition = 2, RelegateToChildCompetition = 3 }).Entity, Context.Competitions.Add( new Competition() { Name = "Sky Bet League One", Country = country, PromoteToParentCompetition = 2, RelegateToChildCompetition = 4 }).Entity, Context.Competitions.Add( new Competition() { Name = "Sky Bet League Two", Country = country, PromoteToParentCompetition = 3, RelegateToChildCompetition = 2 }).Entity, Context.Competitions.Add( new Competition() { Name = "Vanorama National League", Country = country, PromoteToParentCompetition = 1 }).Entity }; Context.SaveChanges(); //Couple all Competitions for promotion-system for (int i = 0; i < divisions.Count; i++) { if (i < divisions.Count - 1) { divisions[i].ChildCompetitionId = divisions[i + 1].Id; } if (i > 0) { divisions[i].ParentCompetitionId = divisions[i - 1].Id; } } //Create Competition Events CreateDefaultCompetitionEvents(divisions[0], new DateTime(2019, 6, 6, 12, 0, 0), new DateTime(2019, 8, 12, 15, 0, 0), new DateTime(2020, 5, 12, 15, 0, 0) ); for (int i = 1; i < divisions.Count; i++) { CreateDefaultCompetitionEvents(divisions[i], new DateTime(2019, 6, 6, 12, 0, 0), new DateTime(2019, 8, 4, 15, 0, 0), new DateTime(2020, 5, 4, 15, 0, 0) ); } //Create Playoffs and Events CreateDefaultPlayoffStructure(divisions[0], divisions[1], new DateTime(2020, 5, 12, 21, 0, 0), new DateTime(2020, 5, 17, 15, 0, 0), new DateTime(2020, 5, 24, 15, 0, 0), 0, 4); CreateDefaultPlayoffStructure(divisions[1], divisions[2], new DateTime(2020, 5, 12, 21, 0, 0), new DateTime(2020, 5, 17, 15, 0, 0), new DateTime(2020, 5, 24, 15, 0, 0), 0, 4); for (int i = 2; i < divisions.Count - 1; i++) { CreateDefaultPlayoffStructure(divisions[i], divisions[i + 1], new DateTime(2020, 5, 5, 21, 0, 0), new DateTime(2020, 5, 9, 15, 0, 0), new DateTime(2020, 5, 12, 15, 0, 0), 0, 4); } //Create Season end for (int i = 0; i <= 2; i++) { Context.CompetitionEvents.Add( new DefaultSeasonEndEvent() { Name = "Seizoenseinde", Competition = divisions[i], Date = new DateTime(2020, 5, 25, 15, 0, 0) }); } for (int i = 3; i < divisions.Count; i++) { Context.CompetitionEvents.Add( new DefaultSeasonEndEvent() { Name = "Seizoenseinde", Competition = divisions[i], Date = new DateTime(2020, 5, 13, 15, 0, 0) }); } Context.SaveChanges(); return(divisions); }
public void Post([FromBody] Country value) { _repository.Add(value); }
public void Put(int id, [FromBody] Country value) { value.Id = id; _repository.Update(value); }
private void LogAccept(Country c, DateTime at) { Log("Server accepted notification about {0} at {1}", c.ToString(), I18n.Localize(at, DateTimeFormat.YMDhms)); }
private void add_Click(object sender, EventArgs e) { if (City_dpt.Text != "" && Country.Text != "" && Name.Text != "" && Price.Text != "" && Date.Text != "" && Night.Text != "") { DialogResult dr = MessageBox.Show("Добавить запись?", "Добавление", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (dr == DialogResult.OK) { bool flag = false; for (int i = 0; i < tour.Count; i++) { if (City_dpt.Text == tour[i].City && Country.Text == tour[i].Country1 && Name.Text == tour[i].Name1 && Price.Text == tour[i].Price1 && Date.Text == tour[i].dateofdep.ToString() && Night.Text == tour[i].numberofnights) { flag = true; } } if (!flag) { this.Validate(); this.toursBindingSource.EndEdit(); DataRow nRow = tiuDataSet2.Tables[0].NewRow(); nRow["Город отправления"] = City_dpt.Text.ToString(); nRow["Страна назначения"] = Country.Text.ToString(); nRow["Название тура"] = Name.Text.ToString(); CultureInfo MyCultureInfo = new CultureInfo("en-US"); nRow["Стоимость"] = Price.Text.ToString(); nRow["Дата вылета"] = DateTime.ParseExact(Date.Text.ToString(), "dd.M.yyyy", MyCultureInfo); nRow["Количество ночей"] = Night.Text.ToString(); tiuDataSet2.Tables[0].Rows.Add(nRow); toursTableAdapter.Update(tiuDataSet2.Tours); tiuDataSet2.Tables[0].AcceptChanges(); TuiTour.Refresh(); Fn.update(this.TuiTour, this.tour); City_dpt.Clear(); Country.Clear(); Name.Clear(); Price.Clear(); Date.Clear(); Night.Clear(); } if (flag) { DialogResult er = MessageBox.Show("Такая запись уже существует!", "Добавление", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); } } } else { DialogResult dr = MessageBox.Show("Некорректный ввод! Поля пусты.", "Добавление", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); } }