Blog - Single Post

using google-gdata to build a simple picasa photo album slide show to integrate in your website

There is a very good sample libraries available by google. google-gdata You can go through all these example, but for my scenario, I have need only 3 assembles from the core project.

  1. Google.GData.Client.dll
  2. Google.GData.Extensions.dll
  3. Google.GData.Photos.dll

using references on above library, we now start building our client to read a album from your personal Picasa account.

List of files you need

  1. PhotoList.cs
  2. FeedSerializer.cs
  3. GoogleClientLogin.cs
  4. PicasaClient.cs
  5. PictureBrowser.cs

PhotoList.cs


public class PhotoList
    {
        public string Name { get; set; }
        public string ThumbnailUrl { get; set; }
        public string ImageUrl { get; set; }
    }

FeedSerializer.cs


[XmlType("feed", Namespace = "http://www.w3.org/2005/Atom")]
    [XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
    public class picasa
    {
        [XmlAttribute]
        public string id { get; set; }

        [XmlAttribute]
        public string title { get; set; }

        [XmlAttribute]
        public string icon { get; set; }

        [XmlElement("link")]
        public FeedLink[] links { get; set; }

        [XmlElement("generator")]
        public FeedGenerator generator { get; set; }

        [XmlElement("author")]
        public FeedAuthor author { get; set; }

        [XmlElement(Namespace = "http://a9.com/-/spec/opensearch/1.1/")]
        public int totalResults { get; set; }

        [XmlElement("entry")]
        public FeedEntry[] entries { get; set; }

        [XmlType("entry", Namespace = "http://www.w3.org/2005/Atom")]
        public partial class FeedEntry
        {
            [XmlElement]
            public string id { get; set; }

            [XmlElement]
            public FeedCategory category { get; set; }

            [XmlElement]
            public string title { get; set; }

            [XmlElement]
            public string summary { get; set; }

            [XmlElement]
            public string rights { get; set; }

            [XmlElement("link")]
            public FeedLink[] links { get; set; }

            [XmlElement("author")]
            public FeedAuthor author { get; set; }

            [XmlElement(ElementName = "id", Namespace = "http://schemas.google.com/photos/2007")]
            public string gid { get; set; }

            [XmlElement(ElementName = "name", Namespace = "http://schemas.google.com/photos/2007")]
            public string gname { get; set; }

            [XmlElement(ElementName = "location", Namespace = "http://schemas.google.com/photos/2007")]
            public string glocation { get; set; }

            [XmlElement(ElementName = "access", Namespace = "http://schemas.google.com/photos/2007")]
            public string gaccess { get; set; }

            [XmlElement(ElementName = "timestamp", Namespace = "http://schemas.google.com/photos/2007")]
            public string gtimestamp { get; set; }

            [XmlElement(ElementName = "numphotos", Namespace = "http://schemas.google.com/photos/2007")]
            public int gnumphotos { get; set; }

            [XmlElement(ElementName = "numphotosremaining", Namespace = "http://schemas.google.com/photos/2007")]
            public int gnumphotosremaining { get; set; }

            [XmlElement(ElementName = "bytesUsed", Namespace = "http://schemas.google.com/photos/2007")]
            public int gbytesUsed { get; set; }

            [XmlElement(ElementName = "user", Namespace = "http://schemas.google.com/photos/2007")]
            public string guser { get; set; }

            [XmlElement(ElementName = "nickname", Namespace = "http://schemas.google.com/photos/2007")]
            public string gnickname { get; set; }

            [XmlElement(ElementName = "commentingEnabled", Namespace = "http://schemas.google.com/photos/2007")]
            public string gcommentingEnabled { get; set; }

            [XmlElement(ElementName = "commentCount", Namespace = "http://schemas.google.com/photos/2007")]
            public int gcommentCount { get; set; }

            [XmlElement(ElementName = "group", Namespace = "http://search.yahoo.com/mrss/")]
            public MediaGroup mgroup { get; set; }


        }

        #region XML types
        [XmlType("author", Namespace = "http://www.w3.org/2005/Atom")]
        public partial class FeedAuthor
        {
            [XmlElement(ElementName = "name", Namespace = "http://www.w3.org/2005/Atom")]
            public string name { get; set; }

            [XmlElement(ElementName = "uri", Namespace = "http://www.w3.org/2005/Atom")]
            public string uri { get; set; }
        }

        [XmlType("category", Namespace = "http://www.w3.org/2005/Atom")]
        public partial class FeedCategory
        {
            [XmlAttribute(AttributeName = "scheme", Namespace = "http://www.w3.org/2005/Atom")]
            public string scheme { get; set; }

            [XmlAttribute(AttributeName = "term", Namespace = "http://www.w3.org/2005/Atom")]
            public string term { get; set; }
        }

        [XmlType("link", Namespace = "http://www.w3.org/2005/Atom")]
        public partial class FeedLink
        {
            [XmlAttribute(AttributeName = "rel", Namespace = "http://www.w3.org/2005/Atom")]
            public string rel { get; set; }

            [XmlAttribute(AttributeName = "type", Namespace = "http://www.w3.org/2005/Atom")]
            public string type { get; set; }

            [XmlAttribute(AttributeName = "href", Namespace = "http://www.w3.org/2005/Atom")]
            public string href { get; set; }
        }

        [XmlType("generator", Namespace = "http://www.w3.org/2005/Atom")]
        public partial class FeedGenerator
        {
            [XmlAttribute(AttributeName = "version", Namespace = "http://www.w3.org/2005/Atom")]
            public string version { get; set; }

            [XmlAttribute(AttributeName = "uri", Namespace = "http://www.w3.org/2005/Atom")]
            public string uri { get; set; }

            [XmlText]
            public string text { get; set; }
        }

        [XmlType("group", Namespace = "http://search.yahoo.com/mrss/")]
        public partial class MediaGroup
        {
            [XmlElement(ElementName = "content", Namespace = "http://search.yahoo.com/mrss/")]
            public MediaContent mgcontent { get; set; }

            [XmlElement(ElementName = "credit", Namespace = "http://search.yahoo.com/mrss/")]
            public string mgcredit { get; set; }

            [XmlElement(ElementName = "description", Namespace = "http://search.yahoo.com/mrss/")]
            public MediaDescription mgdescription { get; set; }

            [XmlElement(ElementName = "thumbnail", Namespace = "http://search.yahoo.com/mrss/")]
            public Thumbnail[] mgthumbnail { get; set; }
        }

        [XmlType("content", Namespace = "http://search.yahoo.com/mrss/")]
        public partial class MediaContent
        {
            [XmlAttribute(AttributeName = "url", Namespace = "http://search.yahoo.com/mrss/")]
            public string url { get; set; }

            [XmlAttribute(AttributeName = "type", Namespace = "http://search.yahoo.com/mrss/")]
            public string type { get; set; }

            [XmlAttribute(AttributeName = "medium", Namespace = "http://search.yahoo.com/mrss/")]
            public string medium { get; set; }
        }

        [XmlType("thumbnail", Namespace = "http://search.yahoo.com/mrss/")]
        public partial class Thumbnail
        {
            [XmlAttribute(AttributeName = "url", Namespace = "http://search.yahoo.com/mrss/")]
            public string url { get; set; }

            [XmlAttribute(AttributeName = "height", Namespace = "http://search.yahoo.com/mrss/")]
            public string height { get; set; }

            [XmlAttribute(AttributeName = "width", Namespace = "http://search.yahoo.com/mrss/")]
            public string width { get; set; }

        }

        [XmlType("description", Namespace = "http://search.yahoo.com/mrss/")]
        public partial class MediaDescription
        {
            [XmlAttribute("type", Namespace = "http://search.yahoo.com/mrss/")]
            public string type { get; set; }

            [XmlText]
            public string description { get; set; }
        }
        #endregion
    }

**GoogleClientLogin.cs**


----------
 public class GoogleClientLogin
    {
        private string userName;
        private string password;
        private string authToken;
        private Service service;
        public string User
        {
            get
            {
                return this.userName;
            }
        }
        public string AuthenticationToken
        {
            get
            {
                return this.authToken;
            }
        }

        public GoogleClientLogin(Service serviceToUse, string username, string password)
        {
            //
            // Required for Windows Form Designer support
            //
            this.service = serviceToUse;
            this.userName = username;
            this.password = password;
            this.Login();
        }

        private void Login()
        {
            this.service.setUserCredentials(this.userName, this.password);
            this.authToken = this.service.QueryClientLoginToken();
        }
    }

PicasaClient.cs


public class PicasaClient
    {
        private String googleAuthToken = null;
        private String user = null;
        private PicasaService picasaService = new PicasaService("PhotoBrowser");
        private PicasaFeed picasaFeed = null;

        public Dictionary<string, string> albumPhotos = new Dictionary<string, string>();
        public List<PhotoList> photosList = new List<PhotoList>();
        public void Initialize()
        {
            if (this.googleAuthToken == null)
            {
                //GoogleClientLogin loginDialog = new GoogleClientLogin(
                //    new PicasaService("PhotoBrowser"),
                //    "dpasala@gmail.com",
                //    "04681a041");
                GoogleClientLogin loginDialog = new GoogleClientLogin(
                   new PicasaService("PhotoBrowser"),
                   ConfigurationManager.AppSettings["GoogleUserName"],
                   ConfigurationManager.AppSettings["GooglePassword"]);

                this.googleAuthToken = loginDialog.AuthenticationToken;
                this.user = loginDialog.User;

                if (this.googleAuthToken != null)
                {
                    picasaService.SetAuthenticationToken(loginDialog.AuthenticationToken);
                    UpdateAlbumFeed();
                }
            }
        }

        private void UpdateAlbumFeed()
        {
            AlbumQuery query = new AlbumQuery();

            query.Uri = new Uri(PicasaQuery.CreatePicasaUri(this.user));

            this.picasaFeed = this.picasaService.Query(query);

            if (this.picasaFeed != null && this.picasaFeed.Entries.Count > 0)
            {
                foreach (PicasaEntry entry in this.picasaFeed.Entries)
                {
                    Console.WriteLine(entry.Title.Text + " - " +
                        entry.GetPhotoExtensionValue(GPhotoNameTable.NumPhotos));
                }
                GetAlbumDetails(this.picasaFeed.Entries.Where(x => x.Title.Text == ConfigurationManager.AppSettings["AlbumName"] as string).FirstOrDefault() as PicasaEntry);
                BrowseAlbum(this.picasaFeed.Entries.Where(x => x.Title.Text == ConfigurationManager.AppSettings["AlbumName"] as string).FirstOrDefault() as PicasaEntry);
            }
        }

        private void GetAlbumDetails(PicasaEntry entry)
        {
            Uri thumbnailUri = null;
            if (entry != null)
            {
                //this.Cursor = Cursors.WaitCursor;
                MediaThumbnail thumb = entry.Media.Thumbnails[0];
                try
                {
                    thumbnailUri = new Uri(thumb.Attributes["url"] as string);
                    //Stream stream = this.picasaService.Query(new Uri(thumb.Attributes["url"] as string));

                    albumPhotos.Add(thumbnailUri.AbsoluteUri, thumbnailUri.AbsoluteUri);
                }
                catch
                {
                    // Handle error 
                }
                Album a = new Album();
                a.AtomEntry = entry;
            }
        }

        private void BrowseAlbum(PicasaEntry entry)
        {
            if (entry != null)
            {
                string photoUri = entry.FeedUri;
                if (photoUri != null)
                {
                    PictureBrowser b = new PictureBrowser(this.picasaService, false);
                    b.StartQuery(photoUri, entry.Title.Text);
                    ////IService iService = null;
                    ////var feed = new PicasaFeed(new Uri(photoUri), this.picasaService);
                    //b.OnDone(new PicasaFeed(new Uri(photoUri), this.picasaService));
                    ParsePhotos(photoUri);
                    //this.photosList = b.photosList;
                }
            }


        }

        private void ParsePhotos(string photoUri)
        {
            if (!string.IsNullOrEmpty(photoUri))
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(photoUri);

                // Set some reasonable limits on resources used by this request
                request.MaximumAutomaticRedirections = 4;
                request.MaximumResponseHeadersLength = 4;
                // Set credentials to use for this request.
                request.Credentials = CredentialCache.DefaultCredentials;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {

                    Console.WriteLine("Content length is {0}", response.ContentLength);
                    Console.WriteLine("Content type is {0}", response.ContentType);

                    // Get the stream associated with the response.
                    using (Stream receiveStream = response.GetResponseStream())
                    {
                        // Pipes the stream to a higher level stream reader with the required encoding format. 
                        using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                        {

                            Console.WriteLine("Response stream received.");
                            string resultXml = readStream.ReadToEnd();

                            XmlSerializer serializer = new XmlSerializer(typeof(picasa));
                            MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(resultXml));
                            picasa resultingMessage = (picasa)serializer.Deserialize(memStream);



                            foreach (var item in resultingMessage.entries)
                            {
                                Console.WriteLine(item.title);
                            }
                            response.Close();
                            readStream.Close();
                        }
                    }
                }
            }
        }
    }

PictureBrowser.cs


public class PictureBrowser
    {
        private List<UserState> states = new List<UserState>();
        private PicasaService picasaService;
        private PicasaFeed photoFeed;
        public List<PhotoList> photosList = new List<PhotoList>();
        public PictureBrowser(PicasaService service, bool doBackup)
        {
            //
            // Required for Windows Form Designer support
            //
            this.picasaService = service;
            this.picasaService.AsyncOperationCompleted += new AsyncOperationCompletedEventHandler(this.OnDone);
            this.picasaService.AsyncOperationProgress += new AsyncOperationProgressEventHandler(this.OnProgress);

            if (doBackup == true)
            {
            }
        }

        private void InitializeList(string title)
        {
           // this.Text = title;

            if (this.photoFeed != null && this.photoFeed.Entries.Count > 0)
            {
                foreach (PicasaEntry entry in this.photoFeed.Entries)
                {
                    this.photosList.Add(new PhotoList
                    {
                        Name = entry.Title.Text,
                        ImageUrl = entry.Media.Content.Url,
                        ThumbnailUrl = entry.Media.Thumbnails.FirstOrDefault() != null ? entry.Media.Thumbnails.FirstOrDefault().Url : null
                    });
                }
            }
        }

        public void StartQuery(string uri, string albumTitle)
        {
            UserState us = new UserState();
            this.states.Add(us);

            us.opType = UserState.OperationType.query;
            us.filename = albumTitle;

            this.picasaService.QueryFeedAync(new Uri(uri), DateTime.MinValue, us);
        }
        public void OnDone(PicasaFeed feed)
        {
            this.photoFeed = feed;
            this.InitializeList(null);
        }
        private void OnDone(object sender, AsyncOperationCompletedEventArgs e)
        {
            UserState ut = e.UserState as UserState;

            if (this.states.Contains(ut) == false)
                return;

            this.states.Remove(ut);

            if (e.Error == null && e.Cancelled == false)
            {
                if (ut.opType == UserState.OperationType.query ||
                    ut.opType == UserState.OperationType.queryForBackup)
                {
                    if (e.Feed != null)
                    {
                        this.photoFeed = e.Feed as PicasaFeed;
                        this.InitializeList(ut.filename);
                    }
                }
            }
        }
        private void OnProgress(object sender, AsyncOperationProgressEventArgs e)
        {
        }
    }

    public class UserState
    {
        public enum OperationType
        {
            upload,
            download,
            downloadList,
            query,
            queryForBackup
        }

        public string filename;
        public OperationType opType;
        public PicasaFeed feed;
        public int counter = 0;
        public string foldername;

    }