private ICodelistObject GetCodeListCostraint(
            IDataflowObject df,
            IDataStructureObject kf,
            IComponent component)
        {
            //           ICodelistObject codes = GetCodeList(query, component);

            ICodelistObject codes = null;

            bool Contrained = component.StructureType.EnumType != Org.Sdmxsource.Sdmx.Api.Constants.SdmxStructureEnumType.DataAttribute;

            #region Criteria
            List<IContentConstraintMutableObject> criterias = new List<IContentConstraintMutableObject>();
            if (Contrained)
            {
                string currentComponent = component.ConceptRef.ChildReference.Id;

                IContentConstraintMutableObject criteria = new ContentConstraintMutableCore();
                criteria.Id = currentComponent ?? "SPECIAL";
                criteria.AddName("en", "english");
                criteria.AgencyId = "agency";

                ICubeRegionMutableObject region = new CubeRegionMutableCore();

                if (currentComponent != null)
                {
                    IKeyValuesMutable keyValue = new KeyValuesMutableImpl();
                    keyValue.Id = currentComponent;
                    keyValue.AddValue(SpecialValues.DummyMemberValue);
                    region.AddKeyValue(keyValue);

                    if (CodemapObj.PreviusCostraint != null)
                    {
                        foreach (string costreintKey in CodemapObj.PreviusCostraint.Keys)
                        {
                            if (costreintKey == currentComponent) continue;
                            if (costreintKey == kf.TimeDimension.Id)
                            {

                                // Qui considerare il caso in qui in CodemapObj.PreviusCostraint[costreintKey][0] ci sia solo un valore, ke equivale alla data da.
                                if (CodemapObj.PreviusCostraint[costreintKey].Count > 1)
                                //if (!string.IsNullOrEmpty(CodemapObj.PreviusCostraint[costreintKey][1]))
                                {
                                    DateTime MinDate = GetDateTimeFromSDMXTimePeriod(CodemapObj.PreviusCostraint[costreintKey][0].ToString(), 'M'); //DateTime.ParseExact(CodemapObj.PreviusCostraint[costreintKey][0].ToString(), "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None);
                                    DateTime MaxDate = GetDateTimeFromSDMXTimePeriod(CodemapObj.PreviusCostraint[costreintKey][1].ToString(), 'M'); //DateTime.ParseExact(CodemapObj.PreviusCostraint[costreintKey][1].ToString(), "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None);

                                    if (MinDate.CompareTo(MaxDate) > 0)
                                    {
                                        criteria.StartDate = MaxDate;
                                        criteria.EndDate = MinDate;
                                    }
                                    else
                                    {
                                        criteria.StartDate = MinDate;
                                        criteria.EndDate = MaxDate;
                                    }

                                }
                            }
                            else
                            {
                                foreach (var code in CodemapObj.PreviusCostraint[costreintKey])
                                {
                                    IKeyValuesMutable _keyValue = new KeyValuesMutableImpl();
                                    _keyValue.Id = costreintKey;
                                    _keyValue.AddValue(code);
                                    region.AddKeyValue(_keyValue);
                                }
                            }
                        }
                    }

                }
                criteria.IncludedCubeRegion = region;
                criterias.Add(criteria);

            }
            #endregion

            codes = GetSDMXObject.GetCodelist(df, kf, component, criterias, Contrained);

            return codes;
        }
        public int GetCountObservation(SessionQuery query)
        {
            ISdmxObjects structure = query.Structure;
            IDataflowObject df = structure.Dataflows.First();
            IDataStructureObject kf = structure.DataStructures.First();

            if (kf == null)
                throw new InvalidOperationException("DataStructure is not set");
            if (df == null)
                throw new InvalidOperationException("Dataflow is not set");

            var currentComponent = "CL_COUNT";

            IContentConstraintMutableObject criteria = new ContentConstraintMutableCore();
            criteria.Id = currentComponent;
            criteria.AddName("en", "english");
            criteria.AgencyId = "agency";
            ICubeRegionMutableObject region = new CubeRegionMutableCore();

            if (currentComponent != null)
            {
                IKeyValuesMutable keyValue = new KeyValuesMutableImpl();
                keyValue.Id = currentComponent;
                keyValue.AddValue(SpecialValues.DummyMemberValue);
                region.AddKeyValue(keyValue);

                if (query.Criteria != null)
                {
                    foreach (string costreintKey in query.Criteria.Keys)
                    {
                        if (costreintKey == currentComponent) continue;
                        if (costreintKey == kf.TimeDimension.Id)
                        {

                            // Qui considerare il caso in qui in CodemapObj.PreviusCostraint[costreintKey][0] ci sia solo un valore, ke equivale alla data da.
                            if (query.Criteria[costreintKey].Count > 1)
                            {
                                DateTime MinDate = GetDateTimeFromSDMXTimePeriod(query.Criteria[costreintKey][0].ToString(), 'M'); //DateTime.ParseExact(CodemapObj.PreviusCostraint[costreintKey][0].ToString(), "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None);
                                DateTime MaxDate = GetDateTimeFromSDMXTimePeriod(query.Criteria[costreintKey][1].ToString(), 'M'); //DateTime.ParseExact(CodemapObj.PreviusCostraint[costreintKey][1].ToString(), "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None);
                                //baco fabio
                                if (MinDate.CompareTo(MaxDate) > 0)
                                {
                                    criteria.StartDate = MaxDate;
                                    criteria.EndDate = MinDate;
                                }
                                else
                                {
                                    criteria.StartDate = MinDate;
                                    criteria.EndDate = MaxDate;
                                }

                            }
                        }
                        else
                        {
                            foreach (var code in query.Criteria[costreintKey])
                            {
                                IKeyValuesMutable _keyValue = new KeyValuesMutableImpl();
                                _keyValue.Id = costreintKey;
                                _keyValue.AddValue(code);
                                region.AddKeyValue(_keyValue);
                            }
                        }
                    }
                }

            }
            criteria.IncludedCubeRegion = region;

            GetSDMXObject = WebServiceSelector.GetSdmxImplementation(this.CodemapObj.Configuration);

            int count = GetSDMXObject.GetDataflowDataCount(df, criteria);

            return count;
        }
        /*FINE NUOVO SESSION QUERY*/
        private ICodelistObject GetCodeList(IDataflowObject df, IDataStructureObject kf, IComponent component)
        {
            ICodelistObject codes = null;
            if (this.SessionObj.CodelistConstrained != null && this.SessionObj.CodelistConstrained.ContainsKey(Utils.MakeKey(df)))
            {
                if (this.SessionObj.CodelistConstrained[Utils.MakeKey(df)].ContainsKey(component.Id))
                {
                    codes = this.SessionObj.CodelistConstrained[Utils.MakeKey(df)][component.Id];
                }
            }

            if (codes == null)
            {
                bool Contrained = component.StructureType.EnumType != Org.Sdmxsource.Sdmx.Api.Constants.SdmxStructureEnumType.DataAttribute;
                #region Criteria
                List<IContentConstraintMutableObject> criterias = new List<IContentConstraintMutableObject>();

                if (Contrained)
                {
                    IContentConstraintMutableObject criteria = new ContentConstraintMutableCore();
                    string currentComponent = component.ConceptRef.ChildReference.Id;
                    criteria.Id = currentComponent ?? "SPECIAL";
                    criteria.AddName("en", "english");
                    criteria.AgencyId = "agency";
                    ICubeRegionMutableObject region = new CubeRegionMutableCore();

                    if (currentComponent != null)
                    {
                        IKeyValuesMutable keyValue = new KeyValuesMutableImpl();
                        keyValue.Id = currentComponent;
                        keyValue.AddValue(SpecialValues.DummyMemberValue);
                        region.AddKeyValue(keyValue);
                    }
                    criteria.IncludedCubeRegion = region;
                    criterias.Add(criteria);
                }

                #endregion
                codes = GetSDMXObject.GetCodelist(df, kf, component, criterias, Contrained);
            }

            return codes;
        }
        /// <summary>
        /// Parse the specified DataflowRefBean object and populate the <see cref="StructureRetrievalInfo.RequestedComponent"/> and <see cref="StructureRetrievalInfo.Criteria"/> fields
        /// </summary>
        /// <param name="d">
        /// The DataflowRefBean to parse 
        /// </param>
        /// <param name="info">
        /// The current structure retrieval state 
        /// </param>
        private static void ParserDataflowRef(IConstrainableStructureReference d, StructureRetrievalInfo info)
        {
            if (d.ConstraintObject != null && d.ConstraintObject.IncludedCubeRegion != null)
            {
                foreach (IKeyValues member in d.ConstraintObject.IncludedCubeRegion.KeyValues)
                {
                    if (member.Values.Count == 0 || (member.Values.Count == 1 && SpecialValues.DummyMemberValue.Equals(member.Values[0])))
                    {
                        info.RequestedComponent = GetRequestedComponentId(info.MappingSet.Dataflow.Dsd, member.Id);
                    }
                    else
                    {
                        IKeyValuesMutable normalizedMember = new KeyValuesMutableImpl(member) { Id = GetRequestedComponentId(info.MappingSet.Dataflow.Dsd, member.Id) };
                        var keyValuesCore = new KeyValuesCore(normalizedMember, member.Parent);
                        info.Criteria.Add(keyValuesCore);
                    }
                }

                info.ReferencePeriod = d.ConstraintObject.MutableInstance.ReferencePeriod;
            }
        }
 /// <summary>
 /// The create key values.
 /// </summary>
 /// <param name="cubeRegionMap">
 /// The cube region map.
 /// </param>
 /// <param name="populateMap">
 /// The populate map.
 /// </param>
 private static void CreateKeyValues(
     IDictionary<string, ISet<string>> cubeRegionMap, ICollection<IKeyValuesMutable> populateMap)
 {
     foreach (var currentConcept in cubeRegionMap)
     {
         IKeyValuesMutable kvs = new KeyValuesMutableImpl();
         kvs.Id = currentConcept.Key;
         kvs.KeyValues.AddAll(currentConcept.Value);
         populateMap.Add(kvs);
     }
 }
        /// <summary>
        /// Handle CubeRegion Child elements
        /// </summary>
        /// <param name="parent">
        /// The parent ICubeRegionMutableObject object
        /// </param>
        /// <param name="localName">
        /// The name of the current xml element
        /// </param>
        /// <returns>
        /// The <see cref="StructureReaderBaseV20.ElementActions"/>.
        /// </returns>
        protected ElementActions HandleChildElements(ICubeRegionMutableObject parent, object localName)
        {
            ElementActions actions = null;
            if (NameTableCache.IsElement(localName, ElementNameTable.Member))
            {
                IKeyValuesMutable member = new KeyValuesMutableImpl();

                ////var isIncluded = Helper.TrySetFromAttribute(this.Attributes, AttributeNameTable.isIncluded, true);
                parent.KeyValues.Add(member);
                actions = this.BuildElementActions(member, this.HandleChildElements, this.HandleTextChildElement);
            }

            return actions;
        }
        /// <summary>
        /// The build cube region.
        /// </summary>
        /// <param name="cubeRegionType">
        /// The cube region type.
        /// </param>
        /// <returns>
        /// The <see cref="ICubeRegionMutableObject"/>.
        /// </returns>
        private static ICubeRegionMutableObject BuildCubeRegion(CubeRegionType cubeRegionType)
        {
            ICubeRegionMutableObject cubeRegion = new CubeRegionMutableCore();
            foreach (MemberType memberType in cubeRegionType.Member)
            {
                IKeyValuesMutable keyValues = new KeyValuesMutableImpl();
                keyValues.Id = memberType.ComponentRef;
                cubeRegion.AddKeyValue(keyValues);
                if (memberType.MemberValue == null || memberType.MemberValue.Count == 0)
                {
                    keyValues.AddValue(SpecialValues.DummyMemberValue);
                }
                else
                {
                    foreach (MemberValueType memberValueType in memberType.MemberValue)
                    {
                        keyValues.AddValue(memberValueType.Value);
                    }
                }
            }

            return cubeRegion;
        }
        private void PopolateKeyValue(ref IKeyValuesMutable kv)
        {
            kv = new KeyValuesMutableImpl();
            kv.Id = lblComponentSelectedID.Text;

            foreach (ListItem li in lbTarget.Items)
            {
                kv.AddValue(li.Value);
            }
        }
        /// <summary>
        /// Create a new Constrain from the <see cref="SessionQuery._queryComponentIndex"/> and optionally for the specified component
        /// </summary>
        /// <param name="currentComponent">
        /// The current component. Normally this component should be belong to the AvailableComponents set. Set to null if there isn't any current component
        /// </param>
        /// <returns>
        /// A constrain bean
        /// </returns>
        public IContentConstraintMutableObject CreateConstraintBean(string currentComponent)
        {
            if (!this._sessionQuery.IsDataflowSet)
            {
                throw new InvalidOperationException("Dataflow is not set");
            }
            IContentConstraintMutableObject criteria = new ContentConstraintMutableCore();
            criteria.Id = currentComponent ?? "SPECIAL";
            criteria.AddName("en", "english");
            criteria.AgencyId = "agency";
            ICubeRegionMutableObject region = new CubeRegionMutableCore();

            if (currentComponent != null)
            {
                IKeyValuesMutable keyValue = new KeyValuesMutableImpl();
                keyValue.Id = currentComponent;
                keyValue.AddValue(SpecialValues.DummyMemberValue);
                region.AddKeyValue(keyValue);
            }

            foreach (var queryComponent in this._sessionQuery.GetQueryComponents())
            {
                if (queryComponent != null && !queryComponent.GetKeyFamilyComponent().ConceptRef.ChildReference.Id.Equals(currentComponent))
                {
                    var setComponents = new KeyValuesMutableImpl();
                    region.AddKeyValue(setComponents);
                    setComponents.Id = queryComponent.GetKeyFamilyComponent().ConceptRef.ChildReference.Id;

                    var dimension = queryComponent.GetKeyFamilyComponent() as IDimension;
                    if (dimension != null && dimension.TimeDimension)
                    {
                        // there is another way to handle this with ReferencePeriod but
                        // ReferencePeriod accepts {xs:Date,xs:DateTime}. Using this way, MemberValue, we can use anything we want.

                        // must be first
                        setComponents.KeyValues.Add(queryComponent.StartDate);

                        if (!string.IsNullOrEmpty(queryComponent.EndDate))
                        {
                            setComponents.KeyValues.Add(queryComponent.EndDate);
                        }
                    }
                    else if (queryComponent.GetKeyFamilyComponent().Representation.Representation.MaintainableReference.MaintainableId != null)
                    {
                        // java has different API for MemberValue
                        foreach (ICode code in queryComponent.RetrieveCodes())
                        {
                            setComponents.KeyValues.Add(code.Id);
                        }
                        if (setComponents.KeyValues.Count == 0)
                        {
                            setComponents.AddValue(SpecialValues.DummyMemberValue);
                        }
                    }
                    else
                    {
                        setComponents.KeyValues.Add(queryComponent.TextValue);
                    }
                }
            }

            if (region.KeyValues.Count > 0)
            {
                criteria.IncludedCubeRegion = region;
            }

            return criteria;
        }
 /// <summary>
 /// The create key values.
 /// </summary>
 /// <param name="cubeRegionMap">
 /// The cube region map.
 /// </param>
 /// <param name="populateMap">
 /// The populate map.
 /// </param>
 private static void CreateKeyValues(
     IDictionary<string, ISet<string>> cubeRegionMap, ICollection<IKeyValuesMutable> populateMap)
 {
     /* foreach */
     foreach (string currentConcept in cubeRegionMap.Keys)
     {
         IKeyValuesMutable kvs = new KeyValuesMutableImpl();
         kvs.Id = currentConcept;
         kvs.KeyValues = new List<string>(cubeRegionMap[currentConcept]);
         populateMap.Add(kvs);
     }
 }
        /// <summary>
        /// Requests the partial codelist.
        /// </summary>
        /// <param name="dataflow">The dataflow.</param>
        /// <param name="firstDsd">The first DSD.</param>
        /// <param name="mutableSearchManager">The mutable search manager.</param>
        /// <returns>The criteria used.</returns>
        private static IEnumerable<IKeyValuesMutable> RequestPartialCodelist(IDataflowMutableObject dataflow, IDataStructureMutableObject firstDsd, IMutableStructureSearchManager mutableSearchManager)
        {
            var currentDataflowReference = _fromMutableBuilder.Build(dataflow);

            var previousMembers = new List<IKeyValuesMutable>();
            foreach (var dimension in firstDsd.Dimensions)
            {
                var representation = dimension.GetEnumeratedRepresentation(firstDsd);
                if (representation != null)
                {
                    IStructureReference codelistRef = new StructureReferenceImpl(representation.MaintainableReference, SdmxStructureEnumType.CodeList);

                    var id = dimension.Id;
                    var agencyId = firstDsd.AgencyId;
                    var version = firstDsd.Version;
                    var name = dimension.ConceptRef.ChildReference.Id;
                    var specialRequest = BuildConstrainableStructureReference(id, agencyId, version, name, previousMembers, currentDataflowReference);
                    var queries = new[] { specialRequest, codelistRef };
                    var objects = mutableSearchManager.RetrieveStructures(queries, false, false);
                    var message = string.Format("DataflowRef : {0}, CodelistRef : {1}", specialRequest, codelistRef);
                    Assert.IsNotNull(objects, message);
                    Assert.IsNotEmpty(objects.Codelists, message);
                    Assert.AreEqual(1, objects.Codelists.Count, message);

                    var codeIds = objects.Codelists.First().Items.TakeWhile(o => _random.Next() % 2 == 0).Select(o => o.Id).ToArray();

                    if (codeIds.Length > 0)
                    {
                        var criteria = new KeyValuesMutableImpl { Id = id };
                        criteria.KeyValues.AddAll(codeIds);
                        previousMembers.Add(criteria);
                    }
                }
                else if (dimension.TimeDimension)
                {
                    var id = dimension.Id;
                    var agencyId = firstDsd.AgencyId;
                    var version = firstDsd.Version;
                    var name = dimension.ConceptRef.ChildReference.Id;
                    IStructureReference specialRequest = BuildConstrainableStructureReference(id, agencyId, version, name, previousMembers, currentDataflowReference);
                    IStructureReference timeCodelistReference = new StructureReferenceImpl(
                        CustomCodelistConstants.Agency, 
                        CustomCodelistConstants.TimePeriodCodeList, 
                        CustomCodelistConstants.Version, 
                        SdmxStructureEnumType.CodeList);
                    var queries = new[] { specialRequest, timeCodelistReference };
                    var objects = mutableSearchManager.RetrieveStructures(queries, false, false);
                    var message = string.Format("DataflowRef : {0}, CodelistRef : {1}", specialRequest, timeCodelistReference);
                    Assert.IsNotNull(objects);
                    Assert.IsNotEmpty(objects.Codelists, message);
                    Assert.AreEqual(1, objects.Codelists.Count, message);
                    var timeCodelist = objects.Codelists.First();
                    Assert.GreaterOrEqual(timeCodelist.Items.Count, 1, message);
                    Assert.LessOrEqual(timeCodelist.Items.Count, 2, message);
                    foreach (var item in timeCodelist.Items)
                    {
                        DateTime date;
                        Assert.IsTrue(DateTime.TryParseExact(item.Id, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out date), "Invalid date : '{0}' for {1}", item.Id, specialRequest);
                    }
                    
                    if (timeCodelist.Items.Count > 0)
                    {
                        var criteria = new KeyValuesMutableImpl { Id = id };
                        criteria.KeyValues.AddAll(timeCodelist.Items.Select(o => o.Id));
                        previousMembers.Add(criteria);
                    }
                }
            }

            return previousMembers;
        }
        /// <summary>
        /// The build constrainable structure reference.
        /// </summary>
        /// <param name="id">
        /// The id.
        /// </param>
        /// <param name="agencyId">
        /// The agency id.
        /// </param>
        /// <param name="version">
        /// The version.
        /// </param>
        /// <param name="name">
        /// The name.
        /// </param>
        /// <param name="previousMembers">
        /// The previous members.
        /// </param>
        /// <param name="currentDataflowReference">
        /// The current dataflow reference.
        /// </param>
        /// <returns>
        /// The <see cref="IConstrainableStructureReference"/>.
        /// </returns>
        private static IConstrainableStructureReference BuildConstrainableStructureReference(
            string id, 
            string agencyId, 
            string version, 
            string name, 
            IEnumerable<IKeyValuesMutable> previousMembers, 
            IStructureReference currentDataflowReference)
        {
            IContentConstraintMutableObject mutableConstraint = new ContentConstraintMutableCore { Id = id, AgencyId = agencyId, Version = version };
            mutableConstraint.AddName("en", name);

            var cubeRegion = new CubeRegionMutableCore();
            mutableConstraint.IncludedCubeRegion = cubeRegion;
            IKeyValuesMutable requestedDimension = new KeyValuesMutableImpl();
            requestedDimension.Id = id;
            requestedDimension.AddValue(SpecialValues.DummyMemberValue);
            cubeRegion.AddKeyValue(requestedDimension);
            if (previousMembers != null)
            {
                cubeRegion.KeyValues.AddAll(previousMembers);
            }

            IContentConstraintObject constraint = new ContentConstraintObjectCore(mutableConstraint);
            IConstrainableStructureReference specialRequest = new ConstrainableStructureReference(currentDataflowReference, constraint);
            return specialRequest;
        }