How to stay safe online in public!

August 11, 2010

I didn’t write this article, but I did find it interesting. Some of the tips here are very common sense, but there is a program that the author recommends (however I have not yet tried it).

Take a look and let me know what you think!

http://www.wisdeo.com/articles/view_post/8375

0

Getting elements of a Table in Javascript

July 17, 2010
Tags:

If you ever need to loop through a table in javascript this is how I was able to navigate through one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var oTable = document.getElementById('myTable');
//gets table

var rowLength = oTable.rows.length;
//gets rows of table

for (i = 0; i < rowLength - 2; i++){
//loops through rows

   var oCells = oTable.rows.item(i).cells;
   //gets cells of current row
   var cellLength = oCells.length;
       for(var j = 0; j < cellLength; j++){
       //loops through each cell in current row
          <!--get your cell info here-->
          <!--var cellVal = oCells.item(j).innerHTML;-->      
       }
}
0

PHP: Objects Populating and Returning Data

July 14, 2010
Tags: ,

Now that you have setup your object, now the fun begins.  I will preface that the following examples are how I currently have my objects set up.  There are probably people out there that know some other super cool ways of populating and retrieving data from objects, however, this is the way I know how.  So I’m up for suggestions if you have them!

For me I either wanted to return a single value or some sort of list.  Remember I’m keeping my OOP super simple.  I’m not getting into child lists or grandchildren or anything too complicated.  For me simple is better and until I find an example of something complicated that is explained into simple…  I’m sticking with simple.

I have already gone over how to Set & Get a property.  To call a single property after it has been populated would go something like this:

1
2
3
4
5
$_bibleAnswer= new bibleAnswer();

$_bibleAnswer->getAnswer();

echo $_bibleAnswer->answerText;

To break this down.  Remember the function __construct() {} found in the object created in the last post?  Basically we are instantiating the object as a “New” object on the very first line.    So now the variable $_bibleAnswer contains an instance of the class bibleAnswer.  The next line calls the method getAnswer().  Even though in the last example I didn’t run any query or populate the properties, a function like this would populate your properties so they can be returned.  The final line writes out the value to the variable $_bibleAnswer that contains an instance of the object bibleAnswer which has the property answerText.  I know it might sound a little confusing but the next example should clear it up a little.

In this example I am showing the getStoryCount method from my siteStats object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getStoryCount()
{
$dbconnect = db_connect() or trigger_error("SQL", E_USER_ERROR);
$query = "SELECT count(storyId) as storyCount FROM STORY where buryCount < 3";
/*echo $query;*/
$result = mysql_query($query, $dbconnect) or trigger_error("SQL", E_USER_ERROR);

if (@mysql_num_rows($result)>0){
while ($row = mysql_fetch_array($result))
{
$this->dbEntries = $row["storyCount"];
}

}
mysql_free_result($result);
mysql_close($dbconnect);
}

I will explain the Database Object that I am using in a post in the future.  I did not create that particular object, but it works for me and it certainly worth sharing.  However in the example above you see I am calling my table and I returning a value which then populates the property dbEntries.  Pretty simple, now the example above should make a little more sense.

I mentioned above that there were 2 things I wanted to be able to get from my objects.  A single value, which I just showed how to get and a list.  Now for me I just declare a variable in my object like this:

1
var $data_array;        // data from the database

I do not have a Get and Set for this variable.

Then in my get method:

1
2
3
4
5
6
7
8
9
10
11
12
13
$i = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

$da[$i] = array('storyId'=>$row["storyId"], 'categoryId'=>$row["categoryId"],
'URL'=>$row["URL"], 'title'=>$row[title],'summary'=>$row["summary"],
'voteCount'=>$row["voteCount"], 'commentCount'=>$row["commentCount"]);
$i++;
}
$this->data_array = $da;

mysql_free_result($result);
mysql_close($dbconnect);
}

While in my loop I populate an array by setting each property with the value from the database.  Then you set the variable $data_array equal to the array you just looped through.

When you want to display this data you will have to loop through the array.  I do it like this:

1
2
3
4
5
6
7
8
9
10
$_story->getStoryListLimit(); //Calling GET method

for($i = 0; $i <= count($_story->data_array) - 1; $i++) //loop through variable data_array

echo "<a href='".$_story->data_array[$i]['URL']."' target='_new'>" . $_story->data_array[$i]['title'] . "</a></p>";
echo "<p class='lftBottomText'>" . $newurl["scheme"]."://". $newurl["host"] . "</p>";
echo "<p class='lftBottomTextBottom'>Votes: " . $_story->data_array[$i]['voteCount'];
echo " Comments: " . $_story->data_array[$i]['commentCount'] . "</p>";

}

In my setup of the data_array when I was populating the properties I can now references name values by using the following notation:

1
$_story->data_array[$i]['voteCount']

Again, this is how I do it.  There are probably many ways of doing it.  This works for me.  However, if you have a better way, a cleaner way or more of a “right” way, please let me know.  I just want this to be an option for people.

0

PHP: Objects

July 12, 2010
Tags: ,

For me, the thought of .php being Object Oriented was both intriguing and a little concerning.  I was excited about the possibilities (cleaner code, and better designed applications), but I was also concerned as I had to learn this not that easy of a concept in an environment that I was just getting started in.

For me the best way to learn something is to start small.  So I asked myself what is an object?  This was simple…  It is just a file that contains properties and CRUD operations (Create, Update, Delete and Get).  Now the question was how do I implement this.   Once again the community came to the rescue and after searching for just a couple of minutes I was creating my first object in .php!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
class bibleAnswer

{

var answerId;
var questionId;
var answerText;

function __construct() {}

function set_answerId($new_answerId) {
$this->answerId = $new_answerId;

}

function get_answerId() {
return $this->answerId;
}

function set_questionId($new_questionId) {
$this->questionId = $new_questionId;
}

function get_questionId() {
return $this->questionId;
}

function set_answerText($new_answerText) {
$this->answerText = $new_answerText;
}

function get_answerText() {
return $this->answerText;
}

function addAnswer(){

}

function updateAnswer(){

}

function deleteAnswer(){

}

function getAnswer(){

}

}

This is a very basic object.  If you copied and pasted this code up to your server you would technically have an object.  But lets go through it a little.

First you designate a name.  I called my object: “bibleAnswer’.  I run a Christian website (GODSurfer.com) so that is why you are seeing the naming convention here.  So bibleAnswer is what I set the Class equal to.  The next are the property declarations.  First I declare the variables I want to use.  In this case:

  • answerId
  • questionId
  • AnswerText

The “function __construct” line basically allows you to create a “new” object when you call this object in code (more on that later).

The next several lines are your Get and Set lines for your properties.  In the following snippet  a function called set_answerId.  As a general rule of thumb I tried to use the “set_” and “get_” prefixes attached to my property for ease of reading later.  Setting a property is easy.  It is assigning a value to a variable.  Getting a property is calling that variable and getting the value (assigned in the setting process).

1
2
3
4
5
6
7
8
function set_answerId($new_answerId) {
$this->answerId = $new_answerId;

}

function get_answerId() {
return $this->answerId;
}

In this example you noticed the $this-> notation.  This notation is probably the most complicated part of writing object oriented code in .php.  I will dive into this in upcoming sections.  Just know for now in this setting the “$this->” notation is needed to get and set properties because that is how you reference variables in your base class.

In the next section I have stubbed out my basic CRUD operations (Create, Update, Delete & Get).

That is the structure of an object in .php

You should know that with any programming language you can make things very complicated or you can keep it super simple.  I’ll be honest I’m more in the super simple category.  But that is what works for me.  As I get better at programming in .php I will find new techniques that are more complicated.  The most important thing for me is to understand the code.  So I’m staying simple.

I will explain more about how to populate the objects with data and how to return the objects and its data to the screen in the: PHP: Objects Populating and Returning data post.

0

PHP: The Beginning

July 9, 2010
Tags: ,

I got into .php because I wanted to see if I could learn something new.  Well technically that isn’t 100% true as I was an .Net programmer and I started with classic ASP.  I had heard that .php is similar to ASP so I figured it might be an easier transition.

The similarities to ASP (off the top of my head) are:

  • Server Side Code
  • Delimiters  (ASP: <% %> .php <? ?>)
  • Debugging is similar  (ASP: response.write .php: echo)

There may be others but those are the big ones.  ASP leaned heavily towards VBScript where .php is more javaScript and C like (being  that is more like a C language that also makes it case sensitive).  .php is Open Source and is closely intertwined with mySQL (which is also Open Source).  I think the fact that .php is considered Open Source is its greatest asset.  With .php I never felt like I was recreating the wheel with my own code.  If I could think of something I found that it had already been accomplished by someone else.  So getting the sites up and running was very easy.

By using .php I also had to find a web hosting company that hosted .php sites.  These sites usually ran on Apache web servers.  Getting a good host was harder than I thought at first (as there are so many to choose from).  But eventually after I did my research I was able to find a mid to large size company that was very reasonable and reliable.  I was pleased to find out that managing my website with Apache was very easy to do.  Both hosting companies supplied a control panel that was super easy to figure out.  By fumbling around with the options I learned even more.  My basic rule of thumb is if I didn’t know what it did then I didn’t press the button.  However, when there came a time for me to do some configurations on the server I was easily able to find my answers online and find the appropriate option in my control panel (for example when I needed to redirect my site to include the “www.” prefix).

Well I started my project in .php and fell in love with it.  It was easy, the community was great and I was able to have a working website without having to do too much prep or research.  What I found through the years is that when I attempted something new the 2nd and 3rdversions were always so much cleaner and nicer.  During this time I also learned a ton about CSS and javaScript and AJAX.  Again the community was great so learning these things was not a big deal.    After toiling for a couple of weeks on my project I was done.  What I found was that I had 7 folders and close to 50 files.  This was very reminiscent to classic ASP.  The worst part of ASP was also in .php and that is the dreaded spaghetti code.  Being that .Net was just getting off the ground and I was still very used to the classic ASP style I didn’t do much about my situation.  However, as I got better at OOP and I spent more time in the .php community I found that in the version that I was using they made .php object oriented!  This was huge news, but this time research was needed.

0

Facebook Graph API

July 6, 2010

Holy cow!  I’m super disappointed in the lack of overall examples that Facebook has regarding how to connect to Facebook from a website.  They recently released their Graph API.  Facebook is in the middle of converting their developer docs to their new website at: http://developers.facebook.com/docs/

I had learned about 5 months or so ago how to connect to Facebook using their Facebook Connect.  It was a process but there were lots of examples to go off of.  Eventually I was able to figure it out and it worked.  Well I fired up the code again and all of a sudden it wasn’t working.  So I began my research.  Come to find out Facebook is going in a new direction with this Graph API.  Since my website doesn’t get a lot of traffic (the one that had the FB Connect code), I figured I would try out the “new way” of connecting to FB.

I will say that once you figure out the direction Facebook is going, the new API and related calls make more sense then when you are looking at it not knowing what to do.  The first thing I needed to do is to have my users go through authorization.  Basically they needed to login in to Facebook and tell FB that they are allowing my site to have access.  I believe this was the old “Facebook Connect” process.  With this new API they changed it and to be honest made it better.  The technical process is called OAuth 2.0 protocol.  Facebook has a couple of links that explain this in way more technical detail then I was interested in.  You can find them here: http://developers.facebook.com/docs/authentication/

Since I’m really interested in jQuery and Javascript I noticed that there was a link to more information regarding Javascript-based Authentication.  This link should of had plenty of examples.  However, there were more links and a brief description of User-Agent flow which even though I read 3 times I still couldn’t figure out where they were going with it.  My whole experience in figuring this out was like starting a book in the middle and reading towards the end.  However, no matter how far I backed up in the developers site I never could get to the beginning.  There was one link that did finally have an example.  It is the “Official Javascript SDK“.  There is a folder called “examples” which then opens up to another list of folders and I chose the jQuery folder.  There you will see the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<pre><!doctype html>
<html>
  <!--
Copyright Facebook Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>Connect JavaScript - jQuery Login Example</title>
  </head>
  <body>
    <h1>Connect JavaScript - jQuery Login Example</h1>
    <div>
      <button id="login">Login</button>
      <button id="logout">Logout</button>
      <button id="disconnect">Disconnect</button>
    </div>
    <div id="user-info" style="display: none;"></div>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

    <div id="fb-root"></div>
    <script src="http://connect.facebook.net/en_US/all.js"></script>
    <script>
      // initialize the library with the API key
      FB.init({ apiKey: '<your API KEY>' });

      // fetch the status on load
      FB.getLoginStatus(handleSessionResponse);

      $('#login').bind('click', function() {
        FB.login(handleSessionResponse);
      });

      $('#logout').bind('click', function() {
        FB.logout(handleSessionResponse);
      });

      $('#disconnect').bind('click', function() {
        FB.api({ method: 'Auth.revokeAuthorization' }, function(response) {
          clearDisplay();
        });
      });

      // no user, clear display
      function clearDisplay() {
        $('#user-info').hide('fast');
      }

      // handle a session response from any of the auth related calls
      function handleSessionResponse(response) {
        // if we dont have a session, just hide the user info
        if (!response.session) {
          clearDisplay();
          return;
        }

        // if we have a session, query for the user's profile picture and name
        FB.api(
          {
            method: 'fql.query',
            query: 'SELECT name, pic FROM profile WHERE id=' + FB.getSession().uid
          },
          function(response) {
            var user = response[0];
            $('#user-info').html('<img src="' + user.pic + '">' + user.name).show('fast');
          }
        );
      }
    </script>
  </body>
</html>

If you copy and paste the above code into your project you will see that in fact it does authorize you to use the site (remember you need an API Key when you create your application on Facebook).  However, this example doesn't show how to "extend" the permissions.  It just gives you a very basic example.  Don't get me wrong I was happy to get this far but it is far from usable.  There is no really information about the FQL or the FB. commands.

I hunted and pecked around for hours on the Facebook site trying to find another example.  I went to the forums and found very little (at least for the question I was asking - specifically for the extended params and the Graph API).  I went to stackoverflow.com which by the way is a great resource, however this time I found very little.  So I decided to ask about it: Help using OAuth 2.0 with Javascript jQuery API to integrate with Facebook.  Within an hour a member of stackoverflow.com answered my question with another site with an example: thinkdiff.net

To be honest I had found that site prior to the answer and I implemented his example in my project and it worked.  However, it was a little different then the jQuery example I mentioned above.  The thinkdiff.net example was using FBML and passing the extended permissions on the button.  While I was waiting for the community to answer my question I started to dig deeper into the documentation.  I found information about the "FB." commands.  I also found info on FQL.  Unfortunately I wasn't really able to put 1 and 1 together yet.  When I was redirected to thinkdiff.net I re-tried the example and started to see things a little differently.  I asked a question via the comments and received a very speedy answer.  With that answer I was able to start combining the two examples together into the following.  My first code example is using the jQuery example I found on Facebook and modified it to ask for the extended params inside the jQuery code.  The second example is using the thinkdiff.net example and adding an "FB." command which is from the FB.API.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>New Graph api & Javascript Base FBConnect Tutorial | Thinkdiff.net</title>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '<your API KEY>', status: true, cookie: true, xfbml: true});

/* All the events registered */
FB.Event.subscribe('auth.login', function(response) {
// do something with response
login();
});
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
logout();
});

FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
login();
}
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());

function login(){
FB.api('/me', function(response) {
document.getElementById('login').style.display = "block";
document.getElementById('login').innerHTML = response.name + " succsessfully logged in!";
});
fqlQuery();
}
function logout(){
document.getElementById('login').style.display = "none";
}

//stream publish method
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: name,
caption: '',
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {

});

}
function showStream(){
FB.api('/me', function(response) {
//console.log(response.id);
streamPublish(response.name, 'Thinkdiff.net contains geeky stuff', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
});
}

function share(){
var share = {
method: 'stream.share',
u: 'http://thinkdiff.net/'
};

FB.ui(share, function(response) { console.log(response); });
}

function graphStreamPublish(){
var body = 'Reading New Graph api & Javascript Base FBConnect Tutorial';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}

function fqlQuery(){
FB.api('/me', function(response) {
var query = FB.Data.query('select name, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {

document.getElementById('name').innerHTML =
'Your name: ' + rows[0].name + "<br />" +
'<img src="' + rows[0].pic_square + '" alt="" />' + "<br />" +
'e-mail: ' + response.email ;
});
});
}

function setStatus(){
status1 = document.getElementById('status').value;
FB.api(
{
method: 'status.set',
status: status1
},
function(response) {
if (response == 0){
alert('Your facebook status not updated. Give Status Update Permission.');
}
else{
alert('Your facebook status updated');
}
}
);
}
</script>

<h3>New Graph api & Javascript Base FBConnect Tutorial | Thinkdiff.net</h3>
<p><fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button></p>

<p>
<a href="#" onclick="showStream(); return false;">Publish Wall Post</a> |
<a href="#" onclick="share(); return false;">Share With Your Friends</a> |
<a href="#" onclick="graphStreamPublish(); return false;">Publish Stream Using Graph API</a> |
<a href="#" onclick="fqlQuery(); return false;">FQL Query Example</a>
</p>

<textarea id="status" cols="50" rows="5">Write your status here and click 'Status Set Using Legacy Api Call'</textarea>
<br />
<a href="#" onclick="setStatus(); return false;">Status Set Using Legacy Api Call</a>

<br /><br /><br />
<div id="login" style ="display:none"></div>
<div id="name"></div>

</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>New Graph api & Javascript Base FBConnect Tutorial | Thinkdiff.net</title>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '<your API Key>', status: true, cookie: true, xfbml: true});

/* All the events registered */
FB.Event.subscribe('auth.login', function(response) {
// do something with response
login();
});
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
logout();
});

FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
login();
}
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());

function login(){
FB.api('/me', function(response) {
document.getElementById('login').style.display = "block";
document.getElementById('login').innerHTML = response.name + " succsessfully logged in!";
});
fqlQuery();
}
function logout(){
document.getElementById('login').style.display = "none";
}

//stream publish method
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: name,
caption: '',
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {

});

}
function showStream(){
FB.api('/me', function(response) {
//console.log(response.id);
streamPublish(response.name, 'Thinkdiff.net contains geeky stuff', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
});
}

function share(){
var share = {
method: 'stream.share',
u: 'http://thinkdiff.net/'
};

FB.ui(share, function(response) { console.log(response); });
}

function graphStreamPublish(){
var body = 'Reading New Graph api & Javascript Base FBConnect Tutorial';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}

function fqlQuery(){
FB.api('/me', function(response) {
var query = FB.Data.query('select name, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {

document.getElementById('name').innerHTML =
'Your name: ' + rows[0].name + "<br />" +
'<img src="' + rows[0].pic_square + '" alt="" />' + "<br />" +
'e-mail: ' + response.email ;
});
});
}

function setStatus(){
status1 = document.getElementById('status').value;
FB.api(
{
method: 'status.set',
status: status1
},
function(response) {
if (response == 0){
alert('Your facebook status not updated. Give Status Update Permission.');
}
else{
alert('Your facebook status updated');
}
}
);
}
</script>

<h3>New Graph api & Javascript Base FBConnect Tutorial | Thinkdiff.net</h3>
<p><fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button></p>

<p>
<a href="#" onclick="showStream(); return false;">Publish Wall Post</a> |
<a href="#" onclick="share(); return false;">Share With Your Friends</a> |
<a href="#" onclick="graphStreamPublish(); return false;">Publish Stream Using Graph API</a> |
<a href="#" onclick="fqlQuery(); return false;">FQL Query Example</a>
</p>

<textarea id="status" cols="50" rows="5">Write your status here and click 'Status Set Using Legacy Api Call'</textarea>
<br />
<a href="#" onclick="setStatus(); return false;">Status Set Using Legacy Api Call</a>

<br /><br /><br />
<div id="login" style ="display:none"></div>
<div id="name"></div>

</body>
</html>

I want to give credit where credit is due.  I did not write these examples.  I copied and pasted and modified them.  I am writing this post as hopefully it will serve a stepping stone to other more comprehensive examples.  I still don't understand all of what this new API does, however, I am getting closer to being able use the new API for registration and login functionality.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>New Graph api & Javascript Base FBConnect Tutorial | Thinkdiff.net</title>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '33430d50f1791b68eada779fe84282f2', status: true, cookie: true, xfbml: true});

/* All the events registered */
FB.Event.subscribe('auth.login', function(response) {
// do something with response
login();
});
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
logout();
});

FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
login();
}
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());

function login(){
FB.api('/me', function(response) {
document.getElementById('login').style.display = "block";
document.getElementById('login').innerHTML = response.name + " succsessfully logged in!";
});
fqlQuery();
}
function logout(){
document.getElementById('login').style.display = "none";
}

//stream publish method
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: name,
caption: '',
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {

});

}
function showStream(){
FB.api('/me', function(response) {
//console.log(response.id);
streamPublish(response.name, 'Thinkdiff.net contains geeky stuff', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
});
}

function share(){
var share = {
method: 'stream.share',
u: 'http://thinkdiff.net/'
};

FB.ui(share, function(response) { console.log(response); });
}

function graphStreamPublish(){
var body = 'Reading New Graph api & Javascript Base FBConnect Tutorial';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}

function fqlQuery(){
FB.api('/me', function(response) {
var query = FB.Data.query('select name, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {

document.getElementById('name').innerHTML =
'Your name: ' + rows[0].name + "<br />" +
'<img src="' + rows[0].pic_square + '" alt="" />' + "<br />" +
'e-mail: ' + response.email ;
});
});
}

function setStatus(){
status1 = document.getElementById('status').value;
FB.api(
{
method: 'status.set',
status: status1
},
function(response) {
if (response == 0){
alert('Your facebook status not updated. Give Status Update Permission.');
}
else{
alert('Your facebook status updated');
}
}
);
}
</script>

<h3>New Graph api & Javascript Base FBConnect Tutorial | Thinkdiff.net</h3>
<p><fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button></p>

<p>
<a href="#" onclick="showStream(); return false;">Publish Wall Post</a> |
<a href="#" onclick="share(); return false;">Share With Your Friends</a> |
<a href="#" onclick="graphStreamPublish(); return false;">Publish Stream Using Graph API</a> |
<a href="#" onclick="fqlQuery(); return false;">FQL Query Example</a>
</p>

<textarea id="status" cols="50" rows="5">Write your status here and click 'Status Set Using Legacy Api Call'</textarea>
<br />
<a href="#" onclick="setStatus(); return false;">Status Set Using Legacy Api Call</a>

<br /><br /><br />
<div id="login" style ="display:none"></div>
<div id="name"></div>

</body>
</html>

0

jQuery jqGrid Paging

July 1, 2010
Well after I figured out how to load data into the grid the paging was not very intuitive.  Ultimately I was looking for the page value that was being passed whenever the “Next” or “Previous” buttons are pressed.

My .ajax call in wrapped in a function that passes postdata as a parameter. I couldn’t find any documentation on that parameter but I thought maybe that is where the page value was contained. As you can see I did an alert with postdata.page and low and behold I got a value (based off of the click of the next button).

So I created a parameter in my webservice called page (integer).

Just as a side note, you pass in a integer value from jQuery to your ASP.Net webservice like this:

1
data: "{'page':'" + postdata.page + "'}"

Below is the full function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function processrequest(postdata) {
alert(postdata.page);
$(".loading").show();
$.ajax({
type: "POST",
data: "{'page':'" + postdata.page + "'}",
datatype: "json",
url: "../webServices/myTestWS.asmx/testMethod",
contentType: "application/json; charset-utf-8",
complete: function (jsondata, stat) {
if (stat == "success") {
var thegrid = jQuery("#list")[0];
var jsonObject = (eval("(" + jsondata.responseText + ")"));
thegrid.addJSONData(jsonObject.d);
$(".loading").hide();
} else {
$(".loading").hide();
alert("Error with AJAX callback");
}
}
});
}
0

jQuery jqGrid Example

July 1, 2010

I am using ASP.Net (3.5 framework) in the Visual Studio 2010 environment for this example.  Ultimately I am figuring out how to really make my sites pop visually and I think jQuery is the way to go.  I am working on a project where I needed to replicate a large dataset  that was bound to a desktop datagrid.  Since this project is web based I wanted to see how I can do it in the web without using all the lame Microsoft controls.  I will explain my position about this in another post.  With a little searching I found a jQuery datagrid plugin here.  It is called jqGrid.

Now…  I spent days to be honest figuring out how to use this.  However, I finally created a super simple example that worked which allowed me to use jqGrid in a much more complicated dataset on my project.

First the Basics:

You need the latest version of jQuery.  You can find that here.  You will also need the jQueryUI stylesheet.  You can find that here. I suppose you don’t really need the jquery-ui-1.8.2.custom.css file but for just getting started it will make your life easier.

The Setup:

I’m using a MasterPage setup.  So I’m putting all my needed files in my MasterPage and then I don’t have to add them to any of the other pages as long as they reference this MasterPage.

1
2
3
4
5
6
7
8
9
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href="Styles/jquery-ui-1.8.2.custom.css" rel="stylesheet" type="text/css" />
<link href="Styles/ui.jqgrid.css" rel="stylesheet" type="text/css" />

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Scripts/grid.locale-en.js" type="text/javascript"></script>
<script src="Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>

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

As you can see I have the jquery-1.4.1.min.js and the jquery-ui-1.8.2.custom.css as I mentioned above.  The site.css file is the template I used for my site.   There is an installation text file in the download.  If you follow that then you will have access to jqGrid on your site.  jsTest1.js is my javascript file that I use to make my jQuery calls.

The Object(s):

I am doing a very simple example but this will allow you to see the grid in action.

I have one object that has the following properties:

1
2
3
4
5
Public Class myTest
Private _total As Integer
Private _records As Integer
Private _page As Integer
Private _rows As List(of names)

Then I have a “names” object with the following properties:

1
2
3
Public Class names
Private _name As String
Private _title As String

As you can see this was a very simple example.  There may be other ways to set this up but this is how I chose to do it.  Which worked, which was most important at the time.

The WebService:

If you have not checked out web services in .Net you should really spend some time with them.  I am using them all the time when doing AJAX calls.  jQuery and webservices now go hand in hand.  I will provide an example of how to call a webservice from jQuery but more detail will be in another post.

When you first create a webservice file in ASP.Net it looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class test
Inherits System.Web.Services.WebService

<WebMethod()> _
Public Function HelloWorld() As String
Return "Hello World"
End Function

End Class

In order to use the webservice with jQuery and jqGrid then you need add a few things.  The following is the webservice that I used for my example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Web
Imports System.Web.Script.Services

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class myTestWS
Inherits System.Web.Services.WebService

<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
<WebMethod()> _
Public Function testMethod() As myTest
Dim myString As New myTest
myString.records = 2
myString.total = 2
myString.page = 1

Dim myName As New names
myName.name = "Jeff"
myName.title = "Programmer"

Dim myNamesList As New List(Of names)
myNamesList.Add(myName)

myString.rows = myNamesList

Dim myName2 As New names
myName2.name = "Steve"
myName2.title = "Programmer"

myNamesList.Add(myName2)

Return myString
End Function

End Class

As you compare the differences between the original and the one I used I added:

Imports System.Web
Imports System.Web.Script.Services

I also uncommented out the following line (just followed Microsofts instructions):

<System.Web.Script.Services.ScriptService()>

Then I also added the following above my <WebMethod()> _ call:

<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _

I haven’t done a lot of research as to why I needed all that, I was just getting my example to work.  However, as I do more of these using webservices and jQuery I will probably have to figure it out.  More to come on that.

As you can see in my webservice method I am just populating the properties and adding data to the list property.

Now the jQuery:

In my jsTest1.js file (mentioned above) I have the code that calls the webservice using the jQuery .ajax function returning JSON data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function processrequest(postdata) {
$(".loading").show();
$.ajax({
type: "POST",
data: "{}",
datatype: "json",
url: "../webServices/myTestWS.asmx/testMethod",
contentType: "application/json; charset-utf-8",
complete: function (jsondata, stat) {
if (stat == "success") {
var thegrid = jQuery("#list")[0];
var jsonObject = (eval("(" + jsondata.responseText + ")"));
thegrid.addJSONData(jsonObject.d);
$(".loading").hide();
} else {
$(".loading").hide();
alert("Error with AJAX callback");
}
}
});
}

In lines 3-20: is your .ajax call.  Go here for detailed information.

I use firebug for FireFox to help me in my jQuery exploits.  I was able to get the JSON data returned from the webservice using this tool.  The JSON data looks like this:

1
{"d":{"__type":"myJQueryTestBed.myTest","total":2,"records":2,"page":1,"rows":[{"name":"Jeff","title"<code>:"Programmer"},{"name":"Steve","title":"Programmer"}]}}

The actual jQuery code is here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
datatype: processrequest,
mtype: 'POST',
jsonReader: {
root: "rows", //arry containing actual data
page: "page", //current page
total: "total", //total pages for the query
records: "records", //total number of records
repeatitems: false,
id: "ID" //index of the column with the PK in it
},
colNames: ['Name', 'Title'],
colModel: [
{ name: 'name', index: 'name', width: 55 },
{ name: 'title', index: 'title', width: 90 }
],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 20, 30],
sortorder: "desc",
viewrecords: true,
caption: 'My first grid'
});
});

Notice line 3: datatype: processrequest,

This line calls the function processrequest which called the webservice.  You could see examples that make the Ajax call  inside the jQuery function above but I found it was a little cleaner for me to separate out the calls.

The most obscure item are lines 5-12: the jsonrReader.  I'm still trying to figure it all out but it takes your JSON string and uses it in the jqGrid.  I will tell you once I got my data from the webservice in the right format and added the JSONReader block of code the grid worked.

As you can see the JSON data returned from my webservice includes the names that the JSONReader code is looking for.  In all my searches online on how to figure this out the people that seemed to know what they were talking about all said you need this block.  However, the documentation on this I found to be hard to understand as I'm still trying to figure it out.

Well if you put all of this together I got the following to finally work:

Overall, I'm disappointed it took me a couple of days to figure out this grid.  However, maybe it is a little bit of me (being new to jQuery and webservices and JSON) and a little bit of the plugin being that it is so robust it makes it complicated.   I'm still figuring out the application, but I'm hopeful everything else will be a lot easier now that I have data in the grid.

0