Saturday, December 31, 2011

Problems with Recordset Filter

Problem:

I'm having trouble with a filter on an ADO Recordset in legacy ASP Classic code, and I'm trying to understand if what I'm trying to do is not supported, or if I'm just doing it wrong.
I have a recordset of Items, and they have a Status of 1 (active) or 0 (inactive), and an optional End_Date. In my administrative user interface, I have a control to show all items or only those that should be displayed to end-users: Status = 1 AND ( End_Date is null OR End_Date > Date() )
To implement that logic, I tried:
rs.Filter = "Status = 1 AND ( End_Date = null OR End_Date > #" & Date() & "# )"
but I get
ADODB.Recordset (0x800A0BB9)
Unknown runtime error
After much fooling around, it seems that ADO doesn't like the grouping parens around the End_Date conditions in combination with the AND condition. If I take the parens out, this works:
rs.Filter = "Status = 1 AND End_Date = null OR End_Date > #" & Date() & "#"
But that's just an accident -- it looks like the filter conditions are evaluated in order, and so I get the results I want. If I change the AND to OR, the parens work:
rs.Filter = "Status = 1 OR ( End_Date = null OR End_Date > #" & Date() & "# )"
But of course that logic is wrong -- it shows Active but expired items.
Strangely, if I move the conditions around, it breaks again:
rs.Filter = "End_Date = null OR Status = 1 AND End_Date > #" & Date() & "# "
crashes with the same ADODB error.
I can't seem to predict what will and won't work, and the docs I've read are very sketchy on the syntax expected (it's not pure T-SQL!), the limitations, etc. and all the examples I've seen have at most two conditions. I don't think my conditions are all that complex. Can anyone tell me if what I'm trying to do is supported, if there'


Solutions:
There is no precedence between AND and OR. Clauses can be grouped within parentheses. However, you cannot group clauses joined by an OR and then join the group to another clause with an AND, like this:
(LastName = 'Smith' OR LastName = 'Jones') AND FirstName = 'John'
Instead, you would construct this filter as:
(LastName = 'Smith' AND FirstName = 'John') OR
(LastName = 'Jones' AND FirstName = 'John')
So you would have to construct your filter like this:
rs.Filter = "( Status = 1 AND End_Date = null ) OR ( Status = 1 AND End_Date > #" & Date() & "# )"




Friday, December 30, 2011

ASP ADODB.recordset Sort Error - '800a0cb3'

problem:
I'm running a union query via ASP on an NT4 server that houses both IIS and my Pervasive database. Because it's a union, I can't use an ORDER BY sort in the query itself, so I was attempting to sort the returned recordset. However, when the script hits the sort property, I get the following:

ADODB.Recordset error '800a0cb3'

Current provider does not support the necessary interfaces for sorting or filtering.


Here's the gist of my code:

Set Conn = Server.CreateObject("ADODB.Connection")
Set RS = Server.CreateObject("ADODB.RecordSet")
Conn.Open dsn, dbuser, dbpass
sql="SELECT blah blah blah ... " & _
"UNION ALL " & _
"SELECT blah blah blah ..."
RS.Open sql, Conn
RS.Sort = "Part_Number ASC"





Solutions
All set. A Pervasive tech support dude told me to set the cursor as client-side.

I stuck this line before the RS.Open, and it worked fine:

RS.CursorLocation = 3

3 is the enumerated value of adUseClient.

ADODB.Recordset error '800a0cb3' Current Recordset does not support bookmarks. This may be a limitation of the provider or of the selected cursortype

you're not using the rs.Open method. 
remove the Con.Execute line and use the open method

'Set prodRS= Con.Execute(sqlString) 'don't use this!

Con.Open "driver={Microsoft Access Driver (*.mdb)};DBQ=" & Server.MapPath("\OnlineStore") & "\StoreDB.mdb" 

Set prodRS= Server.CreateObject("ADODB.Recordset")
prodRS.CursorType = adOpenStatic
prodRS.AbsolutePage = pg
prodRS.PageSize = 5
sqlString = "SELECT * FROM Products " &_
"WHERE product_status = 1 " &_
"AND ( product_category LIKE '%" & product_category & "%' " &_
"OR product_brand LIKE '%" & product_brand & "%') " &_
"ORDER BY product_name "

prodRS.Open sqlString, Con

you should set all the needed properties of the recordset object before calling the open() method.

since you're using the constant adOpenStatic, make sure the adovbs.inc must be included in the asp page. Or you may just use the value 3.

Cloning a Recordset

You can use Clone() method of ADODB.Recordset object to create a duplicate recordset object from an existing recordset object. An important advantage of this method is that instead of creating two independent recordsets, it creates two recordset objects that point to the same recordset. This feature allows you to change the current record in the clone, while keeping the current record same in the original recordset object or vice versa.
Using this method is more efficient than creating a new recordset with the same source definition: It saves an extra trip to the database server. You should note that you can only clone a Recordset object that supports bookmarks. If you make changes to a recordset, then those changes will be visible in all clones. If you execute Requery on the original Recordset, the clones will no longer be synchronized to the original. Similarly if you close the original recordset then it won't close the clones or vice versa. Here is a sample method that makes use of Clone method:
 
Private Sub CloneRecordset(ByVal SourceRecordset As 
ADODB.Recordset, ByRef 
TargetRecordset As ADODB.Recordset)

    ' Only boomarkable recordsets support Clone method
    If (SourceRecordset.Supports(adBookmark)) Then
        Set TargetRecordset = SourceRecordset.Clone()
    End If

End Sub

Wednesday, December 28, 2011

5 Steps to publish on a facebook wall using php


Since Facebook has stopped supporting Java we need to use PHP for now to post on a wall.
According to facebook Wiki posting on a  wall is very confusing and very difficult to write a program to publish on a wall.
I spent around 2 weeks reading many articles and many documents, Wiki on facebook but in vein and tried many ways and finally I got one workable model. Below are 5 simple steps to publish on a Facebook wall.

Step1: Login to Facebook to Create a Facebook App

First login to Facebook and goto the url http://www.facebook.com/developers/ then
Click on “+ Set Up New Application” button to start creating the application as shown below.
Create New Facebook application
Provide the application name, click agree for facebook terms and click on “Create Application” button.
Fill in application Name
create app step1
Now Application is created for you. Just copy the Application API Key, Application Secret and Application ID details which will be used to write the application code.
Fill the Name and Description of your application in About Link.
Facebook Application About Page
Now Click on Website Link to get API Key
Facebook Application web Site
Now goto Facebook Integration link and enter any url. Here is where you will get Secret Key.
Enter the Canvas URL and page name. This will be the return URL of your Application.
Facebook Application Facebook Integration
That’s it You now just successfully create a Facebook Application, now lets work on program
Then click on Save. That’s it we have created a facebook application with an Iframe.
Now Copy Application API Key, Application Secret and Application ID details which will be used to write the application code.

Step2: Generate One Time Token to generate Session key

How to generate One Time Session key:
Run below URL to get temporary token for the particular user by logging into Facebook.
Note: Please replace “API_KEY” with your application API key from above page.
Then we will get a temporary token key.
allowaccess
generatemylogin info
savemyinfo
This is one time token key that we can use to generate a permanent session key. Careful! Don’t try to execute this programs many times

Step3: Generate one time session key (permanent session key)

Below is the sample PHP code to generate one time session key.
01<?php
02 
03// FB_APIKEY is your facebook application api key
04 
05// FB_SECRET is your application secrete key
06 
07$FB_APIKEY="YOUR_API";
08 
09$FB_SECRET="YOUR_SECRET";
10 
11$fb new FacebookRestClient($FB_APIKEY$FB_SECRET);
12 
13$testtoken"ONETIMETOKEN"// Replace this value with your Token Value
14 
15$result $fb->call_method('facebook.auth.getSession',
16 
17array('auth_token' => $testtoken'generate_session_secret' => true));
18 
19echo "<br /><pre>";
20 
21print_r($result);
22 
23echo $session_key $result['session_key'];
24 
25?>
(OR)
For example, the full URL for logging in a user could be:
http://www.facebook.com/login.php?api_key=YOURAPIKEY&connect_display=popup&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true&session_key_only=true&req_perms=read_stream,publish_stream,offline_access


If the user is redirected to the URL specified by the next parameter, then Facebook grants your application a session. This session is appended to the URL as a JSON-decodable object of the form:
&session={“session_key”:”SESSIONKEY”, “uid”:USERID, “expires”:0 || UNIXTIME, “secret”:”SESSIONSECRET”}
In continuing with the above example, the redirect for a successful login would be:
http://www.facebook.com/connect/login_success.html?session=%7B%22session_key%22%3A%223.kxhAu6W0qo_bLGjmdWrgfw__.86400.1243443600-688626964%22%2C%22uid%22%3A%22688626964%22%2C%22expires%22%3A1243443600%2C%22secret%22%3A%220NVNMxpO6jVyDcVCvVv_PA__%22%2C%22sig%22%3A%22ac1c0c77c137567389defea70481b7aa%22%7D
If the user grants your application the offline_access extended permission, 0 gets returned for expires and the session never expires unless the user removes the application. In this case, you should store the session key so the user doesn’t have to log in the next time he or she launches your application.
Note: The above code will execute only once. We should note down the above session key, This will be used to auto login into the application.
If you don’t save these session key values you should generate other token key to create one time session key.
We can use the token only once.

Step4: Setting Permission for wall

Giving Permission to your application to publish on facebook wall. To give permission just replace the your API key in below URL and execute in browser.
http://www.facebook.com/login.php?api_key=APIKEYXxxxxxxxxxxxxxxxxx&connect_display=popup&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true&req_perms=read_stream,publish_stream,offline_access
Then you must see the below 3 Screens
If you don’t see the below then your call back URL or Canvas URL must be incorrect, please check again your application settings and execute the URL again.
allowpermission
allowpublishing
Then on final page, you will see a success message.  That’s it you have given permission for read_stream,publish_stream and offline_access.

Step5: Publishing the message on Facebook Wall


PHP Code to create facebook object with onetime session key and publishing the message on Facebook Wall.
01<?php
02 
03define('FB_APIKEY''YOUR_APIKEY');
04 
05define('FB_SECRET''YOUR_SECRET');
06 
07define('FB_SESSION''YOUR_SESSION_key');
08 
09require_once('facebook-platform/php/facebook.php');
10 
11echo "post on wall";
12 
13try {
14 
15$facebook new Facebook(FB_APIKEY, FB_SECRET);
16 
17$facebook->api_client->session_key = FB_SESSION;
18 
19$fetch array('friends' =>
20 
21array('pattern' => '.*',
22 
23'query' => "select uid2 from friend where uid1={$user}"));
24 
25echo $facebook->api_client->admin_setAppProperties(array('preload_fql' => json_encode($fetch)));
26 
27$message 'From My App: publish steven on facebook';
28 
29if$facebook->api_client->stream_publish($message))
30 
31echo "Added on FB Wall";
32 
33} catch(Exception $e) {
34 
35echo $e "<br />";
36 
37}
38 
39?>
Now you will see the post on wall Great.
published on facebook
So thrilling isn’t we can also publish photos videos on wall.
In my next post see how to publish images and videos to facebook is done
http://wiki.developers.facebook.com/index.php/Stream.publish