homesupportsave into a local database via asp.net + sql express [tutorial]

configuration

this is where the application is configured you will need to use your own unique feed and database settings:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.data.sqlclient;
using sampleclientlibrary;

namespace sampledatabasecreatorandupdater
{
class program
{
#region feed configuration
private const string apikey = ""; //insert api key into variable
private const string baseurl = ""; //insert baseurl into variable
#endregion

#region database configuration
private const string dbhost = "localhost\\sqlexpress";
private const string dbname = "dbsimple";
private const string dbuser = "dnapp";
private const string dbpass = "ppand";
private const string dbtablename = "newsarticles";
private const string dbtableidentifier = "[" + dbname + "].[dbo].[" + dbtablename + "]";

private static string dbconnectionstring = "data source=" + dbhost +
";user id=" + dbuser + ";password=" + dbpass + ";";
private static sqlconnection dbconnection = new sqlconnection(dbconnectionstring);
#endregion

[jump to top]

main method

this is the main thread from which the application is executed from here we check if the database name already exists on the sql server and if not to run the create database method. following this we use the sample api to return a collection of news items for the feed and pass them to the update database method.

static void main(string[] args)
{
dbconnection.open();

//check if database already exists
string query = "select * from master.dbo.sysdatabases where name='" + dbname + "'";
bool databaseexists = (new sqlcommand { commandtext = query, connection = dbconnection }.executescalar() == null) ? false : true;

//only create database if it doesn't exist
if (!databaseexists)
{
createdatabase();
}

apicontext ac = new apicontext(apikey, baseurl); //create a new feed object using the api_key
ienumerable newslist = ac.news; //return an array of the latest news items from your feed in html format

updatedatabase(newslist);//update news items to database

dbconnection.close(); //close database connection

console.writeline("operation completed \n press any key to continue...");
console.readkey();
}

[jump to top]

database initialization

this method is executed if the specified database name does not exist and creates the required news articles table as well.

///


/// creates the database and the required table
///


private static void createdatabase()
{
//create database
string query = "create database " + dbname;
sqlcommand dbcommand = new sqlcommand(query, dbconnection);

dbcommand.executenonquery();

//create a news articles table in the database
dbcommand.commandtext = "create table " + dbtableidentifier + "(" +
"[id] int not null," +
"[headline] varchar(255) not null, " +
"[text] text not null, " +
"[publisheddate] datetime not null, " +
"[photourl] text null, " +
"primary key ([id]));";
dbcommand.parameters.add(new sqlparameter("@dbtablename", dbtablename));

dbcommand.executenonquery();
}

[jump to top]

database update

the updatedatabse method recieves a collection of newslist objects and persists them to the database only if the respectice id does not already exist in the database. parameters are used to ensure all unsafe characters are escaped for the query string.

///


/// database update method, takes a list of newsitems and inserts each newsitem into the
/// database on the condition it doesn't exist already
///


private static void updatedatabase(ienumerable newslist)
{
foreach (newsitem n in newslist)
{
sqlcommand dbcommand = new sqlcommand { connection = dbconnection };

dbcommand.parameters.add(new sqlparameter("@id", n.id));
dbcommand.parameters.add(new sqlparameter("@headline", n.headline));
dbcommand.parameters.add(new sqlparameter("@text", n.text));
dbcommand.parameters.add(new sqlparameter("@publishdate", n.publishdate));

//process photo select default photo and return largeurl for it
object photourl = dbnull.value;
photo newsphotos = n.photos.firstordefault();
if (newsphotos != null)
{
photo.instance largephoto = newsphotos.instances.where(x => x.type == enumeratedtypes.enumphotoinstancetype.large).firstordefault();
if (largephoto != null) photourl = largephoto.url;
}
dbcommand.parameters.add(new sqlparameter("@photourl", photourl));

//insert article into database, but ignore it if it already exists
string query = "if not exists (select * from " + dbtableidentifier + " where id = @id)" +
"insert into " + dbtableidentifier +
" values(@id, @headline, @text, @publishdate, @photourl)";
dbcommand.commandtext = query;
dbcommand.executenonquery();
}
}
}
}

[jump to top]