welcome.h

welcome to home page of kubilay erdogan -a freelancer php, iOS and .net developer. he hates postbacks.
html2canvas- Take Screenshot of Web Page and Save It to Server (Javascript and PHP)

html2canvas- Take Screenshot of Web Page and Save It to Server (Javascript and PHP)

FeedBack is important. Usually, end-users struggle to clarify their problems. And you might be unreachable for a phone call or remote connection.

That causes a huge need of visualization. First solution that appears in mind is to capture the current screen of user.

However, when I tried to implement that, it wasn’t so easy as I expected. Some old ways offer ActiveX but it seems too outdated. Since there’s a bridge needed between client side and server, JS libraries are the best way.

There’s a great library, html2canvas. It is told to be reverse-engineered version of Google Plus’ way of taking screenshots.

When I first discovered this library, it took me a while to use for simplest implementation. I just wanted to visualize a div element. However, there was no single page to tell the whole path to follow, thus I had to combine various sources.

Here’s how you can easily use for taking a screenshot of a div:

1- Import libraries
There are 3 libraries to import:

  • jquery.js
  • html2canvas.js
  • jquery.plugin.html2canvas.js

You can download html2canvas and html2canvas jQuery plugin from this link.
Note: The source link contains html2canvas v0.40. I recommend you to check for a newer version and use it instead from official html2canvas site.

I have used jquery.min.js v1.7.1 but you can try other versions. For this jQuery library, use this link.
Here’s first lines of code:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="js/html2canvas.js"></script>
<script type="text/javascript" src="js/jquery.plugin.html2canvas.js"></script>
<!-- -->

2- Create your div
In my code, I used html2canvas for a div. You can use the whole body tag instead, it’s up to you.
Attach a div element to the page with a certain id:

<div id="target">
<!-- Render your page inside of this div. -->
</div>

3- Create a button and a hidden form
This part is important. In order to save the image to server, we need to pass captured image data with a form field.
In 4th step, you’ll see JavaScript code that writes the image data to hidden field and posts the form.

<input type="submit" value="Take Screenshot Of Div" onclick="capture();" />
<form method="POST" enctype="multipart/form-data" action="save.php" id="myForm">
    <input type="hidden" name="img_val" id="img_val" value="" />
</form>

4- JavaScript Code

    function capture() {
        $('#target').html2canvas({
            onrendered: function (canvas) {
                //Set hidden field's value to image data (base-64 string)
                $('#img_val').val(canvas.toDataURL("image/png"));
                //Submit the form manually
                document.getElementById("myForm").submit();
            }
        });
    }

5- Use the posted values
Here I used a form to post the value. You can use Ajax calls or whatever. I have a PHP file, save.php. In this file, we will both show the picture and save it to the server.

//save.php code

//Show the image
echo '<img src="'.$_POST['img_val'].'" />';

//Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);

//Decode the string
$unencodedData=base64_decode($filteredData);

//Save the image
file_put_contents('img.png', $unencodedData);

6- Enjoy your day
So that’s pretty much it. Click here for a live demo or download the codes from Github repository page.

March 1, 2013 5 comments
Javascript: Export HTML Table to Excel With Custom File Name

Javascript: Export HTML Table to Excel With Custom File Name

Web browser wars hurt developers’ hearts. It is mostly about CSS, sometimes about JavaScript, HTML etc…

Thus I know how it feels when you expect something to get done easily appears a lot more harder than you expected.

Code below is tested only with Chrome (24+). It is making these processes:

  • Gets the HTML code of your table inside your div element.
  • Replaces the spaces in the code with correct syntax for Excel (otherwise spaces will be removed in your Excel sheet).
  • Generates a specific file name (for minutes) in order to avoid overriding old files and to supply archiving by date values.
  • And lastly and most importantly, saving the file with a custom file name.

Here’s my combination of codes (from different SO questions or tutorials) if you want to save HTML table to client computer using JavaScript code.

$(document).ready(function() {
	$("#btnExport").click(function(e) {
		//getting values of current time for generating the file name
		var dt = new Date();
		var day = dt.getDate();
		var month = dt.getMonth() + 1;
		var year = dt.getFullYear();
		var hour = dt.getHours();
		var mins = dt.getMinutes();
		var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;
		//creating a temporary HTML link element (they support setting file names)
		var a = document.createElement('a');
		//getting data from our div that contains the HTML table
		var data_type = 'data:application/vnd.ms-excel';
		var table_div = document.getElementById('dvData');
		var table_html = table_div.outerHTML.replace(/ /g, '%20');
		a.href = data_type + ', ' + table_html;
		//setting the file name
		a.download = 'exported_table_' + postfix + '.xls';
		//triggering the function
		a.click();
		//just in case, prevent default behaviour
		e.preventDefault();
	});
});
February 3, 2013 13 comments
Generate DateTime Value in PHP for Using in MySQL Command

Generate DateTime Value in PHP for Using in MySQL Command

When we work with date and/or time values in MySQL, it’s always easy to use built-in MySQL functions such as NOW(), DATE_ADD(), TIMESTAMP() etc… Now imagine you have to pass date/time values to MySQL from PHP variables. First time I tried that, it didn’t work out so easy for me.

Yes, if you simply take one column value and use it again, you have no problem. But here’s an example that you take date and time from MySQL column, add 1 seconds to that value and use it in query again:

//Here's just stuff in order to get a datetime value from MySQL DB.
$query = "SELECT TOP 1 `date` FROM `table`";
$result = mysql_query($query, $db_link);
$date_time_val = "";
if ($result) {
    while($row = mysql_fetch_assoc($result)) {
        //Here we get the value.
        $date_time_val = $row["date"];
    }
}

//Now we add one second to this value and use it again.
//First, use it for generating a DateTime variable from PHP library.
$time = new DateTime($date_time_val);
//If you need current time in PHP, you can use this:
//$time = new DateTime(date("Y-m-d H:i:s"));

//Add one second,
$time->modify("+1 seconds");

//You can not use it as it is
//You need to convert to a string in MySQL datetime format.
$time_string = $time->format("Y-m-d H:i:s");

//Now you're free to use in your query
$query_new = "SELECT * FROM `table` WHERE `date` = '".$time_string."' ";
December 23, 2012 0 comments
ScriptCam Integration for .Net: ScriptCamForDotNet Repository

ScriptCam Integration for .Net: ScriptCamForDotNet Repository

Hi all,

Recently I had to take pictures from web camera in my Asp.Net page. There’s a great flash-based plugin works with jQuery, named ScriptCam. So I been dealing integration of this to my Asp.Net page.

You can see my bio above, I hate (unnecessary) postbacks. So it all works on client, faster, then I store the binary data of captured image in my Session variable. Next page I show it on Page_Load event.

You can see the working example here,
Or you can download the project from here.

That’s my first repository, I hope it becomes helpful for some fellas.

July 3, 2012 2 comments
T-SQL: Concatenate Multiple Rows of a Column into One Cell

T-SQL: Concatenate Multiple Rows of a Column into One Cell

Simple: You have a column and you want to take all rows as one cell. So that you can do searching, ordering, whatever you like.

Solution: Declare a variable, in this case VARCHAR or NVARCHAR, then SELECT the variable by equaling [itself] plus [column name] plus [your seperation char].

Here’s the code snippet:

DECLARE @concatenated NVARCHAR(1000)
SET @concatenated = ''
SELECT @concatenated = @concatenated + [NAME_COLUMN] + ',' FROM [USERS_TABLE] WHERE [ID_COLUMN] < 100
SELECT @concatenated
July 2, 2012 0 comments
Asp.Net Server Side: How to get Iframe’s Parent Window Url?

Asp.Net Server Side: How to get Iframe’s Parent Window Url?

In Asp.Net server sided button’s click event, I somehow needed to find parent window url of an iframe, which means the url you see in the address bar of your web browser.

Let’s think of 2 pages: Parent.aspx and Child.aspx. Child.aspx is loading to an iframe in Parent.aspx. If you have a button in Child.aspx, you will be getting “Child.aspx” result when you use Request.Url method in this button’s click event.

But you see “Parent.aspx” in the address bar, right? So how to get it?

Here you need to work with client side peacefully. Otherwise the server will keep giving you the same result.

First, place a button running at server, add a click event and a client-click event.

    <asp:Button ID="btnFindParentUrl" runat="server" Text="Get Url!" OnClick="btnFindParentUrl_Click" OnClientClick="fillHidden();"></asp:Button>

Put a hidden textbox inside a div with style=”display: none;” (not Visible=”false” for button because if you do client can’t see and fill it):

    <div style="display: none;">
        <asp:TextBox ID="txtHiddenUrlField" runat="server" BorderStyle="None" Font-Size="0px" ForeColor="#F6F6F6" Height="0px" Width="0px"></asp:TextBox>
    </div>

Now place javascript code of fillHidden() function:

    <script type="text/javascript">
        function fillHidden() {
            document.getElementById('<%= txtHiddenUrlField.ClientID %>').value = parent.document.location.href;
        };
    </script>

That’s all you have to do at client side.
Let’s go to the server:

    protected void btnFindParentUrl_Click(object sender, EventArgs e)
    {
        string parentUrl = txtHiddenUrlField.Text;
    }

This way, you should be getting parent url from button in an iframe.

June 22, 2012 1 comment
T-SQL: How to Order by Surname in Full Name Column?

T-SQL: How to Order by Surname in Full Name Column?

Sometimes you need to do ordering by in a full name column. If you want to order by first name, that’s cool, but when you need to order by last name, you need to find the surname for each field.

Let’s take a look at this data:

[Full Name]
—————————-
Albert Einstein
Leonardo da Vinci
Nicolas Tesla

 
These values are ordered by first name so there’s no problem with that. But if we wanted to order by last name(which is not a particular column in this table), we had to find a way like splitting these fields or something else.

Anyway, there was a good line of code in StackOverflow (see question&answer here) written by user Recep.

SELECT [Full Name], REVERSE(SUBSTRING(REVERSE([Full Name]), 0, CHARINDEX(' ', REVERSE([Full Name])))) AS SurnameAfterReversing
FROM GENIUS_TABLE
ORDER BY REVERSE(SUBSTRING(REVERSE([Full Name]), 0, CHARINDEX(' ', REVERSE([Full Name]))))
--We need to select our ORDER BY expression as a new column otherwise it will warn that it can't order by a column which is not exist in query result.

It reverses the whole name here, then gets text until the first space (‘ ‘) character, then reverses the new text back. That way, we actually get the last name so you can do anything you want with this column.

And here is the data as a result of this query:

[Full Name] SurnameAfterReversing
—————————- —————————-
Albert Einstein Einstein
Nicolas Tesla Tesla
Leonardo da Vinci Vinci
June 18, 2012 0 comments
iOS 6 is Still Beta

iOS 6 is Still Beta

iOS 6

The ones who involved with iOS or iOS development might have heard about the beta version of iOS 6. It’s only open for registered Apple developers at the moment but I assure you it’s better this way. People expecting Apple to release latest and common version in fall 2012.

If you want to take a look at new features, here’s 2 links:
One is in English: #iLounge.com Link [Eng],
Another is in Turkish:  #iPhoneTurkey Link [Tr]

Since I am registered as a developer, I had a chance to try iOS 6 beta in my iPhone 4S.

Before I start, I also downloaded the new beta version of Xcode 4.5 and I tried to upgrade through it. But I had the “The iPhone “xxx” could not be updated. This device isn’t eligible for the requested build.” error. I did what adviced on some websites but it didn’t change the result. Then I tried to upgrade through iTunes (which I guess the supported way) and it was successfully done.

I was be able to restore my data but I forgot to sync the apps so all of them was lost. I had to go to my history in App Store and redownload all. Luckily, my restore data had all the data of applications so I lost no data.

As you see, if you want to upgrade, you better not try Xcode instead of iTunes and don’t forget to backup your iPhone then sync all the apps.

What I saw at first that my iPhone was struggling to run iOS 6 sometimes, it was ending up burning like hell. It wasn’t happening all the time actually but for certain applications.

For example, iOS 6 mail application was running too slow sometimes and it doesn’t even respond. Then the iPhone’s temperature was getting high quickly.

Also, since Apple will be using its own maps application instead of Google Maps, the Map application is working on Apple Maps. I wasn’t sure about what the problem is but the maps application is totally useless at the moment. I guess my location Turkiye is involved with this issue but maps application is very slow and it doesn’t even show the maps. They added voice navigation and 3D view too but I couldn’t even get there since the maps app was not working stabile. It also caused heat problem, too.

For sure, beta version had pretty cool features which you will get a chance to see in the links I shared above. What I liked that Siri could open applications now [in iOS 5, it says "I'd like to but I'm not allowed to :("] and navigation in maps will save most people buying a navigation app (I might be one of those), you have options for incoming calls like reply with an sms etc., you can set your iPhone to “don’t disturb” mode or you can keep it open for chosen contacts and all that kind of stuff.

But even though I’m an Apple Developer, I think I’ll wait for the community version of iOS 6. If they release fixed version of beta, that will stay as an option too.

June 18, 2012 0 comments
Generate Random Number and String in MS SQL Server

Generate Random Number and String in MS SQL Server

Sometimes you might wanna generate random number or string in MS SQL. For example, I do it for temporary user passwords.

Here’s how you generate a random number. X is the max value, the code is generating between 0 and (X-1).

SELECT CONVERT(INT, X*RAND())

Be aware that max. generated number is X-1 because it’s generating X numbers starting from 0(zero).

If you generate 5 numbers, your range will be: {0, 1, 2, 3, 4}.

 

Another code is generating random string(VARCHAR). Here it is:

SELECT SUBSTRING(CONVERT(varchar(255), NEWID()), 0, 9)

Attention to 0, 9. It’s substring range, here I’m generating a string value whose length is 10 characters.

June 9, 2012 0 comments
JDK 7 With Netbeans: FTP Problem With Windows Firewall

JDK 7 With Netbeans: FTP Problem With Windows Firewall

Yesterday I installed Netbeans to my Windows PC and tried to add a remote PHP project. I want to say that 1 day before, I installed same version of Netbeans to my Mac and added the remote project, there were no issues.

But yesterday, I was unable to add remote project, no matter what I tried, it was unable to add, giving the error that there is no file on the remote folder. The connection was tested and working too.

So I tried to disable Windows Firewall and ta-dah! It worked. What confused me is that first time I opened Netbeans, it warned me that there might be issues with Windows Firewall and prompted the classic Firewall pop-up to me to either allow or block the application, and I allowed. But it still was unable to get through.

Some searches guided me that that was a problem with JDK 7 and some people downgraded to JDK 6 were able to connect FTP folder.

But I didn’t want to downgrade because it was loooking too unnecessary to me. I mean, this is JDK and Netbeans, seriously, no solutions?

Anyway, I was too sleepy to fight with firewalls or libraries at that moment, I slept. This morning, with a fresh brain, I found out that “The only difference between JDK7 and older releases is that the JDK is using IPv6 sockets when IPv6 is enabled and so IPv4-mapped IPv6 addresses are used. it may be that Windows or the firewall is not configured to allow IPv6 sockets.”(1)

And there was a command that worked for some people(2). I tried, it worked for me, too.

What you have to do is open MS-DOS with administrator rights and paste this, hit enter. Probably, it will work for you, too. Hope so.

netsh advfirewall set global StatefulFTP disable

(1) Source Link
(2) Source Link

January 22, 2012 21 comments