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 = "9a******************";
            SaasposeApp.AppSID = "77*********************";
            //specify product URI
            Product.BaseProductUri = @"http://api.saaspose.com/v1.0";
            try
            {
                int drawingObjectIndex = 1;
                string fileName = "SampleDrawingObject.doc";
                string saveFormat = "xls"; //Choose from jpeg, tiff, png and bmp
                string outputFile = "C:\\OutputDrawingObject." + saveFormat;
                string amazonS3StorageName = "MyAmazonS3Storage";
                string amazonS3BucketName = "MyS3Bucket"; // include folder name if file is not at root folder 

                //build URI
                string strURI = Product.BaseProductUri + "/words/" + fileName + "/drawingObjects/" + drawingObjectIndex;
                strURI += "/oleData?storage=" + amazonS3StorageName + "&folder=" + amazonS3BucketName;

                //sign URI
                string signedURI = Sign(strURI);

                //get response stream
                Stream responseStream = ProcessCommand(signedURI, "GET");

                using (Stream fileStream = System.IO.File.OpenWrite(outputFile))
                {
                    CopyStream(responseStream, fileStream);
                }
                responseStream.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            } 

//Following are the required methods and classes 

        public static string Sign(string url)
        {
            try
            {
                // Add appSID parameter.
                UriBuilder builder = new UriBuilder(url);
                if (builder.Query != null && builder.Query.Length > 1)
                    builder.Query = builder.Query.Substring(1) + "&appSID=" + SaasposeApp.AppSID;
                else
                    builder.Query = "appSID=" + SaasposeApp.AppSID;
                // Remove final slash here as it can be added automatically.
                builder.Path = builder.Path.TrimEnd('/');
                // Compute the hash.

                byte[] privateKey = System.Text.Encoding.UTF8.GetBytes(SaasposeApp.AppKey);

                System.Security.Cryptography.HMACSHA1 algorithm = new System.Security.Cryptography.HMACSHA1(privateKey);
                //System.Text.ASCIIEncoding
                byte[] sequence = System.Text.ASCIIEncoding.ASCII.GetBytes(builder.Uri.AbsoluteUri);
                byte[] hash = algorithm.ComputeHash(sequence);
                string signature = Convert.ToBase64String(hash);
                // Remove invalid symbols.
                signature = signature.TrimEnd('=');
                signature = System.Web.HttpUtility.UrlEncode(signature);
                // Convert codes to upper case as they can be updated automatically.
                signature = System.Text.RegularExpressions.Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper());
                
                // Add the signature to query string.
                return string.Format("{0}&signature={1}", builder.Uri.AbsoluteUri, signature);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public static Stream ProcessCommand(string strURI, string strHttpCommand)
        {
            try
            {
                Uri address = new Uri(strURI);
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(address);
                request.Method = strHttpCommand;
                request.ContentType = "application/json";
                request.ContentLength = 0;
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                return response.GetResponseStream();
            }
            catch (System.Net.WebException webex)
            {
                throw new Exception(webex.Message);
            }
            catch (Exception Ex)
            {
                throw new Exception(Ex.Message);
            }
        }
        public static void CopyStream(Stream input, Stream output)
        {
            try
            {
                byte[] buffer = new byte[8 * 1024];
                int len;
                while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, len);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
    public class Product
    {
       public static string BaseProductUri { get; set; }
    }
    public class SaasposeApp
    {
       public static string AppSID { get; set; }
       public static string AppKey { get; set; }
    }
                
                     expdp system / [password_of_System] @ [SID] schemas=[name of the schema] dumpfile=[filename].dmp logfile=[filename].log
     
 #Example
     
expdp system/oracle@mydbsid SCHEMAS=staging dumpfile=export_staging_original.dmp logfile=original.log                
                    <?php
  $im=imagecreatefromjpeg('http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com');
    header('Content-type:image/jpeg');
    imagejpeg($im);
 ?>                
                    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Demo Page For Autoplay youtube video while clicking on a custom thumbnail image</title>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'><script  type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<style>
	body
	{
		margin	: 0;
		padding	: 0;
		background	: #EEE;
		color		: #333;
		font-family: 'Open Sans', sans-serif;
		font-size	: 12px;
 
	}
	#wrapper
	{
		width	: 1012px;
		margin	: 0 auto;
 
	}
 
</style>
<body>
	<div id="wrapper">
		<h1>Demo Page For Autoplay youtube video while clicking on a custom thumbnail image</h1>
		<div class="custom-th"><img src="http://blog.pixelthemes.com/demo/custom-yt-thumbnail/cusotm-yt-thumbanil.jpg" style="cursor:pointer" /></div>
		<div id="thevideo" style="display:none">
		<object width="560" height="315"><param name="movie" value="http://www.youtube.com/v/XSGBVzeBUbk?&autoplay=1&hl=en_US&version=3"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/XSGBVzeBUbk?hl=en_US&version=3&autoplay=1" type="application/x-shockwave-flash" width="560" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>
		</div>
 
		<p>Demo by : <a href="http://blog.pixelthemes.com/">WordPress Themes</a> </br>
		Article Link : <a href="http://blog.pixelthemes.com/ideas/autoplay-youtube-video-while-clicking-on-a-custom-thumbnail-image">Custom Thumbnail with fadeout animation for Youtube Videos</a>
	</div>
 
	<script type="text/javascript">
	$(document).ready(function() {
		$('.custom-th').click(function() {
			$('.custom-th').fadeOut('slow', function() {
				$("#thevideo").css("display","block");
				});
			});
		});
	</script>
</body>
</html>                
                    SaasposeApp.AppKey = "9a******************";
SaasposeApp.AppSID = "77*********************";
            //specify product URI
            Product.BaseProductUri = @"http://api.saaspose.com/v1.0";
            
            try
            {
                string fileName = "Sample.doc";
                string saveFormat = "doc";
                string outputFile = "C:\\Output." + saveFormat;
                string amazonS3StorageName = "MyAmazonS3Storage";
                string amazonS3BucketName = "MyS3Bucket"; // include folder name if file is not at root folder 

                //serialize the JSON request content
                Field field = new Field();
                field.Alignment = "right";
                field.Format = "{PAGE} of {NUMPAGES}";
                field.IsTop = true;
                field.SetPageNumberOnFirstPage = true;

                string strJSON = JsonConvert.SerializeObject(field);

                //build URI
                string strURI = Product.BaseProductUri + "/words/" + fileName + "/insertPageNumbers";
                strURI += "?storage=" + amazonS3StorageName + "&folder=" + amazonS3BucketName;
                //sign URI
                string signedURI = Sign(strURI);
                //get response stream
                Stream responseStream = ProcessCommand(signedURI, "POST", strJSON, "json");
                //build URI
                strURI = Product.BaseProductUri + "/words/" + fileName;
                strURI += "?format=" + saveFormat + "&storage=" + amazonS3StorageName + "&folder=" + amazonS3BucketName; ;

                //sign URI
                signedURI = Sign(strURI);
                //get response stream
                responseStream = ProcessCommand(signedURI, "GET");

                using (Stream fileStream = System.IO.File.OpenWrite(outputFile))
                {
                    CopyStream(responseStream, fileStream);
                }
                responseStream.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }  
   public static string Sign(string url)
    {
        try
        {
            UriBuilder builder = new UriBuilder(url);
            if (builder.Query != null && builder.Query.Length > 1)
                builder.Query = builder.Query.Substring(1) + "&appSID=" + SaasposeApp.AppSID;
            else
                builder.Query = "appSID=" + SaasposeApp.AppSID;
                builder.Path = builder.Path.TrimEnd('/');
            byte[] privateKey = System.Text.Encoding.UTF8.GetBytes(SaasposeApp.AppKey);

            System.Security.Cryptography.HMACSHA1 algorithm = new System.Security.Cryptography.HMACSHA1(privateKey);
            byte[] sequence = System.Text.ASCIIEncoding.ASCII.GetBytes(builder.Uri.AbsoluteUri);
            byte[] hash = algorithm.ComputeHash(sequence);
            string signature = Convert.ToBase64String(hash);
            signature = signature.TrimEnd('=');
            signature = System.Web.HttpUtility.UrlEncode(signature);
            signature = System.Text.RegularExpressions.Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper());
     return string.Format("{0}&signature={1}", builder.Uri.AbsoluteUri, signature);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    public static Stream ProcessCommand(string strURI, string strHttpCommand)
    {
        try
        {
            Uri address = new Uri(strURI);
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(address);
            request.Method = strHttpCommand;
            request.ContentType = "application/json";

            request.ContentLength = 0;
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            return response.GetResponseStream();
        }
        catch (System.Net.WebException webex)
        {
            throw new Exception(webex.Message);
        }
        catch (Exception Ex)
        {
            throw new Exception(Ex.Message);
        }
    }

   public static Stream ProcessCommand(string strURI, string strHttpCommand, string strContent, string ContentType = "xml")
    {
        try
        {
            byte[] arr = System.Text.Encoding.UTF8.GetBytes(strContent);

            Uri address = new Uri(strURI);
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(address);
            request.Method = strHttpCommand;
            if (ContentType.ToLower() == "xml")
                request.ContentType = "application/xml";
            else
                request.ContentType = "application/json";

            request.ContentLength = arr.Length;

            Stream dataStream = request.GetRequestStream();
            dataStream.Write(arr, 0, arr.Length);
            dataStream.Close();

            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            return response.GetResponseStream();
        }
        catch (System.Net.WebException webex)
        {
            throw new Exception(webex.Message);
        }
        catch (Exception Ex)
        {
            throw new Exception(Ex.Message);
        }
    }
    public static void CopyStream(Stream input, Stream output)
    {
        try
        {
            byte[] buffer = new byte[8 * 1024];
            int len;
            while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, len);
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
}

public class Product
{
   public static string BaseProductUri { get; set; }
}
public class SaasposeApp
{
    public static string AppSID { get; set; }
    public static string AppKey { get; set; }
}
public class Field
{
    public string Format { get; set; }
    public string Alignment { get; set; }
    public bool IsTop { get; set; }
    public bool SetPageNumberOnFirstPage { get; set; }
}
                
                    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;
	}
}