Posts




This is an update on an older post from 2012.

Connecting to a servicestack (see servicestack.net) service from php is very easy. If you go to https://github.com/majorsilence/WebServiceDotNetTesting there is a c# project that has one service called Hello. This service will listen on http://localhost:9200.

In the php folder there is a script servicestack-php.php that will connect to the c# servicestack web service.

The main functions that can be used are get_data_curl, post_data_curl, put_data_curl. These function can be used with both HTTP, HTTPS, and can connect to open services and services protected with basic authentication.

function get_data_curl($base_url, $service_name, $query_string, $credentials)
{

	
	// Will create a string like "http://localhost:9200/servicestack/json/syncreply/Hello";
	$url = $base_url . '/' . $service_name . '/' . $query_string;
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	
	// Override the default headers
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 
		'Accept: application/json', "Expect: 100-continue"));
	
	// 0 do not include header in output, 1 include header in output
	curl_setopt($process, CURLOPT_HEADER, 0);   
	
	// Set username and password
	if ($credentials != "")
	{
		curl_setopt($ch,CURLOPT_USERPWD, $credentials); 
	}
	
	curl_setopt($process, CURLOPT_TIMEOUT, 30); 
	
	// if you are not running with SSL or if you don't have valid SSL
	$verify_peer = false;
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify_peer);
	
	// Disable HOST (the site you are sending request to) SSL Verification,
	// if Host can have certificate which is invalid / expired / not signed by authorized CA.
	$verify_host = false;
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $verify_host);
	
	
	// Set so curl_exec returns the result instead of outputting it.
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	
	// Get the response and close the channel.
	$response = curl_exec($ch);
	curl_close($ch);
	
	$json_obj = json_decode($response);
	return $json_obj;
}


function put_data_curl($base_url, $service_name, $post_data, $credentials)
{

	
	// Will create a string like "http://localhost:9200/servicestack/json/syncreply/Hello";
	$url = $base_url . '/json/syncreply/' . $service_name;
	
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	
	// Override the default headers
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 
		'Accept: application/json', "Expect: 100-continue"));
	
	// 0 do not include header in output, 1 include header in output
	curl_setopt($process, CURLOPT_HEADER, 0);   
	
	// Set username and password
	if ($credentials != "")
	{
		curl_setopt($ch,CURLOPT_USERPWD, $credentials); 
	}
	
	curl_setopt($process, CURLOPT_TIMEOUT, 30); 
	
	// if you are not running with SSL or if you don't have valid SSL
	$verify_peer = false;
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify_peer);
	
	// Disable HOST (the site you are sending request to) SSL Verification,
	// if Host can have certificate which is invalid / expired / not signed by authorized CA.
	$verify_host = false;
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $verify_host);
	
	// Set the post variables
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	
	// Set so curl_exec returns the result instead of outputting it.
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	
	// Get the response and close the channel.
	$response = curl_exec($ch);
	curl_close($ch);
	
	$json_obj = json_decode($response);
	return $json_obj;
}

You can use the function like this.

get_hello_info();
post_hello_info();
put_hello_info();

function get_hello_info()
{
	/*
	$username = "user";
	$password = "password";
	$cred = "{$username}:{$password}";
	*/
	// If you are connecting to a service that uses basic authentication 
	// you can use the code above to set the credentials.
	$cred = "";

	$json = get_data_curl("http://localhost:9200", "Hello", "Testthisservice", $cred);
	echo 'Get Result: ' . $json->{'Result'} . "<br />";
}


function post_hello_info()
{
	$json_str = json_encode(array('Name' =>  'Test this service'));
	
	
	/*
	$username = "user";
	$password = "password";
	$cred = "{$username}:{$password}";
	*/
	// If you are connecting to a service that uses basic authentication 
	// you can use the code above to set the credentials.
	$cred = "";

	$json = post_data_curl("http://localhost:9200", "Hello", $json_str, $cred);
	echo 'Post Result: ' . $json->{'Result'} . "<br />";
}


function put_hello_info()
{
	$json_str = json_encode(array('Name' =>  'Test this service'));
	
	
	/*
	$username = "user";
	$password = "password";
	$cred = "{$username}:{$password}";
	*/
	// If you are connecting to a service that uses basic authentication 
	// you can use the code above to set the credentials.
	$cred = "";

	$json = put_data_curl("http://localhost:9200", "Hello", $json_str, $cred);
	echo 'Put Result: ' . $json->{'Result'} . "<br />";
}

Majorsilence VPN is making good progress. Desktop apps for Mac, Windows, Linux will soon be available.

Be sure to request an invite at peter@majorsilence.com and I’ll send you a beta key.

Also be sure to use the coupon code Beta50Off for 50% off for the first 12 months.


How to generate pdf using c# (mono) on ubuntu linux 14.04.

See https://github.com/majorsilence/IkvmCrystalReports for a git repo with scripts that complete all the below steps.

This is incomplete and ends up with a runtime error.

  • Download crystal reports runtime libraries for java at http://www.businessobjects.com/campaigns/forms/downloads/crystal/eclipse/datasave.asp or http://scn.sap.com/docs/DOC-29757
  • Download IKVM
  • Example of the crystal reports api to produce a pdf http://www.javathinking.com/2011/09/using-crystal-reports-java-api-to.html
  • See http://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports+Java++SDK+Samples for examples of pushing data to crystal reports from java. See the Database section.
  • If connecting to microsoft sql server you will also need com.microsoft.sqlserver.jdbc.SQLServerDriver
  • May also need to use apache derby http://db.apache.org/derby/releases/release-10.11.1.1.cgi

Run a script similar to the following to convert crystal reports java jars to .net.

    "C:\Path\to\ikvm-7.2.4630.5\bin\ikvmc.exe" \
    -target:library commons-collections-3.1.jar commons-configuration-1.2.jar \
    derby.jar derbyclient.jar CrystalCommon2.jar commons-lang-2.1.jar commons-logging.jar \
    com.azalea.ufl.barcode.1.0.jar cvom.jar DatabaseConnectors.jar icu4j.jar jai_imageio.jar \
    JDBInterface.jar jrcerom.jar keycodeDecoder.jar log4j.jar logging.jar pfjgraphics.jar \
    QueryBuilder.jar XMLConnector.jar xpp3.jar CrystalReportsRuntime.jar -out:crystal.dll

Create a .net project. Reference IKVM.Runtime.dll, IKVM.OpenJDK.Core.dll, IKVM.OpenJDK.Jdbc.dll, IKVM.OpenJDK.XML.API.dll, IKVM.OpenJDK.XML.Bind.dll, IKVM.OpenJDK.Crypto.dll, IKVM.OpenJDK.XML.Parse.dll, IKVM.OpenJDK.XML.Transform.dll, IKVM.OpenJDK.XML.XPath.dll and crystal.dll.

Next write a function similar to the one below to generate a pdf report and export to a byte array.


    private static byte[] GetReportSimpleAsBytes()
    {
        // see the java_crj12_web_resultset_datasource.jsp exmpale

        java.sql.Connection cn;
        java.sql.PreparedStatement statement;
        java.sql.ResultSet resultset;
        java.io.ByteArrayInputStream inputStream;
        java.io.ByteArrayOutputStream outputStream = new java.io.ByteArrayOutputStream(); 
        byte[] byteArray;
        int bytesRead;


        var rpt = new com.crystaldecisions.sdk.occa.report.application.ReportClientDocument();
        rpt.setReportAppServer(
            com.crystaldecisions.sdk.occa.report.application.ReportClientDocument.inprocConnectionString);
        rpt.open("thereport.rpt",
            com.crystaldecisions.sdk.occa.report.application.OpenReportOptions._openAsReadOnly);
        var reportSource = rpt.getReportSource();
       
        inputStream = (java.io.ByteArrayInputStream)rpt.getPrintOutputController().export(
            com.crystaldecisions.sdk.occa.report.exportoptions.ReportExportFormat.PDF);


        byteArray = new byte[ 1024];
        while((bytesRead = inputStream.read(byteArray)) != -1) {
            outputStream.write(byteArray, 0, bytesRead);	

        }

        rpt.close();

        return outputStream.toByteArray();
    }


    public byte[] GetReportAsBytes()
    {
        // see the java_crj12_web_resultset_datasource.jsp exmpale

        java.sql.Connection cn;
        java.sql.PreparedStatement statement;
        java.sql.ResultSet resultset;
        java.io.ByteArrayInputStream inputStream;
        byte[] byteArray;
        int bytesRead;


        var rpt = new com.crystaldecisions.sdk.occa.report.application.ReportClientDocument();
        rpt.setReportAppServer(
            com.crystaldecisions.sdk.occa.report.application.ReportClientDocument.inprocConnectionString);
        rpt.open("thereport.rpt",
            com.crystaldecisions.sdk.occa.report.application.OpenReportOptions._openAsReadOnly);

        java.lang.Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
        // See http://msdn.microsoft.com/en-us/sqlserver/aa937724.aspx
        //java.sql.DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
        cn = java.sql.DriverManager.getConnection(
            "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;");
        statement = cn.prepareStatement("EXEC sp_name ?, ? ");
        statement.setString(1, "parameter 1");
        statement.setString(2, "parameter 2");
        resultset = statement.executeQuery();

        rpt.getDatabaseController().setDataSource(resultset, "TableName", "TableName");
        inputStream = (java.io.ByteArrayInputStream)rpt.getPrintOutputController()
            .export(com.crystaldecisions.sdk.occa.report.exportoptions.ReportExportFormat.PDF);


        rpt.close();

        return (byte[])inputStream;
    }

Next get a runtime error. Now what?