How to define a multidimension array from different classes - c#

I am trying to create object with values and a multidimensional array from a second classes. What I created:
class ProductData
{
private ProductPrices[] prices;
public string ParentName { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string TechnicalDescription { get; set; }
public bool Obsolete { get; set; }
public bool Deleted { get; set; }
public string Innercarton { get; set; }
public string Outercarton { get; set; }
public string Package { get; set; }
public string Barcode { get; set; }
public decimal Weight { get; set; }
public decimal EndUserPrice { get; set; }
public int MOQ { get; set; }
public bool ComingSoon { get; set; }
public bool NewProduct { get; set; }
public string Equivalent { get; set; }
public string ReplacedBy { get; set; }
public ProductPrices[] Prices
{
get
{
return prices;
}
set
{
prices = value;
}
}
public List<ProductFeatures> Feature { get; set; }
public List<string> Specification { get; set; }
public List<string> Image { get; set; }
public string File { get; set; }
public string Icon { get; set; }
}
class ProductFeatures
{
public string Feature;
}
public class ProductPrices
{
public decimal Price;
public int MinQuantity;
public DateTime validuntil;
public string currency;
}
Now I would like to have for the ProductPrices an multidimensional array.
So, at the end I would have something like this:
Dictionary<string, ProductData> productInfo = new Dictionary<string, ProductData>();
//Adding data to productInfo
string productName = productInfo.Name;
string description = productInfo.Description;
decimal wholesalePrice = productInfo.ProductPrices[0].Price;
int minQty = productInfo.ProductPrices[0].MinQuantity;
Somewhere I'm missing something. I've been searching around for hours trying to find it but unfortunally...
Thanks in advance!

I already found it.
Remove the private ProductPrices[] prices; and change the
public ProductPrices[] Prices
{
get
{
return prices;
}
set
{
prices = value;
}
}
to
public ProductPrices[] Prices { get; set; }
After that, you can do:
ProductData prData = new ProductData();
prData.ParentName = "Parent name";
prData.Name = "Some name";
prData.Prices = new ProductPrices[enterArrayCount];
ProductPrices prdPrices = new ProductPrices();
prdPrices.Price = Convert.ToDecimal(yourDecimalValue);
prdPrices.MinQuantity = 8;
prdPrices.Currency = "Eur";
prData.Prices[firstIndex] = prdPrices; //So firstIndex must increase after a value has been set.

Related

C# Linq set merged lists as datasource

I'm currently merging to lists will be the datasource of a gridview. This is my code:
// Get models
var products = await API.Zelkon.Products.GetAll();
var productsCurrencies = await API.Zelkon.CurrenciesBackend.Get();
// Merge lists
var results = products.Item1.Zip(productsCurrencies.Item1, (x, y) => new Tuple<Models.Products, Models.Zelkon.CurrenciesBackend>(x, y));
// Create datasource
var datasource = results.Select(r => new { r.Item2.price, r.Item2.setup_fee, r.Item1.product_number });
GridProducts.DataSource = datasource;
// GridProducts.VisibleColumns("name");
UI.CustomizeGridDefault(GridProducts);
My problem is that the value of r.Item2.setup_fee is always the value of the first row. I have checked the collection and the data is correct there.
Am I doing something wrong?
Below are the structures:
class CurrenciesBackend
{
public string currency_name { get; set; }
public string currency_code { get; set; }
public double price { get; set; }
public double recommended_price { get; set; }
public double setup_fee { get; set; }
public int product_number { get; set; }
}
class Products
{
public string name { get; set; }
public string description { get; set; }
public string invoice_layout { get; set; }
public string layout_number { get; set; }
public string payment_terms_name { get; set; }
public string payment_terms_number { get; set; }
public DateTime creation_date { get; set; }
public int enabled { get; set; }
public int is_subscription { get; set; }
public int is_delivery_required { get; set; }
public int allow_discount { get; set; }
public int allow_trial { get; set; }
public int max_discount { get; set; }
public int max_discount_duration { get; set; }
public int vat_percentage { get; set; }
public int trial_period { get; set; }
public int binding_period { get; set; }
public int days_of_credit { get; set; }
public int unit { get; set; }
public string allowed_country_codes { get; set; }
public int product_number { get; set; }
public int authorize_invoice { get; set; }
}
Thanks in advance

Linq To object returns 0 values

I'm trying to get some data from to Lists using Linq. If I use join with equals using one field in each list it's ok and returns number of records as expected, but if I try use join on pair of fields it returns 0 records. Why?
List<Result> inner_join =
(from egais in rests_egais
//join best in rests_best on egais.Product.AlcCode equals best.Product.AlcCode
join best in rests_best
on new {key1 = egais.Shop, key2 = egais.Product.AlcCode}
equals new { key1 = best.Shop, key2 = best.Product.AlcCode }
where egais.Quantity != best.Quantity
select new Result
{
Shop = egais.Shop,
AlcCode = egais.Product.AlcCode,
FullName = egais.Product.FullName,
Quantity_Egais = egais.Quantity,
Quantity_Best = best.Quantity,
Difference = best.Quantity - egais.Quantity
}).ToList();
EDITED: These are classes to use:
public class Rest
{
public Rest()
{
Product = new Product();
}
public string Shop { get; set; }
public DateTime Date { get; set; }
public double Quantity { get; set; }
public string InformF1RegId { get; set; }
public string InformF2RegId { get; set; }
public Product Product { get; set; }
}
public class Product
{
public Product()
{
Producer = new Producer();
}
public string FullName { get; set; }
public string AlcCode { get; set; }
public double Capacity { get; set; }
public string UnitType { get; set; }
public double AlcVolume { get; set; }
public int ProductVCode { get; set; }
public Producer Producer { get; set; }
}
public class Producer
{
public string ClientRegId { get; set; }
public string FullName { get; set; }
public string ShortName { get; set; }
public int Country { get; set; }
public string Description { get; set; }
}
public class Result
{
public string Shop { get; set; }
public string AlcCode { get; set; }
public string FullName { get; set; }
public double Quantity_Egais { get; set; }
public double Quantity_Best { get; set; }
public double Difference { get; set; }
}

I need to parse json result in windows phone app c#

Im new in developing windows phone app --> i have problem so i have tried all the possible solutions but with no vain:-
the application tried to take result from webservice the result come back like this:-
{"d":"{\"sessionid\":null,\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":1,\"PriceChangedTimer\":20,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":true,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"HS Dev\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1234\",\"Username\":\"obeidat\",\"LastTickTime\":\"\/Date(1396613678728)\/\",\"SelectedAccount\":12345791,\"Name\":0,\"CompanyName\":\"HS Dev\",\"UserId\":579,\"DemoClient\":\"0\",\"FName\":\"obeidat\",\"SName\":null,\"TName\":null,\"LName\":null,\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"0\",\"AlertSms\":\"0\",\"Temp\":null,\"GMTOffset\":\"5\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"0\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Thanks for using our platform##We will inform you here with any private news\",\"DealerTreePriv\":1}"}
so i have tried to parse it but it give me errors after that i have tried locally removed the {"d":" and \"LastTickTime\":\"\/Date(1396613678728)\/\" from the string with no connection to webservice and its working fine i use this code :-
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
//Json classes
public class OuterRootObject
{
public string d { get; set; }
}
public class Globals
{
public bool MultiSessionsAllowed { get; set; }
public int CommCalcType { get; set; }
public int PriceChangedTimer { get; set; }
public int ValidLotsLocation { get; set; }
public bool CustumizeTradeMsg { get; set; }
public object FirstWhiteLabeledOffice { get; set; }
public int DealerTreePriv { get; set; }
public int ClientConnectTimer { get; set; }
public int ClientTimeoutTimer { get; set; }
public double DefaultLots { get; set; }
public string WebSecurityID { get; set; }
public int ServerGMT { get; set; }
}
public class VersionInfo
{
public int Rel { get; set; }
public int Ver { get; set; }
public int Patch { get; set; }
public int ForceUpdate { get; set; }
public int UpdateType { get; set; }
public Globals Globals { get; set; }
}
public class SystemLockInfo
{
public int MinutesRemaining { get; set; }
public int HoursRemaining { get; set; }
public int DaysRemaining { get; set; }
public int Maintanance { get; set; }
public int WillBeLocked { get; set; }
}
public class RootObject
{
public string sessionid { get; set; }
public VersionInfo VersionInfo { get; set; }
public SystemLockInfo SystemLockInfo { get; set; }
public string FirstWhiteLabel { get; set; }
public string WLID { get; set; }
public bool CheckWhiteLabel { get; set; }
public string Password { get; set; }
public string Username { get; set; }
public DateTime LastTickTime { get; set; }
public int SelectedAccount { get; set; }
public int Name { get; set; }
public object ServicePath { get; set; }
public string GWSessionID { get; set; }
public string IP { get; set; }
public string SessionDateStart { get; set; }
public string CompanyName { get; set; }
public string UserId { get; set; }
public string DemoClient { get; set; }
public string FName { get; set; }
public string SName { get; set; }
public string TName { get; set; }
public string LName { get; set; }
public object Sms { get; set; }
public string isReadOnly { get; set; }
public string SchSms { get; set; }
public string AlertSms { get; set; }
public object Temp { get; set; }
public string GMTOffset { get; set; }
public string SvrGMT { get; set; }
public object ClientType { get; set; }
public string EnableNews { get; set; }
public string PublicSlideNews { get; set; }
public string PrivateSlideNews { get; set; }
public int DealerTreePriv { get; set; }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var jsonString =
"{\"sessionid\":null,\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":1,\"PriceChangedTimer\":20,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":true,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"HS Dev\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1234\",\"Username\":\"obeidat\",\"SelectedAccount\":12345791,\"Name\":0,\"CompanyName\":\"HS Dev\",\"UserId\":-579,\"DemoClient\":\"0\",\"FName\":\"obeidat\",\"SName\":null,\"TName\":null,\"LName\":null,\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"0\",\"AlertSms\":\"0\",\"Temp\":null,\"GMTOffset\":\"5\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"0\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Thanks for using our platform##We will inform you here with any private news\",\"DealerTreePriv\":1}";
RootObject jsonObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
MessageBox.Show("hello " + jsonObject.Username + "" + jsonObject.UserId);
int val1 = Convert.ToInt16(jsonObject.UserId);
if (val1 > 0)
MessageBox.Show("You are logedin");
else
{
MessageBox.Show("Sorry Please login");
}
}
// // Create a new button and set the text value to the localized string from AppResources.
// ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
// appBarButton.Text = AppResources.AppBarButtonText;
// ApplicationBar.Buttons.Add(appBarButton);
// // Create a new menu item with the localized string from AppResources.
// ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
// ApplicationBar.MenuItems.Add(appBarMenuItem);
//}
}
}
Please help me to parse all of the json result (locally i mean without conection to web)and what is the code to do that.
thank you all
First, your JSON is all a string property of "D". You can't deserialize it to RootClass. Second, your JSON contains invalid escape characters in the LastTickTime area. I removed both of these, and the JSON parses without errors of any kind. I just used a console app to test it.
var s = "{\"sessionid\":null,\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":1,\"PriceChangedTimer\":20,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":true,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"HS Dev\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1234\",\"Username\":\"obeidat\",\"SelectedAccount\":12345791,\"Name\":0,\"CompanyName\":\"HS Dev\",\"UserId\":579,\"DemoClient\":\"0\",\"FName\":\"obeidat\",\"SName\":null,\"TName\":null,\"LName\":null,\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"0\",\"AlertSms\":\"0\",\"Temp\":null,\"GMTOffset\":\"5\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"0\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Thanks for using our platform##We will inform you here with any private news\",\"DealerTreePriv\":1}";
var foo = JsonConvert.DeserializeObject<RootObject>(s);
Console.WriteLine(foo.UserId); // Writes 579
UPDATE
If you have no control over what you get back, do the following:
Take the response and get rid of the / combination. As such:
string webResponse = "your long web response from the server";
webResponse = webResponse.Replace(#"\/", "/");
// If dynamic isn't in the phone subset, you'll need a class here containing "d" as a string.
var jsonOuter = JsonConvert.DeserializeObject<dynamic>(webResponse);
var jsonInner = JsonConvert.DeserializeObject<RootObject>(jsonOuter.d);
if (jsonInner.UserId > .....)

cannot implicitly convert type System.Collections.Generic.List<char>

I am trying to create a list of customer names that is fetched from a Json call but I get an error:
cannot implicitly convert type System.Collections.Generic.List<char>
to System.Collections.Generic.List<string>
I am using these 2 classes:
Customers:
namespace eko_app
{
static class Customers
{
public static List<CustomerResponse> GetCustomers(string customerURL)
{
List<CustomerResponse> customers = new List<CustomerResponse>();
try
{
var w = new WebClient();
var jsonData = string.Empty;
// make the select products call
jsonData = w.DownloadString(customerURL);
if (!string.IsNullOrEmpty(jsonData))
{
// deserialize the json to c# .net
var response = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(jsonData);
if (response != null)
{
customers = response.response;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return customers;
}
public class BusinessAssociate
{
public string business_associate_id { get; set; }
public string created_by { get; set; }
public DateTime created { get; set; }
public DateTime modified { get; set; }
public bool? deleted { get; set; }
public string business_id { get; set; }
public string identity_id { get; set; }
public string associate_type { get; set; }
public string name { get; set; }
}
public class Identity
{
public string identity_id { get; set; }
public string created_by { get; set; }
public DateTime created { get; set; }
public DateTime modified { get; set; }
public bool? deleted { get; set; }
public string name { get; set; }
public object identity_type { get; set; }
}
public class ChartOfAccount
{
public string chart_of_accounts_id { get; set; }
public DateTime created { get; set; }
public DateTime modified { get; set; }
public string created_by { get; set; }
public string deleted { get; set; }
public string account_id { get; set; }
public string account_name { get; set; }
public string business_id { get; set; }
public string account_category { get; set; }
public string accounts_groups_id { get; set; }
public string cash_equivalent { get; set; }
public string acc_category { get; set; }
public decimal? balance { get; set; }
public decimal? credit_balance { get; set; }
public decimal? debit_balance { get; set; }
public decimal? absolute_balance { get; set; }
public string balance_type { get; set; }
public decimal? raw_balance { get; set; }
public string extended_name { get; set; }
public string normal_balance_type { get; set; }
}
public class CustomerResponse
{
public BusinessAssociate BusinessAssociate { get; set; }
public Identity Identity { get; set; }
public ChartOfAccount ChartOfAccount { get; set; }
}
public class Messages
{
public string msgs { get; set; }
public string errs { get; set; }
}
public class RootObject
{
public List<CustomerResponse> response { get; set; }
public Messages messages { get; set; }
}
}
}
HomeForm:
private void GetCustomerNameList()
{
// get customers
customerURL = "https://eko-app.com/BusinessAssociate/list_associates/1/sessionId:" + sessionID + ".json";
var customers = Customers.GetCustomers(customerURL);
List<string> customerNames = new List<string>();
foreach (var c in customers)
{
customerNames = c.BusinessAssociate.name.ToList(); <--------error thrown here
}
}
The error is thrown at customerNames = c.BusinessAssociate.name.ToList(); on the HomeForm.
What am I doing wrong in creating a list of customer names?
I think you wanted to add all Customer.BusinessAssociate names to list:
foreach (var c in customers)
{
customerNames.Add(c.BusinessAssociate.name);
}
What you originally written converted each name string to char list.
You're assigning a list of chars (string) into a list of strings.
Try something like this outside of the foreach loop:
customerNames = customers.Select(x => x.BusinessAssociate.name).ToList();
This also makes the initialization of cutomerNames redundant.
Instead of foreach use:
customerNames = customers.Select(c => c.BusinessAssociate.name).ToList();

Using Linq to pass data from one collection to another

I want to use LINQ to pass data from one custom collection to another. Its complicated because the collection has 2 sub collections.
Want to copy data to:
public class Quote
{
public int Id { get; set; }
public string Type { get; set; }
public virtual ICollection<Rate> Rates { get; set; }
}
public class Rate
{
public int Id { get; set; }
public virtual ICollection<Option> Options { get; set; }
}
public class Option
{
public int Id { get; set; }
public decimal Price { get; set; }
}
from:
public class Quote
{
public int QuoteId { get; set; }
public string Type { get; set; }
public string Destination { get; set; }
public List<RateSet> RateSets { get; set; }
}
public class RateSet
{
public int Id { get; set; }
public decimal ValueMin { get; set; }
public decimal ValueMax { get; set; }
public List<Option> Options { get; set; }
}
public class Option
{
public int Id { get; set; }
public string Name { get; set; }
public decimal? Price { get; set; }
}
I was getting somewhere with this but keeping hitting problems...
newQuotes = Quotes
.Select(x => new Quote() {
Id = x.QuoteId,
Rates = x.RateSets.Select( y => new Rate() {
Id = y.Id,
Options = y.Options.Select(z => new Option() {
Id = z.Id,
Price = z.Price
}).ToList(),....
to
Compiled without any errors
// to
public class Quote2
{
public int Id { get; set; }
public string Type { get; set; }
public virtual ICollection<Rate> Rates { get; set; }
}
public class Rate
{
public int Id { get; set; }
public virtual ICollection<Option2> Options { get; set; }
}
public class Option2
{
public int Id { get; set; }
public decimal Price { get; set; }
}
// from
public class Quote1
{
public int QuoteId { get; set; }
public string Type { get; set; }
public string Destination { get; set; }
public List<RateSet> RateSets { get; set; }
}
public class RateSet
{
public int Id { get; set; }
public decimal ValueMin { get; set; }
public decimal ValueMax { get; set; }
public List<Option1> Options { get; set; }
}
public class Option1
{
public int Id { get; set; }
public string Name { get; set; }
public decimal? Price { get; set; }
}
void Main()
{
var Quotes = new List<Quote1>();
var newQuotes = Quotes
.Select(x => new Quote2 {
Id = x.QuoteId,
Rates = x.RateSets == null ? null : x.RateSets.Select( y => new Rate {
Id = y.Id,
Options = y.Options == null ? null : y.Options.Select(z => new Option2 {
Id = z.Id,
Price = z.Price.Value
}).ToList()}).ToList()}).ToList();
}
I would make it a bit more modular:
newQuotes = Quotes.Select(x => new Quote
{
ID = x.QuoteID,
Type = x.Type,
Rates = ConvertRates(x.RateSets)
});
ConvertRates would use the same approach to create its sub objects and could either be a method or a Func:
ICollection<Rate> ConvertRates(IEnumerable<RateSet> oldRates)
{
return oldRates.Select(x => new Rate
{
ID = x.ID,
Options = ConvertOptions(x.Options)
}).ToList();
}
Basically, this is the same approach you used, just split up and readable.
I think what you need to do is define casting between each two corresponding classes, then cast one list into the other.
A simpler way may be to create methods in each class that would convert itself to the other type. Or if you don't want that kind of coupling, create a factory class that will do the conversion for you, one item at a time. Then use link to loop through and convert each item.
Like so:
public class Quote
{
public int Id { get; set; }
public string Type { get; set; }
public virtual ICollection<Rate> Rates { get; set; }
public static Quote FromData(Data.Quote input){
if (input == null) return null;
Quote output = new Quote()
{
Id = input.QuoteId,
Type = input.Type
};
output.Rates = (from i in input.RateSets
select Rate.FromData(i)).ToList();
}
}
public class Rate
{
public int Id { get; set; }
public virtual ICollection<Option> Options { get; set; }
public static Rate FromData(Data.RateSet input)
{
if (input == null) return null;
Rate output = new Rate()
{
Id = input.Id
};
output.Options = (from i in input.Options
select Option.FromData(i)).ToList();
return output;
}
}
public class Option
{
public int Id { get; set; }
public decimal Price { get; set; }
public static Option FromData(Data.Option input)
{
if (input == null) return null;
Option output = new Option()
{
Id = input.Id,
Price = input.Price ?? 0m
};
return output;
}
}
namespace Data {
public class Quote
{
public int QuoteId { get; set; }
public string Type { get; set; }
public string Destination { get; set; }
public List<RateSet> RateSets { get; set; }
}
public class RateSet
{
public int Id { get; set; }
public decimal ValueMin { get; set; }
public decimal ValueMax { get; set; }
public List<Option> Options { get; set; }
}
public class Option
{
public int Id { get; set; }
public string Name { get; set; }
public decimal? Price { get; set; }
}
}

Categories