Example #1
0
       /// <summary>
       /// Initializes a new instance of the <see cref="ComplexAnnotationReferenceCore"/> class.
       /// </summary>
       /// <param name="range">
       /// The range. 
       /// </param>
       /// <param name="startDate">
       /// The start date. 
       /// </param>
       /// <param name="endDate">
       /// The end date. 
       /// </param>
       /// <param name="startInclusive">
       /// The start inclusive. 
       /// </param>
       /// <param name="endInclusive">
       /// The end inclusive. 
       /// </param>
        public TimeRangeCore(bool range, ISdmxDate startDate, ISdmxDate endDate, bool startInclusive, bool endInclusive) 
        {
	  	    this._range = range;
		    this._startDate = startDate;
		    this._endDate = endDate;
		    this._startInclusive = startInclusive;
		    this._endInclusive = endInclusive;
		 
		    if (startDate == null && endDate == null)
            {
			   throw new SdmxSemmanticException("When setting range, cannot have both start/end periods null.");
		    }

		   if (this._range)
           {
			 if (startDate == null || endDate == null)
             {
				throw new SdmxSemmanticException("When range is defined then both start/end periods should be set.");
			 }
		   } 
           else
           {
			  if (startDate != null && endDate != null) 
              {
				throw new SdmxSemmanticException("When it is not a range then not both start/end periods can be set.");
			  }
		   }
  	    }
        /// <summary>
        /// Initializes a new instance of the <see cref="DataQuerySelectionGroupImpl"/> class.
        /// </summary>
        /// <param name="selections">
        /// The selections. 
        /// </param>
        /// <param name="dateFrom">
        /// The date from. 
        /// </param>
        /// <param name="dateTo">
        /// The date to. 
        /// </param>
        /// ///
        /// <exception cref="ArgumentException">
        /// Throws ArgumentException.
        /// </exception>
        public DataQuerySelectionGroupImpl(
            ISet<IDataQuerySelection> selections, ISdmxDate dateFrom, ISdmxDate dateTo)
        {
            this._selections = new HashSet<IDataQuerySelection>();
            this._selectionForConcept = new Dictionary<string, IDataQuerySelection>();
            this._dateFrom = dateFrom;
            this._dateTo = dateTo;

            // NPE defence. If the selections are null, then exit this method.
            if (selections == null)
            {
                return;
            }

            this._selections = selections;

            // Add each of the Dimensions Selections to the selection concept map. 
            foreach (IDataQuerySelection dimSel in selections)
            {
                if (this._selectionForConcept.ContainsKey(dimSel.ComponentId))
                {
                    // TODO Does this require a exception, or can the code selections be merged?
                    throw new ArgumentException("Duplicate concept");
                }

                this._selectionForConcept.Add(dimSel.ComponentId, dimSel);
            }
        }
        public ComplexDataQuerySelectionGroupImpl(ISet<IComplexDataQuerySelection> complexSelections, 
                                                    ISdmxDate dateFrom, OrderedOperator dateFromOperator, 
                                                    ISdmxDate dateTo, OrderedOperator dateToOperator, 
                                                    ISet<IComplexComponentValue> primaryMeasureValues)
        {
		    //check if the operator to be applied on the time has not the 'NOT_EQUAL' value
		    if (dateFromOperator.Equals(OrderedOperatorEnumType.NotEqual) || dateToOperator.Equals(OrderedOperatorEnumType.NotEqual))
			    throw new SdmxSemmanticException(ExceptionCode.QuerySelectionIllegalOperator);
		
		    if (complexSelections == null) 
            {
			    return;
		    }
		
		    this._dateFrom = dateFrom;
		    this._dateFromOperator = dateFromOperator;
		    this._dateTo = dateTo;
		    this._dateToOperator = dateToOperator;	
		    this._complexSelections = complexSelections;
		    this._primaryMeasureValues = primaryMeasureValues;
		
		    // Add each of the Component Selections to the selection concept map. 
		    foreach (IComplexDataQuerySelection compSel in _complexSelections) 
            {
			    if (_complexSelectionForConcept.ContainsKey(compSel.ComponentId)) 
                {
				    //TODO Does this require a exception, or can the code selections be merged?
				    throw new ArgumentException("Duplicate concept");
			    }
			    _complexSelectionForConcept.Add(compSel.ComponentId, compSel);
		    }		
	    }
Example #4
0
        /// <summary>
        /// Generates the SQL Query where condition from the SDMX Query TimeBean <see cref="ISdmxDate"/>
        /// </summary>
        /// <param name="dateFrom">The start time period</param>
        /// <param name="dateTo">The end time period</param>
        /// <returns>
        /// The string containing SQL Query where condition
        /// </returns>
        public string GenerateWhere(ISdmxDate dateFrom, ISdmxDate dateTo)
        {
            if (dateFrom == null && dateTo == null)
            {
                return(string.Empty);
            }

            var             sqlArray = new List <string>();
            IFormatProvider fmt      = CultureInfo.InvariantCulture;

            // DateTime startTime = SdmxPeriodToDateTime(timeBean.StartTime,true);
            if (dateFrom != null)
            {
                var      dateTime  = dateFrom.Date;
                DateTime startTime = dateTime.HasValue ? dateTime.Value : DateUtil.FormatDate(dateFrom.DateInSdmxFormat, true);
                sqlArray.Add(
                    string.Format(
                        CultureInfo.InvariantCulture, this._startWhereFormat, startTime.ToString("yyyy-MM-dd", fmt)));
            }

            if (dateTo != null)
            {
                // DateTime endTime = SdmxPeriodToDateTime(timeBean.EndTime, false);
                var      dateTime = dateTo.Date;
                DateTime endTime  = dateTime.HasValue ? dateTime.Value : DateUtil.FormatDate(dateTo.DateInSdmxFormat, true);
                sqlArray.Add(
                    string.Format(
                        CultureInfo.InvariantCulture, this._endWhereFormat, endTime.ToString("yyyy-MM-dd", fmt)));
            }

            return(string.Format(CultureInfo.InvariantCulture, "({0})", string.Join(" and ", sqlArray.ToArray())));
        }
        /// <summary>
        /// Check if the <paramref name="thisSdmxDate"/> ends after <paramref name="otherSdmxDate"/>.
        /// </summary>
        /// <param name="thisSdmxDate">The this SDMX date.</param>
        /// <param name="otherSdmxDate">The other SDMX date.</param>
        /// <returns><c>true</c> is the <paramref name="thisSdmxDate"/> ends after <paramref name="otherSdmxDate"/>; otherwise false.</returns>
        public static bool EndsAfter(this ISdmxDate thisSdmxDate, ISdmxDate otherSdmxDate)
        {
            DateTime thisDate = DateUtil.FormatDate(thisSdmxDate.DateInSdmxFormat, false);
            DateTime otherDate = DateUtil.FormatDate(otherSdmxDate.DateInSdmxFormat, false);

            return thisDate.CompareTo(otherDate) > 0;
        }
Example #6
0
        /// <summary>
        /// Translates the specified <paramref name="sdmxDate"/> to <see cref="SdmxQueryPeriod"/>
        /// </summary>
        /// <param name="sdmxDate">The SDMX date.</param>
        /// <param name="periodicity">The periodicity.</param>
        /// <returns>
        /// The <see cref="SdmxQueryPeriod" />.
        /// </returns>
        public static SdmxQueryPeriod ToQueryPeriod(this ISdmxDate sdmxDate, IPeriodicity periodicity)
        {
            if (sdmxDate == null)
            {
                return(null);
            }

            if (periodicity.TimeFormat.EnumType != sdmxDate.TimeFormatOfDate)
            {
                sdmxDate = new SdmxDateCore(sdmxDate.Date, periodicity.TimeFormat);
            }

            var time = new SdmxQueryPeriod();

            string[] startTime = sdmxDate.DateInSdmxFormat.Split('-');
            var      startYear = Convert.ToInt32(startTime[0].Substring(0, 4), _invariantCulture);

            time.Year = startYear;
            if (startTime.Length >= 2)
            {
                int startPeriod;
                if (int.TryParse(startTime[1].Substring(periodicity.DigitStart), NumberStyles.None, _invariantCulture, out startPeriod))
                {
                    time.HasPeriod = true;
                    time.Period    = startPeriod;
                }
            }

            return(time);
        }
Example #7
0
        /// <summary>
        /// Check if the <paramref name="thisSdmxDate"/> ends after <paramref name="otherSdmxDate"/>.
        /// </summary>
        /// <param name="thisSdmxDate">The this SDMX date.</param>
        /// <param name="otherSdmxDate">The other SDMX date.</param>
        /// <returns><c>true</c> is the <paramref name="thisSdmxDate"/> ends after <paramref name="otherSdmxDate"/>; otherwise false.</returns>
        public static bool EndsAfter(this ISdmxDate thisSdmxDate, ISdmxDate otherSdmxDate)
        {
            DateTime thisDate  = DateUtil.FormatDate(thisSdmxDate.DateInSdmxFormat, false);
            DateTime otherDate = DateUtil.FormatDate(otherSdmxDate.DateInSdmxFormat, false);

            return(thisDate.CompareTo(otherDate) > 0);
        }
        /// <summary>
        /// Check if the <paramref name="thisSdmxDate"/> starts before <paramref name="otherSdmxDate"/>.
        /// </summary>
        /// <param name="thisSdmxDate">The this SDMX date.</param>
        /// <param name="otherSdmxDate">The other SDMX date.</param>
        /// <returns><c>true</c> is the <paramref name="thisSdmxDate"/> starts before <paramref name="otherSdmxDate"/>; otherwise false.</returns>
        public static bool StartsBefore(this ISdmxDate thisSdmxDate, ISdmxDate otherSdmxDate)
        {
            DateTime thisDate = DateUtil.FormatDate(thisSdmxDate.DateInSdmxFormat, true);
            DateTime otherDate = DateUtil.FormatDate(otherSdmxDate.DateInSdmxFormat, true);

            return thisDate.CompareTo(otherDate) < 0;
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////BUILD FROM MUTABLE OBJECT                 //////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////    
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ReportPeriodTargetCore"/> class.
        /// </summary>
        /// <param name="parent">
        /// The parent. 
        /// </param>
        /// <param name="itemMutableObject">
        /// The sdmxObject. 
        /// </param>
        /// <exception cref="SdmxSemmanticException">
        /// Throws Validate exception.
        /// </exception>
        public ReportPeriodTargetCore(IIdentifiableObject parent, IReportPeriodTargetMutableObject itemMutableObject)
            : base(itemMutableObject, parent)
        {
            this.textType = TextType.GetFromEnum(TextEnumType.ObservationalTimePeriod);
            if (itemMutableObject.StartTime != null)
            {
                this.startTime = new SdmxDateCore(itemMutableObject.StartTime, TimeFormatEnumType.DateTime);
            }

            if (itemMutableObject.EndTime != null)
            {
                this.endTime = new SdmxDateCore(itemMutableObject.EndTime, TimeFormatEnumType.DateTime);
            }

            if (itemMutableObject.TextType != null)
            {
                this.textType = itemMutableObject.TextType;
            }

            try
            {
                this.Validate();
            }
            catch (SdmxSemmanticException e)
            {
                throw new SdmxSemmanticException(e, ExceptionCode.FailValidation, this);
            }
        }
Example #10
0
        /// <summary>
        /// Generates the SQL Query where condition from the SDMX Query Time
        /// </summary>
        /// <param name="dateFrom">
        /// The start time
        /// </param>
        /// <param name="dateTo">
        /// The end time
        /// </param>
        /// <param name="frequencyValue">
        /// The frequency value
        /// </param>
        /// <returns>
        /// The string containing SQL Query where condition
        /// </returns>
        public string GenerateWhere(ISdmxDate dateFrom, ISdmxDate dateTo, string frequencyValue)
        {
            var whereSql = new StringBuilder();

            if (frequencyValue != null)
            {
                ITimeDimensionMapping engine;
                if (this._timeDimensionMappings.TryGetValue(frequencyValue, out engine))
                {
                    var whereClause = this.GenerateWhereClause(dateFrom, dateTo, frequencyValue, engine);
                    whereSql.Append(whereClause);
                }
            }
            else if (this._timeDimensionMappings.Count > 0)
            {
                string op = string.Empty;
                foreach (var timeDimensionMapping in this._timeDimensionMappings)
                {
                    var generateWhere = this.GenerateWhereClause(dateFrom, dateTo, timeDimensionMapping.Key, timeDimensionMapping.Value);
                    if (!string.IsNullOrWhiteSpace(generateWhere))
                    {
                        whereSql.AppendFormat(CultureInfo.InvariantCulture, "{0} ( {1} )", op, generateWhere);
                        op = " OR ";
                    }
                }
            }

            return(whereSql.Length > 0 ? string.Format("({0})", whereSql) : string.Empty);
        }
Example #11
0
        /// <summary>
        /// Check if the <paramref name="thisSdmxDate"/> starts before <paramref name="otherSdmxDate"/>.
        /// </summary>
        /// <param name="thisSdmxDate">The this SDMX date.</param>
        /// <param name="otherSdmxDate">The other SDMX date.</param>
        /// <returns><c>true</c> is the <paramref name="thisSdmxDate"/> starts before <paramref name="otherSdmxDate"/>; otherwise false.</returns>
        public static bool StartsBefore(this ISdmxDate thisSdmxDate, ISdmxDate otherSdmxDate)
        {
            DateTime thisDate  = DateUtil.FormatDate(thisSdmxDate.DateInSdmxFormat, true);
            DateTime otherDate = DateUtil.FormatDate(otherSdmxDate.DateInSdmxFormat, true);

            return(thisDate.CompareTo(otherDate) < 0);
        }
 /// <summary>
 /// Builds the time codelist.
 /// </summary>
 /// <param name="minPeriod">The minimum period.</param>
 /// <param name="maxPeriod">The maximum period.</param>
 /// <returns>the time codelist.</returns>
 public static ICodelistMutableObject BuildTimeCodelist(ISdmxDate minPeriod, ISdmxDate maxPeriod)
 {
     ICodelistMutableObject timeCodeList = new CodelistMutableCore();
     var startDate = minPeriod.FormatAsDateString(true);
     ICodeMutableObject startCode = new CodeMutableCore { Id = startDate };
     var endDate = maxPeriod.FormatAsDateString(false);
     ICodeMutableObject endCode = !startDate.Equals(endDate) ? new CodeMutableCore { Id = endDate } : null;
     SetupTimeCodelist(startCode, endCode, timeCodeList);
     return timeCodeList;
 }
Example #13
0
        /// <summary>
        /// Generates the where clause.
        /// </summary>
        /// <param name="dateFrom">The date from.</param>
        /// <param name="dateTo">The date to.</param>
        /// <param name="frequencyValue">The frequency value.</param>
        /// <param name="engine">The engine.</param>
        /// <returns>The where clause </returns>
        private string GenerateWhereClause(ISdmxDate dateFrom, ISdmxDate dateTo, string frequencyValue, ITimeDimensionMapping engine)
        {
            string frequencyWhereClause = this._frequencyComponentMapping.GenerateComponentWhere(frequencyValue);

            if (!string.IsNullOrWhiteSpace(frequencyWhereClause))
            {
                string timePeriodsWhereClauses = engine.GenerateWhere(dateFrom, dateTo);
                if (!string.IsNullOrWhiteSpace(timePeriodsWhereClauses))
                {
                    var whereClause = string.Format(CultureInfo.InvariantCulture, "(( {0} ) and ( {1} ))", frequencyWhereClause, timePeriodsWhereClauses);
                    return(whereClause);
                }
            }

            return(string.Empty);
        }
        /// <summary>
        /// Parse a time where condition
        /// </summary>
        /// <param name="DateFrom">Date From in Sdmx Format</param>
        /// <param name="DateTo">Date To in Sdmx Format</param>
        /// <returns>string representing the date where formatted</returns>
        private string ParseTimeValueWhereStatment(ISdmxDate DateFrom, ISdmxDate DateTo)
        {
            try
            {
                IConceptObjectImpl realConceptTime = Concepts.Find(c => c.ConceptType == ConceptTypeEnum.Dimension && ((IDimensionConcept)c).DimensionType == DimensionTypeEnum.Time);
                string             timedim         = string.Format(FormatWhereValue, ((IDimensionConcept)realConceptTime).GetColumTimeName());
                List <string>      SingleValues    = new List <string>();

                //dò per scontato che i timeFormat delle 2 date siano Uguali
                TimeFormatEnumType tf = TimeFormatEnumType.Null;
                if (DateFrom != null && DateFrom.Date.HasValue)
                {
                    tf = DateFrom.TimeFormatOfDate.EnumType;
                    string wherestr = TimePeriodDBFormat.GetTimeWhereStatment(timedim, TimePeriodDBFormat.TypeDateOperation.Major, tf, DateFrom);
                    if (!string.IsNullOrEmpty(wherestr))
                    {
                        SingleValues.Add(wherestr);
                    }
                }

                if (DateTo != null && DateTo.Date.HasValue)
                {
                    if (tf == TimeFormatEnumType.Null)
                    {
                        tf = DateTo.TimeFormatOfDate.EnumType;
                    }
                    string wherestr = TimePeriodDBFormat.GetTimeWhereStatment(timedim, FlyController.Model.TimePeriodDBFormat.TypeDateOperation.Minor, tf, DateTo);
                    if (!string.IsNullOrEmpty(wherestr))
                    {
                        SingleValues.Add(wherestr);
                    }
                }

                if (SingleValues.Count > 0)
                {
                    return(string.Format("({0})", string.Join(") AND (", SingleValues)));
                }

                return(null);
            }
            catch (SdmxException) { throw; }
            catch (Exception ex)
            {
                throw new SdmxException(this, FlyExceptionObject.FlyExceptionTypeEnum.InternalError, ex);
            }
        }
Example #15
0
        ///////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////BUILD FROM MUTABLE OBJECT                 //////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="TimeRangeCore"/> class.
        /// </summary>
        /// <param name="mutable">
        /// The mutable. 
        /// </param>
        /// <param name="parent">
        /// The parent. 
        /// </param>
        public TimeRangeCore(ITimeRangeMutableObject mutable, ISdmxStructure parent)
            : base(SdmxStructureType.GetFromEnum(SdmxStructureEnumType.TimeRange), parent)
        {
            if (mutable.StartDate != null)
            {
                this._startDate = new SdmxDateCore(mutable.StartDate, TimeFormatEnumType.DateTime);
            }

            if (mutable.EndDate != null)
            {
                this._endDate = new SdmxDateCore(mutable.EndDate, TimeFormatEnumType.DateTime);
            }

            this._isRange = mutable.IsRange;
            this._isStartInclusive = mutable.IsStartInclusive;
            this._isEndInclusive = mutable.IsEndInclusive;
        }
Example #16
0
        /// <summary>
        /// Generates the SQL Query where condition from the SDMX Query Time
        /// </summary>
        /// <param name="dateFrom">
        /// The start time
        /// </param>
        /// <param name="dateTo">
        /// The end time
        /// </param>
        /// <param name="frequencyValue">
        /// The frequency value
        /// </param>
        /// <returns>
        /// The string containing SQL Query where condition
        /// </returns>
        public string GenerateWhere(ISdmxDate dateFrom, ISdmxDate dateTo, string frequencyValue)
        {
            if (!string.IsNullOrEmpty(frequencyValue))
            {
                TimeFormat format = TimeFormat.GetTimeFormatFromCodeId(frequencyValue);
                if (dateFrom != null)
                {
                    dateFrom = new SdmxDateCore(dateFrom.Date, format.EnumType);
                }

                if (dateTo != null)
                {
                    dateTo = new SdmxDateCore(dateTo.Date, format.EnumType);
                }
            }

            return(this._timeDimensionMapping.GenerateWhere(dateFrom, dateTo));
        }
Example #17
0
        /// <summary>
        /// Generates the SQL Query where condition from the SDMX Query TimeBean <see cref="ISdmxDate"/>
        /// </summary>
        /// <param name="dateFrom">The start time period</param>
        /// <param name="dateTo">The end time period</param>
        /// <returns>
        /// The string containing SQL Query where condition
        /// </returns>
        public string GenerateWhere(ISdmxDate dateFrom, ISdmxDate dateTo)
        {
            if (dateFrom == null && dateTo == null)
            {
                return(string.Empty);
            }

            ISdmxDate constantDate = new SdmxDateCore(Mapping.Constant);

            var    ret = new StringBuilder("(");
            bool   timeWhereStarted = false;
            string normDateFrom     = dateFrom != null ? new SdmxDateCore(dateFrom.Date, constantDate.TimeFormatOfDate.EnumType).DateInSdmxFormat : null;
            string normDateTo       = dateTo != null ? new SdmxDateCore(dateTo.Date, constantDate.TimeFormatOfDate.EnumType).DateInSdmxFormat : null;
            bool   areEqual         = Equals(normDateFrom, normDateTo);

            if (normDateFrom != null)
            {
                var startTime = normDateFrom.Replace("'", "''");
                if (areEqual)
                {
                    ret.AppendFormat(this._equalsWhere, startTime);
                }
                else
                {
                    ret.AppendFormat(this._fromWhere, startTime);
                    timeWhereStarted = true;
                }
            }

            if (normDateTo != null && !areEqual)
            {
                if (timeWhereStarted)
                {
                    ret.Append(" and ");
                }

                var endTime = normDateTo.Replace("'", "''");
                ret.AppendFormat(this._toWhere, endTime);
            }

            ret.Append(") ");
            return(ret.ToString());
        }
Example #18
0
        /// <summary>
        /// Generates the SQL Query where condition from the SDMX Query TimeBean <see cref="ISdmxDate"/>
        /// </summary>
        /// <param name="dateFrom">The start time period</param>
        /// <param name="dateTo">The end time period</param>
        /// <returns>
        /// The string containing SQL Query where condition
        /// </returns>
        public string GenerateWhere(ISdmxDate dateFrom, ISdmxDate dateTo)
        {
            if (dateFrom == null && dateTo == null)
            {
                return(string.Empty);
            }

            var  ret = new StringBuilder("(");
            bool timeWhereStarted = false;
            bool areEqual         = Equals(dateFrom, dateTo);

            if (dateFrom != null)
            {
                var startTime = dateFrom.DateInSdmxFormat.Replace("'", "''");
                if (areEqual)
                {
                    ret.AppendFormat(this._equalsWhere, startTime);
                }
                else
                {
                    ret.AppendFormat(this._fromWhere, startTime);
                    timeWhereStarted = true;
                }
            }

            if (dateTo != null && !areEqual)
            {
                if (timeWhereStarted)
                {
                    ret.Append(" and ");
                }

                var endTime = dateTo.DateInSdmxFormat.Replace("'", "''");
                ret.AppendFormat(this._toWhere, endTime);
            }

            ret.Append(") ");
            return(ret.ToString());
        }
Example #19
0
        /// <summary>
        /// Extracts a SdmxQueryTimeVO<see cref="SdmxQueryTimeVO"/> object from a TimeBean<see cref="ISdmxDate"/>
        /// </summary>
        /// <param name="dateFrom">
        /// Start time <see cref="ISdmxDate"/> A SDMX Query Time element
        /// </param>
        /// <param name="dateTo">
        /// End time <see cref="ISdmxDate"/> A SDMX Query Time element
        /// </param>
        /// <returns>
        /// SdmxQueryTimeVO<see cref="SdmxQueryTimeVO"/>
        /// </returns>
        public SdmxQueryTimeVO ExtractTimeBean(ISdmxDate dateFrom, ISdmxDate dateTo)
        {
            var startDate = dateFrom.ToQueryPeriod(this._periodicity) ?? new SdmxQueryPeriod {
                HasPeriod = false, Year = 0, Period = 1
            };
            var now     = DateTime.Now;
            var endDate = dateTo.ToQueryPeriod(this._periodicity) ?? new SdmxQueryPeriod {
                HasPeriod = false, Year = now.Year, Period = ((DateTime.Now.Month - 1) / this._periodicity.MonthsPerPeriod) + 1
            };

            if (!startDate.HasPeriod && startDate.Period == 0)
            {
                startDate.Period = 1;
            }

            if (!endDate.HasPeriod && endDate.Period == 0)
            {
                endDate.Period = this._periodicity.PeriodCount;
            }

            return(new SdmxQueryTimeVO {
                EndPeriod = endDate.Period, EndYear = endDate.Year, HasEndPeriod = endDate.HasPeriod, HasStartPeriod = startDate.HasPeriod, StartPeriod = startDate.Period, StartYear = startDate.Year
            });
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////BUILD FROM MUTABLE OBJECT                 //////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ReferencePeriodCore"/> class.
        /// </summary>
        /// <param name="mutable">
        /// The mutable. 
        /// </param>
        /// <param name="parent">
        /// The parent. 
        /// </param>
        /// <exception cref="SdmxSemmanticException">
        /// Throws Validate exception.
        /// </exception>
        public ReferencePeriodCore(IReferencePeriodMutableObject mutable, IContentConstraintObject parent)
            : base(SdmxStructureType.GetFromEnum(SdmxStructureEnumType.ReferencePeriod), parent)
        {
            // These items are mandatory and thus should exist
            if (mutable.StartTime != null)
            {
                this.startTime = new SdmxDateCore(mutable.StartTime, TimeFormatEnumType.DateTime);
            }

            if (mutable.EndTime != null)
            {
                this.endTime = new SdmxDateCore(mutable.EndTime, TimeFormatEnumType.DateTime);
            }

            if (this.startTime == null)
            {
                throw new SdmxSemmanticException("ReferencePeriodCore - start time can not be null");
            }

            if (this.endTime == null)
            {
                throw new SdmxSemmanticException("ReferencePeriodCore - end time can not be null");
            }
        }
        /// <summary>
        /// Generates the SQL Query where condition from the SDMX Query TimeBean <see cref="ISdmxDate"/>
        /// </summary>
        /// <param name="dateFrom">The start time period</param>
        /// <param name="dateTo">The end time period</param>
        /// <returns>
        /// The string containing SQL Query where condition
        /// </returns>
        public string GenerateWhere(ISdmxDate dateFrom, ISdmxDate dateTo)
        {
            if (dateFrom == null && dateTo == null)
            {
                return string.Empty;
            }

            ISdmxDate constantDate = new SdmxDateCore(Mapping.Constant);

            var ret = new StringBuilder("(");
            bool timeWhereStarted = false;
            string normDateFrom = dateFrom != null ? new SdmxDateCore(dateFrom.Date, constantDate.TimeFormatOfDate.EnumType).DateInSdmxFormat : null;
            string normDateTo = dateTo != null ? new SdmxDateCore(dateTo.Date, constantDate.TimeFormatOfDate.EnumType).DateInSdmxFormat : null;
            bool areEqual = Equals(normDateFrom, normDateTo);

            if (normDateFrom != null)
            {
                var startTime = normDateFrom.Replace("'", "''");
                if (areEqual)
                {
                    ret.AppendFormat(this._equalsWhere, startTime);
                }
                else
                {
                    ret.AppendFormat(this._fromWhere, startTime);
                    timeWhereStarted = true;
                }
            }

            if (normDateTo != null && !areEqual)
            {
                if (timeWhereStarted)
                {
                    ret.Append(" and ");
                }

                var endTime = normDateTo.Replace("'", "''");
                ret.AppendFormat(this._toWhere, endTime);
            }

            ret.Append(") ");
            return ret.ToString();
        }
        /// <summary>
        /// Build from a REST query and a bean retrival manager
        /// </summary>
        /// <param name="dataQuery"></param>
        /// <param name="retrievalManager"></param>
        /// <exception cref="SdmxSemmanticException"></exception>
        public DataQueryImpl(IRestDataQuery dataQuery, ISdmxObjectRetrievalManager retrievalManager)
        {
            this._lastUpdated = dataQuery.UpdatedAfter;
            this._dataQueryDetail = dataQuery.QueryDetail ?? DataQueryDetail.GetFromEnum(DataQueryDetailEnumType.Full);

            base.FirstNObservations = dataQuery.FirstNObservations;
            base.LastNObservations = dataQuery.LastNObsertations;
            if (ObjectUtil.ValidString(dataQuery.DimensionAtObservation))
            {
                this.DimensionAtObservation = dataQuery.DimensionAtObservation;
            }

            base.Dataflow = retrievalManager.GetMaintainableObject<IDataflowObject>(dataQuery.FlowRef.MaintainableReference);
            if (base.Dataflow == null)
            {
                throw new SdmxNoResultsException("Data Flow could not be found for query : " + dataQuery.FlowRef);
            }

            base.DataStructure =
                retrievalManager.GetMaintainableObject<IDataStructureObject>(base.Dataflow.DataStructureRef.MaintainableReference);
            if (base.DataStructure == null)
            {
                throw new SdmxNoResultsException("DSD could not be found for query : " + base.Dataflow.DataStructureRef);
            }

            ISet<IDataProvider> dataProviders = new HashSet<IDataProvider>();
            if (dataQuery.ProviderRef != null)
            {
                ISet<IDataProviderScheme> dataProviderSchemes =
                    retrievalManager.GetMaintainableObjects<IDataProviderScheme>(dataQuery.ProviderRef.MaintainableReference);
                foreach (IDataProviderScheme currentDpScheme in dataProviderSchemes)
                {
                    foreach (IDataProvider dataProvider in currentDpScheme.Items)
                    {
                        if (dataProvider.Id.Equals(dataQuery.ProviderRef.ChildReference.Id))
                        {
                            dataProviders.Add(dataProvider);
                        }
                    }
                }
            }
            ISet<IDataQuerySelection> selections = new HashSet<IDataQuerySelection>();
            if (dataQuery.QueryList.Count > 0)
            {
                int i = 0;
                foreach (IDimension dimension in base.DataStructure.GetDimensions(SdmxStructureEnumType.Dimension, SdmxStructureEnumType.MeasureDimension).OrderBy(dimension => dimension.Position))
                {
                    if (dataQuery.QueryList.Count <= i)
                    {
                        throw new SdmxSemmanticException(
                            "Not enough key values in query, expecting "
                            + base.DataStructure.GetDimensions(SdmxStructureEnumType.Dimension, SdmxStructureEnumType.MeasureDimension).Count + " got "
                            + dataQuery.QueryList.Count);
                    }
                    ISet<string> queriesForDimension = dataQuery.QueryList[i];
                    if (queriesForDimension != null && queriesForDimension.Count > 0)
                    {
                        IDataQuerySelection selectionsForDimension =
                            new DataQueryDimensionSelectionImpl(
                                dimension.Id,
                                new HashSet<string>(queriesForDimension));
                        selections.Add(selectionsForDimension);
                    }
                    i++;
                }
            }

            if (ObjectUtil.ValidCollection(selections) || dataQuery.StartPeriod != null || dataQuery.EndPeriod != null)
            {
                _dataQuerySelectionGroups.Add(
                    new DataQuerySelectionGroupImpl(selections, dataQuery.StartPeriod, dataQuery.EndPeriod));
            }
            ValidateQuery();
        }
Example #23
0
        /// <summary>
        /// Formats the <paramref name="sdmxDate"/> as a date string.
        /// </summary>
        /// <param name="sdmxDate">The SDMX date.</param>
        /// <param name="startOfPeriod">if set to <c>true</c> [start of period].</param>
        /// <returns>the <paramref name="sdmxDate"/> as a date string.</returns>
        public static string FormatAsDateString(this ISdmxDate sdmxDate, bool startOfPeriod)
        {
            var date = DateUtil.FormatDate(sdmxDate.DateInSdmxFormat, startOfPeriod);

            return(DateUtil.FormatDate(date, TimeFormatEnumType.Date));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DataQueryImpl"/> class.
        /// </summary>
        /// <param name="dataStructure">
        /// The data structure.
        /// </param>
        /// <param name="lastUpdated">
        /// The last updated.
        /// </param>
        /// <param name="dataQueryDetail">
        /// The data query detail.
        /// </param>
        /// <param name="maxObs">
        /// The max obs.
        /// </param>
        /// <param name="orderAsc">
        /// If the order is ascending.
        /// </param>
        /// <param name="dataProviders">
        /// The data providers.
        /// </param>
        /// <param name="dataflow">
        /// The dataflow.
        /// </param>
        /// <param name="dimensionAtObservation">
        /// The dimension at observation.
        /// </param>
        /// <param name="selectionGroup">
        /// The selection group.
        /// </param>
        public DataQueryImpl(
            IDataStructureObject dataStructure,
            ISdmxDate lastUpdated,
            DataQueryDetail dataQueryDetail,
            int maxObs,
            bool orderAsc,
            ISet<IDataProvider> dataProviders,
            IDataflowObject dataflow,
            string dimensionAtObservation,
            ICollection<IDataQuerySelectionGroup> selectionGroup)
        {
            base.DataStructure = dataStructure;
            this._lastUpdated = lastUpdated;
            this._dataQueryDetail = dataQueryDetail ?? DataQueryDetail.GetFromEnum(DataQueryDetailEnumType.Full);
            if (orderAsc)
            {
                base.FirstNObservations = maxObs;
            }
            else
            {
                base.LastNObservations = maxObs;
            }
            if (dataProviders != null)
            {
                this._dataProviders = new HashSet<IDataProvider>(dataProviders);
            }
            base.Dataflow = dataflow;
            this.DimensionAtObservation = dimensionAtObservation;

            if (selectionGroup != null)
            {
                foreach (IDataQuerySelectionGroup dqsg in selectionGroup)
                {
                    if (dqsg != null)
                    {
                        this._dataQuerySelectionGroups.Add(dqsg);
                    }
                }
            }
            ValidateQuery();
        }
 /// <summary>
 /// Sets the end period.
 /// </summary>
 /// <param name="endPeriod">The end period.</param>
 /// <exception cref="SdmxSemmanticException">Could not format 'endPeriod' value  + endPeriod +  as a date</exception>
 public void SetEndPeriod(string endPeriod)
 {
     try
     {
         this.endPeriod = new SdmxDateCore(endPeriod);
     }
     catch (FormatException e)
     {
         throw new SdmxSemmanticException("Could not format 'endPeriod' value " + endPeriod + " as a date", e);
     }
 }
        /// <summary>
        /// Generates the SQL Query where condition from the SDMX Query Time
        /// </summary>
        /// <param name="dateFrom">
        /// The start time
        /// </param>
        /// <param name="dateTo">
        /// The end time
        /// </param>
        /// <param name="frequencyValue">
        /// The frequency value
        /// </param>
        /// <returns>
        /// The string containing SQL Query where condition
        /// </returns>
        public string GenerateWhere(ISdmxDate dateFrom, ISdmxDate dateTo, string frequencyValue)
        {
            if (!string.IsNullOrEmpty(frequencyValue))
            {
                TimeFormat format = TimeFormat.GetTimeFormatFromCodeId(frequencyValue);
                if (dateFrom != null)
                {
                    dateFrom = new SdmxDateCore(dateFrom.Date, format.EnumType);
                }

                if (dateTo != null)
                {
                    dateTo = new SdmxDateCore(dateTo.Date, format.EnumType);
                }
            }

            return this._timeDimensionMapping.GenerateWhere(dateFrom, dateTo);
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////BUILD FROM V2.1 SCHEMA                 //////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Initializes a new instance of the <see cref="TextFormatObjectCore"/> class.
        /// </summary>
        /// <param name="textFormatType">
        /// The text format type. 
        /// </param>
        /// <param name="parent">
        /// The parent. 
        /// </param>
        public TextFormatObjectCore(TextFormatType textFormatType, ISdmxObject parent)
            : base(_textFormatType, parent)
        {
            this._isSequence = TertiaryBool.GetFromEnum(TertiaryBoolEnumType.Unset);
            this.multilingual = TertiaryBool.GetFromEnum(TertiaryBoolEnumType.Unset);
            if (textFormatType.textType != null)
            {
                this._textType = TextTypeUtil.GetTextType(textFormatType.textType);
            }

            if (textFormatType.isMultiLingual)
            {
                this.multilingual = TertiaryBool.ParseBoolean(textFormatType.isMultiLingual);
            }

            if (textFormatType.isSequence != null && textFormatType.isSequence.Value)
            {
                this._isSequence = TertiaryBool.ParseBoolean(textFormatType.isSequence.Value);
            }

            if (textFormatType.maxLength.HasValue)
            {
                this._maxLength = (long?)textFormatType.maxLength;
            }

            if (textFormatType.minLength != null)
            {
                this._minLength = (long?)textFormatType.minLength;
            }

            if (textFormatType.startValue.HasValue)
            {
                this._startValue = textFormatType.startValue.Value;
            }

            if (textFormatType.endValue.HasValue)
            {
                this._endValue = textFormatType.endValue.Value;
            }

            if (textFormatType.maxValue.HasValue)
            {
                this._maxValue = textFormatType.maxValue.Value;
            }

            if (textFormatType.minValue.HasValue)
            {
                this._minValue = (long)textFormatType.minValue.Value;
            }

            if (textFormatType.interval.HasValue)
            {
                this._interval = textFormatType.interval.Value;
            }

            if (textFormatType.timeInterval != null)
            {
                this._timeInterval = textFormatType.timeInterval.ToString();
            }

            if (textFormatType.decimals.HasValue)
            {
                this._decimals = (long)textFormatType.decimals.Value;
            }

            if (!string.IsNullOrEmpty(textFormatType.pattern))
            {
                this._pattern = textFormatType.pattern;
            }

            if (textFormatType.endTime != null)
            {
                this._endTime = new SdmxDateCore(textFormatType.endTime.ToString());
            }

            if (textFormatType.startTime != null)
            {
                this._startTime = new SdmxDateCore(textFormatType.startTime.ToString());
            }

            this.Validate();
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////BUILD FROM V2.1 SCHEMA                 //////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Initializes a new instance of the <see cref="ReferencePeriodCore"/> class.
        /// </summary>
        /// <param name="refPeriodType">
        /// The ref period type. 
        /// </param>
        /// <param name="parent">
        /// The parent. 
        /// </param>
        /// <exception cref="SdmxSemmanticException">
        /// Throws Validate exception.
        /// </exception>
        public ReferencePeriodCore(ReferencePeriodType refPeriodType, IContentConstraintObject parent)
            : base(SdmxStructureType.GetFromEnum(SdmxStructureEnumType.ReferencePeriod), parent)
        {
            this.startTime = new SdmxDateCore(refPeriodType.startTime, TimeFormatEnumType.DateTime);
            this.endTime = new SdmxDateCore(refPeriodType.endTime, TimeFormatEnumType.DateTime);
            if (this.startTime == null)
            {
                throw new SdmxSemmanticException("ReferencePeriodCore - start time can not be null");
            }

            if (this.endTime == null)
            {
                throw new SdmxSemmanticException("ReferencePeriodCore - start time can not be null");
            }
        }
        /// <summary>
        /// Create a Where Condition filtering Time from Time period value
        /// </summary>
        /// <param name="timedim">Time period colum name</param>
        /// <param name="to">Date to (TypeDateOperation)</param>
        /// <param name="tf">Time format type</param>
        /// <param name="dt">Date in Sdmx Format</param>
        /// <returns></returns>
        public static string GetTimeWhereStatment(string timedim, TypeDateOperation to, TimeFormatEnumType tf, ISdmxDate dt)
        {
            try
            {
                string        SymbolComp        = to == TypeDateOperation.Minor ? "<" : ">";
                List <string> OrTimeFormatWhere = new List <string>();

                int MounthConsidered = dt.Date.Value.Month;
                if (tf == TimeFormatEnumType.Year && to == TypeDateOperation.Minor)
                {
                    MounthConsidered = 12;
                }

                //Tutte le possibili condizioni
                //==yyyy-MM-dd oppure yyyyMMdd
                OrTimeFormatWhere.Add(string.Format("({0} = '{2}')", timedim, SymbolComp, dt.Date.Value.ToString("yyyy-MM-dd")));
                OrTimeFormatWhere.Add(string.Format("({0} = '{2}')", timedim, SymbolComp, dt.Date.Value.ToString("yyyyMMdd")));
                #region Anno
                OrTimeFormatWhere.Add(string.Format("(DATALENGTH({0}) = 4 AND {0} {1}= '{2}')", timedim, SymbolComp, dt.Date.Value.Year));
                #endregion
                #region Mensile
                string DBtimecode = MappingTimePeriodDbFormat[TimeFormat.GetFromEnum(TimeFormatEnumType.Month)];
                OrTimeFormatWhere.Add(string.Format(@"
(
    DATALENGTH({0}) > 4 AND
    SUBSTRING({0},5,1) ='{1}' 
    AND 
    (
        SUBSTRING({0},0,5) {2} '{3}' 
        OR
        (
            SUBSTRING({0},0,5) = '{3}' 
            AND 
            CONVERT(int,SUBSTRING({0},6,DATALENGTH({0})-5)) {2}= {4}
        )
    )
)", timedim, DBtimecode, SymbolComp, dt.Date.Value.Year, MounthConsidered));
                #endregion
                #region Quartely
                DBtimecode = MappingTimePeriodDbFormat[TimeFormat.GetFromEnum(TimeFormatEnumType.QuarterOfYear)];
                int quarter = (MounthConsidered + 2) / 3;
                OrTimeFormatWhere.Add(string.Format(@"
(
    DATALENGTH({0}) > 4 AND
    SUBSTRING({0},5,1) ='{1}' 
    AND 
    (
        SUBSTRING({0},0,5) {2} '{3}' 
        OR
        (
            SUBSTRING({0},0,5) = '{3}' 
            AND 
            CONVERT(int,SUBSTRING({0},6,DATALENGTH({0})-5)) {2}= {4}
        )
    )
)", timedim, DBtimecode, SymbolComp, dt.Date.Value.Year, quarter));
                #endregion
                #region ThirdOfYear
                DBtimecode = MappingTimePeriodDbFormat[TimeFormat.GetFromEnum(TimeFormatEnumType.ThirdOfYear)];
                int ThirdOfYear = (MounthConsidered + 3) / 4;
                OrTimeFormatWhere.Add(string.Format(@"
(
    DATALENGTH({0}) > 4 AND
    SUBSTRING({0},5,1) ='{1}' 
    AND 
    (
        SUBSTRING({0},0,5) {2} '{3}' 
        OR
        (
            SUBSTRING({0},0,5) = '{3}' 
            AND 
            CONVERT(int,SUBSTRING({0},6,DATALENGTH({0})-5)) {2}= {4}
        )
    )
)", timedim, DBtimecode, SymbolComp, dt.Date.Value.Year, ThirdOfYear));
                #endregion
                #region HalfOfYear
                DBtimecode = MappingTimePeriodDbFormat[TimeFormat.GetFromEnum(TimeFormatEnumType.HalfOfYear)];
                int HalfOfYear = (MounthConsidered + 5) / 6;
                OrTimeFormatWhere.Add(string.Format(@"
(
    DATALENGTH({0}) > 4 AND
    SUBSTRING({0},5,1) ='{1}' 
    AND 
    (
        SUBSTRING({0},0,5) {2} '{3}' 
        OR
        (
            SUBSTRING({0},0,5) = '{3}' 
            AND 
            CONVERT(int,SUBSTRING({0},6,DATALENGTH({0})-5)) {2}= {4}
        )
    )
)", timedim, DBtimecode, SymbolComp, dt.Date.Value.Year, HalfOfYear));
                #endregion


                return(string.Format("({0})", string.Join(" OR ", OrTimeFormatWhere)));

                //                if (tf == TimeFormatEnumType.Year)
                //                {
                //                    return string.Format("(DATALENGTH({0}) = 4 AND {0} {1} '{2}')", timedim, SymbolComp, dt.Date.Value.Year);
                //                }
                //                else
                //                {
                //                    string queryValAfterFreq = dt.Date.Value.Month.ToString();
                //                    if (dt.DateInSdmxFormat.IndexOf(dt.TimeFormatOfDate.FrequencyCode) > 4)
                //                        queryValAfterFreq = dt.DateInSdmxFormat.Substring(dt.DateInSdmxFormat.IndexOf(dt.TimeFormatOfDate.FrequencyCode) + 1);

                //                    string DBtimecode = dt.TimeFormatOfDate.FrequencyCode;
                //                    //Trasformo il codice SDMX freq nel nostro formato time nel DB
                //                    if (MappingTimePeriodDbFormat.ContainsKey(dt.TimeFormatOfDate)) //nel Mapping devono essere presenti tutti i timeformat
                //                        DBtimecode = MappingTimePeriodDbFormat[dt.TimeFormatOfDate];

                //                    return string.Format(@"
                //(
                //    SUBSTRING({0},5,1) ='{1}'
                //    AND
                //    (
                //        SUBSTRING({0},0,5) {2} '{3}'
                //        OR
                //        (
                //            SUBSTRING({0},0,5) = '{3}'
                //            AND
                //            CONVERT(int,SUBSTRING({0},6,DATALENGTH({0})-5)) {2}= {4}
                //        )
                //    )
                //)",
                //                    timedim, DBtimecode, SymbolComp, dt.Date.Value.Year, queryValAfterFreq);
                //                }
            }
            catch (SdmxException) { throw; }
            catch (Exception ex)
            {
                throw new SdmxException(typeof(FlyController.Model.TimePeriodDBFormat), FlyExceptionObject.FlyExceptionTypeEnum.InternalError, ex);
            }
        }
        /// <summary>
        /// The where build.
        /// </summary>
        /// <param name="fromDate">
        /// The from date.
        /// </param>
        /// <param name="toDate">
        /// The to date.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public string WhereBuild(ISdmxDate fromDate, ISdmxDate toDate)
        {
            if (fromDate == null && toDate == null)
            {
                return string.Empty;
            }

            // NumberFormatInfo f = CultureInfo.InvariantCulture.NumberFormat;
            var ret = new StringBuilder("(");

            SdmxQueryTimeVO time = this.ExtractTimeBean(fromDate, toDate);

            // start time includes a period and the freq is not annual
            if (time.HasStartPeriod && this._expressionEntity.Freq != TimeFormatEnumType.Year)
            {
                int firstPeriodLength = this._periodicity.PeriodCount;
                if (time.StartYear == time.EndYear)
                {
                    firstPeriodLength = time.EndPeriod;
                }

                string yearStr = time.StartYear.ToString(_formatProvider);
                int lastClause = this.BuildPeriodWhere(ret, yearStr, time.StartPeriod, firstPeriodLength, this._periodicity, this._expressionEntity);
                if (time.StartYear + 1 < time.EndYear)
                {
                    ret.Append(" (");
                    yearStr = (time.StartYear + 1).ToString(_formatProvider);
                    ret.AppendFormat(CultureInfo.InvariantCulture, this._yearOnlyStart, yearStr);
                    yearStr = (time.EndYear - 1).ToString(_formatProvider);
                    ret.Append(" and ");
                    ret.AppendFormat(CultureInfo.InvariantCulture, this._yearOnlyEnd, yearStr);
                    ret.Append(")");

                    lastClause = ret.Length;
                    ret.Append(" or ");
                }

                if (time.StartYear != time.EndYear)
                {
                    if (time.HasEndPeriod)
                    {
                        yearStr = time.EndYear.ToString(_formatProvider);
                        lastClause = this.BuildPeriodWhere(ret, yearStr, 1, time.EndPeriod, this._periodicity, this._expressionEntity);
                    }
                    else
                    {
                        ret.Append(string.Format(CultureInfo.InvariantCulture, this._yearOnlyWhereFormat, time.EndYear.ToString(_formatProvider)));
                        lastClause = ret.Length;
                        ret.Append(" or ");
                    }
                }

                ret.Length = lastClause;
            }
            else
            {
                ret.AppendFormat(CultureInfo.InvariantCulture, this._yearOnlyStart, time.StartYear.ToString(_formatProvider));
                if (toDate != null)
                {
                    ret.Append(" and ");
                    ret.AppendFormat(CultureInfo.InvariantCulture, this._yearOnlyEnd, time.EndYear.ToString(_formatProvider));
                }
            }

            ret.Append(")");
            return ret.ToString();
        }
        /// <summary>
        /// Generates the SQL Query where condition from the SDMX Query TimeBean <see cref="ISdmxDate"/>
        /// </summary>
        /// <param name="dateFrom">The start time period</param>
        /// <param name="dateTo">The end time period</param>
        /// <returns>
        /// The string containing SQL Query where condition
        /// </returns>
        public string GenerateWhere(ISdmxDate dateFrom, ISdmxDate dateTo)
        {
            if (dateFrom == null && dateTo == null)
            {
                return string.Empty;
            }

            var ret = new StringBuilder("(");
            bool timeWhereStarted = false;
            bool areEqual = Equals(dateFrom, dateTo);
            if (dateFrom != null)
            {
                var startTime = dateFrom.DateInSdmxFormat.Replace("'", "''");
                if (areEqual)
                {
                    ret.AppendFormat(this._equalsWhere, startTime);
                }
                else
                {
                    ret.AppendFormat(this._fromWhere, startTime);
                    timeWhereStarted = true;
                }
            }

            if (dateTo != null && !areEqual)
            {
                if (timeWhereStarted)
                {
                    ret.Append(" and ");
                }

                var endTime = dateTo.DateInSdmxFormat.Replace("'", "''");
                ret.AppendFormat(this._toWhere, endTime);
            }

            ret.Append(") ");
            return ret.ToString();
        }
 public IDataQueryFluentBuilder WithLastUpdated(ISdmxDate lastUpdated)
 {
     this._lastUpdated = lastUpdated;
     return this;
 }
Example #33
0
 /// <summary>
 /// Generates the SQL Query where condition from the SDMX Query TimeBean <see cref="ISdmxDate"/>
 /// </summary>
 /// <param name="dateFrom">The start time period</param>
 /// <param name="dateTo">The end time period</param>
 /// <returns>
 /// The string containing SQL Query where condition
 /// </returns>
 public string GenerateWhere(ISdmxDate dateFrom, ISdmxDate dateTo)
 {
     return(this._whereBuilder.WhereBuild(dateFrom, dateTo));
 }
        ///////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////BUILD FROM V2.1 SCHEMA                 //////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////

        #region Constructors and Destructors

        /// <summary>
        ///   Initializes a new instance of the <see cref="ReferenceValueObjectCore" /> class.
        /// </summary>
        /// <param name="parent"> The parent. </param>
        /// <param name="type"> The type. </param>
        public ReferenceValueObjectCore(ITarget parent, ReferenceValueType type)
            : base(SdmxStructureType.GetFromEnum(SdmxStructureEnumType.MetadataReferenceValue), parent)
        {
            this.dataKeys = new List<IDataKey>();
            this.id = type.id;
            if (type.ConstraintContentReference != null)
            {
                this.constraintReference = RefUtil.CreateReference(this, type.ConstraintContentReference);
            }

            if (type.ObjectReference != null)
            {
                this.identifiableReference = RefUtil.CreateReference(this, type.ObjectReference);
            }

            if (type.DataSetReference != null)
            {
                this.datasetId = type.DataSetReference.ID;
                this.identifiableReference = RefUtil.CreateReference(this, type.DataSetReference.DataProvider);
            }

            if (type.DataKey != null)
            {
                foreach (var cvst in type.DataKey.GetTypedKeyValue<DataKeyValueType>())
                {
                    this.dataKeys.Add(new DataKeyObjectCore(this, cvst));
                }
            }

            if (type.ReportPeriod != null)
            {
                reportPeriod = new SdmxDateCore(type.ReportPeriod.ToString());
            }

            this.Validate();
        }
Example #35
0
        /// <summary>
        /// The where build.
        /// </summary>
        /// <param name="fromDate">
        /// The from date.
        /// </param>
        /// <param name="toDate">
        /// The to date.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public string WhereBuild(ISdmxDate fromDate, ISdmxDate toDate)
        {
            if (fromDate == null && toDate == null)
            {
                return(string.Empty);
            }

            // NumberFormatInfo f = CultureInfo.InvariantCulture.NumberFormat;
            var ret = new StringBuilder("(");

            SdmxQueryTimeVO time = this.ExtractTimeBean(fromDate, toDate);

            // start time includes a period and the freq is not annual
            if (time.HasStartPeriod && this._expressionEntity.Freq != TimeFormatEnumType.Year)
            {
                int firstPeriodLength = this._periodicity.PeriodCount;
                if (time.StartYear == time.EndYear)
                {
                    firstPeriodLength = time.EndPeriod;
                }

                string yearStr    = time.StartYear.ToString(_formatProvider);
                int    lastClause = this.BuildPeriodWhere(ret, yearStr, time.StartPeriod, firstPeriodLength, this._periodicity, this._expressionEntity);
                if (time.StartYear + 1 < time.EndYear)
                {
                    ret.Append(" (");
                    yearStr = (time.StartYear + 1).ToString(_formatProvider);
                    ret.AppendFormat(CultureInfo.InvariantCulture, this._yearOnlyStart, yearStr);
                    yearStr = (time.EndYear - 1).ToString(_formatProvider);
                    ret.Append(" and ");
                    ret.AppendFormat(CultureInfo.InvariantCulture, this._yearOnlyEnd, yearStr);
                    ret.Append(")");

                    lastClause = ret.Length;
                    ret.Append(" or ");
                }

                if (time.StartYear != time.EndYear)
                {
                    if (time.HasEndPeriod)
                    {
                        yearStr    = time.EndYear.ToString(_formatProvider);
                        lastClause = this.BuildPeriodWhere(ret, yearStr, 1, time.EndPeriod, this._periodicity, this._expressionEntity);
                    }
                    else
                    {
                        ret.Append(string.Format(CultureInfo.InvariantCulture, this._yearOnlyWhereFormat, time.EndYear.ToString(_formatProvider)));
                        lastClause = ret.Length;
                        ret.Append(" or ");
                    }
                }

                ret.Length = lastClause;
            }
            else
            {
                ret.AppendFormat(CultureInfo.InvariantCulture, this._yearOnlyStart, time.StartYear.ToString(_formatProvider));
                if (toDate != null)
                {
                    ret.Append(" and ");
                    ret.AppendFormat(CultureInfo.InvariantCulture, this._yearOnlyEnd, time.EndYear.ToString(_formatProvider));
                }
            }

            ret.Append(")");
            return(ret.ToString());
        }
 /// <summary>
 /// Sets the start period.
 /// </summary>
 /// <param name="startPeriod">The start period.</param>
 /// <exception cref="SdmxSemmanticException">Could not format 'startPeriod' value  + startPeriod +  as a date</exception>
 public void SetStartPeriod(string startPeriod)
 {
     try
     {
         this.startPeriod = new SdmxDateCore(startPeriod);
     }
     catch (FormatException e)
     {
         throw new SdmxSemmanticException("Could not format 'startPeriod' value " + startPeriod + " as a date", e);
     }
 }
 /// <summary>
 /// Generates the SQL Query where condition from the SDMX Query TimeBean <see cref="ISdmxDate"/>
 /// </summary>
 /// <param name="dateFrom">The start time period</param>
 /// <param name="dateTo">The end time period</param>
 /// <returns>
 /// The string containing SQL Query where condition
 /// </returns>
 public string GenerateWhere(ISdmxDate dateFrom, ISdmxDate dateTo)
 {
     return this._whereBuilder.WhereBuild(dateFrom, dateTo);
 }
 /// <summary>
 /// Sets the updated after.
 /// </summary>
 /// <param name="updatedAfter">The updated after.</param>
 /// <exception cref="SdmxSemmanticException">Could not format 'updatedAfter' value  + updatedAfter +  as a date</exception>
 public void SetUpdatedAfter(string updatedAfter)
 {
     try
     {
         this.updatedAfter = new SdmxDateCore(updatedAfter);
     }
     catch (FormatException e)
     {
         throw new SdmxSemmanticException("Could not format 'updatedAfter' value " + updatedAfter + " as a date", e);
     }
 }
        /// <summary>
        /// Extracts a SdmxQueryTimeVO<see cref="SdmxQueryTimeVO"/> object from a TimeBean<see cref="ISdmxDate"/>
        /// </summary>
        /// <param name="dateFrom">
        /// Start time <see cref="ISdmxDate"/> A SDMX Query Time element
        /// </param>
        /// <param name="dateTo">
        /// End time <see cref="ISdmxDate"/> A SDMX Query Time element
        /// </param>
        /// <returns>
        /// SdmxQueryTimeVO<see cref="SdmxQueryTimeVO"/>
        /// </returns>
        public SdmxQueryTimeVO ExtractTimeBean(ISdmxDate dateFrom, ISdmxDate dateTo)
        {
            var startDate = dateFrom.ToQueryPeriod(this._periodicity) ?? new SdmxQueryPeriod { HasPeriod = false, Year = 0, Period = 1 };
            var now = DateTime.Now;
            var endDate = dateTo.ToQueryPeriod(this._periodicity) ?? new SdmxQueryPeriod { HasPeriod = false, Year = now.Year, Period = ((DateTime.Now.Month - 1) / this._periodicity.MonthsPerPeriod) + 1 };

            if (!startDate.HasPeriod && startDate.Period == 0)
            {
                startDate.Period = 1;
            }

            if (!endDate.HasPeriod && endDate.Period == 0)
            {
                endDate.Period = this._periodicity.PeriodCount;
            }

            return new SdmxQueryTimeVO { EndPeriod = endDate.Period, EndYear = endDate.Year, HasEndPeriod = endDate.HasPeriod, HasStartPeriod = startDate.HasPeriod, StartPeriod = startDate.Period, StartYear = startDate.Year };
        }
        public DataQueryImpl(
            IDataStructureObject dataStructure,
            ISdmxDate lastUpdated,
            DataQueryDetail dataQueryDetail,
            int maxObs,
            bool orderAsc,
            ISet<IDataProvider> dataProviders,
            IDataflowObject dataflow,
            string dimensionAtObservation,
            ISet<IDataQuerySelection> selections,
            DateTime? dateFrom,
            DateTime? dateTo)
        {
            base.DataStructure = dataStructure;
            this._lastUpdated = lastUpdated;
            this._dataQueryDetail = dataQueryDetail ?? DataQueryDetail.GetFromEnum(DataQueryDetailEnumType.Full);
            if (orderAsc)
            {
                base.FirstNObservations = maxObs;
            }
            else
            {
                base.LastNObservations = maxObs;
            }
            if (dataProviders != null)
            {
                this._dataProviders = new HashSet<IDataProvider>(dataProviders);
            }
            base.Dataflow = dataflow;
            this.DimensionAtObservation = dimensionAtObservation;

            if (ObjectUtil.ValidCollection(selections) || dateFrom != null || dateTo != null)
            {
                ISdmxDate sdmxDateFrom = null;
                if (dateFrom != null)
                {
                    sdmxDateFrom = new SdmxDateCore(dateFrom, TimeFormatEnumType.Date);
                }
                ISdmxDate sdmxDateTo = null;
                if (dateTo != null)
                {
                    sdmxDateTo = new SdmxDateCore(dateTo, TimeFormatEnumType.Date);
                }
                //TODO: move to fluent interface
                this._dataQuerySelectionGroups.Add(new DataQuerySelectionGroupImpl(selections, sdmxDateFrom, sdmxDateTo));
            }
            ValidateQuery();
        }
 /// <summary>
 /// The is later.
 /// </summary>
 /// <param name="sdmxDate">
 /// The sdmxDate. 
 /// </param>
 /// <returns>
 /// The <see cref="bool"/> . 
 /// </returns>
 public virtual bool IsLater(ISdmxDate sdmxDate)
 {
     DateTime? dateTime = this.Date;
     return sdmxDate.Date != null
            && (dateTime != null && (dateTime.Value.Ticks / 10000) > (sdmxDate.Date.Value.Ticks / 10000));
 }
Example #42
0
		public virtual bool IsLater(ISdmxDate date0) {
			return (this.Date.Ticks/10000) > (date0.Date.Ticks/10000);
		}
        /// <summary>
        /// Generates the SQL Query where condition from the SDMX Query Time
        /// </summary>
        /// <param name="dateFrom">
        /// The start time
        /// </param>
        /// <param name="dateTo">
        /// The end time
        /// </param>
        /// <param name="frequencyValue">
        /// The frequency value 
        /// </param>
        /// <returns>
        /// The string containing SQL Query where condition
        /// </returns>
        public string GenerateWhere(ISdmxDate dateFrom, ISdmxDate dateTo, string frequencyValue)
        {
            var whereSql = new StringBuilder();
            if (frequencyValue != null)
            {
                ITimeDimensionMapping engine;
                if (this._timeDimensionMappings.TryGetValue(frequencyValue, out engine))
                {
                    var whereClause = this.GenerateWhereClause(dateFrom, dateTo, frequencyValue, engine);
                    whereSql.Append(whereClause);
                }
            }
            else if (this._timeDimensionMappings.Count > 0)
            {
                string op = string.Empty;
                foreach (var timeDimensionMapping in this._timeDimensionMappings)
                {
                    var generateWhere = this.GenerateWhereClause(dateFrom, dateTo, timeDimensionMapping.Key, timeDimensionMapping.Value);
                    if (!string.IsNullOrWhiteSpace(generateWhere))
                    {
                        whereSql.AppendFormat(CultureInfo.InvariantCulture, "{0} ( {1} )", op, generateWhere);
                        op = " OR ";
                    }
                }
            }

            return whereSql.Length > 0 ? string.Format("({0})", whereSql) : string.Empty;
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////BUILD FROM V2.1 SCHEMA                 //////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Initializes a new instance of the <see cref="ReportPeriodTargetCore"/> class.
        /// </summary>
        /// <param name="reportPeriodTargetType">
        /// The report period target type. 
        /// </param>
        /// <param name="parent">
        /// The parent. 
        /// </param>
        /// <exception cref="SdmxSemmanticException">
        /// Throws Validate exception.
        /// </exception>
        protected internal ReportPeriodTargetCore(ReportPeriodTargetType reportPeriodTargetType, IMetadataTarget parent)
            : base(
                reportPeriodTargetType, SdmxStructureType.GetFromEnum(SdmxStructureEnumType.ReportPeriodTarget), parent)
        {
            this.textType = TextType.GetFromEnum(TextEnumType.ObservationalTimePeriod);
            if (reportPeriodTargetType.LocalRepresentation != null)
            {
                RepresentationType repType = reportPeriodTargetType.LocalRepresentation;
                if (repType.TextFormat != null)
                {
                    if (repType.TextFormat.startTime != null)
                    {
                        this.startTime = new SdmxDateCore(repType.TextFormat.startTime.ToString());
                    }

                    if (repType.TextFormat.endTime != null)
                    {
                        this.endTime = new SdmxDateCore(repType.TextFormat.endTime.ToString());
                    }

                    if (repType.TextFormat.textType != null)
                    {
                        this.textType = TextTypeUtil.GetTextType(repType.TextFormat.textType);
                    }
                }
            }

            try
            {
                this.Validate();
            }
            catch (SdmxSemmanticException e)
            {
                throw new SdmxSemmanticException(e, ExceptionCode.FailValidation, this);
            }
        }
        /// <summary>
        /// Generates the where clause.
        /// </summary>
        /// <param name="dateFrom">The date from.</param>
        /// <param name="dateTo">The date to.</param>
        /// <param name="frequencyValue">The frequency value.</param>
        /// <param name="engine">The engine.</param>
        /// <returns>The where clause </returns>
        private string GenerateWhereClause(ISdmxDate dateFrom, ISdmxDate dateTo, string frequencyValue, ITimeDimensionMapping engine)
        {
            string frequencyWhereClause = this._frequencyComponentMapping.GenerateComponentWhere(frequencyValue);
            if (!string.IsNullOrWhiteSpace(frequencyWhereClause))
            {
                string timePeriodsWhereClauses = engine.GenerateWhere(dateFrom, dateTo);
                if (!string.IsNullOrWhiteSpace(timePeriodsWhereClauses))
                {
                    var whereClause = string.Format(CultureInfo.InvariantCulture, "(( {0} ) and ( {1} ))", frequencyWhereClause, timePeriodsWhereClauses);
                    return whereClause;
                }
            }

            return string.Empty;
        }