I need to compile dynamic code in C#
but it has error :
" error CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?)"
in pResults.Errors
my code is:
try {
var className = "test1234";
CodeNamespace ns = new CodeNamespace(className);
CodeTypeDeclaration formulaClass =
new CodeTypeDeclaration(className) {
Attributes = MemberAttributes.Public
};
var constructor = new CodeConstructor { Attributes = MemberAttributes.Public };
formulaClass.Members.Add(constructor);
#region generate method
var formula = #"List<string> UsedValues1 = new List<string>();
for (int i = 0; i < 10; i++)
{
UsedValues1.Add((i * i).ToString());
}
var ttt = UsedValues1.FirstOrDefault(x => x.Contains(""2""));
return ttt;
";
var method = new CodeMemberMethod {
ReturnType = new CodeTypeReference(typeof(string)),
Name = $"M{1}",
Attributes = MemberAttributes.Public
};
method.Statements.Add(new CodeSnippetExpression($"{formula};"));
#endregion
formulaClass.Members.Add(method);
ns.Types.Add(formulaClass);
var pUnit = new CodeCompileUnit();
pUnit.Namespaces.Add(ns);
var pParams = new CompilerParameters {
GenerateInMemory = true,
};
var provider = CodeDomProvider.CreateProvider("csharp");
var pResults = provider.CompileAssemblyFromDom(pParams, pUnit);
var sw = new StringWriter();
provider.CreateGenerator(sw).GenerateCodeFromNamespace(ns, sw, new CodeGeneratorOptions() {
});
var q = sw.ToString();
if (pResults.Errors != null && pResults.Errors.Count > 0) {
return;
}
var GeneratedClass =
pResults.CompiledAssembly.CreateInstance($"{ns.Name}.{formulaClass.Name}");
var methodParams = new List<double[]>();
var ExecResult = (string)GeneratedClass.GetType().InvokeMember($"M{1}", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, GeneratedClass, methodParams.ToArray());
}
catch (Exception e) {
}
Related
What is wrong in my code?
Whenever I try to iterate through the IEnumerable return from this CompileClasses. I got error from this line:
assembly = AppDomain.CurrentDomain.Load(memoryStream.ToArray());
But if I iterate through the object it return I don't got any compile error.
lambda_method(Closure , object , object[] )
Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object target, object[] parameters)
public static IEnumerable<object> CompileClasses(string csharp)
{
if (string.IsNullOrEmpty(csharp))
{
throw new ArgumentNullException(nameof(csharp));
}
SyntaxTree tree = CSharpSyntaxTree.ParseText(csharp);
CompilationUnitSyntax root = tree.GetCompilationUnitRoot();
var system = SyntaxFactory.IdentifierName("System");
var systemCollections = SyntaxFactory.QualifiedName(system, SyntaxFactory.IdentifierName("Collections"));
var systemCollectionsGeneric = SyntaxFactory.QualifiedName(systemCollections, SyntaxFactory.IdentifierName("Generic"));
var systemLinq = SyntaxFactory.QualifiedName(system, SyntaxFactory.IdentifierName("Linq"));
var systemText = SyntaxFactory.QualifiedName(system, SyntaxFactory.IdentifierName("Text"));
var systemXml = SyntaxFactory.QualifiedName(system, SyntaxFactory.IdentifierName("Xml"));
var declaredUsings = root.Usings.Select(x => x.Name.ToString()).ToList();
if (!declaredUsings.Contains("System"))
{
root = root.AddUsings(SyntaxFactory.UsingDirective(system).NormalizeWhitespace());
}
if (!declaredUsings.Contains("System.Collections"))
{
root = root.AddUsings(SyntaxFactory.UsingDirective(systemCollections).NormalizeWhitespace());
}
if (!declaredUsings.Contains("System.Collections.Generic"))
{
root = root.AddUsings(SyntaxFactory.UsingDirective(systemCollectionsGeneric).NormalizeWhitespace());
}
if (!declaredUsings.Contains("System.Linq"))
{
root = root.AddUsings(SyntaxFactory.UsingDirective(systemText).NormalizeWhitespace());
}
if (!declaredUsings.Contains("System.Text"))
{
root = root.AddUsings(SyntaxFactory.UsingDirective(systemLinq).NormalizeWhitespace());
}
if (!declaredUsings.Contains("System.Xml"))
{
root = root.AddUsings(SyntaxFactory.UsingDirective(systemXml).NormalizeWhitespace());
}
tree = CSharpSyntaxTree.Create(root);
root = tree.GetCompilationUnitRoot();
var compilation = CSharpCompilation.Create("CSharp2Json",
new SyntaxTree[] { tree },
references: new[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location), MetadataReference.CreateFromFile(typeof(Uri).Assembly.Location), MetadataReference.CreateFromFile(typeof(DataSet).Assembly.Location), MetadataReference.CreateFromFile(typeof(EntityKey).Assembly.Location),
MetadataReference.CreateFromFile(typeof(XmlDocument).Assembly.Location)
},
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
);
System.Console.WriteLine(compilation);
// load compiled bits into assembly
Assembly assembly;
using (var memoryStream = new MemoryStream())
{
var result = compilation.Emit(memoryStream);
if (!result.Success)
{
throw new System.ArgumentException("Parameter cannot be null", "original");
}
assembly = AppDomain.CurrentDomain.Load(memoryStream.ToArray());
}
// instantiate object instances from assembly types
foreach (var definedType in assembly.DefinedTypes)
{
Type objType = assembly.GetType(definedType.FullName);
if (objType.BaseType?.FullName != "System.Enum")
{
object instance = null;
try
{
instance = assembly.CreateInstance(definedType.FullName);
}
catch (MissingMethodException)
{
// no default constructor - eat the exception
}
if (instance != null)
{
yield return instance;
}
}
}
}
I get the error: Constructor on type 'SimpleScript.Generator' not found.
I tried passing the correct parameters but i still get this error, this is my source code, and the script is a very simple piece of code that generates the Array of Element head and body. And also it is compiled successfully but it throws the error at the execution line.
string source = #"
using System;
using MSiteDLL;
namespace SimpleScript
{
public static class Generator
{
public static Document Generate(Data server)
{
"+script+ #"
Block[] blocks = {
new Block(""head"", head),
new Block(""body"", body),
};
return new Document(blocks);
}
}
}
";
Dictionary<string, string> providerOptions = new Dictionary<string, string>
{
{"CompilerVersion", "v4.0"}
};
CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
CompilerParameters compilerParams = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = false,
ReferencedAssemblies = {
"System.dll",
"System.Core.dll",
"MSiteDLL.dll",
}
};
CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
if (results.Errors.Count != 0)
{
string output = "";
foreach (CompilerError y in results.Errors)
{
output += y.ErrorText + Environment.NewLine;
}
throw new Exception("Compile failed:" + output);
}
object o = results.CompiledAssembly.CreateInstance("SimpleScript.Generator");
MethodInfo mi = o.GetType().GetMethod("Generate");
Data[] parametersArray = new Data[] { server };
Document x = (Document)mi.Invoke(o, parametersArray);
return x;
Since your class is static, you should invoke the method in a static way.
So first, remove this line:
object o = results.CompiledAssembly.CreateInstance("SimpleScript.Generator");
And use those to invoke:
MethodInfo mi = Type.GetType("SimpleScript.Generator").GetMethod("Generate");
Data[] parametersArray = new Data[] { server };
Document x = (Document)mi.Invoke(null, parametersArray);
I am using C# implementation of netsuite api from web reference com.netsuite.webservices
I released filter fileSearch.basic by name (you can see it commented) it is working fine.
Please help to write function to achieve all attached files for current user. Something is wrong in this code, it filters nothing and showing me all files as it is without any filter. Please help me.
public static void GetFileAttachmentByCustomerId(string customerId)
{
using (NetSuiteService netSuiteService = GetNetSuiteService())
{
FileSearch fileSearch = new FileSearch();
// this works fine (filter files by name)
//SearchStringField nameSearchParams = new SearchStringField
//{
// #operator = SearchStringFieldOperator.contains,
// operatorSpecified = true,
// searchValue = "some name",
//};
//fileSearch.basic = new FileSearchBasic() { name = nameSearchParams };
// this code not filter files at all
{
RecordRef nsCustomerRef = new RecordRef
{
internalId = customerId,
type = RecordType.customer,
typeSpecified = true,
};
SearchMultiSelectField shopperSearchParam = new SearchMultiSelectField
{
#operator = SearchMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = new RecordRef[] { nsCustomerRef }
};
fileSearch.shopperJoin = new CustomerSearchBasic { internalId = shopperSearchParam };
}
SearchResult result = netSuiteService.search(fileSearch);
// Get connected objects
{
Customer customer = GetCustomerById(netSuiteService, customerId);
Account account = GetAccountById(netSuiteService, "301395"); //
Folder folder = GetFolderById(netSuiteService, "3962");
}
File file = (File)result.recordList.First();
byte[] fileContent = GetFileContentByInternalId(file.internalId);
}
}
.
Try this:
var nsCustomerRef = new RecordRef
{
internalId = "4",
type = RecordType.employee,
typeSpecified = true,
};
var currentUser = new SearchMultiSelectField()
{
operatorSpecified = true,
#operator = SearchMultiSelectFieldOperator.anyOf,
searchValue = new List<RecordRef>() {nsCustomerRef}.ToArray()
};
var fileSearchBasic = new FileSearchBasic() {owner = currentUser};
var fileSearch = new FileSearch() { basic = fileSearchBasic };
var result = netSuiteService.search(fileSearch);
var file = (File)result.recordList.First();
I am trying to write the following a (pseudo)query in C# for CRM 4:
Status = active
AND
(
mail = somemail
OR
(
firstName like firstNameSearchTerm
AND
lastName like LastNameSearchTerm
)
)
The problem is, that middle names might be part of firstName or LastName. I am having a hard time putting this into ConditionExpressions / FilterExpressions.
#region mail conditions
// Create the ConditionExpression.
ConditionExpression mail1Condition = new ConditionExpression();
mail1Condition.AttributeName = "emailaddress1";
mail1Condition.Operator = ConditionOperator.Like;
mail1Condition.Values = new object[] { Registration.Email };
ConditionExpression mail2Condition = new ConditionExpression();
mail2Condition.AttributeName = "emailaddress2";
mail2Condition.Operator = ConditionOperator.Like;
mail2Condition.Values = new object[] { Registration.Email };
ConditionExpression mail3Condition = new ConditionExpression();
mail3Condition.AttributeName = "emailaddress3";
mail3Condition.Operator = ConditionOperator.Like;
mail3Condition.Values = new object[] { Registration.Email };
ConditionExpression statusCondition = new ConditionExpression();
statusCondition.AttributeName = "statuscode";
statusCondition.Operator = ConditionOperator.Equal;
statusCondition.Values = new object[] { "1" };
FilterExpression mailFilter = new FilterExpression();
mailFilter.FilterOperator = LogicalOperator.Or;
mailFilter.Conditions = new ConditionExpression[] { mail1Condition, mail2Condition, mail3Condition };
#endregion mail conditions
#region name conditions
/* FIRST NAME */
FilterExpression firstNameFilter = new FilterExpression();
firstNameFilter.FilterOperator = LogicalOperator.Or;
List<ConditionExpression> firstNameConditions = new List<ConditionExpression>();
var firstAndMiddleNames = Registration.FirstName.Trim().Split(' ');
firstAndMiddleNames = firstAndMiddleNames.Select(s => s.Replace(s, "%"+s+"%")).ToArray(); // Add wildcard search
foreach (var item in firstAndMiddleNames)
{
ConditionExpression firstNameCondition = new ConditionExpression();
firstNameCondition.AttributeName = "firstname";
firstNameCondition.Operator = ConditionOperator.Like;
firstNameCondition.Values = new object[] { item };
firstNameConditions.Add(firstNameCondition);
}
firstNameFilter.Conditions = firstNameConditions.ToArray();
/* LAST NAME */
FilterExpression lastNameFilter = new FilterExpression();
lastNameFilter.FilterOperator = LogicalOperator.Or;
List<ConditionExpression> lastNameConditions = new List<ConditionExpression>();
var lastAndMiddleNames = Registration.LastName.Trim().Split(' ');
lastAndMiddleNames = lastAndMiddleNames.Select(s => s.Replace(s, "%" + s + "%")).ToArray(); // Add wildcard search
foreach (var item in lastAndMiddleNames)
{
ConditionExpression lastNameCondition = new ConditionExpression();
lastNameCondition.AttributeName = "lastname";
lastNameCondition.Operator = ConditionOperator.Like;
lastNameCondition.Values = new object[] { item };
lastNameConditions.Add(lastNameCondition);
}
lastNameFilter.Conditions = firstNameConditions.ToArray();
#endregion name conditions
FilterExpression nameFilter = new FilterExpression();
nameFilter.FilterOperator = LogicalOperator.And;
nameFilter.Filters = new FilterExpression[] { firstNameFilter, lastNameFilter };
// Create the outer most filter to AND the state condition with the other filters
FilterExpression stateFilter = new FilterExpression();
stateFilter.FilterOperator = LogicalOperator.And;
stateFilter.Conditions = new ConditionExpression[] { statusCondition };
stateFilter.Filters = new FilterExpression[] { nameFilter };
query.EntityName = EntityName.contact.ToString();
query.Criteria = stateFilter;
query.ColumnSet = columns;
BusinessEntityCollection contacts = Service.RetrieveMultiple(query);
I
The query currently bypasses the mail filter for debugging purposes.
The result is that it finds all contacts matching the firstname or lastname (should be AND). Why???
There was a simple typo in the following line
lastNameFilter.Conditions = firstNameConditions.ToArray();
should be
lastNameFilter.Conditions = lastNameConditions.ToArray();
I am creating a xml schema using schema object model, on step "set.compile()", I get the above mentioned error. I guess its related to the base type name of simpletype elements, help!
Is there any method, we can actually see what is giong in while set.compile() method compiles the code??
XmlSchemaSimpleType namesimpletype = new XmlSchemaSimpleType();
XmlSchemaSimpleTypeRestriction res = new XmlSchemaSimpleTypeRestriction();
res.BaseTypeName = new XmlQualifiedName("string","");
XmlSchemaMinLengthFacet facet1 = new XmlSchemaMinLengthFacet();
facet1.Value = "3";
XmlSchemaMaxLengthFacet facet2 = new XmlSchemaMaxLengthFacet();
facet2.Value = "10";
res.Facets.Add(facet1);
res.Facets.Add(facet2);
namesimpletype.Content = res;
XmlSchemaSimpleType phonetype = new XmlSchemaSimpleType();
XmlSchemaSimpleTypeRestriction phone_res = new XmlSchemaSimpleTypeRestriction();
phone_res.BaseTypeName = new XmlQualifiedName("string", "");
XmlSchemaMinLengthFacet phone_facet1 = new XmlSchemaMinLengthFacet();
phone_facet1.Value = "4";
XmlSchemaMaxLengthFacet phone_facet2 = new XmlSchemaMaxLengthFacet();
phone_facet2.Value = "20";
phone_res.Facets.Add(phone_facet1);
phone_res.Facets.Add(phone_facet2);
phonetype.Content = phone_res;
XmlSchemaSimpleType notetype = new XmlSchemaSimpleType();
XmlSchemaSimpleTypeRestriction note_res = new XmlSchemaSimpleTypeRestriction();
note_res.BaseTypeName = new XmlQualifiedName("string", "");
XmlSchemaMinLengthFacet note_facet1 = new XmlSchemaMinLengthFacet();
note_facet1.Value = "0";
XmlSchemaMaxLengthFacet note_facet2 = new XmlSchemaMaxLengthFacet();
facet2.Value = "50";
note_res.Facets.Add(note_facet1);
note_res.Facets.Add(note_facet2);
notetype.Content = note_res;
XmlSchemaComplexType employeetype = new XmlSchemaComplexType();
XmlSchemaSequence emp_seq = new XmlSchemaSequence();
XmlSchemaElement firstname = new XmlSchemaElement();
firstname.Name = "firstname";
firstname.SchemaType = namesimpletype;
XmlSchemaElement lastname = new XmlSchemaElement();
lastname.Name = "lastname";
lastname.SchemaType = namesimpletype;
XmlSchemaElement homephone = new XmlSchemaElement();
homephone.Name = "homePhone";
homephone.SchemaType = phonetype;
XmlSchemaElement notes = new XmlSchemaElement();
notes.Name = "notes";
notes.SchemaType = notetype;
emp_seq.Items.Add(firstname);
emp_seq.Items.Add(lastname);
emp_seq.Items.Add(homephone);
emp_seq.Items.Add(notes);
employeetype.Particle = emp_seq;
/* XmlSchemaAttribute employeeid = new XmlSchemaAttribute();
employeeid.Name = "employeeid";
employeeid.SchemaTypeName = new XmlQualifiedName("int", "");
employeeid.Use = XmlSchemaUse.Required;
employeetype.Attributes.Add(employeeid);
*/
XmlSchemaComplexType complextype = new XmlSchemaComplexType();
complextype.Name = "employees";
XmlSchemaElement employee = new XmlSchemaElement();
employee.Name = "employee";
employee.SchemaType = employeetype;
employee.MinOccurs = 0;
employee.MaxOccursString = "unbounded";
XmlSchemaSequence emps_seq = new XmlSchemaSequence();
emps_seq.Items.Add(employee);
complextype.Particle = emps_seq;
XmlSchema schema = new XmlSchema();
schema.Items.Add(complextype);
XmlSchemaSet set = new XmlSchemaSet();
set.Add(schema);
set.Compile();
/* try
{
set.Compile();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
} */
FileStream stream = new FileStream(textBox1.Text, FileMode.Open);
XmlTextWriter writer = new XmlTextWriter(stream, null);
schema.Write(writer);
writer.Close();
Try to use full name with namespace:
res.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
See Example section on page http://msdn.microsoft.com/en-us/library/1c4sky9s(v=vs.110).aspx