Пример #1
0
        /// <summary>
        /// The duration of a Region has been reached
        /// </summary>
        void TempDurationElapsedEvent()
        {
            Debug.WriteLine("Region Elapsed", "Charging - DurationElapsedEvent");

            _isExpired = true;

            // Check the other regions to see if they are also expired.
            foreach (Region temp in _regions)
            {
                if (!temp.hasExpired)
                {
                    _isExpired = false;
                }
            }

            if (_isExpired)
            {
                // Inform each region that the layout containing it has expired
                foreach (Region temp in _regions)
                {
                    temp.layoutExpired = true;
                }

                System.Diagnostics.Debug.WriteLine("Region Expired - Next Region.", "Charging - DurationElapsedEvent");
                ClientManager.Instance.Schedule.NextLayout();
            }

            App.DoEvents();
        }
Пример #2
0
 /// <summary>
 /// Web browser completed event
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void _webBrowser_DocumentCompleted(object sender, EventArgs e)
 {
     // We have navigated to the temporary file.
     Show();
     AddChild(_webBrowser);
     App.DoEvents();
 }
Пример #3
0
 public void DestroyLayout()
 {
     App.DoEvents();
     if (_regions != null)
     {
         if (_regions.Count == 0)
         {
             _regions = null;
         }
         else
         {
             for (int i = 0; i < _regions.Count; i++)
             {
                 ClientApp.Core.Region region = _regions[i];
                 region.Clear();
                 base.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => {
                     if (region != null)
                     {
                         this.MediaCanvas.Children.Remove(region);
                     }
                 }));
                 try
                 {
                     region.Dispose();
                 }
                 catch (Exception)
                 {
                 }
             }
             _regions.Clear();
             _regions = null;
         }
     }
 }
Пример #4
0
 private void TempDurationElapsedEvent()
 {
     try
     {
         this._isExpired = true;
         foreach (ClientApp.Core.Region region in this._regions)
         {
             if (!region.hasExpired)
             {
                 this._isExpired = false;
             }
         }
         if (this._isExpired)
         {
             foreach (ClientApp.Core.Region region2 in this._regions)
             {
                 region2.layoutExpired = true;
             }
             lock (Instance)
             {
             }
             lock (ScheduleLock)
                 ClientManager.Instance.Schedule.NextLayout("AdvertPlayer");
         }
         App.DoEvents();
     }
     catch (Exception)
     {
     }
 }
Пример #5
0
        public Charging()
        {
            Instance = this;
            InitializeComponent();

            // UserApp data
            Debug.WriteLine(new LogMessage("Charging Load", "User AppData Path: " + App.UserAppDataPath), LogType.Info.ToString());


            // Override the default size if necessary
            if (Settings.Default.sizeX != 0)
            {
                _clientSize = new Size((int)Settings.Default.sizeX, (int)Settings.Default.sizeY);
            }
            else
            {
                _clientSize     = new Size((int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.PrimaryScreenHeight);
                this.Visibility = Visibility.Visible;
                this.Width      = _clientSize.Width;
                this.Height     = _clientSize.Height;
            }


            // Process any stuff that has happened during the loading process
            App.DoEvents();
        }
Пример #6
0
 /// <summary>
 /// Handles the document completed event.
 /// Resets the Background color to be options.backgroundImage
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 void webBrowser_DocumentCompleted(object sender, NavigationEventArgs navigationEventArgs)
 {
     // Show the control
     Show();
     AddChild(_webBrowser);
     App.DoEvents();
 }
Пример #7
0
        void WebBrowserDocumentCompleted(object sender, NavigationEventArgs navigationEventArgs)
        {
            // We have navigated to the temporary file.
            Show();
            //     MediaCanvas.Children.Add(_webBrowser);

            App.DoEvents();
        }
Пример #8
0
        void WebBrowserDocumentCompleted(object sender, NavigationEventArgs navigationEventArgs)
        {
            base.Duration = duration;
            base.RenderMedia();

            // Get ready to show the control
            Show();
            App.DoEvents();
            AddChild(webBrowser);
        }
Пример #9
0
        /// <summary>
        /// XMDS timer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void XmdsTimerTick(object sender, EventArgs e)
        {
            // The Date/time of last XMDS is recorded - this cannot be longer that the xmdsProcessingTimeout flag
            DateTime lastXmdsSuccess  = Settings.Default.XmdsLastConnection;
            int      xmdsResetTimeout = Settings.Default.xmdsResetTimeout;

            // Work out if XMDS has been active for longer than the reset period (means its crashed)
            if (lastXmdsSuccess < (DateTime.Now.AddSeconds(-1 * xmdsResetTimeout)))
            {
                Trace.WriteLine(new LogMessage("xmdsTimer_Tick", String.Format("XMDS reset, last connection was at {0}", lastXmdsSuccess.ToString())), LogType.Error.ToString());
                _xmdsProcessing = false;
            }

            // Ticks every "collectInterval"
            if (_xmdsProcessing)
            {
                System.Diagnostics.Debug.WriteLine("Collection Timer Ticked, but previous request still active", "XmdsTicker");
                return;
            }
            else
            {
                App.DoEvents(); // Make sure everything that is queued to render does

                _xmdsProcessing = true;

                System.Diagnostics.Debug.WriteLine("Collection Timer Ticked, Firing RequiredFilesAsync");

                // Fire off a get required files event - async
                _xmds2.RequiredFilesAsync(Settings.Default.ServerKey, _hardwareKey.Key, Settings.Default.Version);
            }


            ThreadPool.QueueUserWorkItem((t) =>
            {
                try
                {
                    lock (CheckingForUpdate)
                    {
                        if (!UpdateRunning)
                        {
                            UpdateRunning = true;
                            _updater.CheckForUpdate();
                            UpdateRunning = false;
                        }
                    }
                }
                catch (Exception)
                {
                }
            });

            // Flush the log
            System.Diagnostics.Trace.Flush();
        }
Пример #10
0
        // Private Methods (8) 

        /// <summary>
        /// Disposes Layout - removes the controls
        /// </summary>
        public void DestroyLayout()
        {
            Debug.WriteLine("Destroying Layout", "AdvertPlayer - DestoryLayout");

            App.DoEvents();

            if (_regions == null)
            {
                return;
            }

            if (_regions.Count == 0)
            {
                _regions = null;
                return;
            }

            for (int i = 0; i < _regions.Count; i++)
            {
                Region region = _regions[i];
                region.Clear();

                Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
                {
                    if (region != null)
                    {
                        MediaCanvas.Children.Remove(region);
                    }
                }));


                try
                {
                    Debug.WriteLine("Calling Dispose Region", "AdvertPlayer - DestoryLayout");
                    region.Dispose();
                }
                catch (Exception e)
                {
                    //do nothing (perhaps write to some error xml somewhere?)
                    Debug.WriteLine(e.Message);
                }
            }

            _regions.Clear();
            _regions = null;
        }
Пример #11
0
 public AdvertPlayer()
 {
     Instance = this;
     this.InitializeComponent();
     if (Settings.Default.sizeX != 0M)
     {
         this._clientSize = new System.Drawing.Size((int)Settings.Default.sizeX, (int)Settings.Default.sizeY);
     }
     else
     {
         this._clientSize = new System.Drawing.Size((int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.PrimaryScreenHeight);
         base.Visibility  = Visibility.Visible;
         base.Width       = this._clientSize.Width;
         base.Height      = this._clientSize.Height;
     }
     App.DoEvents();
 }
Пример #12
0
 private void TempDurationElapsedEvent()
 {
     this._isExpired = true;
     foreach (ClientApp.Core.Region region in _regions)
     {
         if (!region.hasExpired)
         {
             this._isExpired = false;
         }
     }
     if (this._isExpired)
     {
         foreach (ClientApp.Core.Region region2 in _regions)
         {
             region2.layoutExpired = true;
         }
         ClientManager.Instance.Schedule.NextLayout("Charging");
     }
     App.DoEvents();
 }
Пример #13
0
        public void AnimateIn(Canvas Parent, Media OldOne)
        {
            if (CheckAccess())
            {
                DoubleAnimation ani = new DoubleAnimation(0.0, 1.0, new Duration(TimeSpan.FromMilliseconds(1000)));


                if (OldOne != null)
                {
                    OldOne.AnimateAway(Parent);
                    OldOne = null;
                }
                ani.Completed += delegate
                {
                    App.DoEvents();
                    Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
                    {
                        Opacity = 1.0;
                    }));
                };
                this.BeginAnimation(OpacityProperty, ani);
            }
            else
            {
                Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
                {
                    DoubleAnimation ani = new DoubleAnimation(0.0, 1.0, new Duration(TimeSpan.FromMilliseconds(250)));

                    ani.Completed += delegate
                    {
                        App.DoEvents();
                        Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
                        {
                            Opacity = 1.0;
                        }));
                    };
                    this.BeginAnimation(OpacityProperty, ani);
                }));
            }
        }
Пример #14
0
        private void XmdsTimerTick(object sender, EventArgs e)
        {
            DateTime xmdsLastConnection = Settings.Default.XmdsLastConnection;
            int      xmdsResetTimeout   = Settings.Default.xmdsResetTimeout;

            if (xmdsLastConnection < DateTime.Now.AddSeconds((double)(-1 * xmdsResetTimeout)))
            {
                Trace.WriteLine(new LogMessage("xmdsTimer_Tick", string.Format("XMDS reset, last connection was at {0}", xmdsLastConnection.ToString())), LogType.Error.ToString());
                this._xmdsProcessing = false;
            }
            if (!this._xmdsProcessing)
            {
                App.DoEvents();
                this._xmdsProcessing = true;
                if (!CollectingFiles)
                {
                    this._xmds2.RequiredFilesAsync(Settings.Default.ServerKey, this._hardwareKey.Key, Settings.Default.Version);
                }

                ThreadPool.QueueUserWorkItem(delegate(object p)
                {
                    try
                    {
                        lock (this.CheckingForUpdate)
                        {
                            if (!UpdateRunning)
                            {
                                UpdateRunning = true;
                                this._updater.CheckForUpdate();
                                UpdateRunning = false;
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                });
                Trace.Flush();
            }
        }
Пример #15
0
 private void webBrowser_DocumentCompleted(object sender, NavigationEventArgs navigationEventArgs)
 {
     base.Show();
     this.AddChild(this._webBrowser);
     App.DoEvents();
 }
Пример #16
0
        public void PrepareLayout(string layoutPath)
        {
            Action method = null;
            Action start2 = null;
            Action start3 = null;
            Action <RegionOptions> action = null;
            LayoutModel            layout;

            ClientManager.Instance.Stat            = new ClientApp.Core.Stat();
            ClientManager.Instance.Stat.FileType   = StatType.Layout;
            ClientManager.Instance.Stat.ScheduleID = ClientManager.Instance.ScheduleId;
            ClientManager.Instance.Stat.LayoutID   = this._layoutId;
            ClientManager.Instance.Stat.FromDate   = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            if ((layoutPath == (Settings.Default.LibraryPath + @"\Default.xml")) || string.IsNullOrEmpty(layoutPath))
            {
                throw new Exception("Default layout");
            }
            try
            {
                using (FileStream stream = File.Open(layoutPath, FileMode.Open, FileAccess.Read, FileShare.Write))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(LayoutModel));
                    layout = (LayoutModel)serializer.Deserialize(stream);
                }
            }
            catch (Exception exception)
            {
                Trace.WriteLine(string.Format("Could not find the layout file {0}: {1}", layoutPath, exception.Message));
                throw;
            }
            this._layoutWidth  = layout.Width;
            this._layoutHeight = layout.Height;
            int width  = this._clientSize.Width;
            int height = this._clientSize.Height;

            this._regions = new Collection <ClientApp.Core.Region>();
            RegionOptions options = new RegionOptions();

            try
            {
                if (!string.IsNullOrEmpty(layout.Bgcolor))
                {
                    if (method == null)
                    {
                        method = new Action(() =>
                        {
                            this.MediaCanvas.Background = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(layout.Bgcolor));
                        });
                    }
                    base.Dispatcher.BeginInvoke(DispatcherPriority.Normal, method);
                    options.backgroundColor = layout.Bgcolor;
                }
            }
            catch
            {
                if (start2 == null)
                {
                    start2 = new Action(() =>
                    {
                        this.MediaCanvas.Background = new SolidColorBrush(Colors.Black);
                    });
                }
                base.Dispatcher.BeginInvoke(DispatcherPriority.Normal, start2);
                options.backgroundColor = "#000000";
            }
            try
            {
                if (layout.Background == null)
                {
                    this.MediaCanvas.Background = null;
                    options.backgroundImage     = "";
                }
                else
                {
                    string bgFilePath = string.Concat(new object[] { Settings.Default.LibraryPath, @"\backgrounds\", width, "x", height, "_", layout.Background });
                    Utilities.CreateFolder(Path.GetDirectoryName(bgFilePath));
                    if (!File.Exists(bgFilePath))
                    {
                        System.Drawing.Image original   = System.Drawing.Image.FromFile(Settings.Default.LibraryPath + @"\" + layout.Background);
                        Bitmap            bitmap        = new Bitmap(original, width, height);
                        EncoderParameters encoderParams = new EncoderParameters(1);
                        EncoderParameter  parameter     = new EncoderParameter(Encoder.Quality, 90L);
                        encoderParams.Param[0] = parameter;
                        ImageCodecInfo encoderInfo = GetEncoderInfo("image/jpeg");
                        bitmap.Save(bgFilePath, encoderInfo, encoderParams);
                        original.Dispose();
                        bitmap.Dispose();
                    }
                    base.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
                    {
                        this.MediaCanvas.Background = new ImageBrush(new BitmapImage(new Uri(bgFilePath.Replace(@"\", "/"), UriKind.Relative)));
                    }));
                    options.backgroundImage = bgFilePath;
                }
            }
            catch (Exception)
            {
                if (start3 == null)
                {
                    start3 = new Action(() =>
                    {
                        this.MediaCanvas.Background = System.Windows.Media.Brushes.Black;
                    });
                }
                base.Dispatcher.BeginInvoke(DispatcherPriority.Normal, start3);
                options.backgroundImage = "";
            }
            App.DoEvents();
            List <LayoutRegion> regions            = layout.Regions;
            List <List <LayoutRegionMedia> > list2 = (from r in layout.Regions select r.Media).ToList <List <LayoutRegionMedia> >();

            if ((regions.Count == 0) || (list2.Count == 0))
            {
                Trace.WriteLine(new LogMessage("PrepareLayout", string.Format("A layout with {0} regions and {1} media has been detected.", regions.Count.ToString(), list2.Count.ToString())), LogType.Info.ToString());
                if (ClientManager.Instance.Schedule.ActiveLayouts == 1)
                {
                    Trace.WriteLine(new LogMessage("PrepareLayout", "Only 1 layout scheduled and it has nothing to show."), LogType.Info.ToString());
                    throw new Exception("Only 1 layout schduled and it has nothing to show");
                }
                Trace.WriteLine(new LogMessage("PrepareLayout", string.Format(string.Format("An empty layout detected, will show for {0} seconds.", Settings.Default.emptyLayoutDuration.ToString()), new object[0])), LogType.Info.ToString());
                List <LayoutRegion> list3  = new List <LayoutRegion>();
                LayoutRegion        region = new LayoutRegion
                {
                    Id     = "blah",
                    Width  = 1,
                    Height = 1,
                    Top    = 1,
                    Left   = 1
                };
                List <LayoutRegionMedia> list4 = new List <LayoutRegionMedia>();
                LayoutRegionMedia        media = new LayoutRegionMedia
                {
                    Id       = "blah",
                    Type     = "Text",
                    Duration = 0
                };
                LayoutRegionMediaRaw raw = new LayoutRegionMediaRaw
                {
                    Text = ""
                };
                media.Raw = raw;
                list4.Add(media);
                region.Media = list4;
                list3.Add(region);
                regions = list3;
            }
            else
            {// Keep Running region, preventing visual blank out;
                regions.Add(
                    new LayoutRegion()
                {
                    Height = 0, Width = 0, Name = "Keep Alive Region", Media = new List <LayoutRegionMedia>()
                    {
                        new LayoutRegionMedia()
                        {
                            Duration = (int)TimeSpan.FromDays(10).TotalMilliseconds,
                            Type     = "KeepAlive"
                        }
                    }
                });
            }

            foreach (LayoutRegion region2 in regions)
            {
                if (region2.Media.Count != 0)
                {
                    options.scheduleId = ClientManager.Instance.ScheduleId;
                    options.layoutId   = this._layoutId;
                    options.regionId   = region2.Id;
                    options.Width      = (int)((((double)(region2.Width + 14)) / this._layoutWidth) * this._clientSize.Width);
                    options.Height     = (int)((((double)(region2.Height + 14)) / this._layoutHeight) * this._clientSize.Height);
                    int left = region2.Left;
                    if (left < 0)
                    {
                        left = 0;
                    }
                    int top = region2.Top;
                    if (top < 0)
                    {
                        top = 0;
                    }
                    options.Left           = (int)((((double)left) / this._layoutWidth) * this._clientSize.Width);
                    options.Top            = (int)((((double)top) / this._layoutHeight) * this._clientSize.Height);
                    options.ScaleFactor    = this._scaleFactor;
                    options.BackgroundLeft = options.Left * -1;
                    options.BackgroundTop  = options.Top * -1;
                    options.mediaNodes     = region2.Media;
                    if (action == null)
                    {
                        action = delegate(RegionOptions opts)
                        {
                            Core.Region region = new ClientApp.Core.Region(ClientManager.Instance.StatLog, ClientManager.Instance.CacheManager);
                            region.DurationElapsedEvent += new ClientApp.Core.Region.DurationElapsedDelegate(this.TempDurationElapsedEvent);
                            if (opts.FileType != "Widget")
                            {
                                region.RegionOptions = opts;
                                this._regions.Add(region);
                                region.Opacity = 0.0;
                                this.MediaCanvas.Children.Add(region);
                                region.AnimateIn();
                            }
                            else if (!WidgetsFactory.Widgets.ContainsKey(opts.Name))
                            {
                                region.RegionOptions = opts;
                                region.Opacity       = 0.0;
                                this.MediaCanvas.Children.Add(region);
                                region.AnimateIn();
                            }
                        };
                    }
                    base.Dispatcher.BeginInvoke(DispatcherPriority.Normal, action, options);
                    App.DoEvents();
                }
            }
            regions = null;
            list2   = null;
        }
Пример #17
0
 private void _webBrowser_DocumentCompleted(object sender, EventArgs e)
 {
     base.Show();
     this.AddChild(this._webBrowser);
     App.DoEvents();
 }
Пример #18
0
        public void AnimateAway(Canvas Parent)
        {
            if (CheckAccess())
            {
                DoubleAnimation ani = new DoubleAnimation(1.0, 0.0, new Duration(TimeSpan.FromMilliseconds(1550)));

                ani.Completed += delegate
                {
                    App.DoEvents();
                    Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
                    {
                        this.Hide
                            ();
                        // Remove the controls
                        Parent
                        .
                        Children
                        .
                        Remove
                            (this);
                        this
                        .
                        Dispose
                            ();

                        //            RemoveVisualChild();
                    }));
                };
                this.BeginAnimation(OpacityProperty, ani);
            }
            else
            {
                Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
                {
                    DoubleAnimation ani = new DoubleAnimation(1.0, 0.0, new Duration(TimeSpan.FromMilliseconds(250)));

                    ani.Completed += delegate
                    {
                        App.DoEvents();
                        Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
                        {
                            this.Hide
                                ();
                            // Remove the controls
                            Parent
                            .
                            Children
                            .
                            Remove
                                (this);
                            this
                            .
                            Dispose
                                ();

                            //            RemoveVisualChild();
                        }));
                    };
                    this.BeginAnimation(OpacityProperty, ani);
                }));
            }
        }
Пример #19
0
        /// <summary>
        /// Prepares the Layout.. rendering all the necessary controls
        /// </summary>
        public void PrepareLayout(string layoutPath)
        {
            // Create a start record for this layout
            //  ClientManager.Instance.Stat = new Stat();
            // ClientManager.Instance.Stat.FileType = StatType.Layout;
            //   ClientManager.Instance.Stat.ScheduleID = ClientManager.Instance.ScheduleId;
            //    ClientManager.Instance.Stat.LayoutID = _layoutId;
            //   ClientManager.Instance.Stat.FromDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            LayoutModel layout;

            // Default or not
            if (layoutPath == Settings.Default.LibraryPath + @"\Default.xml" || String.IsNullOrEmpty(layoutPath))
            {
                throw new Exception("Default layout");
            }
            else
            {
                try
                {
                    // Get this layouts XML
                    using (var file = File.Open(layoutPath, FileMode.Open, FileAccess.Read, FileShare.Write))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(LayoutModel));
                        layout = (LayoutModel)serializer.Deserialize(file);
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("Could not find the layout file {0}: {1}", layoutPath, ex.Message));
                    throw;
                }
            }

            // Attributes of the main layout node



            // Set the background and size of the form
            _layoutWidth  = layout.Width;
            _layoutHeight = layout.Height;


            //// Scaling factor, will be applied to all regions
            //_scaleFactor = Math.Max(_clientSize.Width / _layoutWidth, _clientSize.Height / _layoutHeight);

            //// Want to be able to center this shiv - therefore work out which one of these is going to have left overs
            int backgroundWidth  = _clientSize.Width;  // (int)(_layoutWidth * _scaleFactor);
            int backgroundHeight = _clientSize.Height; //(int)(_layoutHeight * _scaleFactor);

            //double leftOverX;
            //double leftOverY;

            //try
            //{
            //    leftOverX = Math.Abs(_clientSize.Width - backgroundWidth);
            //    leftOverY = Math.Abs(_clientSize.Height - backgroundHeight);

            //    if (leftOverX != 0) leftOverX = leftOverX / 2;
            //    if (leftOverY != 0) leftOverY = leftOverY / 2;
            //}
            //catch
            //{
            //    leftOverX = 0;
            //    leftOverY = 0;
            //}


            // New region and region options objects
            _regions = new Collection <Region>();
            RegionOptions options = new RegionOptions();

            // Deal with the color
            try
            {
                if (!String.IsNullOrEmpty(layout.Bgcolor))
                {
                    Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
                    {
                        MediaCanvas.Background =
                            new SolidColorBrush((Color)ColorConverter.ConvertFromString(layout.Bgcolor));
                    }));
                    options.backgroundColor = layout.Bgcolor;
                }
            }
            catch
            {
                Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
                {
                    MediaCanvas.Background = new SolidColorBrush(Colors.Black); // Default black
                }));


                options.backgroundColor = "#000000";
            }

            // Get the background
            try
            {
                if (layout.Background == null)
                {
                    // Assume there is no background image
                    MediaCanvas.Background  = null;
                    options.backgroundImage = "";
                }
                else
                {
                    string bgFilePath = Settings.Default.LibraryPath + @"\backgrounds\" + backgroundWidth + "x" + backgroundHeight + "_" + layout.Background;
                    Utilities.CreateFolder(Path.GetDirectoryName(bgFilePath));
                    // Create a correctly sized background image in the temp folder
                    if (!File.Exists(bgFilePath))
                    {
                        System.Drawing.Image img = System.Drawing.Image.FromFile(Settings.Default.LibraryPath + @"\" + layout.Background);

                        Bitmap            bmp = new Bitmap(img, backgroundWidth, backgroundHeight);
                        EncoderParameters encoderParameters = new EncoderParameters(1);
                        EncoderParameter  qualityParam      = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);
                        encoderParameters.Param[0] = qualityParam;

                        ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

                        bmp.Save(bgFilePath, jpegCodec, encoderParameters);

                        img.Dispose();
                        bmp.Dispose();
                    }

                    Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
                    {
                        MediaCanvas.Background = new ImageBrush(new BitmapImage(new Uri(bgFilePath.Replace("\\", "/"), UriKind.Relative)));
                    }));

                    options.backgroundImage = bgFilePath;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Unable to set background: " + ex.Message);

                // Assume there is no background image
                Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
                {
                    MediaCanvas.Background = Brushes.Black;
                }));

                options.backgroundImage = "";
            }

            // Get it to paint the background now
            App.DoEvents();

            // Get the regions
            var listRegions = layout.Regions;
            var listMedia   = layout.Regions.Select(r => r.Media).ToList();

            // Check to see if there are any regions on this layout.
            if (listRegions.Count == 0 || listMedia.Count == 0)
            {
                Trace.WriteLine(new LogMessage("PrepareLayout",
                                               string.Format("A layout with {0} regions and {1} media has been detected.", listRegions.Count.ToString(), listMedia.Count.ToString())),
                                LogType.Info.ToString());

                if (ClientManager.Instance.Schedule.ActiveLayouts == 1)
                {
                    Trace.WriteLine(new LogMessage("PrepareLayout", "Only 1 layout scheduled and it has nothing to show."), LogType.Info.ToString());

                    throw new Exception("Only 1 layout schduled and it has nothing to show");
                }
                else
                {
                    Trace.WriteLine(new LogMessage("PrepareLayout",
                                                   string.Format(string.Format("An empty layout detected, will show for {0} seconds.", Settings.Default.emptyLayoutDuration.ToString()))), LogType.Info.ToString());

                    // Put a small dummy region in place, with a small dummy media node - which expires in 10 seconds.
                    // Replace the list of regions (they mean nothing as they are empty)
                    listRegions = new List <LayoutRegion>()
                    {
                        new LayoutRegion()
                        {
                            Id    = "blah", Width = 1, Height = 1, Top = 1, Left = 1,
                            Media = new List <LayoutRegionMedia>()
                            {
                                new LayoutRegionMedia()
                                {
                                    Id       = "blah",
                                    Type     = "Text",
                                    Duration = 0,
                                    Raw      = new LayoutRegionMediaRaw()
                                    {
                                        Text = ""
                                    }
                                }
                            }
                        }
                    };
                }
            }

            foreach (var region in listRegions)
            {
                // Is there any media
                if (region.Media.Count == 0)
                {
                    if (region.Type != "Widget")
                    {
                        Debug.WriteLine("A region with no media detected");
                        continue;
                    }
                }

                //each region
                options.scheduleId = ClientManager.Instance.ScheduleId;
                options.layoutId   = _layoutId;
                options.regionId   = region.Id;
                options.Name       = region.Name;
                options.FileType   = region.Type;
                options.Width      = (int)((region.Width + 30.0) / _layoutWidth * _clientSize.Width);  //(int)((region.Width + 15.0) * _scaleFactor);
                options.Height     = (int)((region.Height + 30) / _layoutHeight * _clientSize.Height); //(int)((region.Height + 15.0) * _scaleFactor);
                var left = region.Left - 15;
                if (left < 0)
                {
                    left = 0;
                }

                var top = region.Top - 15;
                if (top < 0)
                {
                    top = 0;
                }

                options.Left = (int)(left / _layoutWidth * _clientSize.Width);  //(int)(region.Left * _scaleFactor);
                options.Top  = (int)(top / _layoutHeight * _clientSize.Height); //(int)(region.Top * _scaleFactor);

                options.ScaleFactor = _scaleFactor;

                // Set the backgrounds (used for Web content offsets)
                options.BackgroundLeft = options.Left * -1;
                options.BackgroundTop  = options.Top * -1;

                //Account for scaling
                //       options.Left = options.Left + (int)leftOverX;
                //        options.Top = options.Top + (int)leftOverY;

                // All the media nodes for this region / layout combination
                options.mediaNodes = region.Media;

                Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action <RegionOptions>(
                                           (opts) =>
                {
                    Region temp = new Region(ClientManager.Instance.StatLog, ClientManager.Instance.CacheManager);
                    temp.DurationElapsedEvent += new Region.DurationElapsedDelegate(TempDurationElapsedEvent);

                    Debug.WriteLine("Created new region", "Charging Player - Prepare Layout");

                    // Dont be fooled, this innocent little statement kicks everything off
                    temp.RegionOptions = opts;

                    _regions.Add(temp);

                    temp.Opacity = 0;

                    MediaCanvas.Children.Add(temp);

                    temp.AnimateIn();

                    //          new TextBox(){
                    //Text                                                                        = "Hey",
                    //                                                                          Margin = new Thickness(options.left,options.top,0,0),
                    //                                                                          Height = options.Height,
                    //                                                                          Width = options.Width
                    //                                                                        })
                    ;
                    //   temp.Background = new SolidColorBrush(Colors.Coral);
                }), options);


                Debug.WriteLine("Adding region", "Charging - Prepare Layout");


                App.DoEvents();
            }

            // Null stuff
            listRegions = null;
            listMedia   = null;
        }