public void SetURI()
        {
            var device = new WebDiscoveryDevice {
                DiscoveryUri = new Uri("http://test.com")
            };

            Assert.IsNotNull(device.DiscoveryUri);
            Assert.AreEqual("http://test.com/", device.DiscoveryUri.ToString());
        }
        /// <summary>
        /// Fetches the discovery document from either a local cache if it exsits otherwise using
        /// a WebDiscoveryDecivce
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/>
        /// </returns>
        public Stream Fetch()
        {
            FileInfo cachedFile = GetCacheFile();
            bool     fetchFile  = false;

            // Check if we need to (re)download the document
            if (cachedFile.Exists == false)
            {
                logger.Debug("Document Not Found In Cache, fetching from web");
                fetchFile = true;
            }
            else if ((DateTime.UtcNow - cachedFile.LastWriteTimeUtc).TotalSeconds > CacheDuration)
            {
                logger.Debug("Document is outdated, refetching from web");
                fetchFile = true;
            }
            else
            {
                logger.Debug("Found Document In Cache");
            }

            // (re-)Fetch the document
            if (fetchFile)
            {
                try
                {
                    using (var device = new WebDiscoveryDevice(DiscoveryUri))
                    {
                        WriteToCache(device);
                    }
                }
                catch (WebException ex)
                {
                    // If we have a working cached file, we can still return it
                    if (cachedFile.Exists)
                    {
                        logger.Warning(
                            string.Format(
                                "Failed to refetch an outdated cache document [{0}]" +
                                " - Using cached document. Exception: {1}", DiscoveryUri, ex.Message), ex);

                        return(cachedFile.OpenRead());
                    }

                    // Otherwise: Throw the exception
                    throw;
                }
            }

            fileStream = cachedFile.OpenRead();
            return(fileStream);
        }
 private void WriteToCache(WebDiscoveryDevice device)
 {
     using (Stream webDocument = device.Fetch())
     {
         FileInfo fileInfo = GetCacheFile();
         using (FileStream cachedFileStream = fileInfo.OpenWrite())
         {
             var buffer = new byte[BufferSize];
             int read;
             while ((read = webDocument.Read(buffer, 0, buffer.Length)) > 0)
             {
                 cachedFileStream.Write(buffer, 0, read);
             }
             cachedFileStream.Close();
         }
     }
 }