BLToolkit Complex Mapping Using SELECT JOIN - database

Trying to use BLToolkit mapper in my project. There is a thing that I really don't know how to solve , the deal is that I have 2 classes Content and Comment.
[MapField("CommentItemId","CommentContent.ContentId")]
public class Comment
{
[MapField("Comment.CommentId")]
public int CommentId;
[Relation(typeof(Content))]
public Content CommentContent;
}
public class Content
{
[MapField("ContentId"),PrimaryKey]
public int ContentId;
public IList<Comment> Comments = new List<Comment>();
}
Well , looks as simple Complex Mapping as example that everybody saw on BLToolkit.net .
But , I'm trying to use SELECT JOIN query. This is my query.
MapResultSet[] sets = new MapResultSet[2];
sets[0] = new MapResultSet(typeof(Content));
sets[1] = new MapResultSet(typeof(Comment));
command = String.Format(#"SELECT con.ContentId,com.CommentId,com.CommentItemId
FROM Content as con,Comments as com
WHERE (con.ContentId = com.CommentItemId AND con.ContentId {0})", itemid, type);
This query returns correct data ( checked with ExecuteReader ). But in MapResultSets there is only Content data , no Comment data ... If i will interchange Content and Comment sets ... I will get only Comment data , and no Content data ... I don't even care about realtions right now , i just want to explain to BLToolkit , that there is data of 2 classes in 1 row.

Related

How to search for empty strings in a text field with Entity Framework?

I'd like to know how can I search for empty strings when I'm using a text type field with Entity Framework.
I've looked the SQL query that Entity is generating and It's using LIKE to compare because It's searching in a text type field, so when I use .Equals(""), == "", == string.Empty, .Contains(""), .Contains(string.Empty), and everything else, It's returning all results because it sql query is like '' and the == command throws exception because It uses the = command that is not valid with text type field.
When I try to use .Equals(null), .Contains(null), == null, It returns nothing, because It is generating FIELD ISNULL command.
I already tried the .Lenght == 0 but It throws an exception...
This works for me:
public class POCO
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
static void Main(string[] args)
{
var pocos = new List<POCO>
{
new POCO { Id = 1, Name = "John", Description = "basic" },
new POCO { Id = 2, Name = "Jane", Description = "" },
new POCO { Id = 3, Name = "Joey", Description = string.Empty }
};
pocos.Where(x => x.Description == string.Empty)
.ToList()
.ForEach(x => Console.WriteLine($"{x.Id} {x.Name} {x.Description}"));
}
However the issue MAY BE that your T4 generated object is not fully realized with data you can use, if you are using Entity Framework. EG the translation from the database is not populating objects to interrogate correctly. I would just do an operation like this to see:
using (var context = new YOURCONTEXTNAME())
{
var persons = context.YOURDATABASEOBJECT.ToList();
persons.ForEach(x => Console.WriteLine($"{x.COLUMNINQUESTION}"));
}
If you are successfully having data in it, it should be retrieved. I would not use text if possible. Use a varchar(max) nvarchar(max) xml, whatever text will be deprecated eventually and is bad form so to speak to continue using at this point.
EDIT
Okay I see, the answer is you cannot interogate the object until it is fully realized when it is text. I did a test on my local database and created a context and tested it and sure enough you cannot do a '== string.empty', '== ""', or 'String.IsNullOrEmpty()' on a text. However you can do it once the object is materialized in a realized object. EG:
// Won't work as context does not understand type
//var persons = context.tePersons.Where(x => x.Description == string.Empty).ToList();
//Works fine as transformation got the object translated to a string in .NET
var start = context.tePersons.ToList();
var persons = start.Where(x => x.Description == String.Empty).ToList();
This poses a problem obviously as you need to get ALL your data potentially before performing a predicate. Not the best means by any measure. You could do a sql object for this instead then to do a function, proc, or view to change this.

Insert CSV using Apex Batch Class Salesforce for OpportunityLineItem

I want to add a button to my opportunity header record that is called Insert Products. This will send the opportunity ID to a visualforce page which will have a select file button and an insert button that will loop through the CSV and insert the records to the related opportunity.
This is for non technical users so using Data loader is not an option.
I got this working using standard apex class however hit a limit when i load over 1,000 records (which would happen regularly).
I need to convert this to a batch process however am not sure how to do this.
Any one able to point me in the right direction? I understand a batch should have a start, execute and finish. However i am not sure where i should split the csv and where to read and load?
I found this link which i could not work out how to translate into my requirements: http://developer.financialforce.com/customizations/importing-large-csv-files-via-batch-apex/
Here is the code i have for the standard apex class which works.
public class importOppLinesController {
public List<OpportunityLineItem> oLiObj {get;set;}
public String recOppId {
get;
// *** setter is NOT being called ***
set {
recOppId = value;
System.debug('value: '+value);
}
}
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public List<OpportunityLineItem> oppLine{get;set;}
public importOppLinesController(){
csvFileLines = new String[]{};
oppLine = New List<OpportunityLineItem>();
}
public void importCSVFile(){
PricebookEntry pbeId;
String unitPrice = '';
try{
csvAsString = csvFileBody.toString();
csvFileLines = csvAsString.split('\n');
for(Integer i=1;i<csvFileLines.size();i++){
OpportunityLineItem oLiObj = new OpportunityLineItem() ;
string[] csvRecordData = csvFileLines[i].split(',');
String pbeCode = csvRecordData[0];
pbeId = [SELECT Id FROM PricebookEntry WHERE ProductCode = :pbeCode AND Pricebook2Id = 'xxxx HardCodedValue xxxx'][0];
oLiObj.PricebookEntryId = pbeId.Id;
oLiObj.Quantity = Decimal.valueOf(csvRecordData[1]) ;
unitPrice = String.valueOf(csvRecordData[2]);
oLiObj.UnitPrice = Decimal.valueOf(unitPrice);
oLiObj.OpportunityId = 'recOppId';;
insert (oLiObj);
}
}
catch (Exception e)
{
ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR, e + ' - ' + unitPrice);
ApexPages.addMessage(errorMessage);
}
}
}
First problem that I can sense is that the insert DML statement is inside FOR-loop. Can you put the new "oLiObj" into a List that is declared before the FOR-loop starts and then try inserting the list after the FOR-loop ?
It should bring some more sanity in your code.

Binding class with master/detail into two datagridview

I had made a class in C# Windows form to represent my database.
It has a master/detail using List<>
A record with Employee profile with Trainings(master) and TrainingDetails(detail)
Now, how can I display this into 2 datagridview that whenever I select a "Training" from the first datagridview it will display the details on the 2nd datagridview.
Its easy to change the datasource of the 2nd datagridview whenever the user select a new item from the first datagridview. But im wondering how it is done professionally.
Also saving is a pain, Im thingking to iterate through the datarow and save it but It mean I have to know what are the data has been update, inserted and deleted.
Please help me. Im a newbie.
BindingSources take care of this for you.
For example say I have two classes, Teachers and Students:
public class Teacher
{
private List<Student> _students = new List<Student>();
public string Name { get; set; }
public string Class { get; set; }
public List<Student> Students { get { return _students; } }
}
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
You can then create a list of Teachers which represents the Master/Detail situation:
List<Teacher> teachers = new List<Teacher>();
Teacher t = new Teacher();
t.Name = "Mr. Smith";
t.Class = "A1";
teachers.Add(t);
Student s = new Student();
s.Name = "Jimmy Jones";
s.Age = 6;
t.Students.Add(s);
s = new Student();
s.Name = "Jane Doe";
s.Age = 5;
t.Students.Add(s);
t = new Teacher();
t.Name = "Ms. Allen";
t.Class = "B3";
teachers.Add(t);
s = new Student();
s.Name = "Sally Student";
s.Age = 7;
t.Students.Add(s);
On my form I have two DataGridViews, teachersDataGridView and studentsDataGridView and two binding sources teachersBindingSource and studentsBindingSource.
I wire everything up like so:
teachersBindingSource.DataSource = teachers;
studentsBindingSource.DataSource = teachersBindingSource;
studentsBindingSource.DataMember = "Students";
teachersDataGridView.DataSource = teachersBindingSource;
studentsDataGridView.DataSource = studentsBindingSource;
And as if by magic when running up on the form selecting an item from the teachers grid changes students grid.
For managing inserts, updates and deletes you will need to implement some sort of change tracking yourself (or use an ORM such as Entity Framework or nHibernate). It is a topic that deserves its own question so read up on those technologies (and look at the blog post I like below) and come back when you have some specific problems.
For this answer I borrowed heavily from this excellent post - the example I've given is complete and avoids a lot of the complexity in that authors example's, but eventually you will probably want to at least know about everything he discusses. Download his demos and have a look.

How to change and entity type in Doctrine2 CTI Inheritance

How (if possible at all) do you change the entity type with Doctrine2, using it's Class Table Inheritance?
Let's say I have a Person parent class type and two inherited types Employe and Client. My system allows to create a Person and specify it's type - that's fairly easy to implement - but I'd also like to be able to change the person from an Employe to a Client, while maintaining the Person-level information (it's id and other associated records).
Is there a simple way to do this with Doctrine2?
I was looking for this behaviour yesterday also.
In the end, after speaking with people in #doctrine on freenode, I was told that it is not possible.
If you want to do this, then you have to go through this:
Upgrading a User
Grab the Person Entity.
Update the discrimator column so that it is no longer a 'person' and change it to 'employee'
Create a corresponding row inyour Employee table for this inheritance.
Removing Inheritance
Likewise if you want to remove inheritance, you have to..
Grab the Person Entity.
Update the discrimnator column so that it is no longer an 'employee' and change it to a 'person'.
Delete the corresponding row in your Employee table. (Yes you have to delete it, just change the discrimator coumn is not sufficient).
This might be 7 months late, but it is at least the correct answer for anything else looking to suport such a feature.
PHP doesn't have support for object casting, so Doctrine doesn't support it. To workaround the problem I write this static method into parent classes:
public static function castToMe($obj) {
$class = get_called_class();
$newObj = New $class();
foreach (get_class_vars(get_class($newObj)) as $property => $value) {
if (method_exists($obj, 'get' . ucfirst($property)) && method_exists($newObj, 'set' . ucfirst($property))) {
$newObj->{'set' . ucfirst($property)}($obj->{'get' . ucfirst($property)}());
}
}
return $newObj;
}
You can create this method in class Person and use it to cast from Employe to Client and viceversa:
$employe = New Employe();
$client = Client::castToMe($employe);
Now, if you want, you can remove the $employe entity.
You could do something like this though:
This Trait can be used on your Repository class:
namespace App\Doctrine\Repository;
trait DiscriminatorTrait
{
abstract public function getClassMetadata();
abstract public function getEntityManager();
private function updateDiscriminatorColumn($id, $class)
{
$classMetadata = $this->getClassMetadata();
if (!in_array($class, $classMetadata->discriminatorMap)) {
throw new \Exception("invalid discriminator class: " . $class);
}
$identifier = $classMetadata->fieldMappings[$classMetadata->identifier[0]]["columnName"];
$column = $classMetadata->discriminatorColumn["fieldName"];
$value = array_search($class, $classMetadata->discriminatorMap);
$connection = $this->getEntityManager()->getConnection();
$connection->update(
$classMetadata->table["name"],
[$column => $value],
[$identifier => $id]
);
}
}
There still might be some extra work you need to put in, like clearing values in fields that are only present on one of your sub-classes
In Doctrine2, when you have your parent entity class, Person set as:
/**
* #Entity
* #InheritanceType("JOINED")
* #DiscriminatorColumn(name="discr", type="string")
* #DiscriminatorMap({"person" = "Person", "employee" = "Employee", , "client" = "Client"})
*/
class Person
{
// ...
}
and sub classes such as Client set as:
/** #Entity */
class Client extends Person
{
// ...
}
when you instantiate Person as:
$person = new Person();
Doctrine2 checks your #DiscriminatorMap statement (above) for a corresponding mapping to Person and when found, creates a string value in the table column set in #DiscriminatorColumn above.
So when you decide to have an instance of Client as:
$client = new Client();
Following these principles, Doctrine2 will create an instance for you as long as you have declared the parameters in the #DiscriminatorMap. Also an entry will be made on the Person table, in the discr column to reflect that type of entity class that has just been instantiated.
Hope that helps. It's all in the documentation though
i use this method
trait DiscriminatorTrait
{
// ...
public function updateDiscriminatorColumn($id, $class)
{
// ... other code here
$connection->update(
"Person", // <-- just there i put my parent class
[$column => $value],
[$identifier => $id]
);
}
}
and i use call like this after :
$this->em->getRepository(Client::class)->updateDiscriminatorColumn($cCenter->getId(), Employe::class);
$this->em->close();
// I update the data directly without going through doctrine otherwise it will create a new Person
try {
$query = "
INSERT INTO Employe (id, /* ... other fields */)
VALUES ({$callCenter->getId()}, /* ... other fields */)
";
$results = $this->connection->executeQuery($query)->execute();
} catch (\Exception $exception) {
echo $exception->getMessage().PHP_EOL;
}
$this->em->close();
// i restart the connection
/** #var EntityManagerInterface $entityManager */
$entityManager = $this->em;
if ($this->em->isOpen() === false) {
$this->em = $entityManager->create(
$this->em->getConnection(),
$this->em->getConfiguration(),
$this->em->getEventManager()
);
}
// and there a get Employer en update him
$employe = $this->em->getRepository(Employe::class)->find($id);
$employe->setFirstname($callCenter->getFirstName());
// other code
And it is work for me

How to bind WPF Datagrid to a joined table

I have a big problem. I try to bind my WPF DataGrid to a table, created with inner join. I have created a class for the info to convert successfully:
public class NeshtoSi
{
public NeshtoSi() { }
public string ssn;
public string name;
public string surname;
}
And then I create the inner-joined tables. Still when I assign the ItemsSource and all values are transferred properly, but the DataGrid does not visualize them.
var dd = from d in dataContext.Medical_Examinations
join p in dataContext.Patients on d.SSN equals p.SSN
select new NeshtoSi { ssn = d.SSN, name = p.Name, surname = p.Surname };
IQueryable<NeshtoSi> sQuery = dd;
if (!string.IsNullOrEmpty(serName.Text))
sQuery = sQuery.Where(x => x.name.Contains(serName.Text));
if (!string.IsNullOrEmpty(serSurame.Text))
sQuery = sQuery.Where(x => x.surname.Contains(serSurame.Text));
if (!string.IsNullOrEmpty(serSSN.Text))
sQuery = sQuery.Where(x => x.ssn.Contains(serSSN.Text));
var results = sQuery.ToList();
AnSearch.ItemsSource = sQuery;
I hope that someone can help me...
The code that you presented seems ok - it doesn't matter how an object is created - what matters is the object itself.
Rather than showing us this, you should show the xaml.
One more thing - are we talking about DataGridView from winforms or rather the one that comes with WPF Toolkit ?
=======================================
Sorry. I've missed it in the first place - you don't have properties in your class! You've created public fields instead of properties and that's probably the problem.
The code should look like this:
public class NeshtoSi
{
public NeshtoSi() { }
public string ssn{get; set;}
public string name{get; set;}
public string surname{get; set;}
}
I went through this recently, and the answer is outlined in a post of mine that is here

Resources