Tag: c#

  • Visual studio project configuration file settings priority

    csproj in explorerTHE PROBLEM
    For multiple versions (Dev, Test, Prod) of a single ClickOnce application one has to name assemblies differently. In this way you can have all three versions on the same computer. This can be easily achieved by using configuration in Visual Studio. The problem I had was that no matter what the assembly name I specified in the configuration, it would not use it during build.

    SOLUTION
    The problem was hidden on the bottom of the “application.csproj” file. All the properties of each configuration were placed on top of the csproj file and the bottom parameter was always setting like a default value.

     
    .
    .
    .
    <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
       <OutputPath>bin\Release\</OutputPath>
       <DefineConstants>TRACE</DefineConstants>
       <Optimize>true</Optimize>
       <DebugType>pdbonly</DebugType>
       <PlatformTarget>AnyCPU</PlatformTarget>
       <ErrorReport>prompt</ErrorReport>
       <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>
       <AssemblyName>Application Test</AssemblyName>
       <ProductName>Application Test</ProductName>
       <InstallUrl>https://localhost/install/</InstallUrl>
       <PublishUrl>C:\Deploy\</PublishUrl>
       <UseVSHostingProcess>false</UseVSHostingProcess>
    </PropertyGroup>
    .
    .
    .
    <PropertyGroup>
       <AssemblyName>Application</AssemblyName>
    </PropertyGroup>
    .
    .
    .
    

    Just remove the bottom PropertyGroup and your configuration setting will be applied at build time. Don’t forget to always reload the project when you change the configuration file, as visual studio always reads it only at project load.

    PS: To edit the csproj you must first unload the project. Then you can right click on it and choose edit. (or use a text editor in explorer)

  • Use iText 4.1.6 to signing a PDF file with C#

    Here is an C# example of signing a PDF file with certificate in file using the latest free MPL & GPL version of iText. It can be downloaded from here (source) or here(DLL) or via NuGet package manager in Visual Studio.

    After importing iText in the project you have access to the following functions.

    The code for PDF processing goes like this:

     var _certificate = new X509Certificate2(@"C:\cert.pfx", "iLikeMyCertPass" , X509KeyStorageFlags.Exportable);
    
    var certParser = new Org.BouncyCastle.X509.X509CertificateParser();
    var chain = new Org.BouncyCastle.X509.X509Certificate[]
        {
          certParser.ReadCertificate(_certificate.RawData)
        };
    AsymmetricKeyParameter bouncyCastlePrivateKey = DotNetUtilities.GetKeyPair(_certificate.PrivateKey).Private;
    
    
    var reader = new PdfReader(@"C:\test.pdf");
    var writer = new FileStream(@"C:\test-signed.pdf"), FileMode.Create, FileAccess.Write);
    
    PdfStamper st = PdfStamper.CreateSignature(reader, writer, '\0');
    
    PdfSignatureAppearance sap = st.SignatureAppearance;
    
    sap.Layer2Font = new Font(Font.UNDEFINED, 4);
    sap.Reason = "I can sign it!";
    sap.Location = "At home";
    
    sap.SetVisibleSignature(new Rectangle(0, 0, 120, 35), reader.NumberOfPages, "Signature");
    sap.Render = PdfSignatureAppearance.SignatureRender.Description;
    sap.SetCrypto(bouncyCastlePrivateKey, chain, null, PdfName.ADOBE_PPKLITE);
    sap.Acro6Layers = true;
    //if I uncomment the following line the status of file is UNKNOWN in Acrobat reader
    //sap.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED;
    
    reader.Appendable = true;
    
    var dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
    dic.Reason = sap.Reason;
    dic.Contact = sap.Contact;
    dic.Location = sap.Location;
    dic.Date = new PdfDate(sap.SignDate);
    sap.CryptoDictionary = dic;
    
    int contentEstimated = 15000; //you can modify this you have loads of contents in signature
    
    var exc = new Hashtable();
    exc[PdfName.CONTENTS] = contentEstimated*2 + 2;
    sap.PreClose(exc);
    
    PdfPKCS7 sgn = new PdfPKCS7(bouncyCastlePrivateKey, chain, null, "SHA-1", false);
    IDigest messageDigest = DigestUtilities.GetDigest("SHA-1");
    Stream data = sap.RangeStream;
    byte[] buf = new byte[contentEstimated];
    int n;
    while ((n = data.Read(buf, 0, buf.Length)) > 0)
    {
        messageDigest.BlockUpdate(buf, 0, n);
    }
    byte[] hash = new byte[messageDigest.GetDigestSize()];
    messageDigest.DoFinal(hash, 0);
    DateTime cal = DateTime.Now;
    
    byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, null);
    sgn.Update(sh, 0, sh.Length);
    
    byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal, null, null);
    if (contentEstimated + 2 < encodedSig.Length)
        throw new Exception("Not enough space");
    
    var paddedSig = new byte[contentEstimated];
    Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length);
    
    var dic2 = new PdfDictionary();
    dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
    sap.Close(dic2);
    

    Leave any feedback if it doesn’t work.

  • Use iText 5.4.x to signing a PDF file

    Here is a sample code to sign a PDF using iTextSharp library and it is using a certificate file (with private key).

    X509Certificate2 cert = new X509Certificate2("C:\\mycert.p12");
    
    Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();
    Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] {
    cp.ReadCertificate(cert.RawData)};
    
    IExternalSignature externalSignature = new X509Certificate2Signature(cert, "SHA-1");
    
    PdfReader pdfReader = new PdfReader("C:\\multi-page-test.pdf");
    
    var signedPdf = new FileStream("C:\\multi-page-test-signed.pdf", FileMode.Create);
    
    var pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0');
    PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
    
    signatureAppearance.SignatureGraphic = Image.GetInstance("C:\\logo.png");
    signatureAppearance.Reason = "Because i can";
    signatureAppearance.Location = "Tu podpišem";
    signatureAppearance.SetVisibleSignature(new Rectangle(100, 100, 250, 150), pdfReader.NumberOfPages, "Signature");
    signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
    
    MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
    
  • Snippet for Ctrl-A Shortcut To Select All Text (Windows.Forms.TextBox)

    Set this event handler for your textbox to enable Ctrl-A shortcut and select all text:

    private void anyTextBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
    if (e.KeyChar == '\x1')
    {
    ((TextBox)sender).SelectAll();
    e.Handled = true;
    }
    }

    Thanks to:
    http://www.dzone.com/snippets/ctrl-shortcut-select-all-text