internal static IEnumerable <KeyValuePair <string, string> > ToParameters(this SessionQuery query)
        {
            var builder = new ParameterBuilder();

            builder.Add("dataSourceName", query?.DataSourceName);
            builder.Add("requestedAfterDate", query?.RequestedAfterDate);
            builder.Add("requestedBeforeDate", query?.RequestedBeforeDate);
            builder.Add(query?.Page);
            return(builder.GetParameters());
        }
        internal void render(TextWriter writer, SessionQuery query)
        {
            IDataSetModel l = new DataSetModelStore(Structure, store);

            /*
             * if (query._dataSetModel != null)
             * {
             *  l = query._dataSetModel;
             *  l.UpdateAxis(layObj.axis_z, layObj.axis_x, layObj.axis_y);
             *  query._store.SetCriteria(this.Criterias);
             *  query.DatasetModel = l;
             * }
             * else
             * {
             *  l.Initialize(this.Criterias);
             *  l.UpdateAxis(layObj.axis_z, layObj.axis_x, layObj.axis_y);
             *  query.DatasetModel = l;
             * }
             */

            if (query.DatasetModel != null)
            {
                //query.DatasetModel.UpdateAxis(layObj.axis_z, layObj.axis_x, layObj.axis_y);
                query.DatasetModel.UpdateAxis(layObj.axis_z, layObj.axis_x, layObj.axis_y, this.Criterias);
                //fabio baco multilista
                //query._store.SetCriteria(this.Criterias);
            }
            else
            {
                query.DatasetModel = new DataSetModelStore(Structure, store);
                query.DatasetModel.Initialize(this.Criterias);
                //query.DatasetModel.UpdateAxis(layObj.axis_z, layObj.axis_x, layObj.axis_y);
                query.DatasetModel.UpdateAxis(layObj.axis_z, layObj.axis_x, layObj.axis_y, this.Criterias);
            }

            HtmlRenderer htmlRenderer = new HtmlRenderer(this.codemap, true, _useAttr, cFrom, cTo);


            //  { if (!DataStream.store.ExistsColumn(axisX)) DataStream.layObj.axis_x.Remove(axisX); });
            //this.Criterias.ForEach(c => l.UpdateSliceKeyValue(c.component, c.values.FirstOrDefault()));

            /*
             * for(int i=0; i<layObj.axis_z.Count; i++) {
             *  string criterio=layObj.axis_z[i];
             *  this.Criterias.ForEach(c => {if (c.component==criterio) {l.UpdateSliceKeyValue(c.component, c.values.FirstOrDefault());}});
             * }
             */
            //htmlRenderer.Render(l, writer);
            htmlRenderer.Render(query._dataSetModel, writer);

            //new HtmlRenderer(query.GetComponentCodeDescriptionMap(), true).Render(
            //   query.DatasetModel,
            //   context.Response.Output);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Subscribe to all session events
        /// </summary>
        /// <param name="onStreamClosed"></param>
        /// <returns>An awaitable task that finishes when the stream is opened</returns>
        public async Task SubscribeSessionEvents(Action onStreamClosed = null)
        {
            var command = new SessionQuery();

            var eventStream = await EventStream.Create($"{clientConfig.Endpoint}/fetch/{command.Type}", null, StreamHeaders);

            eventStream.OnDataReceived += SessionStore.Dispatch;
            eventStream.Start();
            eventStream.OnEventsFinished += () =>
            {
                onStreamClosed?.Invoke();
            };
        }
        public async Task <SessionResponseList> List(SessionQuery query = null)
        {
            try
            {
                var result = await SessionRepository.List(query);

                return(result);
            }
            catch (Exception ex)
            {
                Logger.Error("SessionService.List failed", this, ex);
            }

            return(null);
        }
Ejemplo n.º 5
0
 public UserController(
     CreateUserCommandHandler createCommand,
     GetAllUsersQuery getAllQuery,
     GetUserQuery getOneQuery,
     DownloadPhotoQuery getPhotoQuery,
     SessionQuery sessionQuery,
     UpdateUserCommandHandler updateCommand,
     DeleteUserCommandHandler deleteCommand)
 {
     this.createCommand = createCommand;
     this.getAllQuery   = getAllQuery;
     this.getOneQuery   = getOneQuery;
     this.getPhotoQuery = getPhotoQuery;
     this.sessionQuery  = sessionQuery;
     this.updateCommand = updateCommand;
     this.deleteCommand = deleteCommand;
 }
        private async Task GetClients(bool isRefresh)
        {
            if (!_navigationService.IsNetworkAvailable || (_dataLoaded && !isRefresh))
            {
                return;
            }

            SetProgressBar("Getting clients...");

            try
            {
                var query = new SessionQuery
                {
                    ControllableByUserId  = AuthenticationService.Current.LoggedInUserId,
                    SupportsRemoteControl = true
                };
                var clients = await _apiClient.GetClientSessionsAsync(query);

                Clients = clients.Where(x => x.DeviceId != _apiClient.DeviceId && x.SupportsRemoteControl).ToList();

                if (!Clients.IsNullOrEmpty())
                {
                    if (SelectedClient != null)
                    {
                        SelectedClient = Clients.FirstOrDefault(x => x.DeviceId == SelectedClient.DeviceId) ?? Clients[0];
                    }
                    else
                    {
                        SelectedClient = Clients[0];
                    }

                    SetSessionDetails(SelectedClient);

                    _dataLoaded = true;
                }
            }
            catch (HttpException ex)
            {
                Log.ErrorException("GetClients()", ex);
            }

            SetProgressBar();
        }
        /// <summary>
        /// Initialize the session, get a cookie for language
        /// </summary>
        /// <param name="sender">
        /// The parameter is not used.
        /// </param>
        /// <param name="e">
        /// The parameter is not used.
        /// </param>
        protected void Session_Start(object sender, EventArgs e)
        {
            Logger.Info("starting session ...");
            try
            {
                RemoveJsTreeCookie(this.Context);
                CultureInfo culture = LocaleResolver.GetCookie(this.Context);
                Thread.CurrentThread.CurrentUICulture = culture;
                Logger.Info("starting session success");


                var query = new SessionQuery {
                    CurrentCulture = culture
                };

                Utils.App_Data_Path = this.Context.Server.MapPath("~/App_Data/");
                string cacheFolder = this.GetCacheFolder();

                query.SetCacheFolder(cacheFolder);
                SessionQueryManager.SaveSessionQuery(this.Context.Session, query);
                Thread.CurrentThread.CurrentUICulture = culture;
                Logger.Info("starting session success");
            }
            catch (HttpException ex)
            {
                Logger.Error("starting session failled");
                Logger.Error(ex.Message, ex);
            }
            catch (SecurityException ex)
            {
                Logger.Error("starting session failled");
                Logger.Error(ex.Message, ex);
            }
            catch (IOException ex)
            {
                Logger.Error("starting session failled");
                Logger.Error(ex.Message, ex);
            }
        }
Ejemplo n.º 8
0
        public static void StreamDataTable(object DataObjectsForStreaming, TextWriter streamResponse, bool useAttr, CultureInfo cFrom, CultureInfo cTo, SessionQuery query)
        {
            if (DataObjectsForStreaming == null || !(DataObjectsForStreaming is DataObjectForStreaming))
                throw new Exception("Data not found");

            DataObjectForStreaming DataStream = (DataObjectForStreaming)DataObjectsForStreaming;

            #region CheckLayout
            DataStream.layObj.axis_x.ForEach(axisX => { if (!DataStream.store.ExistsColumn(axisX)) DataStream.layObj.axis_x.Remove(axisX); });
            DataStream.layObj.axis_y.ForEach(axisY => { if (!DataStream.store.ExistsColumn(axisY)) DataStream.layObj.axis_y.Remove(axisY); });
            DataStream.layObj.axis_z.ForEach(axisZ => { if (!DataStream.store.ExistsColumn(axisZ)) DataStream.layObj.axis_z.Remove(axisZ); });
            #endregion

            DataRender rea = new DataRender(
                DataStream.store,
                DataStream.Criterias,
                DataStream.layObj,
                DataStream.structure,
                DataStream.codemap,
                useAttr,
                cFrom,cTo);

            rea.render(streamResponse,query);

            //DataStream.store.Dispose();
        }
Ejemplo n.º 9
0
        public IList <Session> FindSessions(SessionQuery query)
        {
            IList <Session> sessionList = new List <Session>();

            var sessionClient = GetIndexClient(Indexes.session);
            var parameters    = new SearchParameters();

            //Handle Session Time by a filter
            if (query.StartTime > DateTime.MinValue)
            {
                var startTimeJson   = JsonConvert.SerializeObject(query.StartTime);
                var filterStartTime = "time ge " + startTimeJson.Replace("\"", "");
                parameters.Filter = filterStartTime;
            }


            if (query.EndTime > DateTime.MinValue)
            {
                var endTimeJson   = JsonConvert.SerializeObject(query.EndTime);
                var filterEndTime = "time le " + endTimeJson.Replace("\"", "");
                if (!string.IsNullOrWhiteSpace(parameters.Filter))
                {
                    filterEndTime = " and " + filterEndTime;
                }

                parameters.Filter += filterEndTime;
            }

            //Search for sessions with ANY of the Topics
            //Multiple words will be treated as Phrase
            var searchText = "";

            if (query.Topics.Count > 0)
            {
                searchText = string.Format("\"{0}\"", string.Join("\"|\"", query.Topics));
            }

            //Search for the Speaker's name
            if (query.Speaker != null)
            {
                searchText = searchText + "+" + query.Speaker;
            }

            //Search for the Room name
            if (query.Room != null)
            {
                searchText = searchText + "+" + query.Room;
            }

            //If we're only search for time, need to put a wild card into the searchText
            if (string.IsNullOrWhiteSpace(searchText))
            {
                searchText = "*";
            }
            var response = sessionClient.Documents.Search <Session>(searchText, parameters);

            foreach (SearchResult <Session> result in response.Results)
            {
                sessionList.Add(result.Document);
            }

            return(sessionList);
        }
Ejemplo n.º 10
0
        public ActionResult GetTree()
        {
            try
            {
                // Get parameter
                GetTreeObject PostDataArrived = CS.GetPostData<GetTreeObject>(this.Request);
                PostDataArrived.Configuration.Locale = System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

                TreeWidget treeWidget = new TreeWidget(PostDataArrived, connectionStringSetting.ConnectionString);
                SessionImplObject ret = treeWidget.GetTree();

                // Clear session on change ws
                Session[SESSION_KEY] = null;

                /*NUOVO */
                var query = new SessionQuery { CurrentCulture = System.Threading.Thread.CurrentThread.CurrentCulture };
                if (SessionQueryManager.SessionQueryExistsAndIsValid(Session))
                {
                    query = SessionQueryManager.GetSessionQuery(Session);
                }
                else
                {
                    query = new SessionQuery { CurrentCulture = System.Threading.Thread.CurrentThread.CurrentCulture };
                    SessionQueryManager.SaveSessionQuery(Session, query);
                }
                query._endpointSettings = PostDataArrived.Configuration;

                // Clear sessionQueryManager
                ISdmxObjects obj = ret.SdmxObject;

                // Get categories - first without annotations
                IList<ICategorySchemeObject> categoriesWithAnnotation = new List<ICategorySchemeObject>();
                IList<ICategorySchemeObject> categoriesWithoutAnnotation = new List<ICategorySchemeObject>();

                foreach (var categoryScheme in obj.CategorySchemes)
                {
                    if (categoryScheme.Annotations.Count > 0 && categoryScheme.Annotations[0].FromAnnotation() == CustomAnnotationType.CategorySchemeNodeOrder)
                    {
                        categoriesWithAnnotation.Add(categoryScheme);
                    }
                    else
                    {
                        categoriesWithoutAnnotation.Add(categoryScheme);
                    }
                }

                IEnumerable<ICategorySchemeObject> categoriesWithAnnotationOrderedBy = categoriesWithAnnotation.OrderBy(category => Convert.ToInt64(category.Annotations[0].ValueFromAnnotation()));

                IEnumerable<ICategorySchemeObject> categories = categoriesWithoutAnnotation.Concat(categoriesWithAnnotationOrderedBy);

                //Get dataflows
                ISet<IDataflowObject> dataflows = obj.Dataflows;

                // Get categorisations - first without annotations
                IList<ICategorisationObject> categorisationsWithAnnotation = new List<ICategorisationObject>();
                IList<ICategorisationObject> categorisationsWithoutAnnotation = new List<ICategorisationObject>();

                foreach (var categorisation in obj.Categorisations)
                {
                    if (categorisation.Annotations.Count > 0 && categorisation.Annotations[0].FromAnnotation() == CustomAnnotationType.CategorySchemeNodeOrder)
                    {
                        categorisationsWithAnnotation.Add(categorisation);
                    }
                    else
                    {
                        categorisationsWithoutAnnotation.Add(categorisation);
                    }
                }

                IEnumerable<ICategorisationObject> categorisationsWithAnnotationOrderedBy = categorisationsWithAnnotation.OrderBy(categ => Convert.ToInt64(categ.Annotations[0].ValueFromAnnotation()));

                IEnumerable<ICategorisationObject> categorisations = categorisationsWithoutAnnotation.Concat(categorisationsWithAnnotationOrderedBy);

                query.InitializeDataflowMap(dataflows);

                // Get dsds
                ISet<IDataStructureObject> dataStructure = obj.DataStructures;
                query.ResetDsds();
                query.Dsds = dataStructure;

                query.SetDataflowTree(categories, dataflows, categorisations, dataStructure);

                /*FINE NUOVO*/

                /*old*/
                return CS.ReturnForJQuery(ret.SavedTree);
                //return CS.ReturnForJQuery(query._dataflowTreeList.GetJSTree());
            }
            catch (Exception ex)
            {
                return CS.ReturnForJQuery(ex.Message);
            }
        }
Ejemplo n.º 11
0
        /*NUOVO SESSION QUERY*/
        /// <summary>
        /// Get a CodeList for the specified component from either <see cref="INsiClient"/> or from <see cref="SessionQuery"/> cache.
        /// </summary>
        /// <param name="query">
        /// The SessionQuery holding the current dataflow and possibly the artefact cache
        /// </param>
        /// <param name="component">
        /// The SDMX DSD component to retrieve the artefact for
        /// </param>
        /// <returns>
        /// A artefact or null
        /// </returns>
        private ICodelistObject GetCodeList(SessionQuery query, IComponent component)
        {
            //INsiClient nsiClient = GetNSIClient(this.Context);
            ICodelistObject codes = query.GetCachedCodelist(component);
            if (codes == null)
            {
                //QueryBuilder queryBuilder = new QueryBuilder(query);
                //codes = IGetSDMX.GetCodelist(query.Dataflow, query.KeyFamily, component, queryBuilder.CreateConstraintBean(component.ConceptRef.ChildReference.Id),true);
                codes = this.GetCodeListCostraint(query.Dataflow, query.KeyFamily, component);
                query.UpdateCodelistMap(codes, component);
                //NEL CASO DI CODE TIME LIST VENGONO RIPARSATE
                codes = query.GetCachedCodelist(component);
            }
            /*cort code @order@
            var sortedCodes = codes.Items.OrderBy<ICode, int>(
                 o =>
                 {
                     var corder = o.Annotations.FirstOrDefault(mutableObject => string.Equals(mutableObject.Type, "@ORDER@"));
                     return corder != null ? int.Parse(corder.Text[0].Value) : 0;
                 }).ToArray();

            foreach (ICode obj in codes.Items)
                codes.Items.Remove(obj);

            foreach (ICode obj in sortedCodes)
                codes.Items.Add(obj);
            */

            return codes;
        }
Ejemplo n.º 12
0
        public SessionImplObject GetSpecificCodemap(bool firstDimension, ConnectionStringSettings connectionStringSetting, SessionQuery query)
        {
            try
            {
                ISdmxObjects structure;
                //ISdmxObjects structure = query._structure;
                if (query.Structure == null)
                { structure = GetDsd(); }
                else
                { structure =
                    query.Structure; }

                IDataflowObject df = structure.Dataflows.First();
                IDataStructureObject kf = structure.DataStructures.First();

                query.Structure = structure;
                query.Dataflow = df;

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

                TemplateWidget templateWidget = new TemplateWidget();
                var template = new TemplateObject();
                //if (connectionStringSetting.ConnectionString !=null && connectionStringSetting.ConnectionString.ToLower() != "file")
                if (connectionStringSetting.ConnectionString != null)
                {
                    templateWidget = new TemplateWidget(connectionStringSetting.ConnectionString);
                    template = templateWidget.GetSingle(new GetTemplateObject()
                    {
                        Template = new TemplateObject()
                        {
                            Dataflow = CodemapObj.Dataflow,
                            Configuration = CodemapObj.Configuration,
                        }
                    });
                }
                else
                { template = null; }

                string dimension = null;
                Dictionary<string, ICodelistObject> ConceptCodelists = null;

                // Se ha una template forzo il retrive di tutte le codelist per evitare problemi in stampa tabella
                if (template!=null)
                {
                    ConceptCodelists = this.GetCodelistMap(query, false);
                    query.Criteria = template.Criteria;

                    if (template.Criteria.ContainsKey(kf.TimeDimension.Id))
                    {
                        List<string> typeCheck = template.Criteria[kf.TimeDimension.Id] as List<string>;
                        if (typeCheck != null)
                            typeCheck.Sort();
                        query.SetCriteriaTime(typeCheck);
                    }
                }
                else
                 {
                    dimension = (firstDimension) ? kf.DimensionList.Dimensions.FirstOrDefault().Id : CodemapObj.Codelist;
                    IComponent component = kf.GetComponent(dimension);
                    ICodelistObject ConceptCodelistsComponent = GetCodeList(query, component);
                    //se chiedo tutte le codelist insieme
                    //ConceptCodelists = GetCodelistMap(query, false);
                    //se chiedo una codelist alla volta
                    //ConceptCodelists = GetCodelistMap(component.Id, df, kf;
                    ConceptCodelists = GetCodelistMap(component.Id, df, kf,query);

                  }

                CodemapSpecificResponseObject codemapret = new CodemapSpecificResponseObject()
                {
                    codemap = ParseCodelist(ConceptCodelists,kf,query),
                    costraint = (template != null) ? template.Criteria : null,
                    hideDimension = (template != null) ? template.HideDimension : null,
                    //enabledVar = (template != null) ? template.EnableVaration : true,
                    enabledVar = (template != null) ? template.EnableVaration : false,
                    enabledCri = (template != null) ? template.EnableCriteria : true,
                    enabledDec = (template != null) ? template.EnableDecimal : true,
                    codelist_target = dimension,
                    key_time_dimension = kf.TimeDimension.Id,
                    freq_dimension = kf.FrequencyDimension.Id,
                    dataflow = new MaintenableObj()
                    {
                        id = df.Id,
                        agency = df.AgencyId,
                        version = df.Version,
                        name = TextTypeHelper.GetText(df.Names, this.CodemapObj.Configuration.Locale),
                        description = TextTypeHelper.GetText(df.Descriptions, this.CodemapObj.Configuration.Locale)
                    }
                };

                this.SessionObj.SavedCodemap = new JavaScriptSerializer().Serialize(codemapret);
                return this.SessionObj;
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message, ex);
                throw ex;
            }
        }
Ejemplo n.º 13
0
        public SessionImplObject GetCodemap(SessionQuery query, ConnectionStringSettings connectionStringSetting)
        {
            try
            {
                ISdmxObjects structure = query.Structure;// GetDsd();
                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");

                Dictionary<string, ICodelistObject> ConceptCodelists = GetCodelistMap(query, false);

                if (this.SessionObj.SdmxObject!=null )
                { this.SessionObj.SdmxObject.Codelists.Clear();

                foreach (ICodelistObject codelist in ConceptCodelists.Values)
                    this.SessionObj.SdmxObject.AddCodelist(codelist);
                }

                /*check if exist connection and one template*/
                TemplateWidget templateWidget = new TemplateWidget();
                var template = new TemplateObject();

                ///if (connectionStringSetting.ConnectionString!=null && connectionStringSetting.ConnectionString.ToLower() != "file")
                if (connectionStringSetting.ConnectionString != null)
                {
                    templateWidget = new TemplateWidget(connectionStringSetting.ConnectionString);
                    template = templateWidget.GetSingle(new GetTemplateObject()
                    {
                        Template = new TemplateObject()
                        {
                            Dataflow = CodemapObj.Dataflow,
                            Configuration = CodemapObj.Configuration,
                        }
                    });
                }
                else
                { template = null; }

                CodemapSpecificResponseObject codemapret = new CodemapSpecificResponseObject()
                {
                    codemap = ParseCodelist(ConceptCodelists),
                    costraint = (template != null) ? template.Criteria : null,
                    hideDimension = (template != null) ? template.HideDimension : null,
                    //enabledVar = (template != null) ? template.EnableVaration : true,
                    enabledVar = (template != null) ? template.EnableVaration : false,
                    enabledCri = (template != null) ? template.EnableCriteria : true,
                    enabledDec = (template != null) ? template.EnableDecimal : true,
                    key_time_dimension = kf.TimeDimension.Id,
                    freq_dimension = kf.FrequencyDimension.Id,
                    dataflow = new MaintenableObj()
                    {
                        id = df.Id,
                        agency = df.AgencyId,
                        version = df.Version,
                        name = TextTypeHelper.GetText(df.Names, this.CodemapObj.Configuration.Locale),
                        description = TextTypeHelper.GetText(df.Descriptions, this.CodemapObj.Configuration.Locale)
                    }
                };

                this.SessionObj.SavedCodemap = new JavaScriptSerializer().Serialize(codemapret);
                return this.SessionObj;
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message, ex);
                throw ex;
            }
        }
Ejemplo n.º 14
0
        public Dictionary<string, ICodelistObject> GetCodelistMap(
             SessionQuery query,
             bool withAttribute)
        {
            Dictionary<string, ICodelistObject> Conceptcodelist = new Dictionary<string, ICodelistObject>();
            IDataflowObject df = query._dataflow;
            IDataStructureObject kf = query._keyFamily;

            if (kf != null && df != null)
            {
                RetrieveMissingCodeslists(query);

                foreach (IDimension component in
                    kf.DimensionList.Dimensions.Where(
                    c => c.HasCodedRepresentation()
                        && !string.IsNullOrEmpty(c.Representation.Representation.MaintainableReference.MaintainableId)))
                    Conceptcodelist.Add(component.Id, this.GetCodeList(query, component));

                if (withAttribute && kf.AttributeList != null)
                {
                    foreach (IComponent component in kf.AttributeList.Attributes.Where(c => c.HasCodedRepresentation() && !string.IsNullOrEmpty(c.Representation.Representation.MaintainableReference.MaintainableId)))
                        Conceptcodelist.Add(component.Id, this.GetCodeList(query, component));
                }

                if (Conceptcodelist.ContainsKey(kf.FrequencyDimension.Id) == true
                    && Conceptcodelist[kf.FrequencyDimension.Id] != null)
                    Conceptcodelist.Add(kf.TimeDimension.Id, this.GetTimeCodeList(Conceptcodelist[kf.FrequencyDimension.Id], df, kf,query));

                if (this.SessionObj.CodelistConstrained == null) this.SessionObj.CodelistConstrained = new Dictionary<string, Dictionary<string, ICodelistObject>>();
                this.SessionObj.CodelistConstrained[Utils.MakeKey(df)] = Conceptcodelist;

            }
            return Conceptcodelist;
        }
        public static void Main(string[] args)
        {
            /******************* REQUEST VARIABLES*******************************/

            string host      = "esqa.moneris.com";
            string store_id  = "moneris";
            string api_token = "hurgle";

            /****************** TRANSACTION VARIABLES *****************************/

            string order_id;                    //will prompt user for input
            string session_id   = "abc123";
            string service_type = "session";
            string event_type   = "LOGIN";

            Console.Write("Please enter an order ID: ");
            order_id = Console.ReadLine();

            SessionQuery sq = new SessionQuery(order_id, session_id, service_type);

            sq.setEventType(event_type);

            //sq.setPolicy("");
            //sq.setDeviceId("4EC40DE5-0770-4fa0-BE53-981C067C598D");
            sq.setAccountLogin("13195417-8CA0-46cd-960D-14C158E4DBB2");
            sq.setPasswordHash("489c830f10f7c601d30599a0deaf66e64d2aa50a");
            sq.setAccountNumber("3E17A905-AC8A-4c8d-A417-3DADA2A55220");
            sq.setAccountName("4590FCC0-DF4A-44d9-A57B-AF9DE98B84DD");
            sq.setAccountEmail("*****@*****.**");
            //sq.setAccountTelephone("5556667777");
            sq.setPan("4242424242424242");
            //sq.setAccountAddressStreet1("3300 Bloor St W");
            //sq.setAccountAddressStreet2("4th Flr West Tower");
            //sq.setAccountAddressCity("Toronto");
            //sq.setAccountAddressState("Ontario");
            //sq.setAccountAddressCountry("Canada");
            //sq.setAccountAddressZip("M8X2X2");
            //sq.setShippingAddressStreet1("3300 Bloor St W");
            //sq.setShippingAddressStreet2("4th Flr West Tower");
            //sq.setShippingAddressCity("Toronto");
            //sq.setShippingAddressState("Ontario");
            //sq.setShippingAddressCountry("Canada");
            //sq.setShippingAddressZip("M8X2X2");
            //sq.setLocalAttrib1("a");
            //sq.setLocalAttrib2("b");
            //sq.setLocalAttrib3("c");
            //sq.setLocalAttrib4("d");
            //sq.setLocalAttrib5("e");
            //sq.setTransactionAmount("1.00");
            //sq.setTransactionCurrency("840");
            //set SessionAccountInfo
            sq.setTransactionCurrency("CAN");


            HttpsPostRequest mpgReq =
                new HttpsPostRequest(host, store_id, api_token, sq);

            try
            {
                Hashtable results = new Hashtable();
                string[]  rules;
                Receipt   receipt = mpgReq.GetReceipt();

                Console.WriteLine("ResponseCode = " + receipt.GetResponseCode());
                Console.WriteLine("Message = " + receipt.GetMessage());
                Console.WriteLine("TxnNumber = " + receipt.GetTxnNumber());

                results = receipt.GetResult();

                //Iterate through the response
                IDictionaryEnumerator r = results.GetEnumerator();
                while (r.MoveNext())
                {
                    Console.WriteLine(r.Key.ToString() + " = " + r.Value.ToString());
                }

                //Iterate through the rules that were fired
                rules = receipt.GetRules();

                for (int i = 0; i < rules.Length; i++)
                {
                    Console.WriteLine("RuleName = " + rules[i]);
                    Console.WriteLine("RuleCode = " + receipt.GetRuleCode(rules[i]));
                    Console.WriteLine("RuleMessageEn = " + receipt.GetRuleMessageEn(rules[i]));
                    Console.WriteLine("RuleMessageFr = " + receipt.GetRuleMessageFr(rules[i]));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Ejemplo n.º 16
0
        public Task <SessionResponseList> List(SessionQuery query = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var parameters = query.ToParameters();

            return(apiConnection.Get <SessionResponseList>("/sessions", parameters, HttpMessageTransformer, cancellationToken));
        }
        internal IDataSetStore GetDataset(IDataflowObject df, IDataStructureObject kf, List <DataCriteria> Criterias, ref Dictionary <string, List <DataChacheObject> > DataCache, bool useAttr, SessionQuery query)
        {
            // if it is not time series then assume it is cross
            SDMXWSFunction op    = SDMXWSFunction.GetCompactData;
            bool           cross = (DataObjConfiguration._TypeEndpoint == EndpointType.V21 || DataObjConfiguration._TypeEndpoint == EndpointType.REST)
                          ? NsiClientHelper.DataflowDsdIsCrossSectional(kf) : !Utils.IsTimeSeries(kf);

            if (cross)
            {
                op = SDMXWSFunction.GetCrossSectionalData;
            }

            var ser = new JavaScriptSerializer();

            ser.MaxJsonLength = int.MaxValue;
            try
            {
                #region Connessione e Creazione DB SQLLite FABIO se nullo lo istanzio
                string   table         = null;
                IGetSDMX GetSDMXObject = (query._IGetSDMX == null) ? WebServiceSelector.GetSdmxImplementation(DataObjConfiguration) : query._IGetSDMX;
                GetSDMXObject.ExecuteQuery(CreateQueryBean(df, kf, Criterias), op, FileTmpData);

                #region Connessione e Creazione DB SQLLite
                table = Path.Combine(Utils.GetAppPath(), string.Format(CultureInfo.InvariantCulture, "{0}-{1}.sqlite", Utils.MakeKey(df).Replace("+", "_").Replace(".", ""), Guid.NewGuid()));
                string        ConnectionString = string.Format(CultureInfo.InvariantCulture, Constants.FileDBSettingsFormat, table);
                var           info             = new DBInfo(ConnectionString);
                string        tempTable        = "table_" + Utils.MakeKey(df).Replace("+", "_").Replace(".", "");
                IDataSetStore store            = new DataSetStoreDB(info, tempTable, kf, true, useAttr);
                #endregion

                using (var dataLocation = new FileReadableDataLocation(FileTmpData))
                {
                    switch (op)
                    {
                    case SDMXWSFunction.GetCompactData:
                        var compact       = new CompactDataReaderEngine(dataLocation, df, kf);
                        var readerCompact = new SdmxDataReader(kf, store);
                        readerCompact.ReadData(compact);
                        break;

                    case SDMXWSFunction.GetCrossSectionalData:
                        var dsdCrossSectional = (ICrossSectionalDataStructureObject)kf;
                        var crossSectional    = new CrossSectionalDataReaderEngine(dataLocation, dsdCrossSectional, df);
                        var reader            = new SdmxDataReader(kf, store);
                        reader.ReadData(crossSectional);
                        break;

                    default:
                        throw new ArgumentException(Resources.ExceptionUnsupported_operation + op.ToString(), "operation");
                    }
                }

                #endregion FABIO



                return(store);
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message, ex);
                throw ex;
            }
            finally
            {
                //delete the temporary file
                if (File.Exists(FileTmpData))
                {
                    File.Delete(FileTmpData);
                }
            }
        }
 public Task <SessionInfoDto[]> GetClientSessionsAsync(SessionQuery query)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 19
0
        public static SessionQuery Where(string dataSourceName = null, DateTimeOffset?requestedAfterDate = null, DateTimeOffset?requestedBeforeDate = null, SessionQuery query = null)
        {
            var theQuery = query ?? new SessionQuery()
            {
                DataSourceName = dataSourceName
            };

            theQuery.DataSourceName = dataSourceName;
            if (requestedAfterDate.HasValue)
            {
                theQuery.RequestedAfterDate = requestedAfterDate;
            }
            if (requestedBeforeDate.HasValue)
            {
                theQuery.RequestedBeforeDate = requestedBeforeDate;
            }

            return(theQuery);
        }
Ejemplo n.º 20
0
        public ActionResult ClearSession()
        {
            // Clear session on change ws
            Session[SESSION_KEY] = null;

            var query = new SessionQuery { CurrentCulture = System.Threading.Thread.CurrentThread.CurrentCulture };
            if (SessionQueryManager.SessionQueryExistsAndIsValid(Session))
            {
                query = SessionQueryManager.GetSessionQuery(Session);
            }
            query.Reset();

            return CS.ReturnForJQuery(JSONConst.Success);
        }
Ejemplo n.º 21
0
        public ActionResult IsCachingDataSet()
        {
            GetDataObject PostDataArrived = CS.GetPostData<GetDataObject>(this.Request);
            CacheWidget cache = new CacheWidget(connectionStringSetting.ConnectionString);

            /*reset query*/
            var query = new SessionQuery { CurrentCulture = System.Threading.Thread.CurrentThread.CurrentCulture };
            if (SessionQueryManager.SessionQueryExistsAndIsValid(Session))
            {
                query = SessionQueryManager.GetSessionQuery(Session);
            }
            query.Reset();

            if (PostDataArrived.WidgetId > 0 && UseWidgetCache)
            {
                if (cache.IsCachedWidget(PostDataArrived.WidgetId, System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.Trim()))
                    return CS.ReturnForJQuery(JSONConst.Success);
            }

            return CS.ReturnForJQuery(JSONConst.Error);
        }
Ejemplo n.º 22
0
        private ICodelistObject GetTimeCodeList(ICodelistObject FreqCodelist, IDataflowObject df, IDataStructureObject kf,SessionQuery query)
        {
            ICodelistObject CL_TIME_MA = this.GetCodeList(query, kf.TimeDimension);
            if (CL_TIME_MA == null || CL_TIME_MA.Items == null || CL_TIME_MA.Items.Count != 2)
                return CL_TIME_MA;

            //string format_time = (CL_TIME_MA.Items[0].Id.Contains("-")) ? "yyyy-MM-dd" : "yyyy";
            string time_min_normal = CL_TIME_MA.Items[0].Id;
            string time_max_normal = CL_TIME_MA.Items[1].Id;

            /*fabio 04/11/2015 v3.0.0.0*/
            if (time_min_normal.CompareTo(time_max_normal) > 0)
            {
                time_max_normal = CL_TIME_MA.Items[0].Id;
                time_min_normal = CL_TIME_MA.Items[1].Id;
            }
            else
            {
                time_max_normal = CL_TIME_MA.Items[1].Id;
                time_min_normal = CL_TIME_MA.Items[0].Id;
            }
            /*fine fabio 04/11/2015 v3.0.0.0*/

            string FrequencyDominant = null;
            if (CodemapObj.PreviusCostraint != null
                && CodemapObj.PreviusCostraint.ContainsKey(kf.FrequencyDimension.Id))
                FrequencyDominant = CodemapObj.PreviusCostraint[kf.FrequencyDimension.Id].First();
            if (FrequencyDominant == null)
            {
                FrequencyDominant = "A";
                if (FreqCodelist.Items.Count(c => c.Id.ToUpper() == "S") > 0) FrequencyDominant = "S";
                if (FreqCodelist.Items.Count(c => c.Id.ToUpper() == "Q") > 0) FrequencyDominant = "Q";
                if (FreqCodelist.Items.Count(c => c.Id.ToUpper() == "M") > 0) FrequencyDominant = "M";
            }
            if (!CL_TIME_MA.Items[0].Id.Contains("-"))
            {
                time_min_normal = string.Format("{0}-{1}-{2}", CL_TIME_MA.Items[0].Id, "01", "01");
                time_max_normal = string.Format("{0}-{1}-{2}", CL_TIME_MA.Items[1].Id, "01", "01");
            }
            else
            {
                var time_p_c = CL_TIME_MA.Items[0].Id.Split('-');
                if (time_p_c.Length == 2)
                {
                    int mul =
                        (FrequencyDominant == "M") ? 1 :
                        (FrequencyDominant == "Q") ? 3 :
                        (FrequencyDominant == "S") ? 6 : 0;

                    int t_fix = (int.Parse(time_p_c[1].Substring(1))) * mul;
                    time_min_normal = string.Format("{0}-{1}-{2}", time_p_c[0], (t_fix > 9) ? t_fix.ToString() : "0" + t_fix.ToString(), "01");
                    time_p_c = CL_TIME_MA.Items[1].Id.Split('-');
                    t_fix = (int.Parse(time_p_c[1].Substring(1))) * mul;
                    time_max_normal = string.Format("{0}-{1}-{2}", time_p_c[0], (t_fix > 9) ? t_fix.ToString() : "0" + t_fix.ToString(), "01");
                }
                if (CL_TIME_MA.Items[0].Id.Contains("S"))
                {
                    var time_p = CL_TIME_MA.Items[0].Id.Split('-');
                    int t_fix = (int.Parse(time_p[1].Substring(1))) * 6;
                    time_min_normal = string.Format("{0}-{1}-{2}", time_p[0], (t_fix > 9) ? t_fix.ToString() : "0" + t_fix.ToString(), "01");

                    time_p = CL_TIME_MA.Items[1].Id.Split('-');
                    t_fix = (int.Parse(time_p[1].Substring(1))) * 6;
                    time_max_normal = string.Format("{0}-{1}-{2}", time_p[0], (t_fix > 9) ? t_fix.ToString() : "0" + t_fix.ToString(), "01");
                }
                if (CL_TIME_MA.Items[0].Id.Contains("Q"))
                {
                    var time_p = CL_TIME_MA.Items[0].Id.Split('-');
                    int t_fix = ((int.Parse(time_p[1].Substring(1))) * 3);
                    time_min_normal = string.Format("{0}-{1}-{2}", time_p[0], (t_fix > 9) ? t_fix.ToString() : "0" + t_fix.ToString(), "01");

                    time_p = CL_TIME_MA.Items[1].Id.Split('-');
                    t_fix = ((int.Parse(time_p[1].Substring(1))) * 3);
                    time_max_normal = string.Format("{0}-{1}-{2}", time_p[0], (t_fix > 9) ? t_fix.ToString() : "0" + t_fix.ToString(), "01");
                }
                if (CL_TIME_MA.Items[0].Id.Contains("M"))
                {
                    var time_p = CL_TIME_MA.Items[0].Id.Split('-');
                    int t_fix = (int.Parse(time_p[1].Substring(1))) * 1;
                    time_min_normal = string.Format("{0}-{1}-{2}", time_p[0], (t_fix > 9) ? t_fix.ToString() : "0" + t_fix.ToString(), "01");

                    time_p = CL_TIME_MA.Items[1].Id.Split('-');
                    t_fix = (int.Parse(time_p[1].Substring(1))) * 1;
                    time_max_normal = string.Format("{0}-{1}-{2}", time_p[0], (t_fix > 9) ? t_fix.ToString() : "0" + t_fix.ToString(), "01");
                }
            }

            DateTime MinDate = DateTime.ParseExact(time_min_normal, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None);
            DateTime MaxDate = DateTime.ParseExact(time_max_normal, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None);
            //fabio baco
            //CultureInfo enEn = new CultureInfo("en");
            //DateTime MinDate = DateTime.ParseExact(time_min_normal, "yyyy-MM-dd", enEn, DateTimeStyles.None);
            //DateTime MaxDate = DateTime.ParseExact(time_max_normal, "yyyy-MM-dd", enEn, DateTimeStyles.None);

            ICodelistMutableObject CL_TIME = new CodelistMutableCore();
            CL_TIME.Id = CL_TIME_MA.Id;
            CL_TIME.AgencyId = CL_TIME_MA.AgencyId;
            CL_TIME.Version = CL_TIME_MA.Version;

            CL_TIME_MA.Names.ToList().ForEach(n => CL_TIME.AddName(n.Locale, n.Value));

            DateTime ActualDate = MinDate;
            switch (FrequencyDominant)
            {
                case "A":
                    #region Aggiungo gli Annual
                    while (ActualDate.CompareTo(MaxDate) <= 0)
                    {
                        ICodeMutableObject code = new CodeMutableCore();
                        code.Id = ActualDate.Year.ToString();
                        code.AddName("en", code.Id);
                        CL_TIME.AddItem(code);

                        ActualDate = ActualDate.AddYears(1);
                    }
                    #endregion
                    break;
                case "S":
                    #region Aggiungo gli Semestrali
                    while (ActualDate.CompareTo(MaxDate) <= 0)
                    {
                        ICodeMutableObject code = new CodeMutableCore();
                        code.Id = ActualDate.Year.ToString() + "-S" + (ActualDate.Month < 6 ? "1" : "2");
                        code.AddName("en", code.Id);
                        CL_TIME.AddItem(code);

                        ActualDate = ActualDate.AddMonths(6);
                    }
                    #endregion
                    break;
                case "Q":
                    #region Aggiungo i Quartely
                    while (ActualDate.CompareTo(MaxDate) <= 0)
                    {
                        ICodeMutableObject code = new CodeMutableCore();
                        code.Id = ActualDate.Year.ToString() + "-Q" + ((ActualDate.Month - 1) / 3 + 1).ToString();
                        code.AddName("en", code.Id);
                        CL_TIME.AddItem(code);

                        ActualDate = ActualDate.AddMonths(3);
                    }
                    #endregion
                    break;
                case "M":
                    #region Aggiungo i Mensili
                    while (ActualDate.CompareTo(MaxDate) <= 0)
                    {
                        ICodeMutableObject code = new CodeMutableCore();
                        code.Id = ActualDate.ToString("yyyy-MM");
                        code.AddName("en", code.Id);
                        CL_TIME.AddItem(code);

                        ActualDate = ActualDate.AddMonths(1);
                    }
                    #endregion
                    break;
                default:
                    break;
            }

            return CL_TIME.ImmutableInstance;
        }
Ejemplo n.º 23
0
        private Dictionary<string, CodemapObj> ParseCodelist(Dictionary<string, ICodelistObject> Codemap, IDataStructureObject kf,SessionQuery query)
        {
            Dictionary<string, CodemapObj> dr_codemap = new Dictionary<string, CodemapObj>();
            //IDataStructureObject kf = query._keyFamily;

            foreach (string conceptId in Codemap.Keys)
            {
                ICodelistObject codelist = Codemap[conceptId];
                if (codelist != null)
                {
                    if (this.SessionObj != null && this.SessionObj.SdmxObject != null)
                    { this.SessionObj.SdmxObject.AddCodelist(codelist); }

                    var component =
                       kf.DimensionList.Dimensions.FirstOrDefault(
                       c => c.HasCodedRepresentation()
                           && c.ConceptRef.FullId == conceptId);
                           //&& !string.IsNullOrEmpty(c.Representation.Representation.MaintainableReference.MaintainableId));
                           //&& c.Representation.Representation.MaintainableReference.MaintainableId == Codemap[conceptId].Id);
                           //&& kf.Id == conceptId);

                    if (component != null )
                    {
                        //var conceptScheme = this.SessionObj.SdmxObject.ConceptSchemes.FirstOrDefault(c => c.Id == component.ConceptRef.MaintainableId);
                        var conceptScheme = query.Structure.ConceptSchemes.FirstOrDefault(c => c.Id == component.ConceptRef.MaintainableId);
                        //var conceptScheme = this.GetCodeList(query, component);
                        //GetCodelistMap(query, false);

                        foreach (var concept in conceptScheme.Items)
                        {
                            //if (component.Id == concept.Id)
                           if (component.ConceptRef.FullId == concept.Id)
                           // if (component.ConceptRef.FullId == concept.AsReference.FullId)
                            //if (component.Representation.Representation.MaintainableId == concept.IdentifiableParent.Id)
                            {
                                //if (Codemap[conceptId]==concept){
                                CodemapObj codemap = new CodemapObj()
                                {
                                    title = TextTypeHelper.GetText(concept.Names, this.CodemapObj.Configuration.Locale),
                                    codes = new Dictionary<string, CodeObj>()
                                };
                                foreach (ICode codeItem in codelist.Items)
                                    codemap.codes.Add(
                                        codeItem.Id.ToString(),
                                        new CodeObj()
                                        {
                                            name = TextTypeHelper.GetText(codeItem.Names, this.CodemapObj.Configuration.Locale),
                                            parent = codeItem.ParentCode
                                        });

                                codemap.codes = codemap.codes.OrderBy(c => c.Value.parent == null).ToDictionary(c => c.Key, c => c.Value);
                                dr_codemap.Add(conceptId, codemap);
                            }
                        }

                     }
                     else {  //time_period code_list esiste nel codemap ma non esiste nel concept schema
                                CodemapObj codemap = new CodemapObj()
                                {
                                    title = TextTypeHelper.GetText(codelist.Names, this.CodemapObj.Configuration.Locale),
                                    codes = new Dictionary<string, CodeObj>()
                                };
                                foreach (ICode codeItem in codelist.Items)
                                    codemap.codes.Add(
                                        codeItem.Id.ToString(),
                                        new CodeObj()
                                        {
                                            name = TextTypeHelper.GetText(codeItem.Names, this.CodemapObj.Configuration.Locale),
                                            parent = codeItem.ParentCode
                                        });

                                codemap.codes = codemap.codes.OrderBy(c => c.Value.parent == null).ToDictionary(c => c.Key, c => c.Value);
                                dr_codemap.Add(conceptId, codemap);
                           }
                }
                else { dr_codemap.Add(conceptId, null); }

            }
            return dr_codemap;
        }
Ejemplo n.º 24
0
        private static IDataSetStore GetDataSetStore(SessionQuery query)
        {
            IDataSetStore store;
            long size = 0;

            string dataSet = query.GetSdmxMLDataSet(false);
            using (var datasetStream = System.IO.File.Open(dataSet, FileMode.Open, FileAccess.Read, FileShare.None))
                {

                    if (datasetStream.CanSeek)
                    {
                        size = datasetStream.Length / 1024 / 1024;
                    }
                    else
                    {

                        size = (WebClientSettings.Instance.MaxResultObs == 0
                                    ? query.CurrentMax
                                    : Math.Min(WebClientSettings.Instance.MaxResultObs, query.CurrentMax)) / 10000;
                    }
                }

            if (size < 10)
            {
                var settings = Constants.InMemoryDBSettings;
                store = BuildDBDataSetStore(query, settings);
            }
            else
            {
                string sqliteFileName = string.Format(
                    CultureInfo.InvariantCulture,
                    Constants.FileDBFileNameFormat,
                    query.GetSessionPrefix(),
                    Path.GetRandomFileName());
                string table = Path.Combine(
                    query.GetCacheFolder().FullName,
                    sqliteFileName);
                var settings = new ConnectionStringSettings(
                    Constants.ConnectionStringSettingsName, string.Format(CultureInfo.InvariantCulture, Constants.FileDBSettingsFormat, table), Constants.SystemDataSqlite);
                store = BuildDBDataSetStore(query, settings);
            }

            return store;
        }
Ejemplo n.º 25
0
        public Dictionary<string, ICodelistObject> GetCodelistMap(
            string dim,
            IDataflowObject df,
            IDataStructureObject kf,
            SessionQuery query)
        {
            Dictionary<string, ICodelistObject> Conceptcodelist = new Dictionary<string, ICodelistObject>();

            foreach (IDimension component in kf.DimensionList.Dimensions)

                Conceptcodelist.Add(component.Id, null);

            if (dim != kf.TimeDimension.Id)
            {
                var dimCodelist = kf.DimensionList.Dimensions.Where(
                    c => c.HasCodedRepresentation()
                    && !string.IsNullOrEmpty(c.Representation.Representation.MaintainableReference.MaintainableId)
                    && c.Id == dim).FirstOrDefault();

                //fabio nuovo 25/11/2015
                //var dimCodelistSession = this.SessionObj.SdmxObject.Codelists.Where(c => c.Id == dimCodelist.Representation.Representation.MaintainableReference.MaintainableId).FirstOrDefault();
                var dimCodelistSession = this.SessionObj.SdmxObject.Codelists.Where(c => c.Id == dimCodelist.ConceptRef.FullId).FirstOrDefault();
                if (dimCodelistSession != null)
                { Conceptcodelist[dimCodelist.Id] = dimCodelistSession; }
                else
                {
                    //Conceptcodelist[dimCodelist.Id] = this.GetCodeListCostraint(df, kf, dimCodelist);
                    Conceptcodelist[dimCodelist.Id] = GetCodeList(query, dimCodelist);
                }
                //fine
            }
            else
            {
                //fabio nuovo 25/11/2015
                var freqCodelist = this.SessionObj.SdmxObject.Codelists.Where(c => c.Id == kf.FrequencyDimension.Representation.Representation.MaintainableId).FirstOrDefault();
                if (freqCodelist != null)
                { Conceptcodelist[kf.FrequencyDimension.Id] = freqCodelist; }
                else
                { freqCodelist = (Conceptcodelist[kf.FrequencyDimension.Id] != null) ? Conceptcodelist[kf.FrequencyDimension.Id] : this.GetCodeListCostraint(df, kf, kf.FrequencyDimension); }

                var TimeDimensionCodelist = this.SessionObj.SdmxObject.Codelists.Where(c => c.Id == "CL_" + kf.TimeDimension.Id).FirstOrDefault();

                if (TimeDimensionCodelist != null)
                { Conceptcodelist[kf.TimeDimension.Id] = TimeDimensionCodelist; }
                else
                { Conceptcodelist[kf.TimeDimension.Id] = this.GetTimeCodeListCostraint(freqCodelist, df, kf); }
                //fine

                //var freqCodelist = (Conceptcodelist[kf.FrequencyDimension.Id] != null) ? Conceptcodelist[kf.FrequencyDimension.Id] : this.GetCodeListCostraint(df, kf, kf.FrequencyDimension);
                //Conceptcodelist[kf.TimeDimension.Id] = this.GetTimeCodeListCostraint(freqCodelist, df, kf);
            }
            return Conceptcodelist;
        }
Ejemplo n.º 26
0
 private static IDataSetStore BuildDBDataSetStore(SessionQuery query, ConnectionStringSettings settings)
 {
     var info = new DBInfo(settings);
     string tempTable = "table_" + Path.GetRandomFileName().Replace(".", "_");
     query.AddToDataDisposeList(info);
     return new DataSetStoreDB(info, tempTable, query.KeyFamily,true,false);
 }
Ejemplo n.º 27
0
        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;
        }
Ejemplo n.º 28
0
        public SessionImplObject GetData(out object DataStream,SessionQuery query)
        {
            try
            {
                // Init session objects
                if (this.SessionObj == null)
                {
                    this.SessionObj = new SessionImplObject();
                    this.SessionObj.SdmxObject = new SdmxObjectsImpl();
                }

                if (BDO == null || GetSDMXObject == null)
                    throw new Exception(Messages.label_error_network + " " + DataObj.Configuration.Title);

                codemapWidget = new CodemapWidget(new GetCodemapObject() {
                    Configuration = this.DataObj.Configuration,
                    Dataflow = this.DataObj.Dataflow,
                    PreviusCostraint=this.DataObj.Criteria },
                    this.SessionObj);
                //ISdmxObjects structure = codemapWidget.GetDsd();
                ISdmxObjects structure = query.Structure;
                IDataflowObject df = structure.Dataflows.FirstOrDefault();
                IDataStructureObject kf = structure.DataStructures.First();
                if (df == null) throw new InvalidOperationException("Dataflow is not set");

                /****************/
                // Get all codelist
                /****************/
                //Dictionary<string, ICodelistObject> ConceptCodelists = codemapWidget.GetCodelistMap(df, kf, true);
                Dictionary<string, ICodelistObject> ConceptCodelists = codemapWidget.GetCodelistMap(query, false);
                ComponentCodeDescriptionDictionary codemap = new ComponentCodeDescriptionDictionary();
                foreach (string ConceptId in ConceptCodelists.Keys)
                {
                    ICodelistObject codelist = ConceptCodelists[ConceptId];
                    Dictionary<string, string> codes = new Dictionary<string, string>();
                    foreach (ICode codeItem in codelist.Items)
                        codes.Add(codeItem.Id, TextTypeHelper.GetText(codeItem.Names, this.DataObj.Configuration.Locale));
                    codemap.Add(ConceptId, codes);
                }
                /****************/
                //codemapWidget.GetCodeListCostraint(df,kf,component)

                this.SessionObj.MergeObject(codemapWidget.SessionObj);

                #region Gestione last period
                if (this.DataObj.Criteria.ContainsKey(kf.TimeDimension.Id)
                 && this.DataObj.Criteria[kf.TimeDimension.Id].Count == 1
                 && !this.DataObj.Layout.axis_z.Contains(kf.TimeDimension.Id))
                {
                    int offsetTime = int.Parse(this.DataObj.Criteria[kf.TimeDimension.Id].First());
                    var codMap = codemap;
                    int lengthTime = codMap[kf.TimeDimension.Id].Count;

                    if ((lengthTime - offsetTime) >= 0)
                    {
                        var codes = codMap[kf.TimeDimension.Id].Reverse().Take(offsetTime);
                        List<string> _criteriaTime = (from c in codes select c.Key).ToList<string>();

                        this.DataObj.Criteria[kf.TimeDimension.Id] = new List<string>();
                        this.DataObj.Criteria[kf.TimeDimension.Id].Add(_criteriaTime.Last());
                        this.DataObj.Criteria[kf.TimeDimension.Id].Add(_criteriaTime.First());
                    }
                    else
                    {
                        this.DataObj.Criteria[kf.TimeDimension.Id] = new List<string>();
                        this.DataObj.Criteria[kf.TimeDimension.Id].Add(codemap[kf.TimeDimension.Id].First().Key);
                        this.DataObj.Criteria[kf.TimeDimension.Id].Add(codemap[kf.TimeDimension.Id].Last().Key);
                    }
                }
                #endregion

                LayoutObj layObj = InitLayout(df, kf);
                List<DataCriteria> Criterias = BDO.InitCriteria(kf, this.DataObj.Criteria);
                //query.GetCriteria();

                Dictionary<string, List<DataChacheObject>> DataCache = SessionObj.DataCache;
                List <string> ret = null;
                List<DataCriteria> QueryCriterias=new List<DataCriteria>();

                if (query.Criteria != null)//criteri nulli se proviene da un template
                {
                    if (query._store != null) //.Count == 1)
                    { query.SetCriteriaTime(this.DataObj.Criteria[kf.TimeDimension.Id]); }

                    if (query.Criteria.TryGetValue(kf.TimeDimension.Id, out ret))
                    {
                        if (ret.Count == 1)
                        { query.SetCriteriaTime(this.DataObj.Criteria[kf.TimeDimension.Id]); }
                    }

                    QueryCriterias = query.GetCriteria();
                    /*if (query._store == null) //.Count == 1)
                    { QueryCriterias = Criterias; }
                    else
                    { QueryCriterias = query.GetCriteria(); }*/

                }
                else
                {
                    QueryCriterias = Criterias;
                }

                //aggiunta da fabio
                IDataSetStore store;
                if (query._store != null)
                { store = query._store; }
                else
                {
                    //store = BDO.GetDataset(df, kf, Criterias, ref DataCache, _useAttr);
                    store = BDO.GetDataset(df, kf, QueryCriterias, ref DataCache, _useAttr);
                    query._store = store;
                }
                //fine nuovo

                SessionObj.DataCache = DataCache;

                DataStream = new DataObjectForStreaming()
                {
                    Configuration = this.DataObj.Configuration,
                    store = store,
                    layObj = layObj,
                    Criterias = Criterias,
                    structure = structure,
                    codemap = codemap
                };

                return this.SessionObj;
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message, ex);
                throw ex;
            }
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Retrieve any missing codelists
 /// </summary>
 /// <param name="query">
 /// 
 /// The SessionQuery holding the current dataflow and possibly the artefact cache
 /// </param>
 /// 
 public void RetrieveMissingCodeslists(SessionQuery query)
 {
     foreach (IDimension component in query.KeyFamily.DimensionList.Dimensions)
     {
         if (component.HasCodedRepresentation() && !string.IsNullOrEmpty(component.Representation.Representation.MaintainableReference.MaintainableId))
         {
             this.GetCodeList(query, component);
         }
     }
 }
Ejemplo n.º 30
0
    /// <inheritdoc/>
    public virtual async Task <QueryResult <ServerSideSession> > QuerySessionsAsync(SessionQuery filter = null, CancellationToken cancellationToken = default)
    {
        cancellationToken = cancellationToken == CancellationToken.None ? CancellationTokenProvider.CancellationToken : cancellationToken;

        // it's possible that this implementation could have been done differently (e.g. use the page number for the token)
        // but it was done deliberately in such a way to allow document databases to mimic the logic
        // and omit features not supported (such as total count, total pages, and current page)
        // given that this is intended to be used as an administrative UI feature, performance was less of a concern

        filter ??= new();

        // these are the ids of first and last items in the prior results
        // stored as "x,y" in the filter.ResultsToken.
        var first = 0;
        var last  = 0;

        if (filter.ResultsToken != null)
        {
            var parts = filter.ResultsToken.Split(',', StringSplitOptions.RemoveEmptyEntries);
            if (parts != null && parts.Length == 2)
            {
                Int32.TryParse(parts[0], out first);
                Int32.TryParse(parts[1], out last);
            }
        }

        var countRequested = filter.CountRequested;

        if (countRequested <= 0)
        {
            countRequested = 25;
        }

        var query = Context.ServerSideSessions.AsNoTracking().AsQueryable();

        if (!String.IsNullOrWhiteSpace(filter.DisplayName) ||
            !String.IsNullOrWhiteSpace(filter.SubjectId) ||
            !String.IsNullOrWhiteSpace(filter.SessionId))
        {
            query = query.Where(x =>
                                (filter.SubjectId == null || x.SubjectId.Contains(filter.SubjectId)) ||
                                (filter.SessionId == null || x.SessionId.Contains(filter.SessionId)) ||
                                (filter.DisplayName == null || (x.DisplayName != null && x.DisplayName.Contains(filter.DisplayName) == true))
                                );
        }

        var totalCount = await query.CountAsync(cancellationToken);

        var totalPages = (int)Math.Max(1, Math.Ceiling(totalCount / (countRequested * 1.0)));

        var currPage = 1;

        var hasNext = false;
        var hasPrev = false;

        Entities.ServerSideSession[] items = null;

        if (filter.RequestPriorResults)
        {
            // sets query at the prior record from the last results, but in reverse order
            items = await query.OrderByDescending(x => x.Id)
                    .Where(x => x.Id < first)
                    // and we +1 to see if there's a prev page
                    .Take(countRequested + 1)
                    .ToArrayAsync(cancellationToken);

            // put them back into ID order
            items = items.OrderBy(x => x.Id).ToArray();

            // if we have the one extra, we have a prev page
            hasPrev = items.Length > countRequested;

            if (hasPrev)
            {
                // omit prev results entry
                items = items.Skip(1).ToArray();
            }

            // how many are to the right of these results?
            if (items.Any())
            {
                var postCountId = items[items.Length - 1].Id;
                var postCount   = await query.CountAsync(x => x.Id > postCountId, cancellationToken);

                hasNext  = postCount > 0;
                currPage = totalPages - (int)Math.Ceiling((1.0 * postCount) / countRequested);
            }

            if (currPage == 1 && hasNext && items.Length < countRequested)
            {
                // this handles when we went back and are now at the beginning but items were deleted.
                // we need to start over and re-query from the beginning.
                filter.ResultsToken        = null;
                filter.RequestPriorResults = false;
                return(await QuerySessionsAsync(filter, cancellationToken));
            }
        }
        else
        {
            items = await query.OrderBy(x => x.Id)
                    // if lastResultsId is zero, then this will just start at beginning
                    .Where(x => x.Id > last)
                    // and we +1 to see if there's a next page
                    .Take(countRequested + 1)
                    .ToArrayAsync(cancellationToken);

            // if we have the one extra, we have a next page
            hasNext = items.Length > countRequested;

            if (hasNext)
            {
                // omit next results entry
                items = items.SkipLast(1).ToArray();
            }

            // how many are to the left of these results?
            if (items.Any())
            {
                var priorCountId = items[0].Id;
                var priorCount   = await query.CountAsync(x => x.Id < last, cancellationToken);

                hasPrev  = priorCount > 0;
                currPage = 1 + (int)Math.Ceiling((1.0 * priorCount) / countRequested);
            }
        }

        // this handles prior entries being deleted since paging begun
        if (currPage <= 1)
        {
            currPage = 1;
            hasPrev  = false;
        }

        string resultsToken = null;

        if (items.Length > 0)
        {
            resultsToken = $"{items[0].Id},{items[items.Length - 1].Id}";
        }
        else
        {
            // no results, so we're out of bounds
            hasPrev    = false;
            hasNext    = false;
            totalCount = 0;
            totalPages = 0;
            currPage   = 0;
        }

        var results = items.Select(entity => new ServerSideSession
        {
            Key         = entity.Key,
            Scheme      = entity.Scheme,
            SubjectId   = entity.SubjectId,
            SessionId   = entity.SessionId,
            DisplayName = entity.DisplayName,
            Created     = entity.Created,
            Renewed     = entity.Renewed,
            Expires     = entity.Expires,
            Ticket      = entity.Data,
        }).ToArray();

        var result = new QueryResult <ServerSideSession>
        {
            ResultsToken   = resultsToken,
            HasNextResults = hasNext,
            HasPrevResults = hasPrev,
            TotalCount     = totalCount,
            TotalPages     = totalPages,
            CurrentPage    = currPage,
            Results        = results
        };

        Logger.LogDebug("Found {serverSideSessionCount} server-side sessions in database", results.Length);

        return(result);
    }
Ejemplo n.º 31
0
        public string ComponentSave(string concept, string[] ids, SessionQuery query)
        {
            //SessionQuery query = SessionQueryManager.GetSessionQuery(HttpContext.Current.Session);
            if (query == null || query.KeyFamily == null)
            {
                throw new InvalidOperationException("query is not set");
            }

            IDimension component = Utils.GetComponentByName(query.KeyFamily, concept);

            ICodelistObject codes = query.GetCachedCodelist(component);
            query.ClearCodeListAfter(component);
            if (ids.Length == 0)
            {
                query.RemoveComponent(component);
                return _emptyJSON;
            }

               // try
            //{
                if (codes == null)
                {
                    //QueryBuilder queryBuilder = new QueryBuilder(query);
                    //INsiClient nsiClient = GetNSIClient(this.Context);
                    //codes = nsiClient.GetCodelist(query.Dataflow, query.KeyFamily, component, queryBuilder.CreateConstraintBean(component.ConceptRef.ChildReference.Id));
                    codes = this.GetCodeListCostraint(query.Dataflow, query.KeyFamily, component);
                    query.UpdateCodelistMap(codes, component);
                }

                var codesList = new List<ICode>();

                //time dimensione with region period
                if (component.TimeDimension && ids.Length == 1)
                {
                    {
                        int offsetTime = int.Parse(ids.First());
                        int lengthTime = codes.Items.Count;

                        if ((lengthTime - offsetTime) >= 0)
                        {
                            var _codes = codes.Items.Reverse().Take(offsetTime);// codMap[kf.TimeDimension.Id].Reverse().Take(offsetTime);
                            List<string> _criteriaTime = (from c in _codes select c.Id).ToList<string>();

                            codesList.Add((ICode)codes.GetCodeById(_criteriaTime.Last()));
                            codesList.Add((ICode)codes.GetCodeById(_criteriaTime.First()));
            /*
                            this.DataObj.Criteria[kf.TimeDimension.Id] = new List<string>();
                            this.DataObj.Criteria[kf.TimeDimension.Id].Add(_criteriaTime.Last());
                            this.DataObj.Criteria[kf.TimeDimension.Id].Add(_criteriaTime.First());
             * */
                        }
                        else
                        {
                            /*
                            this.DataObj.Criteria[kf.TimeDimension.Id] = new List<string>();
                            this.DataObj.Criteria[kf.TimeDimension.Id].Add(codemap[kf.TimeDimension.Id].First().Key);
                            this.DataObj.Criteria[kf.TimeDimension.Id].Add(codemap[kf.TimeDimension.Id].Last().Key);
                             */
                            var _codes = codes.Items.Reverse().Take(lengthTime);// codMap[kf.TimeDimension.Id].Reverse().Take(offsetTime);
                            List<string> _criteriaTime = (from c in _codes select c.Id).ToList<string>();

                            codesList.Add((ICode)codes.GetCodeById(_criteriaTime.First()));
                            codesList.Add((ICode)codes.GetCodeById(_criteriaTime.Last()));

                        }
                    }
                }
                else
                {
                    foreach (string id in ids)
                    {
                        codesList.Add((ICode)codes.GetCodeById(id));
                    }
                }

                    query.SaveComponent(component, codesList);
                return _emptyJSON;
              //  }
        }
Ejemplo n.º 32
0
        private string ModelJson(SessionQuery query)
        {
            var ser = new JavaScriptSerializer();
            string deserializedObject = string.Empty;

            var json = new StringBuilder();
            if (query == null)
            {
                json.Append("InvalidSession");
            }
            else if (query.DatasetModel == null)
            {
                json.Append("NoData");
            }
            else
            {

               var dict = query.DatasetModel.SliceKeyValues.Cast<DictionaryEntry>().ToDictionary(k => (string)k.Key, v => (string)v.Value).ToArray();
               var dictionary = dict.ToDictionary(x => x.Key, x => x.Value);
                var dataSetModel = new Dictionary<string, object>(StringComparer.Ordinal)
                    {
                         { "AllValidKeys", query.DatasetModel.AllValidKeys },
                         { "HorizontalKeys", query.DatasetModel.HorizontalKeys },
                         { "HorizontalVerticalKeyCount", query.DatasetModel.HorizontalVerticalKeyCount },
                         { "SliceKeyValidValues", query.DatasetModel.SliceKeyValidValues },
                         { "SliceKeyValues", query.DatasetModel.SliceKeyValues },
                         { "SliceKeys", query.DatasetModel.SliceKeys },
                         { "VerticalKeys", query.DatasetModel.VerticalKeys }
                    };

                var model = new Dictionary<string, object>(2)
                    {
                        { "model", dataSetModel }, { "codemap", query.GetComponentCodeDescriptionMap() }
                    };
                try
                {
                    //ser.Serialize(model, json);
                    deserializedObject = new JavaScriptSerializer().Serialize(model);
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }

            return deserializedObject.ToString();
        }
Ejemplo n.º 33
0
        public IList <Session> FindSessions(LuisResult result)
        {
            IList <Session> sessions = new List <Session>();
            SessionQuery    query    = new SessionQuery();
            IList <string>  topics   = new List <string>();

            foreach (EntityRecommendation entity in result.Entities)
            {
                if (entity.Type.Equals("Topic"))
                {
                    topics.Add(entity.Entity);
                }
                else if (entity.Type.Equals("Speaker"))
                {
                    query.Speaker = entity.Entity;
                }
                else if (entity.Type.Equals("Room"))
                {
                    query.Room = entity.Entity;
                }
                else if (entity.Type.Equals("Time"))
                {
                    var      localTimeZone    = TimeZoneInfo.Local.BaseUtcOffset;
                    var      mountainTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time").BaseUtcOffset;
                    var      timeZoneDiff     = localTimeZone.Subtract(mountainTimeZone);
                    DateTime eventDay         = new DateTime(2016, 06, 24, 0, 0, 0, DateTimeKind.Local);
                    int      tzDiff           = timeZoneDiff.Hours;
                    eventDay.AddHours(tzDiff);


                    DateTime timeResult = new DateTime();
                    //specific time
                    var validTime = DateTime.TryParse(entity.Entity, out timeResult);
                    if (validTime)
                    {
                        //Convert to Mountain time
                        timeResult = timeResult.AddHours(tzDiff);

                        //Convert to the Event Date
                        if (timeResult.Date.CompareTo(eventDay) != 0)
                        {
                            TimeSpan ts = eventDay - timeResult.Date;
                            // Difference in days
                            int differenceInDays = ts.Days;
                            timeResult = timeResult.AddDays(differenceInDays);
                        }

                        DateTimeOffset offset = new DateTimeOffset(timeResult.ToUniversalTime());
                        query.StartTime = offset.AddHours(-1);
                        query.EndTime   = offset.AddHours(1);
                    }
                }
            }
            query.Topics = topics;

            var svc = new AzureSearchService();

            sessions = svc.FindSessions(query);

            return(sessions);
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Initialize the session, get a cookie for language
        /// </summary>
        /// <param name="sender">
        /// The parameter is not used.
        /// </param>
        /// <param name="e">
        /// The parameter is not used.
        /// </param>
        protected void Session_Start(object sender, EventArgs e)
        {
            Logger.Info("starting session ...");
            try
            {
                RemoveJsTreeCookie(this.Context);
                CultureInfo culture = LocaleResolver.GetCookie(this.Context);
                Thread.CurrentThread.CurrentUICulture = culture;
                Logger.Info("starting session success");

                var query = new SessionQuery { CurrentCulture = culture };

                Utils.App_Data_Path = this.Context.Server.MapPath("~/App_Data/");
                string cacheFolder = this.GetCacheFolder();

                query.SetCacheFolder(cacheFolder);
                SessionQueryManager.SaveSessionQuery(this.Context.Session, query);
                Thread.CurrentThread.CurrentUICulture = culture;
                Logger.Info("starting session success");

            }
            catch (HttpException ex)
            {
                Logger.Error("starting session failled");
                Logger.Error(ex.Message, ex);
            }
            catch (SecurityException ex)
            {
                Logger.Error("starting session failled");
                Logger.Error(ex.Message, ex);
            }
            catch (IOException ex)
            {
                Logger.Error("starting session failled");
                Logger.Error(ex.Message, ex);
            }
        }
        public async Task <SessionResponseList> List(SessionQuery query = null)
        {
            var parameters = query.ToParameters();

            return(await Client.Get <SessionResponseList>($"{ApiKeys.Endpoint}sessions", ApiKeys.ApiToken, parameters));
        }
Ejemplo n.º 36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="QueryBuilder"/> class.
 /// </summary>
 /// <param name="sessionQuery">
 /// The session query.
 /// </param>
 public QueryBuilder(SessionQuery sessionQuery)
 {
     this._sessionQuery = sessionQuery;
 }
Ejemplo n.º 37
0
 /// <inheritdoc/>
 public Task <QueryResult <UserSession> > QuerySessionsAsync(SessionQuery filter = null, CancellationToken cancellationToken = default)
 {
     return(_serverSideTicketService.QuerySessionsAsync(filter, cancellationToken));
 }
Ejemplo n.º 38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="QueryBuilder"/> class.
 /// </summary>
 /// <param name="sessionQuery">
 /// The session query.
 /// </param>
 public QueryBuilder(SessionQuery sessionQuery)
 {
     this._sessionQuery = sessionQuery;
 }