FileHelpers reading a complex csv file including an inner csv list in a class object - filehelpers

I am having a below csv file:
Employer EID,File Creation Date,File Creation Time,Salary Year and Month,Total Salaries,Total Records,,,
1006200,20032016,1031,201603,2200,1,,,
Record ID,Employee QID,Number of Working Days,Net Salary,Basic Salary,Extra hours,Extra Income,Deductions,Payment Type
1,29135617946,31,2200,2200,0,0,0,SALARY
2,29135617947,31,2200,2300,0,0,0,SALARY
3,29135617948,31,2200,2250,0,0,0,SALARY
Above file is having the first part as the employer information and the seond set of rows having the employees working with that along with their salary.
I want to create a complex class Employer which will be having the employees attributes along with a List of complex type named Employee that will include all the employees information.
Please help me by giving a direction/code to how can I achieve this using the FileHelpers.

You can use a MasterDetailEngine. There is an example in the documentation.
You provide a selector class to enable FileHelpers to determine whether a record is a master record or a detail record.
private RecordAction ExampleSelector(string record)
{
if (record.Length < 2)
return RecordAction.Skip;
if (IsMasterRecord(record)) // some way of identifying your master records
return RecordAction.Master;
else
return RecordAction.Detail;
}
Then you can read your the file into your classes like this:
var engine = new MasterDetailEngine<Employer, Employee>(new MasterDetailSelector(ExampleSelector));
var result = engine.ReadFile("Input.txt");
foreach (var group in result) {
Console.WriteLine("Customer: {0}", group.Master.EmployerEid);
foreach (var detail in group.Details)
Console.WriteLine(" Freight: {0}", detail.EmployeeQid);
}

Related

RepoDb cannot find mapping configuration

I'm trying to use RepoDb to query the contents of a table (in an existing Sql Server database), but all my attempts result in an InvalidOperationException (There are no 'contructor parameter' and/or 'property member' bindings found between the resultset of the data reader and the type 'MyType').
The query I'm using looks like the following:
public Task<ICollection<MyType>> GetAllAsync()
{
var result = new List<MyType>();
using (var db = new SqlConnection(connectionString).EnsureOpen())
{
result = (await db.ExecuteQueryAsync<MyType>("select * from mytype")).ToList();
}
return result;
}
I'm trying to run this via a unit test, similar to the following:
[Test]
public async Task MyTypeFetcher_returns_all()
{
SqlServerBootstrap.Initialize();
var sut = new MyTypeFetcher("connection string");
var actual = await sut.GetAllAsync();
Assert.IsNotNull(actual);
}
The Entity I'm trying to map to matches the database table (i.e. class name and table name are the same, property names and table column names also match).
I've also tried:
putting annotations on the class I am trying to map to (both at the class level and the property level)
using the ClassMapper to map the class to the db table
using the FluentMapper to map the entire class (i.e. entity-table, all columns, identity, primary)
putting all mappings into a static class which holds all mapping and configuration and calling that in the test
providing mapping information directly in the test via both ClassMapper and FluentMapper
From the error message it seems like RepoDb cannot find the mappings I'm providing. Unfortunately I have no idea how to go about fixing this. I've been through the documentation and the sample tutorials, but I haven't been able to find anything of use. Most of them don't seem to need any mapping configuration (similar to what you would expect when using Dapper). What am I missing, and how can I fix this?

Sitefinity - Safely delete orphaned dynamic content records

I've been adding records to a dynamic module via the API and in the process during my experimentation I added a bunch of records that weren't associated correctly with any valid parent record.
I've checked and so far I can see that Sitefinity stores data about these records in a number of tables:
mydynamiccontenttype_table
sf_dynamic_content
sf_dynmc_cntnt_sf_lnguage_data
sf_dynmc_cntent_sf_permissions
I would like to clean up the database by deleting these records but I want to make sure I don't create more problems in the process.
Anyone know if there are more references to these dynamic content type records or a process to safely delete them?
There are probably other tables, so your safest option would be to delete the items using the Sitefinity API.
Just get the masterId of the item and use a code like this:
public static void DeleteDataItemOfType(this DynamicModuleManager manager, string type, Guid Id)
{
Type resolvedType = TypeResolutionService.ResolveType(type);
using (var region = new ElevatedModeRegion(manager))
{
manager.DeleteDataItem(resolvedType, Id);
manager.SaveChanges();
}
}

Linq where a record contains 2 matched fields

I’m working with an existing database with a design I’m not in control of, I’m using EF4, and querying using LINQ. I work in VB.Net but would be quite happy to translate a c# solution.
I would like to pull records from a table where two of the fields match a pair of items from a list.
So i have a list of
Public Class RequestInfo
Public Property INSP_ROUTINE_NM As String
Public Property FEATURE_ID As String
End Class
And I would like to query a table and pull any records where both INSP_ROUTINE_NM and FEATURE_ID match one of the Request Info items.
I can use contains easy enough on either of the fields
Dim Features = (From F In MLDb.TBL_FeatureInfoSet _
Where (C_Request.Select(Function(x) x.INSP_ROUTINE_NM)).Contains(F.INSP_ROUTINE_NM) Select F.FEATURE_ID, F.FEATURE_RUN_NO, F.INSP_ROUTINE_NM).ToList
I could use two contains calls but that would pull any record where both records match somewhere in the list not necessarily any one pair from the request.
You can try this:
C#
var Features= (from f in MLDb.TBL_FeatureInfoSet
let q = C_Request.Select(x=>x.INSP_ROUTINE_NM)
where q.Contains(f.INSP_ROUTINE_NM) || q.Contains(f.INSP_ROUTINE_NM)
// where q.Contains(f.INSP_ROUTINE_NM) && q.Contains(f.INSP_ROUTINE_NM)
select new {f.FEATURE_ID, f.FEATURE_RUN_NO}).ToList();

ASP.NET MVC 4 Deferred query execution not retrieving data from database

I am new in ASP.NET MVC 4. In my project I am using Code First technique in of EF. I want to retrieve some data from database and I used following code for this :
List<SelectListItem> ls = new List<SelectListItem>();
var lm = from m in db.BOs //fetch data from database
select m;
foreach (var temp in lm)
{
ls.Add(new SelectListItem() { Text = temp.Name, Value = temp.Id.ToString() });
}
But when execution pointer move inside foreach it immediately come back out of the loop showing return ls value Count = 0. Code does not giving me any error while running that's why I am not getting where is going wrong.
UPDATE: I found something new this problem. When I kept mouse pointer over var lm; it shows me query and in query table name in FROM clause is not that one in my SQL database. My SQL table name is BO and in query it is taking BOes. I don't know from where this name is coming. So How I overcome this??
decorate your BO class with Table("BO") to specify the table name (attribute is in System.ComponentModel.DataAnnotations.Schema namespace)
[Table("BO")]
public partial class BO
{
...
Write following code inside DbContext class :
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
The modelBuilder.Conventions.Remove statement in the OnModelCreating method prevents table names from being pluralized. If you didn't do this, the generated tables would be named Students, Courses, and Enrollments. Instead, the table names will be Student, Course, and Enrollment. Developers disagree about whether table names should be pluralized or not. This tutorial uses the singular form, but the important point is that you can select whichever form you prefer by including or omitting this line of code.

Regarding relationship management in JPA2

I am getting confused about managing entities in a relationship. According to the book PRO JPA2, relationship should be manually configured and assigned at both ends of the relationship.
Now, consider this relationship.
#Entity
public class Employee {
..
#ManyToOne(cascade=CascadeType.PERSIST)
private Department department;
..
}
#Entity
public class Department {
..
#OneToMany(mappedBy="department")
private Set<Employee> employees = new HashSet<Employee>();
public void addEmployee(Employee e){
getEmployees().add(e);
e.setDepartment(this);
}
}
I made a simple test case that involves this line of code to verify this.
Department dept1 = new Department();
dept1.setName("MARKETING");
Employee e1 = new Employee();
e1.setName("JOHN DOE");
e1.setDepartment(dept1); //[1]
//dept1.addEmployee(e1); //[2]
Consider Line [1]:
I thought this would not properly update the Employee table with the correct department ID but I checked Derby and it is able to properly execute the update.
Consider Line [2]:
This is the proper way according to the book.
Eclipselink/Derby/JPA2
If you do it like in line [1], the Employee 'e1' will be stored in database with the FK ok, but... If you get Department dept1 and invoke getEmployees(); Employee 'e1' will not be in this list. Even if you make a new query to get that deparment from database again; it will not have Employee 'e1' (at least not until you reploy the application). That is why you should always do it in way [2].
When I started working with JPA2 I didn't know this; and was persisting entities like in [1]. I almost went crazy trying to determine why the recently persisted entities were not read by JPA, but were actually stored in the DB.