Create class at runtime, serilize and de-serilize then cast to Interface froblem - class

Hi,
I have the following code :
public static object CreateTypedReport(string typeName, string inheritFrom)
{
DirectoryInfo dirInfo;
CSharpCodeProvider c = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
foreach (Assembly asm in System.AppDomain.CurrentDomain.GetAssemblies())
{
if(!asm.FullName.StartsWith("ReportAssembly, Version=0.0.0.0"))
cp.ReferencedAssemblies.Add(asm.Location);
}
cp.CompilerOptions = "/t:library";
cp.GenerateInMemory = true;
dirInfo = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\MyApp\\ReportAssemblies\\");
if (!dirInfo.Exists)
dirInfo.Create();
cp.OutputAssembly = dirInfo.FullName + typeName + "Assembly";
cp.ReferencedAssemblies.Add(typeof(XtraReport).Assembly.Location);
//cp.OutputAssembly = typeName + "Assembly";
StringBuilder sb = new StringBuilder("");
sb.Append("using System;\n");
sb.Append("using MyNamespace.UI;\n");
sb.Append("namespace TypedReports { \n");
sb.Append("public class " + typeName + " : " + inheritFrom + "{ \n");
sb.Append("} \n");
sb.Append("}\n");
CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());
if (cr.Errors.Count > 0)
{
MessageBox.Show("ERROR: " + cr.Errors[0].ErrorText, "Error evaluating cs code", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
return cr.CompiledAssembly.CreateInstance("TypedReports." + typeName);
}
This will create a class based on the typeName and inheritFrom parameters and then finally an object will be created and returned. inheritFrom will point at a class that implements IMyInterface.
It's possible to cast this object to a IMyInterface if it's needed.
When we then serialize and de-serialize this object we will not be able to cast it to IMyInterface anymore?
Why? And how could I solve it?

The problem was in the serialization och deserialization of the object. When this was changed it worked great. The solution is in a third party product so I canĀ“t post it here.

Related

Parallel execution with Jbehave with pico (jbehave-pico)

I'm new Jbehave. Im trying to find a way to achieve world in cucumber with Jbehave.
I generated project with jbehave with pico archetype. Im trying to run two stories in parallel. I updated threads in pom.xml to 2.
Consider a sample stepdef class as below
public class PojoSteps {
public Pojo pojo;
public PojoSteps(Pojo pojo){
this.pojo = pojo;
System.out.println(" ##" + new Timestamp(System.currentTimeMillis()) + " * this is " + this + ". In PojoSteps constructor. Pojo created is:" + this.pojo + ". Thread = " + Thread.currentThread().getId());
}
#Given("I have a pojo with $i")
public void iHaveAPojoWith1(int i){
pojo.setI(i);
System.out.println(" ##" + new Timestamp(System.currentTimeMillis()) + " * this is " + this + ".In iHaveAPojoWith1. pojo = " + this.pojo +". Value of To be set = " + i +". Value set Pojo.getI() = " + this.pojo.getI() + ". Thread = " + Thread.currentThread().getId());
}
#When("I wait for some time")
public void randomWait() throws InterruptedException {
Thread.sleep(new Random().nextInt(200));
}
#Then("my pojo should still have $expectedi")
public void myPojoShouldStillHave1(int expectedi){
System.out.println(" ##" + new Timestamp(System.currentTimeMillis()) + " * this is " + this +". In myPojoShouldStillHave1. pojo = " + this.pojo + ". expected = " + expectedi + ". actual = " + this.pojo.getI() + ". Thread = " + Thread.currentThread().getId());
Assert.assertEquals(this.pojo.getI(), expectedi);
}
}
I have Pojo model as below
public class Pojo {
private int i;
public void setI(int i){
this.i = i;
}
public int getI(){
return this.i;
}
}
My two stories are as below
PojoOne.story
Scenario: scenario description
Given I have a pojo with 1
When I wait for some time
Then my pojo should still have 1
PojoTwo.story
Scenario: random description
Given I have a pojo with 2
When I wait for some time
Then my pojo should still have 2
I have MyStories class which extends JUnitStories as below
public class MyStories extends JUnitStories {
....
private PicoContainer createPicoContainer() {
MutablePicoContainer container = new DefaultPicoContainer(new Caching().wrap(new ConstructorInjection()));
container.addComponent(PojoSteps.class);
container.addComponent(Pojo.class);
return container;
}
}
When I don't run stories in parallel, they succeed. When I run stories in parallel, they are failing.
##2020-01-02 20:35:36.53 * this is learning.steps.PojoSteps#49f3f232. In PojoSteps constructor. Pojo created is:learning.Support.Pojo#4aa9e824. Thread = 12
##2020-01-02 20:35:36.531 * this is learning.steps.PojoSteps#49f3f232.In iHaveAPojoWith1. pojo = learning.Support.Pojo#4aa9e824. Value of To be set = 1. Value set Pojo.getI() = 1. Thread = 12
##2020-01-02 20:35:36.532 * this is learning.steps.PojoSteps#6136e035. In PojoSteps constructor. Pojo created is:learning.Support.Pojo#1f4412c8. Thread = 13
##2020-01-02 20:35:36.533 * this is learning.steps.PojoSteps#6136e035.In iHaveAPojoWith1. pojo = learning.Support.Pojo#1f4412c8. Value of To be set = 2. Value set Pojo.getI() = 2. Thread = 13
##2020-01-02 20:35:36.558 * this is learning.steps.PojoSteps#6136e035. In myPojoShouldStillHave1. pojo = learning.Support.Pojo#1f4412c8. expected = 1. actual = 2. Thread = 12
##2020-01-02 20:35:36.668 * this is learning.steps.PojoSteps#6136e035. In myPojoShouldStillHave1. pojo = learning.Support.Pojo#1f4412c8. expected = 2. actual = 2. Thread = 13
...
Then my pojo should still have 1 (FAILED)
(java.lang.AssertionError: expected:<2> but was:<1>)
I'm not able to find documentation on how to run tests in parallel with Jbehave and pico. Also I need to have a model outside my stepdef class as I will be having multiple stefdef classes which will share the same model instance.
After reading a bit more and trying out Jbehave with spring,
1. I think there is no way to get different instances of stepdef created per thread.
2. In Jbehave, there is no equivalent of cucumber's world object which is threadsafe.
As #VaL mentioned in the comments of the questions, we have to make thinks threadsafe explicitly.
This is my understanding as of now. If there is any better way - kindly let me know.

write a test class for apex class

I am new to apex, I'm interested in writing a test class for the following controller, but not sure where to begin. Here is my apex class code.
public class tree {
public Account acct{get;set;}
//private final Account acct;
public ApexPages.StandardController stdController {get;set;}
public tree(ApexPages.StandardController stdController) {
stdController.addFields(new String[]{'Id','Tete_de_groupe__c'});
this.acct = (Account)stdController.getRecord();
// this.stdController = stdController;
}
public List<Account> listOfAccount(){
List<Account> acctList;
if (acct.Tete_de_groupe__c == null){
acctList = [SELECT Name,Parent.Name,id,Code_NAF__c ,Industry ,RecordType.Name,Adresse_Agence__c, Tete_de_groupe__c,Statut__c
FROM Account
where id = :this.acct.id or Tete_de_groupe__c = :this.acct.id ];}
else {
acctList = [Select Name,Parent.Name,id,Tete_de_groupe__c,Statut__c
from Account
where id = :this.acct.Tete_de_groupe__c or Tete_de_groupe__c = :this.acct.Tete_de_groupe__c];}
return acctList;
}
Public String getaccountdata(){
String datastr1 = '';
String datastr2 = '';
String datastr = '';
List<Account> lstOfAcc =listOfAccount();
for (integer i=0;i<lstOfAcc.size();i++){
if (lstOfAcc[i].Parent.Name == null){
datastr1 = datastr1 + '{"name": "';
datastr1+= lstOfAcc[i].Name;
datastr1+= '","parent": ';
datastr1+= lstOfAcc[i].Parent.Name;
datastr1+= ',"accountid": "';
datastr1+= lstOfAcc[i].id;
datastr1+= '","Statut__c": "';
datastr1+= lstOfAcc[i].Statut__c;
datastr1+='" }';
}
else{
datastr2 = datastr2 + '{"name": "';
datastr2+= lstOfAcc[i].Name;
datastr2+= '","parent": "';
datastr2+= lstOfAcc[i].Parent.Name;
datastr2+= '","accountid": "';
datastr2+= lstOfAcc[i].id;
datastr2+= '","Statut__c": "';
datastr2+= lstOfAcc[i].Statut__c;
datastr2+='" },';
}
}
if(datastr2 == ''){datastr = '[' + datastr1 + ']';}
else {
datastr2 = datastr2.substring(0,datastr2.length()-1);
datastr = '[' + datastr1 +','+ datastr2 + ']'; }
return datastr;
}
}
I want to create test class. Guys need help if some one can tell me about test class of this apex class.
AParise pointed out the consideration. What you need to do in your test class, step by step:
Insert some account objects into the database (the test runs doesn't see any data by default, and that's OK)
Keep the ID from the first account and use it for Tete_de_groupe__c for the others.
Call the function, roughly like this:
Account mainAccount = populateTestAccounts(); // Helper function
Tree t = new Tree();
t.setAcct(mainAccount);
String result = t.getaccountdata();
assert(....);
That should do the trick!
For unit tests regarding classes like the one you posted, the easiest way is to think about expected results given a code path. For each test method, ask yourself: "Given this set of data, when I invoke this method, I expect this to occur".
Let's walk through your "getaccountdata" method.
"Given this set of data..." - What data does this method require for proper execution? Without diving too deep into your logic, this probably means inserting some Account sObjects.
"When I invoke this method..." - the "getaccountdata" method is being invoked.
"I expect this to occur..." - This is where your assertions come into play. You created the Account sObjects with specific values, so verify that these values propagated into your method return value.

How to retrieve subproperty of a data property in OWL API 4.0

I am using owl api 4.0 and the following code will give me all the property of individuals belonging to class Animal.
OWLClass animalCl = df.getOWLClass(IRI.create(ontologyIRI + "Animal"));
NodeSet<OWLNamedIndividual> animalIndl = reasoner.getInstances(animalCl, false);
for (OWLNamedIndividual animalNamedIndl : animalIndl.getFlattened())
{
Set<OWLDataPropertyAssertionAxiom> propAll= myontology.getDataPropertyAssertionAxioms(animalNamedIndl);
for (OWLDataPropertyAssertionAxiom ax: propAll)
{
for (OWLLiteral propertyLit : EntitySearcher.getDataPropertyValues(animalNamedIndl, ax.getProperty(), myontolgoy))
System.out.println("The property " + ax.getProperty() + "has value" + propertyLit);
}
}
I have a subproperty "propWt" for every data property. I have used following code:-
NodeSet<OWLDataProperty> properties = reasoner.getSubDataProperties((OWLDataProperty) ax.getProperty(), false);
for (OWLDataProperty mysubproperty : properties.getFlattened())
{
System.out.println("the sub property is " + mysubproperty);
}
instead of
the sub property is <http://localhost:3030/BiOnt.owl#propWt>
i get
the sub property is owl:bottomDataProperty
What is the problem here?
Since you are using a reasoner for the ontology, I assume you want all subproperties, either asserted or inferred.
The reasoner can do the job:
NodeSet<OWLDataProperty> properties = reasoner.getSubDataProperties(property, false);

Entity Framework - Table-Valued Functions - Parameter Already Exists

I am using table-valued functions with Entity Framework 5. I just received this error:
A parameter named 'EffectiveDate' already exists in the parameter collection. Parameter names must be unique in the parameter collection. Parameter name: parameter
It is being caused by me joining the calls to table-valued functions taking the same parameter.
Is this a bug/limitation with EF? Is there a workaround? Right now I am auto-generating the code (.edmx file).
It would be really nice if Microsoft would make parameter names unique, at least on a per-context basis.
I've created an issue for this here.
In the meantime, I was able to get this to work by tweaking a few functions in the .Context.tt file, so that it adds a GUID to each parameter name at runtime:
private void WriteFunctionImport(TypeMapper typeMapper, CodeStringGenerator codeStringGenerator, EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) {
if (typeMapper.IsComposable(edmFunction))
{
#>
[EdmFunction("<#=edmFunction.NamespaceName#>", "<#=edmFunction.Name#>")]
<#=codeStringGenerator.ComposableFunctionMethod(edmFunction, modelNamespace)#>
{ var guid = Guid.NewGuid().ToString("N"); <#+
codeStringGenerator.WriteFunctionParameters(edmFunction, " + guid", WriteFunctionParameter);
#>
<#=codeStringGenerator.ComposableCreateQuery(edmFunction, modelNamespace)#>
} <#+
}
else
{
#>
<#=codeStringGenerator.FunctionMethod(edmFunction, modelNamespace, includeMergeOption)#>
{ <#+
codeStringGenerator.WriteFunctionParameters(edmFunction, "", WriteFunctionParameter);
#>
<#=codeStringGenerator.ExecuteFunction(edmFunction, modelNamespace, includeMergeOption)#>
} <#+
if (typeMapper.GenerateMergeOptionFunction(edmFunction, includeMergeOption))
{
WriteFunctionImport(typeMapper, codeStringGenerator, edmFunction, modelNamespace, includeMergeOption: true);
}
} }
...
public void WriteFunctionParameters(EdmFunction edmFunction, string nameSuffix, Action<string, string, string, string> writeParameter)
{
var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef);
foreach (var parameter in parameters.Where(p => p.NeedsLocalVariable))
{
var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null";
var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\"" + nameSuffix + ", " + parameter.FunctionParameterName + ")";
var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\"" + nameSuffix + ", typeof(" + parameter.RawClrTypeName + "))";
writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit);
}
}
...
public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace)
{
var parameters = _typeMapper.GetParameters(edmFunction);
return string.Format(
CultureInfo.InvariantCulture,
"return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});",
_typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace),
edmFunction.NamespaceName,
edmFunction.Name,
string.Join(", ", parameters.Select(p => "#" + p.EsqlParameterName + "\" + guid + \"").ToArray()),
_code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray())));
}
Not a bug. Maybe a limitation or an omission. Apparently this use case has never been taken into account. EF could use auto-created parameter names, but, yeah, it just doesn't.
You'll have to resort to calling one of the functions with .AsEnumerable(). For some reason, this must be the first function in the join (as I have experienced). If you call the second function with .AsEnumerable() it is still translated to SQL and the name collision still occurs.

Dynamic Linq Library Guid exceptions

I am having a problem with the Dynamic Linq Library. I get a the following error "ParserException was unhandled by user code ')" or ','". I have a Dicitionary and I want to create a query based on this dictionary. So I loop through my dictionary and append to a string builder "PersonId = (GUID FROM DICTIONARY). I think the problem is were I append to PersonId for some reason I can't seem to convert my string guid to a Guid so the dynamic library don't crash.
I have tried this to convert my string guid to a guid, but no luck.
query.Append("(PersonId = Guid(" + person.Key + ")");
query.Append("(PersonId = " + person.Key + ")");
I am using VS 2010 RTM and RIA Services as well as the Entity Framework 4.
//This is the loop I use
foreach (KeyValuePair<Guid, PersonDetails> person in personsDetails)
{
if ((person.Value as PersonDetails).IsExchangeChecked)
{
query.Append("(PersonId = Guid.Parse(" + person.Key + ")");
}
}
//Domain service call
var query = this.ObjectContext.Persons.Where(DynamicExpression.ParseLambda<Person, bool>(persons));
Please help, and if you know of a better way of doing this I am open to suggestions.
For GUID comparison with dynamic linq use query properties and the Equals() method like in the provided sample.
var items = new[]
{
new { Id = Guid.Empty },
new { Id = Guid.NewGuid() },
new { Id = Guid.NewGuid() },
new { Id = Guid.NewGuid() }
};
var result = items.AsQueryable()
.Where("Id.Equals(#0)", Guid.Empty)
.Any();
Use a parameterized query, e.g.:
var query = this.ObjectContext.Persons.Where(
"PersonId = #1", new [] { person.Key } );
Did you try(notice the extra ')' ).
query.Append("(PersonId = Guid(" + person.Key + "))");