Example #1
0
        public static IList<ArtefactImportStatus> DeleteStructure(SDMXIdentifier sdmxKey, Org.Sdmxsource.Sdmx.Api.Constants.SdmxStructureEnumType typeArtefact = Org.Sdmxsource.Sdmx.Api.Constants.SdmxStructureEnumType.Dsd)
        {
            IList<ArtefactImportStatus> artefactImportStatuses = new List<ArtefactImportStatus>();

            if (typeArtefact == Org.Sdmxsource.Sdmx.Api.Constants.SdmxStructureEnumType.Dsd)
            {
                IDataStructureObject dsd = DataSDMX.GetDSD(sdmxKey);
                var manager = new MappingStoreManager(SQLConnString_DB, artefactImportStatuses);
                manager.DeleteStructure(dsd);
            }
            else if (typeArtefact == Org.Sdmxsource.Sdmx.Api.Constants.SdmxStructureEnumType.Dataflow)
            {

                IDataflowObject dataflow = DataSDMX.GetDataflow(sdmxKey);
                var manager = new MappingStoreManager(SQLConnString_DB, artefactImportStatuses);
                manager.DeleteStructure(dataflow);
            }

            return artefactImportStatuses;
        }
        public static ICodelistObject GetCodelist(SDMXIdentifier sdmxKey)
        {
            ISdmxMutableObjectRetrievalManager manager = GetManager();

            IMaintainableRefObject query = new MaintainableRefObjectImpl(sdmxKey.agencyid, sdmxKey.id, sdmxKey.version);

            ICodelistMutableObject codelist = manager.GetMutableCodelist(query, false, false);

            if (codelist != null) return codelist.ImmutableInstance;

            return GetConceptSchemeItems(sdmxKey);
        }
        private void SaveDF()
        {
            /*
             * 1. Aggiungo all'oggetto _dfMutable:
             *      Le info della General
             *      La collection di Names
             *      La Collection delle Desctiptions
             * 2. Richiamo il metodo che prende in input un ISdmxObjects che richiama il SaveStructure
             * 3. Visualizzo un messaggio di conferma
             */

            try
            {
                SDMXIdentifier identi = new SDMXIdentifier()
                {
                    agencyid = GetAgencyValue(),
                    id = txtDFID.Text.ToUpper(),
                    version = txtVersion.Text
                };

                _dfMutable.Id = txtDFID.Text.ToUpper();
                _dfMutable.AgencyId = GetAgencyValue();
                _dfMutable.Version = txtVersion.Text;

                _dfMutable.Names.Clear();
                foreach (ITextTypeWrapperMutableObject name in AddTextName.TextObjectList)
                {
                    _dfMutable.Names.Add(name);
                }

                _dfMutable.Descriptions.Clear();
                if (AddTextDescription.TextObjectList != null)
                {
                    foreach (ITextTypeWrapperMutableObject descr in AddTextDescription.TextObjectList)
                    {
                        _dfMutable.Descriptions.Add(descr);
                    }
                }

                _dfMutable.FinalStructure = TertiaryBool.ParseBoolean(chkIsFinal.Checked);
                if (txtURI.Text != String.Empty)
                    _dfMutable.Uri = new Uri(txtURI.Text);

                if (txtValidFrom.Text != String.Empty)
                    _dfMutable.StartDate = DateTime.ParseExact(txtValidFrom.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);

                if (txtValidTo.Text != String.Empty)
                    _dfMutable.EndDate = DateTime.ParseExact(txtValidTo.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);

                _dfMutable.Annotations.Clear();
                if (AnnotationGeneral.AnnotationObjectList != null)
                    foreach (var annotation in AnnotationGeneral.AnnotationObjectList)
                    {
                        _dfMutable.AddAnnotation(annotation);
                    }

                //string[] DSDValues = cmbDSD.SelectedValue.Split('+');

                IStructureReference dsdRef = new StructureReferenceImpl(GetAgencyValue(), txtDFID.Text.ToUpper(), txtVersion.Text,
                                                                        SdmxStructureType.GetFromEnum(SdmxStructureEnumType.Dsd),
                                                                        new string[] { _ntdString });
                _dfMutable.DataStructureRef = dsdRef;

                SetDfToSession();

                //Elimino il Df creato automaiticamente e lo reinserisco
                DataSDMX.DeleteStructure(_sdmxObjects);
                IList<ArtefactImportStatus> ais = DataSDMX.SubmitStructure(_sdmxObjects);

                string msg = "", msgStatus = "";

                foreach (ArtefactImportStatus status in ais)
                {
                    msg += "\n\r" + status.ImportMessage.Message;
                    msgStatus = status.ImportMessage.Status.ToString();
                }

            }
            catch (Exception ex)
            {
                DLUtils.ShowMessageBox(this.Page, "Dataloader-Error", ex.Message);
            }
        }
        private IDataStructureMutableObject RestylingDSD(IDataStructureMutableObject workingDSD, List<string> lCubeColumns, SDMXIdentifier sdmxDFKey)
        {
            // Mi ciclo tutte le dimensioni e gli attributi della DSD di origine, se non sono presenti nella lista componentList li elimino

            List<IDimensionMutableObject> dimsToDelete = new List<IDimensionMutableObject>();
            List<IAttributeMutableObject> attsToDelete = new List<IAttributeMutableObject>();

            List<string> lCubeColumnsName = new List<string>();

            foreach (string col in lCubeColumns)
            {
                lCubeColumnsName.Add(RemoveFirstUnderscore(col));
            }

            foreach (IDimensionMutableObject dim in workingDSD.Dimensions)
            {
                if (!lCubeColumnsName.Contains(dim.Id.ToUpper()))
                {
                    dimsToDelete.Add(dim);
                }
                else
                    _dimensionList.Add(dim.Id);

            }

            if (workingDSD.Attributes != null)
                foreach (IAttributeMutableObject att in workingDSD.Attributes)
                {
                    if (!lCubeColumnsName.Contains(att.Id.ToUpper()))
                    {
                        attsToDelete.Add(att);
                    }
                    else if (att.AttachmentLevel == Org.Sdmxsource.Sdmx.Api.Constants.AttributeAttachmentLevel.Group)
                    {
                        IGroupMutableObject grp = workingDSD.Groups.Where(g => g.Id == att.AttachmentGroup).FirstOrDefault();

                        List<string> lDim = new List<string>();

                        if (grp != null)
                            foreach (string dimName in grp.DimensionRef)
                                if (lCubeColumnsName.Contains(dimName.ToUpper()))
                                    lDim.Add(dimName.ToUpper());

                        //if (grp == null || lDim.Count == 0)
                        //{
                        //    attsToDelete.Add(att);
                        //    continue;
                        //}

                        if (grp == null || lDim.Count == 0)
                        {
                            //se 1 modifico l'attachmentLevel a Dataset
                            att.AttachmentLevel = Org.Sdmxsource.Sdmx.Api.Constants.AttributeAttachmentLevel.DataSet;
                            //continue;
                        }

                        if (lDim.Count >= 1)
                        {
                            foreach (string dimName in lDim)
                                att.DimensionReferences.Add(dimName);

                            att.AttachmentLevel = AttributeAttachmentLevel.DimensionGroup;
                        }

                        att.AttachmentGroup = null;
                        _attributeList.Add(att.Id);
                    }
                    else if (att.AttachmentLevel == Org.Sdmxsource.Sdmx.Api.Constants.AttributeAttachmentLevel.DimensionGroup)
                    {

                        List<string> lDelDim = new List<string>();

                        foreach (string dimName in att.DimensionReferences)
                            if (!lCubeColumnsName.Contains(dimName.ToUpper()))
                                lDelDim.Add(dimName.ToUpper());

                        foreach (string delDimName in lDelDim)
                            att.DimensionReferences.Remove(delDimName);

                        if (att.DimensionReferences.Count == 0)
                        {
                            attsToDelete.Add(att);
                            continue;
                        }
                        //else if (att.DimensionReferences.Count == 1)
                        //{
                        //    att.AttachmentLevel = Org.Sdmxsource.Sdmx.Api.Constants.AttributeAttachmentLevel.DataSet;
                        //    continue;
                        //}
                        _attributeList.Add(att.Id);
                    }
                    else
                        _attributeList.Add(att.Id);
                }

            foreach (IDimensionMutableObject dd in dimsToDelete)
            {
                workingDSD.Dimensions.Remove(dd);
            }

            foreach (IAttributeMutableObject ad in attsToDelete)
            {
                workingDSD.Attributes.Remove(ad);
            }

            workingDSD.Id = sdmxDFKey.id;
            workingDSD.AgencyId = sdmxDFKey.agencyid;
            workingDSD.Version = sdmxDFKey.version;

            if (workingDSD.Groups != null)
                workingDSD.Groups.Clear();

            return workingDSD;
        }
        public static int Get_IDCatFromCategorisation(SDMXIdentifier sdmxKey)
        {
            DataWrapper dtw = new DataWrapper(DataWrapper.ECONNECTIONTYPE.SQL, DataSDMX.SQLConnString_DB.ConnectionString);
            int cat_id = -1;
            if (dtw.TestConnection())
            {
                try
                {
                    dtw.DBConnection.Open();

                    string[] version = sdmxKey.version.Split('.');

                    System.Data.IDbCommand cmd = dtw.DBConnection.CreateCommand();
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = String.Format("SELECT B.CAT_ID " +
                                                    "FROM ARTEFACT A " +
                                                    "    INNER JOIN CATEGORISATION B ON " +
                                                    "        B.CATN_ID = A.ART_ID " +
                                                    "WHERE A.ID = '{0}' " +
                                                    "        AND A.AGENCY = '{1}' " +
                                                    "        AND VERSION1 = {2} " +
                                                    "        AND VERSION2 = {3} ",
                                                    sdmxKey.id, sdmxKey.agencyid, version[0], version[1]);
                    object result = cmd.ExecuteScalar();
                    if (result != null)
                        cat_id = int.Parse(result.ToString());

                    dtw.DBConnection.Close();

                    return cat_id;
                }
                catch (Exception ex)
                {
                    throw ex;
                    //return cat_id;
                }
            }
            return cat_id;
        }
        public static ISet<IDataStructureMutableObject> GetDSDList()
        {
            ISdmxMutableObjectRetrievalManager manager = GetManager();

            SDMXIdentifier sdmxKey = new SDMXIdentifier();
            IMaintainableRefObject query = new MaintainableRefObjectImpl(sdmxKey.agencyid, sdmxKey.id, sdmxKey.version);

            ISet<IDataStructureMutableObject> dsds = manager.GetMutableDataStructureObjects(query, false, true);

            // Remove not final dsd
            //List<IDataStructureMutableObject> dsdNotFinal = new List<IDataStructureMutableObject>();
            //foreach (IDataStructureMutableObject dsd in dsds)
            //{
            //    if (!dsd.FinalStructure.IsTrue)
            //        dsdNotFinal.Add(dsd);
            //}
            //foreach (IDataStructureMutableObject dsd in dsdNotFinal)
            //{
            //    dsds.Remove(dsd);
            //}

            return dsds;
        }
        public static IDataStructureObject GetDSD(SDMXIdentifier sdmxKey, bool stub)
        {
            ISdmxMutableObjectRetrievalManager manager = GetManager();

            IMaintainableRefObject query = new MaintainableRefObjectImpl(sdmxKey.agencyid, sdmxKey.id, sdmxKey.version);

            IDataStructureMutableObject dsd = manager.GetMutableDataStructure(query, false, stub);

            return dsd.ImmutableInstance;
        }
        public static IDataflowObject GetDataflow(SDMXIdentifier sdmxKey, bool stub)
        {
            ISdmxMutableObjectRetrievalManager manager = GetManager();

            IMaintainableRefObject query = new MaintainableRefObjectImpl(sdmxKey.agencyid, sdmxKey.id, sdmxKey.version);

            IDataflowMutableObject dataflow = manager.GetMutableDataflow(query, false, stub);

            if (dataflow == null) return null;

            return dataflow.ImmutableInstance;
        }
        public string GetDSD(string agency, string id, string version)
        {
            // Retrive Logged user
            SDMX_Dataloader.Engine.Client client = null;
            try
            {
                client = HttpContext.Current.Session[UserDef.UserSessionKey] as SDMX_Dataloader.Engine.Client; if (client == null) throw new Exception("Session Expiried");
            }
            catch (Exception ex)
            {
                return JsonMessage.SessionExpired;
            }

            try
            {

                if (!UserDef.UserCan(client.LoggedUser, UserDef.ActionDef.DefaultProc))
                    return JsonMessage.GetError(Resources.Notification.err_action_denied);

                if (client.BuilderProcedure == null) client.BuilderProcedure = BuilderProcedure.Create();

                SDMXIdentifier sdmxIdentity = new SDMXIdentifier()
                {
                    agencyid = agency,
                    id = id,
                    version = version
                };

                DataStructure dsd=client.BuilderProcedure.Get_DSD(sdmxIdentity);

                Dictionary<string, object> param = new Dictionary<string, object>();
                param.Add("DIMENSION", dsd.Dimensions);
                param.Add("ATTRIBUTE", dsd.Attributes);

                if (dsd.IsFinal)
                    param.Add("ISFINAL", dsd.IsFinal);

                return JsonMessage.GetData(param);
            }

            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return JsonMessage.GetError(ex.Message);
            }
        }
Example #10
0
        public string DeleteDSD(string agency, string id, string version)
        {
            // Retrive Logged user
            SDMX_Dataloader.Engine.Client client = null;
            try
            {
                client = HttpContext.Current.Session[UserDef.UserSessionKey] as SDMX_Dataloader.Engine.Client; if (client == null) throw new Exception("Session Expiried");
            }
            catch (Exception ex)
            {
                return JsonMessage.SessionExpired;
            }
            try
            {

                if (!UserDef.UserCan(client.LoggedUser, UserDef.ActionDef.CRUDSchema))
                    return JsonMessage.GetError(Resources.Notification.err_action_denied);

                SDMXIdentifier sdmxIdentity = new SDMXIdentifier()
                {
                    agencyid = agency,
                    id = id,
                    version = version
                };

                if (client.BuilderProcedure == null) client.BuilderProcedure = BuilderProcedure.Create();

                client.BuilderProcedure.Delete_DSD(sdmxIdentity);

                return JsonMessage.EmptyJSON;

            }

            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return JsonMessage.GetError(ex.Message);
            }
        }
Example #11
0
        public string CreateExport(string agency, string id, string version, List<string> dimensions, List<string> attributes, string type_download)
        {
            // Retrive Logged user
            SDMX_Dataloader.Engine.Client client = null;
            try
            {
                client = HttpContext.Current.Session[UserDef.UserSessionKey] as SDMX_Dataloader.Engine.Client; if (client == null) throw new Exception("Session Expiried");
            }
            catch (Exception ex)
            {
                return JsonMessage.SessionExpired;
            }

            try
            {

                if (!UserDef.UserCan(client.LoggedUser, UserDef.ActionDef.DefaultProc))
                    return JsonMessage.GetError(Resources.Notification.err_action_denied);

                // Get Settings Properties
                ISTAT.EXPORT.Settings.ContactSettingsHandler configContact =
                   (ISTAT.EXPORT.Settings.ContactSettingsHandler)System.Configuration.ConfigurationManager.GetSection(
                       "ExportDotStatSettingsGroup/ContactSection");

                ISTAT.EXPORT.Settings.SecuritySettingsHandler configSecurity =
                   (ISTAT.EXPORT.Settings.SecuritySettingsHandler)System.Configuration.ConfigurationManager.GetSection(
                       "ExportDotStatSettingsGroup/SecuritySection");

                // Get the current user

                SDMXIdentifier sdmxIdentity = new SDMXIdentifier()
                {
                    agencyid = agency,
                    id = id,
                    version = version
                };

                string filenameDSD = sdmxIdentity.ToString();

                Org.Sdmxsource.Sdmx.Util.Objects.Container.SdmxObjectsImpl sdmxObjects = new Org.Sdmxsource.Sdmx.Util.Objects.Container.SdmxObjectsImpl();

                Org.Sdmxsource.Sdmx.Api.Model.Objects.DataStructure.IDataStructureObject dsd = DataSDMX.GetDSD(sdmxIdentity);

                sdmxObjects.AddDataStructure(dsd);

                foreach (Org.Sdmxsource.Sdmx.Api.Model.Objects.DataStructure.IDimension dim in dsd.DimensionList.Dimensions){
                    if (!dim.TimeDimension && dimensions.Contains(dim.Id) && dim.HasCodedRepresentation())
                    {
                        Org.Sdmxsource.Sdmx.Api.Model.Objects.Codelist.ICodelistObject codelist = DataSDMX.GetCodelist(new SDMXIdentifier()
                        {
                            agencyid = dim.Representation.Representation.MaintainableReference.AgencyId,
                            id = dim.Representation.Representation.MaintainableReference.MaintainableId,
                            version = dim.Representation.Representation.MaintainableReference.Version
                        });
                        sdmxObjects.AddCodelist(codelist);
                    }
                }

                foreach (Org.Sdmxsource.Sdmx.Api.Model.Objects.DataStructure.IAttributeObject att in dsd.Attributes){
                    if (attributes.Contains(att.Id) && att.HasCodedRepresentation())
                    {
                        Org.Sdmxsource.Sdmx.Api.Model.Objects.Codelist.ICodelistObject codelist=DataSDMX.GetCodelist(new SDMXIdentifier(){
                            agencyid = att.Representation.Representation.MaintainableReference.AgencyId,
                            id = att.Representation.Representation.MaintainableReference.MaintainableId,
                            version = att.Representation.Representation.MaintainableReference.Version
                        });
                        sdmxObjects.AddCodelist(codelist);
                    }
                }

                List<ISTAT.IO.Utility.FileGeneric> files = new List<ISTAT.IO.Utility.FileGeneric>();

                List<ContactRef> contacs = new List<ContactRef>();
                contacs.Add(new ContactRef()
                {
                    name = configContact.Name,
                    direction = configContact.Direction,
                    email = configContact.Email
                });

                List<SecurityDef> securities = new List<SecurityDef>();
                securities.Add(new SecurityDef()
                {
                    domain = configSecurity.Domain,
                    userGroup = configSecurity.UserGroup,
                });

                DSDExporter _dsdExp = new DSDExporter(sdmxObjects);

                #region Export DSD
                if (type_download == "dsd")
                {

                    if (_dsdExp.CreateData(
                        contacs,
                        securities,
                        true, false))
                    {
                        System.Xml.XmlDocument xDoc = _dsdExp.XMLDoc;

                        MemoryStream xmlStream = new MemoryStream();
                        xDoc.Save(xmlStream);

                        xmlStream.Flush();
                        xmlStream.Position = 0;

                        ISTAT.IO.Utility.FileGeneric file = new ISTAT.IO.Utility.FileGeneric();
                        file.filename = filenameDSD + ".xml";
                        file.stream = xmlStream;

                        files.Add(file);
                    }
                }
                #endregion
                #region Export Codelist
                if (type_download == "codelist")
                {

                    if (_dsdExp.CreateData(
                        contacs,
                        securities,
                        true, false))
                    {
                        foreach (CodelistExporter _codeExp in _dsdExp.ExporterCodelists)
                        {
                            System.Xml.XmlDocument xDoc_code = _codeExp.XMLDoc;
                            MemoryStream xmlStream_code = new MemoryStream();
                            xDoc_code.Save(xmlStream_code);
                            xmlStream_code.Flush();
                            xmlStream_code.Position = 0;
                            ISTAT.IO.Utility.FileGeneric file_code = new ISTAT.IO.Utility.FileGeneric();
                            file_code.filename = _codeExp.Code.ToString() + ".xml";
                            file_code.stream = xmlStream_code;
                            files.Add(file_code);

                            Stream streamCSV = CSVWriter.CreateStream(_codeExp.DataView);
                            ISTAT.IO.Utility.FileGeneric file_csv = new ISTAT.IO.Utility.FileGeneric();
                            file_csv.filename = _codeExp.DataFilename;
                            file_csv.stream = streamCSV;
                            files.Add(file_csv);
                        }
                    }
                }
                #endregion
                #region Export ALL
                if (type_download == "all")
                {

                    if (_dsdExp.CreateData(
                        contacs,
                        securities,
                        true, false))
                    {
                        System.Xml.XmlDocument xDoc = _dsdExp.XMLDoc;

                        MemoryStream xmlStream = new MemoryStream();
                        xDoc.Save(xmlStream);

                        xmlStream.Flush();
                        xmlStream.Position = 0;

                        ISTAT.IO.Utility.FileGeneric file = new ISTAT.IO.Utility.FileGeneric();
                        file.filename = filenameDSD + ".xml";
                        file.stream = xmlStream;

                        files.Add(file);
                        foreach (CodelistExporter _codeExp in _dsdExp.ExporterCodelists)
                        {
                            System.Xml.XmlDocument xDoc_code = _codeExp.XMLDoc;
                            MemoryStream xmlStream_code = new MemoryStream();
                            xDoc_code.Save(xmlStream_code);
                            xmlStream_code.Flush();
                            xmlStream_code.Position = 0;
                            ISTAT.IO.Utility.FileGeneric file_code = new ISTAT.IO.Utility.FileGeneric();
                            file_code.filename = _codeExp.Code.ToString() + ".xml";
                            file_code.stream = xmlStream_code;
                            files.Add(file_code);

                            Stream streamCSV = CSVWriter.CreateStream(_codeExp.DataView);
                            ISTAT.IO.Utility.FileGeneric file_csv = new ISTAT.IO.Utility.FileGeneric();
                            file_csv.filename = _codeExp.DataFilename;
                            file_csv.stream = streamCSV;
                            files.Add(file_csv);
                        }
                    }
                }
                #endregion

                string fileZip = System.Web.HttpContext.Current.Server.MapPath(@"~\Temp\\" + filenameDSD + ".zip");
                System.IO.File.Delete(fileZip);
                Ionic.Utils.Zip.ZipFile zip = new Ionic.Utils.Zip.ZipFile(fileZip);
                foreach (ISTAT.IO.Utility.FileGeneric file in files)
                    zip.AddFileStream(file.filename, string.Empty, file.stream);
                zip.Save();

                client.FileToDownload = fileZip;

                return JsonMessage.EmptyJSON;

            }
            catch (Exception ex)
            {

                Logger.Error(ex.Message);
                return JsonMessage.ErrorOccured;

            }
        }
        public static SDMXIdentifier GetIdentifierFromIDSet(int idSet)
        {
            DataWrapper dtw = new DataWrapper(DataWrapper.ECONNECTIONTYPE.SQL, DataAccess.SQLConnString_DB.ConnectionString);
            SDMXIdentifier identifier = null;

            if (!dtw.TestConnection())
                throw new Exception("Connection Error!");

            dtw.DBConnection.Open();

            try
            {
                System.Data.IDbCommand cmd = dtw.DBConnection.CreateCommand();
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = "SELECT AgencyID , " +
                                      "  ID , " +
                                      "  Version " +
                                      "  FROM dbo.CatDataFlow " +
                                      "  WHERE IDSet =" + idSet.ToString();

                IDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    identifier = new SDMXIdentifier() { id = reader["ID"].ToString(), agencyid = reader["AgencyID"].ToString(), version = reader["Version"].ToString() };
                }

                dtw.DBConnection.Close();

                return identifier;
            }
            catch (Exception ex)
            {
                dtw.DBConnection.Close();
                throw ex;
            }
        }
        /// <summary>
        /// Insert_DataFlow
        /// </summary>
        /// <param name="idDataFlow">ID of dataflow</param>
        /// <param name="idset">ID of Structure</param>
        /// <returns>Return true if success | false if error</returns>
        public static bool Insert_DataFlow(int idDataFlow, int idset, SDMXIdentifier sdmxKey)
        {
            DataWrapper dtw = new DataWrapper(DataWrapper.ECONNECTIONTYPE.SQL, DataAccess.SQLConnString_DB.ConnectionString);

            if (dtw.TestConnection())
            {
                dtw.DBConnection.Open();
                try
                {

                    ////////////////////////
                    System.Data.IDbCommand cmd = dtw.DBConnection.CreateCommand();
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.CommandText = "dbo.proc_INSERT_DATAFLOW";

                    System.Data.IDbDataParameter _idset = cmd.CreateParameter();
                    _idset.DbType = System.Data.DbType.Int32;
                    _idset.ParameterName = "IDSet";
                    _idset.Value = idset;
                    cmd.Parameters.Add(_idset);

                    System.Data.IDbDataParameter _idFlow = cmd.CreateParameter();
                    _idFlow.DbType = System.Data.DbType.Int32;
                    _idFlow.ParameterName = "IDFlow";
                    _idFlow.Value = idDataFlow;
                    cmd.Parameters.Add(_idFlow);

                    System.Data.IDbDataParameter _agencyID = cmd.CreateParameter();
                    _agencyID.DbType = System.Data.DbType.String;
                    _agencyID.ParameterName = "AgencyID";
                    _agencyID.Value = sdmxKey.agencyid;
                    cmd.Parameters.Add(_agencyID);

                    System.Data.IDbDataParameter _id = cmd.CreateParameter();
                    _id.DbType = System.Data.DbType.String;
                    _id.ParameterName = "ID";
                    _id.Value = sdmxKey.id;
                    cmd.Parameters.Add(_id);

                    System.Data.IDbDataParameter _version = cmd.CreateParameter();
                    _version.DbType = System.Data.DbType.String;
                    _version.ParameterName = "Version";
                    _version.Value = sdmxKey.version;
                    cmd.Parameters.Add(_version);

                    cmd.ExecuteNonQuery();

                    ////////////////////////

                    dtw.DBConnection.Close();
                    return true;
                }
                catch// (Exception ex)
                {
                    dtw.DBConnection.Close();
                    return false;
                }
            } return false;
        }
        protected void btnSaveAll_Click(object sender, EventArgs e)
        {
            RefreshDataTableFromGridView();

            if (!ValidateData())
                return;

            SDMX_Dataloader.Engine.Client client = Session[UserDef.UserSessionKey] as SDMX_Dataloader.Engine.Client;
            string uri = System.Configuration.ConfigurationManager.AppSettings["URIofDataflow"].ToString();

            if (_action == DLEnums.Action.UPDATE)
                QueryBuilderProcedure.DeleteCubeView(_idSet);

            IDataflowMutableObject dataflow = _dfMutable;

            List<string> lComponent;
            lComponent = GetSelectedComponentNames();

            List<CubeFilter> lcubeFilter;
            lcubeFilter = GetCubeFilter();

            SDMXIdentifier sdmxKey = new SDMXIdentifier() { id = txtDFID.Text.ToUpper(), agencyid = GetAgencyValue(), version = txtVersion.Text };

            ISdmxObjects sdmxObjectDsd = new SdmxObjectsImpl();

            bool doRedirect = false;

            try
            {
                QueryBuilderProcedure qb = new QueryBuilderProcedure(Int32.Parse(cmbCubeList.SelectedValue), lComponent, sdmxKey);

                // Salvo la DSD
                sdmxObjectDsd = qb.CreateDSD(AddTextName.TextObjectList);

                // Salvo il DF
                SaveDF();

                int originalIDCat = DataAccess.GetIDCatFromIDSet(Int32.Parse(cmbCubeList.SelectedValue));

                _categoryID = (!String.IsNullOrEmpty(tvCategory.SelectedValue)) ? Int32.Parse(tvCategory.SelectedValue) : originalIDCat;

                int idDSD = ISTAT.DBDAL.DataSDMX.Get_IDDsd(sdmxKey);
                int idDF = ISTAT.DBDAL.DataSDMX.Get_IDDataflow(sdmxKey);

                // Salvo la Categorisation
                //ISTAT.DBDAL.DataSDMX.InsertCategorisation(sdmxKey, idDF, _categoryID, _dfMutable.ImmutableInstance.Urn.AbsoluteUri);

                // Salvo la query cubo
                List<string[]> nameList = GetDFNameList(dataflow);
                List<string[]> descriptionList = GetDFDescriptionList(dataflow);

                //TODO: MODIFICARE
                qb.CreateCubeView(originalIDCat, client.LoggedUser.ID, uri, lcubeFilter, nameList, descriptionList, _categoryID);

                Session[_snInsDf] = null;
                Session[_snSdmxObjects] = null;

                //TODO: Restituisco un messaggio e ritorno alla lista dei cubi
                // DLUtils.ShowMessageBox(this.Page, "Dataloader-Success", "La vista è stata creata correttamente.");

                //ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "script", "location.href='CubeViewList.aspx'", true);
                doRedirect = true;

            }
            catch (Exception ex)
            {
                DataSDMX.DeleteStructure(_sdmxObjects);
                DataSDMX.DeleteStructure(sdmxObjectDsd);
                DLUtils.ShowMessageBox(this.Page, "Dataloader-Error", Resources.Messages.err_saving_cubeview);
            }
            if (doRedirect)
            {
                try
                {
                    Server.Transfer("CubeViewList.aspx");
                }
                catch (Exception ex) { }
            }
        }
        public static IConceptObject GetConcept(SDMXIdentifier sdmxKey, string idConcept)
        {
            ISdmxMutableObjectRetrievalManager manager = GetManager();

            IMaintainableRefObject query = new MaintainableRefObjectImpl(sdmxKey.agencyid, sdmxKey.id, sdmxKey.version);

            IConceptSchemeMutableObject concepts = manager.GetMutableConceptScheme(query, false, false);
            foreach (IConceptObject concept in concepts.ImmutableInstance.Items)
            {
                if (concept.Id == idConcept)
                {

                    return concept;
                }
            }
            return null;
        }
 public void Delete_DSD(SDMXIdentifier sdmxIdentity)
 {
     var result=ISTAT.DBDAL.DataSDMX.DeleteStructure(sdmxIdentity);
 }
        public static ICodelistObject GetConceptSchemeItems(SDMXIdentifier sdmxKey)
        {
            ISdmxMutableObjectRetrievalManager manager = GetManager();

            IMaintainableRefObject query = new MaintainableRefObjectImpl(sdmxKey.agencyid, sdmxKey.id, sdmxKey.version);

            Org.Sdmxsource.Sdmx.SdmxObjects.Model.Mutable.Codelist.CodelistMutableCore codelist =
                new Org.Sdmxsource.Sdmx.SdmxObjects.Model.Mutable.Codelist.CodelistMutableCore();

            codelist.Id = sdmxKey.id;
            codelist.AgencyId = sdmxKey.agencyid;
            codelist.Version = sdmxKey.version;
            codelist.StructureType = Org.Sdmxsource.Sdmx.Api.Constants.SdmxStructureType.GetFromEnum(Org.Sdmxsource.Sdmx.Api.Constants.SdmxStructureEnumType.CodeList);
            //codelist.StartDate = codelist.EndDate = DateTime.Now;
            codelist.FinalStructure = Org.Sdmxsource.Sdmx.Api.Constants.TertiaryBool.GetFromEnum(Org.Sdmxsource.Sdmx.Api.Constants.TertiaryBoolEnumType.True);

            IConceptSchemeMutableObject concepts = manager.GetMutableConceptScheme(query, false, false);

            foreach (ITextTypeWrapper IText in concepts.ImmutableInstance.Names)
                codelist.Names.Add(new Org.Sdmxsource.Sdmx.SdmxObjects.Model.Mutable.Base.TextTypeWrapperMutableCore(IText));
            foreach (ITextTypeWrapper IText in concepts.ImmutableInstance.Descriptions)
                codelist.Descriptions.Add(new Org.Sdmxsource.Sdmx.SdmxObjects.Model.Mutable.Base.TextTypeWrapperMutableCore(IText));

            foreach (IConceptObject concept in concepts.ImmutableInstance.Items)
            {

                Org.Sdmxsource.Sdmx.SdmxObjects.Model.Mutable.Codelist.CodeMutableCore code =
                    new Org.Sdmxsource.Sdmx.SdmxObjects.Model.Mutable.Codelist.CodeMutableCore();

                code.Id = concept.Id;
                code.ParentCode = concept.ParentConcept;

                foreach (ITextTypeWrapper IText in concept.Names)
                    code.Names.Add(new Org.Sdmxsource.Sdmx.SdmxObjects.Model.Mutable.Base.TextTypeWrapperMutableCore(IText));
                foreach (ITextTypeWrapper IText in concept.Descriptions)
                    code.Descriptions.Add(new Org.Sdmxsource.Sdmx.SdmxObjects.Model.Mutable.Base.TextTypeWrapperMutableCore(IText));

                codelist.AddItem(code);

            }
            return codelist.ImmutableInstance;
        }
        public List<Dictionary<string, string>> Get_DSDs()
        {
            ISet<Org.Sdmxsource.Sdmx.Api.Model.Mutable.DataStructure.IDataStructureMutableObject> dsds = ISTAT.DBDAL.DataSDMX.GetDSDList();
            List<Dictionary<string, string>> _res = new List<Dictionary<string, string>>();
            foreach (Org.Sdmxsource.Sdmx.Api.Model.Mutable.DataStructure.IDataStructureMutableObject dsd in dsds)
            {

                SDMXIdentifier sdmxIdentity = new SDMXIdentifier()
                {
                    agencyid = dsd.AgencyId,
                    id = dsd.Id,
                    version = dsd.Version
                };

                List<TextTypeWrapper> locations = new List<TextTypeWrapper>();
                foreach (Org.Sdmxsource.Sdmx.Api.Model.Mutable.Base.ITextTypeWrapperMutableObject text in dsd.Names)
                    locations.Add(new TextTypeWrapper(text.Locale, text.Value));

                int langIndex = TextTypeWrapper.GetIndexLocale(locations, SDMX_Dataloader.Engine.BuilderProcedure.CurrentCultureInfo);

                Dictionary<string, string> _result = new Dictionary<string, string>();

                string notFinal = "";

                if (!dsd.FinalStructure.IsTrue)
                    notFinal = "(Not final)";

                _result.Add("Text", string.Format(" [ {0} ] - {1} ", notFinal +" "+ sdmxIdentity.ToString(), dsd.Names[langIndex].Value));
                _result.Add("Value", sdmxIdentity.ToString());

                _res.Add(_result);
            }
            return _res;
        }
        public static int GetDataflowID(SDMXIdentifier sdmxKey)
        {
            DataWrapper dtw = new DataWrapper(DataWrapper.ECONNECTIONTYPE.SQL, DataSDMX.SQLConnString_DB.ConnectionString);
            int dfID = 0;

            if (dtw.TestConnection())
            {
                try
                {
                    dtw.DBConnection.Open();

                    string sql = string.Format("SELECT a.ART_ID " +
                                                "FROM dbo.ARTEFACT a " +
                                                "    INNER JOIN  dbo.DATAFLOW b ON  " +
                                                "        b.DF_ID = a.ART_ID  " +
                                                "WHERE A.ID = '{0}'  " +
                                                "        AND A.VERSION1 = '{1}'  " +
                                                "        AND A.VERSION2 = '{2}'  " +
                                                "        AND AGENCY = '{3}' ",
                                                sdmxKey.id,
                                                sdmxKey.version.Substring(0, sdmxKey.version.IndexOf(".")),
                                                sdmxKey.version.Substring(sdmxKey.version.IndexOf(".") + 1),
                                                sdmxKey.agencyid);

                    System.Data.IDbCommand cmd = dtw.DBConnection.CreateCommand();
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = sql;

                    System.Data.IDataReader reader = cmd.ExecuteReader();

                    if (reader.Read())
                    {
                        dfID = Int32.Parse(reader["ART_ID"].ToString());
                    }

                    dtw.DBConnection.Close();

                    return dfID;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return 0;
        }
        public static int InsertCategorisation(SDMXIdentifier sdmxKey, int idFlow, int idCat, string uri)
        {
            DataWrapper dtw = new DataWrapper(DataWrapper.ECONNECTIONTYPE.SQL, DataSDMX.SQLConnString_DB.ConnectionString);
            if (dtw.TestConnection())
            {
                try
                {
                    dtw.DBConnection.Open();

                    System.Data.IDbCommand cmd_cat = dtw.DBConnection.CreateCommand();
                    cmd_cat.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd_cat.CommandText = "dbo.INSERT_CATEGORISATION";

                    System.Data.IDbDataParameter _id_df = cmd_cat.CreateParameter();
                    _id_df.DbType = System.Data.DbType.String;
                    _id_df.ParameterName = "p_id";
                    _id_df.Value = sdmxKey.id;
                    cmd_cat.Parameters.Add(_id_df);

                    System.Data.IDbDataParameter _version_df = cmd_cat.CreateParameter();
                    _version_df.DbType = System.Data.DbType.String;
                    _version_df.ParameterName = "p_version";
                    _version_df.Value = sdmxKey.version;
                    cmd_cat.Parameters.Add(_version_df);

                    System.Data.IDbDataParameter _agency_df = cmd_cat.CreateParameter();
                    _agency_df.DbType = System.Data.DbType.String;
                    _agency_df.ParameterName = "p_agency";
                    _agency_df.Value = sdmxKey.agencyid;
                    cmd_cat.Parameters.Add(_agency_df);

                    System.Data.IDbDataParameter _uri_df = cmd_cat.CreateParameter();
                    _uri_df.DbType = System.Data.DbType.String;
                    _uri_df.ParameterName = "p_uri";
                    _uri_df.Value = uri;
                    cmd_cat.Parameters.Add(_uri_df);

                    System.Data.IDbDataParameter _art_id = cmd_cat.CreateParameter();
                    _art_id.DbType = System.Data.DbType.Int32;
                    _art_id.ParameterName = "p_art_id";
                    _art_id.Value = idFlow;
                    cmd_cat.Parameters.Add(_art_id);

                    System.Data.IDbDataParameter _cat_id = cmd_cat.CreateParameter();
                    _cat_id.DbType = System.Data.DbType.Int32;
                    _cat_id.ParameterName = "p_cat_id";
                    _cat_id.Value = idCat;
                    cmd_cat.Parameters.Add(_cat_id);

                    System.Data.IDbDataParameter _pk_cat = cmd_cat.CreateParameter();
                    _pk_cat.DbType = System.Data.DbType.Int32;
                    _pk_cat.ParameterName = "p_pk";
                    _pk_cat.Direction = System.Data.ParameterDirection.Output;
                    cmd_cat.Parameters.Add(_pk_cat);

                    cmd_cat.ExecuteNonQuery();

                    return (int)_pk_cat.Value;

                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return -1;
        }
        public static IDataStructureObject GetDSDFromDataflowID(int dfID)
        {
            DataWrapper dtw = new DataWrapper(DataWrapper.ECONNECTIONTYPE.SQL, DataSDMX.SQLConnString_DB.ConnectionString);
            SDMXIdentifier sdmxKey;

            if (dtw.TestConnection())
            {
                try
                {
                    dtw.DBConnection.Open();

                    string sql = string.Format("SELECT b.ID,b.AGENCY, " +
                                                "'Version'=CAST(b.VERSION1 AS VARCHAR(2)) + '.' + CAST(b.VERSION2 AS VARCHAR(2)) " +
                                                "FROM DATAFLOW a  " +
                                                "    INNER JOIN ARTEFACT b ON " +
                                                "        a.DSD_ID = b.ART_ID " +
                                                "WHERE DF_ID = {0} ",
                                                dfID.ToString());

                    System.Data.IDbCommand cmd = dtw.DBConnection.CreateCommand();
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = sql;

                    System.Data.IDataReader reader = cmd.ExecuteReader();

                    if (reader.Read())
                    {
                        sdmxKey = new SDMXIdentifier()
                        {
                            id = reader["ID"].ToString(),
                            agencyid = reader["AGENCY"].ToString(),
                            version = reader["Version"].ToString()
                        };

                        return GetDSD(sdmxKey, false);
                    }

                    dtw.DBConnection.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return null;
        }
        public static int Insert_Dataflow(SDMXIdentifier sdmxKey, int dsd_id, int idCat, List<TextTypeWrapper> names, List<TextTypeWrapper> descs, string uri)
        {
            DataWrapper dtw = new DataWrapper(DataWrapper.ECONNECTIONTYPE.SQL, DataSDMX.SQLConnString_DB.ConnectionString);
            int idFlow = -1;
            if (dtw.TestConnection())
            {
                try
                {
                    dtw.DBConnection.Open();

                    ////////////////////////

                    #region Insert dataflow
                    System.Data.IDbCommand cmd = dtw.DBConnection.CreateCommand();
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.CommandText = "dbo.INSERT_DATAFLOW";

                    System.Data.IDbDataParameter _id = cmd.CreateParameter();
                    _id.DbType = System.Data.DbType.String;
                    _id.ParameterName = "p_id";
                    _id.Value = sdmxKey.id;
                    cmd.Parameters.Add(_id);

                    System.Data.IDbDataParameter _version = cmd.CreateParameter();
                    _version.DbType = System.Data.DbType.String;
                    _version.ParameterName = "p_version";
                    _version.Value = sdmxKey.version;
                    cmd.Parameters.Add(_version);

                    System.Data.IDbDataParameter _agency = cmd.CreateParameter();
                    _agency.DbType = System.Data.DbType.String;
                    _agency.ParameterName = "p_agency";
                    _agency.Value = sdmxKey.agencyid;
                    cmd.Parameters.Add(_agency);

                    System.Data.IDbDataParameter _uri = cmd.CreateParameter();
                    _uri.DbType = System.Data.DbType.String;
                    _uri.ParameterName = "p_uri";
                    _uri.Value = uri;
                    cmd.Parameters.Add(_uri);

                    System.Data.IDbDataParameter _dsd_id = cmd.CreateParameter();
                    _dsd_id.DbType = System.Data.DbType.Int32;
                    _dsd_id.ParameterName = "p_dsd_id";
                    _dsd_id.Value = dsd_id;
                    cmd.Parameters.Add(_dsd_id);

                    System.Data.IDbDataParameter _is_final = cmd.CreateParameter();
                    _is_final.DbType = System.Data.DbType.Int32;
                    _is_final.ParameterName = "p_is_final";
                    _is_final.Value = 0;
                    cmd.Parameters.Add(_is_final);

                    int pk = -1;
                    System.Data.IDbDataParameter _pk = cmd.CreateParameter();
                    _pk.DbType = System.Data.DbType.Int32;
                    _pk.ParameterName = "p_pk";
                    _pk.Value = pk;
                    _pk.Direction = System.Data.ParameterDirection.Output;
                    cmd.Parameters.Add(_pk);

                    object obj = cmd.ExecuteScalar();

                    #endregion

                    idFlow = int.Parse(_pk.Value.ToString());

                    #region Insert Localised string

                    System.Data.IDbCommand cmd_localised = dtw.DBConnection.CreateCommand();
                    cmd_localised.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd_localised.CommandText = "dbo.INSERT_LOCALISED_STRING";

                    System.Data.IDbDataParameter _p_art_id = cmd_localised.CreateParameter();
                    _p_art_id.DbType = System.Data.DbType.Int32;
                    _p_art_id.ParameterName = "p_art_id";
                    _p_art_id.Value = idFlow;
                    cmd_localised.Parameters.Add(_p_art_id);

                    System.Data.IDbDataParameter _p_text = cmd_localised.CreateParameter();
                    _p_text.DbType = System.Data.DbType.String;
                    _p_text.ParameterName = "p_text";
                    cmd_localised.Parameters.Add(_p_text);

                    System.Data.IDbDataParameter _p_type = cmd_localised.CreateParameter();
                    _p_type.DbType = System.Data.DbType.String;
                    _p_type.ParameterName = "p_type";
                    cmd_localised.Parameters.Add(_p_type);

                    System.Data.IDbDataParameter _p_language = cmd_localised.CreateParameter();
                    _p_language.DbType = System.Data.DbType.String;
                    _p_language.ParameterName = "p_language";
                    cmd_localised.Parameters.Add(_p_language);

                    int pk_localised = -1;
                    System.Data.IDbDataParameter _pk_localised = cmd_localised.CreateParameter();
                    _pk_localised.DbType = System.Data.DbType.Int32;
                    _pk_localised.ParameterName = "p_pk";
                    _pk_localised.Value = pk_localised;
                    _pk_localised.Direction = System.Data.ParameterDirection.Output;
                    cmd_localised.Parameters.Add(_pk_localised);

                    foreach (TextTypeWrapper name in names)
                    {
                        _p_language.Value = name.Locale;
                        _p_type.Value = "Name";
                        _p_text.Value = name.Value;
                        cmd_localised.ExecuteNonQuery();
                    }
                    foreach (TextTypeWrapper desc in descs)
                    {
                        _p_language.Value = desc.Locale;
                        _p_type.Value = "Desc";
                        _p_text.Value = desc.Value;
                        cmd_localised.ExecuteNonQuery();
                    }

                    #endregion

                    dtw.DBConnection.Close();

                    //InsertCategorisation(sdmxKey, idFlow, idCat, uri);

                    return idFlow;
                }
                catch// (Exception ex)
                {
                    return idFlow;
                }
            } return idFlow;
        }
        public static System.IO.MemoryStream GetStreamSDMXObject(SDMXIdentifier sdmxIdentity, Org.Sdmxsource.Sdmx.Api.Constants.SdmxStructureEnumType structureType)
        {
            ISdmxMutableObjectRetrievalManager manager = GetManager();

            IMaintainableRefObject query = new MaintainableRefObjectImpl(sdmxIdentity.agencyid, sdmxIdentity.id, sdmxIdentity.version);

            Org.Sdmxsource.Sdmx.Api.Model.Objects.ISdmxObjects sdmxObjects =
                new Org.Sdmxsource.Sdmx.Util.Objects.Container.SdmxObjectsImpl();

            switch (structureType)
            {
                case Org.Sdmxsource.Sdmx.Api.Constants.SdmxStructureEnumType.AgencyScheme:
                    sdmxObjects.AddAgencyScheme(manager.GetMutableAgencyScheme(query, false, false).ImmutableInstance);
                    break;
                case Org.Sdmxsource.Sdmx.Api.Constants.SdmxStructureEnumType.CategoryScheme:
                    sdmxObjects.AddCategoryScheme(manager.GetMutableCategoryScheme(query, false, false).ImmutableInstance);
                    break;
                case Org.Sdmxsource.Sdmx.Api.Constants.SdmxStructureEnumType.ConceptScheme:
                    sdmxObjects.AddConceptScheme(manager.GetMutableConceptScheme(query, false, false).ImmutableInstance);
                    break;
                case Org.Sdmxsource.Sdmx.Api.Constants.SdmxStructureEnumType.CodeList:
                    sdmxObjects.AddCodelist(manager.GetMutableCodelist(query, false, false).ImmutableInstance);
                    break;
                case Org.Sdmxsource.Sdmx.Api.Constants.SdmxStructureEnumType.Dsd:
                    sdmxObjects.AddDataStructure(manager.GetMutableDataStructure(query, false, false).ImmutableInstance);
                    break;
            }

            System.IO.MemoryStream mem = GetStream(sdmxObjects, Org.Sdmxsource.Sdmx.Api.Constants.StructureOutputFormatEnumType.SdmxV21StructureDocument);

            return mem;
        }
        public static ICategorisationObject GetCategorisation(SDMXIdentifier sdmxKey, bool stub)
        {
            ISdmxMutableObjectRetrievalManager manager = GetManager();

            IMaintainableRefObject query = new MaintainableRefObjectImpl(sdmxKey.agencyid, sdmxKey.id, sdmxKey.version);

            ICategorisationMutableObject cat = manager.GetMutableCategorisation(query, false, stub);

            return cat.ImmutableInstance;
        }
        public static int Get_IDDataflow(SDMXIdentifier sdmxKey)
        {
            DataWrapper dtw = new DataWrapper(DataWrapper.ECONNECTIONTYPE.SQL, DataSDMX.SQLConnString_DB.ConnectionString);
            int df_id = -1;
            if (dtw.TestConnection())
            {
                try
                {
                    dtw.DBConnection.Open();

                    ////////////////////////

                    System.Data.IDbCommand cmd = dtw.DBConnection.CreateCommand();
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = "SELECT ART_ID " +
                                      "FROM ARTEFACT A " +
                                      "INNER JOIN DATAFLOW B ON A.ART_ID = B.DF_ID " +
                                      "WHERE ID='" + sdmxKey.id +
                                      "' AND  AGENCY='" + sdmxKey.agencyid +
                                      "' AND  CAST(VERSION1 as char(1))+CASE ISNULL(VERSION2,-1) WHEN -1 THEN '' ELSE '.' END+CAST(VERSION2 as char(1))+CASE ISNULL(VERSION3,-1) WHEN -1 THEN '' ELSE '.' END+CASE ISNULL(VERSION3,-1) WHEN -1 THEN '' ELSE CAST(VERSION3 as char(1)) END ='" + sdmxKey.version + "'";
                    object result = cmd.ExecuteScalar();
                    if (result != null)
                        df_id = int.Parse(result.ToString());

                    ////////////////////////

                    dtw.DBConnection.Close();

                    return df_id;
                }
                catch //(Exception ex)
                {
                    return df_id;
                }
            }
            return df_id;
        }
        public static List<ICategoryObject> GetCategoryScheme()
        {
            ISdmxMutableObjectRetrievalManager manager = GetManager();

            SDMXIdentifier sdmxKey = new SDMXIdentifier();
            IMaintainableRefObject query = new MaintainableRefObjectImpl(sdmxKey.agencyid, sdmxKey.id, sdmxKey.version);

            ISet<Org.Sdmxsource.Sdmx.Api.Model.Mutable.CategoryScheme.ICategorySchemeMutableObject> categories =
                manager.GetMutableCategorySchemeObjects(query, false, false);

            List<Org.Sdmxsource.Sdmx.Api.Model.Objects.CategoryScheme.ICategoryObject> cats = new List<Org.Sdmxsource.Sdmx.Api.Model.Objects.CategoryScheme.ICategoryObject>();

            foreach (Org.Sdmxsource.Sdmx.Api.Model.Mutable.CategoryScheme.ICategorySchemeMutableObject catSchm in categories)
            {
                cats.AddRange(GetCategories(catSchm.ImmutableInstance.Items));
            }

            return cats;
        }
 public QueryBuilderProcedure(int originalIDSet, List<string> lCubeColumnsName, SDMXIdentifier sdmxDFKey)
 {
     _originalIDSet = originalIDSet;
     _lCubeColumnsName = lCubeColumnsName;
     _sdmxDFKey = sdmxDFKey;
 }
        public DataStructure Create_DATASET(int iduser, string code,
                                            int categoryCode,
                                            List<string[]> names,
                                            List<string[]> descs, List<string> dimensions,
                                            List<string> attributes, string uriDataflow,
                                            bool isCube, int originalIDSet = 0,
                                            List<string> lCubeColumnsName = null,
                                            List<CubeFilter> lCubeFilter = null,
                                            int idflow = 0,
                                            int idCat= 0)
        {
            #region GET ALL INFO FOR DIMENSIONI

            List<Dimension> _partDim = new List<Dimension>();
            foreach (Dimension dim in _ds.Dimensions)
            {
                try
                {
                    if (dimensions.Contains(dim.Id))
                    {
                        if (!dim.TimeDimension)
                        {
                            if (dim.MeasureDimension)
                            {
                                Org.Sdmxsource.Sdmx.Api.Model.Objects.Codelist.ICodelistObject codelist =
                                ISTAT.DBDAL.DataSDMX.GetConceptSchemeItems(new SDMXIdentifier()
                                {
                                    agencyid = dim.CodelistAgency,
                                    id = dim.Codelist,
                                    version = dim.CodelistVersion
                                });

                                dim.Merge(codelist);
                            }
                            else
                            {
                                //Logger.DebugFormat("Create Datastructure Process: Retrive Codelist for dimension {0}", dim.Codelist);

                                Org.Sdmxsource.Sdmx.Api.Model.Objects.Codelist.ICodelistObject codelist =
                                ISTAT.DBDAL.DataSDMX.GetCodelist(new SDMXIdentifier()
                                {
                                    agencyid = dim.CodelistAgency,
                                    id = dim.Codelist,
                                    version = dim.CodelistVersion
                                });

                                dim.Merge(codelist);

                            }
                        }
                        else
                        {

                            Org.Sdmxsource.Sdmx.Api.Model.Objects.ConceptScheme.IConceptObject concept =
                            ISTAT.DBDAL.DataSDMX.GetConcept(new SDMXIdentifier()
                            {
                                agencyid = dim.ConceptSchemeAgency,
                                id = dim.ConceptSchemeId,
                                version = dim.ConceptSchemeVersion
                            }, dim.Id);

                            dim.Merge(concept);

                        }

                        _partDim.Add(dim);

                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            _ds.Dimensions = _partDim;

            #endregion
            #region GET ALL INFO FOR ATTRIBUTI

            List<ISTAT.ENTITY.Attribute> _partAtt = new List<ISTAT.ENTITY.Attribute>();
            foreach (ISTAT.ENTITY.Attribute att in _ds.Attributes)
            {
                try
                {
                    if (attributes.Contains(att.Id))
                    {
                        //Logger.DebugFormat("Create Datastructure Process: Retrive Codelist for attribute {0}", att.Codelist);

                        if (att.CodelistAgency != null && att.Codelist != null && att.CodelistVersion != null)
                        {
                            Org.Sdmxsource.Sdmx.Api.Model.Objects.Codelist.ICodelistObject codelist =
                            ISTAT.DBDAL.DataSDMX.GetCodelist(new SDMXIdentifier()
                            {
                                agencyid = att.CodelistAgency,
                                id = att.Codelist,
                                version = att.CodelistVersion
                            });

                            att.Merge(codelist);
                        }
                        else
                        {
                            Org.Sdmxsource.Sdmx.Api.Model.Objects.ConceptScheme.IConceptObject concept =
                            ISTAT.DBDAL.DataSDMX.GetConcept(new SDMXIdentifier()
                            {
                                agencyid = att.ConceptSchemeAgency,
                                id = att.ConceptSchemeId,
                                version = att.ConceptSchemeVersion
                            }, att.ConceptRef);

                            att.Merge(concept);
                        }

                        _partAtt.Add(att);
                    }
                }
                catch// (Exception ex)
                {
                    //Logger.Warn(ex.Message);
                }
            }
            _ds.Attributes = _partAtt;

            #endregion

            int idSet = -1;
            //int idflow = -1;
            int idCategory = -1;
            try
            {

                if (idCat == 0)
                    idCat = categoryCode;

                //if ((idCategory = ISTAT.DBDAL.DataAccess.Insert_Theme(categoryCode)) > 0)
                //{

                if ((idSet = ISTAT.DBDAL.DataAccess.Insert_DataStructure(iduser, idCat, code, isCube)) > 0)
                    {

                        List<TextTypeWrapper> locationNames = new List<TextTypeWrapper>();
                        foreach (string[] name in names)
                            if (name[1] != string.Empty)
                                locationNames.Add(new TextTypeWrapper(name[0].ToString(), name[1].ToString()));

                        List<TextTypeWrapper> locationDescs = new List<TextTypeWrapper>();
                        foreach (string[] desc in descs)
                            if (desc[1] != string.Empty)
                                locationDescs.Add(new TextTypeWrapper(desc[0].ToString(), desc[1].ToString()));

                        if (!ISTAT.DBDAL.DataAccess.Insert_LocalisedString(locationNames, idSet, "CatSet"))
                            throw new Exception("Insert string location fail");

                        _ds.IDSet = idSet;
                        _ds.DSDIdentifier.id = _ds.Code = code;
                        _ds.IDCat = idCategory;
                        _ds.Names = locationNames;

                        //if(idCat == 0)
                        //    idCat = ISTAT.DBDAL.DataSDMX.Get_IDCategory(categoryCode);

                        if (idflow != 0 || (idflow = GetOrInsertDataflow(idCat, locationNames, locationDescs, uriDataflow)) > 0)
                        {
                            #region Categorisation

                            CategoryScheme cs = ISTAT.DBDAL.DataAccess.GetCategoryInfo(idCat);
                            string catsID = GetCategorisationID(cs);

                            SDMXIdentifier sdmxIDCategorisation = new SDMXIdentifier()
                            {
                                id = catsID,
                                agencyid = _ds.DSDIdentifier.agencyid,
                                version = "1.0"
                            };

                            ISTAT.DBDAL.DataSDMX.InsertCategorisation(sdmxIDCategorisation, idflow, idCat, uriDataflow);

                            #endregion

                            // Set status of production off
                            ISTAT.DBDAL.DataSDMX.Set_DataflowProduction(idflow, false);

                            if (idflow > 0)
                            {
                                if (!ISTAT.DBDAL.DataAccess.Insert_DataFlow(idflow, _ds.IDSet, _ds.DSDIdentifier))
                                    throw new Exception("Insert and registry Dataflow fail");
                            }

                            //Logger.DebugFormat("Create Datastructure Process: Insert and registry Dimensions");
                            if (!ISTAT.DBDAL.DataAccess.Insert_Dimension(_ds.IDSet, _ds.Dimensions))
                                throw new Exception("Insert and registry Dimensions fail");

                            //Logger.DebugFormat("Create Datastructure Process: Insert and registry Attributes");
                            if (!ISTAT.DBDAL.DataAccess.Insert_Attribute(_ds.IDSet, _ds.Attributes))
                                throw new Exception("Insert and registry Attributes fail");

                            //TODO: DA RIVEDERE PER OTTIMIZZAZIONE
                            //Logger.DebugFormat("Create Datastructure Process: Insert dimensions code");
                            if (!ISTAT.DBDAL.DataAccess.Insert_DimensionItems(_ds.Dimensions))
                                throw new Exception("Insert dimensions code fail");

                            //TODO: DA RIVEDERE PER OTTIMIZZAZIONE
                            //Logger.DebugFormat("Create Datastructure Process: Insert Attributes code");
                            if (!ISTAT.DBDAL.DataAccess.Insert_AttributeItems(_ds.Attributes))
                                throw new Exception("Insert Attributes code fail");

                            //Logger.DebugFormat("Create Datastructure Process: Create fact table");
                            if (isCube)
                            {
                                if (!ISTAT.DBDAL.DataAccess.Create_FactTable(_ds.IDSet))
                                    throw new Exception("Create fact table fail");
                            }
                            else
                            {
                                // Inserisco in CubeViewRelation (cubeProps)
                                ISTAT.DBDAL.DataAccess.InsertCubeRelation(idSet, originalIDSet);

                                // Inserisco in CubeColumns (lCubeColumnsName)
                                ISTAT.DBDAL.DataAccess.InsertCatCubeColumnsName(idSet, lCubeColumnsName);

                                // Inserisco in CubeFilter (lCubeFilter)
                                ISTAT.DBDAL.DataAccess.InsertCatCubeFilter(idSet, lCubeFilter);

                                ISTAT.DBDAL.DataAccess.Create_CubeViews(_ds.IDSet, originalIDSet);

                                //ISTAT.DBDAL.DataAccess.AddCategoryToCube(_ds.IDSet, idCat);

                            }

                            return this._ds;
                            //Logger.DebugFormat("Create Datastructure Process: End");

                        }
                        else throw new Exception();
                    }
                    else throw new Exception();
                //}
                //else throw new Exception();
            }
            catch (Exception ex)
            {

                ISTAT.DBDAL.DataAccess.Delete_Datastructure(idSet);
                ISTAT.DBDAL.DataSDMX.Delete_Dataflow(idflow);

                throw ex;
                //return null;
            }
        }