Esempio n. 1
0
        /// <summary> Reads the CompleteTemplate XML configuration file specified into a CompleteTemplate object </summary>
        /// <param name="XML_File"> Filename of the CompleteTemplate XML configuraiton file to read  </param>
        /// <param name="ThisCompleteTemplate"> CompleteTemplate object to populate form the configuration file </param>
        /// <param name="exclude_divisions"> Flag indicates whether to include the structure map, if included in the CompleteTemplate file </param>
        public void Read_XML(string XML_File, CompleteTemplate ThisCompleteTemplate, bool exclude_divisions)
        {
            // Load this MXF File
            XmlDocument templateXml = new XmlDocument();

            templateXml.Load(XML_File);

            // create the node reader
            XmlNodeReader nodeReader = new XmlNodeReader(templateXml);

            // Read through all main input CompleteTemplate tag is found
            move_to_node(nodeReader, "input_template");

            // Process all of the header information for this CompleteTemplate
            process_template_header(nodeReader, ThisCompleteTemplate);

            // Process all of the input portion / hierarchy
            process_inputs(nodeReader, ThisCompleteTemplate, exclude_divisions);

            // Process any constant sectoin
            process_constants(nodeReader, ThisCompleteTemplate);

            // Do any final processing
            ThisCompleteTemplate.Build_Final_Adjustment_And_Checks();
        }
Esempio n. 2
0
        private void process_constants(XmlNodeReader nodeReader, CompleteTemplate ThisCompleteTemplate)
        {
            // Read all the nodes
            while (nodeReader.Read())
            {
                // Get the node name, trimmed and to upper
                string nodeName = nodeReader.Name.Trim().ToUpper();

                // If this is the inputs or constant start tag, return
                if ((nodeReader.NodeType == XmlNodeType.EndElement) && (nodeName == "CONSTANTS"))
                {
                    return;
                }

                // If this is the beginning tag for an element, assign the next values accordingly
                if ((nodeReader.NodeType == XmlNodeType.Element) && (nodeName == "ELEMENT") && (nodeReader.HasAttributes))
                {
                    abstract_Element newConstant = process_element(nodeReader, -1);
                    if (newConstant != null)
                    {
                        newConstant.isConstant = true;
                        ThisCompleteTemplate.Add_Constant(newConstant);
                    }
                }
            }
        }
        private void process_constants( XmlNodeReader nodeReader, CompleteTemplate ThisCompleteTemplate )
        {
            // Read all the nodes
            while ( nodeReader.Read() )
            {
                // Get the node name, trimmed and to upper
                string nodeName = nodeReader.Name.Trim().ToUpper();

                // If this is the inputs or constant start tag, return
                if (( nodeReader.NodeType == XmlNodeType.EndElement ) && ( nodeName == "CONSTANTS" ))
                {
                    return;
                }

                // If this is the beginning tag for an element, assign the next values accordingly
                if (( nodeReader.NodeType == XmlNodeType.Element ) && ( nodeName == "ELEMENT" ) && ( nodeReader.HasAttributes ))
                {
                    abstract_Element newConstant = process_element( nodeReader, -1 );
                    if (newConstant != null)
                    {
                        newConstant.isConstant = true;
                        ThisCompleteTemplate.Add_Constant(newConstant);
                    }
                }
            }
        }
Esempio n. 4
0
        /// <summary> Static method reads a template XML configuraton file and creates the <see cref="CompleteTemplate"/> object  </summary>
        /// <param name="XmlFile"> Filename of the template XML configuraiton file to read </param>
        /// <param name="ExcludeDivisions"> Flag indicates whether to include the structure map, if included in the template file </param>
        /// <returns> Fully built template object </returns>
        /// <remarks> This utilizes the <see cref="Template_XML_Reader"/> class to do the actual reading</remarks>
        public static CompleteTemplate Read_XML_Template(string XmlFile, bool ExcludeDivisions)
        {
            CompleteTemplate    returnValue = new CompleteTemplate();
            Template_XML_Reader reader      = new Template_XML_Reader();

            reader.Read_XML(XmlFile, returnValue, ExcludeDivisions);
            returnValue.Build_Final_Adjustment_And_Checks();
            return(returnValue);
        }
        /// <summary> Stores the template ( for online submission and editing ) to the cache or caching server </summary>
        /// <param name="Template_Code"> Code for the template to store </param>
        /// <param name="StoreObject"> CompleteTemplate object for online submissions and editing to store</param>
        /// <param name="Tracer"> Trace object keeps a list of each method executed and important milestones in rendering</param>
        public static void Store_Template(string Template_Code, CompleteTemplate StoreObject, Custom_Tracer Tracer)
        {
            // Determine the key
            string key = "TEMPLATE_" + Template_Code;

            if (Tracer != null)
            {
                Tracer.Add_Trace("Template_MemoryMgmt_Utility.Store_Template", "Adding object '" + key + "' to the cache with expiration of thirty minutes");
            }

            // Store this on the cache
            if (HttpContext.Current.Cache[key] == null)
            {
                HttpContext.Current.Cache.Insert(key, StoreObject, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(30));
            }
        }
        /// <summary> Reads the CompleteTemplate XML configuration file specified into a CompleteTemplate object </summary>
        /// <param name="XML_File"> Filename of the CompleteTemplate XML configuraiton file to read  </param>
        /// <param name="ThisCompleteTemplate"> CompleteTemplate object to populate form the configuration file </param>
        /// <param name="exclude_divisions"> Flag indicates whether to include the structure map, if included in the CompleteTemplate file </param>
        public void Read_XML( string XML_File, CompleteTemplate ThisCompleteTemplate, bool exclude_divisions )
        {
            // Load this MXF File
            XmlDocument templateXml = new XmlDocument();
            templateXml.Load( XML_File );

            // create the node reader
            XmlNodeReader nodeReader = new XmlNodeReader( templateXml );

            // Read through all main input CompleteTemplate tag is found
            move_to_node( nodeReader, "input_template" );

            // Process all of the header information for this CompleteTemplate
            process_template_header( nodeReader, ThisCompleteTemplate );

            // Process all of the input portion / hierarchy
            process_inputs(nodeReader, ThisCompleteTemplate, exclude_divisions);

            // Process any constant sectoin
            process_constants( nodeReader, ThisCompleteTemplate );

            // Do any final processing
            ThisCompleteTemplate.Build_Final_Adjustment_And_Checks();
        }
        /// <summary> Reads the CompleteTemplate XML configuration file specified into a CompleteTemplate object </summary>
        /// <param name="XML_File"> Filename of the CompleteTemplate XML configuraiton file to read  </param>
        /// <param name="ThisCompleteTemplate"> CompleteTemplate object to populate form the configuration file </param>
        /// <param name="exclude_divisions"> Flag indicates whether to include the structure map, if included in the CompleteTemplate file </param>
        public void Read_XML( string XML_File, CompleteTemplate ThisCompleteTemplate, bool exclude_divisions )
        {
            // Set some default for this read
            complexMainTitleExists = false;

            // Load this MXF File
            XmlDocument templateXml = new XmlDocument();
            templateXml.Load( XML_File );

            // create the node reader
            XmlNodeReader nodeReader = new XmlNodeReader( templateXml );

            // Read through all main input CompleteTemplate tag is found
            move_to_node( nodeReader, "input_template" );

            // Process all of the header information for this CompleteTemplate
            process_template_header( nodeReader, ThisCompleteTemplate );

            // Process all of the input portion / hierarchy
            process_inputs(nodeReader, ThisCompleteTemplate, exclude_divisions);

            // Process any constant sectoin
            process_constants( nodeReader, ThisCompleteTemplate );
        }
 /// <summary> Static method reads a template XML configuraton file and creates the <see cref="CompleteTemplate"/> object  </summary>
 /// <param name="XmlFile"> Filename of the template XML configuraiton file to read </param>
 /// <param name="ExcludeDivisions"> Flag indicates whether to include the structure map, if included in the template file </param>
 /// <returns> Fully built template object </returns>
 /// <remarks> This utilizes the <see cref="Template_XML_Reader"/> class to do the actual reading</remarks>
 public static CompleteTemplate Read_XML_Template( string XmlFile, bool ExcludeDivisions )
 {
     CompleteTemplate returnValue = new CompleteTemplate();
     Template_XML_Reader reader = new Template_XML_Reader();
     reader.Read_XML( XmlFile, returnValue, ExcludeDivisions );
     returnValue.Build_Final_Adjustment_And_Checks();
     return returnValue;
 }
        /// <summary> Constructor for a new instance of the Edit_Item_Behaviors_MySobekViewer class </summary>
        ///  <param name="RequestSpecificValues"> All the necessary, non-global data specific to the current request </param>
        public Edit_Item_Behaviors_MySobekViewer(RequestCache RequestSpecificValues)
            : base(RequestSpecificValues)
        {
            RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Behaviors_MySobekViewer.Constructor", String.Empty);

            // If no user then that is an error
            if ((RequestSpecificValues.Current_User == null) || (!RequestSpecificValues.Current_User.LoggedOn))
            {
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Aggregation;
                RequestSpecificValues.Current_Mode.Aggregation = String.Empty;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // Ensure BibID and VID provided
            RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Behaviors_MySobekViewer.Constructor", "Validate provided bibid / vid");
            if ((String.IsNullOrEmpty(RequestSpecificValues.Current_Mode.BibID)) || (String.IsNullOrEmpty(RequestSpecificValues.Current_Mode.VID)))
            {
                RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Behaviors_MySobekViewer.Constructor", "BibID or VID was not provided!");
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : BibID/VID missing in item behavior request";
                return;
            }

            // Ensure the item is valid
            RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Behaviors_MySobekViewer.Constructor", "Validate bibid/vid exists");
            if (!UI_ApplicationCache_Gateway.Items.Contains_BibID_VID(RequestSpecificValues.Current_Mode.BibID, RequestSpecificValues.Current_Mode.VID))
            {
                RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Behaviors_MySobekViewer.Constructor", "BibID/VID indicated is not valid", Custom_Trace_Type_Enum.Error);
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : BibID/VID indicated is not valid";
                return;
            }

            RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Behaviors_MySobekViewer.Constructor", "Try to pull this sobek complete item");
            currentItem = SobekEngineClient.Items.Get_Sobek_Item(RequestSpecificValues.Current_Mode.BibID, RequestSpecificValues.Current_Mode.VID, RequestSpecificValues.Current_User.UserID, RequestSpecificValues.Tracer);
            if (currentItem == null)
            {
                RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Behaviors_MySobekViewer.Constructor", "Unable to build complete item");
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : Unable to build complete item";
                return;
            }

            // If no item, then an error occurred
            if (currentItem == null)
            {
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                RequestSpecificValues.Current_Mode.Error_Message = "Invalid item indicated";
                return;
            }

            // If the RequestSpecificValues.Current_User cannot edit this currentItem, go back
            if (!RequestSpecificValues.Current_User.Can_Edit_This_Item(currentItem.BibID, currentItem.Bib_Info.SobekCM_Type_String, currentItem.Bib_Info.Source.Code, currentItem.Bib_Info.HoldingCode, currentItem.Behaviors.Aggregation_Code_List))
            {
                RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            const string TEMPLATE_CODE = "itembehaviors";
            completeTemplate = Template_MemoryMgmt_Utility.Retrieve_Template(TEMPLATE_CODE, RequestSpecificValues.Tracer);
            if (completeTemplate != null)
            {
                RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Behaviors_MySobekViewer.Constructor", "Found CompleteTemplate in cache");
            }
            else
            {
                RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Behaviors_MySobekViewer.Constructor", "Reading CompleteTemplate file");

                // Look in the user-defined templates portion first
                string user_template = UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\user\\standard\\" + TEMPLATE_CODE + ".xml";
                if (!File.Exists(user_template))
                    user_template = UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\default\\standard\\" + TEMPLATE_CODE + ".xml";

                // Read this CompleteTemplate
                Template_XML_Reader reader = new Template_XML_Reader();
                completeTemplate = new CompleteTemplate();
                reader.Read_XML(user_template, completeTemplate, true);

                // Save this into the cache
                Template_MemoryMgmt_Utility.Store_Template(TEMPLATE_CODE, completeTemplate, RequestSpecificValues.Tracer);
            }

            // See if there was a hidden request
            string hidden_request = HttpContext.Current.Request.Form["behaviors_request"] ?? String.Empty;

            // If this was a cancel request do that
            if (hidden_request == "cancel")
            {
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
            }
            else if (hidden_request == "save")
            {
                // Changes to the tracking box require the metadata search citation be rebuilt for this currentItem
                // so save the old tracking box information first
                string oldTrackingBox = currentItem.Tracking.Tracking_Box;

                // Save these changes to bib
                completeTemplate.Save_To_Bib(currentItem, RequestSpecificValues.Current_User, 1);

                // Save the behaviors
                SobekCM_Item_Database.Save_Behaviors(currentItem, currentItem.Behaviors.Text_Searchable, false, false);

                // Save the serial hierarchy as well (sort of a behavior)
                SobekCM_Item_Database.Save_Serial_Hierarchy_Information(currentItem, currentItem.Web.GroupID, currentItem.Web.ItemID);

                // Did the tracking box change?
                if (currentItem.Tracking.Tracking_Box != oldTrackingBox)
                {
                    SobekCM_Item_Database.Create_Full_Citation_Value(currentItem.Web.ItemID);
                }

                // Remoe from the caches (to replace the other)
                CachedDataManager.Items.Remove_Digital_Resource_Object(currentItem.BibID, currentItem.VID, RequestSpecificValues.Tracer);

                // Also remove the list of volumes, since this may have changed
                CachedDataManager.Items.Remove_Items_In_Title(currentItem.BibID, RequestSpecificValues.Tracer);
                CachedDataManager.Items.Remove_Items_List(currentItem.BibID, RequestSpecificValues.Tracer);

                // Also clear the engine
                SobekEngineClient.Items.Clear_Item_Group_Cache(currentItem.BibID, RequestSpecificValues.Tracer);

                // Also clear any searches or browses ( in the future could refine this to only remove those
                // that are impacted by this save... but this is good enough for now )
                CachedDataManager.Clear_Search_Results_Browses();

                // Forward
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
            }
        }
        /// <summary> Constructor for a new instance of the Edit_TEI_Item_MySobekViewer class </summary>
        /// <param name="RequestSpecificValues"> All the necessary, non-global data specific to the current request </param>
        public Edit_TEI_Item_MySobekViewer(RequestCache RequestSpecificValues)
            : base(RequestSpecificValues)
        {
            RequestSpecificValues.Tracer.Add_Trace("Edit_TEI_Item_MySobekViewer.Constructor", String.Empty);

            // If the RequestSpecificValues.Current_User cannot submit items, go back
            if (!RequestSpecificValues.Current_User.Can_Submit)
            {
                RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // Ensure the TEI plug-in is enabled
            if ((UI_ApplicationCache_Gateway.Configuration.Extensions == null) ||
                (UI_ApplicationCache_Gateway.Configuration.Extensions.Get_Extension("TEI") == null) ||
                (!UI_ApplicationCache_Gateway.Configuration.Extensions.Get_Extension("TEI").Enabled))
            {
                RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // Ensure BibID and VID provided
            RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "Validate provided bibid / vid");
            if ((String.IsNullOrEmpty(RequestSpecificValues.Current_Mode.BibID)) || (String.IsNullOrEmpty(RequestSpecificValues.Current_Mode.VID)))
            {
                RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "BibID or VID was not provided!");
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : BibID/VID missing in item metadata edit request";
                return;
            }

            bibid = RequestSpecificValues.Current_Mode.BibID;
            vid = RequestSpecificValues.Current_Mode.VID;

            // Ensure the item is valid
            RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "Validate bibid/vid exists");
            if (!UI_ApplicationCache_Gateway.Items.Contains_BibID_VID(bibid, vid))
            {
                RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "BibID/VID indicated is not valid", Custom_Trace_Type_Enum.Error);
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : BibID/VID indicated is not valid";
                return;
            }

            // Determine the in process directory for this
            if (RequestSpecificValues.Current_User.ShibbID.Trim().Length > 0)
                userInProcessDirectory = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.In_Process_Submission_Location, RequestSpecificValues.Current_User.ShibbID, "teiedit", bibid + "_" + vid);
            else
                userInProcessDirectory = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.In_Process_Submission_Location, RequestSpecificValues.Current_User.UserName.Replace(".", "").Replace("@", ""), "teiedit", bibid + "_" + vid);

            // Clear any old files (older than 24 hours) that are in the directory
            if (!Directory.Exists(userInProcessDirectory))
                Directory.CreateDirectory(userInProcessDirectory);
            else
            {
                // Anything older than a day should be deleted
                string[] files = Directory.GetFiles(userInProcessDirectory);
                foreach (string thisFile in files)
                {
                    DateTime modifiedDate = ((new FileInfo(thisFile)).LastWriteTime);
                    if (DateTime.Now.Subtract(modifiedDate).TotalHours > (24*7))
                    {
                        try
                        {
                            File.Delete(thisFile);
                        }
                        catch (Exception)
                        {
                            // Unable to delete existing file in the RequestSpecificValues.Current_User's folder.
                            // This is an error, but how to report it?
                        }
                    }
                }
            }

            // Load the CompleteTemplate
            completeTemplate = Template_MemoryMgmt_Utility.Retrieve_Template("tei_edit", RequestSpecificValues.Tracer);
            if (completeTemplate != null)
            {
                RequestSpecificValues.Tracer.Add_Trace("Edit_TEI_Item_MySobekViewer.Constructor", "Found template in cache");
            }
            else
            {
                RequestSpecificValues.Tracer.Add_Trace("Edit_TEI_Item_MySobekViewer.Constructor", "Reading template");

                string user_template = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.Application_Server_Network, "plugins\\tei\\templates\\user\\edit.xml");
                if (!File.Exists(user_template))
                    user_template = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.Application_Server_Network, "plugins\\tei\\templates\\default\\edit.xml");

                // Read this CompleteTemplate
                Template_XML_Reader reader = new Template_XML_Reader();
                completeTemplate = new CompleteTemplate();
                reader.Read_XML(user_template, completeTemplate, true);

                // Save this into the cache
                Template_MemoryMgmt_Utility.Store_Template("tei_edit", completeTemplate, RequestSpecificValues.Tracer);
            }

            // Determine the number of total CompleteTemplate pages
            totalTemplatePages = completeTemplate.InputPages_Count + 3;

            // Determine the title for this CompleteTemplate, or use a default
            toolTitle = completeTemplate.Title;
            if (toolTitle.Length == 0)
                toolTitle = "TEI Editing Tool";

            // Determine the current phase
            currentProcessStep = 1;
            if ((RequestSpecificValues.Current_Mode.My_Sobek_SubMode.Length > 0) && (Char.IsNumber(RequestSpecificValues.Current_Mode.My_Sobek_SubMode[0])))
            {
                Int32.TryParse(RequestSpecificValues.Current_Mode.My_Sobek_SubMode.Substring(0), out currentProcessStep);
            }

            // Load some information from the session
            if (HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".Mapping_File"] != null)
                mapping_file = HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".Mapping_File"] as string;
            if (HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".XSLT_File"] != null)
                xslt_file = HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".XSLT_File"] as string;
            if (HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".CSS_File"] != null)
                css_file = HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".CSS_File"] as string;
            if (HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".Original_TEI_File"] != null)
                original_tei_file = HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".Original_TEI_File"] as string;

            // Pull the current item beig edited
            editingItem = null;
            if (HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".New_Item"] != null)
                editingItem = HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".New_Item"] as SobekCM_Item;

            // If any are null or blank, pull from the item
            if ((String.IsNullOrEmpty(mapping_file)) || (String.IsNullOrEmpty(xslt_file)) || (String.IsNullOrEmpty(original_tei_file)) || (editingItem == null))
            {
                // Pull the original item
                RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "Try to pull this sobek complete item");
                SobekCM_Item currentItem = SobekEngineClient.Items.Get_Sobek_Item(bibid, vid, RequestSpecificValues.Current_User.UserID, RequestSpecificValues.Tracer);
                if (currentItem == null)
                {
                    RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "Unable to build complete item");
                    RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                    RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : Unable to build complete item";
                    return;
                }

                // If the editing item was NULL, assign it
                if (editingItem == null)
                {
                    editingItem = currentItem;
                    editingItem.Source_Directory = userInProcessDirectory;
                    HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".New_Item"] = editingItem;
                }

                // Settings SHOULD not be null
                if (currentItem.Behaviors.Settings != null)
                {
                    // Build the setting dictionary
                    Dictionary<string, string> settingDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                    foreach (Tuple<string, string> setting in currentItem.Behaviors.Settings)
                    {
                        settingDictionary[setting.Item1] = setting.Item2;
                    }

                    // Now, use to assign to each value
                    if ((String.IsNullOrEmpty(mapping_file)) && (settingDictionary.ContainsKey("TEI.Mapping")))
                        mapping_file = settingDictionary["TEI.Mapping"];
                    if ((String.IsNullOrEmpty(css_file)) && (settingDictionary.ContainsKey("TEI.CSS")))
                        css_file = settingDictionary["TEI.CSS"];
                    if ((String.IsNullOrEmpty(xslt_file)) && (settingDictionary.ContainsKey("TEI.XSLT")))
                        xslt_file = settingDictionary["TEI.XSLT"];
                    if ((String.IsNullOrEmpty(original_tei_file)) && (settingDictionary.ContainsKey("TEI.Source_File")))
                        original_tei_file = settingDictionary["TEI.Source_File"];

                    // Now, save all these
                    HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".Mapping_File"] = mapping_file;
                    HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".XSLT_File"] = xslt_file;
                    HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".CSS_File"] = css_file;
                    HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".Original_TEI_File"] = original_tei_file;
                }
            }

            // If there is a boundary infraction here, go back to step 1
            if (currentProcessStep < 0)
                currentProcessStep = 1;
            if ((currentProcessStep > completeTemplate.InputPages.Count + 4) && (currentProcessStep != 8) && (currentProcessStep != 9))
                currentProcessStep = 1;

            // Find the TEI file
            if (Directory.Exists(userInProcessDirectory))
            {
                string[] tei_files = Directory.GetFiles(userInProcessDirectory, "*.xml");
                if (tei_files.Length > 1)
                {
                    // Two XML files, so delete all but the latest
                    string latest_tei_file = String.Empty;
                    DateTime latest_timestamp = DateTime.MinValue;

                    // Find the latest TEI file
                    foreach (string thisTeiFile in tei_files)
                    {
                        // If this is marc.xml, skip it
                        if ((Path.GetFileName(thisTeiFile).ToLower().IndexOf("marc.xml") >= 0) || (Path.GetFileName(thisTeiFile).ToLower().IndexOf("mets.xml") >= 0))
                            continue;

                        DateTime file_timestamp = File.GetLastWriteTime(thisTeiFile);

                        if (DateTime.Compare(latest_timestamp, file_timestamp) < 0)
                        {
                            latest_tei_file = thisTeiFile;
                            latest_timestamp = file_timestamp;
                        }
                    }

                    // If a latest file as found, delete the others
                    if (!String.IsNullOrEmpty(latest_tei_file))
                    {
                        foreach (string thisTeiFile in tei_files)
                        {
                            // If this is marc.xml, skip it
                            if ((Path.GetFileName(thisTeiFile).ToLower().IndexOf("marc.xml") >= 0) || (Path.GetFileName(thisTeiFile).ToLower().IndexOf("mets.xml") >= 0))
                                continue;

                            // Was this the latest file?
                            if (String.Compare(thisTeiFile, latest_tei_file, StringComparison.OrdinalIgnoreCase) == 0)
                                continue;

                            try
                            {
                                File.Delete(thisTeiFile);
                            }
                            catch
                            {
                            }

                        }
                    }

                    new_tei_file = latest_tei_file;
                }
                else if (tei_files.Length == 1)
                {
                    new_tei_file = Path.GetFileName(tei_files[0]);
                }
            }

            #region Handle any other post back requests

            // If this is post-back, handle it
            if (RequestSpecificValues.Current_Mode.isPostBack)
            {
                // Was this where the mapping, xslt, and css is set?
                if (currentProcessStep == 1)
                {
                    string[] getKeys = HttpContext.Current.Request.Form.AllKeys;
                    foreach (string thisKey in getKeys)
                    {
                        if (thisKey.IndexOf("mapping_select") == 0)
                        {
                            mapping_file = HttpContext.Current.Request.Form[thisKey];
                            HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".Mapping_File"] = mapping_file;
                        }
                        if (thisKey.IndexOf("xslt_select") == 0)
                        {
                            xslt_file = HttpContext.Current.Request.Form[thisKey];
                            HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".XSLT_File"] = xslt_file;
                        }
                        if (thisKey.IndexOf("css_select") == 0)
                        {
                            css_file = HttpContext.Current.Request.Form[thisKey];
                            HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".CSS_File"] = css_file;
                        }
                    }
                }

                // If this is a post back from editing the XML, save this
                if (currentProcessStep == 2)
                {
                    // Get the content of the edited source
                    string new_output = HttpContext.Current.Request.Form["tei_source_content"];

                    // If the user is editing the current TEI file, make a new version under the
                    // user process folder now
                    string save_tei_file = Path.Combine(userInProcessDirectory, original_tei_file);
                    if (!String.IsNullOrEmpty(new_tei_file))
                    {
                        // Determine new filename
                        save_tei_file = Path.Combine(userInProcessDirectory, new_tei_file);
                    }
                    else
                    {
                        new_tei_file = original_tei_file;
                    }

                    // Save new source file
                    try
                    {
                        StreamWriter writer = new StreamWriter(save_tei_file);
                        writer.Write(new_output);
                        writer.Flush();
                        writer.Close();

                        success_message = "Saved TEI changes";
                    }
                    catch (Exception ee)
                    {
                        error_message = "Error saving the new XML source.<br /><br />" + ee.Message + "<br /><br />";

                    }

                }

                string action = HttpContext.Current.Request.Form["action"];
                if (action == "cancel")
                {
                    // Clear all files in the RequestSpecificValues.Current_User process folder
                    try
                    {
                        string[] all_files = Directory.GetFiles(userInProcessDirectory);
                        foreach (string thisFile in all_files)
                            File.Delete(thisFile);
                        Directory.Delete(userInProcessDirectory);
                    }
                    catch (Exception ee)
                    {
                        new_tei_file = ee.Message;
                        // Unable to delete existing file in the RequestSpecificValues.Current_User's folder.
                        // This is an error, but how to report it?
                    }

                    // Clear all the information in memory
                    HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".New_Item"] = null;
                    HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".Mapping_File"] = null;
                    HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".XSLT_File"] = null;
                    HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".CSS_File"] = null;
                    HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".Original_TEI_File"] = null;

                    // Clear any temporarily assigned current project and CompleteTemplate
                    RequestSpecificValues.Current_User.Current_Default_Metadata = null;
                    RequestSpecificValues.Current_User.Current_Template = null;

                    // Forward back to item page
                    RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
                    RequestSpecificValues.Current_Mode.BibID = bibid;
                    RequestSpecificValues.Current_Mode.VID = vid;
                    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                }

                if (action == "next_phase")
                {
                    string next_phase = HttpContext.Current.Request.Form["phase"];

                    if (currentProcessStep == 1)
                    {
                        // Should be a TEI file to continue
                        if (!String.IsNullOrEmpty(new_tei_file))
                        {
                            XmlValidator validator = new XmlValidator();
                            string tei_filepath = Path.Combine(userInProcessDirectory, new_tei_file);
                            bool isValid = validator.IsValid(tei_filepath);
                            if (!isValid)
                            {
                                string validatorErrors = validator.Errors.Replace("\n", "<br />\n");
                                error_message = "Uploaded TEI file is not a valid XML source file.<br /><br />\n" + validatorErrors;
                                next_phase = "1";
                            }
                        }
                    }

                    // Was this from editing the XMl file?
                    if (currentProcessStep == 2)
                    {
                        // Was there an error?
                        if (!String.IsNullOrEmpty(error_message))
                            next_phase = "2";
                        else if (!String.IsNullOrEmpty(new_tei_file))
                        {
                            XmlValidator validator = new XmlValidator();
                            string tei_filepath = Path.Combine(userInProcessDirectory, new_tei_file);
                            bool isValid = validator.IsValid(tei_filepath);
                            if (!isValid)
                            {
                                string validatorErrors = validator.Errors.Replace("\n", "<br />\n");
                                error_message = "TEI is not valid XML.<br /><br />\n" + validatorErrors;
                                next_phase = "2";
                            }
                        }
                    }

                    // If this is going from a step that includes the metadata entry portion, save this to the item
                    if ((currentProcessStep >= 4) && (currentProcessStep < 8))
                    {
                        // Save to the item
                        completeTemplate.Save_To_Bib(editingItem, RequestSpecificValues.Current_User, currentProcessStep - 4);
                        editingItem.Save_METS();
                        HttpContext.Current.Session["Edit_TEI_mySobekViewer." + bibid + "_" + vid + ".New_Item"] = editingItem;
                    }

                    // For now, just forward to the next phase
                    if (currentProcessStep.ToString() != next_phase)
                    {
                        RequestSpecificValues.Current_Mode.My_Sobek_SubMode = next_phase;
                        UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                        return;
                    }
                }
            }

            #endregion

            #region Perform some validation to determine if the RequestSpecificValues.Current_User should be at this step

            // If this is past the step to upload a TEI file, ensure a TEI file exists
            if ((currentProcessStep > 1) && ((String.IsNullOrEmpty(mapping_file)) || (String.IsNullOrEmpty(xslt_file))))
            {
                RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "1";
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // If this is to put up items or complete the item, validate the METS
            if (currentProcessStep >= 8)
            {
                // Validate that a METS file exists
                if (Directory.GetFiles(userInProcessDirectory, "*.mets*").Length == 0)
                {
                    RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "2";
                    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                    return;
                }

                // Get the validation errors
                validationErrors = new List<string>();
                SobekCM_Item_Validator.Validate_SobekCM_Item(editingItem, validationErrors);

                // Get the validation errors
                if ((validationErrors == null ) || ( validationErrors.Count == 0))
                    editingItem.Save_METS();
                else
                {
                    editingItem.Web.Show_Validation_Errors = true;

                    RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "4";
                    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                    return;
                }
            }

            // If this is going into the last process step, check that any mandatory info (file, url, .. )
            // from the last step is present
            if (currentProcessStep == 9)
            {
                // Complete the item submission
                complete_item_submission(editingItem, RequestSpecificValues.Tracer);
            }

            #endregion
        }
        private void process_template_header( XmlNodeReader nodeReader, CompleteTemplate ThisCompleteTemplate )
        {
            // Read all the nodes
            while ( nodeReader.Read() )
            {
                // Get the node name, trimmed and to upper
                string nodeName = nodeReader.Name.Trim().ToUpper();

                // If this is the inputs or constant start tag, return
                if (( nodeReader.NodeType == XmlNodeType.Element ) &&
                    (( nodeName == "INPUTS" ) || ( nodeName == "CONSTANTS" )))
                {
                    return;
                }

                // If this is the beginning tag for an element, assign the next values accordingly
                if ( nodeReader.NodeType == XmlNodeType.Element )
                {
                    // switch the rest based on the tag name
                    switch (nodeName)
                    {
                        case "BANNER":
                            ThisCompleteTemplate.Banner = read_text_node(nodeReader);
                            break;

                        case "INCLUDEUSERASAUTHOR":
                            ThisCompleteTemplate.Include_User_As_Author = Convert.ToBoolean(read_text_node(nodeReader));
                            break;

                        case "UPLOADS":
                            string upload_type_text = read_text_node(nodeReader).Trim().ToUpper();
                            switch (upload_type_text)
                            {
                                case "NONE":
                                    ThisCompleteTemplate.Upload_Types = CompleteTemplate.Template_Upload_Types.None;
                                    break;

                                case "FILE":
                                    ThisCompleteTemplate.Upload_Types = CompleteTemplate.Template_Upload_Types.File;
                                    break;

                                case "URL":
                                    ThisCompleteTemplate.Upload_Types = CompleteTemplate.Template_Upload_Types.URL;
                                    break;

                                case "FILE_OR_URL":
                                    ThisCompleteTemplate.Upload_Types = CompleteTemplate.Template_Upload_Types.File_or_URL;
                                    break;

                                default:
                                    ThisCompleteTemplate.Upload_Types = CompleteTemplate.Template_Upload_Types.File;
                                    break;

                            }
                            break;

                        case "UPLOADMANDATORY":
                            ThisCompleteTemplate.Upload_Mandatory = Convert.ToBoolean(read_text_node(nodeReader));
                            break;

                        case "NAME":
                            ThisCompleteTemplate.Title = read_text_node(nodeReader);
                            break;

                        case "PERMISSIONS":
                            ThisCompleteTemplate.Permissions_Agreement = read_text_node(nodeReader);
                            break;

                        case "NOTES":
                            ThisCompleteTemplate.Notes = (ThisCompleteTemplate.Notes + "  " + read_text_node(nodeReader)).Trim();
                            break;

                        case "DATECREATED":
                            DateTime dateCreated;
                            if (DateTime.TryParse(read_text_node(nodeReader), out dateCreated))
                                ThisCompleteTemplate.DateCreated = dateCreated;
                            break;

                        case "LASTMODIFIED":
                            DateTime lastModified;
                            if (DateTime.TryParse(read_text_node(nodeReader), out lastModified))
                                ThisCompleteTemplate.LastModified = lastModified;
                            break;

                        case "CREATOR":
                            ThisCompleteTemplate.Creator = read_text_node(nodeReader);
                            break;

                        case "BIBIDROOT":
                            ThisCompleteTemplate.BibID_Root = read_text_node(nodeReader);
                            break;

                        case "DEFAULTVISIBILITY":
                            string visibilityValue = read_text_node(nodeReader);
                            switch (visibilityValue)
                            {
                                case "PRIVATE":
                                    ThisCompleteTemplate.Default_Visibility = -1;
                                    break;

                                case "PUBLIC":
                                    ThisCompleteTemplate.Default_Visibility = 0;
                                    break;
                            }
                            break;

                        case "EMAILUPONSUBMIT":
                            ThisCompleteTemplate.Email_Upon_Receipt = read_text_node(nodeReader);
                            break;
                    }
                }
            }
        }
        private void process_inputs( XmlNodeReader nodeReader, CompleteTemplate ThisCompleteTemplate, bool exclude_divisions )
        {
            // Keep track of the current pages and panels
            Template_Page currentPage = null;
            Template_Panel currentPanel = null;
            bool inPanel = false;

            // Read all the nodes
            while ( nodeReader.Read() )
            {
                // Get the node name, trimmed and to upper
                string nodeName = nodeReader.Name.Trim().ToUpper();

                // If this is the inputs or constant start tag, return
                if ((( nodeReader.NodeType == XmlNodeType.EndElement ) && ( nodeName == "INPUTS" )) ||
                    (( nodeReader.NodeType == XmlNodeType.Element ) && ( nodeReader.Name == "CONSTANTS")))
                {
                    return;
                }

                // If this is the beginning tag for an element, assign the next values accordingly
                if ( nodeReader.NodeType == XmlNodeType.Element )
                {
                    // Does this start a new page?
                    if ( nodeName == "PAGE" )
                    {
                        // Set the inPanel flag to false
                        inPanel = false;

                        // Create the new page and add to this CompleteTemplate
                        currentPage = new Template_Page();
                        ThisCompleteTemplate.Add_Page( currentPage );
                    }

                    // Does this start a new panel?
                    if (( nodeName == "PANEL" ) && ( currentPage != null ))
                    {
                        // Set the inPanel flag to true
                        inPanel = true;

                        // Create the new panel and add to the current page
                        currentPanel = new Template_Panel();
                        currentPage.Add_Panel( currentPanel );
                    }

                    // Is this a name element?
                    if ((nodeName == "NAME") && (currentPage != null))
                    {
                        // Get the text
                        string title = read_text_node( nodeReader );

                        // Set the name for either the page or panel
                        if ( inPanel )
                        {
                            currentPanel.Title = title;
                        }
                        else
                        {
                            currentPage.Title = title;
                        }
                    }

                    // Is this a name element?
                    if ((nodeName == "INSTRUCTIONS") && (currentPage != null))
                    {
                        // Get the text
                        string instructions = read_text_node(nodeReader);

                        // Set the name for either the page or panel
                        if (!inPanel)
                        {
                            currentPage.Instructions = instructions;
                        }
                    }

                    // Is this a new element?
                    if ((nodeName == "ELEMENT") && (nodeReader.HasAttributes) && (currentPanel != null))
                    {
                        abstract_Element currentElement = process_element( nodeReader, ThisCompleteTemplate.InputPages.Count );
                        if (( currentElement != null ) && (( !exclude_divisions ) || ( currentElement.Type != Element_Type.Structure_Map )))
                            currentPanel.Add_Element( currentElement );
                    }
                }
            }
        }
        /// <summary> Constructor for a new instance of the Group_Add_Volume_MySobekViewer class </summary>
        /// <param name="RequestSpecificValues"> All the necessary, non-global data specific to the current request </param>
        public Group_Add_Volume_MySobekViewer(RequestCache RequestSpecificValues)
            : base(RequestSpecificValues)
        {
            RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", String.Empty);

            // If no user then that is an error
            if ((RequestSpecificValues.Current_User == null) || (!RequestSpecificValues.Current_User.LoggedOn))
            {
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Aggregation;
                RequestSpecificValues.Current_Mode.Aggregation = String.Empty;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // Ensure BibID provided
            RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "Validate provided bibid");
            if (String.IsNullOrEmpty(RequestSpecificValues.Current_Mode.BibID))
            {
                RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "BibID was not provided!");
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : BibID missing in item group metadata edit request";
                return;
            }

            // Ensure the item is valid
            RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "Validate bibid exists");
            if (!UI_ApplicationCache_Gateway.Items.Contains_BibID(RequestSpecificValues.Current_Mode.BibID))
            {
                RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "BibID indicated is not valid", Custom_Trace_Type_Enum.Error);
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : BibID indicated is not valid";
                return;
            }

            RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "Try to pull this sobek complete item group");
            currentItem = SobekEngineClient.Items.Get_Sobek_Item_Group(RequestSpecificValues.Current_Mode.BibID, RequestSpecificValues.Tracer);
            if (currentItem == null)
            {
                RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "Unable to build complete item group");
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : Unable to build complete item";
                return;
            }

            // Pull the list of items tied to this group - Get the list of other volumes
            RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "Get the list of items under " + RequestSpecificValues.Current_Mode.BibID);
            try
            {
                allVolumes = SobekEngineClient.Items.Get_Multiple_Volumes(RequestSpecificValues.Current_Mode.BibID, RequestSpecificValues.Tracer);
            }
            catch (Exception ee)
            {
                RequestSpecificValues.Tracer.Add_Trace("Tracking_ItemViewer.Constructor", "Unable to pull volumes under " + RequestSpecificValues.Current_Mode.BibID);
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                RequestSpecificValues.Current_Mode.Error_Message = "Internal Error : Unable to pull volumes under " + RequestSpecificValues.Current_Mode.BibID;
                return;
            }

            // Set some defaults
            ipRestrict = -1;
            title = String.Empty;
            date = String.Empty;
            level1 = String.Empty;
            level2 = String.Empty;
            level3 = String.Empty;
            level1Order = -1;
            level2Order = -1;
            level3Order = -1;
            hierarchyCopiedFromDate = false;
            message = String.Empty;
            trackingBox = String.Empty;
            bornDigital = false;
            materialRecdDate = null;
            materialRecdNotes = String.Empty;
            dispositionAdvice = -1;
            dispositionAdviceNotes = String.Empty;

            // If the user cannot edit this item, go back
            if (!RequestSpecificValues.Current_User.Can_Edit_This_Item(currentItem.BibID, currentItem.Bib_Info.SobekCM_Type_String, currentItem.Bib_Info.Source.Code, currentItem.Bib_Info.HoldingCode, currentItem.Behaviors.Aggregation_Code_List))
            {
                RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // Determine the default CompleteTemplate code
            string template_code = "addvolume";
            if (!RequestSpecificValues.Current_User.Include_Tracking_In_Standard_Forms)
                template_code = "addvolume_notracking";

            // Load this CompleteTemplate
            completeTemplate = Template_MemoryMgmt_Utility.Retrieve_Template(template_code, RequestSpecificValues.Tracer);
            if (completeTemplate != null)
            {
                RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "Found CompleteTemplate in cache");
            }
            else
            {
                RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "Reading CompleteTemplate file");

                // Look in the user-defined templates portion first
                string user_template = UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\user\\standard\\" + template_code + ".xml";
                if (!File.Exists(user_template))
                    user_template = UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\default\\standard\\" + template_code + ".xml";

                // Read this template
                Template_XML_Reader reader = new Template_XML_Reader();
                completeTemplate = new CompleteTemplate();
                reader.Read_XML(user_template, completeTemplate, true);

                // Save this into the cache
                Template_MemoryMgmt_Utility.Store_Template(template_code, completeTemplate, RequestSpecificValues.Tracer);
            }

            // See if there was a hidden request
            string hidden_request = HttpContext.Current.Request.Form["action"] ?? String.Empty;

            // If this was a cancel request do that
            if (hidden_request == "cancel")
            {
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
            }
            else if (hidden_request.IndexOf("save") == 0 )
            {
                // Get the VID that used as a source for this
                string vid = HttpContext.Current.Request.Form["base_volume"];

                if (string.IsNullOrEmpty(vid))
                {
                     message = "<span style=\"color: red\"><strong>No base volume selected!</strong></span>";
                }
                else
                {
                    try
                    {
                        // Get a new instance of this item
                        SobekCM_Item saveItem = SobekCM_Item_Factory.Get_Item(RequestSpecificValues.Current_Mode.BibID, vid, UI_ApplicationCache_Gateway.Icon_List, RequestSpecificValues.Tracer);

                        // Clear some values for this item
                        saveItem.VID = String.Empty;
                        saveItem.Divisions.Clear();
                        saveItem.Behaviors.Serial_Info.Clear();
                        saveItem.Bib_Info.Series_Part_Info.Clear();
                        saveItem.Behaviors.Clear_Ticklers();
                        saveItem.Tracking.Internal_Comments = String.Empty;
                        saveItem.Bib_Info.Location.PURL = String.Empty;
                        saveItem.Behaviors.Main_Thumbnail = String.Empty;
                        saveItem.METS_Header.Create_Date = DateTime.Now;
                        saveItem.METS_Header.Modify_Date = saveItem.METS_Header.Create_Date;
                        saveItem.METS_Header.Creator_Software = "SobekCM Web - Online add a volume (derived from VID " + vid + ")";
                        saveItem.METS_Header.Clear_Creator_Individual_Notes();
                        saveItem.METS_Header.Creator_Individual = RequestSpecificValues.Current_User.Full_Name;
                        saveItem.Bib_Info.Location.Other_URL = String.Empty;
                        saveItem.Bib_Info.Location.Other_URL_Display_Label = String.Empty;
                        saveItem.Bib_Info.Location.Other_URL_Note = String.Empty;

                        // Save the CompleteTemplate changes to this item
                        completeTemplate.Save_To_Bib(saveItem, RequestSpecificValues.Current_User, 1);

                        // Save this item and copy over
                        complete_item_submission(saveItem, RequestSpecificValues.Tracer);

                        // Clear the volume list
                        CachedDataManager.Items.Remove_Items_In_Title(saveItem.BibID, RequestSpecificValues.Tracer);
                        CachedDataManager.Items.Remove_Items_List(saveItem.BibID, RequestSpecificValues.Tracer);

                        // Also clear the engine
                        SobekEngineClient.Items.Clear_Item_Group_Cache(saveItem.BibID, RequestSpecificValues.Tracer);

                        // Also clear any searches or browses ( in the future could refine this to only remove those
                        // that are impacted by this save... but this is good enough for now )
                        CachedDataManager.Clear_Search_Results_Browses();

                        // Forward differently depending on request
                        switch (hidden_request)
                        {
                            case "save_edit":
                                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.My_Sobek;
                                RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Edit_Item_Metadata;
                                RequestSpecificValues.Current_Mode.VID = saveItem.VID;
                                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                                break;

                            case "save_again":
                                // No redirect, but save values
                                date = saveItem.Bib_Info.Origin_Info.Date_Issued;
                                ipRestrict = saveItem.Behaviors.IP_Restriction_Membership;
                                trackingBox = saveItem.Tracking.Tracking_Box;
                                bornDigital = saveItem.Tracking.Born_Digital;
                                dispositionAdvice = saveItem.Tracking.Disposition_Advice;
                                dispositionAdviceNotes = saveItem.Tracking.Disposition_Advice_Notes;
                                materialRecdDate = saveItem.Tracking.Material_Received_Date;
                                materialRecdNotes = saveItem.Tracking.Material_Received_Notes;
                                if (!hierarchyCopiedFromDate)
                                {
                                    if (saveItem.Behaviors.Serial_Info.Count > 0)
                                    {
                                        level1 = saveItem.Behaviors.Serial_Info[0].Display;
                                        level1Order = saveItem.Behaviors.Serial_Info[0].Order;
                                    }
                                    if (saveItem.Behaviors.Serial_Info.Count > 1)
                                    {
                                        level2 = saveItem.Behaviors.Serial_Info[1].Display;
                                        level2Order = saveItem.Behaviors.Serial_Info[1].Order;
                                    }
                                    if (saveItem.Behaviors.Serial_Info.Count > 2)
                                    {
                                        level3 = saveItem.Behaviors.Serial_Info[2].Display;
                                        level3Order = saveItem.Behaviors.Serial_Info[2].Order;
                                    }
                                }
                                message = message + "<span style=\"color: blue\"><strong>Saved new volume ( " + saveItem.BibID + " : " + saveItem.VID + ")</strong></span>";
                                break;

                            case "save_addfiles":
                                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.My_Sobek;
                                RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.File_Management;
                                RequestSpecificValues.Current_Mode.VID = saveItem.VID;
                                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                                break;

                            default:
                                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
                                RequestSpecificValues.Current_Mode.VID = saveItem.VID;
                                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                                break;
                        }

                    }
                    catch ( Exception ee )
                    {
                        message = message + "<br /><span style=\"color: red\"><strong>EXCEPTION CAUGHT!<br /><br />" + ee.Message + "<br /><br />" + ee.StackTrace.Replace("\n","<br />") + "</strong></span>";

                    }
                }
            }
        }
        /// <summary> Constructor for a new instance of the Edit_Item_Behaviors_MySobekViewer class </summary>
        ///  <param name="RequestSpecificValues"> All the necessary, non-global data specific to the current request </param>
        public Edit_Item_Behaviors_MySobekViewer(RequestCache RequestSpecificValues)
            : base(RequestSpecificValues)
        {
            RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Behaviors_MySobekViewer.Constructor", String.Empty);

            // If the RequestSpecificValues.Current_User cannot edit this RequestSpecificValues.Current_Item, go back
            if (!RequestSpecificValues.Current_User.Can_Edit_This_Item(RequestSpecificValues.Current_Item.BibID, RequestSpecificValues.Current_Item.Bib_Info.SobekCM_Type_String, RequestSpecificValues.Current_Item.Bib_Info.Source.Code, RequestSpecificValues.Current_Item.Bib_Info.HoldingCode, RequestSpecificValues.Current_Item.Behaviors.Aggregation_Code_List))
            {
                RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            const string TEMPLATE_CODE = "itembehaviors";
            completeTemplate = Template_MemoryMgmt_Utility.Retrieve_Template(TEMPLATE_CODE, RequestSpecificValues.Tracer);
            if (completeTemplate != null)
            {
                RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Behaviors_MySobekViewer.Constructor", "Found CompleteTemplate in cache");
            }
            else
            {
                RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Behaviors_MySobekViewer.Constructor", "Reading CompleteTemplate file");

                // Look in the user-defined templates portion first
                string user_template = UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\user\\standard\\" + TEMPLATE_CODE + ".xml";
                if (!File.Exists(user_template))
                    user_template = UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\default\\standard\\" + TEMPLATE_CODE + ".xml";

                // Read this CompleteTemplate
                Template_XML_Reader reader = new Template_XML_Reader();
                completeTemplate = new CompleteTemplate();
                reader.Read_XML(user_template, completeTemplate, true);

                // Add the current codes to this CompleteTemplate
                completeTemplate.Add_Codes(UI_ApplicationCache_Gateway.Aggregations);

                // Save this into the cache
                Template_MemoryMgmt_Utility.Store_Template(TEMPLATE_CODE, completeTemplate, RequestSpecificValues.Tracer);
            }

            // See if there was a hidden request
            string hidden_request = HttpContext.Current.Request.Form["behaviors_request"] ?? String.Empty;

            // If this was a cancel request do that
            if (hidden_request == "cancel")
            {
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
            }
            else if (hidden_request == "save")
            {
                // Changes to the tracking box require the metadata search citation be rebuilt for this RequestSpecificValues.Current_Item
                // so save the old tracking box information first
                string oldTrackingBox = RequestSpecificValues.Current_Item.Tracking.Tracking_Box;

                // Save these changes to bib
                completeTemplate.Save_To_Bib(RequestSpecificValues.Current_Item, RequestSpecificValues.Current_User, 1);

                // Save the behaviors
                SobekCM_Database.Save_Behaviors(RequestSpecificValues.Current_Item, RequestSpecificValues.Current_Item.Behaviors.Text_Searchable, false, false );

                // Save the serial hierarchy as well (sort of a behavior)
                SobekCM_Database.Save_Serial_Hierarchy_Information(RequestSpecificValues.Current_Item, RequestSpecificValues.Current_Item.Web.GroupID, RequestSpecificValues.Current_Item.Web.ItemID);

                // Did the tracking box change?
                if (RequestSpecificValues.Current_Item.Tracking.Tracking_Box != oldTrackingBox)
                {
                    SobekCM_Database.Create_Full_Citation_Value(RequestSpecificValues.Current_Item.Web.ItemID);
                }

                // Remoe from the caches (to replace the other)
                CachedDataManager.Remove_Digital_Resource_Object(RequestSpecificValues.Current_Item.BibID, RequestSpecificValues.Current_Item.VID, RequestSpecificValues.Tracer);

                // Also remove the list of volumes, since this may have changed
                CachedDataManager.Remove_Items_In_Title(RequestSpecificValues.Current_Item.BibID, RequestSpecificValues.Tracer);

                // Forward
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
            }
        }
        /// <summary> Constructor for a new instance of the Edit_Item_Metadata_MySobekViewer class </summary>
        /// <param name="DefaultMetadata"> Default metadata object, if that is how this is being used </param>
        /// <param name="RequestSpecificValues"> All the necessary, non-global data specific to the current request </param>
        public Edit_Item_Metadata_MySobekViewer( SobekCM_Item DefaultMetadata, RequestCache RequestSpecificValues)
            : base(RequestSpecificValues)
        {
            RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", String.Empty);

            popUpFormsHtml = String.Empty;
            delayed_popup = String.Empty;

            // If no user then that is an error
            if ((RequestSpecificValues.Current_User == null) || (!RequestSpecificValues.Current_User.LoggedOn))
            {
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Aggregation;
                RequestSpecificValues.Current_Mode.Aggregation = String.Empty;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // If the default metadata was provided, use that
            if (DefaultMetadata != null)
            {
                currentItem = DefaultMetadata;
            }
            else
            {
                // Ensure BibID and VID provided
                RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "Validate provided bibid / vid");
                if ((String.IsNullOrEmpty(RequestSpecificValues.Current_Mode.BibID)) || (String.IsNullOrEmpty(RequestSpecificValues.Current_Mode.VID)))
                {
                    RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "BibID or VID was not provided!");
                    RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                    RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : BibID/VID missing in item metadata edit request";
                    return;
                }

                // Ensure the item is valid
                RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "Validate bibid/vid exists");
                if (!UI_ApplicationCache_Gateway.Items.Contains_BibID_VID(RequestSpecificValues.Current_Mode.BibID, RequestSpecificValues.Current_Mode.VID))
                {
                    RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "BibID/VID indicated is not valid", Custom_Trace_Type_Enum.Error);
                    RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                    RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : BibID/VID indicated is not valid";
                    return;
                }

                RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "Try to pull this sobek complete item");
                currentItem = SobekEngineClient.Items.Get_Sobek_Item(RequestSpecificValues.Current_Mode.BibID, RequestSpecificValues.Current_Mode.VID, RequestSpecificValues.Current_User.UserID, RequestSpecificValues.Tracer);
                if (currentItem == null)
                {
                    RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "Unable to build complete item");
                    RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                    RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : Unable to build complete item";
                    return;
                }
            }

            // If the RequestSpecificValues.Current_User cannot edit this item, go back
            if (!RequestSpecificValues.Current_User.Can_Edit_This_Item(currentItem.BibID, currentItem.Bib_Info.SobekCM_Type_String, currentItem.Bib_Info.Source.Code, currentItem.Bib_Info.HoldingCode, currentItem.Behaviors.Aggregation_Code_List))
            {
                RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                HttpContext.Current.Response.Redirect(UrlWriterHelper.Redirect_URL(RequestSpecificValues.Current_Mode));
            }

            // Is this a project
            isProject = currentItem.Bib_Info.SobekCM_Type == TypeOfResource_SobekCM_Enum.Project;

            string template_code = RequestSpecificValues.Current_User.Edit_Template_Code_Simple;

            if ((currentItem.Contains_Complex_Content) || (currentItem.Using_Complex_Template))
            {
                template_code = RequestSpecificValues.Current_User.Edit_Template_Code_Complex;
            }
            if (isProject)
            {
                template_code = "standard_project";
                completeTemplate = Template_MemoryMgmt_Utility.Retrieve_Template(template_code, RequestSpecificValues.Tracer);
                if (completeTemplate != null)
                {
                    RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "Found project-specific template in cache");
                }
                else
                {
                    RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "Reading project-specific template file");

                    // Look in the user-defined portion
                    string user_template = UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\user\\standard\\project.xml";
                    if (!File.Exists(user_template))
                        user_template = UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\default\\standard\\project.xml";

                    // Read this CompleteTemplate
                    Template_XML_Reader reader = new Template_XML_Reader();
                    completeTemplate = new CompleteTemplate();
                    reader.Read_XML(user_template, completeTemplate, true);

                    // Save this into the cache
                    Template_MemoryMgmt_Utility.Store_Template(template_code, completeTemplate, RequestSpecificValues.Tracer);
                }
            }
            else
            {
                completeTemplate = Template_MemoryMgmt_Utility.Retrieve_Template(template_code, RequestSpecificValues.Tracer);
                if (completeTemplate != null)
                {
                    RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "Found template in cache");
                }
                else
                {
                    RequestSpecificValues.Tracer.Add_Trace("Edit_Item_Metadata_MySobekViewer.Constructor", "Reading template file");

                    // Look in the user-defined portion
                    string user_template = UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\user\\edit\\" + template_code + ".xml";
                    if (!File.Exists(user_template))
                        user_template = UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\default\\edit\\" + template_code + ".xml";

                    // Read this CompleteTemplate
                    Template_XML_Reader reader = new Template_XML_Reader();
                    completeTemplate = new CompleteTemplate();
                    reader.Read_XML(user_template, completeTemplate, true);
                    if ( completeTemplate != null ) completeTemplate.Build_Final_Adjustment_And_Checks();

                    // Save this into the cache
                    Template_MemoryMgmt_Utility.Store_Template(template_code, completeTemplate, RequestSpecificValues.Tracer);
                }
            }

            // Get the current page number, or default to 1
            page = 1;
            if (!String.IsNullOrEmpty(RequestSpecificValues.Current_Mode.My_Sobek_SubMode))
            {
                if ((RequestSpecificValues.Current_Mode.My_Sobek_SubMode == "preview") || (RequestSpecificValues.Current_Mode.My_Sobek_SubMode == "marc") || (RequestSpecificValues.Current_Mode.My_Sobek_SubMode == "mets"))
                {
                    page = 0;
                }
                else
                {
                    page = 1;
                    bool isNumber = RequestSpecificValues.Current_Mode.My_Sobek_SubMode.All(Char.IsNumber);
                    if (isNumber)
                    {
                        if (isProject)
                            Double.TryParse(RequestSpecificValues.Current_Mode.My_Sobek_SubMode[0].ToString(), out page);
                        else
                            Double.TryParse(RequestSpecificValues.Current_Mode.My_Sobek_SubMode, out page);
                    }
                    else if ( isProject )
                    {
                        if ( Char.IsNumber(RequestSpecificValues.Current_Mode.My_Sobek_SubMode[0]))
                            Double.TryParse(RequestSpecificValues.Current_Mode.My_Sobek_SubMode[0].ToString(), out page);
                    }
                }
            }

            // Handle post backs
            if (RequestSpecificValues.Current_Mode.isPostBack)
            {
                // See if there was a hidden request
                string hidden_request = HttpContext.Current.Request.Form["new_element_requested"] ?? String.Empty;

                // If this was a cancel request do that
                if (hidden_request == "cancel")
                {
                    if (isProject)
                    {
                        CachedDataManager.Remove_Project(RequestSpecificValues.Current_User.UserID, currentItem.BibID, null);

                        RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Administrative;
                        RequestSpecificValues.Current_Mode.Admin_Type = Admin_Type_Enum.Default_Metadata;
                        RequestSpecificValues.Current_Mode.My_Sobek_SubMode = String.Empty;
                        UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                    }
                    else
                    {
                        CachedDataManager.Items.Remove_Digital_Resource_Object(RequestSpecificValues.Current_User.UserID, currentItem.BibID, currentItem.VID, null);

                        // Also clear the engine
                        SobekEngineClient.Items.Clear_Item_Cache(currentItem.BibID, currentItem.VID, RequestSpecificValues.Tracer);

                        RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
                        UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                    }
                    return;
                }

                // Save these changes to bib
                completeTemplate.Save_To_Bib(currentItem, RequestSpecificValues.Current_User, ((int) page));

                // See if the RequestSpecificValues.Current_User asked for a new element of a complex form type
                delayed_popup = String.Empty;
                switch (hidden_request.Trim())
                {
                    case "name":
                        delayed_popup = "name";
                        currentItem.Bib_Info.Add_Named_Entity(String.Empty).Name_Type = Name_Info_Type_Enum.Personal;
                        break;

                    case "title":
                        delayed_popup = "title";
                        currentItem.Bib_Info.Add_Other_Title(String.Empty, Title_Type_Enum.Alternative);
                        break;

                    case "subject":
                        delayed_popup = "subject";
                        currentItem.Bib_Info.Add_Subject();
                        break;

                    case "spatial":
                        delayed_popup = "spatial";
                        currentItem.Bib_Info.Add_Hierarchical_Geographic_Subject();
                        break;

                    case "relateditem":
                        delayed_popup = "relateditem";
                        currentItem.Bib_Info.Add_Related_Item(new Related_Item_Info());
                        break;

                    case "save":
                        Complete_Item_Save();
                        break;

                    case "complicate":
                        currentItem.Using_Complex_Template = true;
                        HttpContext.Current.Response.Redirect( "?" + HttpContext.Current.Request.QueryString, false);
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                        RequestSpecificValues.Current_Mode.Request_Completed = true;
                        return;

                    case "simplify":
                        currentItem.Using_Complex_Template = false;
                        HttpContext.Current.Response.Redirect( "?" + HttpContext.Current.Request.QueryString, false);
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                        RequestSpecificValues.Current_Mode.Request_Completed = true;
                        return;
                }

                // Was this for a new page?
                if (hidden_request.IndexOf("newpage") == 0)
                {
                    string page_requested = hidden_request.Replace("newpage", "");
                    if (page_requested != RequestSpecificValues.Current_Mode.My_Sobek_SubMode)
                    {
                        // forward to requested page
                        RequestSpecificValues.Current_Mode.My_Sobek_SubMode = page_requested;
                        if (RequestSpecificValues.Current_Mode.My_Sobek_SubMode == "0")
                            RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "preview";
                        if (isProject)
                            RequestSpecificValues.Current_Mode.My_Sobek_SubMode = page_requested + currentItem.BibID;

                        HttpContext.Current.Response.Redirect(UrlWriterHelper.Redirect_URL(RequestSpecificValues.Current_Mode) + "#CompleteTemplate", false);
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                        RequestSpecificValues.Current_Mode.Request_Completed = true;
                    }
                }
            }
        }
        /// <summary> Constructor for a new instance of the Mass_Update_Items_MySobekViewer class </summary>
        /// <param name="RequestSpecificValues"> All the necessary, non-global data specific to the current request </param>
        public Mass_Update_Items_MySobekViewer(RequestCache RequestSpecificValues)
            : base(RequestSpecificValues)
        {
            RequestSpecificValues.Tracer.Add_Trace("Mass_Update_Items_MySobekViewer.Constructor", String.Empty);

            // Since this is a mass update, just create a new empty item with the GroupID included
            // from the provided item
            SobekCM_Item emptyItem = new SobekCM_Item {BibID = RequestSpecificValues.Current_Item.BibID};
            emptyItem.Web.GroupID = RequestSpecificValues.Current_Item.Web.GroupID;
            emptyItem.Bib_Info.Source.Code = String.Empty;
            emptyItem.Behaviors.CheckOut_Required_Is_Null = true;
            emptyItem.Behaviors.IP_Restriction_Membership_Is_Null = true;
            emptyItem.Behaviors.Dark_Flag_Is_Null = true;
            item = emptyItem;

            // If the user cannot edit this item, go back
            if (!RequestSpecificValues.Current_User.Can_Edit_This_Item(RequestSpecificValues.Current_Item.BibID, RequestSpecificValues.Current_Item.Bib_Info.SobekCM_Type_String, RequestSpecificValues.Current_Item.Bib_Info.Source.Code, RequestSpecificValues.Current_Item.Bib_Info.HoldingCode, RequestSpecificValues.Current_Item.Behaviors.Aggregation_Code_List))
            {
                RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            const string TEMPLATE_CODE = "massupdate";
            completeTemplate = Template_MemoryMgmt_Utility.Retrieve_Template(TEMPLATE_CODE, RequestSpecificValues.Tracer);
            if (completeTemplate != null)
            {
                RequestSpecificValues.Tracer.Add_Trace("Mass_Update_Items_MySobekViewer.Constructor", "Found CompleteTemplate in cache");
            }
            else
            {
                RequestSpecificValues.Tracer.Add_Trace("Mass_Update_Items_MySobekViewer.Constructor", "Reading CompleteTemplate file");

                // Read this CompleteTemplate
                Template_XML_Reader reader = new Template_XML_Reader();
                completeTemplate = new CompleteTemplate();
                reader.Read_XML(UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\defaults\\" + TEMPLATE_CODE + ".xml", completeTemplate, true);

                // Add the current codes to this CompleteTemplate
                completeTemplate.Add_Codes(UI_ApplicationCache_Gateway.Aggregations);

                // Save this into the cache
                Template_MemoryMgmt_Utility.Store_Template(TEMPLATE_CODE, completeTemplate, RequestSpecificValues.Tracer);
            }

            // See if there was a hidden request
            string hidden_request = HttpContext.Current.Request.Form["behaviors_request"] ?? String.Empty;

            // If this was a cancel request do that
            if (hidden_request == "cancel")
            {
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
            }
            else if (hidden_request == "save")
            {
                // Save these changes to bib
                completeTemplate.Save_To_Bib(item, RequestSpecificValues.Current_User, 1);

                // Save the behaviors
                SobekCM_Database.Save_Behaviors(item, false, true, false );

                // Store on the caches (to replace the other)
                CachedDataManager.Remove_Digital_Resource_Objects(item.BibID, RequestSpecificValues.Tracer);

                // Forward
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
            }
        }
Esempio n. 17
0
        private void process_inputs(XmlNodeReader nodeReader, CompleteTemplate ThisCompleteTemplate, bool exclude_divisions)
        {
            // Keep track of the current pages and panels
            Template_Page  currentPage  = null;
            Template_Panel currentPanel = null;
            bool           inPanel      = false;

            // Read all the nodes
            while (nodeReader.Read())
            {
                // Get the node name, trimmed and to upper
                string nodeName = nodeReader.Name.Trim().ToUpper();

                // If this is the inputs or constant start tag, return
                if (((nodeReader.NodeType == XmlNodeType.EndElement) && (nodeName == "INPUTS")) ||
                    ((nodeReader.NodeType == XmlNodeType.Element) && (nodeReader.Name == "CONSTANTS")))
                {
                    return;
                }

                // If this is the beginning tag for an element, assign the next values accordingly
                if (nodeReader.NodeType == XmlNodeType.Element)
                {
                    // Does this start a new page?
                    if (nodeName == "PAGE")
                    {
                        // Set the inPanel flag to false
                        inPanel = false;

                        // Create the new page and add to this CompleteTemplate
                        currentPage = new Template_Page();
                        ThisCompleteTemplate.Add_Page(currentPage);
                    }

                    // Does this start a new panel?
                    if ((nodeName == "PANEL") && (currentPage != null))
                    {
                        // Set the inPanel flag to true
                        inPanel = true;

                        // Create the new panel and add to the current page
                        currentPanel = new Template_Panel();
                        currentPage.Add_Panel(currentPanel);
                    }

                    // Is this a name element?
                    if ((nodeName == "NAME") && (currentPage != null))
                    {
                        // Get the text
                        string title = read_text_node(nodeReader);

                        // Set the name for either the page or panel
                        if (inPanel)
                        {
                            currentPanel.Title = title;
                        }
                        else
                        {
                            currentPage.Title = title;
                        }
                    }

                    // Is this a name element?
                    if ((nodeName == "INSTRUCTIONS") && (currentPage != null))
                    {
                        // Get the text
                        string instructions = read_text_node(nodeReader);

                        // Set the name for either the page or panel
                        if (!inPanel)
                        {
                            currentPage.Instructions = instructions;
                        }
                    }

                    // Is this a new element?
                    if ((nodeName == "ELEMENT") && (nodeReader.HasAttributes) && (currentPanel != null))
                    {
                        abstract_Element currentElement = process_element(nodeReader, ThisCompleteTemplate.InputPages.Count);
                        if (currentElement != null)
                        {
                            currentPanel.Add_Element(currentElement);
                        }
                    }
                }
            }
        }
        /// <summary> Constructor for a new instance of the New_TEI_MySobekViewer class </summary>
        /// <param name="RequestSpecificValues"> All the necessary, non-global data specific to the current request </param>
        public New_TEI_MySobekViewer(RequestCache RequestSpecificValues)
            : base(RequestSpecificValues)
        {
            RequestSpecificValues.Tracer.Add_Trace("New_TEI_MySobekViewer.Constructor", String.Empty);

            // If the RequestSpecificValues.Current_User cannot submit items, go back
            if (!RequestSpecificValues.Current_User.Can_Submit)
            {
                RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // Ensure the TEI plug-in is enabled
            if ((UI_ApplicationCache_Gateway.Configuration.Extensions == null) ||
                (UI_ApplicationCache_Gateway.Configuration.Extensions.Get_Extension("TEI") == null) ||
                (!UI_ApplicationCache_Gateway.Configuration.Extensions.Get_Extension("TEI").Enabled))
            {
                RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // Ensure this user is enabled to add TEI
            string user_tei_enabled = RequestSpecificValues.Current_User.Get_Setting("TEI.Enabled", "false");
            if (String.Compare(user_tei_enabled, "true", StringComparison.OrdinalIgnoreCase) != 0)
            {
                RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // Determine the in process directory for this
            if (RequestSpecificValues.Current_User.ShibbID.Trim().Length > 0)
                userInProcessDirectory = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.In_Process_Submission_Location, RequestSpecificValues.Current_User.ShibbID + "\\tei");
            else
                userInProcessDirectory = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.In_Process_Submission_Location, RequestSpecificValues.Current_User.UserName.Replace(".", "").Replace("@", "") + "\\tei");

            // Load the CompleteTemplate
            completeTemplate = Template_MemoryMgmt_Utility.Retrieve_Template("tei", RequestSpecificValues.Tracer);
            if (completeTemplate != null)
            {
                RequestSpecificValues.Tracer.Add_Trace("New_TEI_MySobekViewer.Constructor", "Found template in cache");
            }
            else
            {
                RequestSpecificValues.Tracer.Add_Trace("New_TEI_MySobekViewer.Constructor", "Reading template");

                string user_template = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.Application_Server_Network, "plugins\\tei\\templates\\user\\template.xml");
                if (!File.Exists(user_template))
                    user_template = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.Application_Server_Network, "plugins\\tei\\templates\\default\\template.xml");

                // Read this CompleteTemplate
                Template_XML_Reader reader = new Template_XML_Reader();
                completeTemplate = new CompleteTemplate();
                reader.Read_XML(user_template, completeTemplate, true);

                // Save this into the cache
                Template_MemoryMgmt_Utility.Store_Template("tei", completeTemplate, RequestSpecificValues.Tracer);
            }

            // Determine the number of total CompleteTemplate pages
            totalTemplatePages = completeTemplate.InputPages_Count + 3;
            if (completeTemplate.Permissions_Agreement.Length > 0)
                totalTemplatePages++;
            if (completeTemplate.Upload_Types != CompleteTemplate.Template_Upload_Types.None)
                totalTemplatePages++;

            // Determine the title for this CompleteTemplate, or use a default
            toolTitle = completeTemplate.Title;
            if (toolTitle.Length == 0)
                toolTitle = "TEI Submission Tool";

            // Determine the current phase
            currentProcessStep = 1;
            if ((RequestSpecificValues.Current_Mode.My_Sobek_SubMode.Length > 0) && (Char.IsNumber(RequestSpecificValues.Current_Mode.My_Sobek_SubMode[0])))
            {
                Int32.TryParse(RequestSpecificValues.Current_Mode.My_Sobek_SubMode.Substring(0), out currentProcessStep);
            }

            // Load some information from the session
            if ( HttpContext.Current.Session["New_TEI_mySobekViewer.Mapping_File"] != null )
                mapping_file = HttpContext.Current.Session["New_TEI_mySobekViewer.Mapping_File"] as string;
            if ( HttpContext.Current.Session["New_TEI_mySobekViewer.XSLT_File"] != null )
                xslt_file = HttpContext.Current.Session["New_TEI_mySobekViewer.XSLT_File"] as string;
            if ( HttpContext.Current.Session["New_TEI_mySobekViewer.CSS_File"] != null )
                css_file = HttpContext.Current.Session["New_TEI_mySobekViewer.CSS_File"] as string;

            // If this is process step 1 and there is no permissions statement in the CompleteTemplate,
            // just go to step 2
            if ((currentProcessStep == 1) && (completeTemplate.Permissions_Agreement.Length == 0))
            {
                // Delete any pre-existing agreement from an earlier aborted submission process
                if (File.Exists(userInProcessDirectory + "\\agreement.txt"))
                    File.Delete(userInProcessDirectory + "\\agreement.txt");

                // Skip the permissions step
                currentProcessStep = 2;
            }

            // If there is a boundary infraction here, go back to step 2
            if (currentProcessStep < 0)
                currentProcessStep = 2;
            if ((currentProcessStep > completeTemplate.InputPages.Count + 4) && (currentProcessStep != 8) && (currentProcessStep != 9))
                currentProcessStep = 2;

            // Look for the item in the session, then directory, then just create a new one
            if (HttpContext.Current.Session["TEI_Item"] == null)
            {
                // Clear any old files (older than 24 hours) that are in the directory
                if (!Directory.Exists(userInProcessDirectory))
                    Directory.CreateDirectory(userInProcessDirectory);
                else
                {
                    // Anything older than a day should be deleted
                    string[] files = Directory.GetFiles(userInProcessDirectory);
                    foreach (string thisFile in files)
                    {
                        DateTime modifiedDate = ((new FileInfo(thisFile)).LastWriteTime);
                        if (DateTime.Now.Subtract(modifiedDate).TotalHours > (24 * 7))
                        {
                            try
                            {
                                File.Delete(thisFile);
                            }
                            catch (Exception)
                            {
                                // Unable to delete existing file in the RequestSpecificValues.Current_User's folder.
                                // This is an error, but how to report it?
                            }
                        }
                    }
                }

                // First, look for an existing METS file
                string[] existing_mets = Directory.GetFiles(userInProcessDirectory, "*.mets*");
                if (existing_mets.Length > 0)
                {
                    RequestSpecificValues.Tracer.Add_Trace("New_TEI_MySobekViewer.Constructor", "Reading existing METS file<br />(" + existing_mets[0] + ")");
                    item = SobekCM_Item.Read_METS(existing_mets[0]);

                    // Set the visibility information from the CompleteTemplate
                    item.Behaviors.IP_Restriction_Membership = completeTemplate.Default_Visibility;
                }

                // If there is still no item, just create a new one
                if (item == null)
                {
                    // Build a new empty METS file
                    new_item(RequestSpecificValues.Tracer);
                }

                // Save this to the session state now
                HttpContext.Current.Session["Item"] = item;
            }
            else
            {
                RequestSpecificValues.Tracer.Add_Trace("New_TEI_MySobekViewer.Constructor", "Item found in session cache");
                item = (SobekCM_Item)HttpContext.Current.Session["Item"];
            }

            // Find the TEI file
            if (Directory.Exists(userInProcessDirectory))
            {
                string[] tei_files = Directory.GetFiles(userInProcessDirectory, "*.xml");
                if (tei_files.Length > 1)
                {
                    // Two XML files, so delete all but the latest
                    string latest_tei_file = String.Empty;
                    DateTime latest_timestamp = DateTime.MinValue;

                    // Find the latest TEI file
                    foreach (string thisTeiFile in tei_files)
                    {
                        // If this is marc.xml, skip it
                        if ((Path.GetFileName(thisTeiFile).ToLower().IndexOf("marc.xml") >= 0) || (Path.GetFileName(thisTeiFile).ToLower().IndexOf("mets.xml") >= 0))
                            continue;

                        DateTime file_timestamp = File.GetLastWriteTime(thisTeiFile);

                        if (DateTime.Compare(latest_timestamp, file_timestamp) < 0)
                        {
                            latest_tei_file = thisTeiFile;
                            latest_timestamp = file_timestamp;
                        }
                    }

                    // If a latest file as found, delete the others
                    if (!String.IsNullOrEmpty(latest_tei_file))
                    {
                        foreach (string thisTeiFile in tei_files)
                        {
                            // If this is marc.xml, skip it
                            if ((Path.GetFileName(thisTeiFile).ToLower().IndexOf("marc.xml") >= 0) || (Path.GetFileName(thisTeiFile).ToLower().IndexOf("mets.xml") >= 0))
                                continue;

                            // Was this the latest file?
                            if (String.Compare(thisTeiFile, latest_tei_file, StringComparison.OrdinalIgnoreCase) == 0)
                                continue;

                            try
                            {
                                File.Delete(thisTeiFile);
                            }
                            catch { }

                        }
                    }

                    tei_file = latest_tei_file;
                }
                else if (tei_files.Length == 1)
                {
                    tei_file = Path.GetFileName(tei_files[0]);
                }
            }

            #region Special code to handle any uploaded files

            // Any post-processing to do?
            if ((currentProcessStep == 8) && (Directory.Exists(userInProcessDirectory)))
            {
                string[] processFiles = Directory.GetFiles(userInProcessDirectory);
                foreach (string thisFile in processFiles)
                {
                    FileInfo thisFileInfo = new FileInfo(thisFile);
                    if ((thisFileInfo.Extension.ToUpper() == ".TIF") || (thisFileInfo.Extension.ToUpper() == ".TIFF"))
                    {
                        // Is there a JPEG and/or thumbnail?
                        string jpeg = userInProcessDirectory + "\\" + thisFileInfo.Name.Replace(thisFileInfo.Extension, "") + ".jpg";
                        string jpeg_thumbnail = userInProcessDirectory + "\\" + thisFileInfo.Name.Replace(thisFileInfo.Extension, "") + "thm.jpg";

                        // Is one missing?
                        if ((!File.Exists(jpeg)) || (!File.Exists(jpeg_thumbnail)))
                        {
                            using (Image tiffImg = Image.FromFile(thisFile))
                            {
                                try
                                {
                                    var mainImg = ScaleImage(tiffImg, UI_ApplicationCache_Gateway.Settings.Resources.JPEG_Width, UI_ApplicationCache_Gateway.Settings.Resources.JPEG_Height);
                                    mainImg.Save(jpeg, ImageFormat.Jpeg);
                                    mainImg.Dispose();
                                    var thumbnailImg = ScaleImage(tiffImg, 150, 400);
                                    thumbnailImg.Save(jpeg_thumbnail, ImageFormat.Jpeg);
                                    thumbnailImg.Dispose();
                                }
                                catch
                                {

                                }
                                finally
                                {
                                    if (tiffImg != null)
                                        tiffImg.Dispose();
                                }
                            }

                        }
                    }
                }
            }

            #endregion

            #region Handle any other post back requests

            // If this is post-back, handle it
            if (RequestSpecificValues.Current_Mode.isPostBack)
            {
                // If this is a request from stage 8, save the new labels and url first
                if (currentProcessStep == 8)
                {
                    string[] getKeys = HttpContext.Current.Request.Form.AllKeys;
                    string file_name_from_keys = String.Empty;
                    string label_from_keys = String.Empty;
                    foreach (string thisKey in getKeys)
                    {
                        if (thisKey.IndexOf("upload_file") == 0)
                        {
                            file_name_from_keys = HttpContext.Current.Request.Form[thisKey];
                        }
                        if (thisKey.IndexOf("upload_label") == 0)
                        {
                            label_from_keys = HttpContext.Current.Request.Form[thisKey];
                        }
                        if ((file_name_from_keys.Length > 0) && (label_from_keys.Length > 0))
                        {
                            HttpContext.Current.Session["file_" + file_name_from_keys.Trim()] = label_from_keys.Trim();
                            file_name_from_keys = String.Empty;
                            label_from_keys = String.Empty;
                        }

                        if (thisKey == "url_input")
                        {
                            item.Bib_Info.Location.Other_URL = HttpContext.Current.Request.Form[thisKey];
                        }
                    }
                }

                // Was this where the mapping, xslt, and css is set?
                if (currentProcessStep == 3)
                {
                    string[] getKeys = HttpContext.Current.Request.Form.AllKeys;
                    string file_name_from_keys = String.Empty;
                    string label_from_keys = String.Empty;
                    foreach (string thisKey in getKeys)
                    {
                        if (thisKey.IndexOf("mapping_select") == 0)
                        {
                            mapping_file = HttpContext.Current.Request.Form[thisKey];
                            HttpContext.Current.Session["New_TEI_mySobekViewer.Mapping_File"] = mapping_file;
                        }
                        if (thisKey.IndexOf("xslt_select") == 0)
                        {
                            xslt_file = HttpContext.Current.Request.Form[thisKey];
                            HttpContext.Current.Session["New_TEI_mySobekViewer.XSLT_File"] = xslt_file;
                        }
                        if (thisKey.IndexOf("css_select") == 0)
                        {
                            css_file = HttpContext.Current.Request.Form[thisKey];
                            HttpContext.Current.Session["New_TEI_mySobekViewer.CSS_File"] = css_file;
                        }
                    }
                }

                string action = HttpContext.Current.Request.Form["action"];
                if (action == "cancel")
                {
                    // Clear all files in the RequestSpecificValues.Current_User process folder
                    try
                    {
                        string[] all_files = Directory.GetFiles(userInProcessDirectory);
                        foreach (string thisFile in all_files)
                            File.Delete(thisFile);
                        Directory.Delete(userInProcessDirectory);
                    }
                    catch (Exception ee)
                    {
                        tei_file = ee.Message;
                        // Unable to delete existing file in the RequestSpecificValues.Current_User's folder.
                        // This is an error, but how to report it?
                    }

                    // Clear all the information in memory
                    HttpContext.Current.Session["agreement_date"] = null;
                    HttpContext.Current.Session["item"] = null;

                    HttpContext.Current.Session["New_TEI_mySobekViewer.Mapping_File"] = null;
                    HttpContext.Current.Session["New_TEI_mySobekViewer.XSLT_File"] = null;
                    HttpContext.Current.Session["New_TEI_mySobekViewer.CSS_File"] = null;

                    // Clear any temporarily assigned current project and CompleteTemplate
                    RequestSpecificValues.Current_User.Current_Default_Metadata = null;
                    RequestSpecificValues.Current_User.Current_Template = null;

                    // Forward back to my Sobek home
                    RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                }

                if (action == "delete")
                {
                    string filename = HttpContext.Current.Request.Form["phase"];
                    try
                    {
                        if (File.Exists(userInProcessDirectory + "\\" + filename))
                            File.Delete(userInProcessDirectory + "\\" + filename);

                        // Forward
                        UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                        return;
                    }
                    catch (Exception)
                    {
                        // Unable to delete existing file in the RequestSpecificValues.Current_User's folder.
                        // This is an error, but how to report it?
                    }
                }

                if (action == "clear")
                {
                    // If there is an old METS file, delete it
                    if (File.Exists(userInProcessDirectory + "\\TEMP000001_00001.mets"))
                        File.Delete(userInProcessDirectory + "\\TEMP000001_00001.mets");

                    // Create the new METS file and add to the session
                    new_item(null);
                    HttpContext.Current.Session["Item"] = item;

                    // Forward back to the same URL
                    RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "2";
                    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                    return;
                }

                if (action == "next_phase")
                {

                    string next_phase = HttpContext.Current.Request.Form["phase"];

                    // If this goes from step 1 to step 2, write the permissions first
                    if ((currentProcessStep == 1) && (next_phase == "2") && (completeTemplate.Permissions_Agreement.Length > 0))
                    {
                        // Store this agreement in the session state
                        DateTime agreement_date = DateTime.Now;
                        HttpContext.Current.Session["agreement_date"] = agreement_date;

                        // Also, save this as a text file
                        string agreement_file = userInProcessDirectory + "\\agreement.txt";
                        StreamWriter writer = new StreamWriter(agreement_file, false);
                        writer.WriteLine("Permissions Agreement");
                        writer.WriteLine();
                        if (!String.IsNullOrWhiteSpace(RequestSpecificValues.Current_User.ShibbID))
                            writer.WriteLine("User: "******" ( " + RequestSpecificValues.Current_User.ShibbID + " )");
                        else
                            writer.WriteLine("User: "******"Date: " + agreement_date.ToString());
                        writer.WriteLine("IP Address: " + HttpContext.Current.Request.UserHostAddress);
                        writer.WriteLine();
                        writer.WriteLine(completeTemplate.Permissions_Agreement);
                        writer.Flush();
                        writer.Close();

                        if (HttpContext.Current.Request.Form["setNewDefaultCheckBox"] != null)
                        {
                            // Set the default metadata preference first
                            string prefProject = HttpContext.Current.Request.Form["prefProject"];
                            if (!String.IsNullOrEmpty(prefProject))
                                RequestSpecificValues.Current_User.Set_Current_Default_Metadata(prefProject.Trim());

                            // Set the template code next
                            string prefTemplate = HttpContext.Current.Request.Form["prefTemplate"];
                            if (!String.IsNullOrEmpty(prefTemplate))
                                RequestSpecificValues.Current_User.Set_Default_Template(prefTemplate.Trim());

                            // Save the user preferences
                            SobekCM_Database.Save_User(RequestSpecificValues.Current_User, String.Empty, RequestSpecificValues.Current_User.Authentication_Type, RequestSpecificValues.Tracer);
                        }
                    }

                    // If this goes from step 2 (upload TEI) to step 3, validate the TEI XML file
                    if ((currentProcessStep == 2) && (next_phase == "3"))
                    {
                        // Should be a TEI file to continue
                        if (!String.IsNullOrEmpty(tei_file))
                        {
                            XmlValidator validator = new XmlValidator();
                            string tei_filepath = Path.Combine(userInProcessDirectory, tei_file);
                            bool isValid = validator.IsValid(tei_filepath);
                            if (!isValid)
                            {
                                string validatorErrors = validator.Errors.Replace("\n", "<br />\n");
                                error_message = "Uploaded TEI file is not a valid XML source file.<br /><br />\n" + validatorErrors + "<br />";
                                next_phase = "2";
                            }
                        }
                    }

                    // If this is going from a step that includes the metadata entry portion, save this to the item
                    if ((currentProcessStep > 4) && (currentProcessStep < 8))
                    {
                        // Save to the item
                        completeTemplate.Save_To_Bib(item, RequestSpecificValues.Current_User, currentProcessStep - 4);
                        item.Save_METS();
                        HttpContext.Current.Session["Item"] = item;

                        // Save the pertinent data to the METS file package
                        item.METS_Header.Create_Date = DateTime.Now;
                        if ((HttpContext.Current.Session["agreement_date"] != null) && (HttpContext.Current.Session["agreement_date"].ToString().Length > 0))
                        {
                            DateTime asDateTime;
                            if (DateTime.TryParse(HttpContext.Current.Session["agreement_date"].ToString(), out asDateTime))
                                item.METS_Header.Create_Date = asDateTime;
                        }
                        HttpContext.Current.Session["Item"] = item;

                        // Save this item, just in case it gets lost somehow
                        item.Source_Directory = userInProcessDirectory;
                        string acquisition_append = "Submitted by " + RequestSpecificValues.Current_User.Full_Name + ".";
                        if (item.Bib_Info.Notes_Count > 0)
                        {
                            foreach (Note_Info thisNote in item.Bib_Info.Notes.Where(ThisNote => ThisNote.Note_Type == Note_Type_Enum.Acquisition))
                            {
                                if (thisNote.Note.IndexOf(acquisition_append) < 0)
                                    thisNote.Note = thisNote.Note.Trim() + "  " + acquisition_append;
                                break;
                            }
                        }

                        // Also, check all the authors to add the current users attribution information
                        if (RequestSpecificValues.Current_User.Organization.Length > 0)
                        {
                            if ((item.Bib_Info.Main_Entity_Name.Full_Name.IndexOf(RequestSpecificValues.Current_User.Family_Name) >= 0) && ((item.Bib_Info.Main_Entity_Name.Full_Name.IndexOf(RequestSpecificValues.Current_User.Given_Name) >= 0) || ((RequestSpecificValues.Current_User.Nickname.Length > 2) && (item.Bib_Info.Main_Entity_Name.Full_Name.IndexOf(RequestSpecificValues.Current_User.Nickname) > 0))))
                            {
                                item.Bib_Info.Main_Entity_Name.Affiliation = RequestSpecificValues.Current_User.Organization;
                                if (RequestSpecificValues.Current_User.College.Length > 0)
                                    item.Bib_Info.Main_Entity_Name.Affiliation = item.Bib_Info.Main_Entity_Name.Affiliation + " -- " + RequestSpecificValues.Current_User.College;
                                if (RequestSpecificValues.Current_User.Department.Length > 0)
                                    item.Bib_Info.Main_Entity_Name.Affiliation = item.Bib_Info.Main_Entity_Name.Affiliation + " -- " + RequestSpecificValues.Current_User.Department;
                                if (RequestSpecificValues.Current_User.Unit.Length > 0)
                                    item.Bib_Info.Main_Entity_Name.Affiliation = item.Bib_Info.Main_Entity_Name.Affiliation + " -- " + RequestSpecificValues.Current_User.Unit;
                            }
                            if (item.Bib_Info.Names_Count > 0)
                            {
                                foreach (Name_Info thisName in item.Bib_Info.Names)
                                {
                                    if ((thisName.Full_Name.IndexOf(RequestSpecificValues.Current_User.Family_Name) >= 0) && ((thisName.Full_Name.IndexOf(RequestSpecificValues.Current_User.Given_Name) >= 0) || ((RequestSpecificValues.Current_User.Nickname.Length > 2) && (thisName.Full_Name.IndexOf(RequestSpecificValues.Current_User.Nickname) > 0))))
                                    {
                                        thisName.Affiliation = RequestSpecificValues.Current_User.Organization;
                                        if (RequestSpecificValues.Current_User.College.Length > 0)
                                            thisName.Affiliation = thisName.Affiliation + " -- " + RequestSpecificValues.Current_User.College;
                                        if (RequestSpecificValues.Current_User.Department.Length > 0)
                                            thisName.Affiliation = thisName.Affiliation + " -- " + RequestSpecificValues.Current_User.Department;
                                        if (RequestSpecificValues.Current_User.Unit.Length > 0)
                                            thisName.Affiliation = thisName.Affiliation + " -- " + RequestSpecificValues.Current_User.Unit;

                                    }
                                }
                            }
                        }
                        item.Save_METS();
                        HttpContext.Current.Session["Item"] = item;
                    }

                    // For now, just forward to the next phase
                    if (currentProcessStep.ToString() != next_phase)
                    {
                        RequestSpecificValues.Current_Mode.My_Sobek_SubMode = next_phase;
                        UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                        return;
                    }
                }
            }

            #endregion

            #region Perform some validation to determine if the RequestSpecificValues.Current_User should be at this step

            // If this is past the agreement phase, check that an agreement exists
            if (currentProcessStep > 1)
            {
                // Validate that an agreement.txt file exists, if the CompleteTemplate has permissions
                if ((completeTemplate.Permissions_Agreement.Length > 0) && (!File.Exists(userInProcessDirectory + "\\agreement.txt")))
                {
                    RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "1";
                    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                    return;
                }

                // Get the validation errors
                validationErrors = new List<string>();
                SobekCM_Item_Validator.Validate_SobekCM_Item(item, validationErrors);
            }

            // If this is past the step to upload a TEI file, ensure a TEI file exists
            if ((currentProcessStep > 2) && (String.IsNullOrEmpty(tei_file)))
            {
                RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "2";
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // If this is past the step to upload a TEI file, ensure a TEI file exists
            if ((currentProcessStep > 3) && ((String.IsNullOrEmpty(mapping_file)) || (String.IsNullOrEmpty(xslt_file))))
            {
                RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "3";
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // If this is to put up items or complete the item, validate the METS
            if (currentProcessStep >= 8)
            {
                // Validate that a METS file exists
                if (Directory.GetFiles(userInProcessDirectory, "*.mets*").Length == 0)
                {
                    RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "2";
                    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                    return;
                }

                // Get the validation errors
                if (validationErrors.Count == 0)
                    item.Save_METS();
                else
                {
                    item.Web.Show_Validation_Errors = true;
                    RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "2";
                    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                    return;
                }
            }

            // If this is for step 8, ensure that this even takes this information, or go to step 9
            if ((currentProcessStep == 8) && (completeTemplate.Upload_Types == CompleteTemplate.Template_Upload_Types.None))
            {
                RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "9";
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // If this is going into the last process step, check that any mandatory info (file, url, .. )
            // from the last step is present
            if (currentProcessStep == 9)
            {
                // Complete the item submission
                complete_item_submission(item, RequestSpecificValues.Tracer);
            }

            #endregion
        }
        /// <summary> Constructor for a new instance of the Mass_Update_Items_MySobekViewer class </summary>
        /// <param name="RequestSpecificValues"> All the necessary, non-global data specific to the current request </param>
        public Mass_Update_Items_MySobekViewer(RequestCache RequestSpecificValues)
            : base(RequestSpecificValues)
        {
            RequestSpecificValues.Tracer.Add_Trace("Mass_Update_Items_MySobekViewer.Constructor", String.Empty);

            // If no user then that is an error
            if ((RequestSpecificValues.Current_User == null) || (!RequestSpecificValues.Current_User.LoggedOn))
            {
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Aggregation;
                RequestSpecificValues.Current_Mode.Aggregation = String.Empty;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // Ensure BibID provided
            RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "Validate provided bibid");
            if (String.IsNullOrEmpty(RequestSpecificValues.Current_Mode.BibID))
            {
                RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "BibID was not provided!");
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : BibID missing in item group metadata edit request";
                return;
            }

            // Ensure the item is valid
            RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "Validate bibid exists");
            if (!UI_ApplicationCache_Gateway.Items.Contains_BibID(RequestSpecificValues.Current_Mode.BibID))
            {
                RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "BibID indicated is not valid", Custom_Trace_Type_Enum.Error);
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : BibID indicated is not valid";
                return;
            }

            RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "Try to pull this sobek complete item group");
            SobekCM_Item currentItem = SobekEngineClient.Items.Get_Sobek_Item_Group(RequestSpecificValues.Current_Mode.BibID, RequestSpecificValues.Tracer);
            if (currentItem == null)
            {
                RequestSpecificValues.Tracer.Add_Trace("Group_Add_Volume_MySobekViewer.Constructor", "Unable to build complete item group");
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
                RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : Unable to build complete item";
                return;
            }

            // Since this is a mass update, just create a new empty item with the GroupID included
            // from the provided item
            SobekCM_Item emptyItem = new SobekCM_Item {BibID = currentItem.BibID};
            emptyItem.Web.GroupID = currentItem.Web.GroupID;
            emptyItem.Bib_Info.Source.Code = String.Empty;
            emptyItem.Behaviors.CheckOut_Required_Is_Null = true;
            emptyItem.Behaviors.IP_Restriction_Membership_Is_Null = true;
            emptyItem.Behaviors.Dark_Flag_Is_Null = true;
            item = emptyItem;

            // If the user cannot edit this item, go back
            if (!RequestSpecificValues.Current_User.Can_Edit_This_Item(currentItem.BibID, currentItem.Bib_Info.SobekCM_Type_String, currentItem.Bib_Info.Source.Code, currentItem.Bib_Info.HoldingCode, currentItem.Behaviors.Aggregation_Code_List))
            {
                RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            const string TEMPLATE_CODE = "massupdate";
            completeTemplate = Template_MemoryMgmt_Utility.Retrieve_Template(TEMPLATE_CODE, RequestSpecificValues.Tracer);
            if (completeTemplate != null)
            {
                RequestSpecificValues.Tracer.Add_Trace("Mass_Update_Items_MySobekViewer.Constructor", "Found CompleteTemplate in cache");
            }
            else
            {
                RequestSpecificValues.Tracer.Add_Trace("Mass_Update_Items_MySobekViewer.Constructor", "Reading CompleteTemplate file");

                // Read this CompleteTemplate
                Template_XML_Reader reader = new Template_XML_Reader();
                completeTemplate = new CompleteTemplate();
                reader.Read_XML(UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\default\\standard\\" + TEMPLATE_CODE + ".xml", completeTemplate, true);

                // Save this into the cache
                Template_MemoryMgmt_Utility.Store_Template(TEMPLATE_CODE, completeTemplate, RequestSpecificValues.Tracer);
            }

            // See if there was a hidden request
            string hidden_request = HttpContext.Current.Request.Form["behaviors_request"] ?? String.Empty;

            // If this was a cancel request do that
            if (hidden_request == "cancel")
            {
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
            }
            else if (hidden_request == "save")
            {
                // Save these changes to bib
                completeTemplate.Save_To_Bib(item, RequestSpecificValues.Current_User, 1);

                // Save the behaviors
                SobekCM_Item_Database.Save_Behaviors(item, false, true, false );

                // Store on the caches (to replace the other)
                CachedDataManager.Items.Remove_Digital_Resource_Objects(item.BibID, RequestSpecificValues.Tracer);

                // Forward
                RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
            }
        }
        /// <summary> Constructor for a new instance of the New_Group_And_Item_MySobekViewer class </summary>
        /// <param name="RequestSpecificValues"> All the necessary, non-global data specific to the current request </param>
        public New_Group_And_Item_MySobekViewer(RequestCache RequestSpecificValues)
            : base(RequestSpecificValues)
        {
            RequestSpecificValues.Tracer.Add_Trace("New_Group_And_Item_MySobekViewer.Constructor", String.Empty);

            // If the RequestSpecificValues.Current_User cannot submit items, go back
            if (!RequestSpecificValues.Current_User.Can_Submit)
            {
                RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // Determine the in process directory for this
            if (RequestSpecificValues.Current_User.ShibbID.Trim().Length > 0)
                userInProcessDirectory = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.In_Process_Submission_Location, RequestSpecificValues.Current_User.ShibbID + "\\newgroup");
            else
                userInProcessDirectory = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.In_Process_Submission_Location, RequestSpecificValues.Current_User.UserName.Replace(".","").Replace("@","") + "\\newgroup");

            // Handle postback for changing the CompleteTemplate or project
            templateCode = RequestSpecificValues.Current_User.Current_Template;
            if (RequestSpecificValues.Current_Mode.isPostBack)
            {
                string action1 = HttpContext.Current.Request.Form["action"];
                if ((action1 != null) && ((action1 == "template") || (action1 == "project")))
                {
                    string newvalue = HttpContext.Current.Request.Form["phase"];
                    if ((action1 == "template") && ( newvalue != templateCode ))
                    {
                        RequestSpecificValues.Current_User.Current_Template = newvalue;
                        templateCode = RequestSpecificValues.Current_User.Current_Template;
                        if (File.Exists(userInProcessDirectory + "\\agreement.txt"))
                            File.Delete(userInProcessDirectory + "\\agreement.txt");
                    }
                    if ((action1 == "project") && (newvalue != RequestSpecificValues.Current_User.Current_Default_Metadata))
                    {
                        RequestSpecificValues.Current_User.Current_Default_Metadata = newvalue;
                    }
                    HttpContext.Current.Session["item"] = null;
                }
            }

            // Load the CompleteTemplate
            templateCode = RequestSpecificValues.Current_User.Current_Template;
            completeTemplate = Template_MemoryMgmt_Utility.Retrieve_Template(templateCode, RequestSpecificValues.Tracer);
            if ( completeTemplate != null )
            {
                RequestSpecificValues.Tracer.Add_Trace("New_Group_And_Item_MySobekViewer.Constructor", "Found template in cache");
            }
            else
            {
                RequestSpecificValues.Tracer.Add_Trace("New_Group_And_Item_MySobekViewer.Constructor", "Reading template");

                // Look in the user-defined templates portion first
                string user_template = UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\user\\" + templateCode + ".xml";
                if (!File.Exists(user_template))
                    user_template = UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\default\\" + templateCode + ".xml";

                // Read this CompleteTemplate
                Template_XML_Reader reader = new Template_XML_Reader();
                completeTemplate = new CompleteTemplate();
                reader.Read_XML(user_template, completeTemplate, true);

                // Add the current codes to this CompleteTemplate
                completeTemplate.Add_Codes(UI_ApplicationCache_Gateway.Aggregations);

                // Save this into the cache
                Template_MemoryMgmt_Utility.Store_Template(templateCode, completeTemplate, RequestSpecificValues.Tracer);
            }

            // Determine the number of total CompleteTemplate pages
            totalTemplatePages = completeTemplate.InputPages_Count;
            if (completeTemplate.Permissions_Agreement.Length > 0)
                totalTemplatePages++;
            if (completeTemplate.Upload_Types != CompleteTemplate.Template_Upload_Types.None)
                totalTemplatePages++;

            // Determine the title for this CompleteTemplate, or use a default
            toolTitle = completeTemplate.Title;
            if (toolTitle.Length == 0)
                toolTitle = "Self-Submittal Tool";

            // Determine the current phase
            currentProcessStep = 1;
            if ((RequestSpecificValues.Current_Mode.My_Sobek_SubMode.Length > 0) && (Char.IsNumber(RequestSpecificValues.Current_Mode.My_Sobek_SubMode[0])))
            {
                Int32.TryParse(RequestSpecificValues.Current_Mode.My_Sobek_SubMode.Substring(0), out currentProcessStep);
            }

            // If this is process step 1 and there is no permissions statement in the CompleteTemplate,
            // just go to step 2
            if ((currentProcessStep == 1) && (completeTemplate.Permissions_Agreement.Length == 0))
            {
                // Delete any pre-existing agreement from an earlier aborted submission process
                if (File.Exists(userInProcessDirectory + "\\agreement.txt"))
                    File.Delete(userInProcessDirectory + "\\agreement.txt");

                // Skip the permissions step
                currentProcessStep = 2;
            }

            // If there is a boundary infraction here, go back to step 2
            if (currentProcessStep < 0)
                currentProcessStep = 2;
            if ((currentProcessStep > completeTemplate.InputPages.Count + 1 ) && ( currentProcessStep != 8 ) && ( currentProcessStep != 9 ))
                currentProcessStep = 2;

            // If this is to enter a file or URL, and the CompleteTemplate does not include this, skip over this step
            if (( currentProcessStep == 8 ) && ( completeTemplate.Upload_Types == CompleteTemplate.Template_Upload_Types.None ))
            {
                // For now, just forward to the next phase
                RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "9";
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // Look for the item in the session, then directory, then just create a new one
            if (HttpContext.Current.Session["Item"] == null)
            {
                // Clear any old files (older than 24 hours) that are in the directory
                if (!Directory.Exists(userInProcessDirectory))
                    Directory.CreateDirectory(userInProcessDirectory);
                else
                {
                    // Anything older than a day should be deleted
                    string[] files = Directory.GetFiles(userInProcessDirectory);
                    foreach (string thisFile in files)
                    {
                        DateTime modifiedDate = ((new FileInfo(thisFile)).LastWriteTime);
                        if (DateTime.Now.Subtract(modifiedDate).TotalHours > (24 * 7))
                        {
                            try
                            {
                                File.Delete(thisFile);
                            }
                            catch(Exception )
                            {
                                // Unable to delete existing file in the RequestSpecificValues.Current_User's folder.
                                // This is an error, but how to report it?
                            }
                        }
                    }
                }

                // First, look for an existing METS file
                string[] existing_mets = Directory.GetFiles(userInProcessDirectory, "*.mets*");
                if (existing_mets.Length > 0)
                {
                    RequestSpecificValues.Tracer.Add_Trace("New_Group_And_Item_MySobekViewer.Constructor", "Reading existing METS file<br />(" + existing_mets[0] + ")");
                    item = SobekCM_Item.Read_METS(existing_mets[0]);

                    // Set the visibility information from the CompleteTemplate
                    item.Behaviors.IP_Restriction_Membership = completeTemplate.Default_Visibility;
                }

                // If there is still no item, just create a new one
                if (item == null)
                {
                    // Build a new empty METS file
                    new_item(RequestSpecificValues.Tracer);
                }

                // Save this to the session state now
                HttpContext.Current.Session["Item"] = item;
            }
            else
            {
                RequestSpecificValues.Tracer.Add_Trace("New_Group_And_Item_MySobekViewer.Constructor", "Item found in session cache");
                item = (SobekCM_Item)HttpContext.Current.Session["Item"];
            }

            #region Special code to handle any uploaded files

            // Any post-processing to do?
            if ((currentProcessStep == 8) && (Directory.Exists(userInProcessDirectory)))
            {
                string[] processFiles = Directory.GetFiles(userInProcessDirectory);
                foreach (string thisFile in processFiles)
                {
                    FileInfo thisFileInfo = new FileInfo(thisFile);
                    if ((thisFileInfo.Extension.ToUpper() == ".TIF") || (thisFileInfo.Extension.ToUpper() == ".TIFF"))
                    {
                        // Is there a JPEG and/or thumbnail?
                        string jpeg = userInProcessDirectory + "\\" + thisFileInfo.Name.Replace(thisFileInfo.Extension, "") + ".jpg";
                        string jpeg_thumbnail = userInProcessDirectory + "\\" + thisFileInfo.Name.Replace(thisFileInfo.Extension, "") + "thm.jpg";

                        // Is one missing?
                        if ((!File.Exists(jpeg)) || (!File.Exists(jpeg_thumbnail)))
                        {
                            using (Image tiffImg = Image.FromFile(thisFile))
                            {
                                try
                                {
                                    var mainImg = ScaleImage(tiffImg, UI_ApplicationCache_Gateway.Settings.Resources.JPEG_Width, UI_ApplicationCache_Gateway.Settings.Resources.JPEG_Height);
                                    mainImg.Save(jpeg, ImageFormat.Jpeg);
                                    mainImg.Dispose();
                                    var thumbnailImg = ScaleImage(tiffImg, 150, 400);
                                    thumbnailImg.Save(jpeg_thumbnail, ImageFormat.Jpeg);
                                    thumbnailImg.Dispose();
                                }
                                catch
                                {

                                }
                                finally
                                {
                                    if ( tiffImg != null )
                                        tiffImg.Dispose();
                                }
                            }

                        }
                    }
                }
            }

            #endregion

            #region Handle any other post back requests

            // If this is post-back, handle it
            if (RequestSpecificValues.Current_Mode.isPostBack)
            {
                // If this is a request from stage 8, save the new labels and url first
                if (currentProcessStep == 8)
                {
                    string[] getKeys = HttpContext.Current.Request.Form.AllKeys;
                    string file_name_from_keys = String.Empty;
                    string label_from_keys = String.Empty;
                    foreach (string thisKey in getKeys)
                    {
                        if (thisKey.IndexOf("upload_file") == 0)
                        {
                            file_name_from_keys = HttpContext.Current.Request.Form[thisKey];
                        }
                        if (thisKey.IndexOf("upload_label") == 0)
                        {
                            label_from_keys = HttpContext.Current.Request.Form[thisKey];
                        }
                        if ((file_name_from_keys.Length > 0) && (label_from_keys.Length > 0))
                        {
                            HttpContext.Current.Session["file_" + file_name_from_keys.Trim()] = label_from_keys.Trim();
                            file_name_from_keys = String.Empty;
                            label_from_keys = String.Empty;
                        }

                        if (thisKey == "url_input")
                        {
                            item.Bib_Info.Location.Other_URL = HttpContext.Current.Request.Form[thisKey];
                        }
                    }
                }

                string action = HttpContext.Current.Request.Form["action"];
                if (action == "cancel")
                {
                    // Clear all files in the RequestSpecificValues.Current_User process folder
                    try
                    {
                        string[] all_files = Directory.GetFiles(userInProcessDirectory);
                        foreach (string thisFile in all_files)
                            Directory.Delete(thisFile);
                        Directory.Delete(userInProcessDirectory);
                    }
                    catch (Exception)
                    {
                        // Unable to delete existing file in the RequestSpecificValues.Current_User's folder.
                        // This is an error, but how to report it?
                    }

                    // Clear all the information in memory
                    HttpContext.Current.Session["agreement_date"] = null;
                    HttpContext.Current.Session["item"] = null;

                    // Clear any temporarily assigned current project and CompleteTemplate
                    RequestSpecificValues.Current_User.Current_Default_Metadata = null;
                    RequestSpecificValues.Current_User.Current_Template = null;

                    // Forward back to my Sobek home
                    RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                }

                if ( action == "delete" )
                {
                    string filename = HttpContext.Current.Request.Form["phase"];
                    try
                    {
                        if (File.Exists(userInProcessDirectory + "\\" + filename))
                            File.Delete(userInProcessDirectory + "\\" + filename);

                        // Forward
                        UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                        return;
                    }
                    catch (Exception)
                    {
                        // Unable to delete existing file in the RequestSpecificValues.Current_User's folder.
                        // This is an error, but how to report it?
                    }
                }

                if (action == "clear")
                {
                    // If there is an old METS file, delete it
                    if (File.Exists(userInProcessDirectory + "\\TEMP000001_00001.mets"))
                        File.Delete(userInProcessDirectory + "\\TEMP000001_00001.mets");

                    // Create the new METS file and add to the session
                    new_item(null);
                    HttpContext.Current.Session["Item"] = item;

                    // Forward back to the same URL
                    RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "2";
                    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                    return;
                }

                if (action == "next_phase")
                {

                    string next_phase = HttpContext.Current.Request.Form["phase"];

                    // If this goes from step 1 to step 2, write the permissions first
                    if ((currentProcessStep == 1) && (next_phase == "2") && ( completeTemplate.Permissions_Agreement.Length > 0 ))
                    {
                        // Store this agreement in the session state
                        DateTime agreement_date = DateTime.Now;
                        HttpContext.Current.Session["agreement_date"] = agreement_date;

                        // Also, save this as a text file
                        string agreement_file = userInProcessDirectory + "\\agreement.txt";
                        StreamWriter writer = new StreamWriter(agreement_file, false);
                        writer.WriteLine("Permissions Agreement");
                        writer.WriteLine();
                        if ( !String.IsNullOrWhiteSpace(RequestSpecificValues.Current_User.ShibbID))
                            writer.WriteLine("User: "******" ( " + RequestSpecificValues.Current_User.ShibbID + " )");
                        else
                            writer.WriteLine("User: "******"Date: " + agreement_date.ToString());
                        writer.WriteLine("IP Address: " + HttpContext.Current.Request.UserHostAddress);
                        writer.WriteLine();
                        writer.WriteLine(completeTemplate.Permissions_Agreement);
                        writer.Flush();
                        writer.Close();

                        if (HttpContext.Current.Request.Form["setNewDefaultCheckBox"] != null )
                        {
                            string prefProject = HttpContext.Current.Request.Form["prefProject"];
                            string prefTemplate = HttpContext.Current.Request.Form["prefTemplate"];
                            RequestSpecificValues.Current_User.Set_Default_Template(prefTemplate.Trim());
                            RequestSpecificValues.Current_User.Set_Current_Default_Metadata(prefProject.Trim());
                            SobekCM_Database.Save_User(RequestSpecificValues.Current_User, String.Empty, RequestSpecificValues.Current_User.Authentication_Type, RequestSpecificValues.Tracer);
                        }
                    }

                    // If this is going from a step that includes the metadata entry portion, save this to the item
                    if ((currentProcessStep > 1) && (currentProcessStep < 8))
                    {
                        // Save to the item
                        completeTemplate.Save_To_Bib(item, RequestSpecificValues.Current_User, currentProcessStep - 1);
                        item.Save_METS();
                        HttpContext.Current.Session["Item"] = item;

                        // Save the pertinent data to the METS file package
                        item.METS_Header.Create_Date = DateTime.Now;
                        if ((HttpContext.Current.Session["agreement_date"] != null) && (HttpContext.Current.Session["agreement_date"].ToString().Length > 0))
                        {
                            DateTime asDateTime;
                            if (DateTime.TryParse(HttpContext.Current.Session["agreement_date"].ToString(), out asDateTime))
                                item.METS_Header.Create_Date = asDateTime;
                        }
                        HttpContext.Current.Session["Item"] = item;

                        // Save this item, just in case it gets lost somehow
                        item.Source_Directory = userInProcessDirectory;
                        string acquisition_append = "Submitted by " + RequestSpecificValues.Current_User.Full_Name + ".";
                        if (item.Bib_Info.Notes_Count > 0)
                        {
                            foreach (Note_Info thisNote in item.Bib_Info.Notes.Where(ThisNote => ThisNote.Note_Type == Note_Type_Enum.Acquisition))
                            {
                                if (thisNote.Note.IndexOf(acquisition_append) < 0)
                                    thisNote.Note = thisNote.Note.Trim() + "  " + acquisition_append;
                                break;
                            }
                        }

                        // Also, check all the authors to add the current users attribution information
                        if (RequestSpecificValues.Current_User.Organization.Length > 0)
                        {
                            if ((item.Bib_Info.Main_Entity_Name.Full_Name.IndexOf(RequestSpecificValues.Current_User.Family_Name) >= 0) && ((item.Bib_Info.Main_Entity_Name.Full_Name.IndexOf(RequestSpecificValues.Current_User.Given_Name) >= 0) || ((RequestSpecificValues.Current_User.Nickname.Length > 2) && (item.Bib_Info.Main_Entity_Name.Full_Name.IndexOf(RequestSpecificValues.Current_User.Nickname) > 0))))
                            {
                                item.Bib_Info.Main_Entity_Name.Affiliation = RequestSpecificValues.Current_User.Organization;
                                if (RequestSpecificValues.Current_User.College.Length > 0)
                                    item.Bib_Info.Main_Entity_Name.Affiliation = item.Bib_Info.Main_Entity_Name.Affiliation + " -- " + RequestSpecificValues.Current_User.College;
                                if (RequestSpecificValues.Current_User.Department.Length > 0)
                                    item.Bib_Info.Main_Entity_Name.Affiliation = item.Bib_Info.Main_Entity_Name.Affiliation + " -- " + RequestSpecificValues.Current_User.Department;
                                if (RequestSpecificValues.Current_User.Unit.Length > 0)
                                    item.Bib_Info.Main_Entity_Name.Affiliation = item.Bib_Info.Main_Entity_Name.Affiliation + " -- " + RequestSpecificValues.Current_User.Unit;
                            }
                            if (item.Bib_Info.Names_Count > 0)
                            {
                                foreach (Name_Info thisName in item.Bib_Info.Names)
                                {
                                    if ((thisName.Full_Name.IndexOf(RequestSpecificValues.Current_User.Family_Name) >= 0) && ((thisName.Full_Name.IndexOf(RequestSpecificValues.Current_User.Given_Name) >= 0) || ((RequestSpecificValues.Current_User.Nickname.Length > 2) && (thisName.Full_Name.IndexOf(RequestSpecificValues.Current_User.Nickname) > 0))))
                                    {
                                        thisName.Affiliation = RequestSpecificValues.Current_User.Organization;
                                        if (RequestSpecificValues.Current_User.College.Length > 0)
                                            thisName.Affiliation = thisName.Affiliation + " -- " + RequestSpecificValues.Current_User.College;
                                        if (RequestSpecificValues.Current_User.Department.Length > 0)
                                            thisName.Affiliation = thisName.Affiliation + " -- " + RequestSpecificValues.Current_User.Department;
                                        if (RequestSpecificValues.Current_User.Unit.Length > 0)
                                            thisName.Affiliation = thisName.Affiliation + " -- " + RequestSpecificValues.Current_User.Unit;

                                    }
                                }
                            }
                        }
                        item.Save_METS();
                        HttpContext.Current.Session["Item"] = item;
                    }

                    // For now, just forward to the next phase
                    RequestSpecificValues.Current_Mode.My_Sobek_SubMode = next_phase;
                    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                    return;
                }
            }

            #endregion

            #region Perform some validation to determine if the RequestSpecificValues.Current_User should be at this step

            // If this is past the agreement phase, check that an agreement exists
            if (currentProcessStep > 1)
            {
                // Validate that an agreement.txt file exists, if the CompleteTemplate has permissions
                if (( completeTemplate.Permissions_Agreement.Length > 0 ) && (!File.Exists(userInProcessDirectory + "\\agreement.txt")))
                {
                    RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "1";
                    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                    return;
                }

                // Get the validation errors
                validationErrors = new List<string>();
                SobekCM_Item_Validator.Validate_SobekCM_Item(item, validationErrors);
            }

            // If this is to put up items or complete the item, validate the METS
            if ( currentProcessStep >= 8 )
            {
                // Validate that a METS file exists
                if (Directory.GetFiles( userInProcessDirectory, "*.mets*").Length == 0 )
                {
                    RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "2";
                    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                    return;
                }

                // Get the validation errors
                if ( validationErrors.Count == 0 )
                    item.Save_METS();
                else
                {
                    item.Web.Show_Validation_Errors = true;
                    RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "2";
                    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                    return;
                }
            }

            // If this is for step 8, ensure that this even takes this information, or go to step 9
            if (( currentProcessStep == 8 ) && ( completeTemplate.Upload_Types == CompleteTemplate.Template_Upload_Types.None ))
            {
                RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "9";
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // If this is going into the last process step, check that any mandatory info (file, url, .. )
            // from the last step is present
            if ( currentProcessStep == 9 )
            {
                // Only check if this is mandatory
                if (( completeTemplate.Upload_Mandatory ) && ( completeTemplate.Upload_Types != CompleteTemplate.Template_Upload_Types.None ))
                {
                    // Does this require either a FILE or URL?
                    bool required_file_present = false;
                    bool required_url_present = false;

                    // If this accepts files, check for acceptable files
                    if (( completeTemplate.Upload_Types == CompleteTemplate.Template_Upload_Types.File ) || ( completeTemplate.Upload_Types == CompleteTemplate.Template_Upload_Types.URL ))
                    {
                        // Get list of files in this package
                        string[] all_files = Directory.GetFiles(userInProcessDirectory);
                        List<string> acceptable_files = all_files.Where(ThisFile => (ThisFile.IndexOf("agreement.txt") < 0) && (ThisFile.IndexOf("TEMP000001_00001.mets") < 0)).ToList();

                        // Acceptable files found?
                        if ( acceptable_files.Count > 0 )
                            required_file_present = true;
                    }

                    // If this accepts URLs, check for a URL
                    if (( completeTemplate.Upload_Types == CompleteTemplate.Template_Upload_Types.URL ) || ( completeTemplate.Upload_Types == CompleteTemplate.Template_Upload_Types.File_or_URL ))
                    {
                        if ( item.Bib_Info.Location.Other_URL.Length > 0 )
                        {
                            required_url_present = true;
                        }
                    }

                    // If neither was present, go back to step 8
                    if (( !required_file_present ) && ( !required_url_present ))
                    {
                        RequestSpecificValues.Current_Mode.My_Sobek_SubMode = "8";
                        UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                        return;
                    }
                }

                // Complete the item submission
                complete_item_submission(item, RequestSpecificValues.Tracer);
            }

            #endregion
        }
Esempio n. 21
0
        private void process_template_header(XmlNodeReader nodeReader, CompleteTemplate ThisCompleteTemplate)
        {
            // Read all the nodes
            while (nodeReader.Read())
            {
                // Get the node name, trimmed and to upper
                string nodeName = nodeReader.Name.Trim().ToUpper();

                // If this is the inputs or constant start tag, return
                if ((nodeReader.NodeType == XmlNodeType.Element) &&
                    ((nodeName == "INPUTS") || (nodeName == "CONSTANTS")))
                {
                    return;
                }

                // If this is the beginning tag for an element, assign the next values accordingly
                if (nodeReader.NodeType == XmlNodeType.Element)
                {
                    // switch the rest based on the tag name
                    switch (nodeName)
                    {
                    case "BANNER":
                        ThisCompleteTemplate.Banner = read_text_node(nodeReader);
                        break;

                    case "INCLUDEUSERASAUTHOR":
                        ThisCompleteTemplate.Include_User_As_Author = Convert.ToBoolean(read_text_node(nodeReader));
                        break;

                    case "UPLOADS":
                        string upload_type_text = read_text_node(nodeReader).Trim().ToUpper();
                        switch (upload_type_text)
                        {
                        case "NONE":
                            ThisCompleteTemplate.Upload_Types = CompleteTemplate.Template_Upload_Types.None;
                            break;

                        case "FILE":
                            ThisCompleteTemplate.Upload_Types = CompleteTemplate.Template_Upload_Types.File;
                            break;

                        case "URL":
                            ThisCompleteTemplate.Upload_Types = CompleteTemplate.Template_Upload_Types.URL;
                            break;

                        case "FILE_OR_URL":
                            ThisCompleteTemplate.Upload_Types = CompleteTemplate.Template_Upload_Types.File_or_URL;
                            break;

                        default:
                            ThisCompleteTemplate.Upload_Types = CompleteTemplate.Template_Upload_Types.File;
                            break;
                        }
                        break;

                    case "UPLOADMANDATORY":
                        ThisCompleteTemplate.Upload_Mandatory = Convert.ToBoolean(read_text_node(nodeReader));
                        break;

                    case "NAME":
                        ThisCompleteTemplate.Title = read_text_node(nodeReader);
                        break;

                    case "PERMISSIONS":
                        ThisCompleteTemplate.Permissions_Agreement = read_text_node(nodeReader);
                        break;

                    case "NOTES":
                        ThisCompleteTemplate.Notes = (ThisCompleteTemplate.Notes + "  " + read_text_node(nodeReader)).Trim();
                        break;

                    case "DATECREATED":
                        DateTime dateCreated;
                        if (DateTime.TryParse(read_text_node(nodeReader), out dateCreated))
                        {
                            ThisCompleteTemplate.DateCreated = dateCreated;
                        }
                        break;

                    case "LASTMODIFIED":
                        DateTime lastModified;
                        if (DateTime.TryParse(read_text_node(nodeReader), out lastModified))
                        {
                            ThisCompleteTemplate.LastModified = lastModified;
                        }
                        break;

                    case "CREATOR":
                        ThisCompleteTemplate.Creator = read_text_node(nodeReader);
                        break;

                    case "BIBIDROOT":
                        ThisCompleteTemplate.BibID_Root = read_text_node(nodeReader);
                        break;

                    case "DEFAULTVISIBILITY":
                        string visibilityValue = read_text_node(nodeReader);
                        switch (visibilityValue)
                        {
                        case "PRIVATE":
                            ThisCompleteTemplate.Default_Visibility = -1;
                            break;

                        case "PUBLIC":
                            ThisCompleteTemplate.Default_Visibility = 0;
                            break;
                        }
                        break;

                    case "EMAILUPONSUBMIT":
                        ThisCompleteTemplate.Email_Upon_Receipt = read_text_node(nodeReader);
                        break;
                    }
                }
            }
        }
        /// <summary> Constructor for a new instance of the Edit_Group_Behaviors_MySobekViewer class </summary>
        /// <param name="RequestSpecificValues"> All the necessary, non-global data specific to the current request </param>
        public Edit_Group_Behaviors_MySobekViewer(RequestCache RequestSpecificValues)
            : base(RequestSpecificValues)
        {
            RequestSpecificValues.Tracer.Add_Trace("Edit_Group_Behaviors_MySobekViewer.Constructor", String.Empty);

               // If the RequestSpecificValues.Current_User cannot edit this RequestSpecificValues.Current_Item, go back
               if (!RequestSpecificValues.Current_User.Can_Edit_This_Item(RequestSpecificValues.Current_Item.BibID, RequestSpecificValues.Current_Item.Bib_Info.SobekCM_Type_String, RequestSpecificValues.Current_Item.Bib_Info.Source.Code, RequestSpecificValues.Current_Item.Bib_Info.HoldingCode, RequestSpecificValues.Current_Item.Behaviors.Aggregation_Code_List))
               {
               RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
               UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
               return;
               }

               const string TEMPLATE_CODE = "groupbehaviors";
               completeTemplate = Template_MemoryMgmt_Utility.Retrieve_Template(TEMPLATE_CODE, RequestSpecificValues.Tracer);
               if (completeTemplate != null)
               {
               RequestSpecificValues.Tracer.Add_Trace("Edit_Group_Behaviors_MySobekViewer.Constructor", "Found CompleteTemplate in cache");
               }
               else
               {
               RequestSpecificValues.Tracer.Add_Trace("Edit_Group_Behaviors_MySobekViewer.Constructor", "Reading CompleteTemplate file");

               // Read this CompleteTemplate
               Template_XML_Reader reader = new Template_XML_Reader();
               completeTemplate = new CompleteTemplate();
               if (File.Exists(UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\user\\standard\\" + TEMPLATE_CODE + ".xml"))
               {
                   reader.Read_XML(UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\user\\standard\\" + TEMPLATE_CODE + ".xml", completeTemplate, true);
               }
               else
               {
                   reader.Read_XML(UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\default\\standard\\" + TEMPLATE_CODE + ".xml", completeTemplate, true);
               }

               // Add the current codes to this CompleteTemplate
               completeTemplate.Add_Codes(UI_ApplicationCache_Gateway.Aggregations);

               // Save this into the cache
               Template_MemoryMgmt_Utility.Store_Template(TEMPLATE_CODE, completeTemplate, RequestSpecificValues.Tracer);
               }

               // See if there was a hidden request
               string hidden_request = HttpContext.Current.Request.Form["behaviors_request"] ?? String.Empty;

               // If this was a cancel request do that
               if (hidden_request == "cancel")
               {
               RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
               UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
               }
               else if (hidden_request == "save")
               {
               // Save these changes to bib
               completeTemplate.Save_To_Bib(RequestSpecificValues.Current_Item, RequestSpecificValues.Current_User, 1);

               // Save the group title
               SobekCM_Database.Update_Item_Group(RequestSpecificValues.Current_Item.BibID, RequestSpecificValues.Current_Item.Behaviors.GroupTitle, RequestSpecificValues.Current_Item.Bib_Info.SortSafeTitle(RequestSpecificValues.Current_Item.Behaviors.GroupTitle, true), String.Empty, RequestSpecificValues.Current_Item.Behaviors.Primary_Identifier.Type, RequestSpecificValues.Current_Item.Behaviors.Primary_Identifier.Identifier );

               // Save the interfaces to the group RequestSpecificValues.Current_Item as well
               SobekCM_Database.Save_Item_Group_Web_Skins(RequestSpecificValues.Current_Item.Web.GroupID, RequestSpecificValues.Current_Item );

               // Store on the caches (to replace the other)
               CachedDataManager.Remove_Digital_Resource_Objects(RequestSpecificValues.Current_Item.BibID, RequestSpecificValues.Tracer);

               // Forward
               RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
               UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
               }
        }
        /// <summary> Constructor for a new instance of the Edit_Group_Behaviors_MySobekViewer class </summary>
        /// <param name="RequestSpecificValues"> All the necessary, non-global data specific to the current request </param>
        public Edit_Group_Behaviors_MySobekViewer(RequestCache RequestSpecificValues)
            : base(RequestSpecificValues)
        {
            RequestSpecificValues.Tracer.Add_Trace("Edit_Group_Behaviors_MySobekViewer.Constructor", String.Empty);

               // If no user then that is an error
               if ((RequestSpecificValues.Current_User == null) || (!RequestSpecificValues.Current_User.LoggedOn))
               {
               RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Aggregation;
               RequestSpecificValues.Current_Mode.Aggregation = String.Empty;
               UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
               return;
               }

               // Ensure BibID provided
               RequestSpecificValues.Tracer.Add_Trace("Edit_Group_Behaviors_MySobekViewer.Constructor", "Validate provided bibid");
               if (String.IsNullOrEmpty(RequestSpecificValues.Current_Mode.BibID))
               {
               RequestSpecificValues.Tracer.Add_Trace("Edit_Group_Behaviors_MySobekViewer.Constructor", "BibID was not provided!");
               RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
               RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : BibID missing in item group metadata edit request";
               return;
               }

               // Ensure the item is valid
               RequestSpecificValues.Tracer.Add_Trace("Edit_Group_Behaviors_MySobekViewer.Constructor", "Validate bibid exists");
               if (!UI_ApplicationCache_Gateway.Items.Contains_BibID(RequestSpecificValues.Current_Mode.BibID))
               {
               RequestSpecificValues.Tracer.Add_Trace("Edit_Group_Behaviors_MySobekViewer.Constructor", "BibID indicated is not valid", Custom_Trace_Type_Enum.Error);
               RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
               RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : BibID indicated is not valid";
               return;
               }

               RequestSpecificValues.Tracer.Add_Trace("Edit_Group_Behaviors_MySobekViewer.Constructor", "Try to pull this sobek complete item group");
               currentItem = SobekEngineClient.Items.Get_Sobek_Item_Group(RequestSpecificValues.Current_Mode.BibID, RequestSpecificValues.Tracer);
               if (currentItem == null)
               {
               RequestSpecificValues.Tracer.Add_Trace("Edit_Group_Behaviors_MySobekViewer.Constructor", "Unable to build complete item group");
               RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Error;
               RequestSpecificValues.Current_Mode.Error_Message = "Invalid Request : Unable to build complete item";
               return;
               }

               // If the RequestSpecificValues.Current_User cannot edit this currentItem, go back
               if (!RequestSpecificValues.Current_User.Can_Edit_This_Item(currentItem.BibID, currentItem.Bib_Info.SobekCM_Type_String, currentItem.Bib_Info.Source.Code, currentItem.Bib_Info.HoldingCode, currentItem.Behaviors.Aggregation_Code_List))
               {
               RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
               UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
               return;
               }

               const string TEMPLATE_CODE = "groupbehaviors";
               completeTemplate = Template_MemoryMgmt_Utility.Retrieve_Template(TEMPLATE_CODE, RequestSpecificValues.Tracer);
               if (completeTemplate != null)
               {
               RequestSpecificValues.Tracer.Add_Trace("Edit_Group_Behaviors_MySobekViewer.Constructor", "Found CompleteTemplate in cache");
               }
               else
               {
               RequestSpecificValues.Tracer.Add_Trace("Edit_Group_Behaviors_MySobekViewer.Constructor", "Reading CompleteTemplate file");

               // Read this CompleteTemplate
               Template_XML_Reader reader = new Template_XML_Reader();
               completeTemplate = new CompleteTemplate();
               if (File.Exists(UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\user\\standard\\" + TEMPLATE_CODE + ".xml"))
               {
                   reader.Read_XML(UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\user\\standard\\" + TEMPLATE_CODE + ".xml", completeTemplate, true);
               }
               else
               {
                   reader.Read_XML(UI_ApplicationCache_Gateway.Settings.Servers.Base_MySobek_Directory + "templates\\default\\standard\\" + TEMPLATE_CODE + ".xml", completeTemplate, true);
               }

               // Save this into the cache
               Template_MemoryMgmt_Utility.Store_Template(TEMPLATE_CODE, completeTemplate, RequestSpecificValues.Tracer);
               }

               // See if there was a hidden request
               string hidden_request = HttpContext.Current.Request.Form["behaviors_request"] ?? String.Empty;

               // If this was a cancel request do that
               if (hidden_request == "cancel")
               {
               RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
               UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
               }
               else if (hidden_request == "save")
               {
               // Save these changes to bib
               completeTemplate.Save_To_Bib(currentItem, RequestSpecificValues.Current_User, 1);

               // Save the group title
               SobekCM_Item_Database.Update_Item_Group(currentItem.BibID, currentItem.Behaviors.GroupTitle, currentItem.Bib_Info.SortSafeTitle(currentItem.Behaviors.GroupTitle, true), String.Empty, currentItem.Behaviors.Primary_Identifier.Type, currentItem.Behaviors.Primary_Identifier.Identifier );

               // Save the interfaces to the group currentItem as well
               SobekCM_Item_Database.Save_Item_Group_Web_Skins(currentItem.Web.GroupID, currentItem );

               // Store on the caches (to replace the other)
               CachedDataManager.Items.Remove_Digital_Resource_Objects(currentItem.BibID, RequestSpecificValues.Tracer);

               // Also remove the list of volumes, since this may have changed
               CachedDataManager.Items.Remove_Items_In_Title(currentItem.BibID, RequestSpecificValues.Tracer);

               // Also clear the engine
               SobekEngineClient.Items.Clear_Item_Group_Cache(currentItem.BibID, RequestSpecificValues.Tracer);

               // Forward
               RequestSpecificValues.Current_Mode.Mode = Display_Mode_Enum.Item_Display;
               UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
               }
        }