libflickrnet-48055~2.2.0/FlickrNet/0000755000175000017500000000000011155417352015724 5ustar varunvarunlibflickrnet-48055~2.2.0/FlickrNet/Cache.cs0000644000175000017500000002306011155417352017257 0ustar varunvarunusing System; using System.Collections; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace FlickrNet { /// /// Internal Cache class /// internal sealed class Cache { private class CacheException : Exception { public CacheException(string message) : base(message) {} } private static PersistentCache _downloads; /// /// A static object containing the list of cached downloaded files. /// public static PersistentCache Downloads { get { lock(lockObject) { if( _downloads == null ) _downloads = new PersistentCache(Path.Combine(CacheLocation, "downloadCache.dat"), new PictureCacheItemPersister(), CacheSizeLimit); return _downloads; } } } private static PersistentCache _responses; /// /// A static object containing the list of cached responses from Flickr. /// public static PersistentCache Responses { get { lock(lockObject) { if( _responses == null ) _responses = new PersistentCache(Path.Combine(CacheLocation, "responseCache.dat"), new ResponseCacheItemPersister(), CacheSizeLimit); return _responses; } } } private Cache() { } private static object lockObject = new object(); private enum Tristate { Null, True, False } private static Tristate _cacheDisabled; internal static bool CacheDisabled { get { #if !WindowsCE if( _cacheDisabled == Tristate.Null && FlickrConfigurationManager.Settings != null ) _cacheDisabled = (FlickrConfigurationManager.Settings.CacheDisabled?Tristate.True:Tristate.False); #endif if( _cacheDisabled == Tristate.Null ) _cacheDisabled = Tristate.False; return (_cacheDisabled==Tristate.True); } set { _cacheDisabled = value?Tristate.True:Tristate.False; } } private static string _cacheLocation; internal static string CacheLocation { get { #if !WindowsCE if( _cacheLocation == null && FlickrConfigurationManager.Settings != null ) _cacheLocation = FlickrConfigurationManager.Settings.CacheLocation; #endif if( _cacheLocation == null ) { try { #if !WindowsCE _cacheLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FlickrNet"); #else _cacheLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "FlickrNetCache"); #endif } catch(System.Security.SecurityException) { // Permission to read application directory not provided. throw new CacheException("Unable to read default cache location. Please cacheLocation in configuration file or set manually in code"); } } if( _cacheLocation == null ) throw new CacheException("Unable to determine cache location. Please set cacheLocation in configuration file or set manually in code"); return _cacheLocation; } set { _cacheLocation = value; } } // Default cache size is set to 50MB private static long _cacheSizeLimit = 52428800; private static long _cacheSize; internal static long CacheSizeLimit { get { return _cacheSizeLimit; } set { _cacheSizeLimit = value; } } internal static long CacheSize { get { return _cacheSize; } set { _cacheSize = value; } } // Default cache timeout is 1 hour private static TimeSpan _cachetimeout = new TimeSpan(0, 1, 0, 0, 0); /// /// The default timeout for cachable objects within the cache. /// public static TimeSpan CacheTimeout { get { return _cachetimeout; } set { _cachetimeout = value; } } internal static void FlushCache(string url) { Responses[url] = null; Downloads[url] = null; } internal static void FlushCache() { Responses.Flush(); Downloads.Flush(); } } /// /// A cache item containing details of a REST response from Flickr. /// [Serializable] public class ResponseCacheItem : ICacheItem { private string url; private string response; private DateTime creationTime; /// /// Gets or sets the original URL of the request. /// public string Url { get { return url; } set { url = value; } } /// /// Gets or sets the XML response. /// public string Response { get { return response; } set { response = value; } } /// /// Gets or sets the time the cache item was created. /// public DateTime CreationTime { get { return creationTime; } set { creationTime = value; } } /// /// Gets the filesize of the request. /// public long FileSize { get { return (response==null?0:response.Length); } } void ICacheItem.OnItemFlushed() { } } internal class ResponseCacheItemPersister : CacheItemPersister { public override ICacheItem Read(Stream inputStream) { string s = Utils.ReadString(inputStream); string response = Utils.ReadString(inputStream); string[] chunks = s.Split('\n'); // Corrupted cache record, so throw IOException which is then handled and returns partial cache. if( chunks.Length != 2 ) throw new IOException("Unexpected number of chunks found"); string url = chunks[0]; DateTime creationTime = new DateTime(long.Parse(chunks[1])); ResponseCacheItem item = new ResponseCacheItem(); item.Url = url; item.CreationTime = creationTime; item.Response = response; return item; } public override void Write(Stream outputStream, ICacheItem cacheItem) { ResponseCacheItem item = (ResponseCacheItem) cacheItem; StringBuilder result = new StringBuilder(); result.Append(item.Url + "\n"); result.Append(item.CreationTime.Ticks.ToString("0")); Utils.WriteString(outputStream, result.ToString()); Utils.WriteString(outputStream, item.Response); } } /// /// An item that can be stored in a cache. /// public interface ICacheItem { /// /// The time this cache item was created. /// DateTime CreationTime { get; } /// /// Gets called back when the item gets flushed /// from the cache. /// void OnItemFlushed(); /// /// The size of this item, in bytes. Return 0 /// if size management is not important. /// long FileSize { get; } } /// /// An interface that knows how to read/write subclasses /// of ICacheItem. Obviously there will be a tight /// coupling between concrete implementations of ICacheItem /// and concrete implementations of ICacheItemPersister. /// public abstract class CacheItemPersister { /// /// Read a single cache item from the input stream. /// public abstract ICacheItem Read(Stream inputStream); /// /// Write a single cache item to the output stream. /// public abstract void Write(Stream outputStream, ICacheItem cacheItem); } /// /// Contains details of image held with the Flickr.Net cache. /// [Serializable] public class PictureCacheItem : ICacheItem { #region [ Internal Variables ] internal string url; internal DateTime creationTime; internal string filename; internal long fileSize; #endregion #region [ Public Properties ] /// /// The URL of the original image on Flickr. /// public string Url { get { return url; } } /// /// The that the cache item was created. /// public DateTime CreationTime { get { return creationTime; } } /// /// The filesize in bytes of the image. /// public long FileSize { get { return fileSize; } } /// /// The Flickr photo id of the image. /// public string PhotoId { get { if( url == null ) return null; else { int begin = url.LastIndexOf("/"); int end = url.IndexOf("_"); return url.Substring(begin + 1, (end - begin) - 1); } } } #endregion #region [ Public Methods ] void ICacheItem.OnItemFlushed() { File.Delete(filename); } #endregion } /// /// Persists PictureCacheItem objects. /// internal class PictureCacheItemPersister : CacheItemPersister { public override ICacheItem Read(Stream inputStream) { string s = Utils.ReadString(inputStream); string[] chunks = s.Split('\n'); string url = chunks[0]; DateTime creationTime = new DateTime(long.Parse(chunks[1])); string filename = chunks[2]; long fileSize = long.Parse(chunks[3]); PictureCacheItem pci = new PictureCacheItem(); pci.url = url; pci.creationTime = creationTime; pci.filename = filename; pci.fileSize = fileSize; return pci; } public override void Write(Stream outputStream, ICacheItem cacheItem) { PictureCacheItem pci = (PictureCacheItem) cacheItem; StringBuilder output = new StringBuilder(); output.Append(pci.url + "\n"); output.Append(pci.creationTime.Ticks + "\n"); output.Append(pci.filename + "\n"); output.Append(pci.fileSize + "\n"); Utils.WriteString(outputStream, output.ToString()); } } } libflickrnet-48055~2.2.0/FlickrNet/FlickrException.cs0000644000175000017500000000062711155417352021351 0ustar varunvarunusing System; namespace FlickrNet { /// /// Generic Flickr.Net Exception. /// [Serializable] public class FlickrException : Exception { internal FlickrException() { } internal FlickrException(string message) : base(message) { } internal FlickrException(string message, Exception innerException) : base(message, innerException) { } } } libflickrnet-48055~2.2.0/FlickrNet/FlickrNetCF.csproj0000644000175000017500000001352011155417352021241 0ustar varunvarun Debug AnyCPU 8.0.50727 2.0 {DACD45D5-ED22-4DD5-9D1D-B1706E0AD1B9} Library Properties FlickrNetCF FlickrNetCF {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} WindowsCE E2BECB1F-8C8C-41ba-B736-9BE7D946A398 5.00 FlickrNetCF v2.0 true FlickrNet.snk true full false bin\Debug\ TRACE;DEBUG;PocketPC;WindowsCE true true prompt 512 4 Off bin\Debug\FlickrNetCF.XML pdbonly true bin\Release\ TRACE;PocketPC;WindowsCE true true prompt 512 4 Off libflickrnet-48055~2.2.0/FlickrNet/PartialSearchOptions.cs0000644000175000017500000001150511155417352022353 0ustar varunvarunusing System; namespace FlickrNet { /// /// Summary description for PartialSearchOptions. /// public class PartialSearchOptions { #region Private Variables private DateTime _minUploadDate = DateTime.MinValue; private DateTime _maxUploadDate = DateTime.MinValue; private DateTime _minTakenDate = DateTime.MinValue; private DateTime _maxTakenDate = DateTime.MinValue; private PhotoSearchExtras _extras = PhotoSearchExtras.None; private PhotoSearchSortOrder _sort = PhotoSearchSortOrder.None; private int _perPage = 0; private int _page = 0; private PrivacyFilter _privacyFilter = PrivacyFilter.None; #endregion #region Public Properties /// /// Minimum date uploaded. Defaults to which /// signifies that the value is not to be used. /// public DateTime MinUploadDate { get { return _minUploadDate; } set { _minUploadDate = value; } } /// /// Maximum date uploaded. Defaults to which /// signifies that the value is not to be used. /// public DateTime MaxUploadDate { get { return _maxUploadDate; } set { _maxUploadDate = value; } } /// /// Minimum date taken. Defaults to which /// signifies that the value is not to be used. /// public DateTime MinTakenDate { get { return _minTakenDate; } set { _minTakenDate = value; } } /// /// Maximum date taken. Defaults to which /// signifies that the value is not to be used. /// public DateTime MaxTakenDate { get { return _maxTakenDate; } set { _maxTakenDate = value; } } /// /// Optional extras to return, defaults to all. See for more details. /// public PhotoSearchExtras Extras { get { return _extras; } set { _extras = value; } } /// /// Number of photos to return per page. Defaults to 100. /// public int PerPage { get { return _perPage; } set { _perPage = value; } } /// /// The page to return. Defaults to page 1. /// public int Page { get { return _page; } set { if( value < 0 ) throw new ArgumentOutOfRangeException("Page", "Must be greater than 0"); _page = value; } } /// /// The sort order of the returned list. Default is . /// public PhotoSearchSortOrder SortOrder { get { return _sort; } set { _sort = value; } } /// /// The privacy fitler to filter the search on. /// public PrivacyFilter PrivacyFilter { get { return _privacyFilter; } set { _privacyFilter = value; } } #endregion #region Constructors /// /// Default constructor. /// public PartialSearchOptions() { } /// /// Constructor taking a default parameter. /// /// See for more details. public PartialSearchOptions(PhotoSearchExtras extras) { Extras = extras; } /// /// Constructor taking a perPage and page parameter. /// /// The number of photos to return per page (maximum). /// The page number to return. public PartialSearchOptions(int perPage, int page) { PerPage = perPage; Page = page; } /// /// Constructor taking a perPage and page parameter and a default parameter. /// /// The number of photos to return per page (maximum). /// The page number to return. /// See for more details. public PartialSearchOptions(int perPage, int page, PhotoSearchExtras extras) { PerPage = perPage; Page = page; Extras = extras; } #endregion internal PartialSearchOptions(PhotoSearchOptions options) { this.Extras = options.Extras; this.MaxTakenDate = options.MaxTakenDate; this.MinTakenDate = options.MinTakenDate; this.MaxUploadDate = options.MaxUploadDate; this.MinUploadDate = options.MinUploadDate; this.Page = options.Page; this.PerPage = options.PerPage; this.PrivacyFilter = options.PrivacyFilter; } internal string ExtrasString { get { return Utils.ExtrasToString(Extras); } } internal string SortOrderString { get { return Utils.SortOrderToString(SortOrder); } } } } libflickrnet-48055~2.2.0/FlickrNet/GeoAccuracy.cs0000644000175000017500000000365411155417352020450 0ustar varunvarunusing System; using System.Xml.Serialization; namespace FlickrNet { /// /// Geo-taggin accuracy. Used in and . /// /// /// Level descriptions are only approximate. /// [Serializable] public enum GeoAccuracy { /// /// No accuracy level specified. /// [XmlEnum("0")] None = 0, /// /// World level, level 1. /// [XmlEnum("1")] World = 1, /// /// Level 2 /// [XmlEnum("2")] Level2 = 2, /// /// Level 3 - approximately Country level. /// [XmlEnum("3")] Country = 3, /// /// Level 4 /// [XmlEnum("4")] Level4 = 4, /// /// Level 5 /// [XmlEnum("5")] Level5 = 5, /// /// Level 6 - approximately Region level /// [XmlEnum("6")] Region = 6, /// /// Level 7 /// [XmlEnum("7")] Level7 = 7, /// /// Level 8 /// [XmlEnum("8")] Level8 = 8, /// /// Level 9 /// [XmlEnum("9")] Level9 = 9, /// /// Level 10 /// [XmlEnum("10")] Level10 = 10, /// /// Level 11 - approximately City level /// [XmlEnum("11")] City = 11, /// /// Level 12 /// [XmlEnum("12")] Level12 = 12, /// /// Level 13 /// [XmlEnum("13")] Level13 = 13, /// /// Level 14 /// [XmlEnum("14")] Level14 = 14, /// /// Level 15 /// [XmlEnum("15")] Level15 = 15, /// /// Street level (16) - the most accurate level and the default. /// [XmlEnum("16")] Street = 16 } } libflickrnet-48055~2.2.0/FlickrNet/SignatureRequiredException.cs0000644000175000017500000000054311155417352023576 0ustar varunvarunusing System; namespace FlickrNet { /// /// Thrown when a method requires a valid signature but no shared secret has been supplied. /// public class SignatureRequiredException : FlickrException { internal SignatureRequiredException() : base("Method requires signing but no shared secret supplied.") { } } } libflickrnet-48055~2.2.0/FlickrNet/Groups.cs0000644000175000017500000002653411155417352017544 0ustar varunvarunusing System; using System.Xml.Serialization; using System.Xml.Schema; using System.Xml; namespace FlickrNet { /// /// Provides details of a particular group. /// /// Used by and /// . [System.Serializable] public class Group { /// /// The id of the group. /// [XmlAttribute("nsid", Form=XmlSchemaForm.Unqualified)] public string GroupId; /// /// The name of the group /// [XmlAttribute("name", Form=XmlSchemaForm.Unqualified)] public string GroupName; /// /// The number of memebers of the group. /// [XmlAttribute("members", Form=XmlSchemaForm.Unqualified)] public long Members; } /// /// Provides details of a particular group. /// /// /// Used by the Url methods and method. /// The reason for a and are due to xml serialization /// incompatabilities. /// [System.Serializable] public class GroupFullInfo { internal GroupFullInfo() { } internal GroupFullInfo(XmlNode node) { if( node.Attributes.GetNamedItem("id") != null ) _groupId = node.Attributes.GetNamedItem("id").Value; if( node.SelectSingleNode("name") != null ) _groupName = node.SelectSingleNode("name").InnerText; if( node.SelectSingleNode("description") != null ) _description = node.SelectSingleNode("description").InnerXml; if (node.SelectSingleNode("iconserver") != null) _iconServer = node.SelectSingleNode("iconserver").InnerText; if (node.SelectSingleNode("members") != null) _members = int.Parse(node.SelectSingleNode("members").InnerText); if( node.SelectSingleNode("privacy") != null ) _privacy = (PoolPrivacy)int.Parse(node.SelectSingleNode("privacy").InnerText); if( node.SelectSingleNode("throttle") != null ) { XmlNode throttle = node.SelectSingleNode("throttle"); ThrottleInfo = new GroupThrottleInfo(); if( throttle.Attributes.GetNamedItem("count") != null ) ThrottleInfo.Count = int.Parse(throttle.Attributes.GetNamedItem("count").Value); if( throttle.Attributes.GetNamedItem("mode") != null ) ThrottleInfo.setMode(throttle.Attributes.GetNamedItem("mode").Value); if( throttle.Attributes.GetNamedItem("remaining") != null ) ThrottleInfo.Remaining = int.Parse(throttle.Attributes.GetNamedItem("remaining").Value); } } private string _groupId; private string _groupName; private string _description; private long _members; private string _iconServer; private PoolPrivacy _privacy; /// public string GroupId { get { return _groupId; } } /// public string GroupName { get { return _groupName; } } /// public string Description { get { return _description; } } /// public long Members { get { return _members; } } /// /// The server number used for the groups icon. /// public string IconServer { get { return _iconServer; } } /// public PoolPrivacy Privacy { get { return _privacy; } } /// public GroupThrottleInfo ThrottleInfo; /// /// Methods for automatically converting a object into /// and instance of a object. /// /// The incoming object. /// The instance. public static implicit operator Group( GroupFullInfo groupInfo ) { Group g = new Group(); g.GroupId = groupInfo.GroupId; g.GroupName = groupInfo.GroupName; g.Members = groupInfo.Members; return g; } /// /// Converts the current into an instance of the /// class. /// /// A instance. public Group ToGroup() { return (Group)this; } } /// /// Throttle information about a group (i.e. posting limit) /// public class GroupThrottleInfo { /// /// The number of posts in each period allowed to this group. /// public int Count; /// /// The posting limit mode for a group. /// public GroupThrottleMode Mode; internal void setMode(string mode) { switch(mode) { case "day": Mode = GroupThrottleMode.PerDay; break; case "week": Mode = GroupThrottleMode.PerWeek; break; case "month": Mode = GroupThrottleMode.PerMonth; break; case "ever": Mode = GroupThrottleMode.Ever; break; case "none": Mode = GroupThrottleMode.NoLimit; break; case "disabled": Mode = GroupThrottleMode.Disabled; break; default: throw new ArgumentException(string.Format("Unknown mode found {0}", mode), "mode"); } } /// /// The number of remainging posts allowed by this user. If unauthenticated then this will be zero. /// public int Remaining; } /// /// The posting limit most for a group. /// public enum GroupThrottleMode { /// /// Per day posting limit. /// PerDay, /// /// Per week posting limit. /// PerWeek, /// /// Per month posting limit. /// PerMonth, /// /// No posting limit. /// NoLimit, /// /// Posting limit is total number of photos in the group. /// Ever, /// /// Posting is disabled to this group. /// Disabled } /// /// Information about a group the authenticated user is a member of. /// public class MemberGroupInfo { internal static MemberGroupInfo[] GetMemberGroupInfo(XmlNode node) { XmlNodeList list = node.SelectNodes("//group"); MemberGroupInfo[] infos = new MemberGroupInfo[list.Count]; for(int i = 0; i < infos.Length; i++) { infos[i] = new MemberGroupInfo(list[i]); } return infos; } internal MemberGroupInfo(XmlNode node) { if( node.Attributes["nsid"] != null ) _groupId = node.Attributes["nsid"].Value; if( node.Attributes["name"] != null ) _groupName = node.Attributes["name"].Value; if( node.Attributes["admin"] != null ) _isAdmin = node.Attributes["admin"].Value=="1"; if( node.Attributes["privacy"] != null ) _privacy = (PoolPrivacy)Enum.Parse(typeof(PoolPrivacy),node.Attributes["privacy"].Value, true); if( node.Attributes["photos"] != null ) _numberOfPhotos = Int32.Parse(node.Attributes["photos"].Value); if( node.Attributes["iconserver"] != null ) _iconServer = node.Attributes["iconserver"].Value; } private string _groupId; /// /// Property which returns the group id for the group. /// public string GroupId { get { return _groupId; } } private string _groupName; /// The group name. public string GroupName { get { return _groupName; } } private bool _isAdmin; /// /// True if the user is the admin for the group, false if they are not. /// public bool IsAdmin { get { return _isAdmin; } } private long _numberOfPhotos; /// /// The number of photos currently in the group pool. /// public long NumberOfPhotos { get { return _numberOfPhotos; } } private PoolPrivacy _privacy; /// /// The privacy of the pool (see ). /// public PoolPrivacy Privacy { get { return _privacy; } } private string _iconServer; /// /// The server number for the group icon. /// public string IconServer { get { return _iconServer; } } /// /// The URL for the group icon. /// public Uri GroupIconUrl { get { return new Uri(String.Format("http://static.flickr.com/{0}/buddyicons/{1}.jpg", IconServer, GroupId)); } } /// /// The URL for the group web page. /// public Uri GroupUrl { get { return new Uri(String.Format("http://www.flickr.com/groups/{0}/", GroupId)); } } } /// /// Information about public groups for a user. /// [System.Serializable] public class PublicGroupInfo { internal static PublicGroupInfo[] GetPublicGroupInfo(XmlNode node) { XmlNodeList list = node.SelectNodes("//group"); PublicGroupInfo[] infos = new PublicGroupInfo[list.Count]; for(int i = 0; i < infos.Length; i++) { infos[i] = new PublicGroupInfo(list[i]); } return infos; } internal PublicGroupInfo(XmlNode node) { if( node.Attributes["nsid"] != null ) _groupId = node.Attributes["nsid"].Value; if( node.Attributes["name"] != null ) _groupName = node.Attributes["name"].Value; if( node.Attributes["admin"] != null ) _isAdmin = node.Attributes["admin"].Value=="1"; if( node.Attributes["eighteenplus"] != null ) _isEighteenPlus = node.Attributes["eighteenplus"].Value=="1"; } private string _groupId; /// /// Property which returns the group id for the group. /// public string GroupId { get { return _groupId; } } private string _groupName; /// The group name. public string GroupName { get { return _groupName; } } private bool _isAdmin; /// /// True if the user is the admin for the group, false if they are not. /// public bool IsAdmin { get { return _isAdmin; } } private bool _isEighteenPlus; /// /// Will contain 1 if the group is restricted to people who are 18 years old or over, 0 if it is not. /// public bool EighteenPlus { get { return _isEighteenPlus; } } /// /// The URL for the group web page. /// public Uri GroupUrl { get { return new Uri(String.Format("http://www.flickr.com/groups/{0}/", GroupId)); } } } /// /// The various pricay settings for a group. /// [System.Serializable] public enum PoolPrivacy { /// /// No privacy setting specified. /// [XmlEnum("0")] None = 0, /// /// The group is a private group. You cannot view pictures or posts until you are a /// member. The group is also invite only. /// [XmlEnum("1")] Private = 1, /// /// A public group where you can see posts and photos in the group. The group is however invite only. /// [XmlEnum("2")] InviteOnlyPublic = 2, /// /// A public group. /// [XmlEnum("3")] OpenPublic = 3 } } libflickrnet-48055~2.2.0/FlickrNet/Methods.cs0000644000175000017500000000602111155417352017655 0ustar varunvarunusing System; using System.Xml; using System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// Summary description for Methods. /// public class Methods { private Methods() { } internal static string[] GetMethods(XmlElement element) { XmlNodeList nodes = element.SelectNodes("method"); string[] _methods = new string[nodes.Count]; for(int i = 0; i < nodes.Count; i++) { _methods[i] = nodes[i].Value; } return _methods; } } /// /// A method supported by the Flickr API. /// /// /// See Flickr API Documentation for a complete list /// of methods. /// [Serializable] public class Method { /// /// Default constructor. /// public Method() { } /// /// The name of the method. /// [XmlAttribute("name", Form=XmlSchemaForm.Unqualified)] public string Name; /// /// The description of the method. /// [XmlElement("description", Form=XmlSchemaForm.Unqualified)] public string Description; /// /// An example response for the method. /// [XmlElement("response", Form=XmlSchemaForm.Unqualified)] public string Response; /// /// An explanation of the example response for the method. /// [XmlElement("explanation", Form=XmlSchemaForm.Unqualified)] public string Explanation; /// /// The arguments of the method. /// [XmlElement("arguments", Form=XmlSchemaForm.Unqualified)] public Arguments Arguments; /// /// The possible errors that could be returned by the method. /// [XmlArray()] [XmlArrayItem("error", typeof(MethodError), Form=XmlSchemaForm.Unqualified)] public MethodError[] Errors; } /// /// An instance containing a collection of instances. /// [Serializable] public class Arguments { /// /// A collection of instances. /// [XmlElement("argument", Form=XmlSchemaForm.Unqualified)] public Argument[] ArgumentCollection; } /// /// An argument for a method. /// [Serializable] public class Argument { /// /// The name of the argument. /// [XmlElement("name")] public string ArgumentName; /// /// Is the argument optional or not. /// [XmlElement("optional")] public int Optional; /// /// The description of the argument. /// [XmlText()] public string ArgumentDescription; } /// /// A possible error that a method can return. /// [Serializable] public class MethodError { /// /// The code for the error. /// [XmlElement("code")] public int Code; } } libflickrnet-48055~2.2.0/FlickrNet/PhotoInfo.cs0000644000175000017500000003503511155417352020166 0ustar varunvarunusing System; using System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// Detailed information returned by or methods. /// [System.Serializable] public class PhotoInfo { private string _photoId; private string _secret; private string _server; private string _farm; private string _originalFormat; private string _originalSecret; private int _views; private int _comments; private string _title; private string _description; private PhotoInfoTags _tags = new PhotoInfoTags(); private PhotoInfoUsage _usage = new PhotoInfoUsage(); /// /// The id of the photo. /// [XmlAttribute("id", Form=XmlSchemaForm.Unqualified)] public string PhotoId { get { return _photoId; } set { _photoId = value; } } /// /// The secret of the photo. Used to calculate the URL (amongst other things). /// [XmlAttribute("secret", Form=XmlSchemaForm.Unqualified)] public string Secret { get { return _secret; } set { _secret = value; } } /// /// The server on which the photo resides. /// [XmlAttribute("server", Form=XmlSchemaForm.Unqualified)] public string Server { get { return _server; } set { _server = value; } } /// /// The server farm on which the photo resides. /// [XmlAttribute("farm", Form=XmlSchemaForm.Unqualified)] public string Farm { get { return _farm; } set { _farm = value; } } /// /// The original format of the image (e.g. jpg, png etc). /// [XmlAttribute("originalformat", Form=XmlSchemaForm.Unqualified)] public string OriginalFormat { get { return _originalFormat; } set { _originalFormat = value; } } /// /// Optional extra field containing the original 'secret' of the /// photo used for forming the Url. /// [XmlAttribute("originalsecret", Form=XmlSchemaForm.Unqualified)] public string OriginalSecret { get { return _originalSecret; } set { _originalSecret = value; } } /// /// The date the photo was uploaded (or 'posted'). /// [XmlIgnore()] public DateTime DateUploaded { get { return Utils.UnixTimestampToDate(dateuploaded_raw); } } /// /// The raw value for when the photo was uploaded. /// [XmlAttribute("dateuploaded", Form=XmlSchemaForm.Unqualified)] public string dateuploaded_raw; /// /// Is the photo a favourite of the current authorised user. /// Will be 0 if the user is not authorised. /// [XmlAttribute("isfavorite", Form=XmlSchemaForm.Unqualified)] public int IsFavourite; /// /// The license of the photo. /// [XmlAttribute("license", Form=XmlSchemaForm.Unqualified)] public int License; /// /// The owner of the photo. /// /// /// See for more details. /// [XmlElement("owner", Form=XmlSchemaForm.Unqualified)] public PhotoInfoOwner Owner; /// /// The title of the photo. /// [XmlElement("title", Form=XmlSchemaForm.Unqualified)] public string Title { get { return _title; } set { _title = value; } } /// /// The description of the photo. /// [XmlElement("description", Form=XmlSchemaForm.Unqualified)] public string Description { get { return _description; } set { _description = value; } } /// /// The visibility of the photo. /// /// /// See for more details. /// [XmlElement("visibility", Form=XmlSchemaForm.Unqualified)] public PhotoInfoVisibility Visibility; /// /// The permissions of the photo. /// /// /// See for more details. /// [XmlElement("permissions", Form=XmlSchemaForm.Unqualified)] public PhotoInfoPermissions Permissions; /// /// The editability of the photo. /// /// /// See for more details. /// [XmlElement("editability", Form=XmlSchemaForm.Unqualified)] public PhotoInfoEditability Editability; /// /// The number of comments the photo has. /// [XmlElement("comments", Form=XmlSchemaForm.Unqualified)] public int CommentsCount { get { return _comments; } set { _comments = value; } } /// /// The number of views the photo has. /// [XmlAttribute("views", Form=XmlSchemaForm.Unqualified)] public int ViewCount { get { return _views; } set { _views = value; } } /// /// The notes for the photo. /// [XmlElement("notes", Form=XmlSchemaForm.Unqualified)] public PhotoInfoNotes Notes; /// /// The tags for the photo. /// [XmlElement("tags", Form=XmlSchemaForm.Unqualified)] public PhotoInfoTags Tags { get { return _tags; } set { _tags = (value==null?new PhotoInfoTags():value); } } /// /// The EXIF tags for the photo. /// [XmlElement("exif", Form=XmlSchemaForm.Unqualified)] public ExifTag[] ExifTagCollection; /// /// The dates (uploaded and taken dates) for the photo. /// [XmlElement("dates", Form=XmlSchemaForm.Unqualified)] public PhotoDates Dates; /// /// The location information of this photo, if available. /// /// /// Will be null if the photo has no location information stored on Flickr. /// [XmlElement("location", Form=XmlSchemaForm.Unqualified)] public PhotoLocation Location; /// /// The Web url for flickr web page for this photo. /// [XmlIgnore()] public string WebUrl { get { return string.Format("http://www.flickr.com/photos/{0}/{1}/", Owner.UserId, PhotoId); } } /// /// The URL for the square thumbnail for the photo. /// [XmlIgnore()] public string SquareThumbnailUrl { get { return Utils.UrlFormat(this, "_s", "jpg"); } } /// /// The URL for the thumbnail for the photo. /// [XmlIgnore()] public string ThumbnailUrl { get { return Utils.UrlFormat(this, "_t", "jpg"); } } /// /// The URL for the small version of this photo. /// [XmlIgnore()] public string SmallUrl { get { return Utils.UrlFormat(this, "_m", "jpg"); } } /// /// The URL for the medium version of this photo. /// /// /// There is no guarentee that this size of the image actually exists. /// Use to get a list of existing photo URLs. /// [XmlIgnore()] public string MediumUrl { get { return Utils.UrlFormat(this, "", "jpg"); } } /// /// The URL for the large version of this photo. /// /// /// There is no guarentee that this size of the image actually exists. /// Use to get a list of existing photo URLs. /// [XmlIgnore()] public string LargeUrl { get { return Utils.UrlFormat(this, "_b", "jpg"); } } /// /// If was returned then this will contain the url of the original file. /// [XmlIgnore()] public string OriginalUrl { get { if( OriginalFormat == null || OriginalFormat.Length == 0 ) throw new InvalidOperationException("No original format information available."); return Utils.UrlFormat(this, "_o", OriginalFormat); } } /// /// Allowed usage for this photo, based on the users permissions. /// [XmlElement("usage", Form=XmlSchemaForm.Unqualified)] public PhotoInfoUsage Usage { get { return _usage; } set { _usage = value; } } } /// /// The information about the owner of a photo. /// [System.Serializable] public class PhotoInfoOwner { /// /// The id of the own of the photo. /// [XmlAttribute("nsid", Form=XmlSchemaForm.Unqualified)] public string UserId; /// /// The username of the owner of the photo. /// [XmlAttribute("username", Form=XmlSchemaForm.Unqualified)] public string UserName; /// /// The real name (as stored on Flickr) of the owner of the photo. /// [XmlAttribute("realname", Form=XmlSchemaForm.Unqualified)] public string RealName; /// /// The location (as stored on Flickr) of the owner of the photo. /// [XmlAttribute("location", Form=XmlSchemaForm.Unqualified)] public string Location; } /// /// The visibility of the photo. /// [System.Serializable] public class PhotoInfoVisibility { /// /// Is the photo visible to the public. /// [XmlAttribute("ispublic", Form=XmlSchemaForm.Unqualified)] public int IsPublic; /// /// Is the photo visible to contacts marked as friends. /// [XmlAttribute("isfriend", Form=XmlSchemaForm.Unqualified)] public int IsFriend; /// /// Is the photo visible to contacts marked as family. /// [XmlAttribute("isfamily", Form=XmlSchemaForm.Unqualified)] public int IsFamily; } /// /// Who has permissions to add information to this photo (comments, tag and notes). /// [System.Serializable] public class PhotoInfoPermissions { /// /// Who has permissions to add comments to this photo. /// [XmlAttribute("permcomment", Form=XmlSchemaForm.Unqualified)] public PermissionComment PermissionComment; /// /// Who has permissions to add meta data (tags and notes) to this photo. /// [XmlAttribute("permaddmeta", Form=XmlSchemaForm.Unqualified)] public PermissionAddMeta PermissionAddMeta; } /// /// Information about who can edit the details of a photo. /// [System.Serializable] public class PhotoInfoEditability { /// /// Can the authorized user add new comments. /// /// /// "1" = true, "0" = false. /// [XmlAttribute("cancomment", Form=XmlSchemaForm.Unqualified)] public string CanComment; /// /// Can the authorized user add new meta data (tags and notes). /// /// /// "1" = true, "0" = false. /// [XmlAttribute("canaddmeta", Form=XmlSchemaForm.Unqualified)] public string CanAddMeta; } /// /// A class containing information about the notes for a photo. /// [System.Serializable] public class PhotoInfoNotes { /// /// A collection of notes for this photo. /// [XmlElement("note", Form=XmlSchemaForm.Unqualified)] public PhotoInfoNote[] NoteCollection; } /// /// A class containing information about a note on a photo. /// [System.Serializable] public class PhotoInfoNote { /// /// The notes unique ID. /// [XmlAttribute("id", Form=XmlSchemaForm.Unqualified)] public string NoteId; /// /// The User ID of the user who wrote the note. /// [XmlAttribute("author", Form=XmlSchemaForm.Unqualified)] public string AuthorId; /// /// The name of the user who wrote the note. /// [XmlAttribute("authorname", Form=XmlSchemaForm.Unqualified)] public string AuthorName; /// /// The x (left) position of the top left corner of the note. /// [XmlAttribute("x", Form=XmlSchemaForm.Unqualified)] public int XPosition; /// /// The y (top) position of the top left corner of the note. /// [XmlAttribute("y", Form=XmlSchemaForm.Unqualified)] public int YPosition; /// /// The width of the note. /// [XmlAttribute("w", Form=XmlSchemaForm.Unqualified)] public int Width; /// /// The height of the note. /// [XmlAttribute("h", Form=XmlSchemaForm.Unqualified)] public int Height; /// /// The text of the note. /// [XmlText()] public string NoteText; } /// /// A class containing a collection of tags for the photo. /// [System.Serializable] public class PhotoInfoTags { private PhotoInfoTag[] _tags = new PhotoInfoTag[0]; /// /// A collection of tags for the photo. /// [XmlElement("tag", Form=XmlSchemaForm.Unqualified)] public PhotoInfoTag[] TagCollection { get { return _tags; } set { _tags = (value==null?new PhotoInfoTag[0]:value); } } } /// /// The details of a tag of a photo. /// [System.Serializable] public class PhotoInfoTag { private int _machineTag; private string _tagId; private string _authorId; private string _authorName; /// /// The id of the tag. /// [XmlAttribute("id", Form=XmlSchemaForm.Unqualified)] public string TagId { get { return _tagId; } set { _tagId = value; } } /// /// The author id of the tag. /// [XmlAttribute("author", Form=XmlSchemaForm.Unqualified)] public string AuthorId { get { return _authorId; } set { _authorId = value; } } /// /// Author of the tag - only available if using . /// [XmlAttribute("authorname", Form=XmlSchemaForm.Unqualified)] public string AuthorName { get { return _authorName; } set { _authorName = value; } } /// /// Raw copy of the tag, as the user entered it. /// [XmlAttribute("raw", Form=XmlSchemaForm.Unqualified)] public string Raw; /// /// Raw copy of the tag, as the user entered it. /// [XmlAttribute("machine_tag", Form=XmlSchemaForm.Unqualified)] public int IsMachineTag { get { return _machineTag; } set { _machineTag = value; } } /// /// The actually tag. /// [XmlText()] public string TagText; } } libflickrnet-48055~2.2.0/FlickrNet/SafeNativeMethods.cs0000644000175000017500000000076611155417352021635 0ustar varunvarunusing System; namespace FlickrNet { /// /// Summary description for SafeNativeMethods. /// #if !WindowsCE [System.Security.SuppressUnmanagedCodeSecurity()] #endif internal class SafeNativeMethods { private SafeNativeMethods() { } internal static int GetErrorCode(System.IO.IOException ioe) { #if !WindowsCE return System.Runtime.InteropServices.Marshal.GetHRForException(ioe) & 0xFFFF; #else return 0; #endif } } } libflickrnet-48055~2.2.0/FlickrNet/PhotoPermissions.cs0000644000175000017500000000363611155417352021610 0ustar varunvarunusing System; using System.Xml; namespace FlickrNet { /// /// Permissions for the selected photo. /// [System.Serializable] public class PhotoPermissions { private string _photoId; private bool _isPublic; private bool _isFriend; private bool _isFamily; private PermissionAddMeta _permAddMeta; private PermissionComment _permComment; internal PhotoPermissions(XmlElement element) { if( element.Attributes.GetNamedItem("id") != null ) _photoId = element.Attributes.GetNamedItem("id").Value; if( element.Attributes.GetNamedItem("ispublic") != null ) _isPublic = element.Attributes.GetNamedItem("ispublic").Value=="1"; if( element.Attributes.GetNamedItem("isfamily") != null ) _isFamily = element.Attributes.GetNamedItem("isfamily").Value=="1"; if( element.Attributes.GetNamedItem("isfriend") != null ) _isFriend = element.Attributes.GetNamedItem("isfriend").Value=="1"; if( element.Attributes.GetNamedItem("permcomment") != null ) _permComment = (PermissionComment)Enum.Parse(typeof(PermissionComment), element.Attributes.GetNamedItem("permcomment").Value, true); if( element.Attributes.GetNamedItem("permaddmeta") != null ) _permAddMeta = (PermissionAddMeta)Enum.Parse(typeof(PermissionAddMeta), element.Attributes.GetNamedItem("permaddmeta").Value, true); } /// public string PhotoId { get { return _photoId; } } /// public bool IsPublic { get { return _isPublic; } } /// public bool IsFriend { get { return _isFriend; } } /// public bool IsFamily { get { return _isFamily; } } /// public PermissionComment PermissionComment { get { return _permComment; } } /// public PermissionAddMeta PermissionAddMeta { get { return _permAddMeta; } } } } libflickrnet-48055~2.2.0/FlickrNet/example_app.config0000644000175000017500000000247111155417352021412 0ustar varunvarun
libflickrnet-48055~2.2.0/FlickrNet/License.txt0000644000175000017500000000222511155417352020050 0ustar varunvarunFlickr .Net API Library ----------------------- All source code and information supplied as part of the Flick .Net API Library is copyright too its contributers. The source code has been released under a dual license - meaning you can use either licensed version of the library with your code. It is released under the Common Public License 1.0, a copy of which can be found at the link below. http://www.opensource.org/licenses/cpl.php It is released under the LGPL (GNU Lesser General Public License), a copy of which can be found at the link below. http://www.gnu.org/copyleft/lesser.html You are free to distribute copies of this Program in its compiled, unaltered form, including, but not limited to using it (in library form) in other .Net application, without use of this license. You are free to modify this code, however you must release the resulting Contributions under the CPL or the LGPL (or compatible license). Flickr API Key -------------- I do not have permission to include a Flickr API Key in any distribution which includes source code. If I do by accident then it is not included in the above license and should not be used. libflickrnet-48055~2.2.0/FlickrNet/PhotoSearchExtras.cs0000644000175000017500000000425511155417352021667 0ustar varunvarunusing System; namespace FlickrNet { /// /// Which photo search extras to be included. Can be combined to include more than one /// value. /// /// /// The following code sets options to return both the license and owner name along with /// the other search results. /// /// PhotoSearchOptions options = new PhotoSearchOptions(); /// options.Extras = PhotoSearchExtras.License & PhotoSearchExtras.OwnerName /// /// [Flags] [Serializable] public enum PhotoSearchExtras { /// /// No extras selected. /// None = 0, /// /// Returns a license. /// License = 1, /// /// Returned the date the photos was uploaded. /// DateUploaded = 2, /// /// Returned the date the photo was taken. /// DateTaken = 4, /// /// Returns the name of the owner of the photo. /// OwnerName = 8, /// /// Returns the server for the buddy icon for this user. /// IconServer = 16, /// /// Returns the extension for the original format of this photo. /// OriginalFormat = 32, /// /// Returns the date the photo was last updated. /// LastUpdated = 64, /// /// Returns Tags attribute /// Tags = 128, /// /// Geo-location information /// Geo = 256, /// /// Machine encoded tags /// MachineTags = 512, /// /// Return the Dimensions of the Original Image. /// OriginalDimensions = 1024, /// /// Returns the number of views for a photo. /// Views = 2048, /// /// Returns the media type of the photo, currently either 'photo' or 'video'. /// Media = 4096, /// /// Returns all the above information. /// All = License | DateUploaded | DateTaken | OwnerName | IconServer | OriginalFormat | LastUpdated | Tags | Geo | MachineTags | OriginalDimensions | Views | Media } } libflickrnet-48055~2.2.0/FlickrNet/GeoPermissions.cs0000644000175000017500000000366411155417352021232 0ustar varunvarunusing System; using System.Xml; namespace FlickrNet { /// /// Permissions for the selected photo. /// [System.Serializable] public class GeoPermissions { private string _photoId; private bool _isPublic; private bool _isContact; private bool _isFriend; private bool _isFamily; internal GeoPermissions(XmlElement element) { if( element.Attributes.GetNamedItem("id") != null ) _photoId = element.Attributes.GetNamedItem("id").Value; if( element.Attributes.GetNamedItem("ispublic") != null ) _isPublic = element.Attributes.GetNamedItem("ispublic").Value=="1"; if( element.Attributes.GetNamedItem("iscontact") != null ) _isContact = element.Attributes.GetNamedItem("iscontact").Value=="1"; if( element.Attributes.GetNamedItem("isfamily") != null ) _isFamily = element.Attributes.GetNamedItem("isfamily").Value=="1"; if( element.Attributes.GetNamedItem("isfriend") != null ) _isFriend = element.Attributes.GetNamedItem("isfriend").Value=="1"; } /// /// The ID for the photo whose permissions these are. /// public string PhotoId { get { return _photoId; } } /// /// Are the general unwashed (public) allowed to see the Geo Location information for this photo. /// public bool IsPublic { get { return _isPublic; } } /// /// Are contacts allowed to see the Geo Location information for this photo. /// public bool IsContact { get { return _isContact; } } /// /// Are friends allowed to see the Geo Location information for this photo. /// public bool IsFriend { get { return _isFriend; } } /// /// Are family allowed to see the Geo Location information for this photo. /// public bool IsFamily { get { return _isFamily; } } } } libflickrnet-48055~2.2.0/FlickrNet/Enums.cs0000644000175000017500000001526311155417352017351 0ustar varunvarunusing System; using System.Xml.Serialization; namespace FlickrNet { /// /// A list of service the Flickr.Net API Supports. /// /// /// Not all methods are supported by all service. Behaviour of the library may be unpredictable if not using Flickr /// as your service. /// public enum SupportedService { /// /// Flickr - http://www.flickr.com/services/api /// Flickr = 0, /// /// Zooomr - http://blog.zooomr.com/2006/03/27/attention-developers/ /// Zooomr = 1, /// /// 23HQ = http://www.23hq.com/doc/api/ /// TwentyThreeHQ = 2 } /// /// Used to specify where all tags must be matched or any tag to be matched. /// [Serializable] public enum TagMode { /// /// No tag mode specified. /// None, /// /// Any tag must match, but not all. /// AnyTag, /// /// All tags must be found. /// AllTags, /// /// Uncodumented and unsupported tag mode where boolean operators are supported. /// Boolean } /// /// What type of content is the upload representing. /// [Serializable] public enum ContentType { /// /// No content type specified. /// None = 0, /// /// For normal photographs. /// Photo = 1, /// /// For screenshots. /// Screenshot = 2, /// /// For other uploads, such as artwork. /// Other = 3 } /// /// The values for a content type search. /// [Serializable] public enum ContentTypeSearch { /// /// No content type specified. /// None = 0, /// /// For normal photographs. /// PhotosOnly = 1, /// /// For screenshots. /// ScreenshotsOnly = 2, /// /// For other uploads, such as artwork. /// OtherOnly = 3, /// /// Search for photos and screenshots /// PhotosAndScreenshots = 4, /// /// Search for screenshots and others /// ScreenshotsAndOthers = 5, /// /// Search for photos and other things /// PhotosAndOthers = 6, /// /// Search for anything (default) /// All = 7 } /// /// The units of a radius search /// [Serializable] public enum RadiusUnits { /// /// The radius units are unspecified. /// None = 0, /// /// The radius is in Kilometers. /// Kilometers = 1, /// /// The radius is in Miles. /// Miles = 0 } /// /// Allows you to perform a search on a users contacts. /// [Serializable] public enum ContactSearch { /// /// Do not perform a contact search. /// None = 0, /// /// Perform a search on all a users contacts. /// AllContacts = 1, /// /// Perform a search on only a users friends and family contacts. /// FriendsAndFamilyOnly = 2 } /// /// Safety level of the photographic image. /// [Serializable] public enum SafetyLevel { /// /// No safety level specified. /// None = 0, /// /// Very safe (suitable for a global family audience). /// Safe = 1, /// /// Moderate (the odd articstic nude is ok, but thats the limit). /// Moderate = 2, /// /// Restricted (suitable for over 18s only). /// Restricted = 3 } /// /// Determines weither the photo is visible in public searches. The default is 1, Visible. /// [Serializable] public enum HiddenFromSearch { /// /// No preference specified, defaults to your preferences on Flickr. /// None = 0, /// /// Photo is visible to public searches. /// Visible = 1, /// /// photo is hidden from public searches. /// Hidden = 2 } /// /// Used to specify where all tags must be matched or any tag to be matched. /// [Serializable] public enum MachineTagMode { /// /// No tag mode specified. /// None, /// /// Any tag must match, but not all. /// AnyTag, /// /// All tags must be found. /// AllTags } /// /// When searching for photos you can filter on the privacy of the photos. /// [Serializable] public enum PrivacyFilter { /// /// Do not filter. /// None = 0, /// /// Show only public photos. /// PublicPhotos = 1, /// /// Show photos which are marked as private but viewable by friends. /// PrivateVisibleToFriends = 2, /// /// Show photos which are marked as private but viewable by family contacts. /// PrivateVisibleToFamily = 3, /// /// Show photos which are marked as private but viewable by friends and family contacts. /// PrivateVisibleToFriendsFamily = 4, /// /// Show photos which are marked as completely private. /// CompletelyPrivate = 5 } /// /// An enumeration defining who can add comments. /// [Serializable] public enum PermissionComment { /// /// Nobody. /// [XmlEnum("0")] Nobody = 0, /// /// Friends and family only. /// [XmlEnum("1")] FriendsAndFamily = 1, /// /// Contacts only. /// [XmlEnum("2")] ContactsOnly = 2, /// /// All Flickr users. /// [XmlEnum("3")] Everybody = 3 } /// /// An enumeration defining who can add meta data (tags and notes). /// public enum PermissionAddMeta { /// /// The owner of the photo only. /// [XmlEnum("0")] Owner = 0, /// /// Friends and family only. /// [XmlEnum("1")] FriendsAndFamily = 1, /// /// All contacts. /// [XmlEnum("2")] Contacts = 2, /// /// All Flickr users. /// [XmlEnum("3")] Everybody = 3 } } libflickrnet-48055~2.2.0/FlickrNet/FlickrNet.ndoc0000644000175000017500000000522411155417352020455 0ustar varunvarun Flickr.Net API Library classes. See the Flickr class for main methods. libflickrnet-48055~2.2.0/FlickrNet/PersistentCache.cs0000644000175000017500000002003411155417352021336 0ustar varunvarunusing System; using System.Collections; using System.Diagnostics; using System.IO; //using System.Runtime.Serialization.Formatters.Binary; namespace FlickrNet { /// /// A threadsafe cache that is backed by disk storage. /// /// All public methods that read or write state must be /// protected by the lockFile. Private methods should /// not acquire the lockFile as it is not reentrant. /// internal sealed class PersistentCache { // The in-memory representation of the cache. // Use SortedList instead of Hashtable only to maintain backward // compatibility with previous serialization scheme. If we // abandon backward compatibility, we should switch to Hashtable. private Hashtable dataTable = new Hashtable(); private readonly CacheItemPersister persister; // true if dataTable contains changes vs. on-disk representation private bool dirty; // The persistent file representation of the cache. private readonly FileInfo dataFile; private DateTime timestamp; // last-modified time of dataFile when cache data was last known to be in sync private long length; // length of dataFile when cache data was last known to be in sync private long maxSize; // The file-based mutex. Named (dataFile.FullName + ".lock") private readonly LockFile lockFile; public PersistentCache(string filename, CacheItemPersister persister, long maxSize) { this.maxSize = maxSize; this.persister = persister; this.dataFile = new FileInfo(filename); this.lockFile = new LockFile(filename + ".lock"); } /// /// Return all items in the cache. Works similarly to /// ArrayList.ToArray(Type). /// public ICacheItem[] ToArray(Type valueType) { using (lockFile.Acquire()) { Refresh(); string[] keys; Array values; InternalGetAll(valueType, out keys, out values); return (ICacheItem[]) values; } } public int Count { get { using (lockFile.Acquire()) { Refresh(); return dataTable.Count; } } } /// /// Gets the maximum size for the persistent cache. /// public long MaxSize { get { return maxSize; } } /// /// Gets or sets cache values. /// public ICacheItem this[string key] { get { if (key == null) throw new ArgumentNullException("key"); using (lockFile.Acquire()) { Refresh(); return InternalGet(key); } } set { if (key == null) throw new ArgumentNullException("key"); ICacheItem oldItem; using (lockFile.Acquire()) { Refresh(); oldItem = InternalSet(key, value); Persist(); } if (oldItem != null) oldItem.OnItemFlushed(); } } public ICacheItem Get(string key, TimeSpan maxAge, bool removeIfExpired) { Debug.Assert(maxAge > TimeSpan.Zero || maxAge == TimeSpan.MinValue, "maxAge should be positive, not negative"); ICacheItem item; bool expired; using (lockFile.Acquire()) { Refresh(); item = InternalGet(key); expired = item != null && Expired(item.CreationTime, maxAge); if (expired) { if (removeIfExpired) { item = RemoveKey(key); Persist(); } else item = null; } } if (expired && removeIfExpired) item.OnItemFlushed(); return expired ? null : item; } public void Flush() { Shrink(0); } public void Shrink(long size) { if (size < 0) throw new ArgumentException("Cannot shrink to a negative size", "size"); ArrayList flushed = new ArrayList(); using (lockFile.Acquire()) { Refresh(); string[] keys; Array values; InternalGetAll(typeof(ICacheItem), out keys, out values); long totalSize = 0; foreach (ICacheItem cacheItem in values) totalSize += cacheItem.FileSize; for (int i = 0; i < keys.Length; i++) { if (totalSize <= size) break; ICacheItem cacheItem = (ICacheItem) values.GetValue(i); totalSize -= cacheItem.FileSize; flushed.Add(RemoveKey(keys[i])); } Persist(); } foreach (ICacheItem flushedItem in flushed) { Debug.Assert(flushedItem != null, "Flushed item was null--programmer error"); if (flushedItem != null) flushedItem.OnItemFlushed(); } } private bool Expired(DateTime test, TimeSpan age) { if (age == TimeSpan.MinValue) return true; else if (age == TimeSpan.MaxValue) return false; else return test < DateTime.UtcNow - age; } private void InternalGetAll(Type valueType, out string[] keys, out Array values) { if (!typeof(ICacheItem).IsAssignableFrom(valueType)) throw new ArgumentException("Type " + valueType.FullName + " does not implement ICacheItem", "valueType"); keys = (string[]) new ArrayList(dataTable.Keys).ToArray(typeof(string)); values = Array.CreateInstance(valueType, keys.Length); for (int i = 0; i < keys.Length; i++) values.SetValue(dataTable[keys[i]], i); Array.Sort(values, keys, new CreationTimeComparer()); } private ICacheItem InternalGet(string key) { if (key == null) throw new ArgumentNullException("key"); return (ICacheItem) dataTable[key]; } /// The old value associated with key, if any. private ICacheItem InternalSet(string key, ICacheItem value) { if (key == null) throw new ArgumentNullException("key"); ICacheItem flushedItem; flushedItem = RemoveKey(key); if (value != null) // don't ever let nulls get in dataTable[key] = value; dirty = dirty || !object.ReferenceEquals(flushedItem, value); return flushedItem; } private ICacheItem RemoveKey(string key) { ICacheItem cacheItem = (ICacheItem) dataTable[key]; if (cacheItem != null) { dataTable.Remove(key); dirty = true; } return cacheItem; } private void Refresh() { Debug.Assert(!dirty, "Refreshing even though cache is dirty"); DateTime newTimestamp = DateTime.MinValue; long newLength = -1; if (dataFile.Exists) { dataFile.Refresh(); newTimestamp = dataFile.LastWriteTime; newLength = dataFile.Length; } if (timestamp != newTimestamp || length != newLength) { // file changed if (!dataFile.Exists) dataTable.Clear(); else { Debug.WriteLine("Loading cache from disk"); using (FileStream inStream = dataFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read)) { dataTable = Load(inStream); } } } timestamp = newTimestamp; length = newLength; dirty = false; } private void Persist() { if (!dirty) return; Debug.WriteLine("Saving cache to disk"); using (FileStream outStream = dataFile.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)) { Store(outStream, dataTable); } dataFile.Refresh(); timestamp = dataFile.LastWriteTime; length = dataFile.Length; dirty = false; } private Hashtable Load(Stream s) { Hashtable table = new Hashtable(); int itemCount = Utils.ReadInt32(s); for (int i = 0; i < itemCount; i++) { try { string key = Utils.ReadString(s); ICacheItem val = persister.Read(s); if( val == null ) // corrupt cache file return table; table[key] = val; } catch(IOException) { return table; } } return table; } private void Store(Stream s, Hashtable table) { Utils.WriteInt32(s, table.Count); foreach (DictionaryEntry entry in table) { Utils.WriteString(s, (string) entry.Key); persister.Write(s, (ICacheItem) entry.Value); } } private class CreationTimeComparer : IComparer { public int Compare(object x, object y) { return ((ICacheItem)x).CreationTime.CompareTo(((ICacheItem)y).CreationTime); } } } } libflickrnet-48055~2.2.0/FlickrNet/ActivityEvent.cs0000644000175000017500000000522511155417352021055 0ustar varunvarunusing System; using System.Xml; namespace FlickrNet { /// /// A user event on a photo, e.g. Comment or Favourite etc. /// /// /// Includes the user's Flickr ID, name, the date of the activity and its content (if a comment). /// public class ActivityEvent { private ActivityEventType _type; private string _userId; private string _userName; private DateTime _dateAdded; private string _content; /// /// The of the event, either Comment or Note. /// public ActivityEventType EventType { get { return _type; } } /// /// The user id of the user who made the comment or note. /// public string UserId { get { return _userId; } } /// /// The screen name of the user who made the comment or note. /// public string UserName { get { return _userName; } } /// /// The date the note or comment was added. /// public DateTime DateAdded { get { return _dateAdded; } } /// /// The text of the note or comment. /// public string Value { get { return _content; } } internal ActivityEvent(XmlNode eventNode) { XmlNode node; node = eventNode.Attributes.GetNamedItem("type"); if( node == null ) _type = ActivityEventType.Unknown; else if( node.Value == "comment" ) _type = ActivityEventType.Comment; else if( node.Value == "note" ) _type = ActivityEventType.Note; else if( node.Value == "fave" ) _type = ActivityEventType.Favourite; else _type = ActivityEventType.Unknown; node = eventNode.Attributes.GetNamedItem("user"); if( node != null ) _userId = node.Value; node = eventNode.Attributes.GetNamedItem("username"); if( node != null ) _userName = node.Value; node = eventNode.Attributes.GetNamedItem("dateadded"); if( node != null ) _dateAdded = Utils.UnixTimestampToDate(node.Value); node = eventNode.FirstChild; if( node != null && node.NodeType == XmlNodeType.Text ) _content = node.Value; } } /// /// The type of the . /// public enum ActivityEventType { /// /// The event type was not specified, or was a new unsupported type. /// Unknown, /// /// The event was a comment. /// Comment, /// /// The event was a note. /// Note, /// /// The event is a favourite. /// Favourite } } libflickrnet-48055~2.2.0/FlickrNet/ResponseXmlException.cs0000644000175000017500000000061411155417352022412 0ustar varunvarunusing System; namespace FlickrNet { /// /// Exception thrown when an error parsing the returned XML. /// public class ResponseXmlException : FlickrException { internal ResponseXmlException(string message) : base(message) { } internal ResponseXmlException(string message, Exception innerException) : base(message, innerException) { } } } libflickrnet-48055~2.2.0/FlickrNet/BoundaryBox.cs0000644000175000017500000001637511155417352020523 0ustar varunvarunusing System; namespace FlickrNet { /// /// Summary description for BoundaryBox. /// [Serializable] public class BoundaryBox { private GeoAccuracy _accuracy = GeoAccuracy.Street; private bool _isSet = false; private double _minimumLat = -90; private double _minimumLon = -180; private double _maximumLat = 90; private double _maximumLon = 180; /// /// Gets weither the boundary box has been set or not. /// internal bool IsSet { get { return _isSet; } } /// /// The search accuracy - optional. Defaults to . /// public GeoAccuracy Accuracy { get { return _accuracy; } set { _accuracy = value; } } /// /// The minimum latitude of the boundary box, i.e. bottom left hand corner. /// public double MinimumLatitude { get { return _minimumLat; } set { if( value < -90 || value > 90 ) throw new ArgumentOutOfRangeException("MinimumLatitude", "Must be between -90 and 90"); _isSet = true; _minimumLat = value; } } /// /// The minimum longitude of the boundary box, i.e. bottom left hand corner. Range of -180 to 180 allowed. /// public double MinimumLongitude { get { return _minimumLon; } set { if( value < -180 || value > 180 ) throw new ArgumentOutOfRangeException("MinimumLongitude", "Must be between -180 and 180"); _isSet = true; _minimumLon = value; } } /// /// The maximum latitude of the boundary box, i.e. top right hand corner. Range of -90 to 90 allowed. /// public double MaximumLatitude { get { return _maximumLat; } set { if( value < -90 || value > 90 ) throw new ArgumentOutOfRangeException("MaximumLatitude", "Must be between -90 and 90"); _isSet = true; _maximumLat = value; } } /// /// The maximum longitude of the boundary box, i.e. top right hand corner. Range of -180 to 180 allowed. /// public double MaximumLongitude { get { return _maximumLon; } set { if( value < -180 || value > 180 ) throw new ArgumentOutOfRangeException("MaximumLongitude", "Must be between -180 and 180"); _isSet = true; _maximumLon = value; } } /// /// Default constructor /// public BoundaryBox() { } /// /// Default constructor, specifying only the accuracy level. /// /// The of the search parameter. public BoundaryBox(GeoAccuracy accuracy) { _accuracy = accuracy; } /// /// Constructor for the /// /// A comma seperated list of co-ordinates defining the boundary box. /// The of the search parameter. public BoundaryBox(string points, GeoAccuracy accuracy) : this(points) { _accuracy = accuracy; } /// /// Constructor for the /// /// A comma seperated list of co-ordinates defining the boundary box. public BoundaryBox(string points) { if( points == null ) throw new ArgumentNullException("points"); string[] splits = points.Split(','); if( splits.Length != 4 ) throw new ArgumentException("Parameter must contain 4 values, seperated by commas.", "points"); try { MinimumLongitude = double.Parse(splits[0],System.Globalization.NumberFormatInfo.InvariantInfo); MinimumLatitude = double.Parse(splits[1],System.Globalization.NumberFormatInfo.InvariantInfo); MaximumLongitude = double.Parse(splits[2],System.Globalization.NumberFormatInfo.InvariantInfo); MaximumLatitude = double.Parse(splits[3],System.Globalization.NumberFormatInfo.InvariantInfo); } catch(FormatException) { throw new ArgumentException("Unable to parse points as integer values", "points"); } } /// /// Constructor for the . /// /// The minimum longitude of the boundary box. Range of -180 to 180 allowed. /// The minimum latitude of the boundary box. Range of -90 to 90 allowed. /// The maximum longitude of the boundary box. Range of -180 to 180 allowed. /// The maximum latitude of the boundary box. Range of -90 to 90 allowed. /// The of the search parameter. public BoundaryBox(double minimumLongitude, double minimumLatitude, double maximumLongitude, double maximumLatitude, GeoAccuracy accuracy) : this(minimumLongitude, minimumLatitude, maximumLongitude, maximumLatitude) { _accuracy = accuracy; } /// /// Constructor for the . /// /// The minimum longitude of the boundary box. Range of -180 to 180 allowed. /// The minimum latitude of the boundary box. Range of -90 to 90 allowed. /// The maximum longitude of the boundary box. Range of -180 to 180 allowed. /// The maximum latitude of the boundary box. Range of -90 to 90 allowed. public BoundaryBox(double minimumLongitude, double minimumLatitude, double maximumLongitude, double maximumLatitude) { MinimumLatitude = minimumLatitude; MinimumLongitude = minimumLongitude; MaximumLatitude = maximumLatitude; MaximumLongitude = maximumLongitude; } /// /// Overrides the ToString method. /// /// A comma seperated list of co-ordinates defining the boundary box. public override string ToString() { return String.Format(System.Globalization.NumberFormatInfo.InvariantInfo, "{0},{1},{2},{3}", MinimumLongitude, MinimumLatitude, MaximumLongitude, MaximumLatitude); } /// /// Example boundary box for the UK. /// public static BoundaryBox UK { get { return new BoundaryBox(-11.118164, 49.809632, 1.625977, 62.613562); } } /// /// Example boundary box for Newcastle upon Tyne, England. /// public static BoundaryBox UKNewcastle { get { return new BoundaryBox(-1.71936, 54.935821, -1.389771, 55.145919); } } /// /// Example boundary box for the USA (excludes Hawaii and Alaska). /// public static BoundaryBox USA { get { return new BoundaryBox(-130.429687, 22.43134, -58.535156, 49.382373); } } /// /// Example boundary box for Canada. /// public static BoundaryBox Canada { get { return new BoundaryBox(-143.085937, 41.640078, -58.535156, 73.578167); } } /// /// Example boundary box for the whole world. /// public static BoundaryBox World { get { return new BoundaryBox(-180, -90, 180, 90); } } } } libflickrnet-48055~2.2.0/FlickrNet/GroupSearchResults.cs0000644000175000017500000001125011155417352022056 0ustar varunvarunusing System; using System.Xml; using System.Xml.XPath; namespace FlickrNet { /// /// Returned by methods. /// public class GroupSearchResults { private int page; /// /// The current page that the group search results represents. /// public int Page { get { return page; } } private int pages; /// /// The total number of pages this search would return. /// public int Pages { get { return pages; } } private int perPage; /// /// The number of groups returned per photo. /// public int PerPage { get { return perPage; } } private int total; /// /// The total number of groups that where returned for the search. /// public int Total { get { return total; } } private GroupSearchResultCollection groups = new GroupSearchResultCollection(); /// /// The collection of groups returned for this search. /// /// /// The following code iterates through the list of groups returned: /// /// GroupSearchResults results = flickr.GroupsSearch("test"); /// foreach(GroupSearchResult result in results.Groups) /// { /// Console.WriteLine(result.GroupName); /// } /// /// public GroupSearchResultCollection Groups { get { return groups; } } internal GroupSearchResults(XmlElement element) { page = Convert.ToInt32(element.GetAttribute("page")); pages = Convert.ToInt32(element.GetAttribute("pages")); perPage = Convert.ToInt32(element.GetAttribute("perpage")); total = Convert.ToInt32(element.GetAttribute("total")); XmlNodeList gs = element.SelectNodes("group"); groups.Clear(); for(int i = 0; i < gs.Count; i++) { groups.Add(new GroupSearchResult(gs[i])); } } } /// /// Collection containing list of GroupSearchResult instances /// public class GroupSearchResultCollection : System.Collections.CollectionBase { /// /// Method for adding a new to the collection. /// /// public void Add(GroupSearchResult result) { List.Add(result); } /// /// Method for adding a collection of objects (contained within a /// collection) to this collection. /// /// public void AddRange(GroupSearchResultCollection results) { foreach(GroupSearchResult result in results) List.Add(result); } /// /// Return a particular based on the index. /// public GroupSearchResult this[int index] { get { return (GroupSearchResult)List[index]; } set { List[index] = value; } } /// /// Removes the selected result from the collection. /// /// The result to remove. public void Remove(GroupSearchResult result) { List.Remove(result); } /// /// Checks if the collection contains the result. /// /// The result to see if the collection contains. /// Returns true if the collecton contains the result, otherwise false. public bool Contains(GroupSearchResult result) { return List.Contains(result); } /// /// Copies the current collection to an array of objects. /// /// /// public void CopyTo(GroupSearchResult[] array, int index) { List.CopyTo(array, index); } } /// /// A class which encapsulates a single group search result. /// public class GroupSearchResult { private string _groupId; private string _groupName; private bool _eighteen; /// /// The group id for the result. /// public string GroupId { get { return _groupId; } } /// /// The group name for the result. /// public string GroupName { get { return _groupName; } } /// /// True if the group is an over eighteen (adult) group only. /// public bool EighteenPlus { get { return _eighteen; } } internal GroupSearchResult(XmlNode node) { _groupId = node.Attributes["nsid"].Value; _groupName = node.Attributes["name"].Value; _eighteen = Convert.ToInt32(node.Attributes["eighteenplus"].Value)==1; } } } libflickrnet-48055~2.2.0/FlickrNet/FlickrNet.csproj0000644000175000017500000003414011155417352021031 0ustar varunvarun libflickrnet-48055~2.2.0/FlickrNet/Person.cs0000644000175000017500000001327411155417352017530 0ustar varunvarunusing System; using System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// The class contains details returned by the /// method. /// [System.Serializable] [XmlRoot("person")] public class Person { internal static Person SerializePerson(System.Xml.XmlNode node) { Person p = (Person)Utils.Deserialize(node, typeof(Person)); return p; } private string _userId; private int _isAdmin; private int _isPro; private int _iconServer; private int _iconFarm; private string _username; private string _realname; private string _location; private PersonPhotosSummary _summary = new PersonPhotosSummary(); private string _photosUrl; private string _profileUrl; private string _mboxHash; /// The user id of the user. /// [XmlAttribute("nsid", Form=XmlSchemaForm.Unqualified)] public string UserId { get { return _userId; } set { _userId = value; } } /// Is the user an administrator. /// 1 = admin, 0 = normal user. /// [XmlAttribute("isadmin", Form=XmlSchemaForm.Unqualified)] public int IsAdmin { get { return _isAdmin; } set { _isAdmin = value; } } /// Does the user posses a pro account. /// 0 = free acouunt, 1 = pro account holder. [XmlAttribute("ispro", Form=XmlSchemaForm.Unqualified)] public int IsPro { get { return _isPro; } set { _isPro = value; } } /// Does the user posses a pro account. /// 0 = free acouunt, 1 = pro account holder. [XmlAttribute("iconserver", Form=XmlSchemaForm.Unqualified)] public int IconServer { get { return _iconServer; } set { _iconServer = value; } } /// No idea what purpose this field serves. [XmlAttribute("iconfarm", Form=XmlSchemaForm.Unqualified)] public int IconFarm { get { return _iconFarm; } set { _iconFarm = value; } } /// The users username, also known as their screenname. [XmlElement("username", Form=XmlSchemaForm.Unqualified)] public string UserName { get { return _username; } set { _username = value; } } /// The users real name, as entered in their profile. [XmlElement("realname", Form=XmlSchemaForm.Unqualified)] public string RealName { get { return _realname; } set { _realname = value; } } /// The SHA1 hash of the users email address - used for FOAF networking. [XmlElement("mbox_sha1sum", Form=XmlSchemaForm.Unqualified)] public string MailBoxSha1Hash { get { return _mboxHash; } set { _mboxHash = value; } } /// Consists of your current location followed by country. /// e.g. Newcastle, UK. [XmlElement("location", Form=XmlSchemaForm.Unqualified)] public string Location { get { return _location; } set { _location = value; } } /// Sub element containing a summary of the users photo information. /// [XmlElement("photos", Form=XmlSchemaForm.Unqualified)] public PersonPhotosSummary PhotosSummary { get { return _summary; } set { _summary = value; } } /// /// The users photo location on Flickr /// http://www.flickr.com/photos/username/ /// [XmlElement("photosurl",Form=XmlSchemaForm.Unqualified)] public string PhotosUrl { get { return _photosUrl; } set { _photosUrl = value; } } /// /// The users profile location on Flickr /// http://www.flickr.com/people/username/ /// [XmlElement("profileurl",Form=XmlSchemaForm.Unqualified)] public string ProfileUrl { get { return _profileUrl; } set { _profileUrl = value; } } /// /// Returns the for the users Buddy Icon. /// [XmlIgnore()] public Uri BuddyIconUrl { get { if( IconServer == 0 ) return new Uri("http://www.flickr.com/images/buddyicon.jpg"); else return new Uri(String.Format("http://static.flickr.com/{0}/buddyicons/{1}.jpg", IconServer, UserId)); } } } /// /// A summary of a users photos. /// [System.Serializable] public class PersonPhotosSummary { private int _photoCount; private int _views; /// The first date the user uploaded a picture, converted into format. [XmlIgnore()] public DateTime FirstDate { get { return Utils.UnixTimestampToDate(firstdate_raw); } } /// The first date the user took a picture, converted into format. [XmlIgnore()] public DateTime FirstTakenDate { get { if( firsttakendate_raw == null || firsttakendate_raw.Length == 0 ) return DateTime.MinValue; return System.DateTime.Parse(firsttakendate_raw); } } /// The total number of photos for the user. /// [XmlElement("count", Form=XmlSchemaForm.Unqualified)] public int PhotoCount { get { return _photoCount; } set { _photoCount = value; } } /// The total number of photos for the user. /// [XmlElement("views", Form=XmlSchemaForm.Unqualified)] public int Views { get { return _views; } set { _views = value; } } /// The unix timestamp of the date the first photo was uploaded. [XmlElement("firstdate", Form=XmlSchemaForm.Unqualified)] public string firstdate_raw; /// The date the first photo was taken. [XmlElement("firsttakendate", Form=XmlSchemaForm.Unqualified)] public string firsttakendate_raw; } } libflickrnet-48055~2.2.0/FlickrNet/FlickrNet.snk0000644000175000017500000000112411155417352020320 0ustar varunvarun$RSA29X-AΚwbGoXZb\J&lmŃfXS,sN@# VF[;Cqp S[[-7+Kx͆bY*GXl9veh'IqQid2B{c HЦn+d4`U=d~؞˘o Z3)3O0|޸ҽo>`owݐ(;2eCT2BM/F †)9j?GXȵb,&$/W$4o*:LִDWq t,9b16Ρ(N }FeQ2@(RQg\3JUs}'Q 4G\[_& umވPQyYdɧ~ҁLÃMvVCe8QJ*Yȫe^TBqֺn&cQu($ `Tzc ]-|o~8J1z*)66,h$l͐r'}ștq 'ibª!SJ>libflickrnet-48055~2.2.0/FlickrNet/PhotoCounts.cs0000644000175000017500000000314311155417352020541 0ustar varunvarunusing System; using System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// The information about the number of photos a user has. /// [System.Serializable] public class PhotoCounts { /// /// An array of instances. Null if no counts returned. /// [XmlElement("photocount", Form=XmlSchemaForm.Unqualified)] public PhotoCountInfo[] PhotoCountInfoCollection = new PhotoCountInfo[0]; } /// /// The specifics of a particular count. /// [System.Serializable] public class PhotoCountInfo { /// Total number of photos between the FromDate and the ToDate. /// [XmlAttribute("count", Form=XmlSchemaForm.Unqualified)] public int PhotoCount; /// The From date as a object. [XmlIgnore()] public DateTime FromDate { get { return Utils.UnixTimestampToDate(fromdate_raw); } } /// The To date as a object. [XmlIgnore()] public DateTime ToDate { get { return Utils.UnixTimestampToDate(todate_raw); } } /// The original from date in unix timestamp format. /// [XmlAttribute("fromdate", Form=XmlSchemaForm.Unqualified)] public string fromdate_raw; /// The original to date in unix timestamp format. /// [XmlAttribute("todate", Form=XmlSchemaForm.Unqualified)] public string todate_raw; } }libflickrnet-48055~2.2.0/FlickrNet/Photos.cs0000644000175000017500000001564511155417352017542 0ustar varunvarunusing System; using System.Xml.Serialization; using System.Xml.Schema; using System.Collections; namespace FlickrNet { /// [Serializable] public class Photos { private Photo[] _photos = new Photo[0]; /// [XmlElement("photo", Form = XmlSchemaForm.Unqualified)] public Photo[] PhotoCollection { get { return _photos; } set { _photos = value==null?new Photo[0]:value; } } /// [XmlAttribute("page", Form=XmlSchemaForm.Unqualified)] public long PageNumber; /// [XmlAttribute("pages", Form=XmlSchemaForm.Unqualified)] public long TotalPages; /// [XmlAttribute("perpage", Form=XmlSchemaForm.Unqualified)] public long PhotosPerPage; /// [XmlAttribute("total", Form=XmlSchemaForm.Unqualified)] public long TotalPhotos; } /// /// A collection of instances. /// [System.Serializable] public class PhotoCollection : CollectionBase { /// /// Default constructor. /// public PhotoCollection() { } /// /// Creates an instance of the from an array of /// instances. /// /// An array of instances. public PhotoCollection(Photo[] photos) { if (photos == null) return; for (int i=0; i /// Gets number of photos in the current collection. /// public int Length { get { return List.Count; } } /// /// Gets the index of a photo in this collection. /// /// The photo to find. /// The index of the photo, -1 if it is not in the collection. public int IndexOf(Photo photo) { return List.IndexOf(photo); } #region ICollection Members /// /// Gets a value indicating if the collection is synchronized (thread-safe). /// public bool IsSynchronized { get { return List.IsSynchronized; } } /// /// Copies the elements of the collection to an array of , starting at a /// particular index. /// /// The array to copy to. /// The index in the collection to start copying from. public void CopyTo(Photo[] array, int index) { List.CopyTo(array, index); } /// /// Gets an object that can be used to synchronize the collection. /// public object SyncRoot { get { return List.SyncRoot; } } #endregion #region IList Members /// /// Gets a value indicating whether the collection is read-only. /// public bool IsReadOnly { get { return List.IsReadOnly; } } /// /// Gets or sets a photo based on the index in the collection. /// public Photo this[int index] { get { return (Photo)List[index]; } set { List[index] = value; } } /// /// Inserts a into the collection at the given index. /// /// The index to insert the into. /// Subsequent photos will be moved up. /// The to insert. public void Insert(int index, Photo photo) { List.Insert(index, photo); } /// /// Removes a photo from the collection. /// /// The instance to remove from the collection. public void Remove(Photo photo) { List.Remove(photo); } /// /// Returns true if the collection contains the photo. /// /// The instance to try to find. /// True of False, depending on if the is found in the collection. public bool Contains(Photo photo) { return List.Contains(photo); } /// /// Adds a to the collection. /// /// The instance to add to the collection. /// The index that the photo was added at. public int Add(Photo photo) { return List.Add(photo); } /// /// Adds an array of instances to this collection. /// /// An array of instances. public void AddRange(Photo[] photos) { foreach(Photo photo in photos) List.Add(photo); } /// /// Adds all of the photos in another to this collection. /// /// The containing the photos to add /// to this collection. public void AddRange(PhotoCollection collection) { foreach(Photo photo in collection) List.Add(photo); } /// /// Gets an instance specifying whether the collection is a fixed size. /// public bool IsFixedSize { get { return List.IsFixedSize; } } #endregion /// /// Converts a PhotoCollection instance to an array of Photo objects. /// /// The collection to convert. /// An array of objects. public static implicit operator Photo[](PhotoCollection collection) { Photo[] photos = new Photo[collection.Count]; collection.CopyTo(photos, 0); return photos; } /// /// Converts the collection to an array of objects. /// /// An array of objects. public Photo[] ToPhotoArray() { return (Photo[])this; } /// /// Implicitly converts an array of objects to a . /// /// The array of objects to convert. /// public static implicit operator PhotoCollection(Photo[] photos) { return new PhotoCollection(photos); } /// /// Creates a from an array of objects. /// /// An array of objects. /// A new containing all the objects from the array. public static PhotoCollection FromPhotoArray(Photo[] photos) { return (PhotoCollection)photos; } } }libflickrnet-48055~2.2.0/FlickrNet/User.cs0000644000175000017500000000716611155417352017203 0ustar varunvarunusing System; using System.Xml; namespace FlickrNet { /// /// Contains details of a user /// [Serializable] public class FoundUser { private string _userId; private string _username; /// /// The ID of the found user. /// public string UserId { get { return _userId; } set { _userId = value; } } /// /// The username of the found user. /// public string Username { get { return _username; } set { _username = value; } } /// /// Default constructor. /// public FoundUser() { } internal FoundUser(string userId, string username) { _userId = userId; _username = username; } internal FoundUser(XmlNode node) { if( node.Attributes["nsid"] != null ) _userId = node.Attributes["nsid"].Value; if( node.Attributes["id"] != null ) _userId = node.Attributes["id"].Value; if( node.Attributes["username"] != null ) _username = node.Attributes["username"].Value; if( node.SelectSingleNode("username") != null ) _username = node.SelectSingleNode("username").InnerText; } } /// /// The upload status of the user, as returned by . /// [System.Serializable] public class UserStatus { private bool _isPro; private string _userId; private string _username; private long _bandwidthMax; private long _bandwidthUsed; private long _filesizeMax; internal UserStatus(XmlNode node) { if( node == null ) throw new ArgumentNullException("node"); if( node.Attributes["id"] != null ) _userId = node.Attributes["id"].Value; if( node.Attributes["nsid"] != null ) _userId = node.Attributes["nsid"].Value; if( node.Attributes["ispro"] != null ) _isPro = node.Attributes["ispro"].Value=="1"; if( node.SelectSingleNode("username") != null ) _username = node.SelectSingleNode("username").InnerText; XmlNode bandwidth = node.SelectSingleNode("bandwidth"); if( bandwidth != null ) { _bandwidthMax = Convert.ToInt64(bandwidth.Attributes["max"].Value); _bandwidthUsed = Convert.ToInt64(bandwidth.Attributes["used"].Value); } XmlNode filesize = node.SelectSingleNode("filesize"); if( filesize != null ) { _filesizeMax = Convert.ToInt64(filesize.Attributes["max"].Value); } } /// /// The id of the user object. /// public string UserId { get { return _userId; } } /// /// The Username of the selected user. /// public string UserName { get { return _username; } } /// /// Is the current user a Pro account. /// public bool IsPro { get { return _isPro; } } /// /// The maximum bandwidth (in bytes) that the user can use each month. /// public long BandwidthMax { get { return _bandwidthMax; } } /// /// The number of bytes of the current months bandwidth that the user has used. /// public long BandwidthUsed { get { return _bandwidthUsed; } } /// /// The maximum filesize (in bytes) that the user is allowed to upload. /// public long FilesizeMax { get { return _filesizeMax; } } /// /// representing the percentage bandwidth used so far. Will range from 0 to 1. /// public Double PercentageUsed { get { return BandwidthUsed * 1.0 / BandwidthMax; } } } }libflickrnet-48055~2.2.0/FlickrNet/PhotoSearchOrder.cs0000644000175000017500000000203611155417352021467 0ustar varunvarunusing System; namespace FlickrNet { /// /// The sort order for the , /// , methods. /// [Serializable] public enum PhotoSearchSortOrder { /// /// No sort order. /// None, /// /// Sort by date uploaded (posted). /// DatePostedAsc, /// /// Sort by date uploaded (posted) in descending order. /// DatePostedDesc, /// /// Sort by date taken. /// DateTakenAsc, /// /// Sort by date taken in descending order. /// DateTakenDesc, /// /// Sort by interestingness. /// InterestingnessAsc, /// /// Sort by interestingness in descending order. /// InterestingnessDesc, /// /// Sort by relevance /// Relevance } } libflickrnet-48055~2.2.0/FlickrNet/Comments.cs0000644000175000017500000000550011155417352020040 0ustar varunvarunusing System; using System.Xml; namespace FlickrNet { /// /// Parent object containing details of a photos comments. /// internal class PhotoComments { static private string _photoId; static private Comment[] _comments; static internal Comment[] GetComments(XmlNode node) { if( node.Attributes["photo_id"] != null ) _photoId = node.Attributes["photo_id"].Value; XmlNodeList nodes = node.SelectNodes("comment"); _comments = new Comment[nodes.Count]; for(int i = 0; i < _comments.Length; i++) { _comments[i] = new Comment(_photoId, nodes[i]); } return _comments; } } /// /// Contains the details of a comment made on a photo. /// returned by the method. /// public class Comment { private string _photoId; private string _authorUserId; private string _authorUserName; private string _commentId; private Uri _permaLink; private DateTime _dateCreated; private string _comment; /// /// The photo id associated with this comment. /// public string PhotoId { get { return _photoId; } } /// /// The comment id of this comment. /// public string CommentId { get { return _commentId; } } /// /// The user id of the author of the comment. /// public string AuthorUserId { get { return _authorUserId; } } /// /// The username (screen name) of the author of the comment. /// public string AuthorUserName { get { return _authorUserName; } } /// /// The permalink to the comment on the photos web page. /// public Uri Permalink { get { return _permaLink; } } /// /// The date and time that the comment was created. /// public DateTime DateCreated { get { return _dateCreated; } } /// /// The comment text (can contain HTML). /// public string CommentHtml { get { return _comment; } } internal Comment(string photoId, XmlNode node) { _photoId = photoId; if( node.Attributes["id"] != null ) _commentId = node.Attributes["id"].Value; if( node.Attributes["author"] != null ) _authorUserId = node.Attributes["author"].Value; if( node.Attributes["authorname"] != null ) _authorUserName = node.Attributes["authorname"].Value; if( node.Attributes["permalink"] != null ) _permaLink = new Uri(node.Attributes["permalink"].Value); if( node.Attributes["datecreate"] != null ) _dateCreated = Utils.UnixTimestampToDate(node.Attributes["datecreate"].Value); if( node.InnerXml.Length > 0 ) _comment = node.InnerText; } } } libflickrnet-48055~2.2.0/FlickrNet/FlickrApiException.cs0000644000175000017500000000152511155417352022001 0ustar varunvarunusing System; namespace FlickrNet { /// /// Exception thrown when the Flickr API returned a specifi error code. /// public class FlickrApiException : FlickrException { private int code; private string msg = ""; internal FlickrApiException(ResponseError error) { code = error.Code; msg = error.Message; } /// /// Get the code of the Flickr error. /// public int Code { get { return code; } } /// /// Gets the verbose message returned by Flickr. /// public string Verbose { get { return msg; } } /// /// Overrides the message to return custom error message. /// public override string Message { get { return msg + " (" + code + ")"; } } } } libflickrnet-48055~2.2.0/FlickrNet/Utils.cs0000644000175000017500000002712111155417352017356 0ustar varunvarunusing System; using System.IO; using System.Collections; using System.Text; using System.Text.RegularExpressions; using System.Xml.Serialization; namespace FlickrNet { /// /// Internal class providing certain utility functions to other classes. /// internal sealed class Utils { private static readonly DateTime unixStartDate = new DateTime(1970, 1, 1, 0, 0, 0); private Utils() { } #if !WindowsCE internal static string UrlEncode(string oldString) { if( oldString == null ) return null; string a = System.Web.HttpUtility.UrlEncode(oldString); a = a.Replace("&", "%26"); a = a.Replace("=", "%3D"); a = a.Replace(" ", "%20"); return a; } #else internal static string UrlEncode(string oldString) { if (oldString == null) return String.Empty; StringBuilder sb = new StringBuilder(oldString.Length * 2); Regex reg = new Regex("[a-zA-Z0-9$-_.+!*'(),]"); foreach (char c in oldString) { if (reg.IsMatch(c.ToString())) { sb.Append(c); } else { sb.Append(ToHex(c)); } } return sb.ToString(); } private static string ToHex(char c) { return ((int)c).ToString("X"); } #endif /// /// Converts a object into a unix timestamp number. /// /// The date to convert. /// A long for the number of seconds since 1st January 1970, as per unix specification. internal static long DateToUnixTimestamp(DateTime date) { TimeSpan ts = date - unixStartDate; return (long)ts.TotalSeconds; } /// /// Converts a string, representing a unix timestamp number into a object. /// /// The timestamp, as a string. /// The object the time represents. internal static DateTime UnixTimestampToDate(string timestamp) { if( timestamp == null || timestamp.Length == 0 ) return DateTime.MinValue; return UnixTimestampToDate(long.Parse(timestamp)); } /// /// Converts a , representing a unix timestamp number into a object. /// /// The unix timestamp. /// The object the time represents. internal static DateTime UnixTimestampToDate(long timestamp) { return unixStartDate.AddSeconds(timestamp); } /// /// Utility method to convert the enum to a string. /// /// /// /// PhotoSearchExtras extras = PhotoSearchExtras.DateTaken & PhotoSearchExtras.IconServer; /// string val = Utils.ExtrasToString(extras); /// Console.WriteLine(val); /// /// outputs: "date_taken,icon_server"; /// /// /// internal static string ExtrasToString(PhotoSearchExtras extras) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if( (extras & PhotoSearchExtras.DateTaken) == PhotoSearchExtras.DateTaken ) sb.Append("date_taken"); if( (extras & PhotoSearchExtras.DateUploaded) == PhotoSearchExtras.DateUploaded ) { if( sb.Length>0 ) sb.Append(","); sb.Append("date_upload"); } if( (extras & PhotoSearchExtras.IconServer) == PhotoSearchExtras.IconServer ) { if( sb.Length>0 ) sb.Append(","); sb.Append("icon_server"); } if( (extras & PhotoSearchExtras.License) == PhotoSearchExtras.License ) { if( sb.Length>0 ) sb.Append(","); sb.Append("license"); } if( (extras & PhotoSearchExtras.OwnerName) == PhotoSearchExtras.OwnerName ) { if( sb.Length>0 ) sb.Append(","); sb.Append("owner_name"); } if( (extras & PhotoSearchExtras.OriginalFormat) == PhotoSearchExtras.OriginalFormat ) { if( sb.Length>0 ) sb.Append(","); sb.Append("original_format"); } if( (extras & PhotoSearchExtras.LastUpdated) == PhotoSearchExtras.LastUpdated ) { if( sb.Length>0 ) sb.Append(","); sb.Append("last_update"); } if( (extras & PhotoSearchExtras.Tags) == PhotoSearchExtras.Tags ) { if( sb.Length>0 ) sb.Append(","); sb.Append("tags"); } if( (extras & PhotoSearchExtras.Geo) == PhotoSearchExtras.Geo ) { if( sb.Length>0 ) sb.Append(","); sb.Append("geo"); } if( (extras & PhotoSearchExtras.MachineTags) == PhotoSearchExtras.MachineTags ) { if( sb.Length>0 ) sb.Append(","); sb.Append("machine_tags"); } if( (extras & PhotoSearchExtras.OriginalDimensions) == PhotoSearchExtras.OriginalDimensions ) { if( sb.Length>0 ) sb.Append(","); sb.Append("o_dims"); } if( (extras & PhotoSearchExtras.Views) == PhotoSearchExtras.Views ) { if( sb.Length>0 ) sb.Append(","); sb.Append("views"); } if( (extras & PhotoSearchExtras.Media) == PhotoSearchExtras.Media ) { if( sb.Length>0 ) sb.Append(","); sb.Append("media"); } return sb.ToString(); } internal static string SortOrderToString(PhotoSearchSortOrder order) { switch(order) { case PhotoSearchSortOrder.DatePostedAsc: return "date-posted-asc"; case PhotoSearchSortOrder.DatePostedDesc: return "date-posted-desc"; case PhotoSearchSortOrder.DateTakenAsc: return "date-taken-asc"; case PhotoSearchSortOrder.DateTakenDesc: return "date-taken-desc"; case PhotoSearchSortOrder.InterestingnessAsc: return "interestingness-asc"; case PhotoSearchSortOrder.InterestingnessDesc: return "interestingness-desc"; case PhotoSearchSortOrder.Relevance: return "relevance"; default: return null; } } internal static void PartialOptionsIntoArray(PartialSearchOptions options, Hashtable parameters) { if( options.MinUploadDate != DateTime.MinValue ) parameters.Add("min_uploaded_date", Utils.DateToUnixTimestamp(options.MinUploadDate).ToString()); if( options.MaxUploadDate != DateTime.MinValue ) parameters.Add("max_uploaded_date", Utils.DateToUnixTimestamp(options.MaxUploadDate).ToString()); if( options.MinTakenDate != DateTime.MinValue ) parameters.Add("min_taken_date", options.MinTakenDate.ToString("yyyy-MM-dd HH:mm:ss")); if( options.MaxTakenDate != DateTime.MinValue ) parameters.Add("max_taken_date", options.MaxTakenDate.ToString("yyyy-MM-dd HH:mm:ss")); if( options.Extras != PhotoSearchExtras.None ) parameters.Add("extras", options.ExtrasString); if( options.SortOrder != PhotoSearchSortOrder.None ) parameters.Add("sort", options.SortOrderString); if( options.PerPage > 0 ) parameters.Add("per_page", options.PerPage.ToString()); if( options.Page > 0 ) parameters.Add("page", options.Page.ToString()); if( options.PrivacyFilter != PrivacyFilter.None ) parameters.Add("privacy_filter", options.PrivacyFilter.ToString("d")); } internal static void WriteInt32(Stream s, int i) { s.WriteByte((byte) (i & 0xFF)); s.WriteByte((byte) ((i >> 8) & 0xFF)); s.WriteByte((byte) ((i >> 16) & 0xFF)); s.WriteByte((byte) ((i >> 24) & 0xFF)); } internal static void WriteString(Stream s, string str) { WriteInt32(s, str.Length); foreach (char c in str) { s.WriteByte((byte) (c & 0xFF)); s.WriteByte((byte) ((c >> 8) & 0xFF)); } } internal static void WriteAsciiString(Stream s, string str) { WriteInt32(s, str.Length); foreach (char c in str) { s.WriteByte((byte) (c & 0x7F)); } } internal static int ReadInt32(Stream s) { int i = 0, b; for (int j = 0; j < 4; j++) { b = s.ReadByte(); if (b == -1) throw new IOException("Unexpected EOF encountered"); i |= (b << (j * 8)); } return i; } internal static string ReadString(Stream s) { int len = ReadInt32(s); char[] chars = new char[len]; for (int i = 0; i < len; i++) { int hi, lo; lo = s.ReadByte(); hi = s.ReadByte(); if (lo == -1 || hi == -1) throw new IOException("Unexpected EOF encountered"); chars[i] = (char) (lo | (hi << 8)); } return new string(chars); } internal static string ReadAsciiString(Stream s) { int len = ReadInt32(s); char[] chars = new char[len]; for (int i = 0; i < len; i++) { int c = s.ReadByte(); if (c == -1) throw new IOException("Unexpected EOF encountered"); chars[i] = (char) (c & 0x7F); } return new string(chars); } private const string photoUrl = "http://farm{0}.static.flickr.com/{1}/{2}_{3}{4}.{5}"; internal static string UrlFormat(Photo p, string size, string format) { if( size == "_o" ) return UrlFormat(photoUrl, p.Farm, p.Server, p.PhotoId, p.OriginalSecret, size, format); else return UrlFormat(photoUrl, p.Farm, p.Server, p.PhotoId, p.Secret, size, format); } internal static string UrlFormat(PhotoInfo p, string size, string format) { if( size == "_o" ) return UrlFormat(photoUrl, p.Farm, p.Server, p.PhotoId, p.OriginalSecret, size, format); else return UrlFormat(photoUrl, p.Farm, p.Server, p.PhotoId, p.Secret, size, format); } internal static string UrlFormat(Photoset p, string size, string format) { return UrlFormat(photoUrl, p.Farm, p.Server, p.PrimaryPhotoId, p.Secret, size, format); } private static string UrlFormat(string format, params object[] parameters) { return String.Format(format, parameters); } private static readonly Hashtable _serializers = new Hashtable(); private static XmlSerializer GetSerializer(Type type) { if( _serializers.ContainsKey(type.Name) ) return (XmlSerializer)_serializers[type.Name]; else { XmlSerializer s = new XmlSerializer(type); _serializers.Add(type.Name, s); return s; } } /// /// Converts the response string (in XML) into the object. /// /// The response from Flickr. /// A object containing the details of the internal static Response Deserialize(string responseString) { XmlSerializer serializer = GetSerializer(typeof(FlickrNet.Response)); try { // Deserialise the web response into the Flickr response object StringReader responseReader = new StringReader(responseString); FlickrNet.Response response = (FlickrNet.Response)serializer.Deserialize(responseReader); responseReader.Close(); return response; } catch(InvalidOperationException ex) { // Serialization error occurred! throw new ResponseXmlException("Invalid response received from Flickr.", ex); } } internal static object Deserialize(System.Xml.XmlNode node, Type type) { XmlSerializer serializer = GetSerializer(type); try { // Deserialise the web response into the Flickr response object System.Xml.XmlNodeReader reader = new System.Xml.XmlNodeReader(node); object o = serializer.Deserialize(reader); reader.Close(); return o; } catch(InvalidOperationException ex) { // Serialization error occurred! throw new ResponseXmlException("Invalid response received from Flickr.", ex); } } } } libflickrnet-48055~2.2.0/FlickrNet/FlickrWebException.cs0000644000175000017500000000050611155417352022003 0ustar varunvarunusing System; namespace FlickrNet { /// /// Exception thrown when a communication error occurs with a web call. /// public class FlickrWebException : FlickrException { internal FlickrWebException(string message, Exception innerException) : base(message, innerException) { } } } libflickrnet-48055~2.2.0/FlickrNet/Tags.cs0000644000175000017500000000346311155417352017157 0ustar varunvarunusing System; using System.Xml; namespace FlickrNet { /// /// A simple tag class, containing a tag name and optional count (for ) /// public class Tag { private string _tagName; private int _count; /// /// The name of the tag. /// public string TagName { get { return _tagName; } } /// /// The poularity of the tag. Will be 0 where the popularity is not retreaved. /// public int Count { get { return _count; } } internal Tag(XmlNode node) { if( node.Attributes["count"] != null ) _count = Convert.ToInt32(node.Attributes["count"].Value); _tagName = node.InnerText; } internal Tag(string tagName, int count) { _tagName = tagName; _count = count; } } /// /// Raw tags, as returned by the method. /// public class RawTag { private string _cleanTag; private string[] _rawTags = new string[0]; /// /// An array of strings containing the raw tags returned by the method. /// public string[] RawTags { get { return _rawTags; } } /// /// The clean tag. /// public string CleanTag { get { return _cleanTag; } } internal RawTag(XmlNode node) { if( node.Attributes.GetNamedItem("clean") == null ) throw new ResponseXmlException("clean attribute not found"); _cleanTag = node.Attributes.GetNamedItem("clean").Value; XmlNodeList list = node.SelectNodes("raw"); _rawTags = new string[list.Count]; for(int i = 0; i < list.Count; i++) { XmlNode rawNode = list[i]; _rawTags[i] = rawNode.InnerText; } } } } libflickrnet-48055~2.2.0/FlickrNet/DateGranularity.cs0000644000175000017500000000127711155417352021361 0ustar varunvarunusing System; namespace FlickrNet { /// /// DateGranularity, used for setting taken date in /// or . /// public enum DateGranularity { /// /// The date specified is the exact date the photograph was taken. /// FullDate = 0, /// /// The date specified is the year and month the photograph was taken. /// YearMonthOnly = 4, /// /// The date specified is the year the photograph was taken. /// YearOnly = 6 } } libflickrnet-48055~2.2.0/FlickrNet/ApiKeyRequiredException.cs0000644000175000017500000000054011155417352023014 0ustar varunvarunusing System; namespace FlickrNet { /// /// Exception thrown is no API key is supplied. /// public class ApiKeyRequiredException : FlickrException { /// /// Default constructor. /// public ApiKeyRequiredException() : base("API Key is required for all method calls") { } } } libflickrnet-48055~2.2.0/FlickrNet/Context.cs0000644000175000017500000001032211155417352017675 0ustar varunvarunusing System; using System.Collections; using System.Xml.Serialization; using System.Xml.Schema; using System.Xml; namespace FlickrNet { /// /// The context of the current photo, as returned by /// , /// /// and methods. /// public class Context { /// /// The number of photos in the current context, e.g. Group, Set or photostream. /// public long Count; /// /// The next photo in the context. /// public ContextPhoto NextPhoto; /// /// The previous photo in the context. /// public ContextPhoto PreviousPhoto; } /// /// Temporary class used to excapsulate the context count property. /// [System.Serializable] public class ContextCount { /// /// Default constructor. /// public ContextCount() { } /// /// The number of photos in the context. /// [XmlText()] public long Count; } /// /// The next (or previous) photo in the current context. /// [System.Serializable] public class ContextPhoto { /// /// The id of the next photo. Will be "0" if this photo is the last. /// [XmlAttribute("id", Form=XmlSchemaForm.Unqualified)] public string PhotoId; /// /// The secret for the photo. /// [XmlAttribute("secret", Form=XmlSchemaForm.Unqualified)] public string Secret; /// /// The title of the next photo in context. /// [XmlAttribute("title", Form=XmlSchemaForm.Unqualified)] public string Title; /// /// The URL, in the given context, for the next or previous photo. /// [XmlAttribute("url", Form=XmlSchemaForm.Unqualified)] public string Url; /// /// The URL for the thumbnail of the photo. /// [XmlAttribute("thumb", Form=XmlSchemaForm.Unqualified)] public string Thumbnail; } /// /// All contexts that a photo is in. /// public class AllContexts { private ContextSet[] _sets; private ContextGroup[] _groups; /// /// An array of objects for the current photo. /// public ContextSet[] Sets { get { return _sets; } } /// /// An array of objects for the current photo. /// public ContextGroup[] Groups { get { return _groups; } } internal AllContexts(XmlElement[] elements) { ArrayList sets = new ArrayList(); ArrayList groups = new ArrayList(); if( elements == null ) { _sets = new ContextSet[0]; _groups = new ContextGroup[0]; return; } foreach(XmlElement element in elements) { if( element.Name == "set" ) { ContextSet aset = new ContextSet(); aset.PhotosetId = element.Attributes["id"].Value; aset.Title = element.Attributes["title"].Value; sets.Add(aset); } if( element.Name == "pool" ) { ContextGroup agroup = new ContextGroup(); agroup.GroupId = element.Attributes["id"].Value; agroup.Title = element.Attributes["title"].Value; groups.Add(agroup); } } _sets = new ContextSet[sets.Count]; sets.CopyTo(_sets); _groups = new ContextGroup[groups.Count]; groups.CopyTo(_groups); } } /// /// A set context for a photo. /// public class ContextSet { /// /// The Photoset ID of the set the selected photo is in. /// public string PhotosetId; /// /// The title of the set the selected photo is in. /// public string Title; } /// /// A group context got a photo. /// public class ContextGroup { /// /// The Group ID for the group that the selected photo is in. /// public string GroupId; /// /// The title of the group that then selected photo is in. /// public string Title; } } libflickrnet-48055~2.2.0/FlickrNet/FlickrConfigurationSettings.cs0000644000175000017500000002125611155417352023744 0ustar varunvarun#if !WindowsCE using System; using System.Collections.Specialized ; using System.Xml; namespace FlickrNet { /// /// Configuration settings for the Flickr.Net API Library. /// /// ///

First, register the configuration section in the configSections section:

///

<configSections> /// <section name="flickrNet" type="FlickrNet.FlickrConfigurationManager,FlickrNet"/> /// </configSections> ///

///

/// Next, include the following config section: ///

///

/// <flickrNet /// apiKey="1234567890abc" // optional /// secret="2134123" // optional /// token="234234" // optional /// cacheSize="1234" // optional, in bytes (defaults to 50 * 1024 * 1024 = 50MB) /// cacheTimeout="[d.]HH:mm:ss" // optional, defaults to 1 day (1.00:00:00) - day component is optional /// // e.g. 10 minutes = 00:10:00 or 1 hour = 01:00:00 or 2 days, 12 hours = 2.12:00:00 /// > /// <proxy // proxy element is optional, but if included the attributes below are mandatory as mentioned /// ipaddress="127.0.0.1" // mandatory /// port="8000" // mandatory /// username="username" // optional, but must have password if included /// password="password" // optional, see username /// domain="domain" // optional, used for Microsoft authenticated proxy servers /// /> /// </flickrNet> ///

///
internal class FlickrConfigurationSettings { #region Private Variables private string _apiKey; private string _apiSecret; private string _apiToken; private int _cacheSize; private TimeSpan _cacheTimeout = TimeSpan.MinValue; private string _proxyAddress; private int _proxyPort; private bool _proxyDefined; private string _proxyUsername; private string _proxyPassword; private string _proxyDomain; private string _cacheLocation; private bool _cacheDisabled; private SupportedService _service; #endregion #region FlickrConfigurationSettings Constructor /// /// Loads FlickrConfigurationSettings with the settings in the config file. /// /// XmlNode containing the configuration settings. public FlickrConfigurationSettings(XmlNode configNode) { if( configNode == null ) throw new ArgumentNullException("configNode"); foreach(XmlAttribute attribute in configNode.Attributes) { switch(attribute.Name) { case "apiKey": _apiKey = attribute.Value; break; case "secret": _apiSecret = attribute.Value; break; case "token": _apiToken = attribute.Value; break; case "cacheDisabled": try { _cacheDisabled = bool.Parse(attribute.Value); break; } catch(FormatException ex) { throw new System.Configuration.ConfigurationException("cacheDisbled should be \"true\" or \"false\"", ex, configNode); } case "cacheSize": try { _cacheSize = int.Parse(attribute.Value); break; } catch(FormatException ex) { throw new System.Configuration.ConfigurationException("cacheSize should be integer value", ex, configNode); } case "cacheTimeout": try { _cacheTimeout = TimeSpan.Parse(attribute.Value); break; } catch(FormatException ex) { throw new System.Configuration.ConfigurationException("cacheTimeout should be TimeSpan value ([d:]HH:mm:ss)", ex, configNode); } case "cacheLocation": _cacheLocation = attribute.Value; break; case "service": try { _service = (SupportedService)Enum.Parse(typeof(SupportedService), attribute.Value, true); break; } catch(ArgumentException ex) { throw new System.Configuration.ConfigurationException("service must be one of the supported services (See SupportedServices enum)", ex, configNode); } default: throw new System.Configuration.ConfigurationException(String.Format("Unknown attribute '{0}' in flickrNet node", attribute.Name), configNode); } } foreach(XmlNode node in configNode.ChildNodes) { switch(node.Name) { case "proxy": ProcessProxyNode(node, configNode); break; default: throw new System.Configuration.ConfigurationException(String.Format("Unknown node '{0}' in flickrNet node", node.Name), configNode); } } } #endregion #region ProcessProxyNode - Constructor Helper Method private void ProcessProxyNode(XmlNode proxy, XmlNode configNode) { if( proxy.ChildNodes.Count > 0 ) throw new System.Configuration.ConfigurationException("proxy element does not support child elements"); _proxyDefined = true; foreach(XmlAttribute attribute in proxy.Attributes) { switch(attribute.Name) { case "ipaddress": _proxyAddress = attribute.Value; break; case "port": try { _proxyPort = int.Parse(attribute.Value); } catch(FormatException ex) { throw new System.Configuration.ConfigurationException("proxy port should be integer value", ex, configNode); } break; case "username": _proxyUsername = attribute.Value; break; case "password": _proxyPassword = attribute.Value; break; case "domain": _proxyDomain = attribute.Value; break; default: throw new System.Configuration.ConfigurationException(String.Format("Unknown attribute '{0}' in flickrNet/proxy node", attribute.Name), configNode); } } if( _proxyAddress == null ) throw new System.Configuration.ConfigurationException("proxy ipaddress is mandatory if you specify the proxy element"); if( _proxyPort == 0 ) throw new System.Configuration.ConfigurationException("proxy port is mandatory if you specify the proxy element"); if( _proxyUsername != null && _proxyPassword == null ) throw new System.Configuration.ConfigurationException("proxy password must be specified if proxy username is specified"); if( _proxyUsername == null && _proxyPassword != null ) throw new System.Configuration.ConfigurationException("proxy username must be specified if proxy password is specified"); if( _proxyDomain != null && _proxyUsername == null ) throw new System.Configuration.ConfigurationException("proxy username/password must be specified if proxy domain is specified"); } #endregion #region Public Properties /// /// API key. Null if not present. Optional. /// public string ApiKey { get { return _apiKey; } } /// /// Shared Secret. Null if not present. Optional. /// public string SharedSecret { get { return _apiSecret; } } /// /// API token. Null if not present. Optional. /// public string ApiToken { get { return _apiToken; } } /// /// Cache size in bytes. 0 if not present. Optional. /// public bool CacheDisabled { get { return _cacheDisabled; } } /// /// Cache size in bytes. 0 if not present. Optional. /// public int CacheSize { get { return _cacheSize; } } /// /// Cache timeout. Equals TimeSpan.MinValue is not present. Optional. /// public TimeSpan CacheTimeout { get { return _cacheTimeout; } } public string CacheLocation { get { return _cacheLocation; } } public SupportedService Service { get { return _service; } } /// /// If the proxy is defined in the configuration section. /// public bool IsProxyDefined { get { return _proxyDefined; } } /// /// If is true then this is mandatory. /// public string ProxyIPAddress { get { return _proxyAddress; } } /// /// If is true then this is mandatory. /// public int ProxyPort { get { return _proxyPort; } } /// /// The username for the proxy. Optional. /// public string ProxyUsername { get { return _proxyUsername; } } /// /// The password for the proxy. Optional. /// public string ProxyPassword { get { return _proxyPassword; } } /// /// The domain for the proxy. Optional. /// public string ProxyDomain { get { return _proxyDomain; } } #endregion } } #endiflibflickrnet-48055~2.2.0/FlickrNet/UploadProgressEvent.cs0000644000175000017500000000125711155417352022233 0ustar varunvarunusing System; namespace FlickrNet { /// /// Event arguments for a event. /// public class UploadProgressEventArgs : EventArgs { private bool _uploadComplete; private int _bytes; /// /// Number of bytes transfered so far. /// public int Bytes { get { return _bytes; } } /// /// True if all bytes have been uploaded. /// public bool UploadComplete { get { return _uploadComplete; } } internal UploadProgressEventArgs(int bytes, bool complete) { _bytes = bytes; _uploadComplete = complete; } } } libflickrnet-48055~2.2.0/FlickrNet/AuthenticationRequiredException.cs0000644000175000017500000000056211155417352024615 0ustar varunvarunusing System; namespace FlickrNet { /// /// Exception thrown when method requires authentication but no authentication token is supplied. /// public class AuthenticationRequiredException : FlickrException { internal AuthenticationRequiredException() : base("Method requires authentication but no token supplied.") { } } } libflickrnet-48055~2.2.0/FlickrNet/PhotoDates.cs0000644000175000017500000000355411155417352020334 0ustar varunvarunusing System; using System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// The date information for a photo. /// [System.Serializable] public class PhotoDates { /// /// The date the photo was posted (or uploaded). /// [XmlIgnore] public DateTime PostedDate { get { return Utils.UnixTimestampToDate(raw_posted); } } /// /// The raw timestamp for the date the photo was posted. /// /// Use instead. [XmlAttribute("posted", Form=XmlSchemaForm.Unqualified)] public long raw_posted; /// /// The date the photo was taken. /// [XmlIgnore] public DateTime TakenDate { get { if (raw_taken == null || raw_taken.Length == 0) return DateTime.MinValue; return DateTime.Parse(raw_taken); } } /// /// The raw timestamp for the date the photo was taken. /// /// Use instead. [XmlAttribute("taken", Form=XmlSchemaForm.Unqualified)] public string raw_taken; /// /// The granularity of the taken date. /// [XmlAttribute("takengranularity", Form=XmlSchemaForm.Unqualified)] public int TakenGranularity; /// /// The raw timestamp for the date the photo was last updated. /// [XmlAttribute("lastupdate", Form=XmlSchemaForm.Unqualified)] public long raw_lastupdate; /// /// The date the photo was last updated (includes comments, tags, title, description etc). /// [XmlIgnore()] public DateTime LastUpdated { get{ return Utils.UnixTimestampToDate(raw_lastupdate); } } } } libflickrnet-48055~2.2.0/FlickrNet/Categories.cs0000644000175000017500000000457011155417352020346 0ustar varunvarunusing System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// Contains details of a category, including groups belonging to the category and sub categories. /// [System.Serializable] public class Category { /// /// The name for the category. /// [XmlAttribute("name", Form=XmlSchemaForm.Unqualified)] public string CategoryName; /// /// A forward slash delimited list of the parents of the current group. /// /// /// Can be matched against the list of PathIds to jump directly to a parent group. /// /// /// Group Id 91, Romance will return "/Life/Romance" as the Path and "/90/91" as its PathIds /// [XmlAttribute("path", Form=XmlSchemaForm.Unqualified)] public string Path; /// /// A forward slash delimited list of the ids of the parents of the current group. /// /// /// Can be matched against the Path to jump directly to a parent group. /// /// /// Group Id 91, Romance will return "/Life/Romance" as the Path and "/90/91" as its PathIds /// [XmlAttribute("pathids", Form=XmlSchemaForm.Unqualified)] public string PathIds; /// /// An array of items. /// [XmlElement("subcat", Form=XmlSchemaForm.Unqualified)] public SubCategory[] SubCategories; /// /// An array of items, listing the groups within this category. /// [XmlElement("group", Form=XmlSchemaForm.Unqualified)] public Group[] Groups; } /// /// Holds details of a sub category, including its id, name and the number of groups in it. /// [System.Serializable] public class SubCategory { /// /// The id of the category. /// [XmlAttribute("id", Form=XmlSchemaForm.Unqualified)] public long SubCategoryId; /// /// The name of the category. /// [XmlAttribute("name", Form=XmlSchemaForm.Unqualified)] public string SubCategoryName; /// /// The number of groups found within the category. /// [XmlAttribute("count", Form=XmlSchemaForm.Unqualified)] public long GroupCount; } }libflickrnet-48055~2.2.0/FlickrNet/Uploader.cs0000644000175000017500000000262011155417352020026 0ustar varunvarunusing System; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace FlickrNet { /// /// Information returned by the UploadPicture url. /// [XmlRoot("rsp")] public class Uploader { private ResponseStatus _status; private string _photoId; private string _ticketId; private ResponseError _error; /// /// The status of the upload, either "ok" or "fail". /// [XmlAttribute("stat", Form=XmlSchemaForm.Unqualified)] public ResponseStatus Status { get { return _status; } set { _status = value; } } /// /// If the upload succeeded then this contains the id of the photo. Otherwise it will be zero. /// [XmlElement("photoid", Form=XmlSchemaForm.Unqualified)] public string PhotoId { get { return _photoId; } set { _photoId = value; } } /// /// The ticket id, if using Asynchronous uploading. /// [XmlElement("ticketid", Form=XmlSchemaForm.Unqualified)] public string TicketId { get { return _ticketId; } set { _ticketId = value; } } /// /// Contains the error returned if the upload is unsuccessful. /// [XmlElement("err", Form=XmlSchemaForm.Unqualified)] public ResponseError Error { get { return _error; } set { _error = value; } } } } libflickrnet-48055~2.2.0/FlickrNet/PhotoInfoUsage.cs0000644000175000017500000000234011155417352021144 0ustar varunvarunusing System; using System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// Summary description for PhotoInfoUsage. /// [System.Serializable] public class PhotoInfoUsage { private int _canBlog; private int _canDownload; private int _canPrint; /// /// Specifies if the user allows blogging of this photos. 1 = Yes, 0 = No. /// [XmlAttribute("canblog", Form=XmlSchemaForm.Unqualified)] public int CanBlog { get { return _canBlog; } set { _canBlog = value; } } /// /// Specifies if the user allows downloading of this photos. 1 = Yes, 0 = No. /// [XmlAttribute("candownload", Form=XmlSchemaForm.Unqualified)] public int CanDownload { get { return _canDownload; } set { _canDownload = value; } } /// /// Specifies if the user allows printing of this photos. 1 = Yes, 0 = No. /// [XmlAttribute("canprint", Form=XmlSchemaForm.Unqualified)] public int CanPrint { get { return _canPrint; } set { _canPrint = value; } } /// /// Usage allowances of a photo, based on the users permissions. /// public PhotoInfoUsage() { } } } libflickrnet-48055~2.2.0/FlickrNet/Photo.cs0000644000175000017500000002747311155417352017361 0ustar varunvarunusing System; using System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// [System.Serializable] public class Photo { private string _photoId; private string _userId; private string _secret; private string _server; private string _farm; private string _title; private int _isPublic; private int _isFriend; private int _isFamily; private int _isPrimary; private string _license; private string _ownerName; private string _iconServer; private string _originalFormat; private string _originalSecret; private string _cleanTags; private string _machineTags; private decimal _latitude; private decimal _longitude; private GeoAccuracy _accuracy; private int _originalWidth = -1; private int _originalHeight = -1; private int _views = -1; private string _media; private string _mediaStatus; private string _placeId; private string _woeId; /// [XmlAttribute("id", Form=XmlSchemaForm.Unqualified)] public string PhotoId { get { return _photoId; } set { _photoId = value; } } /// [XmlAttribute("owner", Form=XmlSchemaForm.Unqualified)] public string UserId { get { return _userId; } set { _userId = value; } } /// [XmlAttribute("secret", Form=XmlSchemaForm.Unqualified)] public string Secret { get { return _secret; } set { _secret = value; } } /// [XmlAttribute("server", Form=XmlSchemaForm.Unqualified)] public string Server { get { return _server; } set { _server = value; } } /// [XmlAttribute("farm", Form=XmlSchemaForm.Unqualified)] public string Farm { get { return _farm; } set { _farm = value; } } /// [XmlAttribute("title", Form=XmlSchemaForm.Unqualified)] public string Title { get { return _title; } set { _title = value; } } /// [XmlAttribute("ispublic", Form=XmlSchemaForm.Unqualified)] public int IsPublic { get { return _isPublic; } set { _isPublic = value; } } /// [XmlAttribute("isfriend", Form=XmlSchemaForm.Unqualified)] public int IsFriend { get { return _isFriend; } set { _isFriend = value; } } /// [XmlAttribute("isfamily", Form=XmlSchemaForm.Unqualified)] public int IsFamily { get { return _isFamily; } set { _isFamily = value; } } /// [XmlAttribute("isprimary", Form=XmlSchemaForm.Unqualified)] public int IsPrimary { get { return _isPrimary; } set { _isPrimary = value; } } /// [XmlAttribute("license", Form=XmlSchemaForm.Unqualified)] public string License { get { return _license; } set { _license = value; } } /// /// The width of the original image. /// Only returned if is specified. /// [XmlAttribute("o_width")] public int OriginalWidth { get { return _originalWidth; } set { _originalWidth = value; } } /// /// The height of the original image. /// Only returned if is specified. /// [XmlAttribute("o_height")] public int OriginalHeight { get { return _originalHeight; } set { _originalHeight = value; } } /// [XmlAttribute("dateupload", Form=XmlSchemaForm.Unqualified)] public string dateupload_raw; /// /// Converts the raw dateupload field to a . /// [XmlIgnore] public DateTime DateUploaded { get { return Utils.UnixTimestampToDate(dateupload_raw); } } /// /// Converts the raw lastupdate field to a . /// Returns if the raw value was not returned. /// [XmlIgnore] public DateTime LastUpdated { get { return Utils.UnixTimestampToDate(lastupdate_raw); } } /// [XmlAttribute("lastupdate", Form=XmlSchemaForm.Unqualified)] public string lastupdate_raw; /// [XmlAttribute("dateadded", Form = XmlSchemaForm.Unqualified)] public string dateadded_raw; /// /// Converts the raw DateAdded field to a . /// Returns if the raw value was not returned. /// [XmlIgnore] public DateTime DateAdded { get { return Utils.UnixTimestampToDate(dateadded_raw); } } /// [XmlAttribute("datetaken", Form=XmlSchemaForm.Unqualified)] public string datetaken_raw; /// /// Converts the raw datetaken field to a . /// Returns if the raw value was not returned. /// [XmlIgnore] public DateTime DateTaken { get { if( datetaken_raw == null || datetaken_raw.Length == 0 ) return DateTime.MinValue; return System.DateTime.Parse(datetaken_raw); } } /// [XmlAttribute("ownername", Form=XmlSchemaForm.Unqualified)] public string OwnerName { get { return _ownerName; } set { _ownerName = value; } } /// [XmlAttribute("iconserver", Form=XmlSchemaForm.Unqualified)] public string IconServer { get { return _iconServer; } set { _iconServer = value; } } /// /// Optional extra field containing the original format (jpg, png etc) of the /// photo. /// [XmlAttribute("originalformat", Form=XmlSchemaForm.Unqualified)] public string OriginalFormat { get { return _originalFormat; } set { _originalFormat = value; } } /// /// Optional extra field containing the original 'secret' of the /// photo used for forming the Url. /// [XmlAttribute("originalsecret", Form=XmlSchemaForm.Unqualified)] public string OriginalSecret { get { return _originalSecret; } set { _originalSecret = value; } } /// /// Undocumented tags atrribute. Renamed to CleanTags. /// [Obsolete("Renamed to CleanTags, as the tags are clean, not raw")] public string RawTags { get { return _cleanTags; } set { _cleanTags = value; } } /// /// Tags, in their clean format (exception is machine tags which retain their machine encoding). /// [XmlAttribute("tags", Form=XmlSchemaForm.Unqualified)] public string CleanTags { get { return _cleanTags; } set { _cleanTags = value; } } /// /// Machine tags /// [XmlAttribute("machine_tags", Form=XmlSchemaForm.Unqualified)] public string MachineTags { get { return _machineTags; } set { _machineTags = value; } } /// /// The url to the web page for this photo. Uses the users userId, not their web alias, but /// will still work. /// [XmlIgnore()] public string WebUrl { get { return string.Format("http://www.flickr.com/photos/{0}/{1}/", UserId, PhotoId); } } /// /// The URL for the square thumbnail of a photo. /// [XmlIgnore()] public string SquareThumbnailUrl { get { return Utils.UrlFormat(this, "_s", "jpg"); } } /// /// The URL for the thumbnail of a photo. /// [XmlIgnore()] public string ThumbnailUrl { get { return Utils.UrlFormat(this, "_t", "jpg"); } } /// /// The URL for the small copy of a photo. /// [XmlIgnore()] public string SmallUrl { get { return Utils.UrlFormat(this, "_m", "jpg"); } } /// /// The URL for the medium copy of a photo. /// /// There is a chance that extremely small images will not have a medium copy. /// Use to get the available URLs for a photo. [XmlIgnore()] public string MediumUrl { get { return Utils.UrlFormat(this, "", "jpg"); } } /// /// The URL for the large copy of a photo. /// /// There is a chance that small images will not have a large copy. /// Use to get the available URLs for a photo. [XmlIgnore()] public string LargeUrl { get { return Utils.UrlFormat(this, "_b", "jpg"); } } /// /// If was returned then this will contain the url of the original file. /// [XmlIgnore()] public string OriginalUrl { get { if( OriginalFormat == null || OriginalFormat.Length == 0 ) throw new InvalidOperationException("No original format information available."); return Utils.UrlFormat(this, "_o", OriginalFormat); } } /// /// Latitude. Will be 0 if Geo extras not specified. /// [XmlAttribute("latitude", Form=XmlSchemaForm.Unqualified)] public decimal Latitude { get { return _latitude; } set { _latitude = value; } } /// /// Longitude. Will be 0 if not specified. /// [XmlAttribute("longitude", Form=XmlSchemaForm.Unqualified)] public decimal Longitude { get { return _longitude; } set { _longitude = value; } } /// /// The Place ID. Will be null if is not specified in the search. /// [XmlAttribute("place_id", Form=XmlSchemaForm.Unqualified)] public string PlaceId { get { return _placeId; } set { _placeId = value; } } /// /// The WOE (Where On Earth) ID. Will be null if is not specified in the search. /// [XmlAttribute("woeid", Form=XmlSchemaForm.Unqualified)] public string WoeId { get { return _woeId; } set { _woeId = value; } } /// /// Geo-location accuracy. A value of None means that the information was not returned. /// [XmlAttribute("accuracy", Form=XmlSchemaForm.Unqualified)] public GeoAccuracy Accuracy { get { return _accuracy; } set { _accuracy = value; } } /// /// The number of views for this photo. Only returned if PhotoSearchExtras.Views is set. /// [XmlAttribute("views", Form=XmlSchemaForm.Unqualified)] public int Views { get { return _views; } set { _views = value; } } /// /// The media format for this photo. Only returned if PhotoSearchExtras.Media is set. /// [XmlAttribute("media", Form=XmlSchemaForm.Unqualified)] public string Media { get { return _media; } set { _media = value; } } /// /// The status of the media for this photo. Only returned if PhotoSearchExtras.Media is set. /// [XmlAttribute("media_status", Form=XmlSchemaForm.Unqualified)] public string MediaStatus { get { return _mediaStatus; } set { _mediaStatus = value; } } /// /// A helper method which tries to guess if a large image will be available for this photograph /// based on the original dimensions returned with the photo. /// [XmlIgnore()] public bool DoesLargeExist { get { if( _originalHeight < 0 ) throw new InvalidOperationException("Original Dimensions are not available"); if( _originalHeight > 1280 || _originalWidth > 1280 ) return true; else return false; } } /// /// A helper method which tries to guess if a medium image will be available for this photograph /// based on the original dimensions returned with the photo. /// [XmlIgnore()] public bool DoesMediumExist { get { if( _originalHeight < 0 ) throw new InvalidOperationException("Original Dimensions are not available"); if( _originalHeight > 500 || _originalWidth > 500 ) return true; else return false; } } } } libflickrnet-48055~2.2.0/FlickrNet/LockFile.cs0000644000175000017500000000477011155417352017753 0ustar varunvarunusing System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Threading; namespace FlickrNet { /// /// A non-reentrant mutex that is implemented using /// a lock file, and thus works across processes, /// sessions, and machines (as long as the underlying /// FS provides robust r/w locking). /// /// To use: /// /// FileLock fLock = new FileLock(@"c:\foo\my.lock"); /// /// using (fLock.Acquire()) /// { /// // protected operations /// } /// internal class LockFile { private readonly string filepath; private readonly DisposeHelper disposeHelper; private Stream stream; public LockFile(string filepath) { this.filepath = filepath; this.disposeHelper = new DisposeHelper(this); } public IDisposable Acquire() { string dir = Path.GetDirectoryName(filepath); lock (this) { #if !WindowsCE while (stream != null) Monitor.Wait(this); #endif while (true) { if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); try { Debug.Assert(stream == null, "Stream was not null--programmer error"); stream = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None, 8, false); return disposeHelper; } catch (IOException ioe) { int errorCode = SafeNativeMethods.GetErrorCode(ioe); switch (errorCode) { case 32: case 33: case 32 | 0x1620: case 33 | 0x1620: Thread.Sleep(50); continue; default: throw; } } } } } internal void Release() { lock (this) { #if !WindowsCE // Doesn't hurt to pulse. Note that waiting threads will not actually // continue to execute until this critical section is exited. Monitor.PulseAll(this); #endif if (stream == null) throw new InvalidOperationException("Tried to dispose a FileLock that was not owned"); try { stream.Close(); try { File.Delete(filepath); } catch(IOException) { /* could fail if already acquired elsewhere */ } } finally { stream = null; } } } private class DisposeHelper : IDisposable { private readonly LockFile lockFile; public DisposeHelper(LockFile lockFile) { this.lockFile = lockFile; } public void Dispose() { lockFile.Release(); } } } } libflickrnet-48055~2.2.0/FlickrNet/Place.cs0000644000175000017500000000723511155417352017306 0ustar varunvarunusing System; using System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// /// public class Places : IXmlSerializable { private Place[] _places = new Place[0]; /// /// /// public Place[] PlacesCollection { get { return _places; } set { _places = value; } } void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { throw new NotImplementedException(); } XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { int count = int.Parse(reader.GetAttribute("total")); if( count == 0 ) return; _places = new Place[count]; reader.Read(); for(int i = 0; i < count; i++) { _places[i] = new Place(); IXmlSerializable ser = (IXmlSerializable)_places[i]; ser.ReadXml(reader); } reader.Read(); } } /// /// Summary description for Place. /// public class Place : IXmlSerializable { private string _placeId; /// /// The unique id for this place. /// public string PlaceId { get { return _placeId; } } private string _placeUrl; /// /// The web page URL that corresponds to this place. /// public string PlaceUrl { get { return _placeUrl; } } private string _placeType; /// /// The 'type' of this place, e.g. Region, Country etc. /// public string PlaceType { get { return _placeType; } } private string _woeId; /// /// The WOE id for the locality. /// public string WoeId { get { return _woeId; } } private string _description; /// /// The description of this place, where provided. /// public string Description { get { return _description; } } private decimal _latitude; private decimal _longitude; /// /// The latitude of this place. /// public decimal Latitude { get { return _latitude; } } /// /// The longitude of this place. /// public decimal Longitude { get { return _longitude; } } /// /// Default constructor. /// public Place() { } internal Place(System.Xml.XmlReader reader) { IXmlSerializable x = (IXmlSerializable)this; x.ReadXml(reader); } /// /// Not Implemented /// /// /// void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { throw new NotImplementedException(); } /// /// Always returns null. /// /// System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() { return null; } /// /// Serializes the XML to an instance. /// /// void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { _description = reader.GetAttribute("name"); _placeId = reader.GetAttribute("place_id"); _placeUrl = reader.GetAttribute("place_url"); _placeType = reader.GetAttribute("place_type"); _woeId = reader.GetAttribute("woeid"); string dec = reader.GetAttribute("latitude"); if( dec != null && dec.Length > 0 ) { _latitude = decimal.Parse(dec, System.Globalization.NumberFormatInfo.InvariantInfo); } dec = reader.GetAttribute("longitude"); if( dec != null && dec.Length > 0 ) { _longitude = decimal.Parse(dec, System.Globalization.NumberFormatInfo.InvariantInfo); } reader.Read(); } } } libflickrnet-48055~2.2.0/FlickrNet/..svnbridge/0000755000175000017500000000000011155417352020043 5ustar varunvarunlibflickrnet-48055~2.2.0/FlickrNet/..svnbridge/.svnbridge0000644000175000017500000000041311155417352022025 0ustar varunvarunsvn:ignorebin obj libflickrnet-48055~2.2.0/FlickrNet/Location.cs0000644000175000017500000000531011155417352020022 0ustar varunvarunusing System; using System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// Summary description for Location. /// public class Location : IXmlSerializable { private string _placeId; /// /// The unique id for this place. /// public string PlaceId { get { return _placeId; } } private string _placeUrl; /// /// The web page URL that corresponds to this place. /// public string PlaceUrl { get { return _placeUrl; } } private string _placeType; /// /// The 'type' of this place, e.g. Region, Country etc. /// public string PlaceType { get { return _placeType; } } private string _woeId; /// /// The WOE id for the locality. /// public string WoeId { get { return _woeId; } } private Place _locality; private Place _county; private Place _region; private Place _country; /// /// The Locality of this place. /// public Place Locality { get { return _locality; } } /// /// The County of this place. /// public Place County { get { return _county; } } /// /// The region of this place. /// public Place Region { get { return _region; } } /// /// The country of this place. /// public Place Country { get { return _country; } } private decimal _longitude; private decimal _latitude; /// /// The longitude of this place. /// public decimal Longitude { get { return _longitude; } } /// /// The latitude of this place. /// public decimal Latitude { get { return _longitude; } } void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { throw new NotImplementedException(); } XmlSchema IXmlSerializable.GetSchema() { // TODO: Add Location.GetSchema implementation return null; } void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { _placeId = reader.GetAttribute("place_id"); _placeUrl = reader.GetAttribute("place_url"); _placeType = reader.GetAttribute("place_type"); _woeId = reader.GetAttribute("woeid"); string dec = reader.GetAttribute("latitude"); if( dec != null && dec.Length > 0 ) { _latitude = decimal.Parse(dec); } dec = reader.GetAttribute("longitude"); if( dec != null && dec.Length > 0 ) { _longitude = decimal.Parse(dec); } reader.Read(); _locality = new Place(reader); _county = new Place(reader); _region = new Place(reader); _country = new Place(reader); } } } libflickrnet-48055~2.2.0/FlickrNet/PhotoLocation.cs0000644000175000017500000000631211155417352021037 0ustar varunvarunusing System; using System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// Summary description for PhotoLocation. /// public class PhotoLocation { private double _latitude; private double _longitude; private GeoAccuracy _accuracy; private string _placeId; private PlaceInformation _locality; private PlaceInformation _county; private PlaceInformation _region; private PlaceInformation _country; /// /// Default constructor /// public PhotoLocation() { } /// /// The latitude of the photo. /// [XmlAttribute("latitude", Form=XmlSchemaForm.Unqualified)] public double Latitude { get { return _latitude; } set { _latitude = value; } } /// /// The longitude of the photo. /// [XmlAttribute("longitude", Form=XmlSchemaForm.Unqualified)] public double Longitude { get { return _longitude; } set { _longitude = value; } } /// /// The accuracy of the location information. See for accuracy levels. /// [XmlAttribute("accuracy", Form=XmlSchemaForm.Unqualified)] public GeoAccuracy Accuracy { get { return _accuracy; } set { _accuracy = value; } } /// /// The Place ID of the geolocation of this photo. /// [XmlAttribute("place_id")] public string PlaceId { get { return _placeId; } set { _placeId = value; } } /// /// The locality for the geolocation for this photo. May be null. /// [XmlElementAttribute("locality")] public PlaceInformation Locality { get { return _locality; } set { _locality = value; } } /// /// The county for the geolocation for this photo. May be null. /// [XmlElementAttribute("county")] public PlaceInformation County { get { return _county; } set { _county = value; } } /// /// The region for the geolocation for this photo. May be null. /// [XmlElementAttribute("region")] public PlaceInformation Region { get { return _region; } set { _region = value; } } /// /// The country for the geolocation for this photo. May be null. /// [XmlElementAttribute("country")] public PlaceInformation Country { get { return _country; } set { _country = value; } } } /// /// Contains information about the 'Place' data for a geotagged photo. /// /// /// This data contains its 'place id' as well as names and place ids for its containing regions (county, region, country etc). /// public class PlaceInformation { private string _placeId; private string _placeName; /// /// The ID for this particular place. /// [XmlAttribute("place_id")] public string PlaceId { get { return _placeId; } set { _placeId = value; } } /// /// The name of this particular place. /// [XmlText()] public string PlaceName { get { return _placeName; } set { _placeName = value; } } } } libflickrnet-48055~2.2.0/FlickrNet/PhotoSearchOptions.cs0000644000175000017500000003063011155417352022050 0ustar varunvarunusing System; namespace FlickrNet { /// /// Summary description for PhotoSearchOptions. /// [Serializable] public class PhotoSearchOptions { private string _userId; private string _tags; private TagMode _tagMode = TagMode.None; private string _machineTags; private MachineTagMode _machineTagMode = MachineTagMode.None; private string _text; private DateTime _minUploadDate = DateTime.MinValue; private DateTime _maxUploadDate = DateTime.MinValue; private DateTime _minTakenDate = DateTime.MinValue; private DateTime _maxTakenDate = DateTime.MinValue; private System.Collections.ArrayList _licenses = new System.Collections.ArrayList(); private PhotoSearchExtras _extras = PhotoSearchExtras.None; private int _perPage = 0; private int _page = 0; private PhotoSearchSortOrder _sort = PhotoSearchSortOrder.None; private PrivacyFilter _privacyFilter = PrivacyFilter.None; private BoundaryBox _boundaryBox = new BoundaryBox(); private string _groupId; private SafetyLevel _safeSearch = SafetyLevel.None; private ContentTypeSearch _contentType = ContentTypeSearch.None; private float _longitude = float.NaN; private float _latitude = float.NaN; private bool _hasGeo; private float _radius = float.NaN; private RadiusUnits _radiusUnits = RadiusUnits.None; private ContactSearch _contacts = ContactSearch.None; private string _woeId; private string _placeId; /// /// Creates a new instance of the search options. /// public PhotoSearchOptions() { } /// /// Creates a new instance of the search options, setting the UserId property to the parameter /// passed in. /// /// The ID of the User to search for. public PhotoSearchOptions(string userId) : this(userId, null, TagMode.AllTags, null) { } /// /// Create an instance of the for a given user ID and tag list. /// /// The ID of the User to search for. /// The tags (comma delimited) to search for. Will match all tags. public PhotoSearchOptions(string userId, string tags) : this( userId, tags, TagMode.AllTags, null) { } /// /// Create an instance of the for a given user ID and tag list, /// with the selected tag mode. /// /// The ID of the User to search for. /// The tags (comma delimited) to search for. /// The to use to search. public PhotoSearchOptions(string userId, string tags, TagMode tagMode) : this( userId, tags, tagMode, null) { } /// /// Create an instance of the for a given user ID and tag list, /// with the selected tag mode, and containing the selected text. /// /// The ID of the User to search for. /// The tags (comma delimited) to search for. /// The to use to search. /// The text to search for in photo title and descriptions. public PhotoSearchOptions(string userId, string tags, TagMode tagMode, string text) { this.UserId = userId; this.Tags = tags; this.TagMode = tagMode; this.Text = text; } /// /// The user Id of the user to search on. Defaults to null for no specific user. /// public string UserId { get { return _userId; } set { _userId = value; } } /// /// The group id of the group to search within. /// public string GroupId { get { return _groupId; } set { _groupId = value; } } /// /// A comma delimited list of tags /// public string Tags { get { return _tags; } set { _tags = value; } } /// /// Tag mode can either be 'all', or 'any'. Defaults to /// public TagMode TagMode { get { return _tagMode; } set { _tagMode = value; } } internal string TagModeString { get { switch(_tagMode) { case TagMode.None: return ""; case TagMode.AllTags: return "all"; case TagMode.AnyTag: return "any"; case TagMode.Boolean: return "bool"; default: return ""; } } } /// /// Search for the given machine tags. /// /// /// See http://www.flickr.com/services/api/flickr.photos.search.html for details /// on how to search for machine tags. /// public string MachineTags { get { return _machineTags; } set { _machineTags = value; } } /// /// The machine tag mode. /// /// /// Allowed values are any and all. It defaults to any if none specified. /// public MachineTagMode MachineTagMode { get { return _machineTagMode; } set { _machineTagMode = value; } } internal string MachineTagModeString { get { switch(_machineTagMode) { case MachineTagMode.None: return ""; case MachineTagMode.AllTags: return "all"; case MachineTagMode.AnyTag: return "any"; default: return ""; } } } /// /// Search for the given text in photo titles and descriptions. /// public string Text { get { return _text; } set { _text = value; } } /// /// Minimum date uploaded. Defaults to which /// signifies that the value is not to be used. /// public DateTime MinUploadDate { get { return _minUploadDate; } set { _minUploadDate = value; } } /// /// Maximum date uploaded. Defaults to which /// signifies that the value is not to be used. /// public DateTime MaxUploadDate { get { return _maxUploadDate; } set { _maxUploadDate = value; } } /// /// Minimum date taken. Defaults to which /// signifies that the value is not to be used. /// public DateTime MinTakenDate { get { return _minTakenDate; } set { _minTakenDate = value; } } /// /// Maximum date taken. Defaults to which /// signifies that the value is not to be used. /// public DateTime MaxTakenDate { get { return _maxTakenDate; } set { _maxTakenDate = value; } } /// /// Only return licenses with the selected license number. /// See http://www.flickr.com/services/api/flickr.photos.licenses.getInfo.html /// for more details on the numbers to use. /// [Obsolete("Use AddLicense/RemoveLicense to add/remove licenses")] public int License { get { if( _licenses.Count == 0 ) return 0; else return (int)_licenses[0]; } set { if( _licenses.Count == 0 ) _licenses.Add(value); else _licenses[0] = value; } } /// /// Returns a copy of the licenses to be searched for. /// public int[] Licenses { get { return (int[])_licenses.ToArray(typeof(int)); } } /// /// Adds a new license to the list of licenses to be searched for. /// /// The number of the license to search for. public void AddLicense(int license) { if( !_licenses.Contains(license) ) _licenses.Add(license); } /// /// Removes a license from the list of licenses to be searched for. /// /// The number of the license to remove. public void RemoveLicense(int license) { if( _licenses.Contains(license) ) _licenses.Remove(license); } /// /// Optional extras to return, defaults to all. See for more details. /// public PhotoSearchExtras Extras { get { return _extras; } set { _extras = value; } } /// /// Number of photos to return per page. Defaults to 100. /// public int PerPage { get { return _perPage; } set { _perPage = value; } } /// /// The page to return. Defaults to page 1. /// public int Page { get { return _page; } set { if( value < 0 ) throw new ArgumentOutOfRangeException("Page", "Must be greater than 0"); _page = value; } } /// /// The sort order of the returned list. Default is . /// public PhotoSearchSortOrder SortOrder { get { return _sort; } set { _sort = value; } } /// /// The privacy fitler to filter the search on. /// public PrivacyFilter PrivacyFilter { get { return _privacyFilter; } set { _privacyFilter = value; } } /// /// The boundary box for which to search for geo location photos. /// public BoundaryBox BoundaryBox { get { return _boundaryBox; } set { if( value == null ) _boundaryBox = new BoundaryBox(); else _boundaryBox = value; } } /// /// The accuracy of the search for geo location photos. /// /// /// Can also be set as a property of the property. /// public GeoAccuracy Accuracy { get { return _boundaryBox==null?GeoAccuracy.None:_boundaryBox.Accuracy; } set { if (_boundaryBox==null) { _boundaryBox = new BoundaryBox(); } _boundaryBox.Accuracy = value; } } /// /// Which type of safe search to perform. /// /// /// An unauthenticated search will only ever return safe photos. /// public SafetyLevel SafeSearch { get { return _safeSearch; } set { _safeSearch = value; } } /// /// Filter your search on a particular type of content (photo, screenshot or other). /// public ContentTypeSearch ContentType { get { return _contentType; } set { _contentType = value; } } /// /// Specify the units to use for a Geo location based search. Default is Kilometers. /// public RadiusUnits RadiusUnits { get { return _radiusUnits; } set { _radiusUnits = value; } } /// /// Specify the radius of a particular geo-location search. /// Maximum of 20 miles, 32 kilometers. /// public float Radius { get { return _radius; } set { _radius = value; } } /// /// Specify the longitude center of a geo-location search. /// public float Longitude { get { return _longitude; } set { _longitude = value; } } /// /// Specify the latitude center of a geo-location search. /// public float Latitude { get { return _latitude; } set { _latitude = value; } } /// /// Filter the search results on those that have Geolocation information. /// public bool HasGeo { get { return _hasGeo; } set { _hasGeo = value; } } /// /// Fitler the search results on a particular users contacts. You must set UserId for this option to be honoured. /// public ContactSearch Contacts { get { return _contacts; } set { _contacts = value; } } /// /// The WOE id to return photos for. This is a spatial reference. /// public string WoeId { get { return _woeId; } set { _woeId = value; } } /// /// The Flickr Place to return photos for. /// public string PlaceId { get { return _placeId; } set { _placeId = value; } } internal string ExtrasString { get { return Utils.ExtrasToString(Extras); } } internal string SortOrderString { get { return Utils.SortOrderToString(_sort); } } } } libflickrnet-48055~2.2.0/FlickrNet/Sizes.cs0000644000175000017500000000410211155417354017347 0ustar varunvarunusing System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// Collection of items for a given photograph. /// [System.Serializable] public class Sizes { private Size[] _sizeCollection = new Size[0]; /// /// The size collection contains an array of items. /// [XmlElement("size", Form=XmlSchemaForm.Unqualified)] public Size[] SizeCollection { get { return _sizeCollection; } set { _sizeCollection = value; } } } /// /// Contains details about all the sizes available for a given photograph. /// [System.Serializable] public class Size { private string _label; private int _width; private int _height; private string _source; private string _url; /// /// The label for the size, such as "Thumbnail", "Small", "Medium", "Large" and "Original". /// [XmlAttribute("label", Form=XmlSchemaForm.Unqualified)] public string Label { get { return _label; } set { _label = value; } } /// /// The width of the resulting image, in pixels /// [XmlAttribute("width", Form=XmlSchemaForm.Unqualified)] public int Width { get { return _width; } set { _width = value; } } /// /// The height of the resulting image, in pixels /// [XmlAttribute("height", Form=XmlSchemaForm.Unqualified)] public int Height { get { return _height; } set { _height = value; } } /// /// The source url of the image. /// [XmlAttribute("source", Form=XmlSchemaForm.Unqualified)] public string Source { get { return _source; } set { _source = value; } } /// /// The url to the photographs web page for this particular size. /// [XmlAttribute("url", Form=XmlSchemaForm.Unqualified)] public string Url { get { return _url; } set { _url = value; } } } }libflickrnet-48055~2.2.0/FlickrNet/Blogs.cs0000644000175000017500000000315411155417352017324 0ustar varunvarunusing System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// Contains a list of items for the user. /// /// /// may be null if no blogs are specified. /// [System.Serializable] public class Blogs { /// /// An array of items for the user. /// [XmlElement("blog", Form=XmlSchemaForm.Unqualified)] public Blog[] BlogCollection; } /// /// Provides details of a specific blog, as configured by the user. /// [System.Serializable] public class Blog { /// /// The ID Flickr has assigned to the blog. Use this to post to the blog using /// or /// . /// [XmlAttribute("id", Form=XmlSchemaForm.Unqualified)] public string BlogId; /// /// The name you have assigned to the blog in Flickr. /// [XmlAttribute("name", Form=XmlSchemaForm.Unqualified)] public string BlogName; /// /// The URL of the blog website. /// [XmlAttribute("url", Form=XmlSchemaForm.Unqualified)] public string BlogUrl; /// /// If Flickr stores the password for this then this will be 0, meaning you do not need to pass in the /// password when posting. /// [XmlAttribute("needspassword")] public int NeedsPassword; } }libflickrnet-48055~2.2.0/FlickrNet/PhotoSets.cs0000644000175000017500000001127711155417352020213 0ustar varunvarunusing System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// Collection containing a users photosets. /// [System.Serializable] public class Photosets { private int _canCreate; private Photoset[] _photosetCollection = new Photoset[0]; /// /// Can the user create more photosets. /// /// /// 1 meants yes, 0 means no. /// [XmlAttribute("cancreate", Form=XmlSchemaForm.Unqualified)] public int CanCreate { get { return _canCreate; } set { _canCreate = value; } } /// /// An array of objects. /// [XmlElement("photoset", Form=XmlSchemaForm.Unqualified)] public Photoset[] PhotosetCollection { get { return _photosetCollection; } set { if( value== null ) _photosetCollection = new Photoset[0]; else _photosetCollection = value; } } } /// /// A set of properties for the photoset. /// [System.Serializable] public class Photoset { private string _photosetId; private string _url; private string _ownerId; private string _primaryPhotoId; private string _secret; private string _server; private string _farm; private int _numberOfPhotos; private string _title; private string _description; private Photo[] _photoCollection = new Photo[0]; /// /// The ID of the photoset. /// [XmlAttribute("id", Form=XmlSchemaForm.Unqualified)] public string PhotosetId { get { return _photosetId; } set { _photosetId = value; } } /// /// The URL of the photoset. /// [XmlAttribute("url", Form=XmlSchemaForm.Unqualified)] public string Url { get { return _url; } set { _url = value; } } /// /// The ID of the owner of the photoset. /// [XmlAttribute("owner", Form=XmlSchemaForm.Unqualified)] public string OwnerId { get { return _ownerId; } set { _ownerId = value; } } /// /// The photo ID of the primary photo of the photoset. /// [XmlAttribute("primary", Form=XmlSchemaForm.Unqualified)] public string PrimaryPhotoId { get { return _primaryPhotoId; } set { _primaryPhotoId = value; } } /// /// The secret for the primary photo for the photoset. /// [XmlAttribute("secret", Form=XmlSchemaForm.Unqualified)] public string Secret { get { return _secret; } set { _secret = value; } } /// /// The server for the primary photo for the photoset. /// [XmlAttribute("server", Form=XmlSchemaForm.Unqualified)] public string Server { get { return _server; } set { _server = value; } } /// /// The server farm for the primary photo for the photoset. /// [XmlAttribute("farm", Form=XmlSchemaForm.Unqualified)] public string Farm { get { return _farm; } set { _farm = value; } } /// /// The number of photos in the photoset. /// [XmlAttribute("total", Form=XmlSchemaForm.Unqualified)] public int NumberOfPhotos { get { return _numberOfPhotos; } set { _numberOfPhotos = value; } } /// /// The title of the photoset. /// [XmlElement("title", Form=XmlSchemaForm.Unqualified)] public string Title { get { return _title; } set { _title = value; } } /// /// The description of the photoset. /// [XmlElement("description", Form=XmlSchemaForm.Unqualified)] public string Description { get { return _description; } set { _description = value; } } /// /// An array of photo objects in the photoset. /// [XmlElement("photo", Form=XmlSchemaForm.Unqualified)] public Photo[] PhotoCollection { get { return _photoCollection; } set { if( value == null ) _photoCollection = new Photo[0]; else _photoCollection = value; } } /// /// The URL for the thumbnail of a photo. /// [XmlIgnore()] public string PhotosetThumbnailUrl { get { return Utils.UrlFormat(this, "_t", "jpg"); } } /// /// The URL for the square thumbnail of a photo. /// [XmlIgnore()] public string PhotosetSquareThumbnailUrl { get { return Utils.UrlFormat(this, "_s", "jpg"); } } /// /// The URL for the small copy of a photo. /// [XmlIgnore()] public string PhotosetSmallUrl { get { return Utils.UrlFormat(this, "_m", "jpg"); } } } }libflickrnet-48055~2.2.0/FlickrNet/Auth.cs0000644000175000017500000000402111155417352017151 0ustar varunvarunusing System; namespace FlickrNet { /// /// Used to specify the authentication levels needed for the Auth methods. /// [Serializable] public enum AuthLevel { /// /// No access required - do not use this value! /// None, /// /// Read only access is required by your application. /// Read, /// /// Read and write access is required by your application. /// Write, /// /// Read, write and delete access is required by your application. /// Deleting does not mean deleting photos, just meta data such as tags. /// Delete } /// /// Successful authentication returns a object. /// [Serializable] public class Auth { private string _token; private AuthLevel _permissions; private FoundUser _user; /// /// The authentication token returned by the or methods. /// public string Token { get { return _token; } set { _token = value; } } /// /// The permissions the current token allows the application to perform. /// public AuthLevel Permissions { get { return _permissions; } set { _permissions = value; } } /// /// The object associated with the token. Readonly. /// public FoundUser User { get { return _user; } set { _user = value; } } /// /// Creates a new instance of the class. /// public Auth() { } internal Auth(System.Xml.XmlElement element) { Token = element.SelectSingleNode("token").InnerText; Permissions = (AuthLevel)Enum.Parse(typeof(AuthLevel), element.SelectSingleNode("perms").InnerText, true); System.Xml.XmlNode node = element.SelectSingleNode("user"); User = new FoundUser(node); } } } libflickrnet-48055~2.2.0/FlickrNet/ActivityItem.cs0000644000175000017500000001734611155417352020701 0ustar varunvarunusing System; using System.Xml; namespace FlickrNet { /// /// Activity class used for /// and . /// public class ActivityItem { private ActivityItemType _activityType; private string _id; private string _secret; private string _server; private string _farm; private int _commentsNew; private int _commentsOld; private int _comments; private string _ownerId; private int _more; private int _views; // Photoset specific private int _photos = -1; private string _primaryId = null; // Photo specific private int _notesNew = -1; private int _notesOld = -1; private int _notes = -1; private int _favs = -1; private string _title; private ActivityEvent[] _events; /// /// The of the item. /// public ActivityItemType ItemType { get { return _activityType; } } /// /// The ID of either the photoset or the photo. /// public string Id { get { return _id; } } /// /// The secret for either the photo, or the primary photo for the photoset. /// public string Secret { get { return _secret; } } /// /// The server for either the photo, or the primary photo for the photoset. /// public string Server { get { return _server; } } /// /// The server farm for either the photo, or the primary photo for the photoset. /// public string Farm { get { return _farm; } } /// /// The title of the photoset or photo. /// public string Title { get { return _title; } } /// /// The number of new comments within the given time frame. /// /// /// Only applicable for . /// public int CommentsNew { get { return _commentsNew; } } /// /// The number of old comments within the given time frame. /// /// /// Only applicable for . /// public int CommentsOld { get { return _commentsOld; } } /// /// The number of comments on the item. /// /// /// Only applicable for . /// public int Comments { get { return _comments; } } /// /// Gets the number of views for this photo or photoset. /// public int Views { get { return _views; } } /// /// You want more! You got it! /// /// /// Actually, not sure what this it for! /// public int More { get { return _more; } } /// /// The user id of the owner of this item. /// public string OwnerId { get { return _ownerId; } } /// /// If the type is a photoset then this contains the number of photos in the set. Otherwise returns -1. /// public int Photos { get { return _photos; } } /// /// If this is a photoset then returns the primary photo id, otherwise will be null (Nothing in VB.Net). /// public string PrimaryPhotoId { get { return _primaryId; } } /// /// The number of new notes within the given time frame. /// /// /// Only applicable for photos and when calling . /// public int NotesNew { get { return _notesNew; } } /// /// The number of old notes within the given time frame. /// /// /// Only applicable for photos and when calling . /// public int NotesOld { get { return _notesOld; } } /// /// The number of comments on the photo. /// /// /// Only applicable for photos and when calling . /// public int Notes { get { return _notes; } } /// /// If the type is a photo then this contains the number of favourites in the set. Otherwise returns -1. /// public int Favourites { get { return _favs; } } /// /// The events that comprise this activity item. /// public ActivityEvent[] Events { get { return _events; } } internal ActivityItem(XmlNode itemNode) { XmlNode node; node = itemNode.Attributes.GetNamedItem("type"); if( node == null ) _activityType = ActivityItemType.Unknown; else if( node.Value == "photoset" ) _activityType = ActivityItemType.Photoset; else if( node.Value == "photo" ) _activityType = ActivityItemType.Photo; else _activityType = ActivityItemType.Unknown; node = itemNode.Attributes.GetNamedItem("owner"); if( node != null ) _ownerId = node.Value; node = itemNode.Attributes.GetNamedItem("id"); if( node != null ) _id = node.Value; node = itemNode.Attributes.GetNamedItem("secret"); if( node != null ) _secret = node.Value; node = itemNode.Attributes.GetNamedItem("server"); if( node != null ) _server = node.Value; node = itemNode.Attributes.GetNamedItem("farm"); if( node != null ) _farm = node.Value; node = itemNode.Attributes.GetNamedItem("commentsnew"); if( node != null ) _commentsNew = Convert.ToInt32(node.Value); node = itemNode.Attributes.GetNamedItem("commentsold"); if( node != null ) _commentsOld = Convert.ToInt32(node.Value); node = itemNode.Attributes.GetNamedItem("comments"); if( node != null ) _comments = Convert.ToInt32(node.Value); node = itemNode.Attributes.GetNamedItem("more"); if( node != null ) _more = Convert.ToInt32(node.Value); node = itemNode.Attributes.GetNamedItem("views"); if( node != null ) _views = Convert.ToInt32(node.Value); node = itemNode.SelectSingleNode("title"); if( node != null ) _title = node.InnerText; XmlNodeList list = itemNode.SelectNodes("activity/event"); _events = new ActivityEvent[list.Count]; for(int i = 0; i < _events.Length; i++) { node = list[i]; _events[i] = new ActivityEvent(node); } // Photoset specific // Photos, PrimaryPhotoId node = itemNode.Attributes.GetNamedItem("photos"); if( node != null ) _photos = Convert.ToInt32(node.Value); node = itemNode.Attributes.GetNamedItem("primary"); if( node != null ) _primaryId = node.Value; // Photo specific // NodesNew and NodesOld, Favourites node = itemNode.Attributes.GetNamedItem("notesnew"); if( node != null ) _notesNew = Convert.ToInt32(node.Value); node = itemNode.Attributes.GetNamedItem("notesold"); if( node != null ) _notesOld = Convert.ToInt32(node.Value); node = itemNode.Attributes.GetNamedItem("notes"); if( node != null ) _notes = Convert.ToInt32(node.Value); node = itemNode.Attributes.GetNamedItem("faves"); if( node != null ) _favs = Convert.ToInt32(node.Value); } } /// /// The type of the . /// public enum ActivityItemType { /// /// The type is unknown, either not set of a new unsupported type. /// Unknown, /// /// The activity item is on a photoset. /// Photoset, /// /// The activitiy item is on a photo. /// Photo } } libflickrnet-48055~2.2.0/FlickrNet/ExifPhoto.cs0000644000175000017500000000527511155417352020171 0ustar varunvarunusing System; using System.Xml.Schema; using System.Xml.Serialization; namespace FlickrNet { /// /// EXIF data for the selected photo. /// [Serializable] public class ExifPhoto { internal ExifPhoto(string photoId, string secret, string server, ExifTag[] array) { _photoId = photoId; _secret = secret; _server = server; _tagCollection = array; } private string _photoId; private string _secret; private string _server; private ExifTag[] _tagCollection; /// /// The Photo ID for the photo whose EXIF data this is. /// public string PhotoId { get { return _photoId; } } /// /// The Secret of the photo. /// public string Secret { get { return _secret; } } /// /// The server number for the photo. /// public string Server { get { return _server; } } /// /// An array of EXIF tags. See for more details. /// public ExifTag[] ExifTagCollection { get { return _tagCollection; } } } /// /// Details of an individual EXIF tag. /// [Serializable] public class ExifTag { private string _tagSpace; private int _tagSpaceId; private string _tag; private string _label; private string _raw; private string _clean; /// /// The type of EXIF data, e.g. EXIF, TIFF, GPS etc. /// [XmlAttribute("tagspace")] public string TagSpace { get { return _tagSpace; } set { _tagSpace = value; } } /// /// An id number for the type of tag space. /// [XmlAttribute("tagspaceid")] public int TagSpaceId { get { return _tagSpaceId; } set { _tagSpaceId = value; } } /// /// The tag number. /// [XmlAttribute("tag")] public string Tag { get { return _tag; } set { _tag = value; } } /// /// The label, or description for the tag, such as Aperture /// or Manufacturer /// [XmlAttribute("label")] public string Label { get { return _label; } set { _label = value; } } /// /// The raw EXIF data. /// [XmlElement("raw")] public string Raw { get { return _raw; } set { _raw = value; } } /// /// An optional clean version of the property. /// May be null if the Raw property is in a suitable format already. /// [XmlElement("clean")] public string Clean { get { return _clean; } set { _clean = value; } } } } libflickrnet-48055~2.2.0/FlickrNet/Licenses.cs0000644000175000017500000000243011155417352020017 0ustar varunvarunusing System; using System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// A class which encapsulates a single property, an array of /// objects in its property. /// [System.Serializable] public class Licenses { /// A collection of available licenses. /// [XmlElement("license", Form=XmlSchemaForm.Unqualified)] public License[] LicenseCollection; } /// /// Details of a particular license available from Flickr. /// [System.Serializable] public class License { /// /// The ID of the license. Used by and /// . /// /// [XmlAttribute("id", Form=XmlSchemaForm.Unqualified)] public int LicenseId; /// The name of the license. /// [XmlAttribute("name", Form=XmlSchemaForm.Unqualified)] public string LicenseName; /// The URL for the license text. /// [XmlAttribute("url", Form=XmlSchemaForm.Unqualified)] public string LicenseUrl; } } libflickrnet-48055~2.2.0/FlickrNet/Contacts.cs0000644000175000017500000000342011155417352020030 0ustar varunvarunusing System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// Contains a list of items for a given user. /// [System.Serializable] public class Contacts { /// /// An array of items for the user. /// [XmlElement("contact", Form=XmlSchemaForm.Unqualified)] public Contact[] ContactCollection = new Contact[0]; } /// /// Contains details of a contact for a particular user. /// [System.Serializable] public class Contact { /// /// The user id of the contact. /// [XmlAttribute("nsid", Form=XmlSchemaForm.Unqualified)] public string UserId; /// /// The username (or screen name) of the contact. /// [XmlAttribute("username", Form=XmlSchemaForm.Unqualified)] public string UserName; /// /// Is this contact marked as a friend contact? /// [XmlAttribute("friend", Form=XmlSchemaForm.Unqualified)] public int IsFriend; /// /// Is this user marked a family contact? /// [XmlAttribute("family", Form=XmlSchemaForm.Unqualified)] public int IsFamily; /// /// Unsure how to even set this! /// [XmlAttribute("ignored", Form=XmlSchemaForm.Unqualified)] public int IsIgnored; /// /// Is the user online at the moment (FlickrLive) /// [XmlAttribute("online", Form=XmlSchemaForm.Unqualified)] public int IsOnline; /// /// If the user is online, but marked as away, then this will contains their away message. /// [XmlText()] public string AwayDescription; } }libflickrnet-48055~2.2.0/FlickrNet/Response.cs0000644000175000017500000001020111155417352020043 0ustar varunvarunusing System; using System.Xml; using System.Xml.Serialization; using System.Xml.Schema; namespace FlickrNet { /// /// The root object returned by Flickr. Used with Xml Serialization to get the relevant object. /// It is internal to the FlickrNet API Library and should not be used elsewhere. /// [XmlRoot("rsp", Namespace="", IsNullable=false)] [Serializable] public class Response { /// [XmlElement("blogs", Form=XmlSchemaForm.Unqualified)] public Blogs Blogs; /// [XmlElement("contacts", Form=XmlSchemaForm.Unqualified)] public Contacts Contacts; /// [XmlElement("photos", Form=XmlSchemaForm.Unqualified)] public Photos Photos; /// [XmlElement("category", Form=XmlSchemaForm.Unqualified)] public Category Category; /// [XmlElement("photocounts", Form=XmlSchemaForm.Unqualified)] public PhotoCounts PhotoCounts; /// [XmlElement("photo", Form=XmlSchemaForm.Unqualified)] public PhotoInfo PhotoInfo; /// [XmlElement("photoset", Form=XmlSchemaForm.Unqualified)] public Photoset Photoset; /// [XmlElement("photosets", Form=XmlSchemaForm.Unqualified)] public Photosets Photosets; /// [XmlElement("sizes", Form=XmlSchemaForm.Unqualified)] public Sizes Sizes; /// [XmlElement("licenses", Form=XmlSchemaForm.Unqualified)] public Licenses Licenses; /// [XmlElement("count", Form=XmlSchemaForm.Unqualified)] public ContextCount ContextCount; /// [XmlElement("nextphoto", Form=XmlSchemaForm.Unqualified)] public ContextPhoto ContextNextPhoto; /// [XmlElement("prevphoto", Form=XmlSchemaForm.Unqualified)] public ContextPhoto ContextPrevPhoto; /// [XmlElement("places", Form=XmlSchemaForm.Unqualified)] public Places Places; /// [XmlAttribute("stat", Form=XmlSchemaForm.Unqualified)] public ResponseStatus Status; /// /// If an error occurs the Error property is populated with /// a instance. /// [XmlElement("err", Form=XmlSchemaForm.Unqualified)] public ResponseError Error; /// /// A instance. /// [XmlElement("method", Form=XmlSchemaForm.Unqualified)] public Method Method; /// /// A instance. /// [XmlElement("place", Form=XmlSchemaForm.Unqualified)] public Place Place; /// /// If using flickr.test.echo this contains all the other elements not covered above. /// /// /// t is an array of objects. Use the XmlElement Name and InnerXml properties /// to get the name and value of the returned property. /// [XmlAnyElement(), NonSerialized()] public XmlElement[] AllElements; } /// /// If an error occurs then Flickr returns this object. /// [System.Serializable] public class ResponseError { /// /// The code or number of the error. /// /// /// 100 - Invalid Api Key. /// 99 - User not logged in. /// Other codes are specific to a method. /// [XmlAttribute("code", Form=XmlSchemaForm.Unqualified)] public int Code; /// /// The verbose message matching the error code. /// [XmlAttribute("msg", Form=XmlSchemaForm.Unqualified)] public string Message; } /// /// The status of the response, either ok or fail. /// public enum ResponseStatus { /// /// An unknown status, and the default value if not set. /// [XmlEnum("unknown")] Unknown, /// /// The response returns "ok" on a successful execution of the method. /// [XmlEnum("ok")] OK, /// /// The response returns "fail" if there is an error, such as invalid API key or login failure. /// [XmlEnum("fail")] Failed } }libflickrnet-48055~2.2.0/FlickrNet/AssemblyInfo.cs0000644000175000017500000000557211155417352020657 0ustar varunvarunusing System; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Runtime.InteropServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("Flickr .Net Api Library")] [assembly: AssemblyDescription(".Net library for accessing Flickr.com Api functionality")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Sam Judson")] [assembly: AssemblyProduct("Flickr .Net Api Library")] [assembly: AssemblyCopyright("See website http://www.wackylabs.net/flickr")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("2.2.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyName("")] #if !WindowsCE [assembly: AssemblyKeyFile("..\\..\\FlickrNet.snk")] [assembly: AllowPartiallyTrustedCallers()] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Execution = true)] #endif [assembly: CLSCompliantAttribute(true)] [assembly: ComVisible(false)]libflickrnet-48055~2.2.0/FlickrNet/Flickr.cs0000644000175000017500000063150411155417352017476 0ustar varunvarunusing System; using System.Net; using System.IO; using System.Xml; using System.Xml.XPath; using System.Xml.Serialization; using System.Text; using System.Collections; using System.Collections.Specialized; namespace FlickrNet { /// /// The main Flickr class. /// /// /// Create an instance of this class and then call its methods to perform methods on Flickr. /// /// /// FlickrNet.Flickr flickr = new FlickrNet.Flickr(); /// User user = flickr.PeopleFindByEmail("cal@iamcal.com"); /// Console.WriteLine("User Id is " + u.UserId); /// //[System.Net.WebPermission(System.Security.Permissions.SecurityAction.Demand, ConnectPattern="http://www.flickr.com/.*")] public class Flickr { #region [ Upload Event and Delegate ] /// /// /// public delegate void UploadProgressHandler(object sender, UploadProgressEventArgs e); /// /// UploadProgressHandler is fired during a synchronous upload process to signify that /// a segment of uploading has been completed. This is approximately 50 bytes. The total /// uploaded is recorded in the class. /// public event UploadProgressHandler OnUploadProgress; #endregion #region [ Private Variables ] #if !WindowsCE private static bool _isServiceSet = false; #endif private static SupportedService _defaultService = SupportedService.Flickr; private SupportedService _service = SupportedService.Flickr; private string BaseUrl { get { return _baseUrl[(int)_service]; } } private string[] _baseUrl = new string[] { "http://api.flickr.com/services/rest/", "http://beta.zooomr.com/bluenote/api/rest", "http://www.23hq.com/services/rest/"}; private string UploadUrl { get { return _uploadUrl[(int)_service]; } } private static string[] _uploadUrl = new string[] { "http://api.flickr.com/services/upload/", "http://beta.zooomr.com/bluenote/api/upload", "http://www.23hq.com/services/upload/"}; private string ReplaceUrl { get { return _replaceUrl[(int)_service]; } } private static string[] _replaceUrl = new string[] { "http://api.flickr.com/services/replace/", "http://beta.zooomr.com/bluenote/api/replace", "http://www.23hq.com/services/replace/"}; private string AuthUrl { get { return _authUrl[(int)_service]; } } private static string[] _authUrl = new string[] { "http://www.flickr.com/services/auth/", "http://beta.zooomr.com/auth/", "http://www.23hq.com/services/auth/"}; private string _apiKey; private string _apiToken; private string _sharedSecret; private int _timeout = 30000; private const string UserAgent = "Mozilla/4.0 FlickrNet API (compatible; MSIE 6.0; Windows NT 5.1)"; private string _lastRequest; private string _lastResponse; private WebProxy _proxy;// = WebProxy.GetDefaultProxy(); // Static serializers private static XmlSerializer _responseSerializer = new XmlSerializer(typeof(FlickrNet.Response)); private static XmlSerializer _uploaderSerializer = new XmlSerializer(typeof(FlickrNet.Uploader)); #endregion #region [ Public Properties ] /// /// Get or set the API Key to be used by all calls. API key is mandatory for all /// calls to Flickr. /// public string ApiKey { get { return _apiKey; } set { _apiKey = (value==null||value.Length==0?null:value); } } /// /// API shared secret is required for all calls that require signing, which includes /// all methods that require authentication, as well as the actual flickr.auth.* calls. /// public string ApiSecret { get { return _sharedSecret; } set { _sharedSecret = (value==null||value.Length==0?null:value); } } /// /// The API token is required for all calls that require authentication. /// A will be raised by Flickr if the API token is /// not set when required. /// /// /// It should be noted that some methods will work without the API token, but /// will return different results if used with them (such as group pool requests, /// and results which include private pictures the authenticated user is allowed to see /// (their own, or others). /// [Obsolete("Renamed to AuthToken to be more consistent with the Flickr API")] public string ApiToken { get { return _apiToken; } set { _apiToken = (value==null||value.Length==0?null:value); } } /// /// The authentication token is required for all calls that require authentication. /// A will be raised by Flickr if the authentication token is /// not set when required. /// /// /// It should be noted that some methods will work without the authentication token, but /// will return different results if used with them (such as group pool requests, /// and results which include private pictures the authenticated user is allowed to see /// (their own, or others). /// public string AuthToken { get { return _apiToken; } set { _apiToken = (value==null||value.Length==0?null:value); } } /// /// Gets or sets whether the cache should be disabled. Use only in extreme cases where you are sure you /// don't want any caching. /// public static bool CacheDisabled { get { return Cache.CacheDisabled; } set { Cache.CacheDisabled = value; } } /// /// All GET calls to Flickr are cached by the Flickr.Net API. Set the /// to determine how long these calls should be cached (make this as long as possible!) /// public static TimeSpan CacheTimeout { get { return Cache.CacheTimeout; } set { Cache.CacheTimeout = value; } } /// /// Sets or gets the location to store the Cache files. /// public static string CacheLocation { get { return Cache.CacheLocation; } set { Cache.CacheLocation = value; } } /// /// Gets the current size of the Cache. /// public static long CacheSize { get { return Cache.CacheSize; } } /// /// is the cache file size in bytes for downloaded /// pictures. The default is 50MB (or 50 * 1024 * 1025 in bytes). /// public static long CacheSizeLimit { get { return Cache.CacheSizeLimit; } set { Cache.CacheSizeLimit = value; } } /// /// The default service to use for new Flickr instances /// public static SupportedService DefaultService { get { #if !WindowsCE if( !_isServiceSet && FlickrConfigurationManager.Settings != null ) { _defaultService = FlickrConfigurationManager.Settings.Service; _isServiceSet = true; } #endif return _defaultService; } set { _defaultService = value; #if !WindowsCE _isServiceSet = true; #endif } } /// /// The current service that the Flickr API is using. /// public SupportedService CurrentService { get { return _service; } set { _service = value; #if !WindowsCE if( _service == SupportedService.Zooomr ) ServicePointManager.Expect100Continue = false; #endif } } /// /// Internal timeout for all web requests in milliseconds. Defaults to 30 seconds. /// public int HttpTimeout { get { return _timeout; } set { _timeout = value; } } /// /// Checks to see if a shared secret and an api token are stored in the object. /// Does not check if these values are valid values. /// public bool IsAuthenticated { get { return (_sharedSecret != null && _apiToken != null); } } /// /// Returns the raw XML returned from the last response. /// Only set it the response was not returned from cache. /// public string LastResponse { get { return _lastResponse; } } /// /// Returns the last URL requested. Includes API signing. /// public string LastRequest { get { return _lastRequest; } } /// /// You can set the or alter its properties. /// It defaults to your internet explorer proxy settings. /// public WebProxy Proxy { get { return _proxy; } set { _proxy = value; } } #endregion #region [ Cache Methods ] /// /// Clears the cache completely. /// public static void FlushCache() { Cache.FlushCache(); } /// /// Clears the cache for a particular URL. /// /// The URL to remove from the cache. /// /// The URL can either be an image URL for a downloaded picture, or /// a request URL (see for getting the last URL). /// public static void FlushCache(string url) { Cache.FlushCache(url); } /// /// Provides static access to the list of cached photos. /// /// An array of objects. public static PictureCacheItem[] GetCachePictures() { return (PictureCacheItem[]) Cache.Downloads.ToArray(typeof(PictureCacheItem)); } #endregion #region [ Constructors ] /// /// Constructor loads configuration settings from app.config or web.config file if they exist. /// public Flickr() { #if !WindowsCE FlickrConfigurationSettings settings = FlickrConfigurationManager.Settings; if( settings == null ) return; if( settings.CacheSize != 0 ) CacheSizeLimit = settings.CacheSize; if( settings.CacheTimeout != TimeSpan.MinValue ) CacheTimeout = settings.CacheTimeout; ApiKey = settings.ApiKey; AuthToken = settings.ApiToken; ApiSecret = settings.SharedSecret; if (settings.IsProxyDefined) { Proxy = new WebProxy(); Proxy.Address = new Uri("http://" + settings.ProxyIPAddress + ":" + settings.ProxyPort); if( settings.ProxyUsername != null && settings.ProxyUsername.Length > 0 ) { NetworkCredential creds = new NetworkCredential(); creds.UserName = settings.ProxyUsername; creds.Password = settings.ProxyPassword; creds.Domain = settings.ProxyDomain; Proxy.Credentials = creds; } } else { // try and get default IE settings try { Proxy = WebProxy.GetDefaultProxy(); } catch(System.Security.SecurityException) { // Capture SecurityException for when running in a Medium Trust environment. } } #endif CurrentService = DefaultService; } /// /// Create a new instance of the class with no authentication. /// /// Your Flickr API Key. public Flickr(string apiKey) : this(apiKey, null, null) { } /// /// Creates a new instance of the class with an API key and a Shared Secret. /// This is only useful really useful for calling the Auth functions as all other /// authenticationed methods also require the API Token. /// /// Your Flickr API Key. /// Your Flickr Shared Secret. public Flickr(string apiKey, string sharedSecret) : this(apiKey, sharedSecret, null) { } /// /// Create a new instance of the class with the email address and password given /// /// Your Flickr API Key /// Your FLickr Shared Secret. /// The token for the user who has been authenticated. public Flickr(string apiKey, string sharedSecret, string token) : this() { _apiKey = apiKey; _sharedSecret = sharedSecret; _apiToken = token; } #endregion #region [ Private Methods ] /// /// A private method which performs the actual HTTP web request if /// the details are not found within the cache. /// /// The URL to download. /// The query string parameters to be added to the end of the URL. /// A object. /// If the final length of the URL would be greater than 2000 characters /// then they are sent as part of the body instead. private string DoGetResponse(string url, string variables) { HttpWebRequest req = null; HttpWebResponse res = null; if( variables.Length < 2000 ) { url += "?" + variables; variables = ""; } // Initialise the web request req = (HttpWebRequest)HttpWebRequest.Create(url); req.Method = CurrentService==SupportedService.Zooomr?"GET":"POST"; if (req.Method == "POST") req.ContentLength = variables.Length; req.UserAgent = UserAgent; if( Proxy != null ) req.Proxy = Proxy; req.Timeout = HttpTimeout; req.KeepAlive = false; if (variables.Length > 0) { req.ContentType = "application/x-www-form-urlencoded"; StreamWriter sw = new StreamWriter(req.GetRequestStream()); sw.Write(variables); sw.Close(); } else { // This is needed in the Compact Framework // See for more details: http://msdn2.microsoft.com/en-us/library/1afx2b0f.aspx req.GetRequestStream().Close(); } try { // Get response from the internet res = (HttpWebResponse)req.GetResponse(); } catch(WebException ex) { if( ex.Status == WebExceptionStatus.ProtocolError ) { HttpWebResponse res2 = (HttpWebResponse)ex.Response; if( res2 != null ) { throw new FlickrWebException(String.Format("HTTP Error {0}, {1}", (int)res2.StatusCode, res2.StatusDescription), ex); } } throw new FlickrWebException(ex.Message, ex); } string responseString = string.Empty; using (StreamReader sr = new StreamReader(res.GetResponseStream())) { responseString = sr.ReadToEnd(); } return responseString; } /// /// Download a picture (or anything else actually). /// /// /// Allow automatic redirections. /// private Stream DoDownloadPicture(string url, bool redirect) { HttpWebRequest req = null; HttpWebResponse res = null; try { req = (HttpWebRequest)HttpWebRequest.Create(url); req.UserAgent = UserAgent; if( Proxy != null ) req.Proxy = Proxy; req.Timeout = HttpTimeout; req.KeepAlive = false; req.AllowAutoRedirect = redirect; res = (HttpWebResponse)req.GetResponse(); } catch(WebException ex) { if( ex.Status == WebExceptionStatus.ProtocolError ) { HttpWebResponse res2 = (HttpWebResponse)ex.Response; if( res2 != null ) { throw new FlickrWebException(String.Format("HTTP Error while downloading photo: {0}, {1}", (int)res2.StatusCode, res2.StatusDescription), ex); } } else if( ex.Status == WebExceptionStatus.Timeout ) { throw new FlickrWebException("The request timed-out", ex); } throw new FlickrWebException("Picture download failed (" + ex.Message + ")", ex); } System.Diagnostics.Debug.Write("Http Status Code = " + res.StatusCode); if( !redirect && res.StatusCode == HttpStatusCode.Redirect ) return null; return res.GetResponseStream(); } private void CheckApiKey() { if( ApiKey == null || ApiKey.Length == 0 ) throw new ApiKeyRequiredException(); } private void CheckSigned() { CheckApiKey(); if( ApiSecret == null || ApiSecret.Length == 0 ) throw new SignatureRequiredException(); } private void CheckRequiresAuthentication() { CheckApiKey(); if( ApiSecret == null || ApiSecret.Length == 0 ) throw new SignatureRequiredException(); if( AuthToken == null || AuthToken.Length == 0 ) throw new AuthenticationRequiredException(); } #endregion #region [ GetResponse methods ] private Response GetResponseNoCache(Hashtable parameters) { return GetResponse(parameters, TimeSpan.MinValue); } private Response GetResponseAlwaysCache(Hashtable parameters) { return GetResponse(parameters, TimeSpan.MaxValue); } private Response GetResponseCache(Hashtable parameters) { return GetResponse(parameters, Cache.CacheTimeout); } private Response GetResponse(Hashtable parameters, TimeSpan cacheTimeout) { CheckApiKey(); // Calulate URL string url = BaseUrl; StringBuilder UrlStringBuilder = new StringBuilder("", 2 * 1024); StringBuilder HashStringBuilder = new StringBuilder(_sharedSecret, 2 * 1024); parameters["api_key"] = _apiKey; if( _apiToken != null && _apiToken.Length > 0 ) { parameters["auth_token"] = _apiToken; } string[] keys = new string[parameters.Keys.Count]; parameters.Keys.CopyTo(keys, 0); Array.Sort(keys); foreach(string key in keys) { if( UrlStringBuilder.Length > 0 ) UrlStringBuilder.Append("&"); UrlStringBuilder.Append(key); UrlStringBuilder.Append("="); UrlStringBuilder.Append(Utils.UrlEncode(Convert.ToString(parameters[key]))); HashStringBuilder.Append(key); HashStringBuilder.Append(parameters[key]); } if (_sharedSecret != null && _sharedSecret.Length > 0) { if (UrlStringBuilder.Length > BaseUrl.Length + 1) { UrlStringBuilder.Append("&"); } UrlStringBuilder.Append("api_sig="); UrlStringBuilder.Append(Md5Hash(HashStringBuilder.ToString())); } string variables = UrlStringBuilder.ToString(); _lastRequest = url; _lastResponse = string.Empty; if( CacheDisabled ) { string responseXml = DoGetResponse(url, variables); _lastResponse = responseXml; return Utils.Deserialize(responseXml); } else { ResponseCacheItem cached = (ResponseCacheItem) Cache.Responses.Get(url + "?" + variables, cacheTimeout, true); if (cached != null) { System.Diagnostics.Debug.WriteLine("Cache hit"); _lastResponse = cached.Response; return Utils.Deserialize(cached.Response); } else { System.Diagnostics.Debug.WriteLine("Cache miss"); string responseXml = DoGetResponse(url, variables); _lastResponse = responseXml; ResponseCacheItem resCache = new ResponseCacheItem(); resCache.Response = responseXml; resCache.Url = url; resCache.CreationTime = DateTime.UtcNow; FlickrNet.Response response = Utils.Deserialize(responseXml); if( response.Status == ResponseStatus.OK ) { Cache.Responses.Shrink(Math.Max(0, Cache.CacheSizeLimit - responseXml.Length)); Cache.Responses[url] = resCache; } return response; } } } #endregion #region [ DownloadPicture ] /// /// Downloads the picture from a internet and transfers it to a stream object. Returns null if the image does not exist. /// /// The url of the image to download. /// A object containing the downloaded picture if the image exists, and null if it does not. /// /// The method checks the download cache first to see if the picture has already /// been downloaded and if so returns the cached image. Otherwise it goes to the internet for the actual /// image. /// public Stream DownloadPictureWithoutRedirect(string url) { return DownloadPicture(url, false); } /// /// Downloads the picture from a internet and transfers it to a stream object. /// /// The url of the image to download. /// A object containing the downloaded picture. /// /// The method checks the download cache first to see if the picture has already /// been downloaded and if so returns the cached image. Otherwise it goes to the internet for the actual /// image. /// public System.IO.Stream DownloadPicture(string url) { return DownloadPicture(url, true); } private System.IO.Stream DownloadPicture(string url, bool redirect) { if( CacheDisabled ) { return DoDownloadPicture(url, redirect); } const int BUFFER_SIZE = 1024 * 10; PictureCacheItem cacheItem = (PictureCacheItem) Cache.Downloads[url]; if (cacheItem != null) { return new FileStream(cacheItem.filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); } PictureCacheItem picCache = new PictureCacheItem(); picCache.filename = Path.Combine(Cache.CacheLocation,Guid.NewGuid().ToString()); Stream read = DoDownloadPicture(url, redirect); if( !redirect && read == null ) return null; Stream write = new FileStream(picCache.filename, FileMode.Create, FileAccess.Write, FileShare.None); byte[] buffer = new byte[BUFFER_SIZE]; int bytes = 0; long fileSize = 0; while( (bytes = read.Read(buffer, 0, BUFFER_SIZE)) > 0 ) { fileSize += bytes; write.Write(buffer, 0, bytes); } read.Close(); write.Close(); picCache.url = url; picCache.creationTime = DateTime.UtcNow; picCache.fileSize = fileSize; Cache.Downloads.Shrink(Math.Max(0, Cache.CacheSizeLimit - fileSize)); Cache.Downloads[url] = picCache; return new FileStream(picCache.filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); } #endregion #region [ Auth ] /// /// Retrieve a temporary FROB from the Flickr service, to be used in redirecting the /// user to the Flickr web site for authentication. Only required for desktop authentication. /// /// /// Pass the FROB to the method to calculate the url. /// /// /// /// string frob = flickr.AuthGetFrob(); /// string url = flickr.AuthCalcUrl(frob, AuthLevel.Read); /// /// // redirect the user to the url above and then wait till they have authenticated and return to the app. /// /// Auth auth = flickr.AuthGetToken(frob); /// /// // then store the auth.Token for later use. /// string token = auth.Token; /// /// /// The FROB. public string AuthGetFrob() { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.auth.getFrob"); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.AllElements[0].InnerText; } else { throw new FlickrApiException(response.Error); } } /// /// Calculates the URL to redirect the user to Flickr web site for /// authentication. Used by desktop application. /// See for example code. /// /// The FROB to be used for authentication. /// The stating the maximum authentication level your application requires. /// The url to redirect the user to. public string AuthCalcUrl(string frob, AuthLevel authLevel) { if( _sharedSecret == null ) throw new SignatureRequiredException(); string hash = _sharedSecret + "api_key" + _apiKey + "frob" + frob + "perms" + authLevel.ToString().ToLower(); hash = Md5Hash(hash); string url = AuthUrl + "?api_key=" + _apiKey + "&perms=" + authLevel.ToString().ToLower() + "&frob=" + frob; url += "&api_sig=" + hash; return url; } /// /// Calculates the URL to redirect the user to Flickr web site for /// auehtntication. Used by Web applications. /// See for example code. /// /// /// The Flickr web site provides 'tiny urls' that can be used in place /// of this URL when you specify your return url in the API key page. /// It is recommended that you use these instead as they do not include /// your API or shared secret. /// /// The stating the maximum authentication level your application requires. /// The url to redirect the user to. public string AuthCalcWebUrl(AuthLevel authLevel) { if( _sharedSecret == null ) throw new SignatureRequiredException(); string hash = _sharedSecret + "api_key" + _apiKey + "perms" + authLevel.ToString().ToLower(); hash = Md5Hash(hash); string url = AuthUrl + "?api_key=" + _apiKey + "&perms=" + authLevel.ToString().ToLower(); url += "&api_sig=" + hash; return url; } /// /// After the user has authenticated your application on the flickr web site call this /// method with the FROB (either stored from or returned in the URL /// from the Flickr web site) to get the users token. /// /// The string containing the FROB. /// A object containing user and token details. public Auth AuthGetToken(string frob) { if( _sharedSecret == null ) throw new SignatureRequiredException(); Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.auth.getToken"); parameters.Add("frob", frob); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { Auth auth = new Auth(response.AllElements[0]); return auth; } else { throw new FlickrApiException(response.Error); } } /// /// Gets the full token details for a given mini token, entered by the user following a /// web based authentication. /// /// The mini token. /// An instance class, detailing the user and their full token. public Auth AuthGetFullToken(string miniToken) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.auth.getFullToken"); parameters.Add("mini_token", miniToken.Replace("-", "")); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { Auth auth = new Auth(response.AllElements[0]); return auth; } else { throw new FlickrApiException(response.Error); } } /// /// Checks a authentication token with the flickr service to make /// sure it is still valid. /// /// The authentication token to check. /// The object detailing the user for the token. public Auth AuthCheckToken(string token) { CheckSigned(); Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.auth.checkToken"); parameters.Add("auth_token", token); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { Auth auth = new Auth(response.AllElements[0]); return auth; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Activity ] /// /// Returns a list of recent activity on photos belonging to the calling user. /// /// /// Do not poll this method more than once an hour. /// /// An array of instances. public ActivityItem[] ActivityUserPhotos() { return ActivityUserPhotos(null); } /// /// Returns a list of recent activity on photos belonging to the calling user. /// /// /// Do not poll this method more than once an hour. /// /// The number of days or hours you want to get activity for. /// 'd' for days, 'h' for hours. /// An array of instances. public ActivityItem[] ActivityUserPhotos(int timePeriod, string timeType) { if( timePeriod == 0 ) throw new ArgumentOutOfRangeException("timePeriod", "Time Period should be greater than 0"); if( timeType == null ) throw new ArgumentNullException("timeType"); if( timeType != "d" && timeType != "h" ) throw new ArgumentOutOfRangeException("timeType", "Time type must be 'd' or 'h'"); return ActivityUserPhotos(timePeriod + timeType); } private ActivityItem[] ActivityUserPhotos(string timeframe) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.activity.userPhotos"); if( timeframe != null && timeframe.Length > 0 ) parameters.Add("timeframe", timeframe); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { XmlNodeList list = response.AllElements[0].SelectNodes("item"); ActivityItem[] items = new ActivityItem[list.Count]; for(int i = 0; i < items.Length; i++) { items[i] = new ActivityItem(list[i]); } return items; } else { throw new FlickrApiException(response.Error); } } /// /// Returns a list of recent activity on photos commented on by the calling user. /// /// /// Do not poll this method more than once an hour. /// /// public ActivityItem[] ActivityUserComments(int page, int perPage) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.activity.userComments"); if( page > 0 ) parameters.Add("page", page); if( perPage > 0 ) parameters.Add("per_page", perPage); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { XmlNodeList list = response.AllElements[0].SelectNodes("item"); ActivityItem[] items = new ActivityItem[list.Count]; for(int i = 0; i < items.Length; i++) { items[i] = new ActivityItem(list[i]); } return items; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ UploadPicture ] /// /// Uploads a file to Flickr. /// /// The filename of the file to open. /// The id of the photo on a successful upload. /// Thrown when Flickr returns an error. see http://www.flickr.com/services/api/upload.api.html for more details. /// Other exceptions may be thrown, see constructors for more details. public string UploadPicture(string filename) { return UploadPicture(filename, null, null, null, true, false, false); } /// /// Uploads a file to Flickr. /// /// The filename of the file to open. /// The title of the photograph. /// The id of the photo on a successful upload. /// Thrown when Flickr returns an error. see http://www.flickr.com/services/api/upload.api.html for more details. /// Other exceptions may be thrown, see constructors for more details. public string UploadPicture(string filename, string title) { return UploadPicture(filename, title, null, null, true, false, false); } /// /// Uploads a file to Flickr. /// /// The filename of the file to open. /// The title of the photograph. /// The description of the photograph. /// The id of the photo on a successful upload. /// Thrown when Flickr returns an error. see http://www.flickr.com/services/api/upload.api.html for more details. /// Other exceptions may be thrown, see constructors for more details. public string UploadPicture(string filename, string title, string description) { return UploadPicture(filename, title, description, null, true, false, false); } /// /// Uploads a file to Flickr. /// /// The filename of the file to open. /// The title of the photograph. /// The description of the photograph. /// A comma seperated list of the tags to assign to the photograph. /// The id of the photo on a successful upload. /// Thrown when Flickr returns an error. see http://www.flickr.com/services/api/upload.api.html for more details. /// Other exceptions may be thrown, see constructors for more details. public string UploadPicture(string filename, string title, string description, string tags) { Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); return UploadPicture(stream, title, description, tags, -1, -1, -1, ContentType.None, SafetyLevel.None, HiddenFromSearch.None); } /// /// Uploads a file to Flickr. /// /// The filename of the file to open. /// The title of the photograph. /// The description of the photograph. /// A comma seperated list of the tags to assign to the photograph. /// True if the photograph should be public and false if it should be private. /// True if the photograph should be marked as viewable by friends contacts. /// True if the photograph should be marked as viewable by family contacts. /// The id of the photo on a successful upload. /// Thrown when Flickr returns an error. see http://www.flickr.com/services/api/upload.api.html for more details. /// Other exceptions may be thrown, see constructors for more details. public string UploadPicture(string filename, string title, string description, string tags, bool isPublic, bool isFamily, bool isFriend) { Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); return UploadPicture(stream, title, description, tags, isPublic?1:0, isFamily?1:0, isFriend?1:0, ContentType.None, SafetyLevel.None, HiddenFromSearch.None); } /// /// UploadPicture method that does all the uploading work. /// /// The object containing the pphoto to be uploaded. /// The title of the photo (optional). /// The description of the photograph (optional). /// The tags for the photograph (optional). /// 0 for private, 1 for public. /// 1 if family, 0 is not. /// 1 if friend, 0 if not. /// The content type of the photo, i.e. Photo, Screenshot or Other. /// The safety level of the photo, i.e. Safe, Moderate or Restricted. /// Is the photo hidden from public searches. /// The id of the photograph after successful uploading. public string UploadPicture(Stream stream, string title, string description, string tags, int isPublic, int isFamily, int isFriend, ContentType contentType, SafetyLevel safetyLevel, HiddenFromSearch hiddenFromSearch) { CheckRequiresAuthentication(); /* * * Modified UploadPicture code taken from the Flickr.Net library * URL: http://workspaces.gotdotnet.com/flickrdotnet * It is used under the terms of the Common Public License 1.0 * URL: http://www.opensource.org/licenses/cpl.php * * */ string boundary = "FLICKR_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss"); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(UploadUrl); req.UserAgent = "Mozilla/4.0 FlickrNet API (compatible; MSIE 6.0; Windows NT 5.1)"; req.Method = "POST"; if( Proxy != null ) req.Proxy = Proxy; //req.Referer = "http://www.flickr.com"; req.KeepAlive = true; req.Timeout = HttpTimeout * 1000; req.ContentType = "multipart/form-data; boundary=" + boundary + ""; req.Expect = ""; StringBuilder sb = new StringBuilder(); Hashtable parameters = new Hashtable(); if( title != null && title.Length > 0 ) { parameters.Add("title", title); } if( description != null && description.Length > 0 ) { parameters.Add("description", description); } if( tags != null && tags.Length > 0 ) { parameters.Add("tags", tags); } if( isPublic >= 0 ) { parameters.Add("is_public", isPublic.ToString()); } if( isFriend >= 0 ) { parameters.Add("is_friend", isFriend.ToString()); } if( isFamily >= 0 ) { parameters.Add("is_family", isFamily.ToString()); } if( safetyLevel != SafetyLevel.None ) { parameters.Add("safety_level", (int)safetyLevel); } if( contentType != ContentType.None ) { parameters.Add("content_type", (int)contentType); } if( hiddenFromSearch != HiddenFromSearch.None ) { parameters.Add("hidden", (int)hiddenFromSearch); } parameters.Add("api_key", _apiKey); parameters.Add("auth_token", _apiToken); string[] keys = new string[parameters.Keys.Count]; parameters.Keys.CopyTo(keys, 0); Array.Sort(keys); StringBuilder HashStringBuilder = new StringBuilder(_sharedSecret, 2 * 1024); foreach(string key in keys) { HashStringBuilder.Append(key); HashStringBuilder.Append(parameters[key]); sb.Append("--" + boundary + "\r\n"); sb.Append("Content-Disposition: form-data; name=\"" + key + "\"\r\n"); sb.Append("\r\n"); sb.Append(parameters[key] + "\r\n"); } sb.Append("--" + boundary + "\r\n"); sb.Append("Content-Disposition: form-data; name=\"api_sig\"\r\n"); sb.Append("\r\n"); sb.Append(Md5Hash(HashStringBuilder.ToString()) + "\r\n"); // Photo sb.Append("--" + boundary + "\r\n"); sb.Append("Content-Disposition: form-data; name=\"photo\"; filename=\"image.jpeg\"\r\n"); sb.Append("Content-Type: image/jpeg\r\n"); sb.Append("\r\n"); UTF8Encoding encoding = new UTF8Encoding(); byte[] postContents = encoding.GetBytes(sb.ToString()); byte[] photoContents = new byte[stream.Length]; stream.Read(photoContents, 0, photoContents.Length); stream.Close(); byte[] postFooter = encoding.GetBytes("\r\n--" + boundary + "--\r\n"); byte[] dataBuffer = new byte[postContents.Length + photoContents.Length + postFooter.Length]; Buffer.BlockCopy(postContents, 0, dataBuffer, 0, postContents.Length); Buffer.BlockCopy(photoContents, 0, dataBuffer, postContents.Length, photoContents.Length); Buffer.BlockCopy(postFooter, 0, dataBuffer, postContents.Length + photoContents.Length, postFooter.Length); req.ContentLength = dataBuffer.Length; Stream resStream = req.GetRequestStream(); int j = 1; int uploadBit = Math.Max(dataBuffer.Length / 100, 50*1024); int uploadSoFar = 0; for(int i = 0; i < dataBuffer.Length; i=i+uploadBit) { int toUpload = Math.Min(uploadBit, dataBuffer.Length - i); uploadSoFar += toUpload; resStream.Write(dataBuffer, i, toUpload); if( (OnUploadProgress != null) && ((j++) % 5 == 0 || uploadSoFar == dataBuffer.Length) ) { OnUploadProgress(this, new UploadProgressEventArgs(i+toUpload, uploadSoFar == dataBuffer.Length)); } } resStream.Close(); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); XmlSerializer serializer = _uploaderSerializer; StreamReader sr = new StreamReader(res.GetResponseStream()); string s= sr.ReadToEnd(); sr.Close(); StringReader str = new StringReader(s); FlickrNet.Uploader uploader = (FlickrNet.Uploader)serializer.Deserialize(str); if( uploader.Status == ResponseStatus.OK ) { return uploader.PhotoId; } else { throw new FlickrApiException(uploader.Error); } } /// /// Replace an existing photo on Flickr. /// /// The filename of the photo to upload. /// The ID of the photo to replace. /// The id of the photograph after successful uploading. public string ReplacePicture(string filename, string photoId) { FileStream stream = null; try { stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); return ReplacePicture(stream, photoId); } finally { if( stream != null ) stream.Close(); } } /// /// Replace an existing photo on Flickr. /// /// The object containing the photo to be uploaded. /// The ID of the photo to replace. /// The id of the photograph after successful uploading. public string ReplacePicture(Stream stream, string photoId) { string boundary = "FLICKR_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss"); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(ReplaceUrl); req.UserAgent = "Mozilla/4.0 FlickrNet API (compatible; MSIE 6.0; Windows NT 5.1)"; req.Method = "POST"; if( Proxy != null ) req.Proxy = Proxy; req.Referer = "http://www.flickr.com"; req.KeepAlive = false; req.Timeout = HttpTimeout * 100; req.ContentType = "multipart/form-data; boundary=" + boundary + ""; StringBuilder sb = new StringBuilder(); Hashtable parameters = new Hashtable(); parameters.Add("photo_id", photoId); parameters.Add("api_key", _apiKey); parameters.Add("auth_token", _apiToken); string[] keys = new string[parameters.Keys.Count]; parameters.Keys.CopyTo(keys, 0); Array.Sort(keys); StringBuilder HashStringBuilder = new StringBuilder(_sharedSecret, 2 * 1024); foreach(string key in keys) { HashStringBuilder.Append(key); HashStringBuilder.Append(parameters[key]); sb.Append("--" + boundary + "\r\n"); sb.Append("Content-Disposition: form-data; name=\"" + key + "\"\r\n"); sb.Append("\r\n"); sb.Append(parameters[key] + "\r\n"); } sb.Append("--" + boundary + "\r\n"); sb.Append("Content-Disposition: form-data; name=\"api_sig\"\r\n"); sb.Append("\r\n"); sb.Append(Md5Hash(HashStringBuilder.ToString()) + "\r\n"); // Photo sb.Append("--" + boundary + "\r\n"); sb.Append("Content-Disposition: form-data; name=\"photo\"; filename=\"image.jpeg\"\r\n"); sb.Append("Content-Type: image/jpeg\r\n"); sb.Append("\r\n"); UTF8Encoding encoding = new UTF8Encoding(); byte[] postContents = encoding.GetBytes(sb.ToString()); byte[] photoContents = new byte[stream.Length]; stream.Read(photoContents, 0, photoContents.Length); stream.Close(); byte[] postFooter = encoding.GetBytes("\r\n--" + boundary + "--\r\n"); byte[] dataBuffer = new byte[postContents.Length + photoContents.Length + postFooter.Length]; Buffer.BlockCopy(postContents, 0, dataBuffer, 0, postContents.Length); Buffer.BlockCopy(photoContents, 0, dataBuffer, postContents.Length, photoContents.Length); Buffer.BlockCopy(postFooter, 0, dataBuffer, postContents.Length + photoContents.Length, postFooter.Length); req.ContentLength = dataBuffer.Length; Stream resStream = req.GetRequestStream(); int j = 1; int uploadBit = Math.Max(dataBuffer.Length / 100, 50*1024); int uploadSoFar = 0; for(int i = 0; i < dataBuffer.Length; i=i+uploadBit) { int toUpload = Math.Min(uploadBit, dataBuffer.Length - i); uploadSoFar += toUpload; resStream.Write(dataBuffer, i, toUpload); if( (OnUploadProgress != null) && ((j++) % 5 == 0 || uploadSoFar == dataBuffer.Length) ) { OnUploadProgress(this, new UploadProgressEventArgs(i+toUpload, uploadSoFar == dataBuffer.Length)); } } resStream.Close(); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); XmlSerializer serializer = _uploaderSerializer; StreamReader sr = new StreamReader(res.GetResponseStream()); string s= sr.ReadToEnd(); sr.Close(); StringReader str = new StringReader(s); FlickrNet.Uploader uploader = (FlickrNet.Uploader)serializer.Deserialize(str); if( uploader.Status == ResponseStatus.OK ) { return uploader.PhotoId; } else { throw new FlickrApiException(uploader.Error); } } #endregion #region [ Blogs ] /// /// Gets a list of blogs that have been set up by the user. /// Requires authentication. /// /// A object containing the list of blogs. /// public Blogs BlogGetList() { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.blogs.getList"); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Blogs; } else { throw new FlickrApiException(response.Error); } } /// /// Posts a photo already uploaded to a blog. /// Requires authentication. /// /// The Id of the blog to post the photo too. /// The Id of the photograph to post. /// The title of the blog post. /// The body of the blog post. /// True if the operation is successful. public bool BlogPostPhoto(string blogId, string photoId, string title, string description) { return BlogPostPhoto(blogId, photoId, title, description, null); } /// /// Posts a photo already uploaded to a blog. /// Requires authentication. /// /// The Id of the blog to post the photo too. /// The Id of the photograph to post. /// The title of the blog post. /// The body of the blog post. /// The password of the blog if it is not already stored in flickr. /// True if the operation is successful. public bool BlogPostPhoto(string blogId, string photoId, string title, string description, string blogPassword) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.blogs.postPhoto"); parameters.Add("blog_id", blogId); parameters.Add("photo_id", photoId); parameters.Add("title", title); parameters.Add("description", description); if( blogPassword != null ) parameters.Add("blog_password", blogPassword); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return true; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Contacts ] /// /// Gets a list of contacts for the logged in user. /// Requires authentication. /// /// An instance of the class containing the list of contacts. public Contacts ContactsGetList() { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.contacts.getList"); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Contacts; } else { throw new FlickrApiException(response.Error); } } /// /// Gets a list of the given users contact, or those that are publically avaiable. /// /// The Id of the user who's contacts you want to return. /// An instance of the class containing the list of contacts. public Contacts ContactsGetPublicList(string userId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.contacts.getPublicList"); parameters.Add("user_id", userId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Contacts; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Favorites ] /// /// Adds a photo to the logged in favourites. /// Requires authentication. /// /// The id of the photograph to add. /// True if the operation is successful. public bool FavoritesAdd(string photoId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.favorites.add"); parameters.Add("photo_id", photoId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return true; } else { throw new FlickrApiException(response.Error); } } /// /// Removes a photograph from the logged in users favourites. /// Requires authentication. /// /// The id of the photograph to remove. /// True if the operation is successful. public bool FavoritesRemove(string photoId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.favorites.remove"); parameters.Add("photo_id", photoId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return true; } else { throw new FlickrApiException(response.Error); } } /// /// Get a list of the currently logger in users favourites. /// Requires authentication. /// /// instance containing a collection of objects. public Photos FavoritesGetList() { return FavoritesGetList(null, 0, 0); } /// /// Get a list of the currently logger in users favourites. /// Requires authentication. /// /// Number of photos to include per page. /// The page to download this time. /// instance containing a collection of objects. public Photos FavoritesGetList(int perPage, int page) { return FavoritesGetList(null, perPage, page); } /// /// Get a list of favourites for the specified user. /// /// The user id of the user whose favourites you wish to retrieve. /// instance containing a collection of objects. public Photos FavoritesGetList(string userId) { return FavoritesGetList(userId, 0, 0); } /// /// Get a list of favourites for the specified user. /// /// The user id of the user whose favourites you wish to retrieve. /// Number of photos to include per page. /// The page to download this time. /// instance containing a collection of objects. public Photos FavoritesGetList(string userId, int perPage, int page) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.favorites.getList"); if( userId != null ) parameters.Add("user_id", userId); if( perPage > 0 ) parameters.Add("per_page", perPage.ToString()); if( page > 0 ) parameters.Add("page", page.ToString()); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photos; } else { throw new FlickrApiException(response.Error); } } /// /// Gets the public favourites for a specified user. /// /// This function difers from in that the user id /// is not optional. /// The is of the user whose favourites you wish to return. /// A object containing a collection of objects. public Photos FavoritesGetPublicList(string userId) { return FavoritesGetPublicList(userId, 0, 0); } /// /// Gets the public favourites for a specified user. /// /// This function difers from in that the user id /// is not optional. /// The is of the user whose favourites you wish to return. /// The number of photos to return per page. /// The specific page to return. /// A object containing a collection of objects. public Photos FavoritesGetPublicList(string userId, int perPage, int page) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.favorites.getPublicList"); parameters.Add("user_id", userId); if( perPage > 0 ) parameters.Add("per_page", perPage.ToString()); if( page > 0 ) parameters.Add("page", page.ToString()); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photos; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Groups ] /// /// Returns the top with a list of sub-categories and groups. /// (The top category does not have any groups in it but others may). /// /// A instance. public Category GroupsBrowse() { return GroupsBrowse("0"); } /// /// Returns the specified by the category id with a list of sub-categories and groups. /// /// /// A instance. public Category GroupsBrowse(string catId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.groups.browse"); parameters.Add("cat_id", catId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Category; } else { throw new FlickrApiException(response.Error); } } /// /// Search the list of groups on Flickr for the text. /// /// The text to search for. /// A list of groups matching the search criteria. public GroupSearchResults GroupsSearch(string text) { return GroupsSearch(text, 0, 0); } /// /// Search the list of groups on Flickr for the text. /// /// The text to search for. /// The page of the results to return. /// A list of groups matching the search criteria. public GroupSearchResults GroupsSearch(string text, int page) { return GroupsSearch(text, page, 0); } /// /// Search the list of groups on Flickr for the text. /// /// The text to search for. /// The page of the results to return. /// The number of groups to list per page. /// A list of groups matching the search criteria. public GroupSearchResults GroupsSearch(string text, int page, int perPage) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.groups.search"); parameters.Add("api_key", _apiKey); parameters.Add("text", text); if( page > 0 ) parameters.Add("page", page.ToString()); if( perPage > 0 ) parameters.Add("per_page", perPage.ToString()); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return new GroupSearchResults(response.AllElements[0]); } else { throw new FlickrApiException(response.Error); } } /// /// Returns a object containing details about a group. /// /// The id of the group to return. /// The specified by the group id. public GroupFullInfo GroupsGetInfo(string groupId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.groups.getInfo"); parameters.Add("api_key", _apiKey); parameters.Add("group_id", groupId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return new GroupFullInfo(response.AllElements[0]); } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Group Pool ] /// /// Adds a photo to a pool you have permission to add photos to. /// /// The id of one of your photos to be added. /// The id of a group you are a member of. /// True on a successful addition. public bool GroupPoolAdd(string photoId, string groupId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.groups.pools.add"); parameters.Add("photo_id", photoId); parameters.Add("group_id", groupId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return true; } else { throw new FlickrApiException(response.Error); } } /// /// Gets the context for a photo from within a group. This provides the /// id and thumbnail url for the next and previous photos in the group. /// /// The Photo ID for the photo you want the context for. /// The group ID for the group you want the context to be relevant to. /// The of the photo in the group. public Context GroupPoolGetContext(string photoId, string groupId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.groups.pools.getContext"); parameters.Add("photo_id", photoId); parameters.Add("group_id", groupId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { Context context = new Context(); context.Count = response.ContextCount.Count; context.NextPhoto = response.ContextNextPhoto; context.PreviousPhoto = response.ContextPrevPhoto; return context; } else { throw new FlickrApiException(response.Error); } } /// /// Remove a picture from a group. /// /// The id of one of your pictures you wish to remove. /// The id of the group to remove the picture from. /// True if the photo is successfully removed. public bool GroupPoolRemove(string photoId, string groupId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.groups.pools.remove"); parameters.Add("photo_id", photoId); parameters.Add("group_id", groupId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return true; } else { throw new FlickrApiException(response.Error); } } /// /// Gets a list of /// /// public MemberGroupInfo[] GroupPoolGetGroups() { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.groups.pools.getGroups"); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return MemberGroupInfo.GetMemberGroupInfo(response.AllElements[0]); } else { throw new FlickrApiException(response.Error); } } /// /// Gets a list of photos for a given group. /// /// The group ID for the group. /// A object containing the list of photos. public Photos GroupPoolGetPhotos(string groupId) { return GroupPoolGetPhotos(groupId, null, null, PhotoSearchExtras.All, 0, 0); } /// /// Gets a list of photos for a given group. /// /// The group ID for the group. /// Space seperated list of tags that photos returned must have. /// A object containing the list of photos. public Photos GroupPoolGetPhotos(string groupId, string tags) { return GroupPoolGetPhotos(groupId, tags, null, PhotoSearchExtras.All, 0, 0); } /// /// Gets a list of photos for a given group. /// /// The group ID for the group. /// The number of photos per page. /// The page to return. /// A object containing the list of photos. public Photos GroupPoolGetPhotos(string groupId, int perPage, int page) { return GroupPoolGetPhotos(groupId, null, null, PhotoSearchExtras.All, perPage, page); } /// /// Gets a list of photos for a given group. /// /// The group ID for the group. /// Space seperated list of tags that photos returned must have. /// The number of photos per page. /// The page to return. /// A object containing the list of photos. public Photos GroupPoolGetPhotos(string groupId, string tags, int perPage, int page) { return GroupPoolGetPhotos(groupId, tags, null, PhotoSearchExtras.All, perPage, page); } /// /// Gets a list of photos for a given group. /// /// The group ID for the group. /// Space seperated list of tags that photos returned must have. /// Currently only supports 1 tag at a time. /// The group member to return photos for. /// The specifying which extras to return. All other overloads default to returning all extras. /// The number of photos per page. /// The page to return. /// A object containing the list of photos. public Photos GroupPoolGetPhotos(string groupId, string tags, string userId, PhotoSearchExtras extras, int perPage, int page) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.groups.pools.getPhotos"); parameters.Add("group_id", groupId); if( tags != null && tags.Length > 0 )parameters.Add("tags", tags); if( perPage > 0 ) parameters.Add("per_page", perPage.ToString()); if( page > 0 ) parameters.Add("page", page.ToString()); if( userId != null && userId.Length > 0 ) parameters.Add("user_id", userId); if( extras != PhotoSearchExtras.None ) parameters.Add("extras", Utils.ExtrasToString(extras)); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photos; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Interestingness ] /// /// Gets a list of photos from the most recent interstingness list. /// /// Number of photos per page. /// The page number to return. /// enumeration. /// instance containing list of photos. public Photos InterestingnessGetList(PhotoSearchExtras extras, int perPage, int page) { return InterestingnessGetList(DateTime.MinValue, extras, perPage, page); } /// /// Gets a list of photos from the interstingness list for the specified date. /// /// The date to return the interestingness list for. /// instance containing list of photos. public Photos InterestingnessGetList(DateTime date) { return InterestingnessGetList(date, PhotoSearchExtras.All, 0, 0); } /// /// Gets a list of photos from the most recent interstingness list. /// /// instance containing list of photos. public Photos InterestingnessGetList() { return InterestingnessGetList(DateTime.MinValue, PhotoSearchExtras.All, 0, 0); } /// /// Gets a list of photos from the most recent interstingness list. /// /// The date to return the interestingness photos for. /// The extra parameters to return along with the search results. /// See for more details. /// The number of results to return per page. /// The page of the results to return. /// public Photos InterestingnessGetList(DateTime date, PhotoSearchExtras extras, int perPage, int page) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.interestingness.getList"); if( date > DateTime.MinValue ) parameters.Add("date", date.ToString("yyyy-MM-dd")); if( perPage > 0 ) parameters.Add("per_page", perPage.ToString()); if( page > 0 ) parameters.Add("page", page.ToString()); if( extras != PhotoSearchExtras.None ) parameters.Add("extras", Utils.ExtrasToString(extras)); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photos; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Notes ] /// /// Add a note to a picture. /// /// The photo id to add the note to. /// The X co-ordinate of the upper left corner of the note. /// The Y co-ordinate of the upper left corner of the note. /// The width of the note. /// The height of the note. /// The text in the note. /// public string NotesAdd(string photoId, int noteX, int noteY, int noteWidth, int noteHeight, string noteText) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.notes.add"); parameters.Add("photo_id", photoId); parameters.Add("note_x", noteX.ToString()); parameters.Add("note_y", noteY.ToString()); parameters.Add("note_w", noteWidth.ToString()); parameters.Add("note_h", noteHeight.ToString()); parameters.Add("note_text", noteText); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { foreach(XmlElement element in response.AllElements) { return element.Attributes["id", ""].Value; } return string.Empty; } else { throw new FlickrApiException(response.Error); } } /// /// Edit and update a note. /// /// The ID of the note to update. /// The X co-ordinate of the upper left corner of the note. /// The Y co-ordinate of the upper left corner of the note. /// The width of the note. /// The height of the note. /// The new text in the note. public void NotesEdit(string noteId, int noteX, int noteY, int noteWidth, int noteHeight, string noteText) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.notes.edit"); parameters.Add("note_id", noteId); parameters.Add("note_x", noteX.ToString()); parameters.Add("note_y", noteY.ToString()); parameters.Add("note_w", noteWidth.ToString()); parameters.Add("note_h", noteHeight.ToString()); parameters.Add("note_text", noteText); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } /// /// Delete an existing note. /// /// The ID of the note. public void NotesDelete(string noteId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.notes.delete"); parameters.Add("note_id", noteId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ People ] /// /// Used to fid a flickr users details by specifying their email address. /// /// The email address to search on. /// The object containing the matching details. /// A FlickrApiException is raised if the email address is not found. public FoundUser PeopleFindByEmail(string emailAddress) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.people.findByEmail"); parameters.Add("api_key", _apiKey); parameters.Add("find_email", emailAddress); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return new FoundUser(response.AllElements[0]); } else { throw new FlickrApiException(response.Error); } } /// /// Returns a object matching the screen name. /// /// The screen name or username of the user. /// A class containing the userId and username of the user. /// A FlickrApiException is raised if the email address is not found. public FoundUser PeopleFindByUsername(string username) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.people.findByUsername"); parameters.Add("api_key", _apiKey); parameters.Add("username", username); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return new FoundUser(response.AllElements[0]); } else { throw new FlickrApiException(response.Error); } } /// /// Gets the object for the given user id. /// /// The user id to find. /// The object containing the users details. public Person PeopleGetInfo(string userId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.people.getInfo"); parameters.Add("api_key", _apiKey); parameters.Add("user_id", userId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return Person.SerializePerson(response.AllElements[0]); } else { throw new FlickrApiException(response.Error); } } /// /// Gets the upload status of the authenticated user. /// /// The object containing the users details. public UserStatus PeopleGetUploadStatus() { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.people.getUploadStatus"); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return new UserStatus(response.AllElements[0]); } else { throw new FlickrApiException(response.Error); } } /// /// Get a list of public groups for a user. /// /// The user id to get groups for. /// An array of instances. public PublicGroupInfo[] PeopleGetPublicGroups(string userId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.people.getPublicGroups"); parameters.Add("api_key", _apiKey); parameters.Add("user_id", userId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return PublicGroupInfo.GetPublicGroupInfo(response.AllElements[0]); } else { throw new FlickrApiException(response.Error); } } /// /// Gets a users public photos. Excludes private photos. /// /// The user id of the user. /// The collection of photos contained within a object. public Photos PeopleGetPublicPhotos(string userId) { return PeopleGetPublicPhotos(userId, 0, 0, SafetyLevel.None, PhotoSearchExtras.None); } /// /// Gets a users public photos. Excludes private photos. /// /// The user id of the user. /// The page to return. Defaults to page 1. /// The number of photos to return per page. Default is 100. /// The collection of photos contained within a object. public Photos PeopleGetPublicPhotos(string userId, int perPage, int page) { return PeopleGetPublicPhotos(userId, perPage, page, SafetyLevel.None, PhotoSearchExtras.None); } /// /// Gets a users public photos. Excludes private photos. /// /// The user id of the user. /// The page to return. Defaults to page 1. /// The number of photos to return per page. Default is 100. /// Which (if any) extra information to return. The default is none. /// The safety level of the returned photos. /// Unauthenticated calls can only return Safe photos. /// The collection of photos contained within a object. public Photos PeopleGetPublicPhotos(string userId, int perPage, int page, SafetyLevel safetyLevel, PhotoSearchExtras extras) { if( !IsAuthenticated && safetyLevel > SafetyLevel.Safe ) throw new ArgumentException("Safety level may only be 'Safe' for unauthenticated calls", "safetyLevel"); Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.people.getPublicPhotos"); parameters.Add("api_key", _apiKey); parameters.Add("user_id", userId); if( perPage > 0 ) parameters.Add("per_page", perPage.ToString()); if( page > 0 ) parameters.Add("page", page.ToString()); if( safetyLevel != SafetyLevel.None ) parameters.Add("safety_level", (int)safetyLevel); if( extras != PhotoSearchExtras.None ) parameters.Add("extras", Utils.ExtrasToString(extras)); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photos; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Photos ] /// /// Add a selection of tags to a photo. /// /// The photo id of the photo. /// An array of strings containing the tags. /// True if the tags are added successfully. public void PhotosAddTags(string photoId, string[] tags) { string s = string.Join(",", tags); PhotosAddTags(photoId, s); } /// /// Add a selection of tags to a photo. /// /// The photo id of the photo. /// An string of comma delimited tags. /// True if the tags are added successfully. public void PhotosAddTags(string photoId, string tags) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.addTags"); parameters.Add("photo_id", photoId); parameters.Add("tags", tags); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } /// /// Delete a photo from Flickr. /// /// /// Requires Delete permissions. Also note, photos cannot be recovered once deleted. /// The ID of the photo to delete. public void PhotosDelete(string photoId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.delete"); parameters.Add("photo_id", photoId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } /// /// Get all the contexts (group, set and photostream 'next' and 'previous' /// pictures) for a photo. /// /// The photo id of the photo to get the contexts for. /// An instance of the class. public AllContexts PhotosGetAllContexts(string photoId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.getAllContexts"); parameters.Add("photo_id", photoId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { AllContexts contexts = new AllContexts(response.AllElements); return contexts; } else { throw new FlickrApiException(response.Error); } } /// /// Gets the most recent 10 photos from your contacts. /// /// An instance of the class containing the photos. public Photos PhotosGetContactsPhotos() { return PhotosGetContactsPhotos(0, false, false, false); } /// /// Gets the most recent photos from your contacts. /// /// Returns the most recent photos from all your contact, excluding yourself. /// The number of photos to return, from between 10 and 50. /// An instance of the class containing the photos. /// /// Throws a exception if the cound /// is not between 10 and 50, or 0. public Photos PhotosGetContactsPhotos(long count) { return PhotosGetContactsPhotos(count, false, false, false); } /// /// Gets your contacts most recent photos. /// /// The number of photos to return, from between 10 and 50. /// If true only returns photos from contacts marked as /// 'friends'. /// If true only returns a single photo for each of your contacts. /// Ignores the count if this is true. /// If true includes yourself in the group of people to /// return photos for. /// An instance of the class containing the photos. /// /// Throws a exception if the cound /// is not between 10 and 50, or 0. public Photos PhotosGetContactsPhotos(long count, bool justFriends, bool singlePhoto, bool includeSelf) { if( count != 0 && (count < 10 || count > 50) && !singlePhoto ) { throw new ArgumentOutOfRangeException("count", String.Format("Count must be between 10 and 50. ({0})", count)); } Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.getContactsPhotos"); if( count > 0 && !singlePhoto ) parameters.Add("count", count.ToString()); if( justFriends ) parameters.Add("just_friends", "1"); if( singlePhoto ) parameters.Add("single_photo", "1"); if( includeSelf ) parameters.Add("include_self", "1"); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photos; } else { throw new FlickrApiException(response.Error); } } /// /// Gets the public photos for given users ID's contacts. /// /// The user ID whose contacts you wish to get photos for. /// A object containing details of the photos returned. public Photos PhotosGetContactsPublicPhotos(string userId) { return PhotosGetContactsPublicPhotos(userId, 0, false, false, false, PhotoSearchExtras.All); } /// /// Gets the public photos for given users ID's contacts. /// /// The user ID whose contacts you wish to get photos for. /// A list of extra details to return for each photo. /// A object containing details of the photos returned. public Photos PhotosGetContactsPublicPhotos(string userId, PhotoSearchExtras extras) { return PhotosGetContactsPublicPhotos(userId, 0, false, false, false, extras); } /// /// Gets the public photos for given users ID's contacts. /// /// The user ID whose contacts you wish to get photos for. /// The number of photos to return. Defaults to 10, maximum is 50. /// A object containing details of the photos returned. public Photos PhotosGetContactsPublicPhotos(string userId, long count) { return PhotosGetContactsPublicPhotos(userId, count, false, false, false, PhotoSearchExtras.All); } /// /// Gets the public photos for given users ID's contacts. /// /// The user ID whose contacts you wish to get photos for. /// The number of photos to return. Defaults to 10, maximum is 50. /// A list of extra details to return for each photo. /// A object containing details of the photos returned. public Photos PhotosGetContactsPublicPhotos(string userId, long count, PhotoSearchExtras extras) { return PhotosGetContactsPublicPhotos(userId, count, false, false, false, extras); } /// /// Gets the public photos for given users ID's contacts. /// /// The user ID whose contacts you wish to get photos for. /// The number of photos to return. Defaults to 10, maximum is 50. /// True to just return photos from friends and family (excluding regular contacts). /// True to return just a single photo for each contact. /// True to include photos from the user ID specified as well. /// public Photos PhotosGetContactsPublicPhotos(string userId, long count, bool justFriends, bool singlePhoto, bool includeSelf) { return PhotosGetContactsPublicPhotos(userId, count, justFriends, singlePhoto, includeSelf, PhotoSearchExtras.All); } /// /// Gets the public photos for given users ID's contacts. /// /// The user ID whose contacts you wish to get photos for. /// The number of photos to return. Defaults to 10, maximum is 50. /// True to just return photos from friends and family (excluding regular contacts). /// True to return just a single photo for each contact. /// True to include photos from the user ID specified as well. /// A list of extra details to return for each photo. /// public Photos PhotosGetContactsPublicPhotos(string userId, long count, bool justFriends, bool singlePhoto, bool includeSelf, PhotoSearchExtras extras) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.getContactsPublicPhotos"); parameters.Add("api_key", _apiKey); parameters.Add("user_id", userId); if( count > 0 ) parameters.Add("count", count.ToString()); if( justFriends ) parameters.Add("just_friends", "1"); if( singlePhoto ) parameters.Add("single_photo", "1"); if( includeSelf ) parameters.Add("include_self", "1"); if( extras != PhotoSearchExtras.None ) parameters.Add("extras", Utils.ExtrasToString(extras)); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photos; } else { throw new FlickrApiException(response.Error); } } /// /// Gets the context of the photo in the users photostream. /// /// The ID of the photo to return the context for. /// public Context PhotosGetContext(string photoId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.getContext"); parameters.Add("photo_id", photoId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { Context c = new Context(); c.Count = response.ContextCount.Count; c.NextPhoto = response.ContextNextPhoto; c.PreviousPhoto = response.ContextPrevPhoto; return c; } else { throw new FlickrApiException(response.Error); } } /// /// Returns count of photos between each pair of dates in the list. /// /// If you pass in DateA, DateB and DateC it returns /// a list of the number of photos between DateA and DateB, /// followed by the number between DateB and DateC. /// More parameters means more sets. /// Array of objects. /// class instance. public PhotoCounts PhotosGetCounts(DateTime[] dates) { return PhotosGetCounts(dates, false); } /// /// Returns count of photos between each pair of dates in the list. /// /// If you pass in DateA, DateB and DateC it returns /// a list of the number of photos between DateA and DateB, /// followed by the number between DateB and DateC. /// More parameters means more sets. /// Array of objects. /// Boolean parameter to specify if the dates are the taken date, or uploaded date. /// class instance. public PhotoCounts PhotosGetCounts(DateTime[] dates, bool taken) { StringBuilder s = new StringBuilder(dates.Length * 20); foreach(DateTime d in dates) { s.Append(Utils.DateToUnixTimestamp(d)); s.Append(","); } if( s.Length > 0 ) s.Remove(s.Length-2,1); if( taken ) return PhotosGetCounts(null, s.ToString()); else return PhotosGetCounts(s.ToString(), null); } /// /// Returns count of photos between each pair of dates in the list. /// /// If you pass in DateA, DateB and DateC it returns /// a list of the number of photos between DateA and DateB, /// followed by the number between DateB and DateC. /// More parameters means more sets. /// Comma-delimited list of dates in unix timestamp format. Optional. /// class instance. public PhotoCounts PhotosGetCounts(string dates) { return PhotosGetCounts(dates, null); } /// /// Returns count of photos between each pair of dates in the list. /// /// If you pass in DateA, DateB and DateC it returns /// a list of the number of photos between DateA and DateB, /// followed by the number between DateB and DateC. /// More parameters means more sets. /// Comma-delimited list of dates in unix timestamp format. Optional. /// Comma-delimited list of dates in unix timestamp format. Optional. /// class instance. public PhotoCounts PhotosGetCounts(string dates, string taken_dates) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.getContactsPhotos"); if( dates != null && dates.Length > 0 ) parameters.Add("dates", dates); if( taken_dates != null && taken_dates.Length > 0 ) parameters.Add("taken_dates", taken_dates); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.PhotoCounts; } else { throw new FlickrApiException(response.Error); } } /// /// Gets the EXIF data for a given Photo ID. /// /// The Photo ID of the photo to return the EXIF data for. /// An instance of the class containing the EXIF data. public ExifPhoto PhotosGetExif(string photoId) { return PhotosGetExif(photoId, null); } /// /// Gets the EXIF data for a given Photo ID. /// /// The Photo ID of the photo to return the EXIF data for. /// The secret of the photo. If the secret is specified then /// authentication checks are bypassed. /// An instance of the class containing the EXIF data. public ExifPhoto PhotosGetExif(string photoId, string secret) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.getExif"); parameters.Add("photo_id", photoId); if( secret != null ) parameters.Add("secret", secret); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { ExifPhoto e = new ExifPhoto(response.PhotoInfo.PhotoId, response.PhotoInfo.Secret, response.PhotoInfo.Server, response.PhotoInfo.ExifTagCollection); return e; } else { throw new FlickrApiException(response.Error); } } /// /// Get information about a photo. The calling user must have permission to view the photo. /// /// The id of the photo to fetch information for. /// A class detailing the properties of the photo. public PhotoInfo PhotosGetInfo(string photoId) { return PhotosGetInfo(photoId, null); } /// /// Get information about a photo. The calling user must have permission to view the photo. /// /// The id of the photo to fetch information for. /// The secret for the photo. If the correct secret is passed then permissions checking is skipped. This enables the 'sharing' of individual photos by passing around the id and secret. /// A class detailing the properties of the photo. public PhotoInfo PhotosGetInfo(string photoId, string secret) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.getInfo"); parameters.Add("photo_id", photoId); if( secret != null ) parameters.Add("secret", secret); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.PhotoInfo; } else { throw new FlickrApiException(response.Error); } } /// /// Get permissions for a photo. /// /// The id of the photo to get permissions for. /// An instance of the class containing the permissions of the specified photo. public PhotoPermissions PhotosGetPerms(string photoId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.getPerms"); parameters.Add("photo_id", photoId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return new PhotoPermissions(response.AllElements[0]); } else { throw new FlickrApiException(response.Error); } } /// /// Returns a list of the latest public photos uploaded to flickr. /// /// A class containing the list of photos. public Photos PhotosGetRecent() { return PhotosGetRecent(0, 0, PhotoSearchExtras.All); } /// /// Returns a list of the latest public photos uploaded to flickr. /// /// A comma-delimited list of extra information to fetch for each returned record. /// A class containing the list of photos. public Photos PhotosGetRecent(PhotoSearchExtras extras) { return PhotosGetRecent(0, 0, extras); } /// /// Returns a list of the latest public photos uploaded to flickr. /// /// The page of results to return. If this argument is omitted, it defaults to 1. /// Number of photos to return per page. If this argument is omitted, it defaults to 100. The maximum allowed value is 500. /// A class containing the list of photos. public Photos PhotosGetRecent(long perPage, long page) { return PhotosGetRecent(perPage, page, PhotoSearchExtras.All); } /// /// Returns a list of the latest public photos uploaded to flickr. /// /// A comma-delimited list of extra information to fetch for each returned record. /// The page of results to return. If this argument is omitted, it defaults to 1. /// Number of photos to return per page. If this argument is omitted, it defaults to 100. The maximum allowed value is 500. /// A class containing the list of photos. public Photos PhotosGetRecent(long perPage, long page, PhotoSearchExtras extras) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.getRecent"); parameters.Add("api_key", _apiKey); if( perPage > 0 ) parameters.Add("per_page", perPage.ToString()); if( page > 0 ) parameters.Add("page", page.ToString()); if( extras != PhotoSearchExtras.None ) parameters.Add("extras", Utils.ExtrasToString(extras)); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photos; } else { throw new FlickrApiException(response.Error); } } /// /// Returns the available sizes for a photo. The calling user must have permission to view the photo. /// /// The id of the photo to fetch size information for. /// A class whose property is an array of objects. public Sizes PhotosGetSizes(string photoId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.getSizes"); parameters.Add("photo_id", photoId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Sizes; } else { throw new FlickrApiException(response.Error); } } /// /// Returns a list of your photos with no tags. /// /// A class containing the list of photos. public Photos PhotosGetUntagged() { return PhotosGetUntagged(0, 0, PhotoSearchExtras.All); } /// /// Returns a list of your photos with no tags. /// /// A comma-delimited list of extra information to fetch for each returned record. /// A class containing the list of photos. public Photos PhotosGetUntagged(PhotoSearchExtras extras) { return PhotosGetUntagged(0, 0, extras); } /// /// Returns a list of your photos with no tags. /// /// The page of results to return. If this argument is omitted, it defaults to 1. /// Number of photos to return per page. If this argument is omitted, it defaults to 100. The maximum allowed value is 500. /// A class containing the list of photos. public Photos PhotosGetUntagged(int perPage, int page) { return PhotosGetUntagged(perPage, page, PhotoSearchExtras.All); } /// /// Returns a list of your photos with no tags. /// /// A comma-delimited list of extra information to fetch for each returned record. /// The page of results to return. If this argument is omitted, it defaults to 1. /// Number of photos to return per page. If this argument is omitted, it defaults to 100. The maximum allowed value is 500. /// A class containing the list of photos. public Photos PhotosGetUntagged(int perPage, int page, PhotoSearchExtras extras) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.getUntagged"); if( perPage > 0 ) parameters.Add("per_page", perPage.ToString()); if( page > 0 ) parameters.Add("page", page.ToString()); if( extras != PhotoSearchExtras.None ) parameters.Add("extras", Utils.ExtrasToString(extras)); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photos; } else { throw new FlickrApiException(response.Error); } } /// /// Gets a list of photos not in sets. Defaults to include all extra fields. /// /// instance containing list of photos. public Photos PhotosGetNotInSet() { return PhotosGetNotInSet(new PartialSearchOptions()); } /// /// Gets a specific page of the list of photos which are not in sets. /// Defaults to include all extra fields. /// /// The page number to return. /// instance containing list of photos. public Photos PhotosGetNotInSet(int page) { return PhotosGetNotInSet(0, page, PhotoSearchExtras.None); } /// /// Gets a specific page of the list of photos which are not in sets. /// Defaults to include all extra fields. /// /// Number of photos per page. /// The page number to return. /// instance containing list of photos. public Photos PhotosGetNotInSet(int perPage, int page) { return PhotosGetNotInSet(perPage, page, PhotoSearchExtras.None); } /// /// Gets a list of a users photos which are not in a set. /// /// Number of photos per page. /// The page number to return. /// enumeration. /// instance containing list of photos. public Photos PhotosGetNotInSet(int perPage, int page, PhotoSearchExtras extras) { PartialSearchOptions options = new PartialSearchOptions(); options.PerPage = perPage; options.Page = page; options.Extras = extras; return PhotosGetNotInSet(options); } /// /// Gets a list of the authenticated users photos which are not in a set. /// /// A selection of options to filter/sort by. /// A collection of photos in the class. public Photos PhotosGetNotInSet(PartialSearchOptions options) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.getNotInSet"); Utils.PartialOptionsIntoArray(options, parameters); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photos; } else { throw new FlickrApiException(response.Error); } } /// /// Gets a list of all current licenses. /// /// instance. public Licenses PhotosLicensesGetInfo() { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.licenses.getInfo"); parameters.Add("api_key", _apiKey); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Licenses; } else { throw new FlickrApiException(response.Error); } } /// /// Remove an existing tag. /// /// The id of the tag, as returned by or similar method. /// True if the tag was removed. public bool PhotosRemoveTag(string tagId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.removeTag"); parameters.Add("tag_id", tagId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return true; } else { throw new FlickrApiException(response.Error); } } /// /// Return a list of your photos that have been recently created or which have been recently modified. /// Recently modified may mean that the photo's metadata (title, description, tags) /// may have been changed or a comment has been added (or just modified somehow :-) /// /// The date from which modifications should be compared. /// A list of extra information to fetch for each returned record. /// Returns a instance containing the list of photos. public Photos PhotosRecentlyUpdated(DateTime minDate, PhotoSearchExtras extras) { return PhotosRecentlyUpdated(minDate, extras, 0, 0); } /// /// Return a list of your photos that have been recently created or which have been recently modified. /// Recently modified may mean that the photo's metadata (title, description, tags) /// may have been changed or a comment has been added (or just modified somehow :-) /// /// The date from which modifications should be compared. /// Number of photos to return per page. If this argument is omitted, it defaults to 100. The maximum allowed value is 500. /// The page of results to return. If this argument is omitted, it defaults to 1. /// Returns a instance containing the list of photos. public Photos PhotosRecentlyUpdated(DateTime minDate, int perPage, int page) { return PhotosRecentlyUpdated(minDate, PhotoSearchExtras.None, perPage, page); } /// /// Return a list of your photos that have been recently created or which have been recently modified. /// Recently modified may mean that the photo's metadata (title, description, tags) /// may have been changed or a comment has been added (or just modified somehow :-) /// /// The date from which modifications should be compared. /// Returns a instance containing the list of photos. public Photos PhotosRecentlyUpdated(DateTime minDate) { return PhotosRecentlyUpdated(minDate, PhotoSearchExtras.None, 0, 0); } /// /// Return a list of your photos that have been recently created or which have been recently modified. /// Recently modified may mean that the photo's metadata (title, description, tags) /// may have been changed or a comment has been added (or just modified somehow :-) /// /// The date from which modifications should be compared. /// A list of extra information to fetch for each returned record. /// Number of photos to return per page. If this argument is omitted, it defaults to 100. The maximum allowed value is 500. /// The page of results to return. If this argument is omitted, it defaults to 1. /// Returns a instance containing the list of photos. public Photos PhotosRecentlyUpdated(DateTime minDate, PhotoSearchExtras extras, int perPage, int page) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.recentlyUpdated"); parameters.Add("min_date", Utils.DateToUnixTimestamp(minDate).ToString()); if( extras != PhotoSearchExtras.None ) parameters.Add("extras", Utils.ExtrasToString(extras)); if( perPage > 0 ) parameters.Add("per_page", perPage.ToString()); if( page > 0 ) parameters.Add("page", page.ToString()); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photos; } else { throw new FlickrApiException(response.Error); } } /// /// Search for photos containing text, rather than tags. /// /// The user whose photos you wish to search for. /// The text you want to search for in titles and descriptions. /// A instance. public Photos PhotosSearchText(string userId, string text) { return PhotosSearch(userId, "", 0, text, DateTime.MinValue, DateTime.MinValue, 0, 0, 0, PhotoSearchExtras.All); } /// /// Search for photos containing text, rather than tags. /// /// The user whose photos you wish to search for. /// The text you want to search for in titles and descriptions. /// Optional extras to return. /// A instance. public Photos PhotosSearchText(string userId, string text, PhotoSearchExtras extras) { return PhotosSearch(userId, "", 0, text, DateTime.MinValue, DateTime.MinValue, 0, 0, 0, extras); } /// /// Search for photos containing text, rather than tags. /// /// The user whose photos you wish to search for. /// The text you want to search for in titles and descriptions. /// The license type to return. /// A instance. public Photos PhotosSearchText(string userId, string text, int license) { return PhotosSearch(userId, "", 0, text, DateTime.MinValue, DateTime.MinValue, license, 0, 0, PhotoSearchExtras.All); } /// /// Search for photos containing text, rather than tags. /// /// The user whose photos you wish to search for. /// The text you want to search for in titles and descriptions. /// The license type to return. /// Optional extras to return. /// A instance. public Photos PhotosSearchText(string userId, string text, int license, PhotoSearchExtras extras) { return PhotosSearch(userId, "", 0, text, DateTime.MinValue, DateTime.MinValue, license, 0, 0, extras); } /// /// Search for photos containing text, rather than tags. /// /// The text you want to search for in titles and descriptions. /// Optional extras to return. /// A instance. public Photos PhotosSearchText(string text, PhotoSearchExtras extras) { return PhotosSearch(null, "", 0, text, DateTime.MinValue, DateTime.MinValue, 0, 0, 0, extras); } /// /// Search for photos containing text, rather than tags. /// /// The text you want to search for in titles and descriptions. /// A instance. public Photos PhotosSearchText(string text) { return PhotosSearch(null, "", 0, text, DateTime.MinValue, DateTime.MinValue, 0, 0, 0, PhotoSearchExtras.All); } /// /// Search for photos containing text, rather than tags. /// /// The text you want to search for in titles and descriptions. /// The license type to return. /// A instance. public Photos PhotosSearchText(string text, int license) { return PhotosSearch(null, "", 0, text, DateTime.MinValue, DateTime.MinValue, license, 0, 0, PhotoSearchExtras.All); } /// /// Search for photos containing text, rather than tags. /// /// The text you want to search for in titles and descriptions. /// The license type to return. /// Optional extras to return. /// A instance. public Photos PhotosSearchText(string text, int license, PhotoSearchExtras extras) { return PhotosSearch(null, "", 0, text, DateTime.MinValue, DateTime.MinValue, license, 0, 0, extras); } /// /// Search for photos containing an array of tags. /// /// An array of tags to search for. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string[] tags, PhotoSearchExtras extras) { return PhotosSearch(null, tags, 0, "", DateTime.MinValue, DateTime.MinValue, 0, 0, 0, extras); } /// /// Search for photos containing an array of tags. /// /// An array of tags to search for. /// A instance. public Photos PhotosSearch(string[] tags) { return PhotosSearch(null, tags, 0, "", DateTime.MinValue, DateTime.MinValue, 0, 0, 0, PhotoSearchExtras.All); } /// /// Search for photos containing an array of tags. /// /// An array of tags to search for. /// The license type to return. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string[] tags, int license, PhotoSearchExtras extras) { return PhotosSearch(null, tags, 0, "", DateTime.MinValue, DateTime.MinValue, license, 0, 0, extras); } /// /// Search for photos containing an array of tags. /// /// An array of tags to search for. /// The license type to return. /// A instance. public Photos PhotosSearch(string[] tags, int license) { return PhotosSearch(null, tags, 0, "", DateTime.MinValue, DateTime.MinValue, license, 0, 0, PhotoSearchExtras.All); } /// /// Search for photos. /// /// An array of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// Number of photos to return per page. /// The page number to return. /// A instance. public Photos PhotosSearch(string[] tags, TagMode tagMode, string text, int perPage, int page) { return PhotosSearch(null, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, perPage, page, PhotoSearchExtras.All); } /// /// Search for photos. /// /// An array of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// Number of photos to return per page. /// The page number to return. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string[] tags, TagMode tagMode, string text, int perPage, int page, PhotoSearchExtras extras) { return PhotosSearch(null, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, perPage, page, extras); } /// /// Search for photos. /// /// An array of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// A instance. public Photos PhotosSearch(string[] tags, TagMode tagMode, string text) { return PhotosSearch(null, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, 0, 0, PhotoSearchExtras.All); } /// /// Search for photos. /// /// An array of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string[] tags, TagMode tagMode, string text, PhotoSearchExtras extras) { return PhotosSearch(null, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, 0, 0, extras); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// An array of tags to search for. /// A instance. public Photos PhotosSearch(string userId, string[] tags) { return PhotosSearch(userId, tags, 0, "", DateTime.MinValue, DateTime.MinValue, 0, 0, 0, PhotoSearchExtras.All); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// An array of tags to search for. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string userId, string[] tags, PhotoSearchExtras extras) { return PhotosSearch(userId, tags, 0, "", DateTime.MinValue, DateTime.MinValue, 0, 0, 0, extras); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// An array of tags to search for. /// The license type to return. /// A instance. public Photos PhotosSearch(string userId, string[] tags, int license) { return PhotosSearch(userId, tags, 0, "", DateTime.MinValue, DateTime.MinValue, license, 0, 0, PhotoSearchExtras.All); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// An array of tags to search for. /// The license type to return. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string userId, string[] tags, int license, PhotoSearchExtras extras) { return PhotosSearch(userId, tags, 0, "", DateTime.MinValue, DateTime.MinValue, license, 0, 0, extras); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// An array of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// Number of photos to return per page. /// The page number to return. /// A instance. public Photos PhotosSearch(string userId, string[] tags, TagMode tagMode, string text, int perPage, int page) { return PhotosSearch(userId, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, perPage, page, PhotoSearchExtras.All); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// An array of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// Number of photos to return per page. /// The page number to return. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string userId, string[] tags, TagMode tagMode, string text, int perPage, int page, PhotoSearchExtras extras) { return PhotosSearch(userId, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, perPage, page, extras); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// An array of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// A instance. public Photos PhotosSearch(string userId, string[] tags, TagMode tagMode, string text) { return PhotosSearch(userId, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, 0, 0, PhotoSearchExtras.All); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// An array of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string userId, string[] tags, TagMode tagMode, string text, PhotoSearchExtras extras) { return PhotosSearch(userId, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, 0, 0, extras); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// An array of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// The minimum upload date. /// The maxmimum upload date. /// The license type to return. /// Number of photos to return per page. /// The page number to return. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string userId, string[] tags, TagMode tagMode, string text, DateTime minUploadDate, DateTime maxUploadDate, int license, int perPage, int page, PhotoSearchExtras extras) { return PhotosSearch(userId, String.Join(",", tags), tagMode, text, minUploadDate, maxUploadDate, license, perPage, page, extras); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// An array of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// The minimum upload date. /// The maxmimum upload date. /// The license type to return. /// Number of photos to return per page. /// The page number to return. /// A instance. public Photos PhotosSearch(string userId, string[] tags, TagMode tagMode, string text, DateTime minUploadDate, DateTime maxUploadDate, int license, int perPage, int page) { return PhotosSearch(userId, String.Join(",", tags), tagMode, text, minUploadDate, maxUploadDate, license, perPage, page, PhotoSearchExtras.All); } // PhotoSearch - tags versions /// /// Search for photos. /// /// A comma seperated list of tags to search for. /// The license type to return. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string tags, int license, PhotoSearchExtras extras) { return PhotosSearch(null, tags, 0, "", DateTime.MinValue, DateTime.MinValue, license, 0, 0, extras); } /// /// Search for photos. /// /// A comma seperated list of tags to search for. /// The license type to return. /// A instance. public Photos PhotosSearch(string tags, int license) { return PhotosSearch(null, tags, 0, "", DateTime.MinValue, DateTime.MinValue, license, 0, 0, PhotoSearchExtras.All); } /// /// Search for photos. /// /// A comma seperated list of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// Number of photos to return per page. /// The page number to return. /// A instance. public Photos PhotosSearch(string tags, TagMode tagMode, string text, int perPage, int page) { return PhotosSearch(null, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, perPage, page, PhotoSearchExtras.All); } /// /// Search for photos. /// /// A comma seperated list of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// Number of photos to return per page. /// The page number to return. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string tags, TagMode tagMode, string text, int perPage, int page, PhotoSearchExtras extras) { return PhotosSearch(null, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, perPage, page, extras); } /// /// Search for photos. /// /// A comma seperated list of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// A instance. public Photos PhotosSearch(string tags, TagMode tagMode, string text) { return PhotosSearch(null, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, 0, 0, PhotoSearchExtras.All); } /// /// Search for photos. /// /// A comma seperated list of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string tags, TagMode tagMode, string text, PhotoSearchExtras extras) { return PhotosSearch(null, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, 0, 0, extras); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// A comma seperated list of tags to search for. /// A instance. public Photos PhotosSearch(string userId, string tags) { return PhotosSearch(userId, tags, 0, "", DateTime.MinValue, DateTime.MinValue, 0, 0, 0, PhotoSearchExtras.All); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// A comma seperated list of tags to search for. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string userId, string tags, PhotoSearchExtras extras) { return PhotosSearch(userId, tags, 0, "", DateTime.MinValue, DateTime.MinValue, 0, 0, 0, extras); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// A comma seperated list of tags to search for. /// The license type to return. /// A instance. public Photos PhotosSearch(string userId, string tags, int license) { return PhotosSearch(userId, tags, 0, "", DateTime.MinValue, DateTime.MinValue, license, 0, 0, PhotoSearchExtras.All); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// A comma seperated list of tags to search for. /// The license type to return. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string userId, string tags, int license, PhotoSearchExtras extras) { return PhotosSearch(userId, tags, 0, "", DateTime.MinValue, DateTime.MinValue, license, 0, 0, extras); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// A comma seperated list of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// Number of photos to return per page. /// The page number to return. /// A instance. public Photos PhotosSearch(string userId, string tags, TagMode tagMode, string text, int perPage, int page) { return PhotosSearch(userId, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, perPage, page, PhotoSearchExtras.All); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// A comma seperated list of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// Number of photos to return per page. /// The page number to return. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string userId, string tags, TagMode tagMode, string text, int perPage, int page, PhotoSearchExtras extras) { return PhotosSearch(userId, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, perPage, page, extras); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// A comma seperated list of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// A instance. public Photos PhotosSearch(string userId, string tags, TagMode tagMode, string text) { return PhotosSearch(userId, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, 0, 0, PhotoSearchExtras.All); } /// /// Search for photos. /// /// The ID of the user to search the photos of. /// A comma seperated list of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// Optional extras to return. /// A instance. public Photos PhotosSearch(string userId, string tags, TagMode tagMode, string text, PhotoSearchExtras extras) { return PhotosSearch(userId, tags, tagMode, text, DateTime.MinValue, DateTime.MinValue, 0, 0, 0, extras); } // Actual PhotoSearch function /// /// Search for photos. /// /// The ID of the user to search the photos of. /// A comma seperated list of tags to search for. /// Match all tags, or any tag. /// Text to search for in photo title or description. /// Number of photos to return per page. /// The page number to return. /// Optional extras to return. /// The minimum upload date. /// The maxmimum upload date. /// The license type to return. /// A instance. public Photos PhotosSearch(string userId, string tags, TagMode tagMode, string text, DateTime minUploadDate, DateTime maxUploadDate, int license, int perPage, int page, PhotoSearchExtras extras) { PhotoSearchOptions options = new PhotoSearchOptions(); options.UserId = userId; options.Tags = tags; options.TagMode = tagMode; options.Text = text; options.MinUploadDate = minUploadDate; options.MaxUploadDate = maxUploadDate; if( license > 0 ) options.AddLicense(license); options.PerPage = perPage; options.Page = page; options.Extras = extras; return PhotosSearch(options); } /// /// Search for a set of photos, based on the value of the parameters. /// /// The parameters to search for. /// A collection of photos contained within a object. public Photos PhotosSearch(PhotoSearchOptions options) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.search"); if( options.UserId != null && options.UserId.Length > 0 ) parameters.Add("user_id", options.UserId); if( options.GroupId != null && options.GroupId.Length > 0 ) parameters.Add("group_id", options.GroupId); if( options.Text != null && options.Text.Length > 0 ) parameters.Add("text", options.Text); if( options.Tags != null && options.Tags.Length > 0 ) parameters.Add("tags", options.Tags); if( options.TagMode != TagMode.None ) parameters.Add("tag_mode", options.TagModeString); if( options.MachineTags != null && options.MachineTags.Length > 0 ) parameters.Add("machine_tags", options.MachineTags); if( options.MachineTagMode != MachineTagMode.None ) parameters.Add("machine_tag_mode", options.MachineTagModeString); if( options.MinUploadDate != DateTime.MinValue ) parameters.Add("min_upload_date", Utils.DateToUnixTimestamp(options.MinUploadDate).ToString()); if( options.MaxUploadDate != DateTime.MinValue ) parameters.Add("max_upload_date", Utils.DateToUnixTimestamp(options.MaxUploadDate).ToString()); if( options.MinTakenDate != DateTime.MinValue ) parameters.Add("min_taken_date", options.MinTakenDate.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo)); if( options.MaxTakenDate != DateTime.MinValue ) parameters.Add("max_taken_date", options.MaxTakenDate.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo)); if( options.Licenses.Length != 0 ) { string lic = ""; for(int i = 0; i < options.Licenses.Length; i++) { if( i > 0 ) lic += ","; lic += Convert.ToString(options.Licenses[i]); } parameters.Add("license", lic); } if( options.PerPage != 0 ) parameters.Add("per_page", options.PerPage.ToString()); if( options.Page != 0 ) parameters.Add("page", options.Page.ToString()); if( options.Extras != PhotoSearchExtras.None ) parameters.Add("extras", options.ExtrasString); if( options.SortOrder != PhotoSearchSortOrder.None ) parameters.Add("sort", options.SortOrderString); if( options.PrivacyFilter != PrivacyFilter.None ) parameters.Add("privacy_filter", options.PrivacyFilter.ToString("d")); if( options.BoundaryBox.IsSet ) parameters.Add("bbox", options.BoundaryBox.ToString()); if( options.Accuracy != GeoAccuracy.None ) parameters.Add("accuracy", options.Accuracy.ToString("d")); if( options.SafeSearch != SafetyLevel.None ) parameters.Add("safe_search", options.SafeSearch.ToString("d")); if( options.ContentType != ContentTypeSearch.None ) parameters.Add("content_type", options.ContentType.ToString("d")); if( options.HasGeo ) parameters.Add("has_geo", "1"); if( !float.IsNaN(options.Latitude) ) parameters.Add("lat", options.Latitude.ToString("0.0000")); if( !float.IsNaN(options.Longitude) ) parameters.Add("lon", options.Longitude.ToString("0.0000")); if( !float.IsNaN(options.Radius) ) parameters.Add("radius", options.Radius.ToString("0.00")); if( options.RadiusUnits != RadiusUnits.None ) parameters.Add("radius_units", (options.RadiusUnits == RadiusUnits.Miles? "mi":"km")); if( options.Contacts != ContactSearch.None ) parameters.Add("contacts", (options.Contacts == ContactSearch.AllContacts?"all":"ff")); if( options.WoeId != null ) parameters.Add("woe_id", options.WoeId); if( options.PlaceId != null ) parameters.Add("place_id", options.PlaceId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photos; } else { throw new FlickrApiException(response.Error); } } /// /// Set the date taken for a photo. /// /// /// All dates are assumed to be GMT. It is the developers responsibility to change dates to the local users /// timezone. /// /// The id of the photo to set the date taken for. /// The date taken. /// The granularity of the date taken. /// True if the date was updated successfully. public bool PhotosSetDates(string photoId, DateTime dateTaken, DateGranularity granularity) { return PhotosSetDates(photoId, DateTime.MinValue, dateTaken, granularity); } /// /// Set the date the photo was posted (uploaded). This will affect the order in which photos /// are seen in your photostream. /// /// /// All dates are assumed to be GMT. It is the developers responsibility to change dates to the local users /// timezone. /// /// The id of the photo to set the date posted. /// The new date to set the date posted too. /// True if the date was updated successfully. public bool PhotosSetDates(string photoId, DateTime datePosted) { return PhotosSetDates(photoId, datePosted, DateTime.MinValue, DateGranularity.FullDate); } /// /// Set the date the photo was posted (uploaded) and the date the photo was taken. /// Changing the date posted will affect the order in which photos are seen in your photostream. /// /// /// All dates are assumed to be GMT. It is the developers responsibility to change dates to the local users /// timezone. /// /// The id of the photo to set the dates. /// The new date to set the date posted too. /// The new date to set the date taken too. /// The granularity of the date taken. /// True if the dates where updated successfully. public bool PhotosSetDates(string photoId, DateTime datePosted, DateTime dateTaken, DateGranularity granularity) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.setDates"); parameters.Add("photo_id", photoId); if( datePosted != DateTime.MinValue ) parameters.Add("date_posted", Utils.DateToUnixTimestamp(datePosted).ToString()); if( dateTaken != DateTime.MinValue ) { parameters.Add("date_taken", dateTaken.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo)); parameters.Add("date_taken_granularity", granularity.ToString("d")); } FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return true; } else { throw new FlickrApiException(response.Error); } } /// /// Sets the title and description of the photograph. /// /// The numerical photoId of the photograph. /// The new title of the photograph. /// The new description of the photograph. /// True when the operation is successful. /// Thrown when the photo id cannot be found. public bool PhotosSetMeta(string photoId, string title, string description) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.setMeta"); parameters.Add("photo_id", photoId); parameters.Add("title", title); parameters.Add("description", description); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return true; } else { throw new FlickrApiException(response.Error); } } /// /// Set the permissions on a photo. /// /// The id of the photo to update. /// 1 if the photo is public, 0 if it is not. /// 1 if the photo is viewable by friends, 0 if it is not. /// 1 if the photo is viewable by family, 0 if it is not. /// Who can add comments. See for more details. /// Who can add metadata (notes and tags). See for more details. public void PhotosSetPerms(string photoId, int isPublic, int isFriend, int isFamily, PermissionComment permComment, PermissionAddMeta permAddMeta) { PhotosSetPerms(photoId, (isPublic==1), (isFriend==1), (isFamily==1), permComment, permAddMeta); } /// /// Set the permissions on a photo. /// /// The id of the photo to update. /// True if the photo is public, False if it is not. /// True if the photo is viewable by friends, False if it is not. /// True if the photo is viewable by family, False if it is not. /// Who can add comments. See for more details. /// Who can add metadata (notes and tags). See for more details. public void PhotosSetPerms(string photoId, bool isPublic, bool isFriend, bool isFamily, PermissionComment permComment, PermissionAddMeta permAddMeta) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.setPerms"); parameters.Add("photo_id", photoId); parameters.Add("is_public", (isPublic?"1":"0")); parameters.Add("is_friend", (isFriend?"1":"0")); parameters.Add("is_family", (isFamily?"1":"0")); parameters.Add("perm_comment", permComment.ToString("d")); parameters.Add("perm_addmeta", permAddMeta.ToString("d")); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } /// /// Set the tags for a photo. /// /// /// This will remove all old tags and add these new ones specified. See /// to just add new tags without deleting old ones. /// /// The id of the photo to update. /// An array of tags. /// True if the photo was updated successfully. public bool PhotosSetTags(string photoId, string[] tags) { string s = string.Join(",", tags); return PhotosSetTags(photoId, s); } /// /// Set the tags for a photo. /// /// /// This will remove all old tags and add these new ones specified. See /// to just add new tags without deleting old ones. /// /// The id of the photo to update. /// An comma-seperated list of tags. /// True if the photo was updated successfully. public bool PhotosSetTags(string photoId, string tags) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.setTags"); parameters.Add("photo_id", photoId); parameters.Add("tags", tags); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return true; } else { throw new FlickrApiException(response.Error); } } /// /// Sets the content type for a photo. /// /// The ID of the photos to set. /// The new content type. public void PhotosSetContentType(string photoId, ContentType contentType) { CheckRequiresAuthentication(); Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.setContentType"); parameters.Add("photo_id", photoId); parameters.Add("content_type", (int)contentType); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } /// /// Set the safety level for a photo, but only set the hidden aspect. /// /// The ID of the photo to set the hidden property for. /// The new value of the hidden value. public void PhotosSetSafetyLevel(string photoId, HiddenFromSearch hidden) { PhotosSetSafetyLevel(photoId, SafetyLevel.None, hidden); } /// /// Set the safety level for a photo. /// /// The ID of the photo to set the safety level property for. /// The new value of the safety level value. public void PhotosSetSafetyLevel(string photoId, SafetyLevel safetyLevel) { PhotosSetSafetyLevel(photoId, safetyLevel, HiddenFromSearch.None); } /// /// Sets the safety level and hidden property of a photo. /// /// The ID of the photos to set. /// The new content type. /// The new hidden value. public void PhotosSetSafetyLevel(string photoId, SafetyLevel safetyLevel, HiddenFromSearch hidden) { CheckRequiresAuthentication(); Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.setSafetyLevel"); parameters.Add("photo_id", photoId); if( safetyLevel != SafetyLevel.None ) parameters.Add("safety_level", (int)safetyLevel); switch(hidden) { case HiddenFromSearch.Visible: parameters.Add("hidden", 0); break; case HiddenFromSearch.Hidden: parameters.Add("hidden", 1); break; } FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Photos Comments ] /// /// Gets a list of comments for a photo. /// /// The id of the photo to return the comments for. /// An array of objects. public Comment[] PhotosCommentsGetList(string photoId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.comments.getList"); parameters.Add("photo_id", photoId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return PhotoComments.GetComments(response.AllElements[0]); } else { throw new FlickrApiException(response.Error); } } /// /// Adds a new comment to a photo. /// /// The ID of the photo to add the comment to. /// The text of the comment. Can contain some HTML. /// The new ID of the created comment. public string PhotosCommentsAddComment(string photoId, string commentText) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.comments.addComment"); parameters.Add("photo_id", photoId); parameters.Add("comment_text", commentText); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { XmlNode node = response.AllElements[0]; if( node.Attributes.GetNamedItem("id") != null ) return node.Attributes.GetNamedItem("id").Value; else throw new ResponseXmlException("Comment ID not found in response Xml."); } else { throw new FlickrApiException(response.Error); } } /// /// Deletes a comment from a photo. /// /// The ID of the comment to delete. public void PhotosCommentsDeleteComment(string commentId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.comments.deleteComment"); parameters.Add("comment_id", commentId); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } /// /// Edits a comment. /// /// The ID of the comment to edit. /// The new text for the comment. public void PhotosCommentsEditComment(string commentId, string commentText) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.comments.editComment"); parameters.Add("comment_id", commentId); parameters.Add("comment_text", commentText); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Photosets ] /// /// Add a photo to a photoset. /// /// The ID of the photoset to add the photo to. /// The ID of the photo to add. public void PhotosetsAddPhoto(string photosetId, string photoId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photosets.addPhoto"); parameters.Add("photoset_id", photosetId); parameters.Add("photo_id", photoId); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } /// /// Creates a blank photoset, with a title and a primary photo (minimum requirements). /// /// The title of the photoset. /// The ID of the photo which will be the primary photo for the photoset. This photo will also be added to the set. /// The that is created. public Photoset PhotosetsCreate(string title, string primaryPhotoId) { return PhotosetsCreate(title, null, primaryPhotoId); } /// /// Creates a blank photoset, with a title, description and a primary photo. /// /// The title of the photoset. /// THe description of the photoset. /// The ID of the photo which will be the primary photo for the photoset. This photo will also be added to the set. /// The that is created. public Photoset PhotosetsCreate(string title, string description, string primaryPhotoId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photosets.create"); parameters.Add("title", title); parameters.Add("primary_photo_id", primaryPhotoId); parameters.Add("description", description); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photoset; } else { throw new FlickrApiException(response.Error); } } /// /// Deletes the specified photoset. /// /// The ID of the photoset to delete. /// Returns true when the photoset has been deleted. public bool PhotosetsDelete(string photosetId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photosets.delete"); parameters.Add("photoset_id", photosetId); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return true; } else { throw new FlickrApiException(response.Error); } } /// /// Updates the title and description for a photoset. /// /// The ID of the photoset to update. /// The new title for the photoset. /// The new description for the photoset. /// Returns true when the photoset has been updated. public bool PhotosetsEditMeta(string photosetId, string title, string description) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photosets.editMeta"); parameters.Add("photoset_id", photosetId); parameters.Add("title", title); parameters.Add("description", description); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return true; } else { throw new FlickrApiException(response.Error); } } /// /// Sets the photos for a photoset. /// /// /// Will remove any previous photos from the photoset. /// The order in thich the photoids are given is the order they will appear in the /// photoset page. /// /// The ID of the photoset to update. /// The ID of the new primary photo for the photoset. /// An array of photo IDs. /// Returns true when the photoset has been updated. public bool PhotosetsEditPhotos(string photosetId, string primaryPhotoId, string[] photoIds) { return PhotosetsEditPhotos(photosetId, primaryPhotoId, string.Join(",", photoIds)); } /// /// Sets the photos for a photoset. /// /// /// Will remove any previous photos from the photoset. /// The order in thich the photoids are given is the order they will appear in the /// photoset page. /// /// The ID of the photoset to update. /// The ID of the new primary photo for the photoset. /// An comma seperated list of photo IDs. /// Returns true when the photoset has been updated. public bool PhotosetsEditPhotos(string photosetId, string primaryPhotoId, string photoIds) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photosets.editPhotos"); parameters.Add("photoset_id", photosetId); parameters.Add("primary_photo_id", primaryPhotoId); parameters.Add("photo_ids", photoIds); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return true; } else { throw new FlickrApiException(response.Error); } } /// /// Gets the context of the specified photo within the photoset. /// /// The photo id of the photo in the set. /// The id of the set. /// of the specified photo. public Context PhotosetsGetContext(string photoId, string photosetId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photosets.getContext"); parameters.Add("photo_id", photoId); parameters.Add("photoset_id", photosetId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { Context c = new Context(); c.Count = response.ContextCount.Count; c.NextPhoto = response.ContextNextPhoto; c.PreviousPhoto = response.ContextPrevPhoto; return c; } else { throw new FlickrApiException(response.Error); } } /// /// Gets the information about a photoset. /// /// The ID of the photoset to return information for. /// A instance. public Photoset PhotosetsGetInfo(string photosetId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photosets.getInfo"); parameters.Add("photoset_id", photosetId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photoset; } else { throw new FlickrApiException(response.Error); } } /// /// Gets a list of the currently authenticated users photosets. /// /// A instance containing a collection of photosets. public Photosets PhotosetsGetList() { return PhotosetsGetList(null); } /// /// Gets a list of the specified users photosets. /// /// The ID of the user to return the photosets of. /// A instance containing a collection of photosets. public Photosets PhotosetsGetList(string userId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photosets.getList"); if( userId != null ) parameters.Add("user_id", userId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photosets; } else { throw new FlickrApiException(response.Error); } } /// /// Gets a collection of photos for a photoset. /// /// The ID of the photoset to return photos for. /// A object containing the list of instances. public Photoset PhotosetsGetPhotos(string photosetId) { return PhotosetsGetPhotos(photosetId, PhotoSearchExtras.All, PrivacyFilter.None, 0, 0); } /// /// Gets a collection of photos for a photoset. /// /// The ID of the photoset to return photos for. /// The page to return, defaults to 1. /// The number of photos to return per page. /// A object containing the list of instances. public Photoset PhotosetsGetPhotos(string photosetId, int page, int perPage) { return PhotosetsGetPhotos(photosetId, PhotoSearchExtras.All, PrivacyFilter.None, page, perPage); } /// /// Gets a collection of photos for a photoset. /// /// The ID of the photoset to return photos for. /// The privacy filter to search on. /// A object containing the list of instances. public Photoset PhotosetsGetPhotos(string photosetId, PrivacyFilter privacyFilter) { return PhotosetsGetPhotos(photosetId, PhotoSearchExtras.All, privacyFilter, 0, 0); } /// /// Gets a collection of photos for a photoset. /// /// The ID of the photoset to return photos for. /// The privacy filter to search on. /// The page to return, defaults to 1. /// The number of photos to return per page. /// A object containing the list of instances. public Photoset PhotosetsGetPhotos(string photosetId, PrivacyFilter privacyFilter, int page, int perPage) { return PhotosetsGetPhotos(photosetId, PhotoSearchExtras.All, privacyFilter, page, perPage); } /// /// Gets a collection of photos for a photoset. /// /// The ID of the photoset to return photos for. /// The extras to return for each photo. /// A object containing the list of instances. public Photoset PhotosetsGetPhotos(string photosetId, PhotoSearchExtras extras) { return PhotosetsGetPhotos(photosetId, extras, PrivacyFilter.None, 0, 0); } /// /// Gets a collection of photos for a photoset. /// /// The ID of the photoset to return photos for. /// The extras to return for each photo. /// The page to return, defaults to 1. /// The number of photos to return per page. /// A object containing the list of instances. public Photoset PhotosetsGetPhotos(string photosetId, PhotoSearchExtras extras, int page, int perPage) { return PhotosetsGetPhotos(photosetId, extras, PrivacyFilter.None, page, perPage); } /// /// Gets a collection of photos for a photoset. /// /// The ID of the photoset to return photos for. /// The extras to return for each photo. /// The privacy filter to search on. /// A object containing the list of instances. public Photoset PhotosetsGetPhotos(string photosetId, PhotoSearchExtras extras, PrivacyFilter privacyFilter) { return PhotosetsGetPhotos(photosetId, extras, privacyFilter, 0, 0); } /// /// Gets a collection of photos for a photoset. /// /// The ID of the photoset to return photos for. /// The extras to return for each photo. /// The privacy filter to search on. /// The page to return, defaults to 1. /// The number of photos to return per page. /// An array of instances. public Photoset PhotosetsGetPhotos(string photosetId, PhotoSearchExtras extras, PrivacyFilter privacyFilter, int page, int perPage) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photosets.getPhotos"); parameters.Add("photoset_id", photosetId); if( extras != PhotoSearchExtras.None ) parameters.Add("extras", Utils.ExtrasToString(extras)); if( privacyFilter != PrivacyFilter.None ) parameters.Add("privacy_filter", privacyFilter.ToString("d")); if( page > 0 ) parameters.Add("page", page); if( perPage > 0 ) parameters.Add("per_page", perPage); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { if( response.Photoset.OwnerId != null && response.Photoset.OwnerId.Length > 0 ) { foreach(Photo p in response.Photoset.PhotoCollection) { p.UserId = response.Photoset.OwnerId; } } return response.Photoset; } else { throw new FlickrApiException(response.Error); } } /// /// Changes the order of your photosets. /// /// An array of photoset IDs, /// ordered with the set to show first, first in the list. /// Any set IDs not given in the list will be set to appear at the end of the list, ordered by their IDs. public void PhotosetsOrderSets(string[] photosetIds) { PhotosetsOrderSets(string.Join(",", photosetIds)); } /// /// Changes the order of your photosets. /// /// A comma delimited list of photoset IDs, /// ordered with the set to show first, first in the list. /// Any set IDs not given in the list will be set to appear at the end of the list, ordered by their IDs. public void PhotosetsOrderSets(string photosetIds) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photosets.orderSets"); parameters.Add("photosetIds", photosetIds); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } /// /// Removes a photo from a photoset. /// /// /// An exception will be raised if the photo is not in the set. /// /// The ID of the photoset to remove the photo from. /// The ID of the photo to remove. public void PhotosetsRemovePhoto(string photosetId, string photoId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photosets.removePhoto"); parameters.Add("photoset_id", photosetId); parameters.Add("photo_id", photoId); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Places ] /// /// Returns a list of places which contain the query string. /// /// The string to search for. Must not be null. /// An array of instances. public Place[] PlacesFind(string query) { if( query == null ) throw new ArgumentNullException("query"); Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.places.find"); parameters.Add("query", query); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Places.PlacesCollection; } else { throw new FlickrApiException(response.Error); } } /// /// Returns a place based on the input latitude and longitude. /// /// The latitude, between -180 and 180. /// The longitude, between -90 and 90. /// An instance of the that matches the locality. public Place PlacesFindByLatLon(decimal latitude, decimal longitude) { return PlacesFindByLatLon(latitude, longitude, GeoAccuracy.None); } /// /// Returns a place based on the input latitude and longitude. /// /// The latitude, between -180 and 180. /// The longitude, between -90 and 90. /// The level the locality will be for. /// An instance of the that matches the locality. public Place PlacesFindByLatLon(decimal latitude, decimal longitude, GeoAccuracy accuracy) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.places.findByLatLon"); parameters.Add("lat", latitude.ToString("0.000")); parameters.Add("lon", longitude.ToString("0.000")); if( accuracy != GeoAccuracy.None ) parameters.Add("accuracy", (int)accuracy); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Places.PlacesCollection[0]; } else { throw new FlickrApiException(response.Error); } } /// /// Return a list of locations with public photos that are parented by a Where on Earth (WOE) or Places ID. /// /// A Flickr Places ID. (While optional, you must pass either a valid Places ID or a WOE ID.) /// A Where On Earth (WOE) ID. (While optional, you must pass either a valid Places ID or a WOE ID.) /// Returns an array of elements. public Place[] PlacesGetChildrenWithPhotosPublic(string placeId, string woeId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.places.getChildrenWithPhotosPublic"); if( (placeId == null || placeId.Length == 0) && (woeId == null || woeId.Length == 0 )) { throw new FlickrException("Both placeId and woeId cannot be null or empty."); } parameters.Add("place_id", placeId); parameters.Add("woe_id", woeId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Places.PlacesCollection; } else { throw new FlickrApiException(response.Error); } } /// /// Get informations about a place. /// /// A Flickr Places ID. (While optional, you must pass either a valid Places ID or a WOE ID.) /// A Where On Earth (WOE) ID. (While optional, you must pass either a valid Places ID or a WOE ID.) /// The record for the place/woe ID. public Place PlacesGetInfo(string placeId, string woeId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.places.getInfo"); if( (placeId == null || placeId.Length == 0) && (woeId == null || woeId.Length == 0 ) ) { throw new FlickrException("Both placeId and woeId cannot be null or empty."); } parameters.Add("place_id", placeId); parameters.Add("woe_id", woeId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Place; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Photoset Comments ] /// /// Gets a list of comments for a photoset. /// /// The id of the photoset to return the comments for. /// An array of objects. public Comment[] PhotosetsCommentsGetList(string photosetId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photosets.comments.getList"); parameters.Add("photoset_id", photosetId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return PhotoComments.GetComments(response.AllElements[0]); } else { throw new FlickrApiException(response.Error); } } /// /// Adds a new comment to a photoset. /// /// The ID of the photoset to add the comment to. /// The text of the comment. Can contain some HTML. /// The new ID of the created comment. public string PhotosetsCommentsAddComment(string photosetId, string commentText) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photosets.comments.addComment"); parameters.Add("photoset_id", photosetId); parameters.Add("comment_text", commentText); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { XmlNode node = response.AllElements[0]; if( node.Attributes.GetNamedItem("id") != null ) return node.Attributes.GetNamedItem("id").Value; else throw new ResponseXmlException("Comment ID not found in response."); } else { throw new FlickrApiException(response.Error); } } /// /// Deletes a comment from a photoset. /// /// The ID of the comment to delete. public void PhotosetsCommentsDeleteComment(string commentId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photosets.comments.deleteComment"); parameters.Add("comment_id", commentId); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } /// /// Edits a comment. /// /// The ID of the comment to edit. /// The new text for the comment. public void PhotosetsCommentsEditComment(string commentId, string commentText) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photosets.comments.editComment"); parameters.Add("comment_id", commentId); parameters.Add("comment_text", commentText); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Prefs ] /// /// Gets the currently authenticated users default safety level. /// /// public SafetyLevel PrefsGetSafetyLevel() { CheckRequiresAuthentication(); Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.prefs.getSafetyLevel"); Response res = GetResponseCache(parameters); if( res.Status == ResponseStatus.OK ) { string s = res.AllElements[0].GetAttribute("safety_level"); return (SafetyLevel)int.Parse(s); } else { throw new FlickrApiException(res.Error); } } /// /// Gets the currently authenticated users default hidden from search setting. /// /// public HiddenFromSearch PrefsGetHidden() { CheckRequiresAuthentication(); Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.prefs.getHidden"); Response res = GetResponseCache(parameters); if( res.Status == ResponseStatus.OK ) { string s = res.AllElements[0].GetAttribute("hidden"); return (HiddenFromSearch)int.Parse(s); } else { throw new FlickrApiException(res.Error); } } /// /// Gets the currently authenticated users default content type. /// /// public ContentType PrefsGetContentType() { CheckRequiresAuthentication(); Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.prefs.getContentType"); Response res = GetResponseCache(parameters); if( res.Status == ResponseStatus.OK ) { string s = res.AllElements[0].GetAttribute("content_type"); return (ContentType)int.Parse(s); } else { throw new FlickrApiException(res.Error); } } #endregion #region [ Tags ] /// /// Get the tag list for a given photo. /// /// The id of the photo to return tags for. /// An instance of the class containing only the property. public PhotoInfoTag[] TagsGetListPhoto(string photoId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.tags.getListPhoto"); parameters.Add("api_key", _apiKey); parameters.Add("photo_id", photoId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.PhotoInfo.Tags.TagCollection; } else { throw new FlickrApiException(response.Error); } } /// /// Get the tag list for a given user (or the currently logged in user). /// /// An array of objects. public Tag[] TagsGetListUser() { return TagsGetListUser(null); } /// /// Get the tag list for a given user (or the currently logged in user). /// /// The NSID of the user to fetch the tag list for. If this argument is not specified, the currently logged in user (if any) is assumed. /// An array of objects. public Tag[] TagsGetListUser(string userId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.tags.getListUser"); if( userId != null && userId.Length > 0 ) parameters.Add("user_id", userId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { XmlNodeList nodes = response.AllElements[0].SelectNodes("//tag"); Tag[] tags = new Tag[nodes.Count]; for(int i = 0; i < tags.Length; i++) { tags[i] = new Tag(nodes[i]); } return tags; } else { throw new FlickrApiException(response.Error); } } /// /// Get the popular tags for a given user (or the currently logged in user). /// /// An array of objects. public Tag[] TagsGetListUserPopular() { return TagsGetListUserPopular(null, 0); } /// /// Get the popular tags for a given user (or the currently logged in user). /// /// Number of popular tags to return. defaults to 10 when this argument is not present. /// An array of objects. public Tag[] TagsGetListUserPopular(int count) { return TagsGetListUserPopular(null, count); } /// /// Get the popular tags for a given user (or the currently logged in user). /// /// The NSID of the user to fetch the tag list for. If this argument is not specified, the currently logged in user (if any) is assumed. /// An array of objects. public Tag[] TagsGetListUserPopular(string userId) { return TagsGetListUserPopular(userId, 0); } /// /// Get the popular tags for a given user (or the currently logged in user). /// /// The NSID of the user to fetch the tag list for. If this argument is not specified, the currently logged in user (if any) is assumed. /// Number of popular tags to return. defaults to 10 when this argument is not present. /// An array of objects. public Tag[] TagsGetListUserPopular(string userId, long count) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.tags.getListUserPopular"); if( userId != null ) parameters.Add("user_id", userId); if( count > 0 ) parameters.Add("count", count.ToString()); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { XmlNodeList nodes = response.AllElements[0].SelectNodes("//tag"); Tag[] tags = new Tag[nodes.Count]; for(int i = 0; i < tags.Length; i++) { tags[i] = new Tag(nodes[i]); } return tags; } else { throw new FlickrApiException(response.Error); } } /// /// Gets a list of 'cleaned' tags and the raw values for those tags. /// /// An array of objects. public RawTag[] TagsGetListUserRaw() { return TagsGetListUserRaw(null); } /// /// Gets a list of 'cleaned' tags and the raw values for a specific tag. /// /// The tag to return the raw version of. /// An array of objects. public RawTag[] TagsGetListUserRaw(string tag) { CheckRequiresAuthentication(); Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.tags.getListUserRaw"); if( tag != null && tag.Length > 0 ) parameters.Add("tag", tag); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { XmlNodeList nodes = response.AllElements[0].SelectNodes("//tag"); RawTag[] tags = new RawTag[nodes.Count]; for(int i = 0; i < tags.Length; i++) { tags[i] = new RawTag(nodes[i]); } return tags; } else { throw new FlickrApiException(response.Error); } } /// /// Returns a list of tags 'related' to the given tag, based on clustered usage analysis. /// /// The tag to fetch related tags for. /// An array of objects. public Tag[] TagsGetRelated(string tag) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.tags.getRelated"); parameters.Add("api_key", _apiKey); parameters.Add("tag", tag); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { XmlNodeList nodes = response.AllElements[0].SelectNodes("//tag"); Tag[] tags = new Tag[nodes.Count]; for(int i = 0; i < tags.Length; i++) { tags[i] = new Tag(nodes[i]); } return tags; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Transform ] /// /// Rotates a photo on Flickr. /// /// /// Does not rotate the original photo. /// /// The ID of the photo. /// The number of degrees to rotate by. Valid values are 90, 180 and 270. public void TransformRotate(string photoId, int degrees) { if( photoId == null ) throw new ArgumentNullException("photoId"); if( degrees != 90 && degrees != 180 && degrees != 270 ) throw new ArgumentException("Must be 90, 180 or 270", "degrees"); Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.transform.rotate"); parameters.Add("photo_id", photoId); parameters.Add("degrees", degrees.ToString("0")); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Geo ] /// /// Returns the location data for a give photo. /// /// The ID of the photo to return the location information for. /// Returns null if the photo has no location information, otherwise returns the location information. public PhotoLocation PhotosGeoGetLocation(string photoId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.geo.getLocation"); parameters.Add("photo_id", photoId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.PhotoInfo.Location; } else { if( response.Error.Code == 2 ) return null; else throw new FlickrApiException(response.Error); } } /// /// Sets the geo location for a photo. /// /// The ID of the photo to set to location for. /// The latitude of the geo location. A double number ranging from -180.00 to 180.00. Digits beyond 6 decimal places will be truncated. /// The longitude of the geo location. A double number ranging from -180.00 to 180.00. Digits beyond 6 decimal places will be truncated. public void PhotosGeoSetLocation(string photoId, double latitude, double longitude) { PhotosGeoSetLocation(photoId, latitude, longitude, GeoAccuracy.None); } /// /// Sets the geo location for a photo. /// /// The ID of the photo to set to location for. /// The latitude of the geo location. A double number ranging from -180.00 to 180.00. Digits beyond 6 decimal places will be truncated. /// The longitude of the geo location. A double number ranging from -180.00 to 180.00. Digits beyond 6 decimal places will be truncated. /// The accuracy of the photos geo location. public void PhotosGeoSetLocation(string photoId, double latitude, double longitude, GeoAccuracy accuracy) { System.Globalization.NumberFormatInfo nfi = System.Globalization.NumberFormatInfo.InvariantInfo; Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.geo.setLocation"); parameters.Add("photo_id", photoId); parameters.Add("lat", latitude.ToString(nfi)); parameters.Add("lon", longitude.ToString(nfi)); if( accuracy != GeoAccuracy.None ) parameters.Add("accuracy", ((int)accuracy).ToString()); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } /// /// Removes Location information. /// /// The photo ID of the photo to remove information from. /// Returns true if the location information as found and removed. Returns false if no photo information was found. public bool PhotosGeoRemoveLocation(string photoId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.geo.removeLocation"); parameters.Add("photo_id", photoId); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return true; } else { if( response.Error.Code == 2 ) return false; else throw new FlickrApiException(response.Error); } } /// /// Gets a list of photos that do not contain geo location information. /// /// A list of photos that do not contain location information. public Photos PhotosGetWithoutGeoData() { PartialSearchOptions options = new PartialSearchOptions(); return PhotosGetWithoutGeoData(options); } /// /// Gets a list of photos that do not contain geo location information. /// /// A limited set of options are supported. /// A list of photos that do not contain location information. public Photos PhotosGetWithoutGeoData(PartialSearchOptions options) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.getWithoutGeoData"); Utils.PartialOptionsIntoArray(options, parameters); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photos; } else { throw new FlickrApiException(response.Error); } } /// /// Gets a list of photos that do not contain geo location information. /// /// A limited set of options are supported. /// Unsupported arguments are ignored. /// See http://www.flickr.com/services/api/flickr.photos.getWithGeoData.html for supported properties. /// A list of photos that do not contain location information. [Obsolete("Use the PartialSearchOptions instead")] public Photos PhotosGetWithoutGeoData(PhotoSearchOptions options) { PartialSearchOptions newOptions = new PartialSearchOptions(options); return PhotosGetWithoutGeoData(newOptions); } /// /// Gets a list of photos that contain geo location information. /// /// /// Note, this method doesn't actually return the location information with the photos, /// unless you specify the option in the extras parameter. /// /// A list of photos that contain Location information. public Photos PhotosGetWithGeoData() { PartialSearchOptions options = new PartialSearchOptions(); return PhotosGetWithGeoData(options); } /// /// Gets a list of photos that contain geo location information. /// /// /// Note, this method doesn't actually return the location information with the photos, /// unless you specify the option in the extras parameter. /// /// A limited set of options are supported. /// Unsupported arguments are ignored. /// See http://www.flickr.com/services/api/flickr.photos.getWithGeoData.html for supported properties. /// A list of photos that contain Location information. [Obsolete("Use the new PartialSearchOptions instead")] public Photos PhotosGetWithGeoData(PhotoSearchOptions options) { PartialSearchOptions newOptions = new PartialSearchOptions(options); return PhotosGetWithGeoData(newOptions); } /// /// Gets a list of photos that contain geo location information. /// /// /// Note, this method doesn't actually return the location information with the photos, /// unless you specify the option in the extras parameter. /// /// The options to filter/sort the results by. /// A list of photos that contain Location information. public Photos PhotosGetWithGeoData(PartialSearchOptions options) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.getWithGeoData"); Utils.PartialOptionsIntoArray(options, parameters); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Photos; } else { throw new FlickrApiException(response.Error); } } /// /// Get permissions for a photo. /// /// The id of the photo to get permissions for. /// An instance of the class containing the permissions of the specified photo. public GeoPermissions PhotosGeoGetPerms(string photoId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.geo.getPerms"); parameters.Add("photo_id", photoId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return new GeoPermissions(response.AllElements[0]); } else { throw new FlickrApiException(response.Error); } } /// /// Set the permission for who can see geotagged photos on Flickr. /// /// The ID of the photo permissions to update. /// /// /// /// public void PhotosGeoSetPerms(string photoId, bool IsPublic, bool IsContact, bool IsFamily, bool IsFriend) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.photos.geo.setPerms"); parameters.Add("photo_id", photoId); parameters.Add("is_public", IsPublic?"1":"0"); parameters.Add("is_contact", IsContact?"1":"0"); parameters.Add("is_friend", IsFriend?"1":"0"); parameters.Add("is_family", IsFamily?"1":"0"); FlickrNet.Response response = GetResponseNoCache(parameters); if( response.Status == ResponseStatus.OK ) { return; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Tests ] /// /// Can be used to call unsupported methods in the Flickr API. /// /// /// Use of this method is not supported. /// The way the FlickrNet API Library works may mean that some methods do not return an expected result /// when using this method. /// /// The method name, e.g. "flickr.test.null". /// A list of parameters. Note, api_key is added by default and is not included. Can be null. /// An array of instances which is the expected response. public XmlElement[] TestGeneric(string method, NameValueCollection parameters) { Hashtable _parameters = new Hashtable(); if( parameters != null ) { foreach(string key in parameters.AllKeys) { _parameters.Add(key, parameters[key]); } } _parameters.Add("method", method); FlickrNet.Response response = GetResponseNoCache(_parameters); if( response.Status == ResponseStatus.OK ) { return response.AllElements; } else { throw new FlickrApiException(response.Error); } } /// /// Runs the flickr.test.echo method and returned an array of items. /// /// The parameter to pass to the method. /// The value to pass to the method with the parameter. /// An array of items. /// /// The APi Key has been removed from the returned array and will not be shown. /// /// /// /// XmlElement[] elements = flickr.TestEcho("&param=value"); /// foreach(XmlElement element in elements) /// { /// if( element.Name = "method" ) /// Console.WriteLine("Method = " + element.InnerXml); /// if( element.Name = "param" ) /// Console.WriteLine("Param = " + element.InnerXml); /// } /// /// public XmlElement[] TestEcho(string echoParameter, string echoValue) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.test.echo"); parameters.Add("api_key", _apiKey); if( echoParameter != null && echoParameter.Length > 0 ) { parameters.Add(echoParameter, echoValue); } FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { // Remove the api_key element from the array. XmlElement[] elements = new XmlElement[response.AllElements.Length - 1]; int c = 0; foreach(XmlElement element in response.AllElements) { if(element.Name != "api_key" ) elements[c++] = element; } return elements; } else { throw new FlickrApiException(response.Error); } } /// /// Test the logged in state of the current Filckr object. /// /// The object containing the username and userid of the current user. public FoundUser TestLogin() { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.test.login"); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return new FoundUser(response.AllElements[0]); } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Urls ] /// /// Returns the url to a group's page. /// /// The NSID of the group to fetch the url for. /// An instance of the class containing the URL of the group page. public Uri UrlsGetGroup(string groupId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.urls.getGroup"); parameters.Add("api_key", _apiKey); parameters.Add("group_id", groupId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { if( response.AllElements[0] != null && response.AllElements[0].Attributes["url"] != null ) return new Uri(response.AllElements[0].Attributes["url"].Value); else return null; } else { throw new FlickrApiException(response.Error); } } /// /// Returns the url to a user's photos. /// /// An instance of the class containing the URL for the users photos. public Uri UrlsGetUserPhotos() { return UrlsGetUserPhotos(null); } /// /// Returns the url to a user's photos. /// /// The NSID of the user to fetch the url for. If omitted, the calling user is assumed. /// The URL of the users photos. public Uri UrlsGetUserPhotos(string userId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.urls.getUserPhotos"); if( userId != null && userId.Length > 0 ) parameters.Add("user_id", userId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { if( response.AllElements[0] != null && response.AllElements[0].Attributes["url"] != null ) return new Uri(response.AllElements[0].Attributes["url"].Value); else return null; } else { throw new FlickrApiException(response.Error); } } /// /// Returns the url to a user's profile. /// /// An instance of the class containing the URL for the users profile. public Uri UrlsGetUserProfile() { return UrlsGetUserProfile(null); } /// /// Returns the url to a user's profile. /// /// The NSID of the user to fetch the url for. If omitted, the calling user is assumed. /// An instance of the class containing the URL for the users profile. public Uri UrlsGetUserProfile(string userId) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.urls.getUserProfile"); if( userId != null && userId.Length > 0 ) parameters.Add("user_id", userId); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { if( response.AllElements[0] != null && response.AllElements[0].Attributes["url"] != null ) return new Uri(response.AllElements[0].Attributes["url"].Value); else return null; } else { throw new FlickrApiException(response.Error); } } /// /// Returns a group NSID, given the url to a group's page or photo pool. /// /// The url to the group's page or photo pool. /// The ID of the group at the specified URL on success, a null reference (Nothing in Visual Basic) if the group cannot be found. public string UrlsLookupGroup(string urlToFind) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.urls.lookupGroup"); parameters.Add("api_key", _apiKey); parameters.Add("url", urlToFind); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { if( response.AllElements[0] != null && response.AllElements[0].Attributes["id"] != null ) { return response.AllElements[0].Attributes["id"].Value; } else { return null; } } else { if( response.Error.Code == 1 ) return null; else throw new FlickrApiException(response.Error); } } /// /// Returns a user NSID, given the url to a user's photos or profile. /// /// Thr url to the user's profile or photos page. /// An instance of the class containing the users ID and username. public FoundUser UrlsLookupUser(string urlToFind) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.urls.lookupUser"); parameters.Add("api_key", _apiKey); parameters.Add("url", urlToFind); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return new FoundUser(response.AllElements[0]); } else { throw new FlickrApiException(response.Error); } } #endregion #region [ Reflection ] /// /// Gets an array of supported method names for Flickr. /// /// /// Note: Not all methods might be supported by the FlickrNet Library. /// public string[] ReflectionGetMethods() { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.reflection.getMethods"); parameters.Add("api_key", _apiKey); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return Methods.GetMethods(response.AllElements[0]); } else { throw new FlickrApiException(response.Error); } } /// /// Gets the method details for a given method. /// /// The name of the method to retrieve. /// Returns a instance for the given method name. public Method ReflectionGetMethodInfo(string methodName) { Hashtable parameters = new Hashtable(); parameters.Add("method", "flickr.reflection.getMethodInfo"); parameters.Add("api_key", _apiKey); parameters.Add("method_name", methodName); FlickrNet.Response response = GetResponseCache(parameters); if( response.Status == ResponseStatus.OK ) { return response.Method; } else { throw new FlickrApiException(response.Error); } } #endregion #region [ MD5 Hash ] private static string Md5Hash(string unhashed) { System.Security.Cryptography.MD5CryptoServiceProvider csp = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(unhashed); byte[] hashedBytes = csp.ComputeHash(bytes, 0, bytes.Length); return BitConverter.ToString(hashedBytes).Replace("-", "").ToLower(); } #endregion } } libflickrnet-48055~2.2.0/FlickrNet/FlickrConfigurationManager.cs0000644000175000017500000000156311155417352023515 0ustar varunvarunusing System; using System.Configuration; using System.Xml; #if !WindowsCE namespace FlickrNet { /// /// Summary description for FlickrConfigurationManager. /// internal class FlickrConfigurationManager : IConfigurationSectionHandler { private static string ConfigSection = "flickrNet"; private static FlickrConfigurationSettings settings; public FlickrConfigurationManager() { } public static FlickrConfigurationSettings Settings { get { if( settings == null ) { settings = (FlickrConfigurationSettings)ConfigurationSettings.GetConfig( ConfigSection ); } return settings; } } public object Create(object parent, object configContext, XmlNode section) { ConfigSection = section.Name; return new FlickrConfigurationSettings( section ); } } } #endiflibflickrnet-48055~2.2.0/FlickrNetCF.sln0000644000175000017500000000240711155417352016656 0ustar varunvarun Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FlickrNetCF", "FlickrNet\FlickrNetCF.csproj", "{DACD45D5-ED22-4DD5-9D1D-B1706E0AD1B9}" EndProject Global GlobalSection(TeamFoundationVersionControl) = preSolution SccNumberOfProjects = 2 SccEnterpriseProvider = {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C} SccTeamFoundationServer = https://tfs01.codeplex.com/ SccLocalPath0 = . SccProjectUniqueName1 = FlickrNet\\FlickrNetCF.csproj SccProjectName1 = FlickrNet SccLocalPath1 = FlickrNet EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {DACD45D5-ED22-4DD5-9D1D-B1706E0AD1B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DACD45D5-ED22-4DD5-9D1D-B1706E0AD1B9}.Debug|Any CPU.Build.0 = Debug|Any CPU {DACD45D5-ED22-4DD5-9D1D-B1706E0AD1B9}.Release|Any CPU.ActiveCfg = Release|Any CPU {DACD45D5-ED22-4DD5-9D1D-B1706E0AD1B9}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal libflickrnet-48055~2.2.0/FlickrNet.sln0000644000175000017500000000162111155417352016442 0ustar varunvarunMicrosoft Visual Studio Solution File, Format Version 8.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FlickrNet", "FlickrNet\FlickrNet.csproj", "{5F017126-C1FF-4996-85CC-6150E80C6AFC}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution Debug = Debug Release = Release EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {5F017126-C1FF-4996-85CC-6150E80C6AFC}.Debug.ActiveCfg = Debug|.NET {5F017126-C1FF-4996-85CC-6150E80C6AFC}.Debug.Build.0 = Debug|.NET {5F017126-C1FF-4996-85CC-6150E80C6AFC}.Release.ActiveCfg = Release|.NET {5F017126-C1FF-4996-85CC-6150E80C6AFC}.Release.Build.0 = Release|.NET EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal libflickrnet-48055~2.2.0/RubyTests/0000755000175000017500000000000011155417352016007 5ustar varunvarunlibflickrnet-48055~2.2.0/RubyTests/Specs/0000755000175000017500000000000011155417352017064 5ustar varunvarunlibflickrnet-48055~2.2.0/RubyTests/Specs/mspec_helper.rb0000644000175000017500000000332511155417352022062 0ustar varunvarunrequire File.dirname(__FILE__) + '/mini_rspec' def try(a, b=true) yield return nil rescue a return b end def should_raise(klass = nil, msg = nil) raise ArgumentError, "No exception class given" unless klass begin yield rescue Exception => e unless klass === e raise ArgumentError, "Expected #{klass}, got #{e.class} (#{e.message})" end if msg and msg != e.message then raise ArgumentError, "Expected message #{msg.inspect}, got #{e.message.inspect}" end return true end raise ArgumentError.new("Expected #{klass}, nothing raised") end # Adapted from rs # # Captures output from the IO given as the second argument (STDIN by default) # and matches it against a String or Regexp given as the first argument. def should_output(expected, to = MyIO.new) # TODO: throw for the time being here raise "Not implemented!" require 'fileutils' require 'tmpdir' # Store the old stream old_to = to.dup # Obtain a filehandle to replace (needed for Readline support) to.reopen File.open(File.join(Dir.tmpdir, "should_output_#{$$}"), "w+") # Execute yield # Restore out = to.dup to.reopen old_to # Grab the data out.rewind output = out.read # Match up case expected when Regexp output.should.match expected else output.should.equal expected end # case expected # Clean up ensure out.close unless out.closed? # STDIO redirection will break without this begin to.seek 0, IO::SEEK_END rescue Errno::ESPIPE rescue Errno::EPIPE end FileUtils.rm out.path end # should_output libflickrnet-48055~2.2.0/RubyTests/Specs/mini_mock.rb0000644000175000017500000000762011155417352021363 0ustar varunvarun# The code is ugly because it must be kept as straightforward # as possible, do not blame me. class Object # Provide the method name and a hash with any of the following # :with => Array of arguments or :any (default) # :block => Whether block is present or :any (default) # :count => Number of times invoked, default once (special: :any and :never) # :returning => Object to return def should_receive(sym, info = {:with => :any, :block => :any, :count => 1}) meta = class << self; self; end if self.respond_to? sym meta.instance_eval { alias_method(:"__ms_#{sym}", sym.to_sym) } Mock.set_objects self, sym, :single_overridden else Mock.set_objects self, sym, :single_new end meta.class_eval <<-END def #{sym}(*args, &block) Mock.report self, :#{sym}, *args, &block end END info[:with] = info[:with] || :any info[:block] = info[:block] || :any info[:count] = info[:count] || 1 Mock.set_expect self, sym, info end # Same as should_receive except that :count is 0 def should_not_receive(sym, info = {:with => :any, :block => :any, :count => 0}) info[:count] = 0 should_receive sym, info end end module Mock def self.reset() @expects = {} @objects = [] end def self.set_expect(obj, sym, info) if @expects[[obj, sym]] if tmp = @expects[[obj, sym]].find { |i| i[:with] == info[:with] } @expects[[obj, sym]].delete(tmp) end @expects[[obj, sym]] << info else @expects[[obj, sym]] = [ info ] end end def self.set_objects(obj, sym, type = nil) @objects << [obj, sym, type] end # Verify to correct number of calls def self.verify() @expects.each do |k, expects| expects.each do |info| obj, sym = k[0], k[1] if info[:count] != :never && info[:count] != :any if info[:count] > 0 raise Exception.new("Method #{sym} with #{info[:with].inspect} and block #{info[:block].inspect} called too FEW times on object #{obj.inspect}") end end end end end # Clean up any methods we set up def self.cleanup() @objects.each {|info| obj, sym, type = info[0], info[1], info[2] hidden_name = "__ms_" + sym.to_s # Revert the object back to original if possible case type when :all_instances next when :single_new meta = class << obj; self; end # meta.send :remove_method, sym.to_sym when :single_overridden meta = class << obj; self; end meta.instance_eval { alias_method(sym.to_sym, hidden_name.to_sym) } end } end # Invoked by a replaced method in an object somewhere. # Verifies that the method is called as expected with # the exception that calling the method too few times # is not detected until #verify_expects! gets called # which by default happens at the end of a #specify def self.report(obj, sym, *args, &block) info = @expects[[obj, sym]].find { |info| info[:with] == :any || info[:with] == args } return unless info unless info[:block] == :any if block unless info[:block] return end end end unless info[:count] == :any if info[:count] == :never raise Exception.new("Method #{sym} with #{info[:with].inspect} and block #{info[:block].inspect} should NOT be called on object #{obj.inspect}") end info[:count] = info[:count] - 1 if info[:count] < 0 raise Exception.new("Method #{sym} with #{info[:with].inspect} and block #{info[:block].inspect} called too MANY times on object #{obj.inspect}") end end return info[:returning] end end # Start up Mock.reset libflickrnet-48055~2.2.0/RubyTests/Specs/rspec_helper.rb0000644000175000017500000000306311155417352022066 0ustar varunvarunclass String # remove indentation from the beginning of each line # according to the number of blanks in the first line def unindent match = /^\s+/.match(self) return unless match self.gsub(/^\s{#{match[0].length}}/, "") end end module ExceptionHelper # try(anException, result) { ... } # => result if block does not raise anException, else nil def try(a, b=true) yield return nil rescue a return b end end class Object def should_raise(exc, msg = nil) raised = nil begin yield rescue Object => raised end unless exc === raised raised_str = raised ? raised.inspect : "nothing" reason = "expected to raise %s, but raised %s" % [exc, raised_str] Spec::Expectations.fail_with(reason) end if msg and msg != raised.message then reason = "expected message %p, but got %p" % [msg, e.message] Spec::Expectations.fail_with(reason) end end def should_include(*other) should Spec::Matchers::Include.new(*other) end end # Example courtesy of nicksieger, many thanks! class Spec::Runner::Context def before_context_eval @context_eval_module.include ExceptionHelper case ENV['SPEC_TARGET'] when /mri/ require 'mri_target' @context_eval_module.include MRITarget when /jruby/ require 'jruby_target' @context_eval_module.include JRubyTarget else require 'rubinius_target' @context_eval_module.include RubiniusTarget end end end libflickrnet-48055~2.2.0/RubyTests/Specs/simple_mock.rb0000644000175000017500000001513011155417352021713 0ustar varunvarun# A simple Mock framework that uses only method_missing, alias_method, # remove_method, and respond_to? if !$simple_mock_loaded $simple_mock_loaded = true class Object def singleton class << self; self; end end alias_method :__ms_respond_to?, :respond_to? alias_method :__ms_method_missing, :method_missing def respond_to?(sym) unless @should_receive_method_list.nil? if @should_receive_method_list.include? sym.to_sym # Record the call to respond_to? if @should_receive_method_list.include? :respond_to? Mock.report(self, :respond_to?, sym.to_sym) end return true end methods = Mock.get_method_missing_methods(self, :respond_to?) if methods.include? sym.to_sym return Mock.report(self, :respond_to?, sym.to_sym) end end __ms_respond_to?(sym) end def method_missing(sym, *args, &block) unless @should_receive_method_list.nil? if @should_receive_method_list.include?(sym.to_sym) return Mock.report(self, sym.to_sym, *args, &block) end if @should_receive_method_list.include?(:method_missing) methods = Mock.get_method_missing_methods(self, :method_missing) if methods.include? sym.to_sym # Parameters must include symbol name and rest of arguments rargs = [sym, *args] return Mock.report(self, :method_missing, *rargs, &block) end end end __ms_method_missing(sym, *args, &block) end def should_receive(sym, info = {:with => :any, :block => :any, :count => 1}) if @should_receive_method_list.nil? @should_receive_method_list = [sym.to_sym] else @should_receive_method_list << sym.to_sym end unless sym.to_sym == :respond_to? || sym.to_sym == :method_missing if self.__ms_respond_to? sym.to_sym singleton.send :alias_method, :"__ms_#{sym}", sym.to_sym # Undefine the method from the singleton class so that we handle via method_missing singleton.send :undef_method, sym Mock.set_objects self, sym, :single_overridden else Mock.set_objects self, sym, :single_new end else Mock.set_objects self, sym, :single_overridden end info[:with] = info[:with] || :any info[:block] = info[:block] || :any info[:count] = info[:count] || 1 Mock.set_expect self, sym, info end # Same as should_receive except that :count is 0 def should_not_receive(sym, info = {:with => :any, :block => :any, :count => 0}) info[:count] = 0 should_receive sym, info end end module Mock # TODO: Today, we don't hash List correctly (this is what an IronRuby array # is today) so this class is a workaround placeholder class Storage def initialize @hash = {} end def [](key) raise 'expects a tuple of size 2' if key.length != 2 obj, sym = key.first, key.last return nil if @hash[obj].nil? result = @hash[obj][sym] result end def []=(key, value) raise 'expects a tuple of size 2' if key.length != 2 obj, sym = key.first, key.last @hash[obj] = {} if @hash[obj].nil? @hash[obj][sym] = value end def each @hash.each do |obj, hash| unless hash[obj].nil? hash[obj].each do |sym, value| yield [obj, sym], value end end end end end def self.reset() @expects = Storage.new @objects = [] end def self.set_expect(obj, sym, info) if @expects[[obj, sym]] if tmp = @expects[[obj, sym]].find { |i| i[:with] == info[:with] } @expects[[obj, sym]].delete(tmp) end @expects[[obj, sym]] << info else @expects[[obj, sym]] = [ info ] end end def self.set_objects(obj, sym, type = nil) @objects << [obj, sym, type] end # Verify to correct number of calls def self.verify() @expects.each do |k, expects| expects.each do |info| obj, sym = k[0], k[1] if info[:count] != :never && info[:count] != :any if info[:count] > 0 raise Exception.new("Method #{sym} with #{info[:with].inspect} and block #{info[:block].inspect} called too FEW times on object #{obj.inspect}") end end end end end # Clean up any methods we set up def self.cleanup() @objects.each do |info| obj, sym, type = info[0], info[1], info[2] hidden_name = "__ms_" + sym.to_s # Revert the object back to original if possible case type when :all_instances next when :single_new # meta = class << obj; self; end # meta.send :remove_method, sym.to_sym when :single_overridden meta = class << obj; self; end meta.module_eval { alias_method(sym.to_sym, hidden_name.to_sym) } end end end def self.get_method_missing_methods(obj, sym) methods = [] info = @expects[[obj, sym]] return methods if info.nil? info.each { |info| methods << info[:with].first unless info[:with] == :any } methods end # Invoked by a replaced method in an object somewhere. # Verifies that the method is called as expected with # the exception that calling the method too few times # is not detected until #verify_expects! gets called # which by default happens at the end of a #specify def self.report(obj, sym, *args, &block) info = @expects[[obj, sym]].find do |info| info[:with] == :any || info[:with] == args end return unless info unless info[:block] == :any if block unless info[:block] return end end end unless info[:count] == :any if info[:count] == :never raise Exception.new("Method #{sym} with #{info[:with].inspect} and block #{info[:block].inspect} should NOT be called on object #{obj.inspect}") end info[:count] = info[:count] - 1 if info[:count] < 0 raise Exception.new("Method #{sym} with #{info[:with].inspect} and block #{info[:block].inspect} called too MANY times on object #{obj.inspect}") end end return info[:returning] end end # Start up Mock.reset end libflickrnet-48055~2.2.0/RubyTests/Specs/mini_rspec.rb0000644000175000017500000002257011155417352021547 0ustar varunvarun# mini_rspec.rb # # Very minimal set of features to support RSpec specs like this: # # describe "Array" do # it "responds to new" do # Array.new.should == [] # end # end class SpecReporter class ExpectationReport def exception=(e) @exception = e end def exception @exception end def describe=(d) @describe = d.to_s end def describe @describe end def it=(i) @it = i.to_s end def it @it end end attr_reader :failures def initialize(out=STDOUT) self.out = out @examples = 0 @failures = 0 @exceptions = [] end def out=(out) if out.is_a?(IO) @out = out else @out.close if @out != nil @out = File.open(out, "w") end end def before_describe(msg) @describe = msg end def after_describe(msg); end def before_it(msg) @report = ExpectationReport.new @report.describe = @describe @report.it = msg @examples += 1 end def after_it(msg); end def exception(e) @failures += 1 @report.exception = e @exceptions.push(@report) end def summarized=(flag) @summarized = flag end def summary unless @summarized @out.print "\n\n" @exceptions.each_with_index do |r,i| print_failure(i+1,r) print_backtrace(r.exception) end print_summary @summarized = true end end def print_summary @out.print @examples.to_s + " examples, " + @failures.to_s + " failures\n" end def print_failure(i,r) @out.print i.to_s + ")\n" + r.describe + " " + r.it + " FAILED\n" end def print_backtrace(e) if e.message != "" @out.print e.message + ": \n" begin @out.print e.backtrace.show rescue Exception @out.puts e.backtrace end @out.print "\n" else @out.print "" end @out.print "\n" end end class SpecDoxReporter < SpecReporter def before_describe(msg) super @describe_printed = false end def print_describe unless @describe_printed @out.print "\n" + @describe.to_s + "\n" @describe_printed = true end end def before_it(msg) super print_describe @out.print "- " + msg end def after_it(msg) @out.print "\n" end def exception(e) super if e.is_a?(ExpectationNotMetError) @out.print " (FAILED - " + @failures.to_s + ")" else @out.print " (ERROR - " + @failures.to_s + ")" end end end class DottedReporter < SpecReporter def before_describe(msg) @describe = msg @out.print "\n#{msg}: " end def after_it(msg) if @report.exception if @report.exception.is_a?(ExpectationNotMetError) @out.print 'F' else @out.print 'E' end else @out.print '.' end end def summary puts print_summary @summarized = true end end class SummaryReporter < SpecReporter def summary unless @summarized print_summary @summarized = true end end end class HtmlReporter < SpecReporter end class CIReporter < SpecReporter def print_failure(i,r) @out.print r.describe + " " + r.it + "\n" end def summary unless @summarized @exceptions.each_with_index do |r,i| print_failure(i+1,r) end @summarized = true end end end class ImmediateReporter < SpecReporter def after_it(msg) if @report.exception @out.print 'F' @out.print "\n" + @report.describe + " " + @report.it + " FAILED\n" print_backtrace(@report.exception) else @out.print '.' end end def summary unless @summarized @out.print "\n\n" print_summary @summarized = true end end end class SuccessReporter < SpecReporter def after_it(msg) if !@report.exception @out.puts @report.describe + " " + @report.it end end def summary unless @summarized @out.puts "Total pass: #{@examples - @failures} out of #{@examples} examples" @summarized = true end end end class FailureReporter < SpecReporter def after_it(msg) if @report.exception @out.puts @report.describe + " " + @report.it print_backtrace(@report.exception) end end def summary unless @summarized @out.puts "Total failures: #{@failures} out of #{@examples} examples" @summarized = true end end end class GenerateExcludesReporter < SpecReporter def after_it(msg) if @report.exception @out.puts @report.describe.strip + " " + @report.it.strip end end def summary end end class CoverageReporter < SpecReporter def summary unless @summarized @out.puts "#{@examples-@failures} of #{@examples} (#{(((@examples-@failures).to_f/@examples.to_f)*100).to_i}%) of specs pass." @summarized = true end end end class ExpectationNotMetError < StandardError end class PositiveExpectation def initialize(obj) @obj = obj end def ==(other) unless @obj == other raise ExpectationNotMetError.new("Expected #{@obj.inspect} to equal #{other.inspect}") end end # TODO: uncomment this when we have better regex support #def =~(other) # unless @obj =~ other # raise ExpectationNotMetError.new("Expected #{@obj.inspect} to match #{other.inspect}") # end #end end class NegativeExpectation def initialize(obj) @obj = obj end def ==(other) if @obj == other raise ExpectationNotMetError.new("Expected #{@obj.inspect} not to equal #{other.inspect}") end end # TODO: uncomment this when we have better regex support #def =~(other) # if @obj =~ other # raise ExpectationNotMetError.new("Expected #{@obj.inspect} not to match #{other.inspect}") # end #end end class Object def should PositiveExpectation.new(self) end def should_not NegativeExpectation.new(self) end end class SpecRunner def initialize(reporter=nil) @only = [] @except = [] @reporter = reporter if @reporter == nil @reporter = SpecDoxReporter.new # TODO: enable this again when we have environment variables working #if rep = ENV['REPORTER'] # TODO: cls = Object.const_get(rep) rescue nil # when we fix AST # begin # cls = Object.const_get(rep) # rescue # nil # end # if cls.nil? # puts "Unable to find reporter '#{rep}', falling back." # @reporter = DottedReporter.new # else # @reporter = cls.new # end #else # @reporter = DottedReporter.new #end end end def reporter @reporter end def reporter=(reporter) @reporter = reporter end def escape(str) str.is_a?(Regexp) ? str : Regexp.new(Regexp.escape(str)) end def convert_to_regexps(args) args.inject([]) do |list, item| if item.is_a?(String) and File.exist?(item) if f = File.open(item, "r") f.each do |line| line.chomp! list << escape(line) unless line.empty? end f.close end list else list << escape(item) end end end def only(*args) @only = convert_to_regexps(args) end def except(*args) @except = convert_to_regexps(args) end def skip? example = @describe.to_s + " " + @it.to_s @except.each { |re| return true if re.match(example) } return false if @only.empty? return true unless @only.any? { |re| re.match(example) } end def before(at=:each,&block) if at == :each @before.push block elsif at == :all yield else raise ArgumentError, "I do not know when you want me to call your block" end end def after(at=:each,&block) if at == :each @after.push block elsif at == :all yield else raise ArgumentError, "I do not know when you want me to call your block" end end def it_excluded? it_name = "#{@describe.strip} #{@it.strip}" if $exclusions != nil && $exclusions.length > 0 result = $exclusions.include?(it_name) #puts "excluding #{it_name}" if result return result end false end def it(msg) @it = msg return if skip? return if it_excluded? @reporter.before_it(msg) begin begin @before.each { |b| b.call } yield Mock.verify rescue Exception => e @reporter.exception(e) ensure Mock.cleanup Mock.reset @after.each { |b| b.call } end rescue Exception => e @reporter.exception(e) end @reporter.after_it(msg) end def describe(msg) @before = [] @after = [] @describe = msg @reporter.before_describe(msg) yield @reporter.after_describe(msg) end end if @runner == nil @runner = SpecRunner.new end # Expose the runner methods def before(at=:each, &block) @runner.before(at, &block) end def after(at=:each, &block) @runner.after(at, &block) end def describe(msg, &block) @runner.describe(msg, &block) end def it(msg, &block) @runner.it(msg, &block) end # Alternatives class Object alias_method :context, :describe alias_method :specify, :it alias_method :setup, :before alias_method :teardown, :after end at_exit do @runner.reporter.summary if @runner.reporter.is_a? CoverageReporter #|| @runner.reporter.is_a? GenerateExcludesReporter exit(0) else exit(@runner.reporter.failures) end end libflickrnet-48055~2.2.0/RubyTests/Specs/spec_helper.rb0000644000175000017500000001061411155417352021704 0ustar varunvarun#$:.unshift File.dirname(__FILE__) # TODO: restore when ENV implemented #begin # if ENV['USE_RSPEC'] == '1' # require 'rspec_helper' # ExpectationNotMetError = Spec::Expectations::ExpectationNotMetError # else # require 'mspec_helper' # end #rescue # require 'mspec_helper' #end require File.dirname(__FILE__) + '/mini_rspec' require File.dirname(__FILE__) + '/mspec_helper' require File.dirname(__FILE__) + '/simple_mock' # TODO: restore mini_mock when we have class_eval working #require 'mini_mock' # used for many should_be_close specs TOLERANCE = 0.00003 unless Object.const_defined?(:TOLERANCE) if !defined?(RUBY_NAME) then begin require 'rbconfig' RUBY_NAME = Config::CONFIG["RUBY_INSTALL_NAME"] rescue Exception RUBY_NAME = RUBY_ENGINE end end def engine?(name) case name when :rbx, :rubinius RUBY_NAME == 'rbx' when :mri, :ruby RUBY_NAME == 'ruby' when :jruby RUBY_NAME == 'jruby' when :ironruby RUBY_NAME == 'ironruby' else false end end # The four methods #compliant, #noncompliant, #extension, and #failure # each describe one aspect of the specs they annotate, as follows: # # compliant(:ruby, :jruby) do # Run these specs on the listed engines. # Used for specs that conform to the Ruby "standard" # end # # noncompliant(:rubinius, :jruby) do # Run these specs on the listed engines. # Used for specs that do not conform to the Ruby "standard" # end # # extension(:rubinus, :cardinal) do # Run these specs on the listed engines. # Used for specs that do NOT behave differently than a Ruby # "standard" behavior, perhaps because no equivalent behavior # exists in Ruby. # end # # failure(:rubinius) do # Do NOT run these specs on the listed platform. # Used for specs that are expected to fail, perhaps because of # a bug on the listed engine. This is not for specs that are # noncompliant. This is a convenience to prevent executing # specs on a particular engine, perhaps because executing # the spec causes particularly nasty behavior. # end # # Please refer to these comments for the semantics of these # four methods. Don't refer to the implementation as it could # likely change. def compliant(*engines) yield if engines.any? { |e| engine?(e) } end def failure(*engines) yield unless engines.any? { |e| engine?(e) } end class Object alias_method :noncompliant, :compliant alias_method :extension, :compliant end # platform :darwin, :mswin do # run these specs if RUBY_PLATFORM matches :darwin or :mswin # end # # platform :not, :mswin do # run these specs if RUBY_PLATFORM does not match :mswin # end def platform(*args) yield if guard(*args) { |a| RUBY_PLATFORM.match(a.to_s) } end # version :not, '1.8.4', '1.8.6' do # run these specs if RUBY_VERSION is not 1.8.4 or 1.8.6 # end # # version '1.8.4'..'1.8.6' do # run these specs if RUBY_VERSION is in the range 1.8.4 to 1.8.6 # end def version(*args) yield if guard(*args) { |a| a === RUBY_VERSION } end def guard(*args, &cond) reverse = args.first == :not args.shift if reverse result = args.any?(&cond) reverse ? (not result) : result end class Object def should_include(*others) others = others.to_a unless others.is_a? Array others.each do |other| unless self.include?(other) raise ExpectationNotMetError.new("Expected " + self.inspect + " to include " + other.inspect) end end end def should_not_include(*others) others = others.to_a unless others.is_a? Array others.each do |other| if self.include?(other) raise ExpectationNotMetError.new("Expected " + self.inspect + " to not include " + other.inspect) end end end def should_be_close(value, tolerance) unless (value - self).abs <= tolerance raise ExpectationNotMetError.new("Expected " + self.inspect + " to be close to " + value.inspect) end end def should_be_ancestor_of(klass) unless klass.ancestors.include?(self) raise ExpectationNotMetError.new("Expected " + self.class.name + " to be kind of " + klass.name) end end end def shared(msg, &block) Object.instance_variable_set(:"@#{msg}", Proc.new(&block)) end def it_behaves_like(behavior, meth) Object.instance_variable_get(:"@#{behavior}").call(meth) end def dev_null null = Object.new null.instance_variable_set :@data, '' def null.write(str) @data << str end def null.print(str) write(str+$\.to_s) end def null.data() @data end null end libflickrnet-48055~2.2.0/RubyTests/search_group_spec.rb0000644000175000017500000000073111155417352022030 0ustar varunvarunrequire 'setup' describe 'Place Info' do it 'test group search' do o = FlickrNet::PhotoSearchOptions.new o.GroupId = '13378274@N00' o.PerPage = 10 o.SortOrder = FlickrNet::PhotoSearchSortOrder.DatePostedAsc ps = @flickrApi.PhotosSearch o ps.should_not == nil ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 p = ps.PhotoCollection[0] p.PhotoId.to_str.should == '256591001' end endlibflickrnet-48055~2.2.0/RubyTests/photoinfo_spec.rb0000644000175000017500000000231411155417352021353 0ustar varunvarunrequire 'setup' describe 'Simple searches' do before :each do @o = FlickrNet::PhotoSearchOptions.new @o.UserId = @test_data[:user_id]; @o.PerPage = 1 end it 'check basics' do ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| p.UserId.to_str.should == @test_data[:user_id] p.PhotoId.to_str.should_not == nil end end it 'usage' do ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| pi = @flickrApi.PhotosGetInfo(p.PhotoId) pi.Usage.should_not == nil pi.Usage.CanBlog.should == 0 pi.Usage.CanDownload.should == 1 pi.Usage.CanPrint.should == 0 end end it 'usage auth' do ps = @flickrAuth.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| pi = @flickrAuth.PhotosGetInfo(p.PhotoId) pi.Usage.should_not == nil pi.Usage.CanBlog.should == 1 pi.Usage.CanDownload.should == 1 pi.Usage.CanPrint.should == 1 end end end libflickrnet-48055~2.2.0/RubyTests/setup.rb0000644000175000017500000000156011155417352017476 0ustar varunvarunrequire 'Specs\spec_helper' require 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86' require 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL' require '..\FlickrNet\bin\Debug\FlickrNet.dll' @settings = { :api_key => 'dbc316af64fb77dae9140de64262da0a', :api_secret => '0781969a058a2745', :auth_token => '107943-d3eb4c0b6b08a79a'} @test_data = { :user_id => '41888973@N00', :user_name => 'Sam Judson', :tag => 'microsoft', :machine_tag => 'geo:lat=*'} FlickrNet::Flickr.CacheDisabled = true; @flickrApi = FlickrNet::Flickr.new @settings[:api_key] @flickrShared = FlickrNet::Flickr.new @settings[:api_key], @settings[:api_secret] @flickrAuth = FlickrNet::Flickr.new @settings[:api_key],@settings[:api_secret], @settings[:auth_token] libflickrnet-48055~2.2.0/RubyTests/place_spec.rb0000644000175000017500000000702211155417352020433 0ustar varunvarunrequire 'setup' describe 'Place Info' do before :each do @o = FlickrNet::PhotoSearchOptions.new @o.PerPage = 10 end it 'find by lat/lon' do # Search for newcastle place = @flickrApi.PlacesFindByLatLon 55.0, -1.6 place.PlaceId.should_not == nil place.WoeId.should_not == nil place.PlaceId.to_str.should == 'IEcHLFCaAZwoKQ' place.WoeId.to_str.should == '30079' place.PlaceUrl.to_str.should == '/United+Kingdom/England/Newcastle+upon+Tyne' place.Latitude.should == System::Decimal.new(54.977) place.Longitude.should == System::Decimal.new(-1.612) end it 'resolve place id' do # Search for newcastle location = @flickrApi.PlacesGetInfo 'IEcHLFCaAZwoKQ', nil location.should_not == nil location.PlaceId.to_str.should == 'IEcHLFCaAZwoKQ' location.WoeId.to_str.should == '30079' location.Locality.should_not == nil location.Locality.PlaceId.to_str.should == 'IEcHLFCaAZwoKQ' location.Locality.Description.to_str.should == 'Newcastle upon Tyne' location.Locality.Latitude.should == System::Decimal.new(54.977) location.Locality.Longitude.should == System::Decimal.new(-1.612) location.County.should_not == nil location.County.PlaceId.to_str.should == '5La1sJqYA5qNBtPTrA' location.County.Description.to_str.should == 'Tyne and Wear' location.County.Latitude.should == System::Decimal.new(54.939) location.County.Longitude.should == System::Decimal.new(-1.600) location.Region.should_not == nil location.Region.PlaceId.to_str.should == 'pn4MsiGbBZlXeplyXg' location.Region.Description.to_str.should == 'England' location.Region.Latitude.should == System::Decimal.new(52.883) location.Region.Longitude.should == System::Decimal.new(-1.976) location.Country.should_not == nil location.Country.PlaceId.to_str.should == 'DevLebebApj4RVbtaQ' location.Country.Description.to_str.should == 'United Kingdom' location.Country.Latitude.should == System::Decimal.new(54.313) location.Country.Longitude.should == System::Decimal.new(-2.232) end it 'resolve WOE id' do # Search for newcastle location = @flickrApi.PlacesResolvePlaceId nil, '30079' location.should_not == nil location.PlaceId.to_str.should == 'IEcHLFCaAZwoKQ' location.WoeId.to_str.should == '30079' location.Locality.should_not == nil location.Locality.PlaceId.to_str.should == 'IEcHLFCaAZwoKQ' location.Locality.Description.to_str.should == 'Newcastle upon Tyne' location.County.should_not == nil location.County.PlaceId.to_str.should == '5La1sJqYA5qNBtPTrA' location.Region.should_not == nil location.Region.PlaceId.to_str.should == 'pn4MsiGbBZlXeplyXg' location.Country.should_not == nil location.Country.PlaceId.to_str.should == 'DevLebebApj4RVbtaQ' end it 'resolve place URL' do # Search for newcastle location = @flickrApi.PlacesGetInfoByUrl '/United+Kingdom/England/Newcastle+upon+Tyne' location.should_not == nil location.PlaceId.to_str.should == 'IEcHLFCaAZwoKQ' location.WoeId.to_str.should == '30079' location.Locality.should_not == nil location.Locality.PlaceId.to_str.should == 'IEcHLFCaAZwoKQ' location.Locality.Description.to_str.should == 'Newcastle upon Tyne' location.County.should_not == nil location.County.PlaceId.to_str.should == '5La1sJqYA5qNBtPTrA' location.Region.should_not == nil location.Region.PlaceId.to_str.should == 'pn4MsiGbBZlXeplyXg' location.Country.should_not == nil location.Country.PlaceId.to_str.should == 'DevLebebApj4RVbtaQ' end end libflickrnet-48055~2.2.0/RubyTests/test_all.rb0000644000175000017500000000006511155417352020144 0ustar varunvarunDir['*_spec.rb'].each do |test| require test end libflickrnet-48055~2.2.0/RubyTests/setup_spec.rb0000644000175000017500000000052511155417352020510 0ustar varunvarunrequire 'setup' describe 'setup tests' do it 'settings work' do @settings[:api_key].should == 'dbc316af64fb77dae9140de64262da0a' @settings[:api_secret].should == '0781969a058a2745' @settings[:auth_token].should == '107943-d3eb4c0b6b08a79a' end it 'test data work' do @test_data[:user_id].should_not == nil end end libflickrnet-48055~2.2.0/RubyTests/search_spec.rb0000644000175000017500000001264311155417352020621 0ustar varunvarunrequire 'setup' describe 'Simple searches' do before :each do @o = FlickrNet::PhotoSearchOptions.new @o.PerPage = 10 end it 'check user id' do @o.UserId = @test_data[:user_id] ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| p.UserId.to_str.should == @test_data[:user_id] end end it 'check no extras' do @o.UserId = @test_data[:user_id] ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| p.CleanTags.should == nil p.OwnerName.should == nil p.MachineTags.should == nil p.OriginalFormat.should == nil p.IconServer.should == nil p.Latitude.should == System::Decimal.new(0) p.Longitude.should == System::Decimal.new(0) p.Accuracy.should == FlickrNet::GeoAccuracy.None p.DateTaken.should == System::DateTime.MinValue p.DateAdded.should == System::DateTime.MinValue p.DateUploaded.should == System::DateTime.MinValue p.LastUpdated.should == System::DateTime.MinValue p.OriginalHeight.should == -1 p.OriginalWidth.should == -1 p.License.should == nil p.Views.should == -1 p.Media.should == nil p.MediaStatus.should == nil end end it 'check extras' do @o.UserId = @test_data[:user_id] @o.Extras = FlickrNet::PhotoSearchExtras.All ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| p.CleanTags.should_not == nil p.OwnerName.should_not == nil p.MachineTags.should_not == nil p.OriginalFormat.should_not == nil p.IconServer.should_not == nil p.DateTaken.should_not == System::DateTime.MinValue p.DateUploaded.should_not == System::DateTime.MinValue p.LastUpdated.should_not == System::DateTime.MinValue p.OriginalHeight.should_not == -1 p.OriginalWidth.should_not == -1 p.License.should_not == nil p.Views.should_not == -1 p.Media.should_not == nil p.MediaStatus.should_not == nil end end it 'check locaility info extras' do @o.UserId = @test_data[:user_id] @o.Extras = FlickrNet::PhotoSearchExtras.Geo @o.BoundaryBox = FlickrNet::BoundaryBox.World ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| p.Latitude.should_not == System::Decimal.new(0) p.Longitude.should_not == System::Decimal.new(0) p.Accuracy.should_not == FlickrNet::GeoAccuracy.None end end it 'check original' do @o.UserId = @test_data[:user_id] @o.Extras = FlickrNet::PhotoSearchExtras.OriginalDimensions ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| p.OriginalHeight.should_not == -1 p.OriginalWidth.should_not == -1 end end it 'check owner name' do @o.UserId = @test_data[:user_id] @o.Extras = FlickrNet::PhotoSearchExtras.OwnerName ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| p.OwnerName.to_str.should == @test_data[:user_name] end end it 'check icon server' do @o.UserId = @test_data[:user_id] @o.Extras = FlickrNet::PhotoSearchExtras.IconServer ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| p.IconServer.should_not == nil end end it 'check date taken' do @o.UserId = @test_data[:user_id] @o.Extras = FlickrNet::PhotoSearchExtras.DateTaken ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| p.DateTaken.should_not == System::DateTime.MinValue end end it 'check date uploaded' do @o.UserId = @test_data[:user_id] @o.Extras = FlickrNet::PhotoSearchExtras.DateUploaded ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| p.DateUploaded.should_not == System::DateTime.MinValue end end it 'check last updated' do @o.UserId = @test_data[:user_id] @o.Extras = FlickrNet::PhotoSearchExtras.LastUpdated ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| p.LastUpdated.should_not == System::DateTime.MinValue end end it 'check tag search' do @o.Tags = @test_data[:tag] @o.Extras = FlickrNet::PhotoSearchExtras.Tags ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| p.CleanTags.should_not == nil p.CleanTags.split.index @test_data[:tag] .should_not == nil end end it 'check machine tag search' do @o.MachineTags = @test_data[:machine_tag] @o.Extras = FlickrNet::PhotoSearchExtras.MachineTags ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| p.MachineTags.should_not == nil end end end libflickrnet-48055~2.2.0/RubyTests/does_large_exist_spec.rb0000644000175000017500000000153311155417352022670 0ustar varunvarunrequire 'setup' describe 'Does Large Exist' do before :each do @o = FlickrNet::PhotoSearchOptions.new @o.PerPage = 10 @o.UserId = @test_data[:user_id] @o.Extras = FlickrNet::PhotoSearchExtras.All end it 'is large must return true' do @o.Tags = 'largeexists' ps = @flickrAuth.PhotosSearch @o ps.PhotoCollection.each do |p| p.DoesLargeExist.should == true s = @flickrAuth.DownloadPictureWithoutRedirect(p.LargeUrl) s.should_not == nil s.Close end end it 'is large must return false' do @o.Tags = 'largedoesntexist' ps = @flickrAuth.PhotosSearch @o i = 1 ps.PhotoCollection.each do |p| p.DoesLargeExist.should == false s = @flickrAuth.DownloadPictureWithoutRedirect(p.LargeUrl) s.should == nil end end end libflickrnet-48055~2.2.0/RubyTests/search2_spec.rb0000644000175000017500000000346111155417352020701 0ustar varunvarunrequire 'setup' describe 'More searches' do before :each do @o = FlickrNet::PhotoSearchOptions.new @o.PerPage = 10 end it 'does safe search' do begin @o.SafeSearch = FlickrNet::SafetyLevel.Safe @o.Tags = @test_data[:tag] ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 rescue Exception puts @flickrApi.LastRequest end end it 'does content search' do begin @o.ContentType = FlickrNet::ContentTypeSearch.PhotosOnly @o.Tags = @test_data[:tag] ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 rescue Exception puts @flickrApi.LastRequest end end it 'do lat/lon search' do @o.UserId = @test_data[:user_id] @o.Latitude = 55.0 @o.Longitude = -1.6 @o.Radius = 20.0 @o.RadiusUnits = FlickrNet::RadiusUnits.Miles @o.Extras = FlickrNet::PhotoSearchExtras.Geo ps = @flickrApi.PhotosSearch @o ps.PhotoCollection.should_not == nil ps.PhotoCollection.Length.should_not == 0 ps.PhotoCollection.each do |p| p.Latitude.should_not == System::Decimal.new(0) p.Longitude.should_not == System::Decimal.new(0) p.Accuracy.should_not == FlickrNet::GeoAccuracy.None end end it 'page results' do @o.UserId = @test_data[:user_id] @o.Page = 1 ps1 = @flickrApi.PhotosSearch @o @o.Page = 2 ps2 = @flickrApi.PhotosSearch @o ps1.should_not == nil ps2.should_not == nil ps1.PhotoCollection.should_not == nil ps2.PhotoCollection.should_not == nil ps1.PhotoCollection.Length.should_not == 0 ps2.PhotoCollection.Length.should_not == 0 ps1.PhotoCollection[0].PhotoId.should_not == ps2.PhotoCollection[0].PhotoId end end libflickrnet-48055~2.2.0/RubyTests/auth_spec.rb0000644000175000017500000000152711155417354020316 0ustar varunvarunrequire 'setup' require 'System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL' def serialize(obj) ms = System::IO::MemoryStream.new xs = System::Xml::Serialization::XmlSerializer.new(obj.GetType) xs.Serialize(ms, obj) return ms end def deserialize(ms, t) xs = System::Xml::Serialization::XmlSerializer.new(t) return xs.Deserialize(ms) end describe 'Auth serialization' do it 'save setting' do a = FlickrNet::Auth.new a.Token = "test token" a.User = FlickrNet::FoundUser.new a.User.UserId = @test_data[:user_id] ms = serialize(a) ms.Position = 0 b = deserialize(ms, a.GetType) b.should_not == nil b.Token.should == a.Token b.User.should_not == nil b.User.UserId.should == a.User.UserId end end libflickrnet-48055~2.2.0/RubyTests/simple_spec.rb0000644000175000017500000000173711155417352020647 0ustar varunvarunrequire 'setup' describe 'Constructor test' do it 'everything should be null' do f = FlickrNet::Flickr.new f.ApiKey.should == nil f.ApiSecret.should == nil f.AuthToken.should == nil end it 'api key should be set' do f = FlickrNet::Flickr.new @settings[:api_key] f.ApiKey.to_str.should == @settings[:api_key] f.ApiSecret.should == nil f.AuthToken.should == nil end it 'api key and secret should be set' do f = FlickrNet::Flickr.new @settings[:api_key], @settings[:api_secret] f.ApiKey.to_str.should == @settings[:api_key] f.ApiSecret.to_str.should == @settings[:api_secret] f.AuthToken.should == nil end it 'api key, secret and auth_token should be set' do f = FlickrNet::Flickr.new @settings[:api_key], @settings[:api_secret], @settings[:auth_token] f.ApiKey.to_str.should == @settings[:api_key] f.ApiSecret.to_str.should == @settings[:api_secret] f.AuthToken.to_str.should == @settings[:auth_token] end end libflickrnet-48055~2.2.0/RubyTests/bounding_box_spec.rb0000644000175000017500000000073711155417352022032 0ustar varunvarunrequire 'setup' describe 'Bounding Box in alternative cultures' do it 'test with french culture' do b = FlickrNet::BoundaryBox.UK d = System::Decimal.new(12.02) s1 = b.ToString s2 = d.ToString System::Threading::Thread.CurrentThread.CurrentCulture = System::Globalization::CultureInfo.CreateSpecificCulture("fr") s3 = b.ToString s4 = d.ToString s1.to_str.should == s3.to_str s2.to_str.should_not == s4.to_str end end libflickrnet-48055~2.2.0/Support/0000755000175000017500000000000011155417352015517 5ustar varunvarunlibflickrnet-48055~2.2.0/Support/Flickr Net Sandcastle File.shfb0000644000175000017500000000452611155417352023215 0ustar varunvarun Summary, Parameter, Returns, AutoDocumentCtors, Namespace, TypeParameter InheritedMembers, InheritedFrameworkMembers, Protected, SealedProtected .\Help\ True True HtmlHelp1x False 1.1.4322 False False False Flckr.Net API Library FlickrNet en-US http://www.codeplex.com/FlickrNet Flickr.Net API Library, GPL 2.0 sam@wackylabs.net Contact Sam Judson Local Msdn Blank vs2005 Guid Standard False True False Hierarchical True ms.vsipcc+, ms.vsexpresscc+ 1.0.0.0 AboveNamespaces libflickrnet-48055~2.2.0/..svnbridge/0000755000175000017500000000000011155417352016162 5ustar varunvarunlibflickrnet-48055~2.2.0/..svnbridge/.svnbridge0000644000175000017500000000041011155417352020141 0ustar varunvarunsvn:ignore*.suo