Quantcast
Channel: Chilkat Tech Notes
Viewing all 414 articles
Browse latest View live

Chilkat v9.5.0.73 Release Notes

$
0
0

The v9.5.0.72 release notes are available here: Chilkat v9.5.0.72 Release Notes

v9.5.0.73 Release Notes:

  • Email The SetHtmlBody method, in certain circumstances, would incorrectly set the top-level MIME header to text/html for multipart messages. This was fixed.
  • HTTP Non us-ascii chars in the URL path are now always URL encoded using the utf-8 encoding.
  • OAuth2 Added the UseBasicAuth and AppCallbackUrl properties.
  • MailMan Added methods SendMimeBd and FetchMimeBd.
  • Bounce Fixed a few situations where bounce type 11 (Suspected Bounce) was returned, but should have been 6 (Auto-Reply). In general, minor improvements to Bounce categorization are added as customers report issues, and each new Chilkat version can be assumed to have minor Bounce categorization refinements.
  • Tar Fixed crash (access violation) in the Untar method. This was caused by a corrupt tar file where the internal header contained garbage bytes.
  • Objective-C/CkoJsonObject In iPhoneOS11.2.sdk/usr/include/complex.h, we find the following macro: “#define I _Complex_I”. This caused a compile error because the CkoJsonObject class has a property named “I”. Chilkat updated CkoJsonObject.h to “#undef I” to avoid the conflict.
  • Electron Added builds for Electron 1.8. However the package naming triggered some npm spam detectors (false positives of course), and Chilkat is working to get it resolved. Chilkat will produce builds for Electron 2.0 in the near future.
  • CkByteData Added a SecureClear bool property (get_SecureClear, put_SecureClear). If set to true, then whenever the internal data is deallocated, the memory is first overwritten with 0 bytes.
  • MIME Binary MIME with null bytes in some bodies became corrupted because 0 bytes were replaced with SPACE chars. This is fixed.
  • Signed/Encrypted Email Fixed: The “micalg” attribute incorrectly remained in the Content-Type header field for the encrypted MIME part when the email is also signed.
  • REST Fixed: Stream sources used for uploading were not properly closed after the upload finished.
  • C++ Builder/CkAuthAzureStorage Fixed: The x-ms-date header did not automatically get the correct current date/time for HTTP requests. This only happened for C++ Builder and Delphi builds of Chilkat.
  • Email Added flexibility in parsing non-compliant RFC822 date strings, where the month name and month day number are not in the correct order as specified by RFC822.
  • MIME parsing (general) Added more internal flexibility for handling mixtures of CRLF and bare-LF line endings.
  • XmlDSigGen Now capable of using non-exportable private keys on Windows, such as for A3 certificates where the private key is on a hardware token.
  • SSH Fixed a rarely encountered “handshake” problem.
  • HTTP Changed the default Content-Type for the PostJson method to be “application/json”. The original default value, “application/jsonrequest” was the initial “standard” years ago, but seems to never be used nowadays. If an “application/jsonrequest” is needed (and I doubt it will ever be needed), then PostJson2 may be called to explicitly specify the Content-Type.
  • HTTP The default value of the S3Ssl property is now true.
  • Zip Fixed rare problems involved with rewriting zip archives, when the “move from temp zip to target” fails.
  • Email Fixed certain automatic MIME structuring issues w.r.t. multipart/alternative and multipart/related.
  • Compression Added the DeflateLevel property to the Compression class.
  • CkString The removeDelimited method was missing for Ruby, Java, Perl, Python, Tcl, and PHP.
  • SFTP Fixed: The SyncTreeDownload method was not firing the DownloadRate callback.
  • PrivateKey Fixed: The GetPkcs8Pem method (for ECC keys) was returning PKCS1 but should’ve been returning PKCS8.
  • HTTP Added the SharePointOnlineAuth method.
  • HTTP Fixed problems with the S3_GenerateUrl and S3_GenerateUrlV4 methods.
  • SSH Fixed: After doing a ReadDir, the SFtpFile.IsDirectory property was not correct for some types of SSH servers.
  • Zip Added the PwdProtCharset property.
  • SOCKS5 Fixed problems with IPv6 addresses when using SOCKS5 proxies.
  • Compression Added the CompressSb and DecompressSb methods.
  • JSON Added the methods DtOf and DateOf to both JsonObject and JsonArray.
  • HTTP Fixed problems with non-us-ascii chars in URLs for downloads.
  • StringBuilder Added the ReplaceAfterFinal method.
  • HTTP Fixed: The LastHeader property was empty after the PostUrlEncoded method.
  • SSH Fixed slowness for SSH commands the emit a large amount of output.
  • HTTP Fixed rare server certificate verification problem when the server provides out-of-order certificates in the TLS handshake.
  • FTP2 Fixed: The IdleTimeoutMs property was not being honored for DNS problems.
  • StringBuilder Added the WriteFileIfModified method.
  • PureBasic Fixed a compile error in the CkHttp.pb file.
  • SSH/SFTP/SshTunnel Fixed a host key signature verification failure for certain situations.
  • SSH/SFTP/SshTunnel Added the UncommonOptions property, which will be a place to specify future unforeseen workarounds that may be required for particular SSH servers (old or new).
  • Rest/Socket Fixed a problem when a non-standard HTTP port (not 80 nor 443) is used in for the original Socket connection in conjunction with the Rest.UseConnection method.
  • RSA Added the SetX509Cert method to make it easy to use the private key of certificate. Also allows for A3 certificates where the private key is non-exportable (on a Windows system) such as on a hardware token.
  • XmlDSigGen Added the “X509Data+KeyValue” option for the KeyInfoType property.
  • JsonArray Added the FindString and FindObject methods.
  • Zip Fixed reliability issues in the UnzipToStream method.
  • XmlDSigGen Fixed: The X509SerialNumber in the X509IssuerSerial needed to be in decimal, not hex.
  • S/MIME Fixed an extremely rare issue where a digital signature verification failed but should’ve been successful.
  • JsonObject Fixed the “Unable to lock my JSON object.” error that would be returned if SetStringOf was called on an empty JsonObject.
  • CkString The loadFile method will now recognize Unicode/utf-8 BOMs and will load files correctly based on the BOM encountered.

SSH/SFTP Error: Must first connect to the SSH server

$
0
0

The following error is explained in this post:

ChilkatLog:
  DownloadFileByName:
    DllDate: Apr 25 2018
    ChilkatVersion: 9.5.0.73
    UnlockPrefix: *
    Architecture: Little Endian; 64-bit
    Language: Cocoa Objective-C
    VerboseLogging: 0
    SftpVersion: 3
    Component successfully unlocked using purchased unlock code.
    Must first connect to the SSH server.
  --DownloadFileByName
--ChilkatLog

The above error can happen after a long period of inactivity. Let’s say your application successfully connected and authenticated w/ the SFTP server, did some things, and then did not do anything else for a long period of time.  Meanwhile, the SFTP server decides to disconnect because the client has been inactive for too long.  The client (your app + Chilkat) would only discover that the server has dropped the connection once it tries to do something, such as in a call to DownloadFileByName.  The non-connected socket is discovered in the 1st attempt to send a message, and thus you receive the above error.

There are two possible actions an application might take:

  1. Prevent the disconnect by periodically calling sftp.SendIgnore to keep the connection from being inactive.
  2. (auto-recovery)  If DownloadFileByName (or some other method) returns false/0 to indicate failure, examine the sftp.IsConnected property.  If not connected, then automatically re-connect, re-authenticate, and call InitializeSftp to get back to a connected state, and then retry the method.

POP3 Error: No X-UIDL header found

$
0
0

The Chilkat MailMan class can fetch emails from a POP3 server in two ways: by sequence number, or by UIDL. When an email is fetched by UIDL, or fetched in a way such that a full mapping of UIDL’s to sequence numbers was retrieved, Chilkat will add an “X-UIDL” header to the Email object that is returned. This allows for the email object to be uniquely associated with the email on the server. (Sequence numbers change with each POP3 session, but UIDL’s don’t.)

For convenience, an email object is passed to some MailMan methods, such as w/ DeleteEmail. If the email was not retrieved in a way such that the UIDL was known, then the X-UIDL header will not be present, and the MailMan has no way of specifying which email on the server to delete. For example, if the email was downloaded by calling MailMan.FetchByMsgnum, then no UIDL was ever known (unless perhaps MailMan.GetUidls was previously called in the same POP3 session). Thus the error message in the LastErrorText is “No X-UIDL header found”.

One solution is to call MailMan.GetUidls beforehand. One call at the start of the POP3 session is sufficient.

HMAC Hex Key Ambiguity

$
0
0

This happens all the time..

Quite often, a service provider will provide instructions for HMAC generation, and will provide a hexadecimal HMAC key in the example, such as:

01A0251D601FEF3305A38B124068A001CF3F099AA187DB2886314C67CDFDEBCD

This is implicitly ambiguous because there are two ways to interpret the instructions:

1) The HMAC key is composed of the ascii bytes ‘0’, ‘1’, ‘A’, ‘0’, ‘2’, ‘5’, etc. In other words, the HMAC key is 0x30, 0x31, 0x41, etc.

or

2) The HMAC key is composed of the bytes represented by the hex string. In other words, the HMAC key is 0x01, 0xA0, 0x25, etc.

Both can be accomplished using Chilkat.
For the #1 case, one would call

crypt.SetMacKeyString("01A0251D … 67CDFDEBCD")

For the #2 case, one would call

crypt.SetMacKeyEncoded("01A0251D … 67CDFDEBCD","hex")

Chilkat v9.5.0.74 Release Notes

$
0
0

The Chilkat v9.5.0.73 release notes are available here: Chilkat v9.5.0.73 Release Notes

The Chilkat v9.5.0.74 release was only for the Node.js and Electron builds. It was required to support the release of the latest versions of Electron and Node.js
The .74 release will be skipped for all other programming languages.

How to Encrypt with no Padding (encrypted output size equals input size)

$
0
0

Block encryption algorithms, such as AES, will produce output that is a multiple of the algorithm’s block size. For AES, the output is a multiple of 16 bytes. However, this is for the typically used cipher modes “CBC” (Cipher Block Chaining) and “ECB” (Electronic Cookbook).

There are other cipher modes that turn a block algorithm into a stream cipher. See https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation

Namely, the cipher modes are:

  • Counter Mode (ctr)
  • Cipher Feedback (cfb)
  • Output Feedback (ofb)

In C++, for example, any of the above modes can be used with AES to produce output that is exactly the same size as the input.
For example


    CkCrypt2 crypt;

    crypt.put_CryptAlgorithm("aes");
    // Use Counter mode.  Other stream modes are "cfb" and "ofb".
    crypt.put_CipherMode("ctr");
    crypt.put_KeyLength(128);
    crypt.SetEncodedKey("000102030405060708090A0B0C0D0E0F","hex");
    crypt.SetEncodedIV("A0A1A2A3A4A5A6A7A8A9AAABACADAEAF","hex");

    const unsigned char plainText[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 };

    CkByteData data;
    data.append2(plainText,23);

    CkByteData encData;
    crypt.EncryptBytes(data,encData);

    printf("size of encrypted data = %d\n",encData.getSize());
    const unsigned char *pEncData = encData.getData();

IMPORTANT: The output of encryption consists of bytes that resemble random data, where each byte can have any value from 0x00 to 0xFF. DO NOT try to simply assign such binary data to a string (in any programming language). The purpose of binary encodings, such as base64, hex, etc. are to encode binary data in printable us-ascii chars. Thus, if you the desired encrypted output is to be stored in a string, it must be encoded. Hex encoding uses 2 chars per byte (i.e. 0x01 because “01”). Base64 is a more compact string representation of binary bytes.

Etsi, XAdES-BES, XAdES-EPES, FacturaE, Electronic Invoicing, etc.

$
0
0

Chilkat v9.5.0.75 will include features to make it easy to generate XAdES-BES and XAdES-EPES signatures for electronic invoicing and tax reporting for many countries.

The goal is to provide an easy and inexpensive solution for these complicated requirements.  Chilkat has been working with customers in Spain, Italy, Hungary, India, Brazil, Costa Rica, and elsewhere to get things working smoothly.  (Contact Matt at support@chilkatsoft.com for more information.)

The vision is to offer an online tool that generates the solution (source code) given a sample of already-signed XML.  This tool is live and functioning at https://tools.chilkat.io/xmlDsigGen.cshtml. The tool can generate code in any of approximately 30 different programming languages.  The tool will be updated and refined as Chilkat solves issues and challenges brought by the requirements of new customers.   XML digital signatures can be tricky, fragile, brittle, and different implementations for checking the validity of a signature can be quirky, have undocumented requirements, etc.  The idea is to build into the code generation tool the expertise for knowing the particular needs of different authorities, so you don’t have to spend weeks of frustration in getting things to work.

As time passes, and as more expertise is embodied within the code generation tool, I believe Chilkat can reach the point where it “just works”.

 

Stripe Webhooks?

$
0
0

Question from User:   Is there some sample code for Stripe Webhooks in classic ASP? I looked around, and didnt see anything.  Specifically, validating the signatures https://stripe.com/docs/webhooks/signatures

Answer:  A Webhook is an HTTP POST that will get sent to your server when a particular event occurs.   You would write an ASP page to receive the HTTP POST.  The ASP code to receive the HTTP POST is just straight ASP (no Chilkat involved).

You’ll write ASP code to get the POST’s data. If the POST was an application/json Content-Type, then the body of the HTTP POST will contain JSON.   If the POST was an application/x-www-form-urlencoded Content-Type, then you’ll have name/value params.  The Stripe online developer documentation should tell you about format and data contained in each event’s POST.

Once you’ve accessed/extracted the POST’s data, then you might use Chilkat to help in processing it — such as for the JSON parsing or signature validation.  To help answer questions about signature validation, I would first need to see a sample of the POST data for that particular case.

 


Bd Methods Prevent Copying Huge Amounts of Data

$
0
0

Question: 

One use is for unzip a resource embed into an assembly (.dll). The resource is approximately 224MB in size.   The program sometimes throws an out-of-memory exception.   The exception is thrown by Chilkat.Zip.OpenFromMemory and OpenFromByteData methods.

How can this problem be solved?

Answer:

First, this is truly an out-of-memory condition.  The two possible solutions are (1) to allow your application to use more memory (not sure if this is possible, but you might look here for information on the topic:  https://www.codeproject.com/Articles/483475/Memory-Limits-in-a-NET-Process ) or (2) to use less memory.

The OpenBd method can be used to significantly reduce memory usage.   The problem with OpenFromMemory (and OpenFromByteData) is that the contents of the zip are passed in a .NET managed byte array.  The data must be marshaled from managed memory to unmanaged, and this causes the full 224MB to exists twice in memory (in managed memory within your .NET application, and in unmanaged memory within the underlying native Chilkat C++ implementation).

A better solution is to use a Chilkat.BinData object to load the contents of the file, and then call zip.OpenBd.  This way you’re just passing a handle to the BinData object instead of 224MB.  The zip data exists only once in memory.

*** In general, Chilkat is incrementally adding “Bd” and “Sb” methods for those methods in Chilkat classes that can potentially pass large amounts of binary or text data.  The “Sb” methods pass a Chilkat.StringBuilder object.  The same concept applies:  Instead of marshaling a huge string in the method call, the application can pass a StringBuilder object which contains the text.

Using “Bd” and “Sb” methods is better for other programming languages too, especially anything using the ActiveX because strings in ActiveX/COM are passed as BSTR’s (utf-16) and binary byte data is passed in Variants.  The overhead of conversion/marshaling can be eliminated by using the Bd and Sb methods.

 

Chilkat v9.5.0.75 Release Notes

$
0
0

The v9.5.0.74 release notes are available here: Chilkat v9.5.0.74 Release Notes

v9.5.0.75 Release Notes:

  • Not Finished Yet The release notes listed here are in progress and not yet completed..
  • Smartcard/USB Tokens Support for Smartcard and USB tokens is much improved. Note: At this point, smartcards and USB tokens are supported on Windows operating systems only.
  • XmlDSigGen Many improvements and fixes to XML digital signature generation and verification…
  • Cert Added the Cert.SmartCardPin property.
  • Amazon/AWS Fixed problems with non-us-ascii chars in x-amz-meta-* headers
  • AuthUtil Fixed AuthUtil.WalmartSignature for POST/PUT operations.
  • Imap Fixed: The QuotaRoot method returned invalid JSON in some cases.
  • PFX/P12 Added the ability to open .pfx/.p12 files where two different passwords are required: one for integrity and the other for the private keys. See the example at https://www.example-code.com/csharp/pfx_multiple_passwords.asp
  • Cert Fixed the ValidFrom and ValidTo properties for some certificates (a rare problem, the vast majority of certs exhibited no problems with these properties).
  • ZipCrc Added the CrcString, CrcSb, and CrcBd methods for greater flexibility in calculating CRC32 checksums.
  • Cert Added the HashOf method to return the encoded hash of a particular part of a certificate.
  • Http Added the CreateTimestampRequest and VerifyTimestampReply methods to provide the ability to send RFC 3161 timestamp requests to a TSA (Timestamp Authority).
  • SFtp Fixed the LastReadNumBytes method which always returned 0.
  • Http Fixed certain URL and percent encoding problems for paths and query params.
  • PrivateKey Added the LoadAnyFormat method to load a private key from any text or binary format.
  • Rest Fixed auto-reconnect when the connection is thought to exist, but found to not exist when sending the request.
  • XmlDSigGen Added the empty-string option for the canonMethod argument to the AddSameDocRef, AddObjectRef, and AddExternalXmlRef methods. This makes it possible to add a reference with no transformations.
  • Ssh Added the Ssh.ClientPort property.
  • Rest Can set the expectedStatus argument of the SetResponseBodyStream to a negative number to indicate a range of expected status codes. (See the online reference documentation.)
  • CkString Fixed: The saveToFile method did not write a file with no BOM (Byte Order Mark) when passing “no-bom-utf-8” for the charsetEncoding.
  • XmlDSigGen Added the “TransformSignatureXPath” keyword to the Behaviors property.
  • Http Added the ResumeDownloadBd method.
  • Http Fixed receiving XML responses where the charset is not indicated in the Content-Type response header, but is available in the XML declarator contained in the response body.
  • SFtp Downloading to a file (DownloadFileByName) will check to see if the local target file already exists. If so, it will try to delete it prior to downloading. If it is not possible to delete, then the DownloadFileByName will return failure before trying to download the file.
  • Ssh Fixed the Ssh.HostKeyFingerprint property for ECDSA keys.
  • Http Fixed problem that occurred for request sent with: “Accept-Encoding: gzip, deflate”
  • XmlDSigGen Added the SignedInfoId property.
  • XmlDSigGen Added the KeyInfoId property.
  • XmlDSigGen Added the SetRefIdAttr method.
  • encoding Added the “hexlower” encoding. “hexlower” may be used instead of “hex” to get the hexadecimal encoding using lowercase a-f (“hex” produces uppercase A-F).
  • JsonObject Added the InsertNewArray and InsertNewObject methods.
  • PFX/P12 Fixed a problem with not properly recognizing OID 1.2.840.113549.1.1.10 in some circumstances.
  • Email Fixed a problem with the SetSigningCert and SetSigningCert2 methods.

Calling a REST GET API and Parsing JSON/XML Response

$
0
0

This blog post describes a general procedure for writing code that calls an HTTP/HTTPS GET REST API and parses the JSON or XML response.

Step 1: Form the CURL Command

A GET request in the form of a CURL command will look like this:

curl -X GET https://test-api.service.hmrc.gov.uk/organisations/vat/123456789/obligations \
-H "Accept: application/vnd.hmrc.1.0+json"  \
-H "Authorization: Bearer hmrc_app_server_token"

Some notes:

  • Header fields are added using the “-H” option.  Add the header fields and values as required by your particular REST API.
  • If OAuth2 authentication is required, the OAuth2 access token is provided in an “Authorization: Bearer …” header field.
  • If HTTP Basic authentication is required, which means providing a username/password, then use the –user option like this:
    --user username:password
    
  • Query params are added in the URL and should appear just as they would in a browser address bar.

Step 2. If the REST API GET returns JSON or XML, get a representative sample of the JSON or XML response.  For example:

{
  "obligations": [
    {
      "start": "2017-01-01",
      "end": "2017-03-31",
      "due": "2017-05-07",
      "status": "F",
      "periodKey": "18A1",
      "received": "2017-05-06"
    },
    {
      "start": "2017-04-01",
      "end": "2017-06-30",
      "due": "2017-08-07",
      "status": "O",
      "periodKey": "18A2"
    }
  ]
}

Step 3.  Generate Code

Go to the online tool at http://tools.chilkat.io/curl.cshtml and generate code in any of 29 different programming languages.  Paste the CURL command and respresentative JSON/XML response into the text boxes, and select the type of response (JSON, XML, Text, or Binary).  If the GET returns just a status code, such as 201, and no response body, then select “Text” as the type of response.

Then click “Generate Code” and your sample code is generated.  It generates code to send the request and to parse the JSON or XML response.

Calling a REST POST API and Parsing JSON/XML Response

$
0
0

This blog post describes a general procedure for writing code that calls an HTTP/HTTPS POST REST API and parses the JSON or XML response.

Step 1: Form the CURL Command

A POST request in the form of a CURL command will look like this:

curl -X POST https://test-api.service.hmrc.gov.uk/organisations/vat/123456789/returns \
-H "Accept: application/vnd.hmrc.1.0+json"  \
-H "Content-Type: application/json" \
-H "Authorization: Bearer hmrc_app_server_token" \
-d '{
  "periodKey": "#001",
  "vatDueSales": 100.00,
  "vatDueAcquisitions": 100.00,
  "totalVatDue": 200,
  "vatReclaimedCurrPeriod": 100.00,
  "netVatDue": 100,
  "totalValueSalesExVAT": 500,
  "totalValuePurchasesExVAT": 500,
  "totalValueGoodsSuppliedExVAT": 500,
  "totalAcquisitionsExVAT": 500,
  "finalised": true
}'

Some notes:

  • Header fields are added using the “-H” option. Add the header fields and values as required by your particular REST API.
  • If OAuth2 authentication is required, the OAuth2 access token is provided in an “Authorization: Bearer …” header field.
  • If HTTP Basic authentication is required, which means providing a username/password, then use the –user option like this:
    --user username:password
    
  • If the request body contains JSON or XML, then query params are added in the URL and should appear just as they would in a browser address bar.  For example: https://test-api.service.hmrc.gov.uk/organisations/vat/123456789/returns?param1=value1&param2=value2
  • If the Content-Type is to be application/x-www-form-urlencoded, then params are specified using “-d” options. In this case, the Content-Type does not need to be explicitly specified.  For example:
    curl -X POST http://mws.amazonservices.com/Feeds/2009-01-01 \
      -d "AWSAccessKeyId=AWS_ACCESS_KEY_ID" \
      -d "Action=CancelFeedSubmissions" \
      -d "FeedSubmissionIdList.Id.1=1058369303" \
      -d "FeedTypeList.Type.1=_POST_PRODUCT_DATA_" \
      -d "FeedTypeList.Type.2=_POST_PRODUCT_PRICING_DATA_" \
      -d "MWSAuthToken=MWS_AUTH_TOKEN" \
      -d "Marketplace=ATExampleER" \
      -d "SellerId=MWS_SELLER_ID" \
      -d "SignatureMethod=HmacSHA256" \
      -d "SignatureVersion=2" \
      -d "Timestamp=CURRENT_DATE_TIME" \
      -d "Version=2009-01-01" \
      -d "Signature=MWS_SIGNATURE"
    
  • The JSON or XML body is specified in a “-d” option.  Enclose the full JSON or XML document in single quotes as shown above.

Step 2. If the REST API POST returns JSON or XML, get a representative sample of the JSON or XML response. For example:

{
  …  whatever JSON is returned goes here …
}

Step 3. Generate Code

Go to the online tool at http://tools.chilkat.io/curl.cshtml and generate code in any of 29 different programming languages. Paste the CURL command and respresentative JSON/XML response into the text boxes, and select the type of response (JSON, XML, Text, or Binary). If the POST returns just a status code, such as 201, and no response body, then select “Text” as the type of response.

Then click “Generate Code” and your sample code is generated. It generates code to create the JSON or XML request body, send the request, and to parse the JSON or XML response.   (If you already have the JSON/XML request body composed by some other means, then just ignore the generated code that creates the JSON/XML.)

SSH/SFTP Connection Error: Failed to read KEX_DH_GEX_REQUEST response

$
0
0

The “Failed to read KEX_DH_GEX_REQUEST response” error happens if using a very old version of Chilkat SSH/SFTP with a newer SSH server.   The solution is to update to the latest version of Chilkat.

PayPal REST API OAuth2 Authentication

$
0
0

There’s a lot of confusion about exactly what login/password (or clientID/clientSecret) is to be used for obtaining an OAuth2 access token for PayPal REST API calls.

PayPal uses simple HTTP Basic authentication (protected by a TLS connection) to obtain an access token.   Using the Chilkat Rest library, your application would provide the credentials in this way (in pseudo-code)

rest.SetAuthBasic("CLIENT_ID", "API_SECRET");

So… where exactly does one get the CLIENT_ID and CLIENT_SECRET???

Go to https://developer.paypal.com/developer/accounts/

Click on the “Profile” link for one of your Sandbox accounts.  Then go to the “API Credentials” tab.  You’ll see the following.
(Note: You should have first defined/created a REST app within your PayPal account.  You’ll see it here.  In my case, the name of my REST App is “Chilkat”.  Yours will be whatever you named it.)

Next, click on your REST App.  You’ll see this:

The Client ID and API Secret are the values that should be passed to rest.SetAuthBasic.

Necessary to Import Certificate from USB Token to Windows CertStore?

$
0
0

Question:

Is it necessary to import certificate from USB token to Windows CertStore to sign with success?

If YES, is there a way to do it programmatically and obtain the CommonName to store somewhere for future use?

It will be very heavy for us to do it manually for each customer.

Answer:

Yes, the certificate from the certificate-based USB token must be installed to the Windows certificate store.  The underlying Microsoft CNG (Cryptographic Next Generation) API needs this to know where the private key is located, which is on the USB hardware token.  Unfortunately, I don’t know of a way to automate the installation of a USB token, or if it’s even possible.


WSAEACCES An attempt was made to access a socket in a way forbidden by its access permissions

$
0
0

Question:

Do you have any idea what I could do to get around the following error that is generated by Chilkat DLL?  I have verified that I can run PHP scripts (i.e., version()) through the port 3017 in localhost, so IIS and PHP are configured properly.  The lcUrl = loOauth2.StartAuth() function call kicks up the WSAEACCESS error.  I can see with netstat that port 3017 is listening, and I have tried temporarily disabling any virus software and windows firewall, and I made sure our Cisco firewall hardware is configured to allow port 3017 communications.

This is the error:

ChilkatLog:
  StartAuth:
    DllDate: Aug 25 2018
    ChilkatVersion: 9.5.0.75
    UnlockPrefix: Anything for 30-day trial
    Architecture: Little Endian; 32-bit
    Language: ActiveX
    VerboseLogging: 0
    bindAndListen:
      port: 3017
      backlog: 5
      listenOnPort:
        SocketError: WSAEACCES An attempt was made
to access a socket in a way forbidden by its
access permissions.
        Socket bind failed.
      --listenOnPort
      listenPort: 3017
      Failed.
    --bindAndListen
    Failed.
  --StartAuth
--ChilkatLog_

Answer:

Port 3017 was being used by some system service, but 3018 worked, and I got the access token.

 

 

Chilkat HTTP Methods that return an HttpResponse Object

$
0
0

Question:

I am having a problem identifying read timeouts from sites.

I set ConnectTimeout and ReadTimeout properties of the HTTP object.

When the site fails to respond within ReadTimeout, the following happens:

  • PText still returns 0
  • PText returns a response object
  • Reading of StatusCode and StatusText properties of the response object is successful
  • Reading of BodyStr property of the response object is successful
  • StatusCode is 0
  • StatusText is empty
  • BodyStr is null

What would be the proper way of identifying ReadTimeout (and potentially ConnectTimeout) ?

Answer:

  • The ConnectTimeout property is the number of seconds to wait for the web server to accept the connection for the HTTP request.  If no connection to the server could be established after waiting for this number of seconds, the method will return a null pointer (0) instead of an HttpResponse object, and the http.ConnectFailReason property will be set to an integer value indicating the reason.
  • Once the TCP connection is made, the ReadTimeout applies to receiving responses from the server.  This includes the TLS handshake that happens automatically when connecting via TLS (i.e. https).   The ReadTimeout is the max time to wait for more incoming data.  It is NOT the max time to wait for an entire response.  Let’s say the response is 20 gigabytes, and the ReadTimeout is 60. It will take a long time to receive 20 gigabytes; much longer than 60 seconds.  However, if the incoming data pauses for more than the ReadTimeout value, then Chilkat will return with a failure.
  • If a method returns 0/null instead of an HttpResponse object, then it means no response was received.  It may be that the failure was during the sending of the request.  Or it may be that the request was sent, but the server did not respond, or maybe the server disconnected for some reason (perhaps it did not like the content of the request).
  • I don’t think it’s possible for an HttpResponse object to be returned with a StatusCode = 0.   The first thing sent in an HTTP response is the status code, so if any response is received, it should at least have a status code.   (If an application instantiates a new instance of HttpResponse, then the StatusCode would have an initial value of 0.)
  • The StatusText, like the StatusCode, shouldn’t be empty if any response was received.
  • The HttpResponse.BodyStr should never be null because it’s a property.  A string *property* (as opposed to a method that returns a string) can never be null.  It can be empty, and an HTTP response that contains no body can certainly happen.  For example, it is typical for 204 status code responses to contain no body.

 

Convert CSV to utf-8?

$
0
0

Question:

We’ve purchased a few of your products in the past and they work great.  Here’s a question on another one:  I’m creating a .csv file within a vfp program and I need it to be an Utf-8 format.  I’m not finding anywhere how to do that programatically.  Do you have a product that will convert?

Answer:

For those that may not be familiar with the meaning of “character encoding”, it defines the byte representation for characters.  For example:

Consider the character: É

  • In the iso-8859-1 character encoding, it is represented by a single byte: 0xC9
  • In the utf-8 character encoding, it is represented by a two bytes: 0xC3 0x89
  • In the ucs-2 character encoding, it is represented by a two bytes: 0x00 0xC9

To save text (such as the CSV text) to a file using any desired character encoding, load the string into a Chilkat StringBuilder object, then call StringBuilder.WriteFile.

The arguments to WriteFile are:

  1. localFilePath — the local path of the file to create.
  2. charset — such as “utf-8”.
  3. emitBom — true/false (or 1/0) to indicate if a Byte Order Mark is desired.  BOM’s (also known as preamble) exist for utf-8, utf-16, utf-32, and big-ending utf-16/32.  If you don’t know if you want it, choose false.  A BOM is a sequence of 2 or 3 bytes that indicates the charset of the file.  For example, if the 1st three bytes of a text file are 0xEF,0xBB,0xBF, then you have a utf-8 file.

Note: In some programming languages, such as VB6, VB.NET, C#, FoxPro, and many others, a “string” is an object.  You never deal with the actual byte representation of individual characters.  Therefore, if you have a string (such as in Visual FoxPro or C#), you can pass it to StringBuilder.WriteFile without worry.  Chilkat will write the characters using the byte representation (i.e. character encoding) desired for the file.

Also, everywhere in the Chilkat API where a charset can be specified, any of the charset’s listed at http://cknotes.com/chilkat-charsets-character-encodings-supported/ may be used.

 

 

Test Creating ActiveX Object using VBScript (.vbs)

$
0
0

This article guides you to verify that the Chilkat ActiveX is installed properly and that it’s possible to create an instance of the object.

Please first read this tutorial to understand basic concepts:  https://chilkatsoft.com/activex_dll_registration_tutorial.asp

Step 1.  Download and register the 32-bit Chilkat ActiveX from here: https://chilkatsoft.com/downloads_ActiveX.asp
*select the Zip Install (manual registration)
* DO NOT unzip in C:\Windows or C:\Windows\system32.  Never put files in those directories.
* Unzip to any directory in the “C:” drive.  Do NOT unzip to a mapped or network drive (the DLL will NOT be trusted by Windows).

Make sure you carefully followed the instructions.

Step 2.  We’ll assume you’re running on a 64-bit Windows computer.  To register the 32-bit ActiveX on 64-bit Windows, run the register_x64.bat script that came with the download.  Double-click on register_x64.bat to run it.  This should register the 32-bit ActiveX DLL to your 32-bit Current User Windows Registry.

Step 3. Next we’ll register the 32-bit ActiveX to the 32-bit Local Machine Windows Registry.  This would be needed for applications that run in IIS, as a Windows Service, or as administrator.   Right-click on register_x64.bat and “Run as administrator“.

Step 4.  Download and register the 64-bit ActiveX from here:
*select the Zip Install (manual registration)
https://chilkatsoft.com/downloads_ActiveX.asp

Step 5. Register the 64-bit ActiveX (not as administrator).   Double-click on the register.bat script that came with the download.  This should register the 64-bit ActiveX DLL to your 64-bit Current User Windows Registry.

Step 6. Next we’ll register the 64-bit ActiveX to the 64-bit Local Machine Windows Registry.  Right-click on register.bat and “Run as administrator“.

Next we’ll verify that the ActiveX can be instantiated from VBScript in each of the above cases.

Step 7.  Create a file named testCreateObject.vbs using a text editor.   Copy the following and save.

set zip = CreateObject("Chilkat_9_5_0.Zip")
MsgBox zip.Version

success = zip.UnlockComponent("test")
MsgBox zip.LastErrorText

Step 8.  In the same directory, create a file named testCreate32.bat.  Copy the following and save.

REM This is the 32-bit cscript.
C:\windows\sysWOW64\cscript testCreateObject.vbs
pause

Step 9.  Open a command prompt in the directory where the .vbs and .bat files you just created are located.  Run testCreate32.bat   You should see two message boxes.  The 1st shows the version.  The 2nd shows the LastErrorText for the call to UnlockComponent.  Notice the line that reads “Architecture: Little-Endian; 32-bit”.  This indicates that you’re running in a 32-bit process that loaded the 32-bit ActiveX.

Step 10.  This time, open an administrative command prompt in the same directory and repeat.   If you don’t know how to open an administrative command prompt, Google it…

Step 11. Create a file named testCreate64.bat.  Copy the following and save.

REM This is the 64-bit cscript.
cscript testCreateObject.vbs
pause

 Step 12.  Using a non-administrative command prompt, run testCreate64.bat    The LastErrorText should contain a line that reads:  “Architecture: Little-Endian; 64-bit”.  This indicates that you’re running in a 64-bit process that loaded the 64-bit ActiveX.

Step 13.  Do the same as Step 12, but with an administrative command prompt.  This verifies that the 64-bit ActiveX was properly registered to the Local Machine registry.

Note: The above steps registered and tested the Chilkat ActiveX in all four possible registries:

  • 32-bit Current User Registry
  • 32-bit Local Machine Registry
  • 64-bit Current User Registry
  • 64-bit Local Machine Registry

 

CkPython vs. Chilkat2-Python

$
0
0

Question:

Should I use CKPython or Chilkat2-Python for a new development (environment = Windows and Python 3.6)
What’s the difference between these?

Answer:

The CkPython API is the original Chilkat for Python API that uses something called SWIG (swig.org) to produce the Python wrappers around the C/C++ implementation.  The result is that CkPython API has a style with more a C/C++ flavor that can be distasteful to Python developers.  The Chilkat2-Python API does not use SWIG for the wrapping and results in a more natural Python API.

For example, CkPython looks like this:

imap.put_Ssl(True)
imap.put_Port(993)
success = imap.Connect("imap.someMailServer.com")

Whereas Chilkat2-Python looks like this:

imap.Ssl = True
imap.Port = 993
success = imap.Connect("imap.someMailServer.com")

A few more notes about the differences…

  • Chilkat2-Python is not available for Python 2.6 or 2.7.  It is available for Python versions 3.0 (for some operating systems, such as Alpine Linux, it is available for 3.4 and up, but this is only because we suspect nobody actually needs the older versions of Python on these systems).
  • Chilkat2-Python uses memoryview for passing and returning binary bytes.  Coping directly with binary bytes is difficult in CkPython.
  • The CkPython download contains both a “chilkat.py” and a “_chilkat.so” that are installed to the Python site-packages directory.  The Chilkat2-Python download has no need for a “chilkat.py” wrapper and simply contains a “chilkat2.so” which is installed to the site-packages directory.

If starting fresh with Chilkat in Python, I would recommend using Chilkat2-Python.

Viewing all 414 articles
Browse latest View live