CSV file read result value set to entitiy object - c#

I'm try to update OFAC Sanction list to my database by using following URL.
URL :
http://www.treasury.gov/ofac/downloads/sdn.csv
This csv file has no any header and can download as a file. So I'm split all the record and get as a string Array. I have a problem with how can I assign those results to my entity object to save.
This is my Code :
List<SanctionOFACEntries> sanctionOFACList = new List<SanctionOFACEntries>();
List<string> splitted = new List<string>();
string fileList = GetCSVFileContent(url);
string[] tempStr;
tempStr = Regex.Matches(fileList, "(?:\"(?<m>[^\"]*)\")|(?<m>[^,]+)").Cast<Match>().Select(m => m.Value).ToArray(); ;
int i = 0;
foreach (string item in tempStr)
{
i += 1;
SanctionOFACEntries sanctionOFAC = new SanctionOFACEntries();
if (i != 1)
{
sanctionOFAC.Name = tempStr[i];
}
}
This case that all the records are assign to array list correctly. If any one have this OFAC sample upload code send me .
Please help this.
Thanks.

I'm not 100% clear on your issue, but first of all, I'd recommend you use a csv library. I'm not clear on what your Regex is attempting to due, but I'm assuming it's trying to parse CSV. Using FileHelpers csv library, I've rewritten your code:
var engine = new FileHelperEngine<SanctionOFACEntries>();
var sanctionOFACList = engine.ReadStringAsList(GetCSVFileContent(url));
Far more straight forward. Note your SanctionOFACEntries class should look something like this Treasury Data Spec:
[DelimitedRecord(",")]
public class SanctionOFACEntries
{
public int ent_num
[FieldQuoted]
public string ent_num { get; set; }
[FieldQuoted]
public string SDN_Name { get; set; }
[FieldQuoted]
public string SDN_Type { get; set; }
[FieldQuoted]
public string Program { get; set; }
[FieldQuoted]
public string Title { get; set; }
[FieldQuoted]
public string Call_Sign { get; set; }
[FieldQuoted]
public string Vess_type { get; set; }
[FieldQuoted]
public string Tonnage { get; set; }
[FieldQuoted]
public string GRT { get; set; }
[FieldQuoted]
public string Vess_flag { get; set; }
[FieldQuoted]
public string Vess_owner { get; set; }
[FieldQuoted]
public string Remarks { get; set; }
}

Related

C# Searching List of Arrays for specific value and returning related value

I hope this isn't a foolishly simple question. Im very simply trying to figure out how to manipulate a relatively simple table in SQLite through C#.
Im looking to take a parameter and search a List of Arrays for one such array where the parameter matches, and return a related variable within that same array.
For example where an array in the list might be.
Name IATA
Brisbane BNE
The sqlbind:
public static List<Airport> LoadAirports()
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var output = cnn.Query<Airport>("select * from Airport", new DynamicParameters());
return output.ToList();
}
}
The Class:
class Airport
{
int Id { get; set; }
string Name { get; set; }
string LocationName { get; set; }
string IATA { get; set; }
string PortType { get; set; }
string PortOwner { get; set; }
string MotherPort { get; set; }
bool Active { get; set; }
bool IsApplyMeetAndGreet { get; set; }
decimal MeetAndGreet { get; set; }
}
The main Program:
List<Airport> Airports = new List<Airport>();
public FreightCalculator()
{
LoadAirportsList();
string OriginName = OriginInput.Value;
var OriginAirport = Airports.Where(s => s.Name == OriginName);
}
private void LoadAirportsList()
{
Airports = SqliteDataAccess.LoadAirports();
}
Ive tried various combinations of Where, Equals, For each indexing etc. Always getting an error of some kind.
The Error with the above Airports.Where is that the s.Name is inaccessible due to its protection level.
If I do:
var OriginAirport = Airports.Where(Name => Name == OriginName);
I get an error where the operand == cannot be used with Airport and String (Though Name is a string in Airport.)
Im either missing something simple or making this more complicated than it needs to be. Once I find the matching Airport, I need to return the IATA code.
Which I envisage looking like this:
var OriginIATA = OriginAirport.IATA;
Im tired and feeling dumb. Please help :(
Since you declared all members of the Airport class as properties I assume you wanted to expose them publicly.
The error you get is because they are private members and can't be accessed outside the class.
Change "Airport" class to:
class Airport
{
public int Id { get; set; }
public string Name { get; set; }
public string LocationName { get; set; }
public string IATA { get; set; }
public string PortType { get; set; }
public string PortOwner { get; set; }
public string MotherPort { get; set; }
public bool Active { get; set; }
public bool IsApplyMeetAndGreet { get; set; }
public decimal MeetAndGreet { get; set; }
}

How can I get the List with a custom datatype to a string builder?

I have a class.
public class IdDetails
{
public string transactionDate { get; set; }
public string upnName { get; set; }
public string movementTrade { get; set; }
public string baseCurve { get; set; }
public string cTolerance { get; set; }
//17 more declarations below
}
Then I used it as the DataType of my List Interface
foreach(DataRow r in tbl1.Rows)
{
InterFace.Add(new IdDetails
{
transactionDate = Convert.ToDateTime(r["TransDate"]).ToString(#"MM/dd/yyyy"),
upnName = string.Empty
movementTrade = "incoming",
//... Somemore adding of values
}
}
I have tried this reference. However, I think it is build of strings with Single data inside each item.I dont know the actual terminology for this
I have tried to do it like this using my reference
var x = concatenate<IdDetails>(Interface, Convert.ToString, ';');
But I'm not getting the result i need, Instead I am getting there values
//output im getting
x = "DataImport2.IdDetails;" //<- this string repeated multiple times
Question: How can I directly write the contents of the my custom List to a string builder? Without me transforming it to another object. Because I can cast it to a DataTable and process it to a StringBuilder. That's a rather long process and coding.
Hope someone can help me.
You can use string.Join() to achieve what you need. For example
string.Join(",", Interface.Select(item => item.transactionDate + " " + item.xxx + // etc etc));
EDIT:
Override ToString() in IdDetails to use Reflection to get all values of your class.
public class IdDetails
{
public string transactionDate { get; set; }
public string upnName { get; set; }
public string movementTrade { get; set; }
public string baseCurve { get; set; }
public string cTolerance { get; set; }
private static string SafeString(object s)
{
return s == null ? string.Empty : s.ToString();
}
public override string ToString()
{
PropertyInfo[] properties = typeof(IdDetails).GetProperties();
return string.Join(",", properties.Select(prop => SafeString(prop.GetValue(this, null))).ToArray());
}
//17 more declarations below
}

WPF Loop with DataGrid Rows

First: this is my code at the moment
class Plan
{
public string Linie { get; set; }
public string Kurs { get; set; }
public string Abfahrt { get; set; }
public string Von { get; set; }
public string Nach { get; set; }
public string Ankunft { get; set; }
public string Pause { get; set; }
public Plan(string Linie, string Kurs, string Abfahrt, string Von, string Nach, string Ankunft, string Pause)
{
this.Linie = Linie;
this.Kurs = Kurs;
this.Abfahrt = Abfahrt;
this.Von = Von;
this.Nach = Nach;
this.Ankunft = Ankunft;
this.Pause = Pause;
}
private System.Collections.ObjectModel.ObservableCollection<Plan> _items = new System.Collections.ObjectModel.ObservableCollection<Plan>();
Plan.ItemsSource = _items;
So: I want a loop, that do something foreach row. So, as example: A loop that show a MessageBox, which contains each cell (I mean [as example] the Linie of the seleceted row an so on)
I am happy about each answer!
Thank a lot!
You could make a list of Plan.
To create list:
List<Plan> ListPlan=new List<Plan>();
ListPlan.Add(new Plan("","","",...);
To read list:
foreach (Plan p in ListPlan)
{
MessageBox.Show(p.Linie)
}

Deserialize CSV string to an C# Object

I have a response from Jira API, require to be deserialized into data model:
com.atlassian.greenhopper.service.sprint.Sprint#40675167[id=10151,rapidViewId=171,state=CLOSED,name=Sprint 37.1,startDate=2015-07-30T16:00:22.000+03:00,endDate=2015-08-13T16:00:00.000+03:00,completeDate=2015-08-13T14:31:34.343+03:00,sequence=10151]
This is actually the information of current sprint for issue.
I need to deserialize it to a model like:
public class Model
{
public string name { get; set; }
...
}
I have already removed all non-required information, like com.atlassian.greenhopper.service.sprint.Sprint#40675167 using Regex pattern \[(.*?)\] so I have brackets and all inside.
Now I stopped completely trying to find the a way to convert this string to a data model.
Found the following thread at the Atlassian Answers page and there appears to be no JSON representation of that inner Object. As shown in the example from that thread:
customfield_10007:[
"com.atlassian.greenhopper.service.sprint.Sprint#a29f07[rapidViewId=<null>,state=CLOSED,name=NORD - Sprint 42,startDate=2013-07-29T06:47:00.000+02:00,endDate=2013-08-11T20:47:00.000+02:00,completeDate=2013-08-14T15:31:33.157+02:00,id=107]",
"com.atlassian.greenhopper.service.sprint.Sprint#769133[rapidViewId=<null>,state=ACTIVE,name=NORD - Sprint 43,startDate=2013-08-14T15:32:47.322+02:00,endDate=2013-08-23T15:32:47.322+02:00,completeDate=<null>,id=117]"
],
The response is indeed a JSON array, but the array itself contains CSV's, so you can make use of the following to parse that:
public class DataObject
{
public string id { get; set; }
public string rapidViewId { get; set; }
public string state { get; set; }
public string name { get; set; }
public string startDate { get; set; }
public string endDate { get; set; }
public string completeDate { get; set; }
public string sequence { get; set; }
}
public class Program
{
private const string sampleStringData =
#"[id=10151,rapidViewId=171,state=CLOSED,name=Sprint 37.1,startDate=2015-07-30T16:00:22.000+03:00,endDate=2015-08-13T16:00:00.000+03:00,completeDate=2015-08-13T14:31:34.343+03:00,sequence=10151]";
static void Main(string[] args)
{
var dataObject = new DataObject();
string[][] splitted;
var sampleWithNoBrackets = sampleStringData.Substring(1,sampleStringData.Length-2);
splitted = sampleWithNoBrackets.Split(',').Select(p => p.Split('=')).ToArray();
dataObject.id = splitted[0][1];
dataObject.rapidViewId = splitted[1][1];
dataObject.state = splitted[2][1];
dataObject.name = splitted[3][1];
dataObject.startDate = splitted[4][1];
dataObject.endDate = splitted[5][1];
dataObject.completeDate = splitted[6][1];
dataObject.sequence = splitted[7][1];
Console.ReadKey();
}
}
Here's the output for the above:

Passing a generic list to a method

I have an application that will parse an excel file and add a column, then generate a new CSV file with the results. I am able to create a list of the items I want in the file, but I cannot figure out how to pass that list to the method that is generating the new file.
I have the following class:
public class LocationData
{
public string PostalCode { get; set; }
public string Partner { get; set; }
public string LocationID { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Market { get; set; }
}
and the following code to get the data into a list:
LocationData Locationdata = new LocationData()
{
PostalCode = location[0],
Partner = location[1],
LocationID = location[2],
Name = location[3],
Country = location[4],
Market = repository.GetMarketsForPostalCode(location[0])
}
I also have the method to create the csv and I need to pass in the list info, but I get the error:
foreach statement cannot operate on variables of type 'app.LocationData' because 'app.LocationData' does not contain a public definition for 'GetEnumerator'
I think you are misunderstanding what a list is in C#. I think you need the List data type. Try this:
List<string> Locationdata = new List<string>()
{
location[0],
location[1],
location[2],
location[3],
location[4],
repository.GetMarketsForPostalCode(location[0])
};
Your csv function will look like this
public void GenerateCSV(List<LocationData> data)
{
foreach (LocationData d in data)
{
//put line in csv as
string s = d.PostalCode + "," d.Partner + _"," + d.LocationID...... + Environment.NewLine;
}
}
Your class declaration will remain same
public class LocationData
{
public string PostalCode { get; set; }
public string Partner { get; set; }
public string LocationID { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Market { get; set; }
}
Now you need to add all the data in the list first
which you will do like this
List<LocationData> lst = new List<LocationData>();
LocationData ld = new LocationData();
ld.LocationID = "0";
ld.Market = "market";
lst.Add(ld);
........
GenerateCSV(lst);

Categories