Why am I getting the last element of the list? - c#

Here is the GET REQUEST
var destname = textBox1.Text;
var client1 = new RestClient("https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/autosuggest/v1.0/UK/GBP/en-GB/?query=" + destname);
var request1 = new RestRequest(Method.GET);
request1.AddHeader("x-rapidapi-key", "");
request1.AddHeader("x-rapidapi-host", "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com");
IRestResponse response1 = client1.Execute(request1);
var results = JsonConvert.DeserializeObject<DestinationName>(response1.Content);
And here is the classes
public partial class Place1
{
public string PlaceId { get; set; }
public string PlaceName { get; set; }
public string CountryId { get; set; }
public string RegionId { get; set; }
public string CityId { get; set; }
public string CountryName { get; set; }
}
public partial class DestinationName
{
public List<Place1> Places { get; set; }
}
When I do what is below I should be getting ES-sky which is the first element of the list but for some reason it gives me the last element of the list.
foreach (var a in results.Places)
{
label1.Text = a.PlaceId;
}
Here is the list
ES-sky
BCN-sky
ALC-sky
AGP-sky
MAD-sky
PMI-sky
IBZ-sky
TENE-sky
TFS-sky
TFN-sky
How would I adapt the code so that my output is ES-sky and not TFN-sky.

You are looping through the list, every time its writing value to "label1.Text". Use SingleOrDefault()/FirstOrDefault(). Dont use foreach loop.
Example:
var firstValue=results.Places.FirstOrDefault();
label1.Text = firstValue.PlaceId;

Instead of iterating through the loop here:
foreach (var a in results.Places)
{
label1.Text = a.PlaceId;
}
Just get the first value with appropriate validation:
if(results.Places != null && results.Places.Any())
{
var result = results.Places.First();
label1.Text = a.PlaceId;
}

You can bind only first place data in list from server side and get it on client side OR
bind FirstorDefault method to get first place data from list in client side.

Related

How to use lambda expression to access correct data type?

I am using lambda expression to access values with data type, but the problem I have data type for Time as Time(7) on my local database and using Entity Framework. On my model this data type is define as DateTime.
How do I now access this data type to be time?
This is my code:
public List GetIncident_Details()
{
Entities incident = new Entities();
List result = new List();
var c_incident = incident.Incident_Template.Select(c => c).ToList();
if (c_incident != null && c_incident.Count() > 0)
{
foreach (var cData in c_incident)
{
Incident_DropDown model = new Incident_DropDown();
model.Title = cData.Title;
model.Description = cData.Description;
model.Date_Occurred = cData.Date_Occurred;
// How do I change this to have access?
// It's complaining about the data type object being set to a string?
model.Time = cData.Time;
model.Assignment_Group = cData.Assignment_Group;
model.Reported_CI = cData.Reported_CI;
result.Add(model);
}
}
return result;
}
public class Incident_DropDown
{
public string Title { get; set; }
public string Description { get; set; }
public string Date_Occurred { get; set; }
public DateTime Time { get; set; } // Time
public string Assignment_Group { get; set; }
public string Reported_CI { get; set; }
}
Took some advice from #alexey-rumyantsev, then had to test my code by interrogating model data type for Time it was Date Time, then change to Timespan. While testing this data type compare to my local database record and it was passing correct vales when debugging.
// Model name
public class Incident_DropDown
{
public string Title { get; set; }
public string Description { get; set; }
public string Date_Occured { get; set; }
public TimeSpan Time { get; set; } // had to change to work
public string Assignment_Group { get; set; }
public string Reported_CI { get; set; }
}
// Controller
public List<Incident_DropDown> GetIncident_Details()
{
Entities incident = new Entities();
List<Incident_DropDown> result = new List<Incident_DropDown>();
var c_incident = incident.Incident_Template.Select(c => c).ToList();
if (c_incident != null && c_incident.Count() > 0)
{
foreach (var cData in c_incident)
{
Incident_DropDown model = new Incident_DropDown();
model.Title = cData.Title;
model.Description = cData.Description;
model.Date_Occured = cData.Date_Occured;
model.Time = cData.Time; // This here enable to pass correct time as per database record
model.Assignment_Group = cData.Assignment_Group;
model.Reported_CI = cData.Reported_CI;
result.Add(model);
}
}
return result;
}

How to apply lazy loading to bing ListView in windows store app?

I am working on Sales App of Windows Store app. I want to apply lazy loading for my product module.
When Product page open it get product from backend and show in ListBox control.
It takes time everytime to load. I think main reason is when I check for the image exists on given url.
Here is my code and class:
private async Task getAllProductDetails()
{
var resultproductlist = await client.PostAsync(session.Values["URL"] + "/magemobpos/product/getProductList", contents);
if (resultproductlist.IsSuccessStatusCode)
{
string trys = resultproductlist.Content.ReadAsStringAsync().Result;
List<Productlistdata> objProducts = JsonConvert.DeserializeObject<ProductlistResponse>(trys).productlistdata;
Productlistdata Product;
//all product are in objProducts
foreach (var item in objProducts)
{
bool imageexist = false;
//check if image exist on given url or not
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(item.image.ToString()));
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
int imagelength = Convert.ToInt32(response.ContentLength);
if (imagelength > 0)
imageexist = true;
else
imageexist = false;
}
}
catch (Exception)
{
imageexist = false;
}
//if image not exist, it get default image
if (item.image.ToString().ToLower().Equals("n/a") || imageexist == false)
{
item.image = "Images/NoDataImages/ico-no-orders.png";
}
Product = new Productlistdata()
{
image = item.image,
name = item.name,
price = item.price,
sku = item.sku,
type = item.type[0],
id = item.id
};
//add all product in lstProduct. lstProduct is ListBox Control
lstProduct.Items.Add(Product);
}
}
}
Class:
public class Productlistdata
{
public string id { get; set; }
public string sku { get; set; }
public string name { get; set; }
public string status { get; set; }
public string qty { get; set; }
public string price { get; set; }
public string image { get; set; }
public string type { get; set; }
public string full_productname { get; set; }
}
Can anybody suggest me how to apply lazy loading? I don't know exactly but I think it can apply to bind image once the list is loaded.
I know that you dint ask for it but I ll strongly suggest you to look into Bindings I believe it will help you a lot thinking what you are trying to build. So I ll start by changing some of your code using bindings and then go to the real solution.
Here is what you can try and do:
First remove this code:
bool imageexist = false;
//check if image exist on given url or not
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(item.image.ToString()));
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
int imagelength = Convert.ToInt32(response.ContentLength);
if (imagelength > 0)
imageexist = true;
else
imageexist = false;
}
}
catch (Exception)
{
imageexist = false;
}
Second Step is to get rid of this code
//add all product in lstProduct. lstProduct is ListBox Control
lstProduct.Items.Add(Product);
Now add on top of you page.xaml.cs an ObservableCollection
private ObservableCollection<Productlistdata> productlist = new ObservableCollection<Productlistdata>();
public ObservableCollection<Productlistdata> Productlist
{
get { return productlist ?? (productlist= new ObservableCollection<Productlistdata>()); }
set { productlist= value; }
}
Now you either bind that list in the list box like this
<ListBox ItemsSource="{Binding Productlist}"/>
or In the Contractor of your page do
lstProduct.ItemsSource = Productlist;
That way Productlist is binded to your ListBox and when you add or remove items will it will be updated automatically.
Now you can skip all the above but I suggest you to look into Bindings it powerfull and will solve many of your problems when you get the idea of they work.
Now we will add the first code we removed in your ProductListdata
public class Productlistdata
{
public string id { get; set; }
public string sku { get; set; }
public string name { get; set; }
public string status { get; set; }
public string qty { get; set; }
public string price { get; set; }
public string image { get; set; }
public string type { get; set; }
public string full_productname { get; set; }
public async void CheckImage()
{
bool imageexist = false;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(image));
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
int imagelength = Convert.ToInt32(response.ContentLength);
if (imagelength > 0)
imageexist = true;
else
imageexist = false;
}
}
catch (Exception)
{
imageexist = false;
}
if (!imageexist)
{
image = "Images/NoDataImages/ico-no-orders.png";
}
}
}
And populate your List
private async Task getAllProductDetails()
{
var resultproductlist = await client.PostAsync(session.Values["URL"] + "/magemobpos/product/getProductList", contents);
if (resultproductlist.IsSuccessStatusCode)
{
string trys = resultproductlist.Content.ReadAsStringAsync().Result;
List<Productlistdata> objProducts = JsonConvert.DeserializeObject<ProductlistResponse>(trys).productlistdata;
//all product are in objProducts
foreach (var item in objProducts)
{
Productlistdata Product = new Productlistdata()
{
image = item.image,
name = item.name,
price = item.price,
sku = item.sku,
type = item.type[0],
id = item.id
};
Product.CheckImage();
Productlist.Add(Product);
}
}
}
Product.CheckImage(); will not be awaited. So the Items in the list will load really fast because nothing is awaited in the foreach loop. Product.CheckImage(); will run on another thread at later time.
Finally because image might change after the data is loaded on the ListBoxa(when image wasnt fount) you will have to Notify the UI that a property has changed. To do that you will have to use INotifyPropertyChanged. You can take a look in an other answer of mine how to do that here
I would suggest changing your queries,
firstly instead of getAllProductDetails do getAllProductID
so where you have
var resultproductlist = await client.PostAsync(session.Values["URL"] + "/magemobpos/product/getProductList", contents);
if (resultproductlist.IsSuccessStatusCode)
{
string trys = resultproductlist.Content.ReadAsStringAsync().Result;
List<Productlistdata> objProducts = JsonConvert.DeserializeObject<ProductlistResponse>(trys).productlistdata;
Productlistdata Product;
you would do
var resultproductlist = await client.PostAsync(session.Values["URL"] + "/magemobpos/product/getProductID", contents);
if (resultproductlist.IsSuccessStatusCode)
{
string trys = resultproductlist.Content.ReadAsStringAsync().Result;
List<int> objProducts = JsonConvert.DeserializeObject<ProductlistResponse>(trys).productlistdata;
LazyProductlistdata Product;
secondly create a wrapper
public LazyProductlistdata
{
public string id { get; set; }
private Lazy<Productlistdata> data = new Lazy<Productlistdata>(()=>Productlistdata.CreateFromID(id));
public Productlistdata Data
{
get{return data.Value;}
}
}
expand this so the wrapper contains information required for sorting
finally alter the constructor or create a factory for Productlistdata so that it obtains the individual record from the source
public class Productlistdata
{
public static Productlistdata CreateFromID(int id)
{
//Return single Productlistdata from webservice
}
}
NOTE: lazy loading will increase the overall load time, the advantange is that instead of it being 1 huge block of time its several smaller ones
I would suggest using Converter to supply placeholder see here.
You can also decorate Image.Source binding with IsAsync = True - so that main thread would not be blocked
You can use ImageFailed event to assign image placeholder
foreach (var item in objProducts)
{
var bitmap = new BitmapImage();
bitmap.ImageFailed += (s, e) => bitmap.UriSource = defaultImageUri;
bitmap.UriSource = new Uri(item.image);
item.Add(bitmap);
//set decodepixelwidth and dicodepixelheight correctly to avoid outofmemory exception
}

How to pass a cookie value string array to the controller to get looped as PayPal Items

I'm trying to pass my CookieCarts string array (containing shopping cart items) into my controller to get looped for my Paypal api.
My View
var cookiecart = Server.UrlDecode(Request.Cookies["cookieCart"].Value);
#Html.HiddenFor(m => m.CookieCart, new { Value = cookiecart })
Response.Write(cookiecart);
cookiecart:*[{"datetime":"2016-02-25 02:51:49","id":"749","typeid":"13","qty":1,"fullname":"The Matrix","image":"/Content/images/products/online-video.png","price":"69","sku":"MATRIX"}]*
My Model
public string CookieCart { get; set; }
My Controller
var cartArray = model.CookieCart;
var cartArray = model.CookieCart;
var itemArray = cartArray.Split(',');
foreach (var t in itemArray)
{item.name = itemArray[0]; }
when i quickwatch the data sent to the controller it looks like this:
cartArray displays: "[{\"datetime\":\"2016-02-25 02:51:49\",\"id\":\"749\",\"typeid\":\"13\",\"qty\":1,\"fullname\":\"The Matrix\",\"image\":\"/Content/images/products/online- video.png\",\"price\":\"69\",\"sku\":\"MATRIX\"}]"
item.name displays: *"[{\"datetime\":\"2016-02-25 02:51:49\""*
None of this is right. its so frustrating! How to convert a cookie array value into a C# array.
itemArray[0] should be:
itemArray[0][0] = datetime:"2016-02-25 02:51:49",
itemArray[0][1] = id:"749",
itemArray[0][2] = typeid:"13",
itemArray[0][3] = qty:1,
itemArray[0][4] = fullname:"The Matrix",
itemArray[0][5] = image:"/Content/images/products/online-video.png",
itemArray[0][6] = price:"69"
itemArray[0][7] = sku:"MATRIX"
:(
ok i figured it out. using JSON .Net:
My Controller
var cookie = Request.Cookies["cookieCart"];
cookieArray = JsonConvert.DeserializeObject<List<CookieCart>>
(Server.UrlDecode(cookie.Value));
My Model
public class CookieCart
{
public DateTime Datetime { get; set; }
public int Id { get; set; }
public int Typeid { get; set; }
public string Qty { get; set; }
public string Fullname { get; set; }
public string Image { get; set; }
public string Price { get; set; }
public string Sku { get; set; }
}
then i iterated the array items for PayPal:
foreach (var cartitem in cookiecart)
{
item.name = cartitem.Fullname;
item.currency = "USD";
item.price = cartitem.Price;
item.quantity = cartitem.Qty;
item.sku = cartitem.Sku;
var intPrice = Int32.Parse(cartitem.Price);
subtotal = subtotal + intPrice;
}

Linq List within a list to string

Im trying to do a single linq statement, the following works but want to do it within a single statement.
public class ClientProducts
{
public string To { get; set; }
public string ClientFullName { get; set; }
public string ClientFirstName { get; set; }
public string ProductNames{ get; set; }
}
var list =
clients.Select(
client =>
new ClientProducts()
{
To = client.TelephoneMobile,
ClientFirstName = client.FirstName,
ClientFullName = client.FullName,
//ProductNames= client.Products.Select(p=>p.Name)<-this is what I want
}).ToList();
string productName= string.Empty;
foreach (var client in clients)
{
foreach (var p in client.Products)
{
productName+= Name+ ",";
}
}
replace
//ProductNames= client.Products.Select(p=>p.Name)
with
ProductNames = string.Join(",", client.Products.Select(p=>p.Name))

Entity to LINQ upload CSV file where single rows can have multiple values in columns

I'm currently working on parsing a csv file that was exported by another application. This application exported the data in a strange way. This export is from accoutning and it looks similar to this..
I'm trying to figure out a way to read the csv file, then split up the multiple 'All Accounts' values and 'Amt' Values so that M200 and 300.89 is another entry, M300 and 400.54 are another entry, and M400 and 100.00 are another entry. So after inserting this single row into the database, I should actually have 4 rows like so..
This is how I'm currently reading and inserting into the database.
List<RawData> data = new List<RawData>();
try
{
string text = File.ReadAllText(lblFileName.Text);
string[] lines = text.Split('\n');
int total = 0, reduced = 0;
foreach (string line in lines)
{
RawData temp = new RawData(line);
total++;
if (!(temp.FirstAccount.Length == 0 || temp.FirstAccount == "1ST-ACCT-NO"))
{
reduced++;
data.Add(temp);
}
}
}
catch (IOException ex)
{
Console.WriteLine("Unable to read file. " + ex.ToString());
MessageBox.Show(ex.ToString());
}
try
{
foreach (RawData rData in data)
{
tCarsInTransit cit = new tCarsInTransit
{
FIRST_ACCT_NO = rData.FirstAccount,
ACCOUNT_NO_DV = rData.AccountNoDv,
ACCT_NO = rData.AcctNo,
ACCT_NO_L = rData.AccNoL,
ACCT_NUM_DV = rData.AcctNumDv,
ACCT_PFX = rData.AcctPfx,
ACCT_PFX_PRT = rData.AcctPfxPrt,
ACCT_TYPE_DV = rData.AcctTypeDv,
ADV_NO = rData.AdvNo,
ALL_PRT_FLAG = rData.AllPrtFlag,
AMT = rData.Amt,
AMT_GLE = rData.AmtGle,
BASE_GLE = rData.BaseGle,
CNT_CAT = rData.CntCat,
COLD_PRT_FLAG = rData.ColdPrtFlag,
COST_DV = rData.CostDv,
COST_OVRD_FLAG_DV = rData.CostOvrdFlagDv,
CR_ACCT_DV = rData.CrAcctDv,
CR_ACCT_DV_GLE = rData.CrAcctDvGle,
CROSS_POSTING_FLAG = rData.CrossPostingFlag,
CROSS_POST_CAT = rData.CrossPostCat,
CTRL_NO = rData.CtrlNo,
CTRL_TYPE_DV = rData.CtrlTypeDv,
DESC_REQD_DV = rData.DescReqdDv,
DR_ACCT_DV = rData.DrAcctDv,
GL_DIST_ACCT_DV = rData.GLDistAcctDv,
GL_DIST_DV = rData.GLDistDv,
GRP_NO_DV = rData.GrpNoDv,
ID_PORT_DATE_TIME_FMT_CAT = rData.IdPortDateTimeFmtCat,
INACTIVITY_DV = rData.InactivityDv,
JOIN_COL = rData.JoinCol,
JRNL_DATE = rData.JrnlDate,
JRNL_PFX = rData.JrnlPfx
};
tCIT.tCarsInTransits.Add(cit);
tCIT.SaveChanges();
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "Finished uploading. ";
}
}
catch (DbEntityValidationException ex)
{
foreach (var eve in ex.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
I am not sure how to accomplish this. The above currently inserts the csv file into Sql Server the exact way the csv file was exported. Any ideas would greatly be appreciated! Thanks!
EDIT: Here is the RawData class.
class RawData
{
public string FirstAccount { get; set; }
public string AccountNoDv { get; set; }
public string AcctNo { get; set; }
public string AccNoL { get; set; }
public string AcctNumDv { get; set; }
public string AcctPfx { get; set; }
public string AcctPfxPrt { get; set; }
public string AcctTypeDv { get; set; }
public string AdvNo { get; set; }
public string AllPrtFlag { get; set; }
public string Amt { get; set; }
public string AmtGle { get; set; }
public string BaseGle { get; set; }
public string CntCat { get; set; }
public string ColdPrtFlag { get; set; }
public string CostDv { get; set; }
public string CostOvrdFlagDv { get; set; }
public string CrAcctDv { get; set; }
public string CrAcctDvGle { get; set; }
public string CrossPostingFlag { get; set; }
public string CrossPostCat { get; set; }
public string CtrlNo { get; set; }
public string CtrlTypeDv { get; set; }
public string DescReqdDv { get; set; }
public string DrAcctDv { get; set; }
public string GLDistAcctDv { get; set; }
public string GLDistDv { get; set; }
public string GrpNoDv { get; set; }
public string IdPortDateTimeFmtCat { get; set; }
public string InactivityDv { get; set; }
public string JoinCol { get; set; }
public string JrnlDate { get; set; }
public string JrnlPfx { get; set; }
public RawData(string csvString)
{
string[] citData = csvString.Replace(", ", "").Replace(".,", ".").Split(',');
try
{
FirstAccount = citData[0];
AccountNoDv = citData[1];
AcctNo = citData[2];
AccNoL = citData[3];
AcctNumDv = citData[4];
AcctPfx = citData[5];
AcctPfxPrt = citData[6];
AcctTypeDv = citData[7];
AdvNo = citData[8];
AllPrtFlag = citData[9];
Amt = citData[10];
AmtGle = citData[11];
BaseGle = citData[12];
CntCat = citData[13];
ColdPrtFlag = citData[14];
CostDv = citData[15];
CostOvrdFlagDv = citData[16];
CrAcctDv = citData[17];
CrAcctDvGle = citData[18];
CrossPostingFlag = citData[19];
CrossPostCat = citData[20];
CtrlNo = citData[21];
CtrlTypeDv = citData[22];
DescReqdDv = citData[23];
DrAcctDv = citData[24];
GLDistAcctDv = citData[25];
GLDistDv = citData[26];
GrpNoDv = citData[27];
IdPortDateTimeFmtCat = citData[28];
InactivityDv = citData[29];
JoinCol = citData[30];
JrnlDate = citData[31];
JrnlPfx = citData[32];
}
catch (Exception ex)
{
Console.WriteLine("Something went wrong. " + ex.ToString());
}
}
}
EDIT 2: AllAccounts in the images is acutally 'AccountNoDv' and there are actually many different fields that have multiples like 'AccountNoDv'(AllAccounts) but we might be removing those as this is not a final export. As of right now the two fields I'm worried most about are AccountNoDv and Amt.
Try something like this:
foreach (string line in lines)
{
RawData temp = new RawData(line);
var AllAccounts = temp.AccountNoDv.split(' ');
var Amts = temp.Amt.split(' ');
if (AllAccounts.Length() == Amts.Length() && Amts.Length() > 1) {
// We have multiple values!
reduced++;
for (int i = 0; i < AllAccounts.Length(); i++) {
RawData temp2 = RawDataCopy(temp); // Copy the RawData object
temp2.AccountNoDv = AllAccounts[i];
temp2.Amt = Amts[i];
total++;
data.Add(temp2);
}
}
else {
total++;
if (!(temp.FirstAccount.Length == 0 || temp.FirstAccount == "1ST-ACCT-NO"))
{
reduced++;
data.Add(temp);
}
}
}
And:
private RawData RawDataCopy(RawData copyfrom) {
// Write a function here that returns an exact copy from the one provided
// You might have to create a parameterless constructor for RawData
RawData RawDataCopy = new RawData();
RawDataCopy.FirstAccount = copyfrom.FirstAccount;
RawDataCopy.AccountNoDv = copyfrom.AccountNoDv;
RawDataCopy.AcctNo = copyfrom.AcctNo;
// . . . . . . . .
RawDataCopy.JrnlPfx = copyfrom.JrnlPfx;
return RawDataCopy;
}
Then also add a parameterless constructor to your RawData class:
public RawData()
{
}
Perhaps it would be sexier to implement the ICloneable interface and call the Clone() function instead of the RawDataCopy function, but it gets the idea across.
In Linq you can use SelectMany to increase the number of elements in a list. Here is a rough example of how this could be done. I make the assumption that the number of sub elements in AllAccounts and Amt is the same. A more robust solution would check for these issues.
So after you have loaded your data list:
var expandedData =
data.SelectMany(item =>
// split amount (will just return one item if no spaces)
item.Amt.Split(" ".ToCharArray())
// join this to the split of all accounts
.Zip(item.AllAccounts.Split(" ".ToCharArray()),
// return the joined item as a new anon object
(a,b) => new { amt=a, all=b }),
// take the original list item and the anon object and return our new item
(full,pair) => { full.Amt = pair.amt; full.AllAccounts = pair.all; return full; }));
You will now have a list of your data items with the multiple items expanded into the list.
I don't have test data to test so I might have some minor typos -- but I put in lots of comments to make the Linq as clear as possible.
Here is is simple example I wrote in LinqPad for myself to make sure I understood how SelectMany worked:
string [] list = { "a b c d","e","f g" };
var result = list.SelectMany((e) =>
e.Split(" ".ToCharArray()),
(o,item) => new { org = o, item = item}).Dump();

Categories

Resources