/// <summary>
        /// Handles the ConceptScheme element child elements
        /// </summary>
        /// <param name="parent">
        /// The parent IConceptSchemeMutableObject object
        /// </param>
        /// <param name="localName">
        /// The name of the current xml element
        /// </param>
        private ElementActions HandleChildElements(IConceptSchemeMutableObject parent, object localName)
        {
            ElementActions actions = null;
            if (NameTableCache.IsElement(localName, ElementNameTable.Concept))
            {
                var concept = new ConceptMutableCore();
                ParseAttributes(concept, this.Attributes);

                string representation = Helper.TrySetFromAttribute(
                    this.Attributes, AttributeNameTable.coreRepresentation, string.Empty);
                if (!string.IsNullOrWhiteSpace(representation))
                {
                    concept.CoreRepresentation = new RepresentationMutableCore();
                    string coreRepresentationAgency = Helper.TrySetFromAttribute(
                        this.Attributes, AttributeNameTable.coreRepresentationAgency, string.Empty);
                    concept.CoreRepresentation.Representation = new StructureReferenceImpl(
                        coreRepresentationAgency, representation, null, SdmxStructureEnumType.CodeList);

                    /* TODO check if coreRepresentationVersion was used somewhere.
                     * var coreRepresentationVersion = Helper.TrySetFromAttribute(
                        this.Attributes, AttributeNameTable.coreRepresentationVersion, string.Empty); */
                }

                concept.ParentConcept = Helper.TrySetFromAttribute(
                    this.Attributes, AttributeNameTable.parent, concept.ParentConcept);
                concept.ParentAgency = Helper.TrySetFromAttribute(
                    this.Attributes, AttributeNameTable.parentAgency, concept.ParentAgency);
                parent.AddItem(concept);

                actions = this.AddNameableAction(concept, this.HandleChildElements);
            }

            return actions;
        }
        /// <summary>
        /// Creates a new instance with an id and an english name
        /// </summary>
        /// <param name="id">
        /// The id.
        /// </param>
        /// <param name="name">
        /// The name. 
        /// </param>
         public static IConceptMutableObject GetInstance(string id, string name)
         {
		    
            IConceptMutableObject newInstance = new ConceptMutableCore();
		    newInstance.Id = id;
		    newInstance.AddName("en", name);
		    return newInstance;
	     }
        /// <summary>
        /// Creates and returns a concept with the specified <paramref name="id"/>, <paramref name="name"/> and adds it to
        ///     <paramref name="parent"/>
        /// </summary>
        /// <param name="parent">
        /// The parent.
        /// </param>
        /// <param name="id">
        /// The id.
        /// </param>
        /// <param name="name">
        /// The name.
        /// </param>
        /// <returns>
        /// The <see cref="IConceptObject"/>.
        /// </returns>
        private static IConceptObject CreateConcept(IConceptSchemeObject parent, string id, string name)
        {
            var concept = new ConceptMutableCore { Id = id };
            concept.AddName("en", name);

            //// parent.AddItem(concept);
            return new ConceptCore(parent, concept);
        }
        protected void btnUpdateConcept_Click(object sender, EventArgs e)
        {
            // Get Input field
            string concept_id = txt_id_update.Text.Trim();
            IList<ITextTypeWrapperMutableObject> concept_names = AddTextName_Update.TextObjectList;
            IList<ITextTypeWrapperMutableObject> concept_descs = AddTextDescription_Update.TextObjectList;
            string concept_parent_id = txt_parentid_update.Text.Trim();
            // string code_order_str = txtUpdateCodeOrder.Text.Trim();

            // Get Current Object Session
            IConceptSchemeMutableObject cs = GetConceptSchemeFromSession();
            IEnumerable<IConceptMutableObject> _rc = (from x in cs.Items where x.Id == concept_id select x).OfType<IConceptMutableObject>();
            if (_rc.Count() == 0) return;

            IConceptMutableObject concept = _rc.First();

            IConceptMutableObject _bConcept = new ConceptMutableCore();

            int indexConcept = cs.Items.IndexOf(concept);
            int indexOrder = 0;
            try
            {

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

                #region CONCEPT NAMES
                if (concept_names != null)
                {
                    foreach (var tmpName in concept_names)
                    {
                        _bConcept.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= '#concepts';");
                    return;
                }
                #endregion

                #region CONCEPT DESCRIPTIONS
                if (concept_descs != null)
                {
                    foreach (var tmpDescription in concept_descs)
                    {
                        _bConcept.AddDescription(tmpDescription.Locale, tmpDescription.Value);
                    }
                }
                #endregion

                #region PARANT ID

                if (concept_id.Equals(concept_parent_id))
                {
                    lblErrorOnUpdate.Text = Resources.Messages.err_parent_id_same_value;
                    Utils.AppendScript("openPopUp('df-Dimension-update', 600 );");
                    Utils.AppendScript("location.href= '#concepts';");
                    return;
                }

                if (!concept_parent_id.Equals(string.Empty) && ValidationUtils.CheckIdFormat(concept_id))
                {
                    //IEnumerable<ICodeMutableObject> parentCode = (from c in cl.Items where c.Id == code_parent_id select c).OfType<ICodeMutableObject>();

                    IEnumerable<IConceptMutableObject> parentConcept = (from c in cs.Items where c.Id == concept_parent_id select c).OfType<IConceptMutableObject>();
                    if (parentConcept.Count() > 0)
                        _bConcept.ParentConcept = concept_parent_id;
                    else
                    {

                        lblErrorOnUpdate.Text = Resources.Messages.err_parent_id_not_found;
                        Utils.AppendScript("openPopUp('df-Dimension-update', 600 );");
                        Utils.AppendScript("location.href= '#concepts';");
                        return;
                    }
                }
                #endregion

                cs.Items.Remove(concept);
                cs.Items.Insert(indexConcept, _bConcept);

                var canRead = cs.ImmutableInstance;
            }
            catch (Exception ex) // ERRORE GENERICO!
            {
                cs.Items.Remove(_bConcept);
                cs.Items.Insert(indexConcept, concept);
                if (ex.Message.Contains("- 706 -"))
                {
                    lblErrorOnUpdate.Text = Resources.Messages.err_parent_item_is_child;
                    Utils.AppendScript("openPopUp('df-Dimension-update', 600);");
                }
                else
                {
                    lblErrorOnUpdate.Text = Resources.Messages.err_concept_update;
                    Utils.AppendScript("openPopUp('df-Dimension-update', 600);");
                }
                Utils.AppendScript("location.href='#concepts';");
                return;
            }

            if (!SaveInMemory(cs))
                return;

            BindData();
            lblErrorOnUpdate.Text = string.Empty;
            Utils.AppendScript("location.href='#concepts';");
        }
        protected void btnImportFromCsv_Click(object sender, EventArgs e)
        {
            if (!csvFile.HasFile)
            {
                Utils.AppendScript("openPopUp( 'importCsv' );");
                Utils.AppendScript("location.href='#concepts'");
                Utils.AppendScript(string.Format("alert( '{0}' );", Resources.Messages.err_no_file_uploaded));
                return;
            }

            IConceptSchemeMutableObject cs = GetConceptSchemeFromSession();

            if (cs == null) return;

            List<csvConcept> concepts = new List<csvConcept>();
            bool errorInUploading = false;
            StreamReader reader = null;
            StreamWriter logWriter = null;
            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_conceptschemes_files/") + filename);

                reader = new StreamReader(Server.MapPath("~/csv_conceptschemes_files/") + filename);
                logWriter = new StreamWriter(Server.MapPath("~/csv_conceptschemes_import_logs/") + logFilename, true);
                logWriter.WriteLine(string.Format("LOG RELATIVO A CARICAMENTO DEL CONCEPT 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;
                    }
                    concepts.Add(new csvConcept(fields[0].ToString().Replace("\"", ""), fields[1].ToString().Replace("\"", ""), fields[2].ToString().Replace("\"", ""), fields[3].ToString().Replace("\"", "")));
                    currentRow++;
                }
            }
            catch (Exception ex)
            {
                Utils.AppendScript(string.Format("Upload status: The file could not be uploaded. The following error occured: {0}", ex.Message));
            }

            foreach (csvConcept concept in concepts)
            {

                if (!concept.parentConcept.Trim().Equals(string.Empty))
                {
                    int cont = (from myConcept in cs.Items
                                where myConcept.Id.Equals(concept.parentConcept)
                                select myConcept).Count();
                    if (cont == 0)
                    {
                        errorInUploading = true;
                        wrongRowsMessageForUser += string.Format(Resources.Messages.err_csv_import_parent_code_error, concept.parentConcept, concept.concept, concept.concept);
                        continue;
                    }
                }

                IEnumerable<IConceptMutableObject> tmpConcepts = (from conc in cs.Items where conc.Id == concept.concept select conc).OfType<IConceptMutableObject>();

                IConceptMutableObject tmpConcept;

                if (!(tmpConcepts.Count() > 0))
                {
                    tmpConcept = new ConceptMutableCore();
                    tmpConcept.Id = concept.concept;
                    tmpConcept.ParentConcept = concept.parentConcept;
                    tmpConcept.AddName(cmbLanguageForCsv.SelectedValue.ToString(), concept.name);
                    tmpConcept.AddDescription(cmbLanguageForCsv.SelectedValue.ToString(), concept.description);
                    cs.AddItem(tmpConcept);
                }
                else
                {
                    tmpConcept = tmpConcepts.First();
                    tmpConcept.Id = concept.concept;
                    tmpConcept.ParentConcept = concept.parentConcept;
                    tmpConcept.AddName(cmbLanguageForCsv.SelectedValue.ToString(), concept.name);
                    tmpConcept.AddDescription(cmbLanguageForCsv.SelectedValue.ToString(), concept.description);
                }
            }

            if (errorInUploading)
            {
                lblImportCsvErrors.Text = wrongRowsMessageForUser;
                lblImportCsvWrongLines.Text = wrongFileLines;
                Utils.AppendScript("openP('importCsvErrors',500);");
            }

            logWriter.Close();
            reader.Close();

            if (!SaveInMemory(cs))
                return;

            BindData();
            if (!errorInUploading)
            {
                Utils.ShowDialog(Resources.Messages.succ_operation);
            }
            Utils.AppendScript("location.href='#concepts';");
        }
        private IConceptSchemeMutableObject InsertConceptInConceptscheme(IConceptSchemeMutableObject cs)
        {
            if (cs == null) return null;

            IConceptMutableObject concept = new ConceptMutableCore();

            string concept_id = txt_id_new.Text.Trim();

            IList<ITextTypeWrapperMutableObject> concept_names = AddTextName_new.TextObjectList;
            IList<ITextTypeWrapperMutableObject> concept_descs = AddTextDescription_new.TextObjectList;
            string concept_parent_id = txt_parentid_new.Text.Trim();
            // string code_order_str = txtOrderNewCode.Text.Trim();     ----- ORDINE

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

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

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

            #region CONCEPT DESCRIPTIONS
            if (concept_descs != null)
            {
                foreach (var tmpDescription in concept_descs)
                {
                    concept.AddDescription(tmpDescription.Locale, tmpDescription.Value);
                }
            }
            #endregion

            #region PARANT ID

            if (concept_id.Equals(concept_parent_id))
            {
                lblErrorOnNewInsert.Text = Resources.Messages.err_parent_id_same_value;
                Utils.AppendScript("openPopUp('df-Dimension-update', 600 );");
                Utils.AppendScript("location.href= '#concepts';");
                return null;
            }

            if (!concept_parent_id.Equals(string.Empty) && ValidationUtils.CheckIdFormat(concept_id))
            {
                IEnumerable<IConceptMutableObject> parentConcept = (from c in cs.Items where c.Id == concept_parent_id select c).OfType<IConceptMutableObject>();
                if (parentConcept.Count() > 0)
                    concept.ParentConcept = concept_parent_id;
                else
                {
                    lblErrorOnNewInsert.Text = Resources.Messages.err_parent_id_not_found;
                    Utils.AppendScript("openPopUp('df-Dimension', 600);");
                    Utils.AppendScript("location.href= '#concepts';");
                    return null;
                }
            }
            #endregion

            cs.Items.Add(concept);

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

                return null;
            }

            return cs;
        }