Andras Csehi
Andras Csehi

Reputation: 4305

Enumerating camera roll pictures throws invalidoperationexception

The below code throws invalidOperationException but only if the debugger is detached. The code targets 7.1 and from time to time users are reporting issues. This is the first time I can repro this issue on a windows phone 8 device but only when I detach the debugger. When the debugger is attached the code runs perfectly fine. The issue is not a consistent repro. In the analytics I saw small percentage of the users facing this issue. Any idea what’s happening here?

       PictureAlbum localRoll = media.GetCameraRoll();
       foreach (Picture pic in localRoll.Pictures) // exception here
       {

       }


        public PictureAlbum GetCameraRoll()
        {
        // Work around for known bug in the media framework.  Hits the static constructors
        // so the user does not need to go to the picture hub first.
        MediaPlayer.Queue.ToString();

        MediaLibrary ml = null;
        PictureAlbum cameraRoll = null;

        foreach (MediaSource source in MediaSource.GetAvailableMediaSources())
        {
            if (source.MediaSourceType == MediaSourceType.LocalDevice)
            {
                ml = new MediaLibrary(source);

                PictureAlbumCollection allAlbums = ml.RootPictureAlbum.Albums;

                foreach (PictureAlbum album in allAlbums)
                {
                    if (album.Name == "Camera Roll")
                    {
                        cameraRoll = album;
                        return cameraRoll;
                    }
                }
            }
        }

        return null;
    }

System.InvalidOperationException: An unexpected error has occurred. at Microsoft.Xna.Framework.Media.MediaLibraryEnumerator'1.System.Collection.Ienumerator'1.get_Item(Int32 index)

Upvotes: 0

Views: 352

Answers (2)

Andras Csehi
Andras Csehi

Reputation: 4305

Very strange but works. Calling OrderBy first on the pictures doesn't throw exception.

                var a = localRoll.Pictures;

                foreach (Picture pic in a.OrderBy(x=>x.Date))
                {

                }

Upvotes: 2

Chhaya Sharma
Chhaya Sharma

Reputation: 464

Please check if localRoll and localRoll.Pictures != null and localRoll.Pictures.Count > 0 because its possible that some phones have 0 pictures and the code is trying to iterate over a null collection.

   PictureAlbum localRoll = media.GetCameraRoll();
   if(localRoll != null)
   {
      if(localRoll.Pictures != null)
      {
          if(localRoll.Pictures.Count > 0)
          {
             foreach (Picture pic in localRoll.Pictures)
             {

             }
          }
      }
   }

Upvotes: 0

Related Questions