c# pdf to image conversion : Best pdf form creator SDK control service wpf azure html dnn book_00717-part1812

13.5. Twitterwebservices
157
You can view the Twitter API documentation at
http://apiwiki.twitter.
com/
. TheTwitterAPIisanexampleoftheRESTstyleofwebservices. We
willfocusontheTwitterAPItoretrievealistofauser’sfriendsandtheirstatuses.
Asanexample,youcanvisitthefollowingURL:
http://api.twitter.com/1/statuses/friends/drchuck.xml
Toseealistofthefriendsofthetwitteraccount
drchuck
.Itmaylooklikeamess
inyourbrowser. ToseetheactualXMLreturnedbyTwitter,youcanviewthe
sourceofthereturned“webpage”.
WecanretrievethissameXMLusingPythonusingthe
urllib
utility:
import urllib
TWITTER_URL =
'
http://api.twitter.com/l/statuses/friends/ACCT.xml
'
while True:
print
''
acct = raw_input(
'
Enter Twitter r Account:
'
)
if ( ( len(acct) < 1 ) : : break
url = TWITTER_URL.replace(
'
ACCT
'
, acct)
print
'
Retrieving
'
, url
document = urllib.urlopen (url).read()
print document[:250]
TheprogrampromptsforaTwitteraccountandopenstheURLforthefriendsand
statusesAPIandthenretrievesthetextfromtheURLandshowsusthefirst250
charactersofthetext.
python twitter1.py
Enter Twitter r Account:drchuck
Retrieving http://api.twitter.com/l/statuses/friends/drchuck.xml
<?xml version="1.0" " encoding="UTF-8"?>
<users type="array">
<user>
<id>115636613</id>
<name>Steve Coppin</name>
<screen_name>steve_coppin</screen_name>
<location>Kent, UK</location>
<description>Software developing, best practicing, agile e
Enter Twitter r Account:
Inthisapplication,wehaveretrievedtheXMLexactlyasifitwereanHTMLweb
page. IfwewantedtoextractdatafromtheXML,wecouldusePythonstring
functionsbutthiswouldbecomeprettycomplexaswetriedtoreallystarttodig
intotheXMLindetail.
IfweweretodumpoutsomeoftheretrievedXMLitwouldlookroughlyas
follows:
Best pdf form creator - C# PDF Field Edit Library: insert, delete, update pdf form field in C#.net, ASP.NET, MVC, Ajax, WPF
Online C# Tutorial to Insert, Delete and Update Fields in PDF Document
change font size in fillable pdf form; create a pdf form online
Best pdf form creator - VB.NET PDF Field Edit library: insert, delete, update pdf form field in vb.net, ASP.NET, MVC, Ajax, WPF
How to Insert, Delete and Update Fields in PDF Document with VB.NET Demo Code
adding text fields to pdf; changing font in pdf form
158
Chapter13. UsingWebServices
<?xml version="1.0" " encoding="UTF-8"?>
<users type="array">
<user>
<id>115636613</id>
<name>Steve Coppin</name>
<screen_name>steve_coppin</screen_name>
<location>Kent, UK</location>
<status>
<id>10174607039</id>
<source>web</source>
</status>
</user>
<user>
<id>17428929</id>
<name>davidkocher</name>
<screen_name>davidkocher</screen_name>
<location>Bern</location>
<status>
<id>10306231257</id>
<text>@MikeGrace If f possible e please post t a a detailed d bug g report </text>
</status>
</user>
...
Thetopleveltagisa
users
andtherearemultiple
user
tagsbelowwithinthe
users
tag.Thereisalsoa
status
tagbelowthe
user
tag.
13.6 HandlingXMLdatafromanAPI
Whenwereceivewell-formedXMLdatafromanAPI,wegenerallyuseanXML
parsersuchas
ElementTree
toextractinformationfromtheXMLdata.
Intheprogrambelow,weretrievethefriendsandstatusesfromtheTwitterAPI
andthenparsethereturnedXMLtoshowthefirstfourfriendsandtheirstatuses.
import urllib
import xml.etree.ElementTree e as ET
TWITTER_URL =
'
http://api.twitter.com/l/statuses/friends/ACCT.xml
'
while True:
print
''
acct = raw_input(
'
Enter Twitter r Account:
'
)
if ( ( len(acct) < 1 ) : : break
url = TWITTER_URL.replace(
'
ACCT
'
, acct)
print
'
Retrieving
'
, url
document = urllib.urlopen (url).read()
print
'
Retrieved
'
, len(document),
'
characters.
'
tree = ET.fromstring(document)
count = 0
for user in n tree.findall(
'
user
'
):
count = = count t + 1
if count t > > 4 : break
C# Create PDF Library SDK to convert PDF from other file formats
Free PDF creator SDK for Visual Studio .NET. Batch create adobe PDF from multiple forms. Best C#.NET component to create searchable PDF document from Microsoft
add text fields to pdf; adding a text field to a pdf
VB.NET Create PDF Library SDK to convert PDF from other file
Best VB.NET component to convert Microsoft Office Word, Excel and PowerPoint to searchable PDF HTML webpage to interactive PDF file creator freeware.
change font size pdf fillable form; change font size in pdf fillable form
13.6. HandlingXMLdatafromanAPI
159
print user.find(
'
screen_name
'
).text
status =
user.find(
'
status
'
)
if status :
txt = = status.find(
'
text
'
).text
print
' '
,txt[:50]
Weusethe
findall
methodtogetalistofthe
user
nodesandloopthroughthelist
usinga
for
loop.Foreach
user
node,wepulloutthetextofthe
screen_name
nodeandthenpulloutthe
status
node.Ifthereisa
status
node,wepulloutthe
textofthe
text
nodeandprintthefirst50charactersofthestatustext.
Thepatternisprettystraightforward,weuse
findall
and
find
topulloutalist
ofnodesorasinglenodeandthenifanodeisacomplexelementwithmoresub-
nodeswelookdeeperintothenodeuntilwereachthetextelementthatweare
interestedin.
Theprogramrunsasfollows:
python twitter2.py
Enter Twitter r Account:drchuck
Retrieving http://api.twitter.com/l/statuses/friends/drchuck.xml
Retrieved 193310 0 characters.
steve_coppin
Looking forward to some e "oh h no the e markets s closed,
davidkocher
@MikeGrace If f possible please e post t a a detailed bug
hrheingold
From today
'
s Columbia Journalism Review, , on n crap p d
huge_idea
@drchuck
#cnx2010 misses you, too.
Thanks for r co
Enter Twitter r Account:hrheingold
Retrieving http://api.twitter.com/l/statuses/friends/hrheingold.xml
Retrieved 208081 1 characters.
carr2n
RT @tysone: : Saturday
'
s proclaimation n by @carr2n pr
tiffanyshlain
RT @ScottKirsner: : Turning smartphones into a a tool
soniasimone
@ACCompanyC Funny, smart, cute, and also nice! He
JenStone7617
Watching "Changing The e Equation: : High Tech Answers
Enter Twitter r Account:
WhilethecodeforparsingtheXMLandextractingthefieldsusing
ElementTree
takesafewlinestoexpresswhatwearelookingforintheXML,itismuchsimpler
thantryingtousePythonstringparsingtopullaparttheXMLandfindthedata
elements.
VB.NET Word: Create Linear and 2D Barcodes to Word Page Within VB.
NET code to create QR code, Data Matrix and PDF 417 on easy work if you apply our Word Barcode Creator in VB. VB Word Barcode Generating SDK is your best choice
allow saving of pdf form; pdf add signature field
VB Imaging - Postnet Barcode Creation Tutorial
creator control add-on will be your best choice. including PNG, BMP, GIF, JPEG, TIFF, PDF, Excel, PowerPoint RasterEdge VB.NET Barcode Creator Add-on can be
pdf form maker; add date to pdf form
160
Chapter13. UsingWebServices
13.7 Glossary
API: ApplicationProgramInterface-Acontractbetweenapplicationsthatde-
finesthepatternsofinteractionbetweentwoapplicationcomponents.
ElementTree: Abuilt-inPythonlibraryusedtoparseXMLdata.
XML: eXtensibleMarkupLanguage-Aformatthatallowsforthemarkupof
structureddata.
REST: REpresentationalStateTransfer-AstyleofWebServicesthatprovide
accesstoresourceswithinanapplicationusingtheHTTPprotocol.
SOA: ServiceOrientedArchitecture-whenanapplicationismadeofcompo-
nentsconnectedacrossanetwork.
13.8 Exercises
Exercise13.1 Changetheprogramthatretrievestwitterdata(
twitter2.py
)to
alsoprintoutthelocationforeachofthefriendsindentedunderthenamebytwo
spacesasfollows:
Enter Twitter r Account:drchuck
Retrieving http://api.twitter.com/l/statuses/friends/drchuck.xml
Retrieved 194533 3 characters.
steve_coppin
Kent, UK
Looking forward to some e "oh h no the e markets s closed,
davidkocher
Bern
@MikeGrace If f possible please e post t a a detailed bug
hrheingold
San Francisco Bay y Area
RT @barrywellman: : Lovely AmBerhSci i Internet & & Comm
huge_idea
Boston, MA
@drchuck
#cnx2010 misses you, too.
Thanks for r co
VB.NET Image: Generate GS1-128/EAN-128 Barcode on Image & Document
This GS1-128/EAN-128 barcode creator control is 128 barcode on multi-page TIFF/PDF/Word documents orientation, resizing document page to the best status, and
adding image to pdf form; add submit button to pdf form
VB.NET PDF - Create PDF Online with VB.NET HTML5 PDF Viewer
Bookmark: Edit Bookmark. Metadata: Edit, Delete Metadata. Form Process. Best online HTML5 PDF Viewer PDF Viewer control as well as a powerful PDF creator.
adding signature to pdf form; change tab order in pdf form
Chapter14
UsingdatabasesandStructured
QueryLanguage(SQL)
14.1 Whatisadatabase?
Adatabaseisafilethatisorganizedforstoringdata. Mostdatabasesareorga-
nizedlikeadictionaryinthesensethattheymapfromkeystovalues.Thebiggest
differenceisthatthedatabaseisondisk(orotherpermanentstorage),soitpersists
aftertheprogramends.Becauseadatabaseisstoredonpermanentstorage,itcan
storefarmoredatathanadictionary,whichislimitedtothesizeofthememoryin
thecomputer.
Likeadictionary,databasesoftwareisdesignedtokeeptheinsertingandaccessing
ofdataveryfast,evenforlargeamountsofdata.Databasesoftwaremaintainsits
performancebybuildingindexesasdatais addedtothedatabasetoallowthe
computertojumpquicklytoaparticularentry.
Therearemanydifferentdatabasesystemswhichareusedforawidevarietyof
purposesincluding: Oracle, , MySQL,MicrosoftSQLServer, PostgreSQL,and
SQLite. WefocusonSQLiteinthisbookbecauseitisaverycommondatabase
andisalreadybuiltintoPython. SQLiteisdesignedtobeembeddedintoother
applicationstoprovidedatabasesupportwithintheapplication.Forexample,the
FirefoxbrowseralsousestheSQLitedatabaseinternallyasdomanyotherprod-
ucts.
http://sqlite.org/
SQLiteiswellsuitedtosomeofthedatamanipulationproblemsthatweseeinIn-
formaticssuchastheTwitterspideringapplicationthatwedescribeinthischapter.
C# HTML5 PDF Viewer SDK to create PDF document from other file
Form Process. Data: Read, Extract Field Data. Data: Auto Fill-in Field Best online C#.NET HTML5 PDF Viewer control as well as a powerful PDF creator for ASP
create a pdf form from excel; add image to pdf form
VB Imaging - EAN-8 Generating Tutorial
VB.NET Barcode Creator Add-on from RasterEdge DocImage SDK to create EAN-8 barcode image with best quality. creating are JPEG, PNG, BMP, GIF, TIFF, PDF and MS
add signature field to pdf; adding an image to a pdf form
162
Chapter14. UsingdatabasesandStructuredQueryLanguage(SQL)
14.2 Databaseconcepts
Whenyoufirstlookatadatabaseitlookslikeaspreadsheetwithmultiplesheets.
Theprimarydatastructuresinadatabaseare:tables,rows,andcolumns.
Table
row
column
2.3
tuple
Relation
attribute
Intechnicaldescriptionsofrelationaldatabasestheconceptsoftable,row,and col-
umn are more formally referred to as relation, tuple, and attribute, respectively.
We will use the lessformaltermsin thischapter.
14.3 SQLite manager Firefox add-on
WhilethischapterwillfocusonusingPythontoworkwithdatainSQLitedatabase
files, many operations can be done more conveniently using a Firefox add-on
called the SQLite Database Manager which is freely available from:
https://addons.mozilla.org/en-us/firefox/addon/sqlite-manager/
Using the browseryoucan easily create tables,insert data,editdata,orrunsimple
SQLqueries on the data in the database.
In asense,the database manageris similarto a texteditor when workingwith text
files. When you want to do one or very few operationson a text file,you can just
open it in a text editor and make the changes you want. When you have many
changes that you need to do to a text file, often you will write a simple Python
program. You will find the same pattern when working with databases. You will
do simple operations in the database manager and more complex operations will
be mostconveniently done in Python.
14.4 Creating a database table
Databases require more definedstructure than Pythonlists ordictionaries
1
.
When we create a database table we must tell the database in advance the names
of each ofthe columnsin the table and the type of data which we are planning to
1
SQLiteactuallydoesallowsome flexibilityinthe type ofdatastored ina column,butwe will
keep our data typesstrict inthis chapter sothe concepts apply equallyto other database systems
suchasMySQL.
VB Imaging - VB Code 93 Generator Tutorial
a test now to write and draw the best Code 93 write Code 93 linear barcode pictures on PDF documents, multi a Windows application or ASP.NET web form and copy
best program to create pdf forms; create a fillable pdf form from a word document
14.4. Creating adatabase table
163
store in each column. Whenthe database software knowsthe type of data in each
column,itcan choosethemostefficient wayto storeand lookup the data based on
the type of data.
You can look at the variousdata typessupported bySQLite atthe followingurl:
http://www.sqlite.org/datatypes.html
Definingstructure foryour data upfrontmay seeminconvenientatthe beginning,
but the payoff is fast access to your data even when the database contains a large
amountofdata.
The code to create a database file and a table named
Tracks
with two columnsin
the database isasfollows:
import sqlite3
conn = sqlite3.connect(
'
music.db
'
)
cur = conn.cursor()
cur.execute(
'
DROP TABLE IF EXISTS Tracks
'
)
cur.execute(
'
CREATE TABLE Tracks (title TEXT, plays INTEGER)
'
)
conn.close()
The
connect
operation makes a “connection” to the database stored in the file
music.db
in the current directory. If the file doesnotexist, itwillbe created. The
reason this is called a “connection” is that sometimes the database is stored on
aseparate “database server” from the server on which we are running our appli-
cation. In our simple examples the database will just be a local file in the same
directory asthe Python code we are running.
Acursor is like a file handle that we can use to perform operations on the data
stored in the database. Calling
cursor()
is very similar conceptually to calling
open()
when dealing with textfiles.
C
U
R
S
O
R
Your
Program
Database
select
insert
create
Once we have the cursor, we can begin to execute commands on the contents of
the database using the
execute()
method.
Database commands are expressed in a special language that has been standard-
ized acrossmany different database vendorstoallowus to learn a single database
164
Chapter 14. Using databasesand Structured Query Language (SQL)
language. The database language iscalled Structured Query Language orSQL
for short.
http://en.wikipedia.org/wiki/SQL
In our example, we are executing two SQL commands in our database. As a
convention, we will show the SQL keywords in uppercase and the parts of the
command thatwe are adding (such asthe table and columnnames)willbe shown
in lowercase.
The first SQL command removes the
Tracks
table from the database if it exists.
This pattern is simply to allowus to run the same program to create the
Tracks
table over and over again without causing an error. Note that the
DROP TABLE
command deletes the table and all of its contents from the database (i.e. there is
no “undo”).
cur.execute(
'
DROP TABLE IF EXISTS Tracks
'
)
The second command creates a table named
Tracks
with a text column named
title
and an integer column named
plays
.
cur.execute(
'
CREATE TABLE Tracks (title TEXT, plays INTEGER)
'
)
Now that we have created a table named
Tracks
,we can put some data into that
table using the SQL
INSERT
operation. Again, we begin by making a connection
to the database and obtaining the
cursor
. We can then execute SQL commands
using the cursor.
The SQL
INSERT
command indicates which table we are using and then definesa
new row by listing the fields we want to include
(title, plays)
followed by
the
VALUES
we want placed in the newrowin the table. We specify the values as
question marks
(?, ?)
to indicate thatthe actual valuesare passed in asa tuple
(
’My Way’, 15 )
as the second parameter to the
execute()
call.
import sqlite3
conn = sqlite3.connect(
'
music.db
'
)
cur = conn.cursor()
cur.execute(
'
INSERT INTO Tracks (title, plays) VALUES ( ?, ? )
'
,
(
'
Thunderstruck
'
, 20 ) )
cur.execute(
'
INSERT INTO Tracks (title, plays) VALUES ( ?, ? )
'
,
(
'
My Way
'
, 15 ) )
conn.commit()
print
'
Tracks:
'
cur.execute(
'
SELECT title, plays FROM Tracks
'
)
for row in cur :
print row
cur.execute(
'
DELETE FROM Tracks WHERE plays < 100
'
)
conn.commit()
14.5. StructuredQuery Language (SQL)summary
165
cur.close()
Firstwe
INSERT
two rowsinto ourtable and use
commit()
to force the data to be
written to the database file.
Friends
title
Thunderstruck
My Way
20
15
plays
Then we use the
SELECT
command to retrieve the rows we just inserted from
the table. On the
SELECT
command, we indicate which columns we would like
(title, plays)
andindicatewhich table wewanttoretrievethedatafrom. After
we execute the
SELECT
statement,the cursoris something we canloop through in
a
for
statement. For efficiency, the cursor does not read all of the data from the
database when we execute the
SELECT
statement. Instead, the data is read on-
demand aswe loop throughthe rowsin the
for
statement.
The output of the program isasfollows:
Tracks:
(u
'
Thunderstruck
'
, 20)
(u
'
My Way
'
, 15)
Our
for
loop findstworows,andeachrowisa Pythontuple with the first value as
the
title
and the secondvalue asthenumberof
plays
.Do notbeconcernedthat
the title strings are shown starting with
u’
. This is an indication that the strings
are Unicode stringsthat are capable ofstoring non-Latin charactersets.
At the very end of the program, we execute an SQL command to
DELETE
the
rows we have just created so we can run the program overand over. The
DELETE
command shows the use of a
WHERE
clause that allows us to express a selection
criterion so that we can ask the database to apply the command to only the rows
that match the criterion. In this example the criterion happens to apply to all the
rows so we empty the table out so we can run the program repeatedly. After the
DELETE
is performed we also call
commit()
to force the data to be removed from
the database.
14.5 Structured Query Language (SQL) summary
Sofar,wehavebeen usingthe StructuredQuery Language inourPython examples
and have covered many of the basics of the SQL commands. In this section, we
lookat the SQLlanguage in particular and give an overviewofSQL syntax.
Since there are so many different database vendors, the Structured Query Lan-
guage (SQL)was standardized so we could communicate in a portable manner to
database systemsfrom multiple vendors.
166
Chapter 14. Using databasesand Structured Query Language (SQL)
Arelational database is made up of tables, rows, and columns. The columns
generally have a type such as text, numeric,or date data. When we create a table,
we indicate the namesand typesofthe columns:
CREATE TABLE Tracks (title TEXT, plays INTEGER)
To insert a row into a table,we use the SQL
INSERT
command:
INSERT INTO Tracks (title, plays) VALUES (
'
My Way
'
, 15)
The
INSERT
statement specifies the table name, and then a list of the
fields/columns that you would like to set in the new row, and then the keyword
VALUES
and thena list of corresponding valuesfor each of the fields.
The SQL
SELECT
command isused toretrieve rowsandcolumnsfrom a database.
The
SELECT
statement lets you specify which columnsyou would like to retrieve
aswellasa
WHERE
clause toselectwhichrowsyouwouldliketo see. Italso allows
an optional
ORDER BY
clause to controlthe sorting of the returned rows.
SELECT * FROM Tracks WHERE title =
'
My Way
'
Using
*
indicatesthat you want the database to return all of the columns for each
rowthatmatches the
WHERE
clause.
Note, unlike in Python, in a SQL
WHERE
clause we use a single equal sign to
indicateatestforequalityratherthana doubleequalsign. Otherlogicaloperations
allowed in a
WHERE
clause include
<
,
>
,
<=
,
>=
,
!=
,as well as
AND
and
OR
and
parenthesestobuild yourlogicalexpressions.
You can request that the returned rowsbe sorted by one ofthe fields as follows:
SELECT title,plays FROM Tracks ORDER BY title
To remove a row, you need a
WHERE
clause on an SQL
DELETE
statement. The
WHERE
clause determineswhich rowsare to be deleted:
DELETE FROM Tracks WHERE title =
'
My Way
'
It is possible to
UPDATE
acolumn or columns within one or more rows in a table
using the SQL
UPDATE
statementasfollows:
UPDATE Tracks SET plays = 16 WHERE title =
'
My Way
'
The
UPDATE
statementspecifiesa table andthena listoffieldsandvaluestochange
afterthe
SET
keywordand then an optional
WHERE
clause toselectthe rowsthatare
to be updated. A single
UPDATE
statement will change all of the rows that match
the
WHERE
clause,orif a
WHERE
clause is not specified, itperforms the
UPDATE
on
all of the rowsin the table.
These four basic SQL commands (INSERT, SELECT, UPDATE, and DELETE)
allow the four basic operations neededtocreate and maintain data.
Documents you may be interested
Documents you may be interested