Curly-Q(uestion)s

March 31, 2021

Or , how I’ve spent the better part of the last several days, because I get obsessed with some computer that won’t obey me. Why can’t I simply treat it like my wife or my dog or my kids, and just let it dominate me? I suppose it’s a disorder of some kind. But if I medicated it, I’d never get anything done.

Helpful Links (great guys)

Cheap Work Around

Snippet

CURLOPT_SSL_VERIFYPEER => true

(Why do it the easy way when you can spend 20 hours and not get sneered at by random guys on the internet? )

Php Code (some of it):

Snippet

public static function curlPost($url , $header , $jsondata )
    {
        $json_string = json_encode($jsondata, JSON_PRETTY_PRINT);
        print ($json_string);
        fwrite(STDOUT, $json_string . "\n");
 
        $curl = curl_init();
 
        $myArray = _web::curl_options_array($url , "POST" , $header , null);
        curl_setopt_array($curl,  $myArray );
        curl_setopt($curl , CURLOPT_STDERR, fopen('/curl.txt', 'w+'));
 
        curl_setopt($curl, CURLOPT_POSTFIELDS, $jsondata);
 
 
        $response = curl_exec($curl);
        $err     = curl_errno( $curl );
        $errmsg  = curl_error( $curl );
        fwrite(STDOUT, $err . " " . $errmsg . "\n");
        $outheader  = curl_getinfo( $curl );
        fwrite(STDOUT, $outheader . "\n");
 
        curl_close($curl);
        var_dump($response);
        var_dump($err);
        var_dump($errmsg);
        var_dump($outheader);
 
        return $response;
 
    }
    public static function curl_options_array($url , $method = null , $header = null , $json = null)
    {
        if ( is_null ($method )) $method = "GET";
    //    CURLOPT_SSL_VERIFYPEER => false,


        $retArray =  array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_VERBOSE => true ,
        CURLOPT_ENCODING => "" ,                  // handle all encodings
        CURLOPT_CONNECTTIMEOUT => 120 ,           // timeout on connect
        CURLOPT_TIMEOUT => 120 ,                  // timeout on response
        CURLOPT_CUSTOMREQUEST => $method
        );

        if (  !empty($header)  ) $retArray[] = array(CURLOPT_HTTPHEADER => $header); // append the header
        if (  !empty($json) & $method == "POST" )   $retArray[] = array(CURLOPT_POSTFIELDS => $json); // append the data

        return $retArray;
    }


PHP.INI
With the php.ini fragment below, this produces an error code 77 error setting certificate verify locations:  CAfile: C:\Program Files\PHP\v8.0.3\extras\ssl\cacert.perm CApath: none  

And I've been trying various settings, even trying to integrate with Windows as below, so the current ini file doesn't reflect all the permutations it's gone through.

; https://martinsblog.dk/windows-iis-with-php-curl-60-ssl-certificate-problem-unable-to-get-local-issuer-certificate/
curl.cainfo = C:\Program Files\PHP\v8.0.3\extras\ssl\cacert.perm
openssl.cafile= C:\Program Files\PHP\v8.0.3\extras\ssl\cacert.perm
; https://thegeekpage.com/how-to-view-digital-certificates-installed-in-windows-10/
openssl.capath= C:\Users\tharvey2.UTK\AppData\Roaming\Microsoft\SystemCertificates\My\Certificates

Web Project

One thing I also tried was creating a Devsense/php web project , used IIS Express, and clicked the Enable SSL checkbox, with similar results: 60 SSL certificate problem: unable to get local issuer certificate

php.ini

curl.cainfo =”C:\Program Files (x86)\PHP\v8.0\extras\ssl\cacert.pem”

noob phpUnit (using DevSense php Tools for Visual Studio)

March 12, 2021

Visual Studio Solution:

Installing phpUnit

  • put the dll in the php/ext directory (php_xdebug-3.0.3-8.0-vs16-x86_64.dll)
  • add a phpunit.bat or phpunitcmd file in the php directory:
@ECHO OFF php “%~dp0phpunit-9.5.2.phar” %*

Installing xDebug

Xdebug: Installation instructions result

Follow directions

Code

Snippet

<?php
// namespace LearnVStudioTests; seems like namespaces are directories ...
use PHPUnit\Framework\TestCase;

// include_once(LIB.'/tst1.php');    //  BAD

 include __DIR__ . '/../tst1.php'; // GOOD
// include '../tst1.php';  //  BAD
//use LIB;
//set_include_path('LIB');

//spl_autoload_register(function ($class_name) {
//    $filepath = '../'  . $class_name . '.php';
//    include  dirname($filepath) ;
//});


final class tst1Test extends TestCase
{

    /**
     * @group StringTests
     */
    public  function test_hello_Assert()
    {
        $result = '';

        try {
            $result = tst1::hello('todd');
        }
        catch (Exception $e) {
            echo $e->getMessage(), "\n";
        }

        $this->assertEquals('Hello todd' , $result);
    }


   /**
    * @test
    * @group MathTests
    */
   public  function one()
   {
       $result = '';

       try {
           $result = tst1::addOne(99);
       }
       catch (Exception $e) {
           echo $e->getMessage(), "\n";
       }

       $this->assertEquals(100 , $result);
   }


/*
     * https://phpunit.readthedocs.io/en/9.5/organizing-tests.html#composing-a-test-suite-using-the-filesystem
     * https://docs.devsense.com/en/vs/testing/writing-test
 *
 * */

}


?>

Test
<?php
use PHPUnit\Framework\TestCase;

set_include_path('.');

class tst1Test extends PHPUnit_Framework_TestCase
{

    function hello_Assert()
    {
        $result = tst1.hello('todd');
        $this->assertEquals('hello todd' , $result);
    }


}


?>

Config

Snippet

<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/6.3/phpunit.xsd" backupGlobals="true" backupStaticAttributes="false" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" forceCoversAnnotation="false" processIsolation="false" stopOnError="false" stopOnFailure="false" stopOnIncomplete="false" stopOnSkipped="false" stopOnRisky="false" timeoutForSmallTests="1" timeoutForMediumTests="10" timeoutForLargeTests="60" verbose="false">
  <coverage includeUncoveredFiles="true" processUncoveredFiles="true" pathCoverage="true" ignoreDeprecatedCodeUnits="false" disableCodeCoverageIgnore="true">
  </coverage>
  <testsuites>
    <testsuite name="First">
      <directory>tests/</directory>
    </testsuite>
  </testsuites>
</phpunit>

<!-- https://github.com/moneyphp/money --> 

Notes:

  • a syntax error in the test script will prevent the test explorer from displaying your tests
  • see errors in the output windows , use the tab to select “output from tests”
  • open a command prompt in the project directory, run phpunit – this will help get your config debugged and whether or not your files can even be accessed (directory path in the config file)
  • once phpunit from command line works, then probably test explorer will display tests
  • I left the struggles I had in attempting to access LIB classes from the test directory. Apparently that’s a php thing.
  • Original question: getting started with phpUnit – DEVSENSE Community Forum

Classic ASP – How to see your 500 errors in IIS

September 3, 2020

1 Perform items 1 and 2 from the following URL.

https://docs.microsoft.com/en-us/iis/web-hosting/web-server-for-shared-hosting/asp

2 Add this to your web.config:

configuration
system.webServer
httpErrors errorMode=”Detailed”
asp scriptErrorSentToBrowser=”true”
/system.webServer
/configuration

(interleave the relevant portion, I include tags like “configuration” so you can see all the tags. And WordPress doesn’t like tags. You’ll figure it out.)

Javascript: nulls, empty string, and undefined

September 3, 2020

This was about 6 hours of pain over the past two days.

In the following code snippet, the ajax call failed because the value of sContentType was “undefined”
call_post: function (sData, sURL, sContentType) {

// if (this.debugOn === true) alert('call_post data:' + sData + ' url:' + sURL);

// content type "application/json" text/xml
if (sContentType === '') sContentType = '"application/json"';
if (sContentType === null) sContentType = 'application/json';
$.ajax({
cache: false,
type: "POST",
async: false,
url: sURL,
data: sData,
contentType: sContentType,

Maybe if I had done
if (!sContentType) sContentType = 'application/json';

It would have worked.

Magic of MVC , ViewModel containing a complex object and how it’s rendered in the DOM

August 14, 2020

I began with a database table.

I used entity framework to generate a class from the table.

I used visual studio and the “Edit” template to generate a page from that class.

Then I felt I needed more information on that page, so I instead based it on a ViewModel that contained as a member an instance of the table object, and I called the property of the viewmodel containing the table object “T”.

Because the @model of the page was now the ViewModel class, I edited every reference in the HiddenFor’s and EditorFor’s to point to model.T, as:
@Html.HiddenFor(model => model.T.tEmployeeTimesheetID)
@Html.EditorFor(model => model.T.EmployeeLinkingID, new { htmlAttributes = new { @class = "form-control" } })

When the page was rendered, the DOM components became:

Note how the id becomes T UNDERBAR parameter name and the name becomes T DOT parameter name.

When this page is posted to my controller post method, the parameter it expects is of the type of T (not the whole viewmodel, I don’t care about that crap at the time of post).

The magic of MVC converts all the DOM parameters named with UNDERBAR name to a parameter on the object T, and generates the entire object for me in the first line of the post method.

Very handy. I shudder to think of the code where the first 60 lines of a function are Request[parameterName].

Visual Studio (2019) ate my dll!

July 23, 2020

Not literally, but figuratively.

I repeatedly added a reference to a specific Oracle.ManagedDataAccess.dll file , and each time, Visual Studio decided to override the file I was attempting to make a reference to (version 4.121.1.0 ) and replace it with version 4.121.2.0. Why?

Here’s how I tricked it:
the issue was probably that in the LIB project I was adding the reference in, I also had a folder of DLL’s used , to make it easy for someone to check the project out of TFS and build it.
And the dll’s in that folder were in the project. It seems like Visual Studio saw that a member file had the same name as the external file I was attempting to add the reference to, and overrode me, repeatedly , for about 4 hours. So, I deleted the local copy from that DLLs folder, re-added from a remote folder, and this time the desired 4.121.1.0 version was deployed to my web server.

MVC attribute routing good/bad example

July 10, 2020

the controller class

namespace WEB.Controllers
{
[RoutePrefix("My")]
[Route("{action=Index}/{id ?}")] //default action
public class MyController : Controller

the method – FAILS

[ActionName("Next")]
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Next(string id")

the method – GOOD – must be an optional parameter to match the default route on the class.

[ActionName("Next")]
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Next(string id="")

Ajax call to web api – don’t use jsonp with GET

July 6, 2020

Doesn’t Work

$("#birds").autocomplete({
source: function (request, response) {
$.ajax({
url: "../api/Services/Departments",
dataType: "jsonp",
data: {'term' : request.term} ,
success: function (data) {
response(data);
}
});

Works

// http://localhost/HumanResources/Employment
$("#birds").autocomplete({
source: function (request, response) {
$.ajax({
url: "../api/Services/Departments",
dataType: "json",
data: {'term' : request.term} ,
success: function (data) {
response(data);
}
});

web service:

[System.Web.Http.AcceptVerbs("GET")]

public List Departments(string term="")

Route:

config.Routes.MapHttpRoute(
name: "Departments",
routeTemplate: "api/Services/Departments/{term}",
defaults: new
{
controller = "Services",
action = "Departments" ,
term = RouteParameter.Optional
});

Attribute Routing – { id } failed , {id} worked!

May 7, 2020


on the controller:
[RoutePrefix("Employee")]
[Route("{action=Index}/{id ?}")] //default action
public class EmployeeController : Controller

on the method:
[Route("Edit/{id}")]
[HttpGet, ActionName("Edit")]
public ActionResult Edit(int id)

this works

move a div

June 28, 2017

with position

xpos = xpos + x;
ypos = ypos + y;

$(".inner").parent().css({ position: 'relative' });
$(".inner").css({ left: xpos + 'px', top: ypos + 'px', position: 'absolute' });

console.log('AFTER x:' + $('.inner').position().left + ' y:' + $('.inner').position().top);

with offset

console.log('BEFORE x:' + $('.inner').position().left + ' y:' + $('.inner').position().top);

xpos = xpos + x;
ypos = ypos + y;

$(".inner:last").offset({top: ypos,left: xpos});
console.log('AFTER x:' + $('.inner').position().left + ' y:' + $('.inner').position().top);