Saturday, January 12, 2008

Email Elements on Web Page - AJAX Solution

So yesterday I had to quickly come up with a solution to send out an email of a web page that was already rendered. I could go back through all the php server side code and try to hold all of the information in a cache variable that would then also email out the rendered html. This provided me with many complications and issues as I would then have scope to worry about in certain situations and some of the functions had been expressly written to spit out html as they run.

If you have read this far, then you understand the plight..
I came up with the following solution: I decided to try and create an AJAX solution. This is what I did:

Create a div container in your html. This Div Container should encompass everything yould like to appear in your email.


<DIV id="Email">

INSERT YOUR HTML IN HERE

<DIV>


now before this Div element, you will need to declare a form. Here you can declare where your destination ajax call ill be (ajaxsendemail.php), what to call on submit. We are disabling submit via html via return false. You can also see from this code that we have a button which will trigger the call to send the email.



<form id="emailForm" name="emailForm" method="post" action="ajaxsendemail.php" onsubmit="sendEmail(); return false;">

<input name="Send Email" type="button" value="Send Email" id="Send Email" onclick="sendEmail();"/>

<input type="text" name="to" id="to" value="recipient@email.com"/>

<input type="text" name="subject" id="subject" value="Email" />

<textarea>


<DIV id=/"Email">

INSERT YOUR HTML IN HERE

</DIV>


</form>



What you will need to know now is that we will be taking the html contents in the div container we created, then via ajax, we will send this html code through a post method to a php script which will then send the email to your desired destination. Please note that you will need the zxml javascript library:
Which the latest version that I have is here: zxml.js. Please be sure to check (and let me know) if there is an updated version.

So first, we will need to include some javascript on our page, preferably before the div container.

<script type="text/javascript" src="zxml.js"></script>

<script type="text/javascript" >



function sendEmail(){



var oForm = document.emailForm;

var sBody = getRequestBody(oForm);



var oXmlHttp = zXmlHttp.createRequest();

//alert(sBody);

oXmlHttp.open("post", oForm.action, true);

oXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

oXmlHttp.onreadystatechange = function () {

if (oXmlHttp.readyState == 4) {

if (oXmlHttp.status == 200) {

//saveResult(oXmlHttp.responseText);

alert(oXmlHttp.responseText);

} else {

saveResult("An error occurred: " + oXmlHttp.statusText);

alert('error code');



}

}

};

oXmlHttp.send(sBody);

}



function getRequestBody(oForm) {

var aParams = new Array();



for (var i=0 ; i < oForm.elements.length; i++) {

var sParam = encodeURIComponent(oForm.elements[i].name);

sParam += "=";

sParam += encodeURIComponent(oForm.elements[i].value);

aParams.push(sParam);

}

//email body

var sParam = encodeURIComponent('emailBody');

sParam += "=";

sParam += encodeURIComponent(document.getElementById("Email").innerHTML);

aParams.push(sParam);



return aParams.join("&");

}

</script>



Simply speaking, getRequestBody() takes all the form elements that you have made and then creates a Post Body request. In here I have added a bit of code which simply takes the div element (called Email) and creates another Post Variable from this element. You could do this for multiple elements in your document. The send email, instantiates the ajax transport method and calls the getRequestBody to create the post body, which is sent in the command oXmlHttp.send(sBody); . I simply created an alert to let you know what happened with the Ajax call (was the email successful?).

Now we have to take a look at the php code which handles the actual email.
ajaxsendemail.php

<?php

$to = $_POST['to'];

$subject = $_POST['subject'];

$body = '<style type="text/css">

<!--

body,td,th {

font-family: Arial, Helvetica, sans-serif;

}

-->

</style>'.stripslashes($_POST['emailBody']);

$headers = 'MIME-Version: 1.0' . "\r\n";

$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

$headers .= 'From: Orders@NitroPrint.com <Orders@NitroPrint.com>' . "\r\n";


if (mail($to, $subject, $body, $headers)) {

echo("Message successfully sent!");

} else {

echo("Message delivery failed...");

}

?>




that pretty much takes care of it... I hope you will find this useful. If you have the time, please click through one of our fine sponsors.
In addition, if you have any difficulties or suggestions, please let me know.

Labels: , , , , , ,

SQL Server MSDE Separate Instance ASP.NET & DSN Connections

Today I ran into an issue where I had a bit of difficulty connecting ASP.net to SQL Server MSDE Named Instance. The problem is that the website previously did not need to specify a named instance of MSDE/SQL Server. I was able to address the connection over asp rather easily, but there was a bit of development already done in ASP.NET and I was not very familiar with the ASP.NET setup.

A little bit of background on myself... I'm a newbie to .NET, but I am always willing to learn. I've been coding in VBscript (ASP), SQL, PHP, XML/HTML, and Javascript for quite some time. I've even had the opportunity to work on some actionscript / flex projects incorporating calls between dhtml and simple flex applications. So you may laugh at how basic this little bit of info is, or (I hope) you may actually find a useful tidbit of knowledge.

I had been handed over a web site from a previous programmer/software company and I had to figure out a way to deploy the website rather quickly. We went with a Dedicated Machine on Win2k3 Web Edition. I knew that a lot of the other O/S I ran in the past had issues with too many unneeded services (Win2k3 SBS I'm looking at you!). So to help client keep costs low and through previous experience (and knowledge about web traffic) and requirements of site, I decided that using MSDE would be a sufficient solution for the database.

I am familiar with SQL Server Enterprise Manager and SQL Server Query Tool. In using MSDE, I didn't think through that I wouldn't have a GUI if I used MSDE. This lead me through the maze of what is IT and Dev...

So yeah, I called some friends and apparently you can run MSDE and just install SQL Server Tools on a machine to get GUI access. Lucky for my client (and me), I have a legitimate copy of SQL Server I bought for my business. But here's the kicker... Web Edition 2k3 doesn't allow you (due to its licensing) to install SQL Server on the same machine. So now I was back to square one. Eventually I figured out how to use SQL Server 2005 Express Edition to serve as the gui for the MSDE DB I had already created. Don't ask me why, but I didn't feel like porting over to a new instance of 2005 by this point.

Guess what though... you cannot import (at least I haven't figure out yet) data the same way you can with Enterprise Manager. The functionality is significantly limited from Enterprise Manager for importing and exporting data. I have tried to connect to MSDE Instance via tcp ip, but I think my isp seems to be blocking port 1433/1434 udp... but that is a topic for another post I suppose.

so the basics...
1) check web.config file where you have the dsn / application connection string stored. It seemed that ASP.NET was not connecting. After a bit of debugging I realized that it should be connecting to a different instance of SQL Server.

2) in the web config - this can also be edited through IIS - ASP.NET tab...

previously looked something like this:
add key= "DSN16" value="server=LOCALHOST;database=DBNAME;uid=sa;pwd=XC123XC123x;"/

3) Now change it to
add key= "DSN16" value="Server=COMPUTERNAME\INSTANCENAME;Database=DBNAME;uid=sqlserverlogin;pwd=XC123XC123x;"/

One thing I would recommend is that you try to login with SQL Server only credentials when you are logging in through Enterprise Manager or SQL Server Manager 2005. It took me a long time to figure this out, but if you know that you can login with the SQL Server only credentials, they should hypothetically work when ASP.NET is using these credentials to talk to SQL Server.

Oh yeah, another thing is that I had to look up on SQL Server properties to give me a clue to use COMPUTERNAME\INSTANCENAME. Since I had to figure it out on my own and I couldn't find the info online ... I did find about connections with named instances, but without realizing that the credentials i was using weren't SQL server credentials... well it was useless. until I switched to SQL server only credentials, then it worked.

hope this helps and saves you a bit of time. Now please click on a google ad.
thanks,
Mauricio

Labels: , , , , , , , ,

My Current Web Project : Mashup Galore on SAVEonAtoZ.com

Look through multiple search engines, price comparison Engines, and other resources we can find.
Save Money On Everything: SAVEOnAtoZ.com

I am always working on adding new resources to help you find a better price including multiple comparison sites, meta search engines... its like meta^2.

The mashup features results from Amazon, Ebay, Half, Google Base, MSN, Shopzilla, Nextag and a few more resources as well. You can compare side by side in your shopping list and bookmark them for later. I have spent a lot of time on this project just learning how to use APIs and pulling the results from different locations, so I hope my efforts are not in vain.

I hope it saves everyone an incredible amount of money!
thanks for looking and please take some time to visit SAVEonAtoZ
thanks!
Mz

Labels: , , , , , , , , , , , , , , , , , ,

PDF Thumbnails through PHP, ImageMagick, Ghostscript - the Commandline solution

I had run into all sorts of issues with trying to deploy the imagemagick library in php. I was able to get it working fine on my xamp installations, but when I would try to get it working on IIS, I would run into issues.

GD worked fine, but unfortunately we deal with many complex image types. Some of them are only accessible to imagemagick such as PDFs.

And even worse, trying to get it running on an already live server was proving to be extremely difficult as I had to mess with the php.ini and reboot iis and perhaps the machine just to test certain changes - obviously this is not ideal with a server that is already hosting traffic.

After much frustration I came up with the idea that I could just remote php and ImageMagick via commandline. It has already prooved to be very powerful for me. This method might have a few drawbacks in terms of processing power, but its a lot better than remoting Photoshop or similar program.



Ingredients I used for Thumbnailing - you may try and substitute to see if it works for you.
Win2k3 Server, IIS, PHP5x, ImageMagick (any flavour i think), Ghostscript

Hopefully you have remote desktop/admin access otherwise this might not work for you... but maybe you can convince your provider to do this for you?

1) Download and install everything, you should already have PHP installed and working.

2) Install Imagemagick, Install Ghostscript which is necessary to render the PDF thumbnails.

3) but you will need to change a few settings.

one key one is changing permissions on IUSER_XXXXX on %system path%/system32/cmd.exe

you have to actually right click on the cmd.exe file and set the permissions on this file specifically.

4) make sure you have executable permissions in IIS for the website

5) i created a temp directory for easy testing such as
c:\temp\

6) I gave this directory full permissions for testing and also shared it on the network so it could be modified... this is temporary to see if mechanism works.

7) I then created this script... I will leave all the commenting so you can see more or less everything I tried and went through to get it to work...



/ < ? PHP

// MZs IMAGE MAGICK PDF THUMBNAILING MECHANISM
// REQUIRED INGREDIENTS :
// IMAGE MAGICK
// GHOSTSCRIPT
// !!!! NOTE TO RUN EXEC() ON IIS6.win2k6 I had to enable permissions on system32/cmd.exe for INETUSR_XXXXX
//
///
//

function CreateThumbnail($sourcefile, $destfile, $percentage=25 ) {
//$percentage = "25%";
//create command to send out
//exec(,$output,$return);
$command = "convert.exe -colorspace cmyk ".$sourcefile." -thumbnail ".$percentage."%x".$percentage."% ".$destfile;
//$command = 'start /B "convert" "convert.exe -colorspace cmyk '.$sourcefile.' -thumbnail 25%x25% '.$destfile.'"';
//$command = "dir";
echo $command;

$ret = exec($command, $output);
//echo $ret;
//echo sizeof($output[0]);
//echo $output[1].'
';
//echo $output[2].'
';
//echo 'the output'.$output.'
';

return true;
}


$sourcefile = "e:\\test\\1.pdf";
$destfile= "e:\\test\\1.pdf";


if ( $_GET['sourcefile'] ) {
$sourcefile = $_GET['sourcefile'];
}

if ($_GET['destfile'] ) {
$destfile = $_GET['destfile'];
} else {
$destfile = 'thumb-'.$sourcefile;
}

if ($_GET['percentage'] ) {
$percentage = $_GET['percentage'];
} else {
$percentage = 40;
}

CreateThumbnail($sourcefile,$destfile, $percentage) ;


?>


I still have a lot more to write, so I'll keep upating the blog as I make the script better.

you can pass in variables into the script such as thumbnail.php?sourcefile=sourcefile.pdf&destfile=destfile.jpg&percentage=25
and it creates a jpg thumbnail 25% the size of the

Labels: , , , ,