/// <summary>
        /// The Page_Load event handler on this Page is used to
        /// obtain obtain the contents of a picture from the
        /// Pictures table, construct an HTTP Response of the
        /// correct type for the picture, and then stream the
        /// picture contents to the response.  It uses the
        /// Appleseed.PictureDB() data component to encapsulate
        /// the data access functionality.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack && ModuleID > 0 && ItemID > 0)
            {
                // Obtain a single row of picture information
                PicturesDB pictures = new PicturesDB();
                WorkFlowVersion version = Request.QueryString["wversion"] == "Staging"
                                              ? WorkFlowVersion.Staging
                                              : WorkFlowVersion.Production;
                SqlDataReader dr = pictures.GetSinglePicture(ItemID, version);

                PictureItem pictureItem;
                XmlDocument metadata = new XmlDocument();

                try
                {
                    // Read first row from database
                    if (dr.Read())
                    {
                        pictureItem =
                            (PictureItem)
                            Page.LoadControl(Path.ApplicationRoot + "/Design/PictureLayouts/" +
                                             this.ModuleSettings["ImageLayout"]);

                        metadata.LoadXml((string) dr["MetadataXml"]);

                        XmlAttribute albumPath = metadata.CreateAttribute("AlbumPath");
                        albumPath.Value = ((SettingItem<string, TextBox>) this.ModuleSettings["AlbumPath"]).FullPath;

                        XmlAttribute itemID = metadata.CreateAttribute("ItemID");
                        itemID.Value = ((int) dr["ItemID"]).ToString();

                        XmlAttribute moduleID = metadata.CreateAttribute("ModuleID");
                        moduleID.Value = ModuleID.ToString();

                        XmlAttribute wVersion = metadata.CreateAttribute("WVersion");
                        wVersion.Value = version.ToString();

                        if (dr["PreviousItemID"] != DBNull.Value)
                        {
                            XmlAttribute previousItemID = metadata.CreateAttribute("PreviousItemID");
                            previousItemID.Value = ((int) dr["PreviousItemID"]).ToString();
                            metadata.DocumentElement.Attributes.Append(previousItemID);
                        }

                        if (dr["NextItemID"] != DBNull.Value)
                        {
                            XmlAttribute nextItemID = metadata.CreateAttribute("NextItemID");
                            nextItemID.Value = ((int) dr["NextItemID"]).ToString();
                            metadata.DocumentElement.Attributes.Append(nextItemID);
                        }

                        metadata.DocumentElement.Attributes.Append(albumPath);
                        metadata.DocumentElement.Attributes.Append(itemID);
                        metadata.DocumentElement.Attributes.Append(moduleID);
                        metadata.DocumentElement.Attributes.Append(wVersion);

                        if (version == WorkFlowVersion.Production)
                        {
                            XmlNode modifiedFilenameNode =
                                metadata.DocumentElement.SelectSingleNode("@ModifiedFilename");
                            XmlNode thumbnailFilenameNode =
                                metadata.DocumentElement.SelectSingleNode("@ThumbnailFilename");

                            modifiedFilenameNode.Value = modifiedFilenameNode.Value.Replace(".jpg", ".Production.jpg");
                            thumbnailFilenameNode.Value = thumbnailFilenameNode.Value.Replace(".jpg", ".Production.jpg");
                        }

                        pictureItem.Metadata = metadata;
                        pictureItem.DataBind();

                        Picture.Controls.Add(pictureItem);
                    }
                }
                catch
                {
                    lblError.Visible = true;
                    Picture.Visible = false;
                    return;
                }
                finally
                {
                    // Close datareader
                    dr.Close();
                }

                DataBind();
            }
        }
        /// <summary>
        /// The Binddata method on this User Control is used to
        ///     obtain a DataReader of picture information from the Pictures
        ///     table, and then databind the results to a templated DataList
        ///     server control. It uses the Appleseed.PictureDB()
        ///     data component to encapsulate all data functionality.
        /// </summary>
        /// <param name="page">
        /// The page.
        /// </param>
        private void BindData(int page)
        {
            var pictures = new PicturesDB();
            var dsPictures = pictures.GetPicturesPaged(
                this.ModuleID, page, Int32.Parse(this.Settings["PicturesPerPage"].ToString()), this.Version);

            if (dsPictures.Tables.Count > 0 && dsPictures.Tables[0].Rows.Count > 0)
            {
                this.pgPictures.RecordCount = (int)dsPictures.Tables[0].Rows[0]["RecordCount"];
            }

            this.dlPictures.DataSource = dsPictures;
            this.dlPictures.DataBind();
        }
        protected override void OnUpdate(EventArgs e)
        {
            base.OnUpdate(e);

            // Only Update if Entered data is Valid
            if (Page.IsValid == true)
            {
                // Create an instance of Esperantus.Esperantus.Localize. PicturesDB component
                PicturesDB pictures = new PicturesDB();
                Bitmap fullPicture = null;

                //Get Esperantus.Esperantus.Localize. resize option for Esperantus.Esperantus.Localize. thumbnail
                Pictures.ResizeOption thumbnailResize =
                    this.ModuleSettings["ThumbnailResize"].Value.ToString() == string.Empty
                        ?
                    Pictures.ResizeOption.FixedWidthHeight
                        :
                    (Pictures.ResizeOption)Enum.Parse(typeof(Pictures.ResizeOption), this.ModuleSettings["ThumbnailResize"].Value.ToString());

                //Get Esperantus.Esperantus.Localize. resize option for Esperantus.Esperantus.Localize. original picture
                Pictures.ResizeOption originalResize =
                    this.ModuleSettings["OriginalResize"].Value.ToString() == string.Empty
                        ?
                    Pictures.ResizeOption.NoResize
                        :
                    (Pictures.ResizeOption)Enum.Parse(typeof(Pictures.ResizeOption), this.ModuleSettings["OriginalResize"].Value.ToString());

                //Where are we going to save Esperantus.Esperantus.Localize. picture?
                string PathToSave = string.Format("{0}\\", this.Server.MapPath(this.ModuleSettings["AlbumPath"].FullPath));

                //Dimensions of Esperantus.Esperantus.Localize. thumbnail as specified in settings
                int thumbnailWidth = (int)this.ModuleSettings["ThumbnailWidth"].Value;
                int thumbnailHeight = (int)this.ModuleSettings["ThumbnailHeight"].Value;

                //Dimensions of Esperantus.Esperantus.Localize. original picture as specified in settings
                int originalWidth = (int)this.ModuleSettings["OriginalWidth"].Value;
                int originalHeight = (int)this.ModuleSettings["OriginalHeight"].Value;

                // See if Esperantus.Esperantus.Localize.y are doing a bulk load.  Esperantus.Esperantus.Localize.y must have specified
                // a bulk load directory (which is on Esperantus.Esperantus.Localize. server) and Esperantus.Esperantus.Localize.y must not
                // have specified a specific upload file name, and Esperantus.Esperantus.Localize.y must not be
                // editing an item.
                if (ItemID == 0 && flPicture.PostedFile.FileName == string.Empty &&
                    BulkDir.Text != string.Empty)
                {
                    // Esperantus.Esperantus.Localize.y are bulk loading - run through Esperantus.Esperantus.Localize. specified directory and
                    // insert all .JPG files into Esperantus.Esperantus.Localize. database.  User is expected to
                    // provide a FULL file path on Esperantus.Esperantus.Localize. SERVER.
                    string[] files = Directory.GetFiles(BulkDir.Text, "*.jpg");

                    foreach (string file in files)
                    {
                        MetadataXml = null;

                        // Create a new FileInfo object for this filename
                        FileInfo fileInfo = new FileInfo(file);

                        //Create new filenames for Esperantus.Esperantus.Localize. thumbnail and Esperantus.Esperantus.Localize. original picture
                        ModifiedFilename = ModuleID.ToString() + "m" + Guid.NewGuid().ToString() + ".jpg";
                        SetMetadata("ModifiedFilename", ModifiedFilename);

                        ThumbnailFilename = ModuleID.ToString() + "m" + Guid.NewGuid().ToString() + ".jpg";
                        SetMetadata("ThumbnailFilename", ThumbnailFilename);

                        //Full path of Esperantus.Esperantus.Localize. original picture
                        string physicalPath = PathToSave + ModifiedFilename;

                        //Make sure Esperantus.Esperantus.Localize. picture target directory exists
                        Directory.CreateDirectory(PathToSave);

                        SetMetadata("OriginalFilename", fileInfo.FullName);

                        try
                        {
                            //Create a bitmap from Esperantus.Esperantus.Localize. saved picture
                            fullPicture = new Bitmap(fileInfo.FullName);
                        }
                        catch (Exception ex)
                        {
                            Message.Text =
                                General.GetString("PICTURES_INVALID_IMAGE_FILE", "Invalid Image File", this) + "!<br>" +
                                ex.Message;
                            return;
                        }

                        SetMetadata("OriginalWidth", fullPicture.Width.ToString());
                        SetMetadata("OriginalHeight", fullPicture.Height.ToString());

                        if (chkIncludeExif.Checked) SetExifInformation(fullPicture);

                        RotateFlip(fullPicture, selFlip.SelectedItem.Value, selRotate.SelectedItem.Value);

                        try
                        {
                            //Resize Esperantus.Esperantus.Localize. original picture with Esperantus.Esperantus.Localize. given settings to create Esperantus.Esperantus.Localize. thumbnail
                            Bitmap thumbnail =
                                ResizeImage(fullPicture, thumbnailWidth, thumbnailHeight, thumbnailResize);
                            thumbnail.Save(PathToSave + ThumbnailFilename, ImageFormat.Jpeg);
                            SetMetadata("ThumbnailWidth", thumbnail.Width.ToString());
                            SetMetadata("ThumbnailHeight", thumbnail.Height.ToString());
                            thumbnail.Dispose();
                        }
                        catch (Exception ex)
                        {
                            Message.Text =
                                General.GetString("PICTURES_THUMBNAIL_ERROR",
                                                  "Error occured while creating Esperantus.Esperantus.Localize. thumbnail",
                                                  this) + "!<br>" + ex.Message;
                            return;
                        }

                        Bitmap modified = null;

                        try
                        {
                            //Resize original image
                            modified = ResizeImage(fullPicture, originalWidth, originalHeight, originalResize);
                        }
                        catch (Exception ex)
                        {
                            Message.Text =
                                General.GetString("PICTURES_RESIZE_ERROR",
                                                  "Error occured while resizing Esperantus.Esperantus.Localize. image",
                                                  this) + "!<br>" + ex.Message;
                            return;
                        }

                        SetMetadata("ModifiedWidth", modified.Width.ToString());
                        SetMetadata("ModifiedHeight", modified.Height.ToString());

                        fullPicture.Dispose();

                        //Save Esperantus.Esperantus.Localize. resized one
                        modified.Save(physicalPath, ImageFormat.Jpeg);
                        modified.Dispose();

                        FileInfo fi = new FileInfo(physicalPath);
                        SetMetadata("ModifiedFileSize", fi.Length.ToString());

                        int displayOrder = 0;

                        try
                        {
                            displayOrder = Int32.Parse(DisplayOrder.Text);
                        }
                        catch
                        {
                        }

                        SetMetadata("ShortDescription", ShortDescription.Text);
                        SetMetadata("LongDescription", LongDescription.Text);
                        SetMetadata("Caption", Caption.Text);
                        SetMetadata("Keywords", Keywords.Text);
                        SetMetadata("UploadDate", DateTime.Now.ToString());
                        SetMetadata("CreatedBy", PortalSettings.CurrentUser.Identity.UserName);
                        SetMetadata("DisplayOrder", displayOrder.ToString());

                        //Add new picture to Esperantus.Esperantus.Localize. database
                        ItemID =
                            pictures.AddPicture(ModuleID, ItemID, displayOrder, MetadataXml, ShortDescription.Text,
                                                Keywords.Text, PortalSettings.CurrentUser.Identity.UserName, DateTime.Now);
                    }
                }
                else
                {
                    // Determine wheEsperantus.Esperantus.Localize.r a file was uploaded
                    if (flPicture.PostedFile.FileName.Length != 0)
                    {
                        //Create new filenames for Esperantus.Esperantus.Localize. thumbnail and Esperantus.Esperantus.Localize. original picture
                        ModifiedFilename = ModuleID.ToString() + "m" + Guid.NewGuid().ToString() + ".jpg";
                        SetMetadata("ModifiedFilename", ModifiedFilename);

                        ThumbnailFilename = ModuleID.ToString() + "m" + Guid.NewGuid().ToString() + ".jpg";
                        SetMetadata("ThumbnailFilename", ThumbnailFilename);

                        //Full path of Esperantus.Esperantus.Localize. original picture
                        string physicalPath = PathToSave + ModifiedFilename;

                        try
                        {
                            // Save Esperantus.Esperantus.Localize. picture
                            flPicture.PostedFile.SaveAs(physicalPath);
                        }
                        catch (DirectoryNotFoundException ex)
                        {
                            // If Esperantus.Esperantus.Localize. directory is not found, create and Esperantus.Esperantus.Localize.n save
                            Directory.CreateDirectory(PathToSave);
                            flPicture.PostedFile.SaveAs(physicalPath);

                            //This line is here to supress Esperantus.Esperantus.Localize. warning
                            ex.ToString();
                        }
                        catch (Exception ex)
                        {
                            // If oEsperantus.Esperantus.Localize.r error occured report to Esperantus.Esperantus.Localize. user
                            Message.Text = General.GetString("PICTURES_INVALID_FILENAME", "Invalid Filename", this) +
                                           "!<br>" + ex.Message;
                            return;
                        }

                        SetMetadata("OriginalFilename", flPicture.PostedFile.FileName);

                        try
                        {
                            //Create a bitmap from Esperantus.Esperantus.Localize. saved picture
                            fullPicture = new Bitmap(physicalPath);
                        }
                        catch (Exception ex)
                        {
                            Message.Text =
                                General.GetString("PICTURES_INVALID_IMAGE_FILE", "Invalid Image File", this) + "!<br>" +
                                ex.Message;
                            return;
                        }

                        SetMetadata("OriginalWidth", fullPicture.Width.ToString());
                        SetMetadata("OriginalHeight", fullPicture.Height.ToString());

                        if (chkIncludeExif.Checked) SetExifInformation(fullPicture);

                        RotateFlip(fullPicture, selFlip.SelectedItem.Value, selRotate.SelectedItem.Value);

                        try
                        {
                            //Resize Esperantus.Esperantus.Localize. original picture with Esperantus.Esperantus.Localize. given settings to create Esperantus.Esperantus.Localize. thumbnail
                            Bitmap thumbnail =
                                ResizeImage(fullPicture, thumbnailWidth, thumbnailHeight, thumbnailResize);
                            thumbnail.Save(PathToSave + ThumbnailFilename, ImageFormat.Jpeg);
                            SetMetadata("ThumbnailWidth", thumbnail.Width.ToString());
                            SetMetadata("ThumbnailHeight", thumbnail.Height.ToString());
                            thumbnail.Dispose();
                        }
                        catch (Exception ex)
                        {
                            Message.Text =
                                General.GetString("PICTURES_THUMBNAIL_ERROR",
                                                  "Error occured while creating Esperantus.Esperantus.Localize. thumbnail",
                                                  this) + "!<br>" + ex.Message;
                            return;
                        }

                        Bitmap modified = null;

                        try
                        {
                            //Resize original image
                            modified = ResizeImage(fullPicture, originalWidth, originalHeight, originalResize);
                        }
                        catch (Exception ex)
                        {
                            Message.Text =
                                General.GetString("PICTURES_RESIZE_ERROR",
                                                  "Error occured while resizing Esperantus.Esperantus.Localize. image",
                                                  this) + "!<br>" + ex.Message;
                            return;
                        }

                        SetMetadata("ModifiedWidth", modified.Width.ToString());
                        SetMetadata("ModifiedHeight", modified.Height.ToString());

                        fullPicture.Dispose();

                        //Delete Esperantus.Esperantus.Localize. original
                        File.Delete(physicalPath);

                        //Save Esperantus.Esperantus.Localize. resized one
                        modified.Save(physicalPath, ImageFormat.Jpeg);
                        modified.Dispose();

                        FileInfo fi = new FileInfo(physicalPath);
                        SetMetadata("ModifiedFileSize", fi.Length.ToString());
                    }
                    else if (ItemID == 0)
                    {
                        Message.Text =
                            General.GetString("PICTURES_SPECIFY_FILENAME", "Please specify a filename", this) + "!<br>";
                        return;
                    }

                    int displayOrder = 0;

                    try
                    {
                        displayOrder = Int32.Parse(DisplayOrder.Text);
                    }
                    catch
                    {
                    }

                    SetMetadata("ShortDescription", ShortDescription.Text);
                    SetMetadata("LongDescription", LongDescription.Text);
                    SetMetadata("Caption", Caption.Text);
                    SetMetadata("Keywords", Keywords.Text);
                    SetMetadata("UploadDate", DateTime.Now.ToString());
                    SetMetadata("CreatedBy", PortalSettings.CurrentUser.Identity.UserName);
                    SetMetadata("DisplayOrder", displayOrder.ToString());

                    if (ItemID == 0)
                    {
                        //If this is a new picture add it to Esperantus.Esperantus.Localize. database
                        ItemID =
                            pictures.AddPicture(ModuleID, ItemID, displayOrder, MetadataXml, ShortDescription.Text,
                                                Keywords.Text, PortalSettings.CurrentUser.Identity.UserName, DateTime.Now);
                    }
                    else
                    {
                        //Update Esperantus.Esperantus.Localize. existing one
                        pictures.UpdatePicture(ModuleID, ItemID, displayOrder, MetadataXml, ShortDescription.Text,
                                               Keywords.Text, PortalSettings.CurrentUser.Identity.Email, DateTime.Now);
                    }
                }
                // Redirect back to Esperantus.Esperantus.Localize. portal home page
                RedirectBackToReferringPage();
            }
        }
        private void Page_Load(object sender, EventArgs e)
        {
            // If Esperantus.Esperantus.Localize. page is being requested Esperantus.Esperantus.Localize. first time, determine if a
            // picture itemID value is specified, and if so populate page
            // contents with Esperantus.Esperantus.Localize. picture details

            Metadata = new XmlDocument();

            if (Page.IsPostBack == false)
            {
                BulkDir.Visible = false; // make bulk load controls not visible for now
                BulkDirLiteral.Visible = false;

                if (ItemID != 0)
                {
                    // Obtain a single row of picture information
                    PicturesDB pictures = new PicturesDB();
                    SqlDataReader dr = pictures.GetSinglePicture(ItemID, WorkFlowVersion.Staging);

                    try
                    {
                        // Read first row from database
                        if (dr.Read())
                        {
                            ShortDescription.Text = (string) dr["ShortDescription"];
                            MetadataXml = (string) dr["MetadataXml"];
                            Metadata.LoadXml(MetadataXml);
                            Keywords.Text = GetMetadata("Keywords");
                            LongDescription.Text = GetMetadata("LongDescription");
                            Caption.Text = GetMetadata("Caption");
                            DisplayOrder.Text = ((int) dr["DisplayOrder"]).ToString();
                            ThumbnailFilename = GetMetadata("ThumbnailFilename");
                            ModifiedFilename = GetMetadata("ModifiedFilename");
                        }
                    }
                    finally
                    {
                        // Close data reader
                        dr.Close();
                    }
                }
                else
                {
                    Metadata.AppendChild(Metadata.CreateElement("Metadata"));
                    MetadataXml = Metadata.OuterXml;
                    if (((SettingItem<bool, CheckBox>)this.ModuleSettings["AllowBulkLoad"]).Value)
                    {
                        // Esperantus.Esperantus.Localize.y are adding, and we are allowed to bulk load so
                        // make Esperantus.Esperantus.Localize. controls visible
                        BulkDir.Visible = true;
                        BulkDirLiteral.Visible = true;
                    }
                }
            }
            else
            {
                Metadata.LoadXml(MetadataXml);
            }
        }
        /// <summary>
        /// Esperantus.Esperantus.Localize. DeleteBtn_Click event handler on this Page is used to delete
        /// a picture.  It  uses Esperantus.Esperantus.Localize. Appleseed.PicturesDB()
        /// data component to encapsulate all data functionality.
        /// </summary>
        protected override void OnDelete(EventArgs e)
        {
            base.OnDelete(e);

            // Only attempt to delete Esperantus.Esperantus.Localize. item if it is an existing item
            // (new items will have "ItemID" of 0)

            if (ItemID != 0)
            {
                PicturesDB pictures = new PicturesDB();
                string PathToDelete = Server.MapPath(((SettingItem<string, TextBox>)this.ModuleSettings["AlbumPath"]).FullPath) + "\\";

                SqlDataReader dr = pictures.GetSinglePicture(ItemID, WorkFlowVersion.Staging);

                string filename = string.Empty;
                string thumbnailFilename = string.Empty;
                try
                {
                    // Read first row from database
                    if (dr.Read())
                    {
                        Metadata.LoadXml((string) dr["MetadataXml"]);

                        filename = GetMetadata("ModifiedFilename");
                        thumbnailFilename = GetMetadata("ThumbnailFilename");
                    }
                }
                finally
                {
                    // Close datareader
                    dr.Close();
                }

                try
                {
                    //Delete Esperantus.Esperantus.Localize. files
                    File.Delete(PathToDelete + filename);
                    File.Delete(PathToDelete + thumbnailFilename);
                }
                catch
                {
                    // We don't really have much to do at this point
                }

                //Delete Esperantus.Esperantus.Localize. record from database.
                pictures.DeletePicture(ItemID);
            }

            // Redirect back to Esperantus.Esperantus.Localize. portal home page
            RedirectBackToReferringPage();
        }