예제 #1
0
        public void ProcessRequest(HttpContext context)
        {
            string language = null;
            string database = null;
            string table    = null;
            List <LinkManager.LinkItem> queryParams = new List <LinkManager.LinkItem>();

            // Fetch the route data
            var routeData = context.Items["RouteData"] as RouteData;

            if (routeData.Values[PxUrl.LANGUAGE_KEY] != null)
            {
                language = ValidationManager.GetValue(routeData.Values[PxUrl.LANGUAGE_KEY].ToString());
            }
            if (routeData.Values[PxUrl.DB_KEY] != null)
            {
                database = ValidationManager.GetValue(routeData.Values[PxUrl.DB_KEY].ToString());
            }
            if (routeData.Values[PxUrl.TABLE_KEY] != null)
            {
                table = ValidationManager.GetValue(routeData.Values[PxUrl.TABLE_KEY].ToString());
            }

            if ((!string.IsNullOrEmpty(language)) && (!string.IsNullOrEmpty(database)) && (!string.IsNullOrEmpty(table)))
            {
                SearchStatusType        status;
                List <SearchResultItem> result = SearchManager.Current.Search(database, language, table, out status, SearchConstants.SEARCH_FIELD_SEARCHID);

                if (result.Count == 1)
                {
                    DatabaseInfo dbi = PXWeb.Settings.Current.General.Databases.GetDatabase(database);

                    foreach (String key in HttpContext.Current.Request.QueryString.AllKeys)
                    {
                        //
                        queryParams.Add(new LinkManager.LinkItem(key, QuerystringManager.GetQuerystringParameter(key)));
                    }

                    string url = SearchHelper.GetSearchResultUrl(result[0], dbi, language, queryParams);
                    context.Response.Redirect(url);
                }
                else
                {
                    // If table is not found redirect to menu page
                    context.Response.Redirect(LinkManager.CreateLink("Menu.aspx"));
                }
                context.Response.Redirect(LinkManager.CreateLink("Default.aspx"));
            }
        }
예제 #2
0
        private string CreateUrlForScreenRendering(PCAxis.Query.SavedQuery sq, PXModel model)
        {
            if (sq.Sources.Count < 1)
            {
                throw new Exception("No source specified");                       //TODO fix message
            }
            var src = sq.Sources[0];

            if (string.Compare(src.SourceIdType, "path") != 0)
            {
                throw new Exception("Incompatible source type");                                                //TODO fix
            }
            string path      = src.Source;
            var    tableName = QueryHelper.GetTableName(src);

            path = path.Substring(0, path.Length - (tableName.Length + 1));

            if (string.Compare(sq.Sources[0].Type, "CNMM") == 0)
            {
                if (!path.StartsWith("START"))
                {
                    path = "START__" + path;
                }
            }

            path = path.Replace(@"/", PxPathHandler.NODE_DIVIDER);

            List <LinkManager.LinkItem> linkItems = new List <LinkManager.LinkItem>();

            linkItems.Add(new LinkManager.LinkItem(PxUrl.TABLE_KEY, tableName));
            linkItems.Add(new LinkManager.LinkItem(PxUrl.PATH_KEY, path.ToString()));
            linkItems.Add(new LinkManager.LinkItem(PxUrl.DB_KEY, src.DatabaseId));
            linkItems.Add(new LinkManager.LinkItem(PxUrl.LANGUAGE_KEY, src.Language));
            linkItems.Add(new LinkManager.LinkItem(PxUrl.LAYOUT_KEY, "tableViewLayout1"));

            var url = LinkManager.CreateLink("Table.aspx", false, linkItems.ToArray());

            PCAxis.Web.Core.Management.LocalizationManager.ChangeLanguage(src.Language);
            PCAxis.Web.Core.Management.PaxiomManager.PaxiomModel = model;

            return(url);
        }
예제 #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Redirect(LinkManager.CreateLink("~/Table.aspx"));

            PCAxis.Web.Core.Management.PaxiomManager.PaxiomModelBuilder = null;
            ((PxWeb)this.Master).FooterText = "Presentation";

            if (!IsPostBack)
            {
                if (PCAxis.Web.Core.Management.PaxiomManager.PaxiomModel != null)
                {
                    InitializeCommandBar();
                    InitializeTableInformation();
                    InitializeTable();
                    InitializeInformationAndFootnotes();
                }
            }
            CommandBar1.PxActionEvent  += new PCAxis.Web.Controls.PxActionEventHandler(HandlePxAction);
            Table1.PxTableCroppedEvent += new EventHandler(HandlePxTableCroppedEvent);

            lblTableCropped.Visible = false;
        }
예제 #4
0
        private void InitializeLogoLink()
        {
            IPxUrl url = RouteInstance.PxUrlProvider.Create(null);

            if (!string.IsNullOrEmpty(url.Database))
            {
                try
                {
                    IHomepageSettings homepage = PXWeb.Settings.Current.Database[url.Database].Homepages.GetHomepage(url.Language);

                    if (string.IsNullOrWhiteSpace(homepage.Url))
                    {
                        return;
                    }

                    if (homepage.IsExternal)
                    {
                        LogoLink.NavigateUrl = homepage.Url;
                    }
                    else
                    {
                        LogoLink.NavigateUrl = LinkManager.CreateLink(homepage.Url);
                    }
                }
                catch (Exception e)
                {
                    log.Debug("url.Database = " + url.Database + ", url.Language = " + url.Language);
                    log.Error("The error.", e);
                    throw e;
                }
            }
            else
            {
                LogoLink.NavigateUrl = LinkManager.CreateLink("Default.aspx");
            }
        }
예제 #5
0
파일: SearchHelper.cs 프로젝트: trygu/PxWeb
        /// <summary>
        /// Get URL for a search result item
        /// </summary>
        /// <param name="itm">SearchResultItem object</param>
        /// <param name="dbi">DatabaseInfo object</param>
        /// <param name="queryParams">Optional list with querystring parameters that shall be included in the url</param>
        /// <returns>URL to the selection page for the found table</returns>
        public static string GetSearchResultUrl(SearchResultItem itm, DatabaseInfo dbi, string language, List <LinkManager.LinkItem> queryParams = null)
        {
            StringBuilder path = new StringBuilder();

            char[] sep = { '/' };
            string url = "";
            List <LinkManager.LinkItem> linkItems = new List <LinkManager.LinkItem>();

            if (dbi.Type == PCAxis.Web.Core.Enums.DatabaseType.CNMM)
            {
                if (!itm.Path.StartsWith("START"))
                {
                    path.Append("START__");
                }
            }

            path.Append(itm.Path.TrimStart(sep).Replace(@"/", PxPathHandler.NODE_DIVIDER));

            linkItems.Add(new LinkManager.LinkItem(PxUrl.TABLE_KEY, itm.Table));
            linkItems.Add(new LinkManager.LinkItem(PxUrl.PATH_KEY, path.ToString()));
            linkItems.Add(new LinkManager.LinkItem(PxUrl.DB_KEY, dbi.Id));
            linkItems.Add(new LinkManager.LinkItem(PxUrl.LANGUAGE_KEY, language));

            // Add extra querystring parameters
            if (queryParams != null)
            {
                foreach (LinkManager.LinkItem item in queryParams)
                {
                    linkItems.Add(item);
                }
            }

            url = LinkManager.CreateLink("Selection.aspx", false, linkItems.ToArray());

            return(url);
        }
예제 #6
0
        protected void RenderToScreen(PCAxis.Query.SavedQuery query, PXModel model, string defaultLayout, string page, bool safe)
        {
            if (query.Sources.Count < 1)
            {
                throw new Exception("No source specified");                          //TODO fix message
            }
            var src = query.Sources[0];

            if (string.Compare(src.SourceIdType, "path") != 0)
            {
                throw new Exception("Incompatible source type");                                                //TODO fix
            }
            string layout;

            if (query.Output.Params.ContainsKey("layout"))
            {
                layout = query.Output.Params["layout"] ?? defaultLayout;
            }
            else
            {
                layout = defaultLayout;
            }


            string path      = src.Source;
            var    tableName = GetTableName(src);

            path = path.Substring(0, path.Length - (tableName.Length + 1));

            if (string.Compare(query.Sources[0].Type, "CNMM") == 0)
            {
                if (!path.StartsWith("START"))
                {
                    path = "START__" + path;
                }
            }

            path = path.Replace(@"/", PxPathHandler.NODE_DIVIDER);

            string url = null;

            if (RouteInstance.RouteExtender == null)
            {
                List <LinkManager.LinkItem> linkItems = new List <LinkManager.LinkItem>();

                linkItems.Add(new LinkManager.LinkItem(PxUrl.TABLE_KEY, tableName));
                linkItems.Add(new LinkManager.LinkItem(PxUrl.PATH_KEY, path.ToString()));
                linkItems.Add(new LinkManager.LinkItem(PxUrl.DB_KEY, src.DatabaseId));
                linkItems.Add(new LinkManager.LinkItem(PxUrl.LANGUAGE_KEY, model.Meta.CurrentLanguage));
                linkItems.Add(new LinkManager.LinkItem(PxUrl.LAYOUT_KEY, layout));

                url = LinkManager.CreateLink(page, false, linkItems.ToArray());
            }
            else
            {
                string tableId = RouteInstance.RouteExtender.GetTableIdByName(tableName);
                url = page == "Selection.aspx" ? RouteInstance.RouteExtender.GetSelectionRedirectUrl(tableId) : RouteInstance.RouteExtender.GetPresentationRedirectUrl(tableId, layout);
            }

            //info about loaded saved query in query string
            if (Settings.Current.Features.SavedQuery.ShowPeriodAndId)
            {
                var tvar = model.Meta.Variables.FirstOrDefault(v => v.IsTime);

                if (tvar != null)
                {
                    if (!string.IsNullOrEmpty(query.LoadedQueryName))
                    {
                        url += "?loadedQueryId=" + System.IO.Path.GetFileNameWithoutExtension(query.LoadedQueryName);
                    }

                    string timeType      = "item"; //default
                    string timeValue     = null;
                    var    timeQueryItem = query.Sources[0].Quieries.FirstOrDefault(x => x.Code == tvar.Code);

                    if (timeQueryItem != null)
                    {
                        if (timeQueryItem.Selection.Filter == "top")
                        {
                            timeType  = "top";
                            timeValue = timeQueryItem.Selection.Values[0];
                        }
                        else if (timeQueryItem.Selection.Filter == "from")
                        {
                            timeType  = "from";
                            timeValue = timeQueryItem.Selection.Values[0];
                        }

                        url += "&timeType=" + timeType;

                        if (timeValue != null)
                        {
                            url += "&timeValue=" + timeValue;
                        }
                    }
                }
            }

            PCAxis.Web.Core.Management.LocalizationManager.ChangeLanguage(model.Meta.CurrentLanguage);
            PCAxis.Web.Core.Management.PaxiomManager.PaxiomModel = model;

            PaxiomManager.OperationsTracker = new OperationsTracker(query.Workflow.ToArray());
            if (!safe)
            {
                PaxiomManager.OperationsTracker.IsUnsafe = true;
            }
            PaxiomManager.OperationsTracker.IsTimeDependent = query.TimeDependent;


            HttpContext.Current.Response.Redirect(url);
        }
예제 #7
0
        public void ProcessRequest(HttpContext context)
        {
            // Negotiate with the request limiter (if enabled)
            if (_requestLimiter != null)
            {
                if (!_requestLimiter.ClientLimitOK(context.Request))
                {
                    // Deny request
                    // see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
                    context.Response.AppendHeader("Retry-After", _requestLimiter.LimiterTimeSpan.ToString());
                    throw new HttpException(429, "429 - Too many requests in too short timeframe. Please try again later.");
                }
            }

            // Enable CORS and preflight requests for saved queries
            // Preflight requests should also be allowed in the API (SSDHandler).

            if (Settings.Current.Features.SavedQuery.EnableCORS)
            {
                // Enable CORS (Cross-Origin-Resource-Sharing)
                context.Response.AppendHeader("Access-Control-Allow-Origin", "*");

                // Handle Preflight requests
                if (context.Request.HttpMethod == "OPTIONS")
                {
                    context.Response.AppendHeader("Access-Control-Allow-Methods", "GET");
                    return;
                }
            }

            string queryName;
            var    routeData = context.Items["RouteData"] as RouteData;

            if (routeData.Values["QueryName"] != null)
            {
                queryName = ValidationManager.GetValue(routeData.Values["QueryName"].ToString());
            }
            else
            {
                //No query supplied goto error page.
                //TODO just to shut the compiler up
                queryName = "";
                //TODO redirect
                throw new Exception("No query supplied");
            }

            // ----- Handle changed output format -----
            _format = GetChangedOutputFormat(routeData);

            // ----- Handle changed language -----
            HandleChangedLanguage();

            //Load saved query
            PCAxis.Query.SavedQuery sq = null;
            PXModel model = null;
            bool    safe  = true;

            try
            {
                if (PCAxis.Query.SavedQueryManager.StorageType == PCAxis.Query.SavedQueryStorageType.File)
                {
                    string path = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/queries/");

                    if (!queryName.ToLower().EndsWith(".pxsq"))
                    {
                        queryName = queryName + ".pxsq";
                    }

                    string[] allfiles = Directory.GetFiles(path, queryName, SearchOption.AllDirectories);

                    if (allfiles.Length == 0)
                    {
                        throw new HttpException(404, "HTTP/1.1 404 Not Found ");
                    }

                    queryName = allfiles[0];
                }

                //Check if the database is active.
                //It should not be possible to run a saved query if the database is not active
                sq = PCAxis.Query.SavedQueryManager.Current.Load(queryName);
                IEnumerable <string> db;
                TableSource          src = sq.Sources[0];

                if (src.Type.ToLower() == "cnmm")
                {
                    db = PXWeb.Settings.Current.General.Databases.CnmmDatabases;
                }
                else
                {
                    db = PXWeb.Settings.Current.General.Databases.PxDatabases;
                }
                bool activeDatabase = false;
                foreach (var item in db)
                {
                    if (item.ToLower() == src.DatabaseId.ToLower())
                    {
                        activeDatabase = true;
                        break;
                    }
                }
                if (!activeDatabase)
                {
                    throw new SystemException();
                }


                //Validate that the user has the rights to access the table
                string tableName = QueryHelper.GetTableName(src);
                //if (!AuthorizationUtil.IsAuthorized(src.DatabaseId, null, src.Source))
                if (!AuthorizationUtil.IsAuthorized(src.DatabaseId, null, tableName)) //TODO: Should be dbid, menu and selection. Only works for SCB right now... (2018-11-14)
                {
                    List <LinkManager.LinkItem> linkItems = new List <LinkManager.LinkItem>();
                    linkItems.Add(new LinkManager.LinkItem()
                    {
                        Key = PxUrl.LANGUAGE_KEY, Value = src.Language
                    });
                    linkItems.Add(new LinkManager.LinkItem()
                    {
                        Key = PxUrl.DB_KEY, Value = src.DatabaseId
                    });
                    linkItems.Add(new LinkManager.LinkItem()
                    {
                        Key = "msg", Value = "UnauthorizedTable"
                    });

                    string url = LinkManager.CreateLink("~/Menu.aspx", linkItems.ToArray());
                    HttpContext.Current.Response.Redirect(url, false);
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                    return;
                }

                if (string.IsNullOrWhiteSpace(_format))
                {
                    //Output format is not changed - use output format in the saved query
                    _format = sq.Output.Type;
                }

                // "Pre-flight" request from MS Office application
                var userAgent = context.Request.Headers["User-Agent"];
                //if (userAgent.ToLower().Contains("ms-office") && sq.Output.Type == PxUrl.VIEW_TABLE_IDENTIFIER)
                if (userAgent != null && userAgent.ToLower().Contains("ms-office"))
                {
                    context.Response.Write("<html><body>ms office return</body></html>");
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                    //context.Response.End();
                    return;
                }

                //We need to store to be able to run workflow due to variables are referenced with name and not ids
                _originaleSavedQuerylanguage = sq.Sources[0].Language;

                // Check from saved query output type is on screen. If so createCopy shall be true, else false
                bool createCopy = CreateCopyOfCachedPaxiom(_format);

                // Create cache key
                string cacheKey = "";
                if (_language != null)
                {
                    cacheKey = string.Format("{0}_{1}", queryName, _language);
                }
                else
                {
                    cacheKey = string.Format("{0}_{1}", queryName, _originaleSavedQuerylanguage);
                }

                // Handle redirects to the selection page in a special way. The model object will only contain metadata and no data
                if (_format.Equals(PxUrl.PAGE_SELECT))
                {
                    cacheKey = string.Format("{0}_{1}", cacheKey, PxUrl.PAGE_SELECT);
                }

                // Try to get model from cache
                model = PXWeb.Management.SavedQueryPaxiomCache.Current.Fetch(cacheKey, createCopy);
                PaxiomManager.QueryModel = PXWeb.Management.SavedQueryPaxiomCache.Current.FetchQueryModel(cacheKey, createCopy);

                if (model == null || PaxiomManager.QueryModel == null)
                {
                    DateTime timeStamp = DateTime.Now;
                    // Model not found in cache - load it manually

                    model = LoadData(sq);

                    //Check if we need to change langauge to be able to run workflow due to variables are referenced with name and not ids
                    if (!string.IsNullOrEmpty(_language) && _language != _originaleSavedQuerylanguage)
                    {
                        model.Meta.SetLanguage(_originaleSavedQuerylanguage);
                    }

                    // No need to run workflow if we are redirecting to the selection page
                    if (!_format.Equals(PxUrl.PAGE_SELECT))
                    {
                        model = QueryHelper.RunWorkflow(sq, model);
                    }

                    //Set back to requested langauge after workflow operations
                    if (!string.IsNullOrEmpty(_language) && _language != _originaleSavedQuerylanguage)
                    {
                        if (model.Meta.HasLanguage(_language))
                        {
                            model.Meta.SetLanguage(_language);
                        }
                    }

                    // Store model in cache
                    PXWeb.Management.SavedQueryPaxiomCache.Current.Store(cacheKey, model, timeStamp);
                    PXWeb.Management.SavedQueryPaxiomCache.Current.StoreQueryModel(cacheKey, PaxiomManager.QueryModel, timeStamp);
                }

                if (!sq.Safe)
                {
                    safe = !CheckForUnsafeOperations(sq.Workflow);
                }
            }
            catch (Exception ex)
            {
                if ((PCAxis.Query.SavedQueryManager.StorageType == PCAxis.Query.SavedQueryStorageType.File && System.IO.File.Exists(queryName)) ||
                    (PCAxis.Query.SavedQueryManager.StorageType == PCAxis.Query.SavedQueryStorageType.Database))
                {
                    PCAxis.Query.SavedQueryManager.Current.MarkAsFailed(queryName);
                }

                throw new HttpException(404, "HTTP/1.1 404 Not Found");
                //throw ex;
            }

            sq.LoadedQueryName = queryName;
            PCAxis.Query.SavedQueryManager.Current.MarkAsRunned(queryName);

            // Tell the selection page that it sholud clear the PxModel
            if (_format.Equals(PxUrl.PAGE_SELECT))
            {
                HttpContext.Current.Session.Add("SelectionClearPxModel", true);
            }

            ViewSerializerCreator.GetSerializer(_format).Render(_format, sq, model, safe);
        }
예제 #8
0
        /// <summary>
        /// Get the Paxiom model built for selection (only metadata)
        /// </summary>
        /// <param name="db">Database id</param>
        /// <param name="path">Path to PX-file or datatable</param>
        /// <param name="table">Table name (PX-file or CNMM datatable)</param>
        /// <param name="prefLang">Preferred language</param>
        /// <returns>The Paxiom model built for selection</returns>
        public static PCAxis.Paxiom.PXModel GetPaxiomForSelection(string db, string path, string table, string prefLang, bool clearModel)
        {
            //Verify that user is authorized to view the table
            if (!AuthorizationUtil.IsAuthorized(db, path, table)) //TODO: Should be dbid, menu and selection. Only works for SCB right now... (2018-11-14)
            {
                HttpContext.Current.Response.Redirect(LinkManager.CreateLink("~/Menu.aspx", new LinkManager.LinkItem()
                {
                    Key = "msg", Value = "UnauthorizedTable"
                }));
            }

            string tablePath;

            //path = ItemSelectionHelper.CreateFromString(path).Selection;

            PCAxis.Paxiom.IPXModelBuilder builder;
            DatabaseInfo dbi = PXWeb.Settings.Current.General.Databases.GetDatabase(db);

            PCAxis.Web.Controls.PathHandler pHandler;

            pHandler  = PCAxis.Web.Controls.PathHandlerFactory.Create(dbi.Type);
            tablePath = pHandler.CombineTable(db, path, table);

            if (PCAxis.Web.Core.Management.PaxiomManager.PaxiomModelBuilder == null)
            {
                builder = CreatePaxiomBuilder(db, tablePath);
                PCAxis.Web.Core.Management.PaxiomManager.PaxiomModelBuilder = builder;
            }
            else
            {
                string newpath;

                if (dbi.Type == PCAxis.Web.Core.Enums.DatabaseType.PX)
                {
                    // PX
                    newpath = System.IO.Path.Combine(
                        System.Web.HttpContext.Current.Server.MapPath(Settings.Current.General.Paths.PxDatabasesPath),
                        tablePath);
                }
                else
                {
                    // CNMM
                    newpath = tablePath;
                }

                if (PCAxis.Web.Core.Management.PaxiomManager.PaxiomModelBuilder.Path.Equals(newpath) && (clearModel == false))
                {
                    // Existing builder is built against the wanted table
                    builder = PCAxis.Web.Core.Management.PaxiomManager.PaxiomModelBuilder;
                }
                else
                {
                    // Existing builder is built against a differnt builder - Create new builder!!!
                    builder = CreatePaxiomBuilder(db, tablePath);
                    PCAxis.Web.Core.Management.PaxiomManager.PaxiomModelBuilder = builder;
                }
            }

            if (builder.BuilderState < PCAxis.Paxiom.ModelBuilderStateType.BuildForSelection)
            {
                string lang;

                if (!string.IsNullOrEmpty(prefLang))
                {
                    lang = prefLang;
                }
                else if (!string.IsNullOrEmpty(PXWeb.Settings.Current.General.Language.DefaultLanguage))
                {
                    lang = PXWeb.Settings.Current.General.Language.DefaultLanguage;
                }
                else
                {
                    lang = "en";
                }

                if (dbi.Type == PCAxis.Web.Core.Enums.DatabaseType.CNMM)
                {
                    // Check if the language exist in the CNMM database, if not use the default language of the database
                    string dbid = PxContext.GetDbId(tablePath);
                    lang = PxContext.GetCnmmDbLanguage(dbid, lang);
                }

                builder.SetPreferredLanguage(lang);
                builder.BuildForSelection();
            }

            return(builder.Model);
        }
예제 #9
0
        /// <summary>
        /// Gets the menu object for the specified database
        /// </summary>
        /// <remarks></remarks>
        /// <returns>A menu object</returns>
        public static PxMenuBase GetMenu(string db, string nodeId, string lang)
        {
            //Verifies that the user is authorized to view the database
            var dbcfg = Settings.Current.Database[db];

            if (dbcfg != null)
            {
                if (dbcfg.Protection.IsProtected)
                {
                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Check if authenticated");
                    }
                    if (!HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        //TODO Auth
                        //PXWeb.Security.IAuthentication auth = GetAuthentication(dbcfg.Protection.AuthenticationMethod);
                        //auth.Autenticate();
                    }
                    else
                    {
                        if (log.IsDebugEnabled)
                        {
                            log.Debug("Loged on user: "******"~/Default.aspx", new LinkManager.LinkItem()
                        {
                            Key = "msg", Value = "UnauthorizedDatabase"
                        }));
                    }
                }
            }

            DatabaseInfo dbi = PXWeb.Settings.Current.General.Databases.GetDatabase(db);

            if (dbi == null)
            {
                return(null);
            }

            try
            {
                if (dbi.Type == PCAxis.Web.Core.Enums.DatabaseType.PX)
                {
                    return(GetPxMenu(db, nodeId, lang));
                }
                else if (dbi.Type == PCAxis.Web.Core.Enums.DatabaseType.CNMM)
                {
                    return(GetCnmmMenu(db, nodeId, lang));
                }
                return(null);
            }
            catch (Exception e)
            {
                log.Error("Something went wrong when trying to getMenu", e);
                return(null);
            }
        }