I am creating a chart for windows phone 7.
This is the foreach for each hawker returned:
void dbSvc_retrievepopularhawkerCompleted(object sender, RouteServiceRef.retrievepopularhawkerCompletedEventArgs e)
{
List<RouteServiceRef.Hawker> recommendPlaceList;
recommendPlaceList = e.Result.Cast<RouteServiceRef.Hawker>().ToList();
string hawkername = "";
string address = "";
string postal = "";
double coordX = 0.0;
double coordY = 0.0;
double popularity = 0;
foreach (RouteServiceRef.Hawker rp in recommendPlaceList)
{
hawkername = rp.hawkername;
address = rp.address;
postal = rp.postal;
coordX = rp.xcoord;
coordY = rp.ycoord;
popularity = rp.popularity;
}
I have to change the above codes to be inside this list of cities:
List<City> cities = new List<City> { new City { Name = "CLE", Population = 2250871 }, new City { Name = "CMH", Population = 1773120 }, new City { Name = "CVG", Population = 2155137 }, new City { Name = "DET", Population = 4425110 } };
such as: List<City> cities = new List<City> { new City Name = hawkername, Population = popularity }
so that I can do a bind to my chart:
ColumnSeries bs = ChartControl.Series[0] as ColumnSeries; bs.ItemsSource = cities;
I am not sure how to mix them up, can someone guide me along ? As I do not want to hard code the name and population inside.
that's easy, Just follow the code below.
Declare the list of City Above the foreach loop and on each iteration just add new item to the list
List<City> cities = new List<City> ();
foreach (RouteServiceRef.Hawker rp in recommendPlaceList)
{
hawkername = rp.hawkername;
address = rp.address;
postal = rp.postal;
coordX = rp.xcoord;
coordY = rp.ycoord;
popularity = rp.popularity;
cities.Add(new City(){Name = hawkername, Population = popularity });
}
This fills the cities list as well on the completion of foreach loop.
Related
Can I get the language name from country code? I have create a program to let user select localization for currency display purposes. This is the program that do the configuration.
CultureInfo[] cinfo = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures);
Dictionary<string, string> Misc_dictLocalization = new Dictionary<string, string>();
var sortList = cinfo.OrderBy(p => p.EnglishName).ToList();
foreach (CultureInfo cul in sortList)
{
//Add country name and bind with country code
Misc_dictLocalization.Add(cul.Name, cul.EnglishName);
}
Misc_LocalizationCombobox.DataSource = new BindingSource(Misc_dictLocalization, null);
Misc_LocalizationCombobox.DisplayMember = "Value";
Misc_LocalizationCombobox.ValueMember = "Key";
On Combobox selection,
string key = ((KeyValuePair<string, string>)Misc_LocalizationCombobox.SelectedItem).Key;
string value = ((KeyValuePair<string, string>)Misc_LocalizationCombobox.SelectedItem).Value;
Misc_CountryCode.Text = key;
decimal dec = Convert.ToDecimal(Misc_DecimalNumber.Text);
Misc_CurrencyFormat.Text = dec.ToString("C", new CultureInfo(Misc_CountryCode.Text));
I'm currently using
var allCultures = System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures);
string countrycode = "ar-SA";
string langname = allCultures.FirstOrDefault(c => c.Name == countrycode).DisplayName;
//langname will have "Arabic"
How to get native name (endonym) from country code?
Based from the Wikipedia List of ISO 639-1 codes,
I need to get;
1) Philippines(fil-PH) => Tagalog
2) Vietnam(vi-VN) => Tiếng Việt
3) United States(en-US) => English
4) Arabic(ar-SA) => العربية
SOLUTION SOLVED (credit Nhan Phan)
..Exactly like how I would want
DirectoryInfo di = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Language"));
FileInfo[] Files = di.GetFiles("*.xaml");
int ID = 1;
var allCultures = System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures);
LocalizationProperty.LangLoc = new List<AppModel.LanguageLocalization>();
foreach (FileInfo file in Files)
{
string countrycode = file.Name.Replace(".xaml", "").Replace("Resources.", "");
int index = countrycode.LastIndexOf("-");
string ISOName = countrycode;
if (index > 0)
ISOName = ISOName.Substring(0, index);
string langname = allCultures.FirstOrDefault(c => c.Name == ISOName).NativeName;
AppModel.LanguageLocalization applang = new AppModel.LanguageLocalization
{
LanguageID = ID,
CountryCode = countrycode,
LanguageName = langname
};
LocalizationProperty.LangLoc.Add(applang);
ID += 1;
}
string langjson = Newtonsoft.Json.JsonConvert.SerializeObject(LocalizationProperty.LangLoc, Formatting.Indented);
LogEvents($"[{PageTitle} Language file retrieved. {langjson}", EventLogEntryType.Information);
Object2JsonString:-
[
{
"LanguageID":1,
"CountryCode":"ar-SA",
"LanguageName":"العربية"
},
{
"LanguageID":2,
"CountryCode":"en-US",
"LanguageName":"English"
},
{
"LanguageID":3,
"CountryCode":"fil-PH",
"LanguageName":"Filipino"
},
{
"LanguageID":4,
"CountryCode":"ms-MY",
"LanguageName":"Melayu"
},
{
"LanguageID":5,
"CountryCode":"syr-SY",
"LanguageName":"ܣܘܪܝܝܐ"
},
{
"LanguageID":6,
"CountryCode":"ta-IN",
"LanguageName":"தமிழ்"
},
{
"LanguageID":7,
"CountryCode":"tt-RU",
"LanguageName":"Татар"
},
{
"LanguageID":8,
"CountryCode":"vi-VN",
"LanguageName":"Tiếng Việt"
},
{
"LanguageID":9,
"CountryCode":"zh-CN",
"LanguageName":"中文"
}
]
The view:-
You can retrieve it via NativeName instead of DisplayName:
var allCultures = System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures);
string countrycode = "ar-SA";
string langname = allCultures.FirstOrDefault(c => c.Name == countrycode).NativeName;
Here's my code :
public partial class ActivityService
{
public SearchActivityOutput GetActivityFromDbByName(SearchActivityInput input)
{
using (var conn = DbService.GetInstance().GetOpenConnection())
{
var savedActivities = GetSearchResultByNameQuery.GetInstance()
.Execute(conn, new { Name = input.Name });
var activityList = savedActivities.Select(a => new ActivityDetail()
{
Name = a.Name,
City = a.City,
Country = a.Country,
Description = a.Description,
OperationTime = a.OperationTime,
Price = a.Price
}).ToList();
var output = new SearchActivityOutput
{
ActivityList = activityList
};
return output;
}
}
}
How can i create unit test from that class?
my sample unit test for that class:
[TestMethod()]
public void GetActivityFromDbByNameTest()
{
Initializer.Init();
var input = new SearchActivityInput { Name = "Marjan" };
var ActList1 = new ActivityDetail()
{ Name = "Marjan", City = "Bandung", Country = "Indonesia", Description = "coba", OperationTime = "24 Jam", Price = 2000};
var ActList2 = new ActivityDetail()
{ Name = "Marjan", City = "Bandung", Country = "Indonesia", Description = "coba", OperationTime = "24 Jam", Price = 3500 };
var ActList3 = new ActivityDetail()
{ Name = "Marjan aja", City = "Jakarta", Country = "Indonesia", Description = "apapun", OperationTime = "2 Hari", Price = 4500 };
var ActList4 = new ActivityDetail()
{ Name = "Marjan", City = "Stockholm", Country = "Swedia", Description = "123coba", OperationTime = "3 Jam", Price = 3500 };
var ActList5 = new ActivityDetail()
{ Name = "Marjan", City = "Stockholm", Country = "Swedia", Description = "123coba", OperationTime = "3 Jam", Price = 4500 };
var ActList6 = new ActivityDetail()
{ Name = "Marjan aja", City = "Jakarta", Country = "Indonesia", Description = "apapun", OperationTime = "2 Hari", Price = 2000 };
var ActList7 = new ActivityDetail()
{ Name = "Marjan", City = "Stockholm", Country = "Swedia", Description = "123coba", OperationTime = "3 Jam", Price = 3500 };
var ActList8 = new ActivityDetail()
{ Name = "Marjan", City = "Stockholm", Country = "Swedia", Description = "123coba", OperationTime = "3 Jam", Price = 2000 };
var ActList9 = new ActivityDetail()
{ Name = "Marjan", City = "Stockholm", Country = "Swedia", Description = "123coba", OperationTime = "3 Jam", Price = 2000 };
var ActList = new List<ActivityDetail>();
ActList.Add(ActList1);
ActList.Add(ActList2);
ActList.Add(ActList3);
ActList.Add(ActList4);
ActList.Add(ActList5);
ActList.Add(ActList6);
ActList.Add(ActList7);
ActList.Add(ActList8);
ActList.Add(ActList9);
var expectedResult = new SearchActivityOutput
{
ActivityList = ActList
};
using (var conn = DbService.GetInstance().GetOpenConnection())
{
var actualResult = ActivityService.GetInstance().GetActivityFromDbByName(input);
Assert.AreEqual(expectedResult, actualResult);
}
}
but, when i run the unit test, there give some error message :
Test Name: GetActivityFromDbByNameTest Test
Result StackTrace: at
xxxx.ActivityServiceTests.GetActivityFromDbByNameTest()
in
70 Result Message: Assert.AreEqual failed.
Expected:(xxx.yyy.zzz.Model.SearchActivityOutput).
Actual:(xxx.yyy.zzz.Model.SearchActivityOutput).
You should not use the database while your unittesting.
Wikipedia says: A common example of this is classes that depend on a database: in order to test the class, the tester often writes code that interacts with the database. This is a mistake, because a unit test should usually not go outside of its own class boundary, and especially should not cross such process/network boundaries because this can introduce unacceptable performance problems to the unit test-suite.
Use testdata or a dummy class that represent your Database.
https://softwareengineering.stackexchange.com/questions/119367/should-service-test-classes-connect-to-the-database
https://softwareengineering.stackexchange.com/questions/138238/unit-testing-database-coupled-app/138257#138257
You cannot unit test a class that performs any I/O-related tasks. Even if your tests seem to run fine on your development machine, they will likely fail on your colleague's machine or CI server.
In order for your piece of code to be testable, it should be a either a pure function, or it should be reducible to a pure function using some abstraction techniques like IoC / higher order functions / etc.
Learn to write testable code first. This article will give you some advise - https://www.toptal.com/resume/sergey-kolodiy (I'm the author of it).
I completely agree with the other statements about not using the database in your unit tests, but the answer to the failure that you're currently receiving is that you should be using methods of the CollectionAssert class to compare the contents of two collections instead of the Assert class that you're using. If you just want to ensure that the returned List contains the same elements regardless of ordering, you can use
CollectionAssert.AreEquivalent(expectedResult, actualResult);
If sequencing order is important, you should use
CollectionAssert.AreEqual(expectedResult, actualResult);
enter image description here
[WebMethod]
public void AddEmployementRequest(EmployementRequest emp)
{
EmployeeSkill employeeSkill = new EmployeeSkill
{
Skill = emp.,
Description = emp.
};
EmployeeLanguage employeeLanguage = new EmployeeLanguage
{
Name = emp.,
ConversationLevel = emp.
};
EmployeeCours employeeCours = new EmployeeCours
{
Date =emp. ,
Course = emp.,
Duration = emp.,
Association = emp.,
Description = emp.
};
EmployementRequest employementRequest = new EmployementRequest
{
Name = emp.Name,
Address = emp.Address,
Surnam = emp.Surnam,
Father = emp.Father,
IDNumber = emp.IDNumber,
IDCardNumber = emp.IDNumber,
IDCity = emp.IDCity,
Birthday = emp.Birthday,
Birthplace = emp.Birthplace,
Nationality = emp.Nationality,
Religion = emp.Religion,
Phone = emp.Phone,
Cell = emp.Cell,
EmergencyAddress = emp.EmergencyAddress,
EmergencyName = emp.EmergencyName,
EmergencyPhone = emp.EmergencyPhone,
ParentedPeople = emp.ParentedPeople,
Gender = emp.Gender,
MarriageStatus = emp.MarriageStatus,
Residency = emp.Residency,
InsuranceCode = emp.InsuranceCode,
InsuranceStatus = emp.InsuranceStatus,
VehicleType = emp.VehicleType,
MilitaryServiceStatus = emp.MilitaryServiceStatus,
EducatedFrom = emp.EducatedFrom,
EducationField = emp.EducationField,
EducationGrade = emp.EducationGrade,
ExtraWorkCapability = emp.ExtraWorkCapability,
LeisureTimeHobbies = emp.LeisureTimeHobbies,
Salary = emp.Salary,
IntroducerName = emp.IntroducerName,
IntroductionMethod = emp.IntroductionMethod,
Illness = emp.Illness,
VehicleStatus = emp.VehicleStatus,
PKEmploymentRequest = Guid.NewGuid(),
};
employementRequest.EmployeeLanguages.Add(employeeLanguage);
employementRequest.EmployeeSkills.Add(employeeSkill);
employementRequest.EmployeeCourses.Add(employeeCours);
using (var db = new UKN_DBNAMEEntities())
{
db.EmployementRequests.Add(employementRequest);
db.SaveChanges();
}
}
I want to insert to all parent and child tables at once ,As you can see I can't access the properties in child tables and also there's no intellisense to show the properties unlike the parent
I think I need a Linq query but I have no idea
have you tried
[WebMethod]
public void AddEmployementRequest(EmployementRequest emp) {
emp.PKEmploymentRequest = Guid.NewGuid();
using (var db = new UKN_DBNAMEEntities()) {
db.EmployementRequests.Add(emp);
db.SaveChanges();
}
}
It may/should do, but...
Consider:
using automapper or the like;
use some query to avoid recreation of Language or Skil
List 2 show only two elements but I need 4 elements
Address has got 4 elements
Association has got 2 elements
If I will add two more elements to Association I will get 4 elements how do it automatically.
DT_createdRentalObject ro = new DT_createdRentalObject();
//Add Address
List<Address> la = new List<Address>();
la.Add(new Address { City = "Arizona" });
la.Add(new Address { City = "Texas" });
la.Add(new Address { City = "California" });
la.Add(new Address { City = "Florida" });
ro.Address = la.ToArray();
//Add Association
List<Association> aso = new List<Association>();
aso.Add(new Association { AssociationType = "1" });
aso.Add(new Association { AssociationType = "2" });
ro.Association = aso.ToArray();
//Add LandData
List<LandData> landa = new List<LandData>();
landa.Add(new LandData { LandRegistrNumber = "12343" });
landa.Add(new LandData { LandRegistrNumber = "8737" });
landa.Add(new LandData { LandRegistrNumber = "2456" });
ro.LandData = landa.ToArray();
//Object
List<MasterDataObjectID> mdobid = new List<MasterDataObjectID>();
mdobid.Add(new MasterDataObjectID { IDType = "TYPID_212_12" });
//ObjectType
MasterData mdats = new MasterData();
mdats.ObjectType = "Flat";
mdats.ObjectID = mdobid.ToArray();
ro.MasterData = mdats;
var list =
ro.Address.Zip(ro.Association,
(add, asn) => new
{
ro.MasterData.ObjectID[0].IDType,
ro.MasterData.ObjectType,
add.City,
asn.AssociationType,
}
);
var list2 = list.Zip(ro.LandData, (ld, lan) => new
{
ld.AssociationType,
ld.City,
ld.IDType,
ld.ObjectType,
lan.LandRegistrNumber
});
I have the following codes:
void dbSvc_retrievepopularhawkerCompleted(object sender, RouteServiceRef.retrievepopularhawkerCompletedEventArgs e)
{
List<RouteServiceRef.Hawker> recommendPlaceList;
recommendPlaceList = e.Result.Cast<RouteServiceRef.Hawker>().ToList();
string hawkername = "";
string address = "";
string postal = "";
double coordX = 0.0;
double coordY = 0.0;
double popularity = 0;
foreach (RouteServiceRef.Hawker rp in recommendPlaceList)
{
hawkername = rp.hawkername;
address = rp.address;
postal = rp.postal;
coordX = rp.xcoord;
coordY = rp.ycoord;
popularity = rp.popularity;
cities.Add(new City() { Name = hawkername, Population = popularity });
}
ColumnSeries bs = ChartControl.Series[0] as ColumnSeries; bs.ItemsSource = cities;
}
How can I extract the first three word in the string of the hawkername ? The result for hawkername is:
I need to get the first three string out.
var firstThreeWords = hawkername.Split(' ').Take(3);
Don't forget to include using System.Linq; if you're not already using it:
Something like this will do :
var input = "ldsk bkfd badk klsfdl";
var result = string.Join(" ", input.Split(' ').Take(3));
Console.WriteLine(result);