/// <summary>
 /// Handles the Category element
 /// </summary>
 /// <param name="attributes">
 /// The dictionary contains the attributes of the element
 /// </param>
 /// <returns>
 /// The created ICategoryMutableObject
 /// </returns>
 private static ICategoryMutableObject HandleCategory(IDictionary<string, string> attributes)
 {
     var category = new CategoryMutableCore();
     ParseAttributes(category, attributes);
     return category;
 }
        protected void btnImportFromCsv_Click(object sender, EventArgs e)
        {
            if ( !csvFile.HasFile )
            {
                Utils.AppendScript( "openPopUp( 'importCsv' );" );
                Utils.AppendScript( "location.href='#categories'" );
                Utils.AppendScript( string.Format( "alert( '{0}' );", Resources.Messages.err_no_file_uploaded ) );
                return;
            }

            ICategorySchemeMutableObject cs = GetCategorySchemeFromSession();
            ICategoryMutableObject foundCategory = null;

            if (cs == null) return;

            List<csvCategory> categories = new List<csvCategory>();
            bool errorInUploading = false;

            string wrongRowsMessage = string.Empty;
            string wrongRowsMessageForUser = string.Empty;
            string wrongFileLines = string.Empty;

            try
            {
                string filenameWithoutExtension = string.Format("{0}_{1}_{2}", Path.GetFileName(csvFile.FileName).Substring(0, csvFile.FileName.Length - 4), Session.SessionID, DateTime.Now.ToString().Replace('/', '_').Replace(':', '_').Replace(' ', '_'));
                string filename = string.Format("{0}.csv", filenameWithoutExtension);
                string logFilename = string.Format("{0}.log", filenameWithoutExtension);
                csvFile.SaveAs(Server.MapPath("~/csv_categoryschemes_files/") + filename);
                StreamReader reader = new StreamReader(Server.MapPath("~/csv_categoryschemes_files/") + filename);
                StreamWriter logWriter = new StreamWriter(Server.MapPath("~/csv_categoryschemes_import_logs/") + logFilename, true);
                logWriter.WriteLine(string.Format("LOG RELATIVO A CARICAMENTO DEL CATEGORY SCHEME [ ID => \"{0}\"  AGENCY_ID => \"{1}\"  VERSION => \"{2}\" ]  |  LINGUA SELEZIONATA: {3}\n", cs.Id.ToString(), cs.AgencyId.ToString(), cs.Version.ToString(), cmbLanguageForCsv.SelectedValue.ToString()));
                logWriter.WriteLine("-----------------------------------------------------------------------------------------------------------------------------\n");
                reader.ReadLine();

                int currentRow = 1;

                char separator = txtSeparator.Text.Trim().Equals( string.Empty ) ? ';' : txtSeparator.Text.Trim().ElementAt( 0 );

                while (!reader.EndOfStream)
                {
                    string  currentFileLine = reader.ReadLine();
                    string[] fields = currentFileLine.Split( separator );
                    if (fields.Length != 4)
                    {
                        errorInUploading = true;
                        wrongRowsMessage += string.Format(Resources.Messages.err_csv_import_line_bad_format, currentRow + 1);
                        wrongRowsMessageForUser += string.Format(Resources.Messages.err_csv_import_line_bad_format_gui, currentRow + 1);
                        wrongFileLines += string.Format( "{0}\n", currentFileLine );
                        logWriter.WriteLine(string.Format(Resources.Messages.err_csv_import_line_bad_format, currentRow + 1));
                        logWriter.Flush();
                        currentRow++;
                        continue;
                    }
                    if ( fields[0].Trim().Equals("\"\"") || fields[0].Trim().Equals(string.Empty))
                    {
                        errorInUploading = true;
                        wrongRowsMessage += string.Format(Resources.Messages.err_csv_import_id_missing, currentRow + 1);
                        wrongRowsMessageForUser += string.Format(Resources.Messages.err_csv_import_id_missing_gui, currentRow + 1);
                        wrongFileLines += string.Format( "{0}\n", currentFileLine );
                        logWriter.WriteLine(string.Format(Resources.Messages.err_csv_import_id_missing, currentRow + 1));
                        logWriter.Flush();
                        currentRow++;
                        continue;
                    }
                    if (fields[1].Trim().Equals("\"\"") || fields[1].Trim().Equals(string.Empty))
                    {
                        errorInUploading = true;
                        wrongRowsMessage += string.Format(Resources.Messages.err_csv_import_name_missing, currentRow + 1);
                        wrongRowsMessageForUser += string.Format(Resources.Messages.err_csv_import_name_missing_gui, currentRow + 1);
                        wrongFileLines += string.Format( "{0}\n", currentFileLine );
                        logWriter.WriteLine(string.Format(Resources.Messages.err_csv_import_name_missing, currentRow + 1));
                        logWriter.Flush();
                        currentRow++;
                        continue;
                    }
                    categories.Add(new csvCategory(fields[0].ToString().Replace("\"", ""), fields[1].ToString().Replace("\"", ""), fields[2].ToString().Replace("\"", ""), fields[3].ToString().Replace("\"", "")));
                    currentRow++;
                }
                if (!errorInUploading)
                {
                    logWriter.WriteLine("Andato tutto a buon fine con questo file!");
                }
                else
                {
                    lblImportCsvErrors.Text = wrongRowsMessageForUser;
                    Utils.AppendScript("openP('importCsvErrors',500);");
                }
                logWriter.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                Utils.AppendScript(string.Format("Upload status: The file could not be uploaded. The following error occured: {0}", ex.Message));
            }

            foreach (csvCategory category in categories)
            {
                if (category.parentCategory != string.Empty)
                {
                    string[] sequence = category.parentCategory.Split('.');
                    foundCategory = (ICategoryMutableObject)((from c in cs.Items
                                                              where c.Id.Equals(sequence[0])
                                                              select c).First());

                    for (int i = 1; i < sequence.Length; i++)
                    {
                        foundCategory = (ICategoryMutableObject)((from c in foundCategory.Items
                                                                  where c.Id.Equals(sequence[i])
                                                                  select c).First());
                    }

                    IEnumerable<ICategoryMutableObject> tmpCategories = null;
                    if (foundCategory != null)
                    {
                        tmpCategories = (from conc in foundCategory.Items where conc.Id == category.category select conc).OfType<ICategoryMutableObject>();
                    }
                    else
                    {
                        tmpCategories = (from conc in cs.Items where conc.Id == category.category select conc).OfType<ICategoryMutableObject>();
                    }

                    ICategoryMutableObject tmpCategory;

                    if (!(tmpCategories.Count() > 0))
                    {
                        tmpCategory = new CategoryMutableCore();
                        tmpCategory.Id = category.category;
                        tmpCategory.AddName(cmbLanguageForCsv.SelectedValue.ToString(), category.name);
                        tmpCategory.AddDescription(cmbLanguageForCsv.SelectedValue.ToString(), category.description);
                        if (foundCategory != null)
                        {
                            foundCategory.AddItem(tmpCategory);
                        }
                        else
                        {
                            cs.AddItem(tmpCategory);
                        }
                    }
                    else
                    {
                        tmpCategory = tmpCategories.First();
                        tmpCategory.Id = category.category;
                        tmpCategory.AddName(cmbLanguageForCsv.SelectedValue.ToString(), category.name);
                        tmpCategory.AddDescription(cmbLanguageForCsv.SelectedValue.ToString(), category.description);
                    }
                }
                else
                {
                    try
                    {
                        IEnumerable<ICategoryMutableObject> tmpCategories = (from conc in cs.Items where conc.Id == category.category select conc).OfType<ICategoryMutableObject>();
                        ICategoryMutableObject tmpCategory;

                        if (!(tmpCategories.Count() > 0))
                        {
                            tmpCategory = new CategoryMutableCore();
                            tmpCategory.Id = category.category;
                            tmpCategory.AddName(cmbLanguageForCsv.SelectedValue.ToString(), category.name);
                            tmpCategory.AddDescription(cmbLanguageForCsv.SelectedValue.ToString(), category.description);
                            cs.AddItem(tmpCategory);
                        }
                        else
                        {
                            tmpCategory = tmpCategories.First();
                            tmpCategory.Id = category.category;
                            tmpCategory.AddName(cmbLanguageForCsv.SelectedValue.ToString(), category.name);
                            tmpCategory.AddDescription(cmbLanguageForCsv.SelectedValue.ToString(), category.description);
                        }
                    }
                    catch (Exception ex)
                    {
                        // In caso di parent errato!
                        continue;
                    }

                }
            }

            if (!SaveInMemory(cs))
                return;

            BindData();
            if (!errorInUploading)
            {
                Utils.ShowDialog(Resources.Messages.succ_operation);
            }
            else
            {
                lblImportCsvErrors.Text = wrongRowsMessageForUser;
                lblImportCsvWrongLines.Text = wrongFileLines;
                Utils.AppendScript("openP('importCsvErrors',500);");
            }
            Utils.AppendScript("location.href='#categories';");
        }
        protected void btnUpdateCategory_Click(object sender, EventArgs e)
        {
            // TEMPORARY LOG
            TemporaryLog("In aggiornamento category");

            // Get Input field
            string category_id = txtUpdateCategoryID.Text.Trim();
            IList<ITextTypeWrapperMutableObject> category_names = AddText1.TextObjectList;
            IList<ITextTypeWrapperMutableObject> category_descs = AddText2.TextObjectList;
            // string category_parent_id = txtUpdateCategoryParentID.Text.Trim();

            // Get Current Object Session
            ICategorySchemeMutableObject cs = GetCategorySchemeFromSession();
            cs = GetCategoryschemeForm( cs );
            string[] parentElements = TreeView1.SelectedNode.Parent.ValuePath.Split('/');
            string[] elements = TreeView1.SelectedNode.ValuePath.Split('/');
            ICategoryMutableObject currentParentNodeInCategoryScheme = cs.Items.First(obj => obj.Id.Equals(elements[1]));
            ICategoryMutableObject currentNodeInCategoryScheme = cs.Items.First(obj => obj.Id.Equals(elements[1]));

            for (int i = 2; i < elements.Length; i++)
            {
                currentNodeInCategoryScheme =
                    currentNodeInCategoryScheme.Items.First(
                    obj => obj.Id.Equals(elements[i]));
            }

            for (int i = 2; i < parentElements.Length; i++)
            {
                currentParentNodeInCategoryScheme =
                    currentParentNodeInCategoryScheme.Items.First(
                    obj => obj.Id.Equals(parentElements[i]));
            }

            ICategoryMutableObject _bCategory = new CategoryMutableCore();

            try
            {

                #region CATEGORY ID
                if (!category_id.Equals(string.Empty) && ValidationUtils.CheckIdFormat(category_id))
                {
                    _bCategory.Id = category_id;
                }
                else
                {
                    lblErrorOnUpdate.Text = Resources.Messages.err_id_format;
                    Utils.AppendScript("openPopUp('df-Dimension-update', 600 );");
                    Utils.AppendScript("location.href= '#categories';");
                    return;
                }
                #endregion

                #region CATEGORY NAMES
                if (category_names != null)
                {
                    foreach (var tmpName in category_names)
                    {
                        _bCategory.AddName(tmpName.Locale, tmpName.Value);
                    }
                }
                else
                {
                    lblErrorOnUpdate.Text = Resources.Messages.err_list_name_format;
                    Utils.AppendScript("openPopUp('df-Dimension-update', 600 );");
                    Utils.AppendScript("location.href= '#categories';");
                    return;
                }
                #endregion

                #region CATEGORY DESCRIPTIONS
                if (category_descs != null)
                {
                    foreach (var tmpDescription in category_descs)
                    {
                        _bCategory.AddDescription(tmpDescription.Locale, tmpDescription.Value);
                    }
                }
                #endregion

                #region CATEGORY ITEMS

                foreach (var subCategory in currentNodeInCategoryScheme.Items)
                {
                    _bCategory.Items.Add(subCategory);
                }

                #endregion

                #region CATEGORY ANNOTATION

                foreach (var currentAnnotation in AnnotationUpdateControl.AnnotationObjectList)
                    _bCategory.Annotations.Add(currentAnnotation);

                #endregion

                if (parentElements.Length == 1)
                {
                    cs.Items.Remove(currentNodeInCategoryScheme);
                    cs.Items.Add(_bCategory);
                }
                else
                {
                    currentParentNodeInCategoryScheme.Items.Remove(currentNodeInCategoryScheme);
                    currentParentNodeInCategoryScheme.Items.Add(_bCategory);
                }

                var canRead = cs.ImmutableInstance;

            }
            catch (Exception ex) // ERRORE GENERICO!
            {
                currentParentNodeInCategoryScheme.Items.Remove(_bCategory);
                currentParentNodeInCategoryScheme.Items.Add(currentNodeInCategoryScheme);

                Utils.ShowDialog(Resources.Messages.err_category_update, 300, Resources.Messages.err_title);
                Utils.AppendScript("location.href='#categories';");

            }

            if (!SaveInMemory(cs))
                return;

            BindData();

            Utils.AppendScript("location.href='#categories';");
        }
        private ICategorySchemeMutableObject InsertCategoryInCategoryscheme(ICategorySchemeMutableObject cs)
        {
            if (cs == null) return null;

            ICategoryMutableObject category = new CategoryMutableCore();

            string category_id = txtNewCategoryId.Text.Trim();

            IList<ITextTypeWrapperMutableObject> category_names = NewCategoryAddTextName.TextObjectList;
            IList<ITextTypeWrapperMutableObject> category_descs = NewCategoryAddTextDescription.TextObjectList;
            //string category_parent_id = txtParentCategoryNewCategory.Text.Trim();
            // string code_order_str = txtOrderNewCode.Text.Trim();     ----- ORDINE

            #region CATEGORY ID
            if (ValidationUtils.CheckIdFormat(category_id))
            {
                category.Id = category_id;
            }
            else
            {
                lblErrorOnNewInsert.Text = Resources.Messages.err_id_format;
                Utils.AppendScript("openPopUp('df-Dimension', 600);");
                Utils.AppendScript("location.href= '#categories';");
                return null;
            }

            IEnumerable<ICategoryMutableObject> categories = (from c in cs.Items where c.Id == category_id select c).OfType<ICategoryMutableObject>();
            if (categories.Count() > 0)
            {
                lblErrorOnNewInsert.Text = Resources.Messages.err_id_exist;
                Utils.AppendScript("openPopUp('df-Dimension', 600);");
                Utils.AppendScript("location.href= '#categories';");
                return null;
            }
            #endregion

            #region CODE NAMES
            if (category_names != null)
            {
                foreach (var tmpName in category_names)
                {
                    category.AddName(tmpName.Locale, tmpName.Value);
                }
            }
            else
            {
                lblErrorOnNewInsert.Text = Resources.Messages.err_list_name_format;
                Utils.AppendScript("openPopUp('df-Dimension', 600);");
                Utils.AppendScript("location.href= '#categories';");
                return null;
            }
            #endregion

            #region CATEGORY DESCRIPTIONS
            if (category_descs != null)
            {
                foreach (var tmpDescription in category_descs)
                {
                    category.AddDescription(tmpDescription.Locale, tmpDescription.Value);
                }
            }
            #endregion

            #region CATEGORY ANNOTATIONS

            if (AnnotationNewControl.AnnotationObjectList != null)
                foreach (var currentAnnotation in AnnotationNewControl.AnnotationObjectList)
                {
                    category.Annotations.Add(currentAnnotation);
                }

            #endregion

            #region PARANT ID

            if (TreeView1.SelectedNode != null && !TreeView1.Nodes[0].Selected)
            {

                string nodesPath = TreeView1.SelectedNode.ValuePath.ToString();
                string[] elements = nodesPath.Split('/');
                ICategoryMutableObject currentNodeInCategoryScheme = cs.Items.First(obj => obj.Id.Equals(elements[1]));

                for (int i = 2; i < elements.Length; i++)
                {
                    currentNodeInCategoryScheme = currentNodeInCategoryScheme.Items.First(obj => obj.Id.Equals(elements[i]));
                }
                currentNodeInCategoryScheme.Items.Add(category);
            }
            else
            {
                cs.Items.Add(category);
            }
            #endregion

            try
            {
                // Ultimo controllo se ottengo Immutable istanze validazione completa
                var canRead = cs.ImmutableInstance;
            }
            catch (Exception ex)
            {
                //parentCategory.Items.Remove( category );

                return null;

            }

            txtNewCategoryId.Text = string.Empty;
            NewCategoryAddTextDescription.ClearTextObjectListWithOutJS();
            NewCategoryAddTextName.ClearTextObjectListWithOutJS();
            lblErrorOnNewInsert.Text = string.Empty;
            AnnotationNewControl.ClearAnnotationsSession();
            return cs;
        }