.Json not reading a line of the text file - c#-4.0

the problem is that the DOB is not taking any values from the text file, when I print out the DOB it does not give me the date of birth of the subjects that I have in the text file.
This code is in C# with the framework “Newtonsoft.Json”. Please help
using System;
using System.IO;
using Newtonsoft.Json;
namespace Ejercicio_1
{
//MoviStar class
public class MovieStar
{
//variables to store data
public DateTime DOB { get; set; }
public string name { get; set; }
public string surname { get; set; }
public string sex { get; set; }
public string nationality { get; set; }
/// Calculate Age
public int calcAge()
{
int daynow = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
int dob = int.Parse(DOB.ToString("yyyyMMdd"));
int ans= (daynow - dob) / 10000;
return ans;
}
}
}
MovieStarDriver:
using System;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Ejercicio_1
{
internal class MovieStarDriver
{
static void Main(string[] args)
{
// used StreamReader to read file content
StreamReader s = new StreamReader(#"C:\Users\Mengueche\Documents\Task_1\input.txt");
string jsonString = s.ReadToEnd();
// objects list of MovieStar class
List<MovieStar> objs = JsonConvert.DeserializeObject<List<MovieStar>>(jsonString);
// iterate through the list of objects and display results
foreach (MovieStar star in objs)
{
Console.WriteLine(star.name + " " + star.surname);
Console.WriteLine(star.sex);
Console.WriteLine(star.nationality);
Console.WriteLine(star.calcAge() + " years old");
Console.WriteLine();
}
Console.ReadKey();
}
}
}

Related

How to get the current cache/document (Sales Order/Shipment) outside the context of a graph

I'm currently implementing a new carrier method and would like to access additional information on the Shipment/Sales Order object which is not passed through in the GetRateQuote & Ship functions of the implemented ICarrierService class.
The carrier method implements the ICarrierService interface and subsequently does not have access to a Graph where one would typically be able to access the current (cached?) document, etc.
How could I, for example, access the shipment number for which the Ship function is called?
My ultimate goal is to be able to generate a label for the shipment package, and in order to do so, I need to obtain the Shipment Number.
using PX.Api;
using PX.CarrierService;
using PX.CS.Contracts.Interfaces;
using PX.Data;
using PX.Data.Reports;
using PX.Objects.Common.Extensions;
using PX.Reports;
using PX.Reports.Data;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyCarriers.CollectCarrier
{
public class CollectCarrier : ICarrierService
{
private List<CarrierMethod> methods;
private List<string> attributes;
public IList<string> Attributes => (IList<string>)this.attributes;
public string CarrierID { get; set; }
public string Method { get; set; }
public ReadOnlyCollection<CarrierMethod> AvailableMethods => this.methods.AsReadOnly();
public CollectCarrier()
{
this.methods = new List<CarrierMethod>(1);
this.methods.Add(new CarrierMethod("CLT", "Collect"));
this.attributes = new List<string>(1);
}
[...]
public CarrierResult<ShipResult> Ship(CarrierRequest cr)
{
if (cr.Packages == null || cr.Packages.Count == 0)
{
throw new InvalidOperationException("CarrierRequest.Packages must be contain atleast one Package");
}
CarrierResult<ShipResult> carrierResult;
try
{
CarrierResult<RateQuote> rateQuote = this.GetRateQuote(cr, true);
ShipResult result = new ShipResult(rateQuote.Result);
//Report Parameters
Dictionary<String, String> parameters = new Dictionary<String, String>();
// ************************************************************************************
// At this point, I would like to be able to retrieve the current SOShipment's Shipment Number
// ************************************************************************************
parameters["shipmentNbr"] = "000009"; // Hard-coded this value to get the PDF generated.
//Report Processing
PX.Reports.Controls.Report _report = PXReportTools.LoadReport("SO645000", null);
PXReportTools.InitReportParameters(_report, parameters, SettingsProvider.Instance.Default);
ReportNode reportNode = ReportProcessor.ProcessReport(_report);
//Generation PDF
result.Image = PX.Reports.Mail.Message.GenerateReport(reportNode, ReportProcessor.FilterPdf).First();
result.Format = "pdf";
result.Data.Add(new PackageData(
cr.Packages.FirstOrDefault().RefNbr,
this.RandomString(6),
result.Image,
"pdf"
)
{
TrackingData = this.RandomString(6)
});
carrierResult = new CarrierResult<ShipResult>(result);
}
catch (Exception ex)
{
if (this.LogTrace)
{
this.WriteToLog(ex, this.GetType().Name + ".Ship().Exception");
}
List<Message> messageList = this.HandleException(ex);
messageList?.Insert(0, new Message("", "Failed to generate the collection label: "));
carrierResult = new CarrierResult<ShipResult>(false, null, (IList<Message>)messageList);
}
return carrierResult;
}
[...]
}
}
For reference, the CarrierRequest object that is passed to the functions contain the following information:
public class CarrierRequest
{
public string ThirdPartyAccountID
{
get;
set;
}
public string ThirdPartyPostalCode
{
get;
set;
}
public string ThirdPartyCountryCode
{
get;
set;
}
public IAddressBase Shipper
{
get;
set;
}
public IContactBase ShipperContact
{
get;
set;
}
public IAddressBase Origin
{
get;
set;
}
public IContactBase OriginContact
{
get;
set;
}
public IAddressBase Destination
{
get;
set;
}
public IContactBase DestinationContact
{
get;
set;
}
public IList<CarrierBox> Packages
{
get;
set;
}
public IList<CarrierBoxEx> PackagesEx
{
get;
set;
}
public IList<string> Methods
{
get;
set;
}
public DateTime ShipDate
{
get;
set;
}
public UnitsType Units
{
get;
private set;
}
public bool SaturdayDelivery
{
get;
set;
}
public bool Resedential
{
get;
set;
}
public bool Insurance
{
get;
set;
}
public string CuryID
{
get;
private set;
}
public IList<string> Attributes
{
get;
set;
}
public decimal InvoiceLineTotal
{
get;
set;
}
public string FreightClass
{
get;
set;
}
public bool SkipAddressVerification
{
get;
set;
}
public IList<ISETerritoriesMappingBase> TerritoriesMapping
{
get;
set;
}
public CarrierRequest(UnitsType units, string curyID)
{
if (string.IsNullOrEmpty(curyID))
{
throw new ArgumentNullException("curyID");
}
Units = units;
CuryID = curyID;
}
}
I have seen a similar question here on SO, but I'm not entirely sure that is applicable to my specific request?
Any assistance will be highly appreciated.
See below as an option to loop through your currents and search for the specific current object:
SOShipment ship = null;
for (int i = 0; i < Caches.Currents.Length; i++)
{
if (Caches.Currents[i].GetType() == typeof(SOShipment))
{
ship = (SOShipment)Caches.Currents[i];
break;
}
}

Azure Easy Tables - Load only one column

Is there some way to get only one data column for one row from Azure Easy Tables?
For example Xamarin.Forms app will send name of item to Azure and get the item creation DateTime only.
Here's an example where we want to select just the Name Column from our Dog Table.
This sample uses the Azure Mobile Client and the Azure Mobile Client SQL NuGet Packages.
Model
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json;
namespace SampleApp
{
public class Dog
{
public string Name { get; set; }
public string Breed { get; set; }
public int Age { get; set; }
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[CreatedAt]
public DateTimeOffset CreatedAt { get; set; }
[UpdatedAt]
public DateTimeOffset UpdatedAt { get; set; }
[Version]
public string AzureVersion { get; set; }
[Deleted]
public bool IsDeleted { get; set; }
}
}
Logic
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.WindowsAzure.MobileServices;
using Microsoft.WindowsAzure.MobileServices.Sync;
using Microsoft.WindowsAzure.MobileServices.SQLiteStore;
namespace SampleApp
{
public class MobileClientService
{
bool isMobileClientInitialized;
MobileServiceClient mobileClient;
public async Task<string> GetDogName(string id)
{
await InitializeMobileClient();
var dog = await mobileClient.GetSyncTable<Dog>().LookupAsync(id);
var dogName = dog.Name;
return dogName;
}
public async Task<IEnumerable<string>> GetDogNames()
{
await InitializeMobileClient();
var dogNameList = await mobileClient.GetSyncTable<Dog>().Select(x => x.Name).ToEnumerableAsync();
return dogNameList;
}
async Task InitializeMobileClient()
{
if(isMobileClientInitialized)
return;
mobileClient = new MobileServiceClient("Your Azure Mobile Client Url");
var path = Path.Combine(MobileServiceClient.DefaultDatabasePath, "app.db");
var store = new MobileServiceSQLiteStore(path);
store.DefineTable<Dog>();
//ToDo Define all remaining tables
await MobileServiceClient.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());
}
}
}

When trying to override Partition Key using Azuren Search and Azure Table Storage with .NET getting bad request

I am using Azuren Search and Azure Table Storage and with .net and i am trying to index a table and make a partition key filterable now this works fine until i try to insert something in that table where i get a BadRequest with not much of additional info.
This is my class bellow
using System;
using Microsoft.Azure.Search;
using Microsoft.Azure.Search.Models;
using Microsoft.WindowsAzure.Storage.Table;
[SerializePropertyNamesAsCamelCase]
public class Asset : TableEntity
{
public Asset(string name)
{
Name = name;
}
public Asset()
{
}
public Asset(string name, DateTimeOffset toBePublished, string pkey)
{
Name = name;
ToBePublishedDate = toBePublished;
PartitionKey = pkey;
}
[System.ComponentModel.DataAnnotations.Key]
public string Id { get; set; } = DateTimeOffset.UtcNow.ToString("O")
.Replace("+", string.Empty)
.Replace(":", string.Empty)
.Replace(".", string.Empty);
[IsFilterable, IsSortable, IsSearchable]
public new string PartitionKey { get; set; }
[IsFilterable, IsSortable, IsSearchable]
public string Name { get; set; } = "TemptAsset " + new Guid();
[IsFilterable, IsSortable]
public int? Version { get; set; } = 1;
[IsFilterable, IsSortable]
public DateTimeOffset? ToBePublishedDate { get; set; } = DateTimeOffset.UtcNow;
[IsFilterable, IsSortable]
public DateTimeOffset? ToBeRetiredDate { get; set; } = null;
[IsFilterable, IsSearchable, IsSortable]
public string Company { get; set; } = "TempCompany";
[IsFilterable, IsSortable]
public bool IsApproved { get; set; } = false;
[IsFilterable, IsSortable]
public bool IsDraft { get; set; } = true;
}
This runs and the index is created successfully see bellow
Now if i try to add an entity to that table i get a BadRequest, but do the exact same thing with commenting out the PartitionKey in my entity and this works fine.
This is how i create my index
AzureSearch.CreateAssetNameIndex(AzureSearch.CreateSearchServiceClient());
and the methods called bellow
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AssetSynch.Models;
using Microsoft.Azure.Search;
using Microsoft.Azure.Search.Models;
public static SearchServiceClient CreateSearchServiceClient()
{
string searchServiceName = "*****";
string adminApiKey = "********";
SearchServiceClient serviceClient = new SearchServiceClient(searchServiceName,
new SearchCredentials(adminApiKey));
return serviceClient;
}
public static async void CreateAssetNameIndex(SearchServiceClient serviceClient)
{
Index definition = new Index
{
Name = "assetname",
Fields = FieldBuilder.BuildForType<Asset>()
};
await serviceClient.Indexes.CreateAsync(definition);
}
If i return the error using postman this is the exception i get
{
"innerExceptions": [
{
"requestInformation": {
"httpStatusCode": 400,
"httpStatusMessage": "Bad Request",
"serviceRequestID": "59efbc9a-0002-002c-3570-d5d55c000000",
"contentMd5": null,
"etag": null,
"requestDate": "Thu, 25 May 2017 17:05:01 GMT",
"targetLocation": 0,
"extendedErrorInformation": {
"errorCode": "PropertiesNeedValue",
"errorMessage": "The values are not specified for all properties in the entity.\nRequestId:59efbc9a-0002-002c-3570-d5d55c000000\nTime:2017-05-25T16:05:06.5197909Z",
"additionalDetails": {}
},
"isRequestServerEncrypted": false
}
}
]
}
if i remove the Partition key from my entity and re run the same code to re-create the index the same piece of code this executes successfully.
What i did noticed is that there are now 2 Partition keys on my entity one of which will remain null see image bellow and that my property does not override the original.
Is there something i am missing here?
According to your codes, I find your Asset has used new keyword to modify the base class's partition property.
But this will just hidden the base.partition not override it.
public new string PartitionKey { get; set; }
After you set the value in the Asset class, you will find it contains two partition as below:
So if the base class's partition key value is null, it will return 400 error.
So if you want to add the new entity to the table, you need set the base class(TableEntity) partition key value.
So I suggest you could change your Asset as below:
[SerializePropertyNamesAsCamelCase]
public class Asset : TableEntity
{
public Asset(string name)
{
Name = name;
base.PartitionKey = this.PartitionKey;
}
public Asset()
{
base.PartitionKey = this.PartitionKey;
}
public Asset(string name, DateTimeOffset toBePublished, string pkey)
{
Name = name;
ToBePublishedDate = toBePublished;
PartitionKey = pkey;
base.PartitionKey = this.PartitionKey;
}
[Key]
[IsFilterable]
public string Id { get; set; } = DateTimeOffset.UtcNow.ToString("O")
.Replace("+", string.Empty)
.Replace(":", string.Empty)
.Replace(".", string.Empty);
[IsFilterable, IsSortable, IsSearchable]
public new string PartitionKey { get; set; }
[IsFilterable, IsSortable, IsSearchable]
public string Name { get; set; } = "TemptAsset " + new Guid();
[IsFilterable, IsSortable]
public int? Version { get; set; } = 1;
[IsFilterable, IsSortable]
public DateTimeOffset? ToBePublishedDate { get; set; } = DateTimeOffset.UtcNow;
[IsFilterable, IsSortable]
public DateTimeOffset? ToBeRetiredDate { get; set; } = null;
[IsFilterable, IsSearchable, IsSortable]
public string Company { get; set; } = "TempCompany";
[IsFilterable, IsSortable]
public bool IsApproved { get; set; } = false;
[IsFilterable, IsSortable]
public bool IsDraft { get; set; } = true;
}
If you want to use table storage as datasource, I suggest you could refer to this article.

Entity Type 'AstNode' has no key defined

I'm porting a data model from EF4 to EF6 Code First. I'm getting the following message when the database creation is attempted. I'm at a loss to understand what is causing this. I don't have any Context, AstNode or JSParser entities. It is also not looking in the Models namespace:
var context = QPDataContext.Create();
var session = context.DataSessions.FirstOrDefault(ds => ds.DataSessionId = sessionId);
Throws this exception:
{"One or more validation errors were detected during model generation:
QPWebRater.DAL.Context: : EntityType 'Context' has no key defined. Define the key for this EntityType.
QPWebRater.DAL.AstNode: : EntityType 'AstNode' has no key defined. Define the key for this EntityType.
QPWebRater.DAL.JSParser: : EntityType 'JSParser' has no key defined. Define the key for this EntityType.
(many more similar errors snipped).
"}
Here is my database context (I've simplified it a bit):
QPWebRater.DAL.QPDataContext.cs:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Microsoft.Ajax.Utilities;
using QPWebRater.Models;
using QPWebRater.Utilities;
namespace QPWebRater.DAL
{
public class QPDataContext : DbContext
{
public QPDataContext()
: base("DefaultConnection")
{
Database.SetInitializer<QPDataContext>(new CreateDatabaseIfNotExists<QPDataContext>());
}
public static QPDataContext Create()
{
return new QPDataContext();
}
public DbSet<DataSession> DataSession { get; set; }
public DbSet<Document> Documents { get; set; }
public DbSet<Driver> Drivers { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<Lookup> Lookups { get; set; }
public DbSet<Quote> Quotes { get; set; }
public DbSet<Vehicle> Vehicles { get; set; }
public DbSet<Violation> Violations { get; set; }
}
}
QPWebRater.Models.DatabaseModels.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace QPWebRater.Models
{
public partial class DataSession
{
public DataSession()
{
this.Vehicles = new HashSet<Vehicle>();
this.Drivers = new HashSet<Driver>();
...
}
public string DataSessionId { get; set; }
public System.DateTime Timestamp { get; set; }
...
}
public partial class Document
{
public int DocumentId { get; set; }
public int QuoteId { get; set; }
public string DocumentType { get; set; }
public string Url { get; set; }
public string Description { get; set; }
public virtual Quote Quote { get; set; }
}
public partial class Driver
{
public Driver()
{
this.Violations = new HashSet<Violation>();
}
public int DriverId { get; set; }
public string DataSessionId { get; set; }
...
}
}
I solved this by examining all of the DbSet definitions. I had pared down the data model while also upgrading it. I had removed the Lookup model class but neglected to also remove the DbSet<Lookup> Lookups { get; set; } property.
This resulted in the class being resolved as Microsoft.Ajax.Utilities.Lookup. At runtime, EntityFramework tried to add a corresponding database table which failed miserably. If you are running into a similar problem then double check the generic types in your DbSet properties.

Get property values from a string using Reflection

I am new to this concept of reflection and finding problem in retrieving property value from a string. E.g.
I have a class Employee with following properties :
public string Name {get;set;}
public int Age {get;set;}
public string EmployeeID {get;set;}
string s = "Name=ABCD;Age=25;EmployeeID=A12";
I want to retrieve the value of each property from this string and create a new object of Employee with those values retrieved from the string for each field.
Can anyone please suggest how it can be done using reflection ??
//may be..
string s = "Name=ABCD;Age=25;EmployeeID=A12";
string[] words = s.Split(';');
foreach (string word in words)
{
string[] data = word.Split('=');
string _data = data[1];
Console.WriteLine(Name);
}
Here an example of how you maybe could do it
it used Reflection like you wanted ^^
using System;
using System.Collections.Generic;
using System.Reflection;
namespace replace
{
public class Program
{
private static void Main(string[] args)
{
var s = "Name=ABCD;Age=25;EmployeeID=A12";
var list = s.Split(';');
var dic = new Dictionary<string, object>();
foreach (var item in list)
{
var probVal = item.Split('=');
dic.Add(probVal[0], probVal[1]);
}
var obj = new MyClass();
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine(dic[property.Name]);
if (property.PropertyType == typeof(Int32))
property.SetValue(obj, Convert.ToInt32(dic[property.Name]));
//else if (property.PropertyType== typeof(yourtype))
// property.SetValue(obj, (yourtype)dic[property.Name]);
else
property.SetValue(obj, dic[property.Name]);
}
Console.WriteLine("------------");
Console.WriteLine(obj.Name);
Console.WriteLine(obj.Age);
Console.WriteLine(obj.EmployeeID);
Console.Read();
}
}
public class MyClass
{
public string Name { get; set; }
public int Age { get; set; }
public string EmployeeID { get; set; }
}
}

Resources