// Ensure that the viewfinder is upright in LandscapeRight.
        private void CorrectViewfinderOrientation(PageOrientation orientation)
        {
            if (cam != null)
            {
                
                double ang;

                // LandscapeRight rotation when camera is on back of phone.
                int landscapeRightRotation = 180;
                int portraitRotation = 90;

                // Change LandscapeRight rotation for front-facing camera.
                if (cam.SensorLocation == CameraSensorLocation.Front)
                {
                    portraitRotation = -90;
                    landscapeRightRotation = -180;
                }
                
                // Rotate video brush from camera.
                if (orientation == PageOrientation.PortraitUp || orientation == PageOrientation.PortraitDown)
                {
                    ang = portraitRotation;
                }
                else if (orientation == PageOrientation.LandscapeRight)
                {
                    ang = landscapeRightRotation;
                }
                else
                {
                    ang = 0;
                }
                
                var tf = new CompositeTransform() { Rotation = ang };
                var previewSize = tf.TransformBounds(new System.Windows.Rect(new System.Windows.Point(), new System.Windows.Size(cam.PreviewResolution.Width, cam.PreviewResolution.Height)));
                double s1 = Viewfinder.ActualWidth / (double)previewSize.Width;
                double s2 = Viewfinder.ActualHeight / (double)previewSize.Height;

                double scale = Math.Min(s1, s2);
                if (cam.SensorLocation == CameraSensorLocation.Back)
                {
                    ViewfinderBrush.Transform = new CompositeTransform()
                    {
                        Rotation = ang,
                        CenterX = Viewfinder.ActualWidth / 2,
                        CenterY = Viewfinder.ActualHeight / 2,
                        ScaleX = scale,
                        ScaleY = scale
                    };
                }
                else
                {
                    double scaleY = scale;
                    double scaleX = scale;
                    if ((orientation & PageOrientation.Portrait) == PageOrientation.Portrait)
                    {
                        scaleY = scale * -1;
                    }
                    else
                    {
                        scaleX = scale * -1;
                    }

                    ViewfinderBrush.Transform = new CompositeTransform()
                    {
                        Rotation = ang,
                        CenterX = Viewfinder.ActualWidth / 2,
                        CenterY = Viewfinder.ActualHeight / 2,
                        ScaleX = scaleX,
                        ScaleY = scaleY
                    };
                }
            }
        }