DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    SaasposeApp.AppKey = "89**********************";
SaasposeApp.AppSID = "77***********************";
//specify product URI
Product.BaseProductUri = @"http://api.saaspose.com/v1.0";

string[] presentationsList = new string[] { "Presentation2.pptx", "Presentation3.pptx" };
PresentationsList list = new PresentationsList();
list.PresentationPaths = presentationsList;

string strJSON = JsonConvert.SerializeObject(list);

//build URI
string strURI = "http://api.saaspose.com/v1.0/slides/Presentation1.pptx/merge"; //Product.BaseProductUri + "/pdf/" + basePdf + "/appendDocument?appendFile=" + newPdf + "&startPage=1&endPage=" + iPageCount.ToString();
string signedURI = Utils.Sign(strURI);

Utils.ProcessCommand(signedURI, "POST", strJSON);

// build URI to download merged presentation
strURI = "http://api.saaspose.com/v1.0/storage/file/Presentation1.pptx";
signedURI = Utils.Sign(strURI);

using (Stream responseStream = Utils.ProcessCommand(signedURI, "GET"))
{
    //Save output file
    using (Stream fileStream = System.IO.File.OpenWrite("C:\\MergedPresentation.pptx"))
    {
        Utils.CopyStream(responseStream, fileStream);
    }
}

//Following is the PresentationsList class

/// <summary>
/// represents list of presentations to be merged
/// </summary>
class PresentationsList
{
    public PresentationsList() { }

    public string[] PresentationPaths { get; set; }
}

//build URI to upload file to Saaspose
            string strURI = "http://api.saaspose.com/v1.0/storage/file/MyRemoteFileName";
            string signedURI = Sign(strURI);
            UploadFileBinary(localfilepath, signedURI, "PUT");
                
                    <?php

##################### 
//CONFIGURATIONS  
#####################
// Define the name of the backup directory
define('BACKUP_DIR', './myBackups' ) ; 
// Define  Database Credentials
define('HOST', 'localhost' ) ; 
define('USER', 'testd!b' ) ; 
define('PASSWORD', 'k^$2y4n9@#VV' ) ; 
define('DB_NAME', 'test123' ) ; 
/*
Define the filename for the sql file
If you plan to upload the  file to Amazon's S3 service , use only lower-case letters 
*/
$fileName = 'mysqlbackup--' . date('d-m-Y') . '@'.date('h.i.s').'.sql' ; 
// Set execution time limit
if(function_exists('max_execution_time')) {
if( ini_get('max_execution_time') > 0 ) 	set_time_limit(0) ;
}

###########################  

//END  OF  CONFIGURATIONS  

###########################

// Check if directory is already created and has the proper permissions
if (!file_exists(BACKUP_DIR)) mkdir(BACKUP_DIR , 0700) ;
if (!is_writable(BACKUP_DIR)) chmod(BACKUP_DIR , 0700) ; 

// Create an ".htaccess" file , it will restrict direct accss to the backup-directory . 
$content = 'deny from all' ; 
$file = new SplFileObject(BACKUP_DIR . '/.htaccess', "w") ;
$file->fwrite($content) ;

$mysqli = new mysqli(HOST , USER , PASSWORD , DB_NAME) ;
if (mysqli_connect_errno())
{
   printf("Connect failed: %s", mysqli_connect_error());
   exit();
}
 // Introduction information
 $return .= "--\n";
$return .= "-- A Mysql Backup System \n";
$return .= "--\n";
$return .= '-- Export created: ' . date("Y/m/d") . ' on ' . date("h:i") . "\n\n\n";
$return = "--\n";
$return .= "-- Database : " . DB_NAME . "\n";
$return .= "--\n";
$return .= "-- --------------------------------------------------\n";
$return .= "-- ---------------------------------------------------\n";
$return .= 'SET AUTOCOMMIT = 0 ;' ."\n" ;
$return .= 'SET FOREIGN_KEY_CHECKS=0 ;' ."\n" ;
$tables = array() ; 
// Exploring what tables this database has
$result = $mysqli->query('SHOW TABLES' ) ; 
// Cycle through "$result" and put content into an array
while ($row = $result->fetch_row()) 
{
$tables[] = $row[0] ;
}
// Cycle through each  table
 foreach($tables as $table)
 { 
// Get content of each table
$result = $mysqli->query('SELECT * FROM '. $table) ; 
// Get number of fields (columns) of each table
$num_fields = $mysqli->field_count  ;
// Add table information
$return .= "--\n" ;
$return .= '-- Tabel structure for table `' . $table . '`' . "\n" ;
$return .= "--\n" ;
$return.= 'DROP TABLE  IF EXISTS `'.$table.'`;' . "\n" ; 
// Get the table-shema
$shema = $mysqli->query('SHOW CREATE TABLE '.$table) ;
// Extract table shema 
$tableshema = $shema->fetch_row() ; 
// Append table-shema into code
$return.= $tableshema[1].";" . "\n\n" ; 
// Cycle through each table-row
while($rowdata = $result->fetch_row()) 
{ 
// Prepare code that will insert data into table 
$return .= 'INSERT INTO `'.$table .'`  VALUES ( '  ;
// Extract data of each row 
for($i=0; $i<$num_fields; $i++)
{
$return .= '"'.$rowdata[$i] . "\"," ;
 }
 // Let's remove the last comma 
 $return = substr("$return", 0, -1) ; 
 $return .= ");" ."\n" ;
 } 
 $return .= "\n\n" ; 
}
// Close the connection
$mysqli->close() ;
$return .= 'SET FOREIGN_KEY_CHECKS = 1 ; '  . "\n" ; 
$return .= 'COMMIT ; '  . "\n" ;
$return .= 'SET AUTOCOMMIT = 1 ; ' . "\n"  ; 
//$file = file_put_contents($fileName , $return) ; 
$zip = new ZipArchive() ;
$resOpen = $zip->open(BACKUP_DIR . '/' .$fileName.".zip" , ZIPARCHIVE::CREATE) ;
if( $resOpen ){
$zip->addFromString( $fileName , "$return" ) ;
    }
$zip->close() ;
$fileSize = get_file_size_unit(filesize(BACKUP_DIR . "/". $fileName . '.zip')) ; 
$message = <<<msg
  <h2>BACKUP  completed ,</h2><br> 
  the archive has the name of  : <b>  $fileName  </b> and it's file-size is :   $fileSize  .<br>
 This zip archive can't be accessed via a web browser , as it's stored into a protected directory . <br>
  It's highly recomended to transfer this backup to another filesystem , use your favorite FTP client to download the archieve . 
msg;
echo $message ; 

// Function to append proper Unit after file-size . 
function get_file_size_unit($file_size){
switch (true) {
    case ($file_size/1024 < 1) :
        return intval($file_size ) ." Bytes" ;
        break;
    case ($file_size/1024 >= 1 && $file_size/(1024*1024) < 1)  :
        return intval($file_size/1024) ." KB" ;
        break;
	default:
	return intval($file_size/(1024*1024)) ." MB" ;
}
}
                
                    <asp:CompareValidator ID="_cvOrderingWeight" runat="server" ControlToValidate="_txtOrderingWeight"
                        Type="Integer" Operator="DataTypeCheck" Display="None"></asp:CompareValidator>                
                    //build URI to add watermark text
            string strURI = "http://api.saaspose.com/v1.0/words/input.docx/insertWatermarkText";
            string signedURI = Sign(strURI);
            //serialize the JSON request content
            WatermarkText watermark = new WatermarkText();
            watermark.Text = "Watermark Text Here";
            watermark.RotationAngle = 45.0;
            string strJSON = JsonConvert.SerializeObject(watermark);
            Stream responseStream = ProcessCommand(signedURI, "POST", strJSON);
            StreamReader reader = new StreamReader(responseStream);
            string strResponse = reader.ReadToEnd();
            //Parse the json string to JObject
            JObject pJSON = JObject.Parse(strResponse);
            BaseResponse baseResponse = JsonConvert.DeserializeObject<BaseResponse>(pJSON.ToString());
            if (baseResponse.Code == "200" && baseResponse.Status == "OK")
		Console.WriteLine("Watermark text has been added successfully");

	    //Here is the WatermarkText class    	    
            public class WatermarkText
            {
                public string Text { get; set; }
                public double RotationAngle { get; set; }
            }


            //Here is the BaseResponse class    	    
	    public class BaseResponse
            {
        	public BaseResponse() { }
	        public string Code { get; set; }
        	public string Status { get; set; }
    	    }                
                    var t = document.getElementById('ID');
t.onfocus = hideText;
t.onblur = showText;

function hideText() {
	if(this.value == this.defaultValue) {
		this.value = '';
	}
}

function showText() {
	if(this.value == '') {
		this.value = this.defaultValue;
	}
}                
                    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
	public X509Certificate[] getAcceptedIssuers() {
		return null;
	}
	public void checkClientTrusted(X509Certificate[] certs, String authType) {}
	public void checkServerTrusted(X509Certificate[] certs, String authType) {}
} };

SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());

ClientConfig config = new DefaultClientConfig();
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(new HostnameVerifier() {
	@Override
	public boolean verify(String s, SSLSession sslSession) {
		return true;
	}
}, context));

Client client = Client.create(config);
client.setFollowRedirects(true);
WebResource resource = client.resource("https://myserver/myws");
resource.accept(MediaType.APPLICATION_JSON_TYPE);
String result = resource.post(String.class);                
                    //build URI to read barcode
	    //type:  Codabar, Code11, Code128 and Code39Extended etc.
            String strURI = "http://api.saaspose.com/v1.0/barcode/recognize?type=QR&url=http://upload.wikimedia.org/wikipedia/commons/c/ce/WikiQRCode.png";
            // Send the request to Saaspose server
            InputStream responseStream = ProcessCommand(Sign(strURI), "POST");
            // Read the response
            String strJSON = StreamToString(responseStream);
            //Parse and Deserializes the JSON to a object. 
            RecognitionResponse barcodeRecognitionResponse = gson.fromJson(strJSON,RecognitionResponse.class);
	    List<RecognizedBarCode> barcodes = barcodeRecognitionResponse.getBarcodes();
        
            // Display the value and type of all the recognized barcodes
	    for (RecognizedBarCode barcode : barcodes)
	    {
	        System.out.println("Codetext: " + barcode.BarcodeValue() + "\nType: " + barcode.getBarcodeType());
	    }

	    \\Here is the RecognitionResponse class
	    public class RecognitionResponse extends BaseResponse
	    {
	        private List<RecognizedBarCode> Barcodes ;
	        public List<RecognizedBarCode> getBarcodes(){return Barcodes;}
	    }

	    \\Here is the RecognizedBarCode class	    
	    public class RecognizedBarCode
	    {
	        private String BarcodeType ;
	        private String BarcodeValue;
	        public String getBarcodeType(){return BarcodeType;}
	        public String BarcodeValue(){return BarcodeValue;}
	    }

	    \\Here is the BaseResponse class	    
	    public class BaseResponse 
	    {
	        public BaseResponse() { }
	        private String Code;
	        private String Status;
	        public String getCode(){return Code;}
	        public String getStatus(){return Status;}
	        public void  setCode(String temCode){ Code=temCode;}
	        public void setStatus(String temStatus){ Status=temStatus;}
	    }
                
                        <script type="text/javascript">
/* Source: http://www.apphp.com/index.php?snippet=javascript-toggle-elements */
    function toggle(id, id2){  
        var toggle_one = document.getElementById(id);  
        var toggle_two = document.getElementById(id2);  
        if(toggle_one.style.display == "block"){  
            toggle_one.style.display = "none";  
            toggle_two.innerHTML = "Show";  
        }else{  
            toggle_one.style.display = "block";  
            toggle_two.innerHTML = "Hide";  
        }  
    }
    </script>
     
    <a href="#" id="tlink" onclick="toggle('comments', 'tlink');">Show</a> Comments<br><br>  
    <div id="comments" style="display:none;padding 10px;">Now you can see the comments</div>
                
                        <?php
/* Source: http://www.apphp.com/index.php?snippet=php-download-file-with-speed-limit */
    /* set here a limit of downloading rate (e.g. 10.20 Kb/s) */
    $download_rate = 10.20;
     
    $download_file = 'download-file.zip';  
    $target_file = 'target-file.zip';
     
    if(file_exists($download_file)){
        /* headers */
        header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
        header('Cache-control: private');
        header('Content-Type: application/octet-stream');
        header('Content-Length: '.filesize($download_file));
        header('Content-Disposition: filename='.$target_file);
     
        /* flush content */
        flush();
     
        /* open file */
        $fh = @fopen($download_file, 'r');
        while(!feof($fh)){
            /* send only current part of the file to browser */
            print fread($fh, round($download_rate * 1024));
            /* flush the content to the browser */
            flush();
            /* sleep for 1 sec */
            sleep(1);
        }
        /* close file */
        @fclose($fh);
    }else{
        die('Fatal error: the '.$download_file.' file does not exist!');
    }
    ?>
                
                        <?php
/* Source: http://www.apphp.com/index.php?snippet=php-list-directory-contents */
    function list_directory_content($dir){
        if(is_dir($dir)){
            if($handle = opendir($dir)){
                while(($file = readdir($handle)) !== false){
                    if($file != '.' && $file != '..' && $file != '.htaccess'){
                        echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
                    }
                }
                closedir($handle);
            }
        }
    }
    ?>