Mono embed invoking method crash - mono

I am trying to compile a C# source from C API of mono. Please see my code below.
//System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
MonoClass* pCompilerParamsClass = mono_class_from_name (pSystemImage, "System.CodeDom.Compiler", "CompilerParameters");
MonoObject* pCompilerParams = mono_object_new (pDomain, pCompilerParamsClass);
mono_runtime_object_init (pCompilerParams);
//parameters.GenerateExecutable = true;
//parameters.OutputAssembly = "Rules.dll";
SetBoolProperty(pCompilerParams, pCompilerParamsClass, "System.CodeDom.Compiler.CompilerParameters:set_GenerateExecutable", true);
SetStringProperty(pCompilerParams, pCompilerParamsClass, "System.CodeDom.Compiler.CompilerParameters:set_OutputAssembly", "Rules.dll");
//string sourceString = "class A {}"
MonoString* pSourceString = mono_string_new(pDomain, "class A {}");
//CSharpCodeProvider codeProvider = new CSharpCodeProvider();
MonoClass* pCodeProviderClass = mono_class_from_name (pSystemImage, "System.CodeDom.Compiler", "CodeDomProvider");
MonoClass* pCSharpCodeProviderClass = mono_class_from_name (pSystemImage, "Microsoft.CSharp", "CSharpCodeProvider");
MonoObject* pCodeProvider = mono_object_new (pDomain, pCSharpCodeProviderClass);
mono_runtime_object_init (pCodeProvider);
//ICodeCompiler icc = codeProvider.CreateCompiler();
MonoMethodDesc* pMethodDescCreateCompiler = mono_method_desc_new("System.CodeDom.Compiler.CodeDomProvider:CreateCompiler()", false);
MonoMethod* pMethodCreateCompiler = mono_method_desc_search_in_class (pMethodDescCreateCompiler, pCSharpCodeProviderClass);
MonoObject* pIcc = mono_runtime_invoke(pMethodCreateCompiler, pCodeProvider, NULL, NULL);
//icc.CompileAssemblyFromSource(parameters, source)
MonoMethodDesc* pMethodDescCompileAssemblyFromSource = mono_method_desc_new("System.CodeDom.Compiler.ICodeCompiler:CompileAssemblyFromSource()", false);
MonoMethod* pMethodCompileAssemblyFromSource = mono_method_desc_search_in_class (pMethodDescCreateCompiler, mono_object_get_class(pIcc));
MonoArray* pParams = mono_array_new(pDomain, mono_get_object_class(), 2);
mono_array_set(pParams, MonoObject*, 0, pCompilerParams);
mono_array_set(pParams, MonoString*, 0, pSourceString);
mono_runtime_invoke_array(pMethodCompileAssemblyFromSource, pCodeProvider, NULL, NULL);
This code fails at MonoObject* pIcc = mono_runtime_invoke(pMethodCreateCompiler, pCodeProvider, NULL, NULL); line.
What am I doing wrong?

Related

How to verify PKCS#7 signature in PHP

I have a digital signature (encrypted format PKCS#7) needs to be verified So I have tried by using different PHP core methods(openssl_verify, openssl_pkcs7_verify and even tried by external library such as phpseclib But nothing worked :(
I get a signature along with some extra params through by this link..
http://URL?sign={'param':{'Id':'XXXXXXX','lang':'EN','Rc':'00','Email': 'test#yahoo.com'’},'signature':'DFERVgYJKoZIhvcNAQcCoIIFRzCCBUMCAQExCzAJBgUrDg
MCGgUAMIGCBgkqhkiG9w0BBwGgdQRzeyJEYXRlIjoidG9fY2hhcihzeXNkYXRlJ0RETU1ZWVlZJykgIiwiSWQiOiJ
VMDExODg3NyIsIklkaW9tYSI6IkNBUyIsIk51bUVtcCI6IlUwM23D4DEE3dSi...'}
PHP code - returns always 0(false) instead of 1(true).
$JSONDATA = str_replace("'", '"', #$_GET["sign"]);
$data = json_decode($JSONDATA, true);
$this->email = $data['param']["EMAIL"];
$this->signature = $data['signature'];
$this->signature_base64 = base64_decode($this->signature);
$this->dataencoded = json_encode($data['param']);
//SOLUTION 1 (By using phpseclib) but didnt work..
$rsa = $this->phpseclib->load();
$keysize = 2048;
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS8);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
$d = $rsa->createKey($keysize);
$Kver = $d['publickey'];
$KSign = $d['privatekey'];
// Signing
$rsa->loadKey($KSign);
$rsa->setSignatureMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->setHash('sha256');
$signature = $rsa->sign($this->dataencoded);
$signedHS = base64_encode($signature);
// Verification
$rsa->loadKey($Kver);
$status = $rsa->verify($this->dataencoded, $this->firma_base64); // getting an error on this line Message: Invalid signature
var_dump($status); // reutrn false
//SOLUTION 2 (By using code php methods)
// obtener la clave pública desde el certifiado y prepararla
$orignal_parse = parse_url("https://example.com", PHP_URL_HOST);
$get = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE)));
$read = stream_socket_client("ssl://".$orignal_parse.":443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get);
$cert = stream_context_get_params($read);
$certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
openssl_x509_export($cert["options"]["ssl"]["peer_certificate"],$cert_key);
$pubkeyid = openssl_pkey_get_public($cert_key);
$dataencoded = json_encode($data['param']);
echo $ok = openssl_x509_check_private_key($cert_key,$this->firma_base64); // return nothing
echo $ok1 = openssl_verify($dataencoded, $this->firma_base64, $pubkeyid, OPENSSL_ALGO_SHA256); // returns 0
echo $ok2 = openssl_verify($dataencoded, $this->firma_base64, $pubkeyid, OPENSSL_ALGO_SHA512); // returns 0
echo $ok3 = openssl_verify($dataencoded, $this->firma_base64, $pubkeyid, OPENSSL_ALGO_SHA256); // returns 0
echo $ok4 = openssl_verify($dataencoded, $this->firma, $pubkeyid, OPENSSL_ALGO_SHA512); // returns 0
Java code - (this code works and returns true)
private boolean verifySignautre(String frm) throws NetinfException, IOException, CMSException,
CertificateException, OperatorCreationException, Exception {
Security.addProvider(new BouncyCastleProvider());
//we extract the containers that make up the signature and the keystore used to sign included in the same signature.
CMSSignedData signedData = new CMSSignedData(Base64.decode(frm.getBytes()));
SignerInformationStore signers = signedData.getSignerInfos();
Store certStore = signedData.getCertificates();
Collection c = signers.getSigners();
Iterator it = c.iterator();
while (it.hasNext()) {
//retrieve the certificate with the recipient's id.
SignerInformation signerInfo = (SignerInformation) it.next();
Collection certCollection = certStore.getMatches(signerInfo.getSID());
Iterator certIt = certCollection.iterator();
X509CertificateHolder signerCertificateHolder = (X509CertificateHolder) certIt.next();
//create the container to validate signature.
ContentVerifierProvider contentVerifierProvider = new BcRSAContentVerifierProviderBuilder(new
DefaultDigestAlgorithmIdentifierFinder()).build(signerCertificateHolder);
//valid signature and then certificate validity date
try{
X509Certificate signedcert = new
JcaX509CertificateConverter().setProvider("BC").getCertificate(signerCertificateHolder);
signedcert.checkValidity();
signedcert.verify(signedcert.getPublicKey());
return true;
}catch(Exception e){
return false;
}
}
I simply need to convert this Java code into PHP. However, as you can see above that I tried different approaches but none of them worked.
Please support me to find the solution.
your support would be higly appreciated

LINQ expression working in VS2012 not working in VS2015

I have a complex query made in LINQ that is working just fine in a debugging environment in Visual Studio 2012. When I execute the same query with the same database using Visual Studio 2015 it throws the following exception:
Message: No se puede convertir el tipo
'System.Nullable`1[[System.Decimal, mscorlib, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089]]' al tipo
'System.Object'. LINQ to Entities solo admite la conversión de tipos
de enumeración o primitivos de EDM.
Google translation to English:
Cannot convert type 'System.Nullable`1 [[System.Decimal, mscorlib, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089]] to type' System.Object '. LINQ to Entities only supports the conversion of enumeration types or EDM primitives.
Here is the expression. It's pretty complex to explain but maybe there's something wrong that can be seen easily:
Dim dsRiesgoDatosParte1 = listRiesgoEntities _
.Select(Function(r) New With {
.Id = r.IdRiesgo,
.Nombre = r.Nombre,
.Descripcion = r.Descripcion,
.Costo = r.Costo,
.CategoriaRiesgoNivel1 = r.IdCategoriaRiesgo1,
.CategoriaRiesgoNivel2 = r.IdCategoriaRiesgo2,
.CategoriaRiesgoNivel3 = r.IdCategoriaRiesgo3,
.IdNivelDatos = r.IdNivelDatos,
.IdOrganigrama = r.IdOrganigrama,
.Ponderacion = r.Ponderacion,
.Activo = r.Activo,
.Completo = r.Completo,
.ModificadaPorUsuarioControles = r.ModificadaPorUsuarioControles,
.ModificadaPorUsuarioTratamientos = r.ModificadaPorUsuarioTratamientos,
.Comentario = r.Comentario,
.ValidacionRiesgo = If(r.ValidacionRiesgo IsNot Nothing, r.ValidacionRiesgo, 0),
.ValoracionGlobalControlesValor = If(r.ValoracionControles > 0, r.ValoracionControles, CType(Nothing, String)),
.VariablesValoracionGlobalControl = r.DS_RiesgoVariablesValoracionGlobalControl _
.Where(Function(i) r.ValoracionControles > 0) _
.Select(Function(i) New With {
.IdRiesgo = i.IdRiesgo,
.IdVariableConfiguracion = i.IdVariableConfiguracion,
.tmpIdItem = If(i.IdVariableListaItem IsNot Nothing, i.IdVariableListaItem, -1),
.Valor = CType(i.Valor, String)
}),
.ValoracionGlobalTratamientosValor = If(r.ValoracionTratamientos > 0, r.ValoracionTratamientos, CType(Nothing, String)),
.VariablesValoracionGlobalTratamiento = r.DS_RiesgoVariablesValoracionGlobalTratamiento _
.Where(Function(i) r.ValoracionTratamientos > 0) _
.Select(Function(i) New With {
.IdRiesgo = i.IdRiesgo,
.IdVariableConfiguracion = i.IdVariableConfiguracion,
.tmpIdItem = If(i.IdVariableListaItem IsNot Nothing, i.IdVariableListaItem, 0),
.Valor = CType(i.Valor, String)
}),
.tmpArchivos = r.DS_Archivo.Select(Function(a) New DTOArchivo With {
.Id = a.IdArchivo,
.Nombre = a.Nombre
}),
.tmpResponsables = r.DS_Usuarios.Select(Function(u) New DTOResponsable With {
.Login = u.USR_Login
}),
.tmpControlesDatos = r.DS_ControlDato.Select(Function(c) New With {
.Id = c.IdControlDato,
.Nombre = c.Nombre,
.IdVariableConfiguracion = c.IdVariableConfiguracion,
.Comentario = c.Comentario,
.CostoAnual = c.CostoAnual,
.Ponderacion = c.Ponderacion,
.ModificadaPorUsuario = c.ModificadaPorUsuario,
.Valor = CType(c.Valor, String),
.tmpValor = c.Valor,
.TiposControles = c.DS_TipoControl.Select(Function(tc) New DTOTipoControl With {
.Id = tc.IdTipoControl,
.Nombre = tc.Nombre
})
}),
.NivelDato = New DTONivelDato With {
.Id = r.DS_NivelDatosFijo.IdNivelDato,
.Nombre = r.DS_NivelDatosFijo.Nombre,
.Ponderacion = r.DS_NivelDatosFijo.Ponderacion,
.IdNivelConfiguracion = r.DS_NivelDatosFijo.IdNivelConfiguracion,
.IdNivelPadre = r.DS_NivelDatosFijo.IdNivelPadre,
.IdEmpresa = r.DS_NivelDatosFijo.IdEmpresa,
.Activo = r.DS_NivelDatosFijo.Activo
}
}) _
.AsEnumerable
I tried to split the Select in several parts but couldn't find the problem. Also the exception is thrown when I join the result of the previous query, here's the inspection of dsRiesgosDatosParte1:
As I said, it's working just fine in VS2012 but not in VS2015 so there must be something new in LINQ.
The question is, what has changed in LINQ from VS2012 to VS2015 that could affect the result of the execution? I can't find anywhere why this could happend.

Docusign duplicated Signature tags on all pages

I am using Docusign to add a signature my PDF documents in c#.
I have some html file, I add to end of html div with text "SignHere" that Docusign will recognize the zone for signature, but the problem that after converting html to pdf and send Docusign, I see that "SignHere" option in all pages, not the last one.
What I am wrong wrong here?
My code, after converting html to pdf file:
if (System.IO.File.Exists(PdfPath))
{
byte[] fileBytes = System.IO.File.ReadAllBytes(PdfPath);
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.EmailSubject = envDefEmailSubject;
envDef.EventNotification = new EventNotification();
envDef.EventNotification.Url = envDefEventNotificationUrl;
envDef.EventNotification.LoggingEnabled = "true";
envDef.EventNotification.IncludeDocuments = "true";
envDef.EventNotification.RequireAcknowledgment = "true";
envDef.EventNotification.IncludeCertificateWithSoap = "false";
envDef.EventNotification.RequireAcknowledgment = "true";
envDef.EventNotification.UseSoapInterface = "false";
envDef.EventNotification.EnvelopeEvents = new List<EnvelopeEvent>();
EnvelopeEvent envelopeEventSent = new EnvelopeEvent();
envelopeEventSent.EnvelopeEventStatusCode = "sent";
envDef.EventNotification.EnvelopeEvents.Add(envelopeEventSent);
EnvelopeEvent envelopeEventDelivered = new EnvelopeEvent();
envelopeEventDelivered.EnvelopeEventStatusCode = "delivered";
envDef.EventNotification.EnvelopeEvents.Add(envelopeEventDelivered);
EnvelopeEvent envelopeEventSentCompleted = new EnvelopeEvent();
envelopeEventSentCompleted.EnvelopeEventStatusCode = "completed";
envDef.EventNotification.EnvelopeEvents.Add(envelopeEventSentCompleted);
Document doc = new Document();
doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes);
doc.Name = docName;
doc.DocumentId = docDocumentId;
envDef.Documents = new List<Document>();
envDef.Documents.Add(doc);
Signer signer = new Signer();
signer.Email = Email;
signer.Name = signerName + LeadName;
signer.RecipientId = signerRecipientId;
signer.Tabs = new Tabs();
//Custom Field For LeadId and PdfName
envDef.CustomFields = new CustomFields();
envDef.CustomFields.TextCustomFields = new List<TextCustomField>();
TextCustomField textCustomFieldLeadId = new TextCustomField();
textCustomFieldLeadId.Name = "LeadId";
textCustomFieldLeadId.Value = LeadId;
textCustomFieldLeadId.Required = "false";
textCustomFieldLeadId.Name = "false";
envDef.CustomFields.TextCustomFields.Add(textCustomFieldLeadId);
TextCustomField textCustomFieldSignedPdfName = new TextCustomField();
textCustomFieldSignedPdfName.Name = "SignedPdfName";
textCustomFieldSignedPdfName.Value = SignedPdfName;
textCustomFieldSignedPdfName.Required = "false";
textCustomFieldSignedPdfName.Name = "false";
envDef.CustomFields.TextCustomFields.Add(textCustomFieldSignedPdfName);
if (SignHereExist)
{
signer.Tabs.SignHereTabs = new List<SignHere>();
SignHere signHere = new SignHere();
signHere.RecipientId = signHereRecipientId;
signHere.AnchorXOffset = signHereAnchorXOffset;
signHere.AnchorYOffset = signHereAnchorYOffset;
signHere.AnchorIgnoreIfNotPresent = signHereAnchorIgnoreIfNotPresent;
signHere.AnchorUnits = "inches";
signHere.AnchorString = signHereAnchorString;
signer.Tabs.SignHereTabs.Add(signHere);
envDef.Recipients = new Recipients();
envDef.Recipients.Signers = new List<Signer>();
envDef.Recipients.Signers.Add(signer);
envDef.Status = "sent";
ApiClient apiClient = new ApiClient("https://demo.docusign.net/restapi");
DocuSign.eSign.Client.Configuration cfi = new DocuSign.eSign.Client.Configuration(apiClient);
string authHeader = "{\"Username\":\"" + x+ "\", \"Password\":\"" + x+ "\", \"IntegratorKey\":\"" + x+ "\"}";
cfi.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
EnvelopesApi envelopesApi = new EnvelopesApi(cfi);
EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountID, envDef);
}
You are using Docusign Auto-Place (Anchor Tagging) in your request.
signHere.AnchorString = signHereAnchorString;
This will trigger a scan on the text in the document. If the scan finds the text specified in the variable signHereAnchorString anywhere in the document, it automatically places the "SignHere" option next to the text. That is the reason you are seeing "SignHere" option on all pages
You have couple of options if you want to place the Tag only on the last page
Option 1 - Using Anchor Tags: (See documentation here)
Modify your document to contain a unique string where you want to place the Signature tag. In this case, you could add the text "SignHereLastPage" in white font color (so that it isn't visible in the document) to where you want to place the Signature tag on the Document. Use "SignHereLastPage" as the anchor string.
You will just need to change one line in your code
signHere.AnchorString = "SignHereLastPage";
Option 2 - Fixed (or Absolute) Positioning (See documentation here)
You can use Absolute position of Tags and specify where you want to place the signature Tag. See Api recipe here
signer.Tabs.SignHereTabs = new List<SignHere>();
SignHere signHere = new SignHere();
signHere.DocumentId =docDocumentId;
signHere.PageNumber = "1"; // Specify the last Page number here.
signHere.RecipientId = signHereRecipientId;
signHere.XPosition = "100"; //You can adjust this based on your document
signHere.YPosition = "100"; //You can adjust this based on your document
signer.Tabs.SignHereTabs.Add(signHere);

iOS Google Analytics, I still see logs after setDry to YES

I have set dryRun to YES
#if DEBUG
[[GAI sharedInstance] setDryRun:YES];
[[[GAI sharedInstance] logger] setLogLevel:kGAILogLevelVerbose];
#endif
but still see logs like this
2014-10-03 08:58:09.933 HelloWorld[85791:677983] VERBOSE: GoogleAnalytics 3.09 -[GAIBatchingDispatcher persist:] (GAIBatchingDispatcher.m:431): Saved hit: {
parameters = {
"&_crc" = 0;
"&_u" = ".1111";
"&_v" = "mi3.0.9";
"&a" = 941551484;
"&aid" = "co.helloworld.ios";
"&an" = "HelloWorld";
"&av" = "1.0";
"&cd" = "Test Test";
"&cid" = "ca931366-1111-483b-bbcc-111111111111";
"&sr" = 320x568;
"&t" = screenview;
"&tid" = "UA-11111111-1";
"&uid" = "87492A55-98E4-4FF7-1111-111111111111";
"&ul" = en;
"&v" = 1;
"&z" = 4381801786046188211;
gaiVersion = "3.09";
};
timestamp = "2014-10-03 05:58:09 +0000";
}
Where is my fault? How can I disable GAS for debug?
You can also try to setDispatchInterval to negative or/and set optOut to true.

eclipse JDT setting the project

I am a beginner to Eclipse JDT. I was going through some tutorial and found one good example for creating the java file. In this below example in which project they will create the package and java file. I could not see any code pointing to any of the project name. Please make me understand if I am wrong. I just run the below example. I could not see any output..
AST ast = AST.newAST(AST.JLS3);
CompilationUnit unit = ast.newCompilationUnit();
PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
packageDeclaration.setName(ast.newSimpleName("example"));
unit.setPackage(packageDeclaration);
ImportDeclaration importDeclaration = ast.newImportDeclaration();
QualifiedName name =
ast.newQualifiedName(
ast.newSimpleName("java"),
ast.newSimpleName("util"));
importDeclaration.setName(name);
importDeclaration.setOnDemand(true);
unit.imports().add(importDeclaration);
TypeDeclaration type = ast.newTypeDeclaration();
type.setInterface(false);
type.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
type.setName(ast.newSimpleName("HelloWorld"));
MethodDeclaration methodDeclaration = ast.newMethodDeclaration();
methodDeclaration.setConstructor(false);
List modifiers = methodDeclaration.modifiers();
modifiers.add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
modifiers.add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
methodDeclaration.setName(ast.newSimpleName("main"));
methodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration();
variableDeclaration.setType(ast.newArrayType(ast.newSimpleType(ast.newSimpleName("String"))));
variableDeclaration.setName(ast.newSimpleName("args"));
methodDeclaration.parameters().add(variableDeclaration);
org.eclipse.jdt.core.dom.Block block = ast.newBlock();
MethodInvocation methodInvocation = ast.newMethodInvocation();
name =
ast.newQualifiedName(
ast.newSimpleName("System"),
ast.newSimpleName("out"));
methodInvocation.setExpression(name);
methodInvocation.setName(ast.newSimpleName("println"));
InfixExpression infixExpression = ast.newInfixExpression();
infixExpression.setOperator(InfixExpression.Operator.PLUS);
StringLiteral literal = ast.newStringLiteral();
literal.setLiteralValue("Hello");
infixExpression.setLeftOperand(literal);
literal = ast.newStringLiteral();
literal.setLiteralValue(" world");
infixExpression.setRightOperand(literal);
methodInvocation.arguments().add(infixExpression);
ExpressionStatement expressionStatement = ast.newExpressionStatement(methodInvocation);
block.statements().add(expressionStatement);
methodDeclaration.setBody(block);
type.bodyDeclarations().add(methodDeclaration);
unit.types().add(type);
You may take a look at this. It uses Java Model, which means you will need to create a plug-in to make it work.
// create a project with name "TESTJDT"
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject("TESTJDT");
project.create(null);
project.open(null);
//set the Java nature
IProjectDescription description = project.getDescription();
description.setNatureIds(new String[] { JavaCore.NATURE_ID });
//create the project
project.setDescription(description, null);
IJavaProject javaProject = JavaCore.create(project);
//set the build path
IClasspathEntry[] buildPath = {
JavaCore.newSourceEntry(project.getFullPath().append("src")),
JavaRuntime.getDefaultJREContainerEntry() };
javaProject.setRawClasspath(buildPath, project.getFullPath().append(
"bin"), null);
//create folder by using resources package
IFolder folder = project.getFolder("src");
folder.create(true, true, null);
//Add folder to Java element
IPackageFragmentRoot srcFolder = javaProject
.getPackageFragmentRoot(folder);
//create package fragment
IPackageFragment fragment = srcFolder.createPackageFragment(
"com.programcreek", true, null);
//init code string and create compilation unit
String str = "package com.programcreek;" + "\n"
+ "public class Test {" + "\n" + " private String name;"
+ "\n" + "}";
ICompilationUnit cu = fragment.createCompilationUnit("Test.java", str,
false, null);
//create a field
IType type = cu.getType("Test");
type.createField("private String age;", null, true, null);