65.9K
CodeProject 正在变化。 阅读更多。
Home

一个简单的 ASP.NET Flickr 应用程序

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.91/5 (13投票s)

2010年11月14日

CPOL

6分钟阅读

viewsIcon

77284

downloadIcon

2395

一个使用 Flickr.Net API 库和一些炫酷效果的简单 Flickr 应用程序。

引言

首先,我要感谢 Sam Judson 创造了一个非常有用的项目并与我们分享。没有他的努力,这篇文章会更长、更乏味。因此,感谢他和参与该项目的其他人。所有项目详情和下载都可以在此地址找到:http://flickrnet.codeplex.com/

我还使用了适用于 jQuery 1.3 和 1.4 的轻量级、可定制的灯箱插件 ColorBox,用于在图像预览上添加漂亮的效果。ColorBox 由 Jack Moore 编写,也感谢他;您可以在这里找到更多详细信息:http://colorpowered.com/colorbox/。我使用的版本是 1.3.3,但如果您愿意,可以使用最新版本更新您的项目。有关版本历史的更多详细信息可以在这里获取:http://colorpowered.com/colorbox/core/README

为了使用 Flickr API,另一个必不可少的事情是创建您自己的 API 密钥和密钥。如果您已经有一个 Yahoo! 帐户,那会很简单;否则,您应该创建一个。在这两种情况下,您都可以从这里开始:http://www.flickr.com/services/api/keys/。有关 Flick API 的更多详细信息,请访问:http://www.flickr.com/services/api/

请注意,示例应用程序中使用的 API 密钥和密钥是伪造的,它们无法工作。执行应用程序时您将收到错误消息。因此,您应该在 web.config 中将它们更改为您从 Flicker 获取的数据!(您还没有创建自己的密钥?不好不好,去 http://www.flickr.com/services/api/keys/。)

入门

首先创建一个空的 ASP.NET 网站。我使用了 Visual Studio 2010 Ultimate,但使用 Visual Studio Express 也可以完成同样的事情,就像使用 Visual Studio 2008 或 2005 等以前的版本一样。

使用代码

让我们写一些代码。在您的项目中添加一个 ASP.NET 文件夹 App_Code 并创建一个新类,命名为 FlickrBLL。这是要添加的代码

using System;
using System.ComponentModel;
using System.Configuration;
using FlickrNet;

namespace Infrastructure.BLL
{
    /// <summary>
    /// Helper class for confortable pagining and binding
    /// </summary>
    [DataObject(true)]
    public class FlickrBLL
    {
        [DataObjectMethodAttribute(DataObjectMethodType.Select, true)]
        public static PhotosetPhotoCollection GetPagedSet(string setId, 
                      int maximumRows, int startRowIndex)
        {
            Flickr flickr = new Flickr(ConfigurationManager.AppSettings["apiKey"],
                ConfigurationManager.AppSettings["shardSecret"]);
            PhotosetPhotoCollection photos = flickr.PhotosetsGetPhotos(setId, GetPageIndex(
                startRowIndex, maximumRows) + 1, maximumRows);

            return photos;
        }

        public static int GetPagedSetCount(string setId)
        {
            Flickr flickr = new Flickr(ConfigurationManager.AppSettings["apiKey"],
                ConfigurationManager.AppSettings["shardSecret"]);
            Photoset set = flickr.PhotosetsGetInfo(setId);
            return set.NumberOfPhotos;
        }

        [DataObjectMethodAttribute(DataObjectMethodType.Select, false)]
        public static PhotosetCollection GetPhotoSetsByUser(string userId)
        {
            Flickr flickr = new Flickr(ConfigurationManager.AppSettings["apiKey"],
                ConfigurationManager.AppSettings["shardSecret"]);

            return flickr.PhotosetsGetList(userId);
        }

        protected static int GetPageIndex(int startRowIndex, int maximumRows)
        {
            if (maximumRows <= 0)
                return 0;
            else
                return (int)Math.Floor((double)startRowIndex / (double)maximumRows);
        }
    }
}

让我们分析其中一些方法。

Flickr.Net 库方法 PhotosetsGetPhotos 期望页索引,而不是要检索的第一条记录的索引,因此我创建了 GetPageIndex 辅助方法进行转换。

方法 GetPhotoSetsByUser 返回 PhotosetsGetList 的结果。请注意,此函数不期望 Flickr 用户名作为参数,而是用户 ID。您可以使用集成到 Flicker.Net API 中的其他方法或使用 http://www.xflickr.com/fusr/ 等网站检索此数据。

不要被 GetPagedSet 方法属性吓到。ObjectDataSource 控件和 ObjectDataSourceDesigner 类等组件会检查此属性的值(如果存在),以帮助确定在运行时调用哪个数据方法。这不是必需的,但它简化了工作。相同的属性用于指示此类别是数据对象([DataObject(true)])。我决定在此示例中使用分页,这很简单,因为 API 已经提供了此功能。该方法只是调用 Flicker.Net 库中可用的 PhotosetsGetPhotos,并使用适当的重载。

分页所需的 Count 方法使用 GetPagedSetCount,它获取请求的集合信息并返回集合中的项目数。

web.config

为了获取身份验证数据和其他可能变化的参数,我们需要在 web.config 中创建一个 appSettings 部分。

<appSettings>
  <add key="apiKey" value="6370a3f6c4f1c031afd636247a648385"/>
  <add key="shardSecret" value="42cf8c1g85e6d3b2"/>
  <add key="defaultUser" value="10734446@N06"/>
  <add key="defaultPageSize" value="44"/>
</appSettings>

apiKeysharedSecret 是虚拟值。您需要注册并替换它们以获得完整功能,但您仍然可以使用默认用户和默认页面大小。如果您使用不同的布局,可以通过简单地更改此值来更改每页显示的照片数量。

构建页面

向您的项目添加一个新网页表单并在其中放置一个 DropDownList。之后,在页面中放置一个 ObjectDataSource 控件。对于此 ObjectDataSource 控件,您可以使用设计器和智能任务来加快速度。

<p>
    List of default user sets:
    <br />
    <asp:DropDownList ID="ddlSets" runat="server" 
        AutoPostBack="True" DataSourceID="odsSets"
        DataTextField="Title" DataValueField="PhotosetId" 
        Height="21px" Width="450px"
        OnSelectedIndexChanged="ddlSets_SelectedIndexChanged">
    </asp:DropDownList>
</p>
<asp:ObjectDataSource ID="odsSets" runat="server" 
        OldValuesParameterFormatString="original_{0}"
        OnSelecting="odsSets_Selecting" 
        SelectMethod="GetPhotoSetsByUser" 
        TypeName="Infrastructure.BLL.FlickrBLL">
    <SelectParameters>
        <asp:Parameter Name="userId" Type="String" />
    </SelectParameters>
</asp:ObjectDataSource> 

如您所见,我们的方法期望一个值,以便它可以正确检索数据。由于我们的用户 ID 存储在 web.config 中,这是传递请求参数的方法

protected void odsSets_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
   e.InputParameters["userId"] = ConfigurationManager.AppSettings["defaultUser"].ToString();
}

拦截 Selecting 事件并手动设置预期参数。我从 web.config 获取它;您可以选择任何其他方式,例如:在页面中使用另一个控件(如果您创建用户搜索)。如果您没有经验,您可能想知道我如何获得 DataTextFieldDataValueField 值。很简单,它们是 Photoset 类的属性,PhotosetPhotosetCollection 的一个元素,PhotosetCollection 是我们调用方法返回类型。要探索其他属性,请创建 Photoset 类的实例,选择它,然后按 F12。

现在我将添加一个 ListView 控件,以列出我的查询结果数据。

<asp:ListView ID="lvImages" runat="server" DataSourceID="odsPhotos">
    <EmptyDataTemplate>
        <span>No data was returned.</span>
    </EmptyDataTemplate>
    <ItemTemplate>
        <a href="<%# Eval("MediumUrl") %>" rel="images" title="<%# Eval("Title") %>">
            <img alt="" src="<%# Eval("SquareThumbnailUrl") %>" />
	</a> 
	</ItemTemplate>
    <LayoutTemplate>
        <div id="itemPlaceholderContainer" runat="server" style="">
            <span runat="server" id="itemPlaceholder" />
        </div>
            <asp:DataPager ID="DataPager1" runat="server" PageSize="<%$ appSettings:defaultPageSize %>">
                <Fields>
                    <asp:NextPreviousPagerField ButtonType="Image" ShowFirstPageButton="true" ShowNextPageButton="false"
                        ShowPreviousPageButton="true" FirstPageImageUrl="~/images/first.gif" PreviousPageImageUrl="~/images/previous.gif" />
                    <asp:TemplatePagerField>
                        <PagerTemplate>
                            Page
                            <asp:Label runat="server" ID="labelCurrentPage" 
		Text="<%# Container.TotalRowCount > 0 ? (Container.StartRowIndex / Container.PageSize) + 1 : 0 %>" />
                            of
                            <asp:Label runat="server" ID="labelTotalPages" 
                Text="<%#  Math.Ceiling ((double)Container.TotalRowCount / Container.PageSize) %>" />
                        </PagerTemplate>
                    </asp:TemplatePagerField>
                    <asp:NextPreviousPagerField ButtonType="Image" ShowLastPageButton="true" ShowNextPageButton="true"
                        ShowPreviousPageButton="false" LastPageImageUrl="~/images/last.gif" NextPageImageUrl="~/images/next.gif" />
                    <asp:TemplatePagerField>
                        <PagerTemplate>
                            <br />
                            Total Pictures in this set:
                            <asp:Label runat="server" ID="labelTotalPictures" Text="<%#  (double)Container.TotalRowCount %>" />
                        </PagerTemplate>
                    </asp:TemplatePagerField>
                </Fields>
            </asp:DataPager>
    </LayoutTemplate>
</asp:ListView>

请注意,我指定了一个非常简单的 ItemTemplate;代码不言自明。需要注意的重要一点是,在布局模板中,有一个 DataPager 控件。当 DataPagerListView 控件内部时,无需设置 DataPagerPagedControlID。容器 ListView 会自动关联为分页控件。

显然,这在没有数据源的情况下无法工作,所以我们来吧,一个 ObjectDataSource 已准备就绪。

<asp:ObjectDataSource ID="odsPhotos" runat="server" 
        EnablePaging="True" OldValuesParameterFormatString="original_{0}"
        SelectCountMethod="GetPagedSetCount" 
        SelectMethod="GetPagedSet" TypeName="Infrastructure.BLL.FlickrBLL"
        OnSelecting="odsPhotos_Selecting">
    <SelectParameters>
        <asp:ControlParameter ControlID="ddlSets" 
            DefaultValue="0" Name="setId" PropertyName="SelectedValue"
            Type="String" />
    </SelectParameters>
</asp:ObjectDataSource>

您可以使用设计器和智能任务,但请注意,引导式过程将添加用于分页的参数,并且应用程序将无法正常工作。查看启用分页和计数方法的属性。

现在我们需要设置最大行属性,但由于此属性在 web.config 中指定,我们将通过代码完成它。

protected void odsPhotos_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
   e.Arguments.MaximumRows = 
     int.Parse(ConfigurationManager.AppSettings["defaultPageSize"]);
}

差不多就是这样了,但还有一些小问题,比如查看集合的第二页然后更改集合,设置一个只有一页的集合。遗憾的是,更简单地说,每次集合更改时,我们都需要重置页面计数器。

protected void ddlSets_SelectedIndexChanged(object sender, EventArgs e)
{
    DataPager pgr = lvImages.FindControl("DataPager1") as DataPager;
    if (pgr != null && lvImages.Items.Count != pgr.TotalRowCount)
    {
        pgr.SetPageProperties(0, pgr.MaximumRows, false);
    }
}

现在,就是这样,一切都应该完美运行!

AJAX化

让我们摆脱回发。在页面上添加一个 ScriptManager 并进行以下更改

用以下代码围绕 ListView

<asp:UpdatePanel ID="upImages" 
              runat="server" style="text-align: center;">
    <ContentTemplate>
        // my list view
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="ddlSets" />
    </Triggers>
</asp:UpdatePanel>

由于 DropDownListListView 之外,我们需要指出即使该控件也触发回发,并且应该妥善管理。再简单不过了!

修饰

我之前说过我们将使用一个名为 Colorbox 的灯箱插件。所以让我们设置它。首先,将所有随此插件提供的图像放入 images 目录,然后对 CSS 样式执行相同的操作。打开您刚刚复制的 CSS 文件,并检查图像路径。注意有关 IE 解决方法和相关路径的注释。将必要的脚本复制到脚本文件夹,然后准备一些代码。我们应该链接我们的脚本和 CSS 文件,所以在页面头部,添加以下内容

<link href="Styles/colorbox.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.colorbox-min.js"></script>

完成之后,我们需要创建 Colorbox 的实例才能使其工作。由于在通过 UpdatePanel 进行回调后 JavaScript 不再“绑定”,我们需要重新初始化我们的 Colorbox。

<script type="text/javascript">
        $(document).ready(function () {
            $("a[rel='images']").colorbox({ transition: "fade" });
        });

        function pageLoad(sender, args) {
            if (args.get_isPartialLoad()) {
                $("a[rel='images']").colorbox({ transition: "fade" });
            }
        }
</script>

有关灯箱以及如何从这个实用的插件中获得更多信息,请参阅 Colorbox 网页。

结果

最后,通过使用 VS2010 自动创建的样式,结果如下

FlickrPreview1.jpg

这是更详细的视图

FlickrPreview2.jpg

注释

演示中 Flickr 的默认用户实际上是一个活跃且非常不错的 Flickr 个人资料。这是我朋友的个人资料,mind_in_motion,所以如果您喜欢漂亮的照片,请查看一下。谢谢 Jean Claude!这是我在 CodeProject 上的第一篇文章,所以请手下留情!我将尽力回答您的所有问题,如果_有_的话。

编程愉快!

© . All rights reserved.