private void ComputeCurrentCDInfo(IProgress<ImportExportError> iIImportExportProgress)
        {
            try
            {
                iTunesApp iTunesApp = new iTunesApp();

                IITSourceCollection _sources = iTunesApp.Sources;

                var lib = iTunesApp.Sources.Cast<IITSource>().Where(s => s.Kind == ITSourceKind.ITSourceKindAudioCD).FirstOrDefault();

                if (lib == null)
                {
                    iIImportExportProgress.SafeReport(new ItunesCDNotFoundError());
                    return;
                }

                IITAudioCDPlaylist cd = lib.Playlists.get_ItemByName(lib.Name) as IITAudioCDPlaylist;

                if (cd == null)
                {
                    iIImportExportProgress.SafeReport(new ItunesUnknownError());
                    return;
                }

                IFullAlbumDescriptor ad = AlbumDescriptor.FromiTunes(cd);

                FoundCDInfo = new WebMatch<IFullAlbumDescriptor>(ad, MatchPrecision.Suspition, WebProvider.iTunes);
            }
            catch (Exception e)
            {
                Trace.WriteLine("iTunes CD information introspection failed "+e.ToString());
                iIImportExportProgress.SafeReport(new ITunesNotResponding());
            }
        }
 public bool Commit(IProgress<ImportExportError> progress = null)
 {
     EventHandler<ImportExportError> CallBack = (o,e) => progress.SafeReport(e);
     Context.Error += CallBack;
     bool res = CommitChanges();
     Context.Error -= CallBack;
     Dispose();
     return res;
 }
        private bool TrivialCommit(IMusicTransaction IMut,IProgress<ImportExportError> progress)
        {
            bool res = true;

            if (Tracks.Count == 0)
            {
                IMut.ImportContext.AddForRemove(_AM);
                RemoveFileIfNeccessary(_AM.RawTracks, progress);
            }
            else
            {
                IMut.ImportContext.AddForUpdate(_AM);

                try
                {
                    List<TrackModifier> tmstr = new List<TrackModifier>();

                    _Tracks.OnBeforeChangedCommited += ((o, e) =>
                    {
                        if (e.What == NotifyCollectionChangedAction.Remove)
                            tmstr.Add(e.Who as TrackModifier);
                    });

                    _Tracks.CommitChanges();

                    if (tmstr.Count > 0)
                    {
                        var FileToRemove = from t in tmstr select t.Track;

                        foreach (Track tm in FileToRemove)
                        {
                            _IT.AddForRemove(tm);
                        }

                        RemoveFileIfNeccessary(FileToRemove, progress);
                    }

                    using (_AM.MusicSession.Albums.GetRenamerTransaction(_AM))
                    {
                        if (_AuthorDirty)
                        {
                            _Artists.CommitChanges();
                        }

                        if (NewName != null)
                            _AM.Name = NewName;
                    }

                    if (IsImageDirty)
                    {
                        _AlbumImages.CommitChanges();
                        int Count = _AM.Images.Count;
                        PictureTobeStored = (from imama in (from im in _AM.Images where (_IT.ImageManager.IsImageRankOKToEmbed(im.Rank, Count)) select im.ConvertToIPicture()) where imama != null select imama).ToArray();
                    }

                    bool Modifyres = (_AM.Modify(this));

                    if (Modifyres == false)
                    {
                        PictureTobeStored = null;
                        progress.SafeReport(new UnknownNameChangedEventArgs(_AM.ToString()));
                        //OnError(new UnknownNameChangedEventArgs(_AM.ToString()));
                        return false;
                    }
                }
                catch (Exception e)
                {
                    PictureTobeStored = null;
                    Trace.WriteLine(e);
                    progress.SafeReport(new UnknownNameChangedEventArgs(_AM.ToString()));
                    //OnError(new UnknownNameChangedEventArgs(_AM.ToString()));
                    return false;
                }

                PictureTobeStored = null;
            }

            return res;
        }
        private bool PrivateCommit(IProgress<ImportExportError> progress)
        {
            _UnderTrans = true;
            if (!SomeThingChanged)
            {
                _UnderTrans = false;
                _AM.Context = null;
                Dispose();
                return true;
            }

            bool res = false;

            Album toremove = OtherAlbumSameName;
            if (toremove != null)
            {
                AlbumModifier AM = toremove.GetModifiableAlbum(false, _IT);

                if (AM == null)
                {
                    _UnderTrans = false;
                    _AM.Context = null;
                    Dispose();
                    return false;
                }

                using (AM)
                {
                    OtherAlbumConfirmationNeededEventArgs Err = new OtherAlbumConfirmationNeededEventArgs(toremove);
                    progress.SafeReport(Err);
                    //OnError(Err);
                    if (!Err.Continue)
                    {
                        res = false;
                    }
                    else
                    {
                        //this.Author = null;
                        this.Name = null;
                        this._Artists.CancelChanges();

                        res = (SomeThingChanged) ? PrivateSimpleCommit(progress) : true;

                        if (res)
                        {
                            res = AlbumMerge(_AM, AM, _IT, progress);
                        }
                    }
                }
            }
            else res = PrivateSimpleCommit(progress);

            _UnderTrans = false;
            _AM.Context = null;
            Dispose();
            return res;
        }
        private bool RemoveFileIfNeccessary(IEnumerable<Track> FileToRemove, IProgress<ImportExportError> progress)
        {
            bool? delete = _IT.DeleteManager.DeleteFileOnDeleteAlbum;

            if (delete == false)
                return false;

            FileCleaner proprifier = Context.Folders.GetFileCleanerFromTracks(FileToRemove, _IT.Folders.IsFileRemovable, null, true);

            if (delete == null)
            {
                DeleteAssociatedFiles deaf = new DeleteAssociatedFiles(proprifier.Paths);
                progress.SafeReport(deaf);
                delete = (deaf.Continue == true);
            }

            if (delete == true)
                proprifier.Remove();

            return (delete == true);
        }
            bool IMusicfilesConverter.ConvertTomp3(IProgress<TrackConverted> iprogress, CancellationToken iCancellationToken, bool deleteIfSucceed)
            {
                finalres = true;
                int i = 0;

                if (_Lames.Count() != _ICI.RawTrackDescriptors.Count)
                {
                    Trace.WriteLine("CD track number mismatch. May appear when itunes has an open window for a cd (choose correct name).");
                    return false;
                }

                foreach (EncoderLAME AL in _Lames)
                {
                    if (iCancellationToken.IsCancellationRequested)
                        break;

                    TrackDescriptor itd = _ICI.RawTrackDescriptors[i++];

                    if (!AL.EncoderExists)
                    {
                        throw new InvalidDataException("Lame encoder not found.");
                    }

                    int stream = AL.ChannelHandle;

                    double time = Bass.BASS_ChannelBytes2Seconds(stream, Bass.BASS_ChannelGetLength(stream));

                    string OutPut = FileInternalToolBox.CreateNewAvailableName(_Output, string.Format("{0}-{1}", itd.TrackNumber, itd.Name.FormatFileName(100)), FileServices.MP3);

                    AL.OutputFile = OutPut;

                    AL.Start(null, IntPtr.Zero, false);
                    // decode the stream (if not using a decoding channel, simply call "Bass.BASS_ChannelPlay" here)
                    byte[] encBuffer = new byte[65536]; // our dummy encoder buffer
                    while (Bass.BASS_ChannelIsActive(stream) == BASSActive.BASS_ACTIVE_PLAYING)
                    {
                        // getting sample data will automatically feed the encoder
                        int len = Bass.BASS_ChannelGetData(stream, encBuffer, encBuffer.Length);
                    }
                    AL.Stop();  // finish

                    itd.Path = AL.OutputFile;
                    itd.Duration = TimeSpan.FromSeconds(time);

                    iprogress.SafeReport(new TrackConverted(itd, File.Exists(itd.Path)));
                }

                BassCd.BASS_CD_Release(_CD);

                return finalres;
            }
            bool IMusicfilesConverter.ConvertTomp3(IProgress<TrackConverted> iprogress, CancellationToken iCancellationToken, bool deleteIfSucceed)
            {
                if (!_Lame.EncoderExists)
                {
                    throw new InvalidDataException("Lame encoder not found.");
                }

                double From = 0;
                double To = 0;

                int stream = Bass.BASS_StreamCreateFile(_FileName.ToBeConsidered, 0, 0, BASSFlag.BASS_STREAM_DECODE);
                double time = Bass.BASS_ChannelBytes2Seconds(stream, Bass.BASS_ChannelGetLength(stream));
                Bass.BASS_StreamFree(stream);

                bool finalres = true;
                int Count = _Cues.Count;

                for (int i = 0; i < Count; i++)
                {
                    if (iCancellationToken.IsCancellationRequested)
                        break;

                    TrackDescriptor Tr = _Cues[i];

                    if (i == 0)
                        From = -1;
                    else
                    {
                        From = Tr.CueIndex01.TotalSeconds;
                    }

                    if (i + 1 < Count)
                    {
                        TimeCueIndexer tci = _Cues[i + 1].CueIndex00 ?? _Cues[i + 1].CueIndex01;
                        To = tci.TotalSeconds;
                    }
                    else
                    {
                        To = (long)time;
                    }

                    string OutPut = FileInternalToolBox.CreateNewAvailableName(_Output, String.Format("{0}-{1}", Tr.TrackNumber, Tr.Name).FormatFileName(150), FileServices.MP3);

                    FileChecker Out = new FileChecker(OutPut, _TempDir);

                    bool OK = BaseEncoder.EncodeFile(_FileName.ToBeConsidered, Out.ToBeConsidered, _Lame, null, false, false, true, From, To);

                    if (OK)
                    {
                        if (File.Exists(Out.ToBeConsidered))
                            Out.Finalise();
                        else
                            OK = false;
                    }

                    if (OK == false)
                        finalres = false;

                    Tr.Path = OutPut;
                    double realfrom = (From == -1) ? 0 : From;
                    Tr.Duration = TimeSpan.FromSeconds(To - realfrom);

                    iprogress.SafeReport(new TrackConverted(Tr, OK));
                }

                _FileName.Finalise();

                if (finalres && deleteIfSucceed)
                    File.Delete(_FileName.Desired);

                return finalres;
            }
        //private UISafeEvent<InternetFinderResultEventArgs> _OnResult;
        //private UISafeEvent<InternetFailedArgs> _OnInternetError;

        //public event EventHandler<InternetFinderResultEventArgs> OnResult
        //{
        //    add { _OnResult.Event += value; }
        //    remove { _OnResult.Event -= value; }
        //}

        //public event EventHandler<InternetFailedArgs> OnInternetError
        //{
        //    add { _OnInternetError.Event += value; }
        //    remove { _OnInternetError.Event -= value; }
        //}

        private void ConnectionDown(InternetFailed ifa, IProgress<InternetFailed> iInternetFailedArgs, WebProvider? Provider = null)
        {
            ifa.WebService = Provider;
            //_OnInternetError.Fire(ifa, true);
            iInternetFailedArgs.SafeReport(ifa);
        }