How to handle Alamofire responses and reuse in different Views - json

I am newbie in Xcode, sorry if is a basic question need to use the first response in static view and the second in tableview, maybe is some common way to handle both and read data from other view, I can make both responses return the same keys, or if is better push the first in "hits".
Thanks in advance.
I make the requests with Alamofire with .responseJSON
One returning simple row with the following response:
success({
adultos = 2;
aeropuerto = "<null>";
bebes = 0;
compania = "<null>";
destino = Aeropuerto;
dia = 0;
direccion = "calle aragon";
enapto = 0;
entaxi = 0;
exito = 1;
fecha = "0000-00-00";
finalizado = 0;
})
Other with variable number of rows returning
success({
hits = (
{
destino = "Son Servera";
dia = 24;
direccion = "Torre Marina, Ronda de Sol Ixent, 22";
entaxi = 1;
fecha = "2021-06-24";
hora = "22:20";
"id_reservas" = 958687;
mes = "Thursday June 2021";
"nombre_cliente" = "SERVICIO DE PRUEBA";
origen = Aeropuerto;
},
{
destino = "AIDA Cruceros";
dia = 25;
direccion = prueba;
entaxi = 1;
fecha = "2021-06-25";
hora = "12:00";
"id_reservas" = 959442;
mes = "Friday June 2021";
"nombre_cliente" = "TONI CARDONA";
origen = Aeropuerto;
},
);
})

Related

Using custom date format

I have this working script to sent mails with data from a Google sheet:
function SendEmail() {
let timestamp = 0
let poid = 1
let sku = 2
let qty = 3
let description = 4
let licenseid = 5
let itcost = 6
let total = 7
let company = 8
let contact = 9
let contactmail = 10
let endusermail = 11
let address = 12
let country = 13
let status = 14
let suppliermail = 15
let currency = 16
let otherinfo = 17
let brand = 18
let comment = 19
let cc = 20
let emailTemp = HtmlService.createTemplateFromFile("MAIL")
let ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DATA")
let sd = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DATA2")
let data = ws.getRange("A2:V" + ws.getLastRow()).getValues()
let sData = sd.getRange("B2:J" + sd.getLastRow()).getValues()
let sInfo = sData.map(function (r) { return r[0] })
data = data.filter(function (r) { return r[14] == 'SENTNOW' })
if (data.length) {
let found = false
data.forEach(function (row) {
emailTemp.ts = row[timestamp].toLocaleString("da-DK")
emailTemp.po = row[poid]
emailTemp.co = row[contact]
emailTemp.cm = row[company]
emailTemp.ad = row[address]
emailTemp.cu = row[country]
emailTemp.cn = row[contactmail]
emailTemp.sk = row[sku]
emailTemp.de = row[description]
emailTemp.qt = row[qty]
emailTemp.it = (row[itcost]).toLocaleString("da-DK")
emailTemp.to = (row[total]).toLocaleString("da-DK")
emailTemp.ce = row[comment]
emailTemp.cy = row[currency]
emailTemp.eu = row[endusermail]
emailTemp.li = row[licenseid]
emailTemp.ot = row[otherinfo]
let indexSupp = sInfo.indexOf(row[15])
if (indexSupp > -1) {
//only change status if supplierdata email is found
found = true
emailTemp.spname = sData[indexSupp][1]
emailTemp.saddress1 = sData[indexSupp][2]
emailTemp.saddress2 = sData[indexSupp][3]
emailTemp.scountry = sData[indexSupp][4]
emailTemp.sterms = sData[indexSupp][5]
emailTemp.scurrency = sData[indexSupp][6]
emailTemp.sothers = sData[indexSupp][7]
emailTemp.vat = sData[indexSupp][8] * 100
emailTemp.totvat = (row[total] * sData[indexSupp][8]).toLocaleString("da-DK")
emailTemp.totandvat = (row[total] + (row[total] * sData[indexSupp][8])).toLocaleString("da-DK")
let subjectLine = "Subject line # " + row[poid]
let htmlMessage = emailTemp.evaluate().getContent()
//only send email if supplierdata email is found
try {
GmailApp.sendEmail(
row[suppliermail],
subjectLine,
"",
{ name: 'Name', htmlBody: htmlMessage, bcc: 'myemail#domain.com' })
}
catch (err) {
SpreadsheetApp.getUi().alert(err)
}
}
})
if (found) {
let sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DATA")
.getRange('O2:O')
.createTextFinder('SENTNOW')
.replaceAllWith('SENT')
}
}
}
Only problem is the date format emailTemp.ts = row[timestamp].toLocaleString("da-DK")
This give output date-format "11.2.2022 06.00.00" within the e-mail sent to the reciever.
What I wish is the date to be just "02/11/2022"
I tried emailTemp.ts = row[timestamp].toLocaleString("da-DK").getDisplayValue() but that was not working.
Any suggestions ?
You're going to have to figure out your time zone but try this.
emailTemp.ts = Utilities.formatDate(row[timestamp],"GMT","dd/MM/yyyy");
Reference
Utilities.formatDate()

.net core connect to mysql server

I have a issue here for the connect mysql.
I have a vps that contain mysql server have a database name is 'tuyendungbg'. it's had table and data in there. But when i'm connect and query to select data, that have error for 'Table 'tuyendungbg.Careers' doesn't exist'.
here is my controller :
[HttpGet("/nganh-nghe/{slug?}")]
public IActionResult Index(string slug, [FromQuery(Name =
"p")] int currentPage, int
pageSize)
{
if (!string.IsNullOrEmpty(slug))
{
var career = _context.Careers.FirstOrDefault(x =>
x.Slug.Equals(slug));
if (career != null)
{
ViewBag.CareerName = career.CareerName;
//var qr = _context.Careers.ToList();
var qr = (from p in
_context.CompanyCareers.Where(x => x.CareerId ==
career.ID)
from b in _context.Companies.Where(x =>
x.Id == p.CompanyId)
from i in
_context.IndustrialAreas.Where(x => x.ID ==
b.IndustrialAreaId).DefaultIfEmpty()
select new CompanyModelView()
{
Id = b.Id,
CompanyName = b.CompanyName,
BasicSalary = b.BasicSalary,
Allowance = b.Allowance,
DateCreate = b.DateCreate,
JobTitle = b.JobTitle,
Src = b.Src,
_IndustrialArea = i,
Address = b.Address,
Slug = b.Slug,
WorkTypes = (from tc in
_context.CompanyWorkTypes.Where(x =>
x.CompanyId == b.Id)
from type in
_context.WorkTypes.Where(x => x.Id
==
tc.TypeId)
select type)
}
).OrderByDescending(x => x.DateCreate).ToList();
// var worktype = (from w in
_context.CompanyWorkTypes.Where(x =>
x.CompanyId
== qr.))
var totalCate = qr.Count();
if (pageSize <= 0) pageSize = 10;
int countPages =
(int)Math.Ceiling((double)totalCate / pageSize);
if (currentPage > countPages)
currentPage = countPages;
if (currentPage < 1)
currentPage = 1;
var pagingModel = new PagingModel()
{
countpages = countPages,
currentpage = currentPage,
generateUrl = (pageNumber) =>
Url.Action(nameof(Index), new
{
p = pageNumber,
pageSize = pageSize
})
};
ViewBag.pagingModel = pagingModel;
ViewBag.totalPost = totalCate;
ViewBag.cateIndex = (currentPage - 1) * pageSize;
var companies = qr.Skip((currentPage - 1) *
pageSize)
.Take(pageSize).ToList();
ViewBag.JobCount = companies.Count();
//Set slider menu
var leftSlider = new LeftSliderModel()
{
Areas = new SelectList(_context.Areas,
nameof(Area.ID),
nameof(Area.NameArea)),
Careers = new SelectList(_context.Careers,
nameof(Career.ID),
nameof(Career.CareerName)),
WorkTypes = _context.WorkTypes.ToList(),
Experiences = _context.Experiences.ToList()
};
ViewBag.LeftSlider = leftSlider;
return View(companies);
}
}
return NotFound();
}

Property has value in View but appears as 0 in page

Currently I am trying to display a user's age but it appears as 0 in the page.
This is the View
<div class="col-xs-6 col-sm-4 overview-box">
<table class="table-responsive">
<tbody>
<tr>
<td class="overview-description-wrap">
<span class="overview-description">#translations["Player_Age"]</span>
</td>
<td class="overview-info hidden-xs" style="display:table-cell">
<span class="overview-info-lg">#Model.Age</span>
#if (Model.ShowDateOfBirth)
{
<span class="overview-info-sm">(#Model.BirthDate.ToString("dd.MM.yyyy"))</span>
}
</td>
<td class="overview-info hidden-lg hidden-sm hidden-md">
<span class="overview-info-lg">#Model.Age</span>
<br />
<span class="overview-info-sm">(#Model.BirthDate.ToString("dd.MM.yyyy"))</span>
</td>
</tr>
</tbody>
</table>
</div>
And this is the action that gets the values
public PlayerOverviewViewModel GetPlayerViewModel(int playerId, int sport, int country, int currentPlayerId = 0, int clubId = 0, string color = "")
{
PlayerOverviewViewModel result = new PlayerOverviewViewModel();
Nomenclatures.Sports currentsport = (Nomenclatures.Sports)sport;
Nomenclatures.Countries currentCountry = (Nomenclatures.Countries)country;
var state = LoadPlayerState(playerId, sport);
var finishedMatches = GetFinishedMatches(state, playerId, rankingId: 0).ToList();
var upcomingMatches = GetUpcomingMatches(state, playerId, currentPlayerId, 9).ToList();
var testMatches = ParseUpcomingChallenges(state, upcomingMatches);
var eventInvitations = new List<EventInvitationViewModel>();
var tournamentInvitations = GetTournamentInvitations(currentPlayerId);
var parsedInvitations = ParseTournamentInvitations(state, tournamentInvitations);
eventInvitations.AddRange(parsedInvitations);
var clubLeagueInvitations = GetClubLeagueInvitations(currentPlayerId);
parsedInvitations = ParseClubLeagueInvitations(state, clubLeagueInvitations);
eventInvitations.AddRange(parsedInvitations);
var playerRankings = state.PlayerRankings;
var rankingNames = _data.OrganisationRankings.GetRankingNames(playerRankings.Select(x => x.OrganisationRankingId.Value));
var player = state.CurrentPlayer;
int organizationId = state.CurrentPlayer.HomeClubId ?? 0;
var topRanking = GetPlayerRanking(state);
var playerCareerTopRanking = GetPlayerHighestStanding(state);
var playerCareerTopRankingDate = GetTopPlayerRankingDate(state);
var doubleCareerTopRanking = GetTopDoubleRanking(state, sport, country);
var doubleCareerTopRankingDate = GetTopDoubleRankingDate(state, sport, country);
var homeclub = player.Organisation ?? new Organisation();
var profileImg = _data.Images.PlayerImage(playerId);
var playerCareerWins = GetPlayerCareerWins(playerId, sport, state.Challenges);
var playerCurrentYearWins = GetPlayerCurrentYearWins(playerId, sport, state.Challenges);
var playerCareerLooses = GetPlayerCareerLooses(playerId, sport, state.Challenges);
var playerCurrentYearLosses = GetPlayerCurrentYearLooses(playerId, sport, state.Challenges);
var doublePlayerCurrentYearWins = GetDoublePlayerCurrentYearWins(playerId, sport);
var doublePlayerCareerLooses = GetDoublePlayerCareerLooses(state, sport);
var doubleCareerWins = GetDoubleCareerWins(state, sport);
var doublePlayerCurrentYearLooses = GetDoublePlayerCurrentYearLooses(state, sport);
var careerEventParticipations = GetAllEventsParticipations(playerId, sport, state.Challenges);
var currentYearEventParticipations = GetCurrentYearEventsParticipations(playerId, sport, state.Challenges);
var doubleCareerEventParticipations = GetDoubleCareerEventParticipations(state, sport);
var doubleCurrentYearEventParticipations = GetDoubleCurrentYearEventParticipations(state, sport);
var best3Wins = GetBest3Wins(state, playerId);
var singlePlayerHighestRankingCurrentYear = GetSinglePlayerHighestRankingForCurrentYear(state);
var doublePartnerInvitation = GetDoublePartnerInvitation(playerId);
//var playerUnavalability = this.GetPlayerSchedule(playerId);
string racquetName = player.GetRacket();
string shoesName = player.GetShoes();
result.Id = player.p_id;
result.Name = player.Name;
result.FirstName = player.FirstName;
result.MiddleName = player.MiddleName;
result.LastName = player.LastName;
result.Email = player.UserProfile.Email;
result.Address = player.PersonalInfo.pi_address;
result.BirthDate = player.PersonalInfo.pi_birth;
result.Age = DateHelper.GetAge(result.BirthDate);
result.Gender = player.PersonalInfo.pi_gender == 1 ? "Male" : "Female";
result.UserName = player.UserProfile.UserName;
result.Country = player.PersonalInfo.Country.Name;
result.CountryCode = player.PersonalInfo.Country.Short.ToLower();
result.RankingType = ((Nomenclatures.RankingTypes)topRanking.r_rankingtype).Description();
result.RankingClass = ((Nomenclatures.EventClasses)(topRanking.r_class ?? 1)).Description();
result.Points = topRanking.vPoints;
result.Level = topRanking.r_level ?? 1;
result.Standing = topRanking.vStanding;
result.HomeClub = string.IsNullOrEmpty(homeclub.Name) ? "No home club" : homeclub.Name;
result.ImageUrl = _manager.GetImageUrl(profileImg.img_id, Nomenclatures.ImageType.UserProfilePic);
result.ImageId = profileImg.img_id;
result.Racquet = racquetName;
result.Shoes = shoesName;
result.DominantHand = ((Nomenclatures.DominantHand)player.PersonalInfo.DominantHand).ToString();
result.BackHand = ((Nomenclatures.Backhand)player.PersonalInfo.Backhand).ToString();
result.Facebook = player.PersonalInfo.FacebookProfile;
result.Twitter = player.PersonalInfo.TwitterProfile;
result.WebSite = player.PersonalInfo.WebSite;
result.EmailVisible = player.PersonalInfo.pi_email_v;
result.ShowDateOfBirth = player.PersonalInfo.pi_birth_v || player.p_id == currentPlayerId;
//result.ScheduleDays = playerUnavalability.ScheduleDays;
//result.PlayerUnavalabilityVM = playerUnavalability;
result.PlayerCountryFlag = player.PersonalInfo.Country.Short.ToLower();
result.CareerWins = playerCareerWins;
result.GlobalEventsParticipatedSingles = careerEventParticipations;
result.EventsParticipatedSingles = currentYearEventParticipations;
result.CareerWinLossSingles = playerCareerWins + "-" + playerCareerLooses;
result.WinLossSingles = playerCurrentYearWins + "-" + playerCurrentYearLosses;
result.CareerWinLossDouble = doubleCareerWins + "-" + doublePlayerCareerLooses;
result.WinLossDoubles = doublePlayerCurrentYearWins + "-" + doublePlayerCurrentYearLooses;
result.GlobalEventsParticipatedDoubles = doubleCareerEventParticipations;
result.EventsParticipatedDoubles = doubleCurrentYearEventParticipations;
result.Best3Wins.Items = new List<ICarouselItem>(best3Wins);
result.CareerHighSingles = playerCareerTopRanking == 0 ? "-" : playerCareerTopRanking.ToString();
result.CareerHighDoubles = doubleCareerTopRanking == 0 ? "-" : doubleCareerTopRanking.ToString();
result.CareerHighDateSingles = playerCareerTopRankingDate;
result.CareerHighDateDoubles = doubleCareerTopRankingDate;
result.SinglesHighestRankingCurrentYear = singlePlayerHighestRankingCurrentYear == 0 ? "-" : singlePlayerHighestRankingCurrentYear.ToString();
result.DoublesHighestRankingCurrentYear = ""; //TODO: implement this
result.DoublePlayers = new List<DoublePartnersViewModel>();//TODO: implement this
result.PlayerRankings = playerRankings;
result.RankingNames = rankingNames;
result.CurrentSport = currentsport;
result.RankingCountry = currentCountry;
result.SportNumber = sport;
result.CountryNumber = country;
result.ParticipantType = (int)player.ParticipantType;
result.Class = player.p_class ?? 1;
result.DoubleInvitations = doublePartnerInvitation;
result.LastDonationDate = player.LastDonationDate;
int months;
int.TryParse(ConfigurationManager.AppSettings["donationPeriod"], out months);
result.IsDonated = player.LastDonationDate != null && player.LastDonationDate.Value.AddMonths(months) >= DateTime.UtcNow.Date;
var form = finishedMatches.OrderByDescending(x => x.Date).Take(5).Select(x => x.IsWon ? "W" : "L");
result.Form = form;
result.MatchesSection = new MatchesSectionVM
{
PlayerId = playerId,
CurrentPlayerId = currentPlayerId,
FinishedMatches = finishedMatches,
UpcomingMatches = testMatches,
UpcommingMatchesWatermark = !testMatches.Any(),
EventInvitations = eventInvitations,
FinishedMatchesWatermark = !finishedMatches.Any(),
LeftButtonName = "Confirm",
WatermarkMessage = "You dont have any matches to confirm. Create a challenge or join an event",
ShowButtons = currentPlayerId == playerId,
};
return result;
}
And this is the action that displays everything
[Authorize]
public ActionResult Index(int clubId = 0, string color = "")
{
if (mPlayerID == 0)
{
WebSecurity.Logout();
return RedirectToAction("login", "account", new { clubId, color });
}
var playerViewModel = _service.GetPlayerViewModel(mPlayerID, (int)mSport, (int)mCountry, mPlayerID, clubId, color);
playerViewModel.HasPhoto = _data.Images.PlayerHasPhoto(mPlayerID);
var profileCompletion = GetProfileCompletionPercents(playerViewModel);
playerViewModel.Id = mPlayerID;
playerViewModel.CurrentPlayerId = mPlayerID;
playerViewModel.DonationModel = new PayPalDonationModel(_data, mPlayerID);
playerViewModel.Languages = _cacheService.GetActiveLanguages();
ViewBag.ProfileCompletion = profileCompletion.Item1;
ViewBag.CompletionNext = profileCompletion.Item2;
return View(playerViewModel);
}
The only things that don't appear are the birth date and the user's age. Any suggestions ? Debugger shows that the properties have values in the View.

export all rows of a html table with pagenation to excel sheet

I have one html table where pagenation is used. So it displays 10 rows once. When i am exporting my table to a excel, only the first 10 rows which are there in the html table are getting exported. I want all the rows to be exported. Please suggest some way.
Below is the code I am using.
function exportToExcel(){
var mytable = document.getElementById("tlb_setup");
var rowCount = mytable.rows.length;
var colCount = mytable.getElementsByTagName("tr")[0].getElementsByTagName("th").length;
var ExcelApp = new ActiveXObject("Excel.Application");
ExcelApp.Workbooks.Open("........\\requestsInExcel.xlsx");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelApp.Visible = true;
//var ExcelSheet = ExcelApp.Worksheets("Sheet1");
//ExcelSheet.Application.Visible = true;
for (var i = 0; i < rowCount; i++) {
for (var j = 0; j < colCount; j++) {
if (i == 0) {
str = mytable.getElementsByTagName("tr")[i].getElementsByTagName("th")[j].innerText;
}
else {
str = mytable.getElementsByTagName("tr")[i].getElementsByTagName("td")[j].innerText;
}
ExcelApp.ActiveSheet.Cells(i + 1, j + 1).Value = str;
//Workbook.SaveAs("........\\requestsInExcel.xlsx");
}
}
//ExcelApp.ActiveWorkbook.Save();
ExcelApp.ActiveSheet.columns.autofit;
ExcelSheet.Application.Visible = true;
DisplayAlerts = true;
}

Trouble with nested Json data

I'm having a ton of trouble trying to access the nested json data (pasted at the bottom). I'm able write:
var dataResults = jsonResult["data"] as NSDictionary
In order to create a dictionary containing the data within "data", however, Xcode will not allow me to call on anything within "data" such as the information within "current_condition". I've tried to make current_condition it's own dictionary like so:
var results = dataResults["current_condition"] as NSDictionary
But it would seem that this is turning up as nil
I have also attempted accessing using the standard method for calling nested loops:
var dataResults = jsonResult["data"]["current_condition"] as NSDictionary
But this results in a compiler error.
Any help? Much appreciated!
Json data:
{
data = {
"current_condition" = (
{
cloudcover = 0;
humidity = 68;
"observation_time" = "01:39 AM";
precipMM = "0.0";
pressure = 1017;
"temp_C" = 20;
"temp_F" = 68;
visibility = 10;
weatherCode = 143;
weatherDesc = (
{
value = Mist;
}
);
weatherIconUrl = (
{
value = "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0006_mist.png";
}
);
winddir16Point = NE;
winddirDegree = 50;
windspeedKmph = 7;
windspeedMiles = 4;
}
);
request = (
{
query = "London, United Kingdom";
type = City;
}
);
weather = (
{
date = "2014-07-25";
precipMM = "1.5";
tempMaxC = 27;
tempMaxF = 81;
tempMinC = 14;
tempMinF = 57;
weatherCode = 353;
weatherDesc = (
{
value = "Light rain shower";
}
);
weatherIconUrl = (
{
value = "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0009_light_rain_showers.png";
}
);
winddir16Point = NE;
winddirDegree = 54;
winddirection = NE;
windspeedKmph = 15;
windspeedMiles = 10;
},
{
date = "2014-07-26";
precipMM = "5.8";
tempMaxC = 28;
tempMaxF = 83;
tempMinC = 16;
tempMinF = 61;
weatherCode = 176;
weatherDesc = (
{
value = "Patchy rain nearby";
}
);
weatherIconUrl = (
{
value = "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0009_light_rain_showers.png";
}
);
winddir16Point = NNE;
winddirDegree = 12;
winddirection = NNE;
windspeedKmph = 11;
windspeedMiles = 7;
},
{
date = "2014-07-27";
precipMM = "0.2";
tempMaxC = 26;
tempMaxF = 80;
tempMinC = 13;
tempMinF = 55;
weatherCode = 116;
weatherDesc = (
{
value = "Partly Cloudy";
}
);
weatherIconUrl = (
{
value = "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png";
}
);
winddir16Point = NW;
winddirDegree = 321;
winddirection = NW;
windspeedKmph = 14;
windspeedMiles = 9;
},
{
date = "2014-07-28";
precipMM = "1.9";
tempMaxC = 26;
tempMaxF = 78;
tempMinC = 12;
tempMinF = 54;
weatherCode = 116;
weatherDesc = (
{
value = "Partly Cloudy";
}
);
weatherIconUrl = (
{
value = "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png";
}
);
winddir16Point = N;
winddirDegree = 351;
winddirection = N;
windspeedKmph = 13;
windspeedMiles = 8;
},
{
date = "2014-07-29";
precipMM = "0.0";
tempMaxC = 28;
tempMaxF = 82;
tempMinC = 16;
tempMinF = 60;
weatherCode = 113;
weatherDesc = (
{
value = Sunny;
}
);
weatherIconUrl = (
{
value = "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0001_sunny.png";
}
);
winddir16Point = NNW;
winddirDegree = 329;
winddirection = NNW;
windspeedKmph = 13;
windspeedMiles = 8;
}
);
};
}
Oddly enough, I have a sample weather app that I converted to Swift. I get my data elsewhere, but I found this library to be a great way to deal with JSON in Swift: https://github.com/dankogai/swift-json/. Much cleaner and easier.
It's because the subscript in Dictionary returns an optional:
subscript (key: KeyType) -> ValueType?
Meaning you have to unwrap the optional before you can downcast:
let dataResults = jsonResult["data"]! as NSDictionary
let results = dataResults["current_condition"]! as NSDictionary
As of Beta 3 you can access the value directly without downcasting, like this:
let dataResults = jsonResult["data"]!
let results = dataResults["current_condition"]
However I would suggest you wrap it around an if-let to make sure you don't unwrap nil values.