How to pass a different objects to the same function - c#

I'm a little bit lost with dynamic data and I will like your help. This is what I'm trying to do:
I have the following Classes:
public class SmsMessage : MessageCommonDefinition
{
public string MessageServiceKey { get; set; }
public string MessageAttachments { get; set; }
public bool MessageBodyUseTemplate { get; set; }
public string MessageBodyTemplate { get; set; }
public string MessageBodyTemplateValues { get; set; }
public bool ValidateWithCarrier { get; set; }
public bool IncludeCarrierInfo { get; set; }
}
public class EmailMessage : MessageCommonDefinition
{
public string MessageDisplayName { get; set; }
public string MessageCc { get; set; }
public string MessageBcc { get; set; }
public string MessageSubject { get; set; }
public bool MessageIsBodyHtml { get; set; }
public bool MessageBodyUseTemplate { get; set; }
public string MessageBodyTemplate { get; set; }
public string MessageBodyTemplateValues { get; set; }
public bool IsConfidential { get; set; }
public string MessageAttachments { get; set; }
public MailPriority MessagePriority { get; set; }
}
public abstract class MessageCommonDefinition
{
public Guid MessageId { get; set; }
public string CompanyCode { get; set; }
public string MessageCode { get; set; }
public string MessageChannelCode { get; set; }
public string MessageTo { get; set; }
public string MessageFrom { get; set; }
public string MessageBody { get; set; }
public string ChannelName { get; set; }
}
I also have a method to fill a template that receives, among other parameters, the type of message to fill the template (EmailMessage, SmSMessage, etc.)
This is the method:
if (triggerGroup.ToUpper().ToUpper() == AppSettingsKeys.External.ToString().ToUpper())
{
List<PassengerTemplateEntity> passengerTemplateEntity = ACARSRepository.GetPassengerTemplateValues(emailMessage.MessageId);
var passengerTemplateValues = DynamicClassBuilder.BuildObject();
foreach (PassengerTemplateEntity passengerTemplate in passengerTemplateEntity)
{
passengerTemplateValues.AddProperty(passengerTemplate.FieldName, passengerTemplate.FieldData);
}
message.Body = Smart.Format(File.ReadAllText(attFilePath), passengerTemplateValues);
message.Subject = emailMessage.IsConfidential ? SettingsManager.GetAppSettingValue(AppSettingsKeys.ConfidentialKey, "-secmsg-")
+ " " + Smart.Format(emailMessage.MessageSubject.Trim(), passengerTemplateValues) : Smart.Format(emailMessage.MessageSubject.Trim(), passengerTemplateValues);
}
else if (triggerGroup.ToUpper() == AppSettingsKeys.Internal.ToString().ToUpper())
{
alertTemplateValues = CoreRepository.GetExceptionMessage(emailMessage.MessageCode);
if (alertTemplateValues != null)
{
message.Body = Smart.Format(File.ReadAllText(attFilePath), alertTemplateValues);
message.Subject = Smart.Format(emailMessage.MessageSubject.Trim(), alertTemplateValues);
}
else
{
alertTemplateValues = CoreRepository.GetExceptionMessage("E127");
throw new ArgumentException(Smart.Format("BlackBox.{0}: [Exception Code: {1}] {2}", alertTemplateValues.ShortName, alertTemplateValues.ExceptionCode, alertTemplateValues.ExceptionMessage), "ExceptionMessageCode: " + emailMessage.MessageCode, new ArgumentException());
}
}
else
{
alertTemplateValues = CoreRepository.GetExceptionMessage("E123");
throw new ArgumentException(Smart.Format("BlackBox.{0}: [Exception Code: {1}] {2}", alertTemplateValues.ShortName, alertTemplateValues.ExceptionCode, alertTemplateValues.ExceptionMessage), "TriggerGroup: " + triggerGroup, new ArgumentException());
}
As you can see the method uses the emailMessage to retrieve values. What I want to achieve is to use this as a shared function. I want to send a generic parameter regardless it is an emailMessage or a SmsMessage and use the function by sending a generic object and fill the correct class with the correct value.

Related

How to use json.net to Deserialize a nested class?

I have the following class
public class CallbackResultsJson
{
public class CallbackResults
{
public string Status { get; set; }
public string Message { get; set; }
public string Data { get; set; }
public string Log { get; set; }
public string StatusText { get; set; }
public string TransactionToken { get; set; }
}
}
I am trying to use Json.Net to Deserialize requestbody but I am always getting a null for status,data. any ideas why ?
var requestbody =#"
{
"CallbackResults":
{
"TransactionToken":"b65524-qwe",
"Status":0,
"Message":"Publish Application to QaLevel Operation Completed",
"Data":[],
"Log":["sucess"
},
"RequestNumber":"REQ1234"
}"
var TransactionResult = JsonConvert.DeserializeObject<CallbackResultsJson.CallbackResults>(requestBody);
Just a little bit of change should be done.
Your class:
public class CallbackResultsJson
{
public CallbackResultsClass CallbackResults { get; set; }
public string RequestNumber { get; set; }
public class CallbackResultsClass
{
public int Status { get; set; }
public string Message { get; set; }
public string[] Data { get; set; }
public string Log { get; set; }
public string TransactionToken { get; set; }
}
}
Your data:
var requestbody = #"
{
""CallbackResults"":
{
""TransactionToken"":""b65524-qwe"",
""Status"":0,
""Message"":""Publish Application to QaLevel Operation Completed"",
""Data"":[""Data1"", ""Data2""],
""Log"":""sucess""
},
""RequestNumber"":""REQ1234""
}";
var result = JsonConvert.DeserializeObject<CallbackResultsJson>(requestbody);
Your class needs to have a property of the sub-type,
public class CallbackResultsJson
{
public CallBackResults CallbackResults { get; set; }
public string RequestNumber { get; set; )
public class CallbackResults
{
public string Status { get; set; }
public string Message { get; set; }
public string Data { get; set; }
public string Log { get; set; }
public string StatusText { get; set; }
public string TransactionToken { get; set; }
}
}
var result = JsonConvert.DeserializeObject<CallbackResultsJson>(requestBody);
I have used json2csharp.com to convert requestbody to c# classes and it generated these classes.it worked
public class CallbackResults
{
public string TransactionToken { get; set; }
public int Status { get; set; }
public string Message { get; set; }
public List<string> Data { get; set; }
public List<string> Log { get; set; }
}
public class CallbackResultsRootObj
{
public CallbackResults VdiCallbackResults { get; set; }
public string RequestNumber { get; set; }
}
var vdiTransactionResult = JsonConvert.DeserializeObject<CallbackResultsRootObj>(requestBody);

Parse response of Form Data in C#

type=CREATE
resource=transaction
number_of_attempts=1
data={"id":"11e7df5131dd9820bf774044","payment_method":"cc","account_vault_id":null,"recurring_id":null,"first_six":"411111","last_four":"1111","account_holder_name":" MALCOLM BLACK","transaction_amount":"1.00","description":null,"transaction_code":null,"avs":null,"batch":"2","order_num":"798279608211","verbiage":"APPROVAL","transaction_settlement_status":null,"effective_date":null,"routing":null,"return_date":null,"created_ts":1513092547,"modified_ts":1513092547,"transaction_api_id":null,"terms_agree":null,"notification_email_address":null,"notification_email_sent":true,"response_message":null,"auth_amount":"1.00","auth_code":"df5132","status_id":101,"type_id":20,"location_id":"11e7c499daaff1f0a7507909","reason_code_id":1000,"contact_id":"11e7c619b69d209ab41b24dc","billing_zip":"","billing_street":null,"product_transaction_id":"11e7c499db893b0489bb3739","tax":"0.000","customer_ip":null,"customer_id":null,"po_number":null,"avs_enhanced":"V","cvv_response":"N","billing_phone":null,"billing_city":null,"billing_state":null,"clerk_number":null,"tip_amount":"0.00","created_user_id":"11e7c499dac79026a4e740f1","modified_user_id":"11e7c499dac79026a4e740f1","settle_date":null,"charge_back_date":null,"void_date":null,"account_type":"visa","is_recurring":false,"is_accountvault":false,"transaction_c1":null,"transaction_c2":null,"transaction_c3":null,"additional_amounts":[],"terminal_serial_number":null,"entry_mode_id":"K","terminal_id":null,"quick_invoice_id":null,"emv_receipt_data":null}
This is the Form data i am receiving in C# using
string data=Request.Form("data");
Now data is nested how can i get the values of data object. Parsing it in json using JsonConvert.Deserialize is throwing exception.
The original response is:
type=CREATE&resource=transaction&number_of_attempts=1&data=%7b%22id%22%3a%2211e7df5131dd9820bf774044%22%2c%22payment_method%22%3a%22cc%22%2c%22account_vault_id%22%3anull%2c%22recurring_id%22%3anull%2c%22first_six%22%3a%22411111%22%2c%22last_four%22%3a%221111%22%2c%22account_holder_name%22%3a%22+MALCOLM+BLACK%22%2c%22transaction_amount%22%3a%221.00%22%2c%22description%22%3anull%2c%22transaction_code%22%3anull%2c%22avs%22%3anull%2c%22batch%22%3a%222%22%2c%22order_num%22%3a%22798279608211%22%2c%22verbiage%22%3a%22APPROVAL%22%2c%22transaction_settlement_status%22%3anull%2c%22effective_date%22%3anull%2c%22routing%22%3anull%2c%22return_date%22%3anull%2c%22created_ts%22%3a1513092547%2c%22modified_ts%22%3a1513092547%2c%22transaction_api_id%22%3anull%2c%22terms_agree%22%3anull%2c%22notification_email_address%22%3anull%2c%22notification_email_sent%22%3atrue%2c%22response_message%22%3anull%2c%22auth_amount%22%3a%221.00%22%2c%22auth_code%22%3a%22df5132%22%2c%22status_id%22%3a101%2c%22type_id%22%3a20%2c%22location_id%22%3a%2211e7c499daaff1f0a7507909%22%2c%22reason_code_id%22%3a1000%2c%22contact_id%22%3a%2211e7c619b69d209ab41b24dc%22%2c%22billing_zip%22%3a%22%22%2c%22billing_street%22%3anull%2c%22product_transaction_id%22%3a%2211e7c499db893b0489bb3739%22%2c%22tax%22%3a%220.000%22%2c%22customer_ip%22%3anull%2c%22customer_id%22%3anull%2c%22po_number%22%3anull%2c%22avs_enhanced%22%3a%22V%22%2c%22cvv_response%22%3a%22N%22%2c%22billing_phone%22%3anull%2c%22billing_city%22%3anull%2c%22billing_state%22%3anull%2c%22clerk_number%22%3anull%2c%22tip_amount%22%3a%220.00%22%2c%22created_user_id%22%3a%2211e7c499dac79026a4e740f1%22%2c%22modified_user_id%22%3a%2211e7c499dac79026a4e740f1%22%2c%22settle_date%22%3anull%2c%22charge_back_date%22%3anull%2c%22void_date%22%3anull%2c%22account_type%22%3a%22visa%22%2c%22is_recurring%22%3afalse%2c%22is_accountvault%22%3afalse%2c%22transaction_c1%22%3anull%2c%22transaction_c2%22%3anull%2c%22transaction_c3%22%3anull%2c%22additional_amounts%22%3a%5b%5d%2c%22terminal_serial_number%22%3anull%2c%22entry_mode_id%22%3a%22K%22%2c%22terminal_id%22%3anull%2c%22quick_invoice_id%22%3anull%2c%22emv_receipt_data%22%3anull%7d
UPDATE:
try
{
string data = #Request.Form.Get("data");
//now data=
//{"id":"11e7df5131dd9820bf774044","payment_method":"cc","account_vault_id":n//ull.....}
//data = '"' + data + '"';
var stringfy = JsonConvert.DeserializeObject(data);
File.WriteAllText(path, " File Data : " + Request.Form +
Environment.NewLine + " --------------------Total Value 0 " + Request.Form.Keys[0].ToString()
+ Environment.NewLine + " --------------------Total Value 1 " + Request.Form.Keys[1].ToString()
+ Environment.NewLine + " --------------------Total Value 2 " + Request.Form.Keys[2].ToString()
+ Environment.NewLine + " --------------------Total Value 3 " + data);
}
catch (Exception ex)
{
File.WriteAllText(path, "Exception :1 "+ex.Message.ToString());
}
Code is deployed on server so writing exceptions to file but, no code after Deserialize statement is working and no file is being created.
There is a shortcut. You can use this website as a helper - http://json2csharp.com/
All you need to do is past this string {"id":"11e7d...} then click generate.
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
// using QuickType;
//
// var data = Welcome.FromJson(jsonString);
//
namespace QuickType
{
using System;
using System.Net;
using System.Collections.Generic;
using Newtonsoft.Json;
public partial class Welcome
{
[JsonProperty("account_holder_name")]
public string AccountHolderName { get; set; }
[JsonProperty("account_type")]
public string AccountType { get; set; }
[JsonProperty("account_vault_id")]
public object AccountVaultId { get; set; }
[JsonProperty("additional_amounts")]
public object[] AdditionalAmounts { get; set; }
[JsonProperty("auth_amount")]
public string AuthAmount { get; set; }
[JsonProperty("auth_code")]
public string AuthCode { get; set; }
[JsonProperty("avs")]
public object Avs { get; set; }
[JsonProperty("avs_enhanced")]
public string AvsEnhanced { get; set; }
[JsonProperty("batch")]
public string Batch { get; set; }
[JsonProperty("billing_city")]
public object BillingCity { get; set; }
[JsonProperty("billing_phone")]
public object BillingPhone { get; set; }
[JsonProperty("billing_state")]
public object BillingState { get; set; }
[JsonProperty("billing_street")]
public object BillingStreet { get; set; }
[JsonProperty("billing_zip")]
public string BillingZip { get; set; }
[JsonProperty("charge_back_date")]
public object ChargeBackDate { get; set; }
[JsonProperty("clerk_number")]
public object ClerkNumber { get; set; }
[JsonProperty("contact_id")]
public string ContactId { get; set; }
[JsonProperty("created_ts")]
public long CreatedTs { get; set; }
[JsonProperty("created_user_id")]
public string CreatedUserId { get; set; }
[JsonProperty("customer_id")]
public object CustomerId { get; set; }
[JsonProperty("customer_ip")]
public object CustomerIp { get; set; }
[JsonProperty("cvv_response")]
public string CvvResponse { get; set; }
[JsonProperty("description")]
public object Description { get; set; }
[JsonProperty("effective_date")]
public object EffectiveDate { get; set; }
[JsonProperty("emv_receipt_data")]
public object EmvReceiptData { get; set; }
[JsonProperty("entry_mode_id")]
public string EntryModeId { get; set; }
[JsonProperty("first_six")]
public string FirstSix { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("is_accountvault")]
public bool IsAccountvault { get; set; }
[JsonProperty("is_recurring")]
public bool IsRecurring { get; set; }
[JsonProperty("last_four")]
public string LastFour { get; set; }
[JsonProperty("location_id")]
public string LocationId { get; set; }
[JsonProperty("modified_ts")]
public long ModifiedTs { get; set; }
[JsonProperty("modified_user_id")]
public string ModifiedUserId { get; set; }
[JsonProperty("notification_email_address")]
public object NotificationEmailAddress { get; set; }
[JsonProperty("notification_email_sent")]
public bool NotificationEmailSent { get; set; }
[JsonProperty("order_num")]
public string OrderNum { get; set; }
[JsonProperty("payment_method")]
public string PaymentMethod { get; set; }
[JsonProperty("po_number")]
public object PoNumber { get; set; }
[JsonProperty("product_transaction_id")]
public string ProductTransactionId { get; set; }
[JsonProperty("quick_invoice_id")]
public object QuickInvoiceId { get; set; }
[JsonProperty("reason_code_id")]
public long ReasonCodeId { get; set; }
[JsonProperty("recurring_id")]
public object RecurringId { get; set; }
[JsonProperty("response_message")]
public object ResponseMessage { get; set; }
[JsonProperty("return_date")]
public object ReturnDate { get; set; }
[JsonProperty("routing")]
public object Routing { get; set; }
[JsonProperty("settle_date")]
public object SettleDate { get; set; }
[JsonProperty("status_id")]
public long StatusId { get; set; }
[JsonProperty("tax")]
public string Tax { get; set; }
[JsonProperty("terminal_id")]
public object TerminalId { get; set; }
[JsonProperty("terminal_serial_number")]
public object TerminalSerialNumber { get; set; }
[JsonProperty("terms_agree")]
public object TermsAgree { get; set; }
[JsonProperty("tip_amount")]
public string TipAmount { get; set; }
[JsonProperty("transaction_amount")]
public string TransactionAmount { get; set; }
[JsonProperty("transaction_api_id")]
public object TransactionApiId { get; set; }
[JsonProperty("transaction_c1")]
public object TransactionC1 { get; set; }
[JsonProperty("transaction_c2")]
public object TransactionC2 { get; set; }
[JsonProperty("transaction_c3")]
public object TransactionC3 { get; set; }
[JsonProperty("transaction_code")]
public object TransactionCode { get; set; }
[JsonProperty("transaction_settlement_status")]
public object TransactionSettlementStatus { get; set; }
[JsonProperty("type_id")]
public long TypeId { get; set; }
[JsonProperty("verbiage")]
public string Verbiage { get; set; }
[JsonProperty("void_date")]
public object VoidDate { get; set; }
}
public partial class Welcome
{
public static Welcome FromJson(string json) => JsonConvert.DeserializeObject<Welcome>(json, Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this Welcome self) => JsonConvert.SerializeObject(self, Converter.Settings);
}
public class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
};
}
}

How to implement different class types within one variable?

I have 3 object classes:
public class MessageData
{
public string MessageID { get; set; }
public string Date { get; set; }
public bool IsSent { get; set; }
public string EmployeeInfo { get; set; }
}
public class MultiMessageData
{
public string MessageID { get; set; }
public string Date { get; set; }
public bool IsSent { get; set; }
public byte MessageType { get; set; }
public string MessageType { get; set; }
public string Platform { get; set; }
public string EmployeeInfo { get; set; }
}
public class SocialData
{
public string MessageID { get; set; }
public string Date { get; set; }
public bool IsSent { get; set; }
public bool IsReceived { get; set; }
public byte MessageType { get; set; }
public string MessageType { get; set; }
public string Message { get; set; }
public string UserName { get; set; }
}
Then I have a function right now that only implement the MessageData class:
public void SendData()
{
List<MessageData> data = new List<MessageData>();
// some work here with data variable...
_sendRepository.Send(data);
}
Now what I need is to keep most of the logic but a way that I can instantiate a variable that can be of any class type for example:
public void SendData()
{
var data;
if(logic == 1){
data = new List<MessageData>();
} else if(logic == 2){
data = new List<MultiMessageData>();
}else {
data = new List<SocialData>();
}
// some work here...
// if I do that then this Send method I will change it to be a Generic T maybe.
_sendRepository.Send(data);
}
Any clue?
Inheritance is the way to go:
public class MessageDataBase
{
public string MessageID { get; set; }
public string Date { get; set; }
public bool IsSent { get; set; }
}
public class MessageData : MessageDataBase
{
public string EmployeeInfo { get; set; }
}
public class MultiMessageData : MessageDataBase
{
public byte MessageType { get; set; }
public string MessageTypeString { get; set; }
public string Platform { get; set; }
public string EmployeeInfo { get; set; }
}
public class SocialData : MessageDataBase
{
public bool IsReceived { get; set; }
public byte MessageType { get; set; }
public string MessageTypeString { get; set; }
public string Message { get; set; }
public string UserName { get; set; }
}
Use an interface, but you will have to make common changes in the //..do some work here section
public interface IMessageData
{
//Example required function for all MessageData classes
void SetDate(DateTime date);
void SetIsSent(bool date);
}
public abstract class BaseMessageData : IMessageData
{
public string MessageID { get; set; }
public string Date { get; set; }
public bool IsSent { get; set; }
public BaseMessageData(string messageID)
{
MessageID=messageID;
}
public void SetDate(DateTime date)
{
Date = date.ToString("MM/dd/yyyy");
}
public void SetIsSent(bool sentStatus)
{
IsSent = sentStatus;
}
}
public class MessageData : BaseMessageData, IMessageData
{
public string EmployeeInfo { get; set; }
}
public class MultiMessageData : MessageData,IMessageData
{
public byte MessageType { get; set; }
public string MessageType { get; set; }
public string Platform { get; set; }
}
public class SocialData : BaseMessageData, IMessageData
{
public bool IsReceived { get; set; }
public byte MessageType { get; set; }
//Can't have to properties named the same.
//public string MessageType { get; set; }
public string Message { get; set; }
public string UserName { get; set; }
}
Then in your SendData
public void SendData()
{
List<IMessageData> data;
if (logic == 1)
{
data = new List<MessageData>();
}
else if (logic == 2)
{
data = new List<MultiMessageData>();
}
else
{
data = new List<SocialData>();
}
// some work here...
foreach (var d in data)
{
//Only methods that will work are ones declared in the IMessageData interface
d.SesDate(DateTime.Now);
d.SetIsSent(true);
}
// if I do that then this Send method I will change it to be a Generic T maybe.
_sendRepository.Send(data);
}
You can use my open source library, OneOf https://github.com/mcintyre321/OneOf
A OneOf is a special Type which can hold one value from a range of Types, like a Discriminated Union in F#. It provides an alternative to using inheritance/polymorphism.
You would write your method like this:
public void SendData()
{
OneOf<List<MessageData>, List<MultiMessageData>, List<SocialData>> data = null;
if(logic == 1){
data = new List<MessageData>();
} else if(logic == 2){
data = new List<MultiMessageData>();
}else {
data = new List<SocialData>();
}
// some work here...
_sendRepository.Send(data);
}
Or you could have var data = List<OneOf<MessageData, MultiMessageData, SocialData>>(); if you prefer, especially if you want to have different
Types in the list.
install-package OneOf
It supports net451 and netstandard1.6

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();

Categories