Archive for the ‘Uncategorized’ Category

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

mixed razor and html (a little beyond the simple examples you find at w3 school)

July 1, 2014

mixed razor and html (a little beyond the simple examples you find at w3 school)

(sorry about this post all in an image … I’m not skilled enough at word press to format all my bracket characters)

here is what finally worked
we took out as much razor as possible, and now I’m happy. I failed to catch another error in the image of all my travails with this – we got the asp.net system message that echoed to the screen, and the fix for that was to put in a “using” statement … and I could not get this to work in a reasonable amount of time. (less than 4-6 hours) Less razor is a good thing.


    
@Model.pagingLabelText

adding a website to tfs

October 16, 2012

What didn’t work:

1) create empty Visual Studio 2010 solution

2) add an existing website to the solution. (http://localhost:81/myWebSite ) . It was port 81 because I also have Sharepoint on this pc.

What was wrong? the website could not be added to TFS.

Steps to fix:

1) add another existing library project to the solution (I needed it anyway). I think otherwise I couldn’t delete the website from the solution.

2) delete the website from the solution

3) re-add the same website, this time using the “File System” rather than IIS.

4) Check in to TFS no problems.

 

 

when all else fails

September 11, 2012

kind of a comment on that last post – actually, I had the code correct for about 15 minutes or so,  and continued to get 404 errors, and also my test html page did not reflect the posting url in the latest copy of the html file  in my project (which was weird). So I went to the trusty IE/tools/in private browsing to make sure I was starting from a clean playing field, and it all worked.

Too bad that the cached junk had led me down a few stray rabbit trails.

change page url

June 4, 2010

ok, what I learned was that you can’t change the page url using the httpcontext.current.request.rewritePath function. But, to achieve that effect, I did the following:

Protected Sub ddlListRecentErrorSessions_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlListRecentErrorSessions.SelectedIndexChanged
Dim sSession As String = Me.ddlListRecentErrorSessions.SelectedValue
set_url_for_session(sSession)
'handle_load_gridview_for_session(Me.gvResult, sSession)
End Sub

'http://forums.asp.net/p/1315610/2601836.aspx
'Using Context.RewritePath is not for changing how the URL is displayed
'in the browser. Let's be very, very clear.
'You cannot change what is displayed in the browser address bar.
Sub set_url_for_session(ByVal sSession As String)
' change the url to use our session
Dim sPath As String = HttpContext.Current.Request.Path
Dim sQuery As String = "?session=" + sSession
Diagnostics.Debug.Print("set_url SESSION=" + sSession)
Dim sFullPath As String = sPath + sQuery
Response.Redirect(sFullPath, True)
Response.End()
'HttpContext.Current.RewritePath(sPath, True, sQuery)
End Sub

Ghost Process Writing to Visual Studio 2008 Debug Immediate Window

November 4, 2009

If you’ve never seen something like this, you might not believe it.

In debugging a website running under, I had debug.print lines from another website appearing in the immediate window.
They stopped if:
1) I shut down IIS (of course, that killed my debugging as well)
2) I detached the asp_wp worker process from the debugger (and then I couldn’t debug my own project)
3) killing the asp_wp processes from Task Manager gave a brief respite, but the messages started again once the worker process was reactivated.

What I finally did, and this is a temporary fix, is to luckily guess the offending website under IIS, and rename the directory. Now, that website is not able to be browsed.

I had only one instance of IE or any other browser open during the time when I was trying to fix the problem. (generally I have many open)

I suspected some scheduled process browsing to the website – that is still a possibility.
Also, I suspect a coding practice of mine, which is to use some debug logging code in static (vb – shared) functions. Perhaps IIS is for some reason opening this virtual directory? (I know I said web site above, but actually I mean a virtual directory under the same website running in the same IIS .Net 2 process.)
Also, the virtual directory in question was the last one in alphabetical order of all my virtual directories.

I did not search Knowledge Base about this. It’s something I’ve lived with for weeks, at least, and just ignored, until this AM.

How to set an environment variable by setting it in the registry

June 5, 2009

It’s easy to do a “getenv” , but you’d be surprised at how hard it is to set an environment variable.
Sorry, I’m not going to take the time to write here what I learned from some excellent explanations found at codeguru and elsewhere, but I’ll try to post those links at the last.
Basically:
1) set the current user\environment\yourstring=value in the registry
2) send a windows refresh message (this doesn’t communicate with whatever command prompts you may already have, but it will work for the calling process)
3) whatever new command prompt or process will use your new setting


LRESULT CMainDlg::OnSetMyEnvironmentValue(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CString sNetId;
GetDlgItem(IDC_NETID).GetWindowTextA(sNetId);

Handle_SetReg(sNetId);
Handle_RefreshEnvironment();
return Handle_SetEnv(sNetId);
return 0;
}

int CMainDlg::Handle_SetEnv(CString sNetId)
{
//MessageBox (sNetId, "netid", 0) ; //sNetId.GetBuffer()

// set env variable
int iRet = 0;
iRet = SetEnvironmentVariable("netid", sNetId.GetBuffer() );

if( iRet <=0 )
{
GetLastError();
return -1;
}
return 0;

}

int CMainDlg::Handle_SetReg(CString sNetId)
{
CString subKey = "Environment";
HKEY hKey;
char *m_tmpChar = new char[100];

if (RegOpenKeyEx(HKEY_CURRENT_USER, subKey, 0, KEY_SET_VALUE, &hKey))
{
MessageBox("Error opening the key");
RegCreateKey(HKEY_CURRENT_USER, subKey,&hKey);
}

if ( RegSetValueEx(hKey, "netid" , NULL , REG_SZ, (unsigned char*)sNetId.GetBuffer() ,sNetId.GetLength() +1) )
MessageBox("Error setting the value");
RegCloseKey(hKey);

return 0;
}

// http://wiki.answers.com/Q/How_do_you_set_registry_entry_as_environment_variable
int CMainDlg::Handle_RefreshEnvironment()
{
DWORD_PTR dwReturnValue;

SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
(LPARAM) "Environment", SMTO_ABORTIFHUNG,
500, &dwReturnValue);
return dwReturnValue;
}

Here were some helpful links:
reading:
basics
http://www.codeguru.com/forum/showpost.php?p=1171365&postcount=7

REGISTRY
HKEY_CURRENT_USER\Environment
HKEY_CURRENT_USER\VolatileEnvironment
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
http://vlaurie.com/computers2/Articles/environment.htm
VISTA http://vistaonwindows.com/environment_variables.html

registry
http://www.codeguru.com/cpp/w-p/system/registry/print.php/c5793

6/4/09
helpful
http://wiki.answers.com/Q/How_do_you_set_registry_entry_as_environment_variable

looks like broadcasting the wm_settingchange won’t talk to cmd prompts
http://coding.derkeiler.com/Archive/Python/comp.lang.python/2006-03/msg05284.html

recursive stored procedure

March 11, 2009

The business purpose of this stored procedure is to permit a project to contain a sub-project. Because each sub-project could again contain other projects, it looked like I could potentiall get infinite loops in my logic. Therefore I wanted to prevent loop backs in my chains of projects.

The recursive stored procedure was able to walk up the chain of containing projects, and could be used to prevent a project from being inserted twice in the same chain.

There were a few tricks involved, and since it’s been about a month since I worked on this, I’m not sure I can remember all that, and for the time being will simply post the create scripts and hope that they are not too implementation specific and perhaps useful to somebody.

There are two important tables – a Projects table, where each project has an integer projectkey, and then a ProjectsOfProjects table, where each entry has a parent key, a child key, and a grandparent key. If you walk up a chain of records, at some point the grandparent key is null, and that is the end of the chain.

/****** Object: StoredProcedure [dbo].[ProjectAncestors] Script Date: 03/11/2009 17:14:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
/*
-- purpose: can we add this child to the specified parent?
-- return false if no, true if yes,
-- returns all the ancestors by recursively calling itself
-- until the last record has a null for the parent key
-- HOW TO RUN:
-- exec ProjectAncestors 40, 30 , 8 , 1
-- Child key - the current project
-- Parent key - the parent project
-- Parent_ikey - the field in the ikey'th record in the ProjectsOfProjects table where the parent's parent is defined
-- (this is the trick that enables us to "walk up" the table and get all the ancestors
SAMPLES: (we had already set up the ProjectsOfProjects table so that there were some children and parents defined)
exec ProjectsOfProjects_ADD 50 , 30, 8 , 1
NOTE - the first execution of [ProjectAncestors] has to have @start=1

declare @OkToInsert bit
exec @OkToInsert = ProjectAncestors 60,30,8,1
print @OkToInsert

exec ProjectAncestors 40, 30 , 8, 1
*/
-- =============================================
CREATE PROCEDURE [dbo].[ProjectAncestors]
@childkey int,
@parentkey int,
@parent_ikey int,
@start int ,
@returncode int OUTPUT

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
set @returncode = -99

print '******* run [ProjectAncestors] NestLevel=' + convert(varchar(10), @@nestlevel)

declare @Kount int

-- 1) if temp table doesn't exist, then create it
if @start = 1
begin
IF OBJECT_ID('tempdb..#ProjectAncestors') IS NOT NULL drop table #ProjectAncestors

-- set up the table to hold the chain of ancestors
CREATE TABLE #ProjectAncestors (parentkey INT)
-- set up the table to hold the global variable
CREATE TABLE #GlobalVars (childkey INT)
INSERT INTO #GlobalVars (childkey ) VALUES (@childkey )

print ' set the original childkey ' + convert(varchar(10), @childkey)
end

-- 2) go ahead and insert the parameter
INSERT INTO #ProjectAncestors (parentkey ) VALUES (@parentkey )

-- 3) check for the end - when the parent_ikey is null, there are no more relationships defined in the ProjectOfProjects table
if @parent_ikey is NULL
begin
-- a. is it valid to make the relationship? if the desired child was already in the list of ancestors, then it is NOT
-- BUT - remember, this is a recursive procedure, the child key is changing each time we call it. We need to check
-- on the original child key
declare @original_childkey int
select @original_childkey=childkey from #GlobalVars
print ' test the @original_childkey=' + convert(varchar(12),@original_childkey)
select @Kount = count(*) from #ProjectAncestors where parentkey=@original_childkey

-- return the result set
select * from #ProjectAncestors

drop table #ProjectAncestors

print '[ProjectAncestors] just before return @Kount=' + convert(varchar(10),@Kount )
if @Kount > 0
begin
print ' return 0 from [ProjectAncestors]'
print ' the input child record ' + convert(varchar(25), @original_childkey)
print ' was found in the list of ancestors, and therefore cannot be added'
set @returncode = 0
print ' @returncode in [ProjectAncestors]:' + convert(varchar(10),@returncode )
IF OBJECT_ID('tempdb..#ReturnCode') IS NOT NULL
begin
insert into #ReturnCode (returncode) values (@ReturnCode)
end

return 0
end
else
begin
print ' return 1 from [ProjectAncestors]'
print ' the input child record ' + convert(varchar(25), @original_childkey)
print ' was NOT found in the list of ancestors, and therefore CAN be added'
set @returncode = 1
print ' @returncode in [ProjectAncestors]:' + convert(varchar(10),@returncode )
IF OBJECT_ID('tempdb..#ReturnCode') IS NOT NULL
begin
insert into #ReturnCode (returncode) values (@ReturnCode)
end
return 1
end

end

else
begin
print '@parent_ikey is NOT NULL ' + convert(varchar(10),@parent_ikey)

declare @new_parentkey int
declare @new_ikey int
select @new_parentkey=parentkey, @new_ikey=parent_ikey from ProjectsOfProjects where childkey=@parentkey and ikey=@parent_ikey

-- **************************************************************
-- RECURSIVE CALL
-- **************************************************************
-- if it is not null, we recurse
exec projectAncestors @parentkey, @new_parentkey, @new_ikey , 0 , @returncode
end

END

And the structure of the ProjectOfProjects table is:

CREATE TABLE [dbo].[ProjectsOfProjects](
[ikey] [int] IDENTITY(1,1) NOT NULL,
[parentkey] [int] NOT NULL,
[childkey] [int] NOT NULL,
[parent_ikey] [int] NULL,
CONSTRAINT [PK_ProjectsOfProjects] PRIMARY KEY CLUSTERED
(
[ikey] ASC
)

Type initializer exception for shared class

February 11, 2009

From time to time I have gotten a baffling error – “Type initializer exception was unhandled by user code”.

I had a shared (static) class that I use for some utilitity functions, and in that I have a shared constructor and a shared Init function to set a few of the shared variables. And this has run with no incident hundreds if not over a thousand times.

Background – this is a VStudio 2008 web site run from a file directory, not from IIS.

What I notice, however, is that when I run Visual Studio Debug, it may work once, but a second time , if there is a hanging instance of AspDotNet Development Server in my toolbar, then the second time I attempt to debug, my shared class will apparently not instantiate, and I get that weird message. I close Visual Studio, reopen, and then things work.

Also, in the past when I was running from IIS, I attempted to do the same thing (initialize a few variables in this shared class), but I attempted to do it in global.asax. I have since given up on that – the type initializer messages were too weird for me.