internal static FWAdResponse LoadAdResponse(XElement element)
        {
            var result = new FWAdResponse();
            result.Version = (string)element.Attribute("version");
            result.CustomId = (string)element.Attribute("customId");
            var networkId = (string)element.Attribute("networkId");
            if (networkId != null)
            {
                result.NetworkId = int.Parse(networkId);
            }
            result.Diagnostic = (string)element.Element("diagnostic");
            result.CustomState = (string)element.Element("customState");

            var rendererManifestXml = element.Element("rendererManifest");
            if (rendererManifestXml != null)
            {
                result.RendererManifest = rendererManifestXml.Value;
                result.RendererManifestVersion = (string)rendererManifestXml.Attribute("version");
            }

            var visitorXml = element.Element("visitor");
            if (visitorXml != null)
            {
                result.Visitor = LoadVisitor(visitorXml);
            }

            var siteSectionXml = element.Element("siteSection");
            if (siteSectionXml != null)
            {
                result.SiteSection = LoadSiteSection(siteSectionXml);
            }

            var adsXml = element.Element("ads");
            if (adsXml != null)
            {
                foreach (var adXml in adsXml.Elements("ad"))
                {
                    result.Ads.Add(LoadAd(adXml));
                }
            }

            var parametersXml = element.Element("parameters");
            if (parametersXml != null)
            {
                foreach (var parameterXml in parametersXml.Elements("parameter"))
                {
                    result.Parameters.Add(LoadParameter(parameterXml));
                }
            }

            var errorsXml = element.Element("errors");
            if (errorsXml != null)
            {
                foreach (var errorXml in errorsXml.Elements("error"))
                {
                    result.Errors.Add(LoadError(errorXml));
                }
            }

            var eventsXml = element.Element("eventCallbacks");
            if (eventsXml != null)
            {
                foreach (var eventXml in eventsXml.Elements("eventCallback"))
                {
                    result.EventCallbacks.Add(LoadEventCallback(eventXml));
                }
            }

            return result;
        }
 public static IEnumerable<ICompanionSource> GetNonTemporalCompanions(FWAdResponse adResponse)
 {
     foreach (var adSlot in adResponse.SiteSection.AdSlots.Concat(adResponse.SiteSection.VideoPlayer.AdSlots))
     {
         foreach (var adReference in adSlot.SelectedAds)
         {
             var companionAd = adResponse.Ads.FirstOrDefault(a => a.Id == adReference.AdId);
             var companionCreatives = FreeWheelFactory.CreateCompanionAds(companionAd, adReference);
             foreach (var companionCreative in companionCreatives.Companions)
             {
                 yield return companionCreative;
             }
         }
     }
 }
        private static async Task<Ad> CreateAd(FWAdResponse adResponse, FWAdReference adReference)
        {
            var ad = adResponse.Ads.FirstOrDefault(a => a.Id == adReference.AdId);
            if (ad != null)
            {
                var linearCreative = await CreateLinearAd(ad, adReference);

                foreach (var companionAdReference in adReference.CompanionAds)
                {
                    var companionAd = adResponse.Ads.FirstOrDefault(a => a.Id == companionAdReference.AdId);
                    var companionCreative = CreateCompanionAds(companionAd, companionAdReference);
                    companionCreative.Sequence = 1;
                    linearCreative.Creatives.Add(companionCreative);
                }

                return linearCreative;
            }
            return null;
        }
        public static async Task<AdDocumentPayload> GetAdDocumentPayload(FWTemporalAdSlot adSlot, FWAdResponse adResponse, CancellationToken c)
#endif
        {
            var payload = new AdDocumentPayload();
            var adPod = new AdPod();
            payload.AdPods.Add(adPod);
            foreach (var adReference in adSlot.SelectedAds)
            {
                var ad = await CreateAd(adResponse, adReference);
                adPod.Ads.Add(ad);

                foreach (var fallbackAdReference in adReference.FallbackAds)
                {
                    var fallbackAd = await CreateAd(adResponse, fallbackAdReference);
                    ad.FallbackAds.Add(fallbackAd);
                }
            }
            return payload;
        }
        /// <summary>
        /// Creates an AdDocumentPayload from a SmartXML ad slot.
        /// </summary>
        /// <param name="adSlot">The FWTemporalAdSlot object defining the ad payload</param>
        /// <param name="adResponse">The entire SmartXML document (required for cross referencing)</param>
        /// <returns>An AdDocumentPayload object that can be played by the AdHandlerPlugin.</returns>
#if NETFX_CORE
        internal static async Task<AdDocumentPayload> GetAdDocumentPayload(FWTemporalAdSlot adSlot, FWAdResponse adResponse, CancellationToken c)
 /// <summary>
 /// Creates an AdDocumentPayload from a SmartXML ad slot.
 /// </summary>
 /// <param name="adSlot">The FWTemporalAdSlot object defining the ad payload</param>
 /// <param name="adResponse">The entire SmartXML document (required for cross referencing)</param>
 /// <returns>An AdDocumentPayload object that can be played by the AdHandlerPlugin.</returns>
 public static IAsyncOperation<AdDocumentPayload> GetAdDocumentPayload(FWTemporalAdSlot adSlot, FWAdResponse adResponse)
 {
     return AsyncInfo.Run(c => GetAdDocumentPayload(adSlot, adResponse, c));
 }
        /// <summary>
        /// Loads ads from a source URI. Note, this is called automatically if you set the source before the MediaLoading event fires and normally does not need to be called.
        /// </summary>
        /// <param name="source">The SmartXML source URI</param>
        /// <param name="c">A cancellation token that allows you to cancel a pending operation</param>
        /// <returns>A task to await on.</returns>
        public async Task LoadAds(Uri source, CancellationToken c)
        {
            adSlots.Clear();
            var cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(c, cts.Token).Token;

#if SILVERLIGHT
            adResponse = await FreeWheelFactory.LoadSource(source, cancellationToken);
#else
            adResponse = await FreeWheelFactory.LoadSource(source).AsTask(cancellationToken);
#endif

            var videoTracking = adResponse.SiteSection.VideoPlayer.VideoAsset.EventCallbacks.FirstOrDefault(ec => ec.Name == FWEventCallback.VideoView);
            if (videoTracking != null)
            {
                // use the tracking plugins to help with tracking markers. Create it if it doesn't exist.
                var positionTrackingPlugin = MediaPlayer.Plugins.OfType<PositionTrackingPlugin>().FirstOrDefault();
                if (positionTrackingPlugin == null)
                {
                    positionTrackingPlugin = new PositionTrackingPlugin();
                    MediaPlayer.Plugins.Add(positionTrackingPlugin);
                }
                positionTrackingPlugin.EventTracked += trackingPlugin_EventTracked;
                lastTrackingEvent = null; // reset
                trackingEnded = false;
                positionTrackingPlugin.TrackingEvents.Add(new PositionTrackingEvent() { PositionPercentage = 1, Data = videoTracking, Area = TrackingEventArea });

                var playTimeTrackingPlugin = MediaPlayer.Plugins.OfType<PlayTimeTrackingPlugin>().FirstOrDefault();
                if (playTimeTrackingPlugin == null)
                {
                    playTimeTrackingPlugin = new PlayTimeTrackingPlugin();
                    MediaPlayer.Plugins.Add(playTimeTrackingPlugin);
                }
                playTimeTrackingPlugin.EventTracked += trackingPlugin_EventTracked;
                for (int i = 0; i < 60; i = i + 15)
                    playTimeTrackingPlugin.TrackingEvents.Add(new PlayTimeTrackingEvent() { PlayTime = TimeSpan.FromSeconds(i), Data = videoTracking, Area = TrackingEventArea });
                for (int i = 60; i < 60 * 3; i = i + 30)
                    playTimeTrackingPlugin.TrackingEvents.Add(new PlayTimeTrackingEvent() { PlayTime = TimeSpan.FromSeconds(i), Data = videoTracking, Area = TrackingEventArea });
                for (int i = 60 * 3; i < 60 * 10; i = i + 60)
                    playTimeTrackingPlugin.TrackingEvents.Add(new PlayTimeTrackingEvent() { PlayTime = TimeSpan.FromSeconds(i), Data = videoTracking, Area = TrackingEventArea });
                for (int i = 60 * 10; i < 60 * 30; i = i + 120)
                    playTimeTrackingPlugin.TrackingEvents.Add(new PlayTimeTrackingEvent() { PlayTime = TimeSpan.FromSeconds(i), Data = videoTracking, Area = TrackingEventArea });
                for (int i = 60 * 30; i < 60 * 60; i = i + 300)
                    playTimeTrackingPlugin.TrackingEvents.Add(new PlayTimeTrackingEvent() { PlayTime = TimeSpan.FromSeconds(i), Data = videoTracking, Area = TrackingEventArea });
                for (int i = 60 * 60; i < 60 * 180; i = i + 600)
                    playTimeTrackingPlugin.TrackingEvents.Add(new PlayTimeTrackingEvent() { PlayTime = TimeSpan.FromSeconds(i), Data = videoTracking, Area = TrackingEventArea });
            }

            var videoAsset = adResponse.SiteSection.VideoPlayer.VideoAsset;
            if (videoAsset != null)
            {
                foreach (var adSlot in videoAsset.AdSlots)
                {
                    Advertisement ad = null;
                    switch (adSlot.TimePositionClass)
                    {
                        case "preroll":
                            ad = new PrerollAdvertisement();
                            break;
                        case "postroll":
                            ad = new PostrollAdvertisement();
                            break;
                        default:
                            var midroll = new MidrollAdvertisement();
                            midroll.Time = adSlot.TimePosition;
                            ad = midroll;
                            break;
                    }

#if SILVERLIGHT
                    var payload = await FreeWheelFactory.GetAdDocumentPayload(adSlot, adResponse, cancellationToken);
#else
                    var payload = await FreeWheelFactory.GetAdDocumentPayload(adSlot, adResponse).AsTask(cancellationToken);
#endif
                    ad.Source = new AdSource(payload, DocumentAdPayloadHandler.AdType);

                    Advertisements.Add(ad);
                    adSlots.Add(ad, adSlot);
                }
            }

            ShowCompanions();
        }