Store images on Flickr using Flickrnet.dll and ASP.NET MVC

Filed in ASP.NET MVC | C# 3 Comments

For one of my recent projects I had to use Flickr as an image repository, so this code just shows how I was able to do that with the help of the fantastic Flickrnet.dll library. You can download the latest Flickrnet library here: http://flickrnet.codeplex.com/. You can also download the article’s full working Flickr demo code.

Getting Started

Before we dive into the MVC portion, you have to make sure you have installed the flickrnet.dll file, referenced it, and added the appropriate web.config elements.

configSections element

Append the following element after the default sectionGroup:
<section name="flickrNet" type="FlickrNet.FlickrConfigurationManager,FlickrNet"/>

And setup your database connection strings

Flickrnet element

Add the following element before the appSettings element:
<flickrNet apiKey="YOUR_API_KEY" secret="YOUR_SECRET" cacheDisabled="true"/>

appSettings element

Add the following keys to the appSettings element:

<add key="FlickrAuthtoken" value="YOUR_FROB/TOKEN" />
<add key="FlickrUserId" value="YOUR_USERID"/>


Click on the thumbnail for a larger view


That is all you need to do in web.config. You get your apikey and secret through flickr. An awesome article off the flickrnet.codeplex site covers how to get your FROB/Token: http://blogs.msdn.com/coding4fun/archive/2006/11/22/1126978.aspx.

Database Setup

The images are going to be uploaded to Flickr, but we are going to keep references to the images in the database for later retrieval. Here is the table script if you are using MySQL:

CREATE TABLE  `sampledb`.`Image` (
  `ImageID` int(11) NOT NULL AUTO_INCREMENT,
  `ImageURL` varchar(250) DEFAULT NULL,
  `Tags` varchar(150) DEFAULT NULL,
  `FlickrID` varchar(50) DEFAULT NULL,
  `ImageURLThumbnail` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`ImageID`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;

or if you are using SQL Server:

CREATE TABLE  [SampleDB].[dbo].[Image] (
  ImageID int NOT NULL IDENTITY,
  ImageURL varchar(250) DEFAULT NULL,
  Tags varchar(150) DEFAULT NULL,
  FlickrID varchar(50) DEFAULT NULL,
  ImageURLThumbnail varchar(250) DEFAULT NULL,
  PRIMARY KEY (ImageID)
);

Once the database is setup, all we have left is the code for uploading, storing, and retrieving the images.

Uploading Images into Flickr

This part is easier than you think. We start out with a typical upload form. For this sample we are going to only have a file input control and a textbox to store our tags:

<form method="post" enctype="multipart/form-data" id="form1" action="/Home/Index">
        <b>Image</b><br />
        <input type="file" name="NewImageName" id="NewImageName" />
        <br /><br />
        <b>Tags</b><br />
        <input type="text" name="NewImgTags" id="NewImgTags" />
        <br />
        <input type="submit" value="Upload" />
    </form>

Nothing controversial there, moving on to the controller is where we find the meat. The first thing the controller needs is a reference to the Flirckrnet.dll and to System.Configuration, so you add your using statements:

using FlickrNet;
using System.Configuration;

Next up is creating the Index post method. Here, we reference the Flickrnet object and upload the photo. At this point, Flickr takes the image, and depending upon the size and dimensions, will resize it into any of five different sizes: square, thumbnail, small, medium, and large.

We then loop through the different sizes Flickr sends back, and store the thumbnail and large image urls into our table. Below is part of the controller method that uploads the image, and then loops through the sizes. You can download a full working sample here.

var flickr = new Flickr
{
    AuthToken = ConfigurationManager.AppSettings["FlickrAuthtoken"]
};

//
//  Upload the image, title, tags, security settings
//
var flickr_id = flickr.UploadPicture(file.InputStream, ImageTitle, ImageDescription, ImageTags, IsPublic,IsFamily,IsFriends);

//
//  Loop through links to resized images up on flickr
//  and store in the database
//
var flickrPhotos = flickr.PhotosGetSizes(flickr_id);

Image newImage = new Image();
newImage.FlickrID = flickr_id.ToString();

//
//  I only care about the thumbnail and the large image, but
//  you can store all of them (when applicable)
//
for (int i = 0; i < flickrPhotos.SizeCollection.Length; i++)
{
    switch (flickrPhotos.SizeCollection[i].Label)
    {
        case "Square":
            break;
        case "Thumbnail":
            newImage.ImageURLThumbnail = flickrPhotos.SizeCollection[i].Source;
             break;
        case "Small":
             break;
        case "Medium":
             break;
        case "Large":
             newImage.ImageURL = flickrPhotos.SizeCollection[i].Source;
             ViewData["NewUrl"] = flickrPhotos.SizeCollection[i].Source;
             break;
    }
}

newImage.Tags = ImageTags;
newImage.CreateAndFlush();

The code sample then sends the large image url from Flickr back down to the browser to preview. Below is a video of the code in action:

, ,

Autocomplete using Html, JSON, MVC, jQuery

Filed in ASP.NET MVC | C# | jquery 6 Comments

I found an awesome AutoComplete tutorial (here: http://www.nodstrum.com/2007/09/19/autocompleter/#comment) using PHP, jQuery, MySQL, and decided to port it over to Microsoft’s ASP.NET MVC. Turned out to be way easier than I thought! You can download the auto-complete code sample here.

Configure MVC Controller

So this is basic: create a JsonResult method in your controller that runs a query. I’m using nHibernate and ActiveRecord to perform a top 10 query as you can see here:

public JsonResult GetCountry(string searchString)
{
StringBuilder sb = new StringBuilder();
ICriterion[] query = { Expression.Eq("Code", "COUNTRYLIST"), Expression.Like("Value",searchString, MatchMode.Start) };
LookupCode[] countries = LookupCode.SlicedFindAll(0, 10, query);
for (int i = 0; i < countries.Length; i++)
{
sb.Append("<li onClick=\"fill('" + countries[i].Value + "');\">" + countries[i].Description + "</li>");
}
return Json(sb.ToString());
}

Create jQuery Function

There are two jQuery functions we need. The first function simply calls the GetCountry method:

function lookup(inputString) {
$.post("/LookupCode/GetCountry", { searchString: "" + inputString + ""},
function(data) {
var myObject = eval('(' + data + ')');
if (data.length > 0) {
$("#suggestions").show();
$( "#autoSuggestionsList").html('<ul>' + myObject + '</ul>');
}
});
}

The second method is called from the auto-suggest list, and its job is to populate the selected value into the form field and to hide the auto-suggest list:

function fill(thisValue) {
$("#Country").val(thisValue);
setTimeout("$("#suggestions").hide();", 200);
}

Prep Textbox

There are two things we need to do to configure the textbox to trigger the auto-complete functionality:

1. Add the onkeyup=”lookup(this.value);” attribute within the input:

<input type="text" name="Country" id="Country"  onkeyup="lookup(this.value);"  />

2. Add a DIV to hold the suggestion list:

<div class="suggestionsBox" id="suggestions" style="display: none;">
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>

That’s it! For extra credit, we can add some style in the next step.

Add Style

The following style was taken and modified from the original tutorial (here: http://www.nodstrum.com/2007/09/19/autocompleter/#comment) , and is really easy to customize:

.suggestionsBox {
position: relative;
left: 5px;
margin: 10px 0px 0px 0px;
width: 200px;
background-color: #e4e4e4;
-moz-border-radius: 7px;
-webkit-border-radius: 7px;
border: 2px solid #336699;
color:#333333;
}

.suggestionList {
margin: 0px;
padding: 0px;
}

.suggestionList ul {
margin: 0px;
padding: 0px;
}

.suggestionList li {
list-style-type: none;
margin: 0px 0px 0px 0px;
padding: 3px;
cursor: pointer;
}

.suggestionList li:hover {
list-style-type: none;
color:White;
background-color: #336699;
}
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 106px; width: 1px; height: 1px;">function lookup(inputString,prefix) {
if (inputString.length == 0) {
$('#suggestions').hide();
} else {
$.post("/LookupCode/GetCountry", { id: "" + inputString + "", prefix: prefix },
function(data) {

var myObject = eval('(' + data + ')');
var suggestlist = "#" + prefix + "autoSuggestionsList";
var suggestfield = "#" + prefix + "suggestions";

if (data.length > 0) {

$(suggestfield).show();
$(suggestlist).html('<ul>' + myObject + '</ul>');
}
});
}
}
</div>

, , , , , ,

How to implement paging with c#, mvc, nHibernate, ICriterion

Filed in ASP.NET MVC | C# | NHibernate Leave a comment

There is a really cool jQuery tool (http://tablesorter.com/docs/index.html) that uses PFM Technology (Pure Freakin’ Magic) to make your html table just magically page and sort. It works great with MVC and nHibernate, but I wanted to get fancy and make my own. Turned out to be surprisingly easy. Here’s what I did:

Preparing the Controller

1. Create you search criteria:

ICriterion[] query = { Expression.Eq(FieldName, FieldValue) };

2. Get the total record count matching the criteria without actually pulling back all the records. I throw the count into a ViewData variable for later processing on the page:

int count = ActiveRecordMediator<listing>.Count(query);
ViewData["count"] = count;

3. Execute a SlicedFindAll search to only get the subset instead of the entire recordset.

Contact[] pagedContacts = Contact.SlicedFindAll((currentPageIndex) * Rows), Rows, query);

The currentPageIndex variable is passed in from the page. At this point, the controller is ready!

Preparing the View

1. First we will create links to the individual pages. This is also where we use the ViewData["count"] value:

int TotalListings = int.Parse(ViewData["count"].ToString());
int RecordsPerPage = 15;    // <-- this can be defined anywhere, I wired it for this demo
int TotalPages = (TotalListings + RecordsPerPage - 1) / RecordsPerPage;

StringBuilder sb = new StringBuilder();
if (TotalPages > 1)
{
for (int i = 0; i < TotalPages; i++)
{
sb.Append("<a href='/your-url-path/" + i.ToString() + "'>" + (i + 1).ToString() + "</a>&nbsp;&nbsp;");
}

Response.Write(sb.ToString());
}

2. Loop through your recordset, adding your rows.

3. Add an optional footer:

if (TotalPages > 1)
{
Response.Write(sb.ToString());
}

That’s it! This could easily be extended to include next, previous, etc. links, but for demo purposes this works well.

, ,

TOP