Esempio n. 1
0
        public virtual SysParamModel GetById(object id)
        {
            if (IsExists(id))
            {
                SysParam      entity = m_Rep.GetById(id);
                SysParamModel model  = new SysParamModel();
                model.Id           = entity.Id;
                model.TypeCode     = entity.TypeCode;
                model.TypeName     = entity.TypeName;
                model.ParamCode    = entity.ParamCode;
                model.ParamName    = entity.ParamName;
                model.CreatePerson = entity.CreatePerson;
                model.CreateTime   = entity.CreateTime;
                model.ModifyPerson = entity.ModifyPerson;
                model.ModifyTime   = entity.ModifyTime;
                model.Sort         = entity.Sort;
                model.Enable       = entity.Enable;

                return(model);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 2
0
 /// <summary>
 /// Checks the given users access to the permissions specified in the given
 /// access attribute.
 /// </summary>
 /// <param name="user">The user</param>
 /// <param name="access">The attribute</param>
 private static void CheckAccess(IPrincipal user, Piranha.AccessAttribute access)
 {
     if (access != null)
     {
         if (!user.HasAccess(access.Function))
         {
             if (!String.IsNullOrEmpty(access.RedirectUrl))
             {
                 HttpContext.Current.Response.Redirect(access.RedirectUrl);
             }
             else
             {
                 SysParam param = SysParam.GetByName("LOGIN_PAGE");
                 if (param != null)
                 {
                     HttpContext.Current.Response.Redirect(param.Value);
                 }
                 else
                 {
                     HttpContext.Current.Response.Redirect("~/");
                 }
             }
         }
     }
 }
Esempio n. 3
0
        /// <summary>
        /// Check if the current user has access to the action before continuing.
        /// </summary>
        /// <param name="context">The current context</param>
        protected override void OnActionExecuting(ActionExecutingContext context)
        {
            // Get the current permalink
            CurrentPermalink = Request["permalink"];

            try {
                if ((this is SinglePageController && User.HasAccess("ADMIN_PAGE")) || (this is SinglePageController && User.HasAccess("ADMIN_POST")))
                {
                    IsDraft = !String.IsNullOrEmpty(Request["draft"]) ? Convert.ToBoolean(Request["draft"]) : false;
                }
                else
                {
                    IsDraft = false;
                }
            } catch {}

            // Authorize and execute
            if (Authorize(context.ActionDescriptor.ActionName))
            {
                base.OnActionExecuting(context);
            }
            else
            {
                var param = SysParam.GetByName("LOGIN_PAGE");
                if (param != null)
                {
                    context.Result = Redirect(param.Value);
                }
                else
                {
                    context.Result = Redirect("~/");
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Handles the URL Rewriting for the application
        /// </summary>
        /// <param name="context">Http context</param>
        public static void BeginRequest(HttpContext context)
        {
            string path = context.Request.Path.Substring(context.Request.ApplicationPath.Length > 1 ?
                                                         context.Request.ApplicationPath.Length : 0);

            string[] args = path.Split(new char[] { '/' }).Subset(1);

            if (args.Length > 0)
            {
                // Ensure database
                if (args[0] == "" && SysParam.GetByName("SITE_VERSION") == null)
                {
                    context.Response.Redirect("~/manager");
                }

                // Find the correct request handler
                foreach (RequestHandlerRegistration hr in Handlers.Values)
                {
                    if (hr.UrlPrefix.ToLower() == args[0].ToLower())
                    {
                        // Execute the handler
                        hr.Handler.HandleRequest(context, args.Subset(1));
                        break;
                    }
                }
            }
        }
Esempio n. 5
0
        static void Main()
        {
            try
            {
                //设置应用的异常处理方式:异常捕获
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                //设置出现未处理异常的委托
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);


                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                frm = new Form1();
                Application.Run(frm);
            }catch (Exception ex)
            {
                string str = GetExceptionMsg(ex, string.Empty);
                MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                FileOperation.WriteLog(DateTime.Now.ToString() + "\r\n" + str);
                if (null != frm && null != frm.MyParamSet)
                {
                    SysParam.SaveAllInfor();
                }
            }
        }
Esempio n. 6
0
 public static void CommonInit()
 {
     ClearOldData();
     SysParam.LoadParameter();
     timer.ThreadTimerTickEvent += timerTime_Tick;
     OpenCDIVision();
 }
Esempio n. 7
0
 protected void Imagebutton1_Click(object sender, ImageClickEventArgs e)
 {
     if (string.IsNullOrEmpty(this.hidCValue.Value))
     {
         this.PrintfError("没有选择要修改的纪录!");
         this.txtExp.Text     = "";
         this.txtValue.Text   = "";
         this.hidCValue.Value = "";
         return;
     }
     if (string.IsNullOrEmpty(this.txtValue.Text) || string.IsNullOrEmpty(this.txtExp.Text))
     {
         this.PrintfError("参数值和参数名不能为空!");
         return;
     }
     try
     {
         SysParam parm = new SysParam(this.hidCValue.Value, this.txtValue.Text, this.txtExp.Text);
         parm.Update();
         this.txtExp.Text     = "";
         this.txtValue.Text   = "";
         this.hidCValue.Value = "";
         BindSysParam();
     }
     catch
     {
         this.PrintfError("数据访问错误,请重试!");
         return;
     }
 }
Esempio n. 8
0
        /// <summary>
        /// 保存数据
        /// </summary>
        public virtual void SaveImportData(IEnumerable <SysParamModel> list)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var model in list)
                    {
                        SysParam entity = new SysParam();
                        entity.Id           = 0;
                        entity.TypeCode     = model.TypeCode;
                        entity.TypeName     = model.TypeName;
                        entity.ParamCode    = model.ParamCode;
                        entity.ParamName    = model.ParamName;
                        entity.CreatePerson = model.CreatePerson;
                        entity.CreateTime   = ResultHelper.NowTime;
                        entity.ModifyPerson = model.ModifyPerson;
                        entity.ModifyTime   = model.ModifyTime;
                        entity.Sort         = model.Sort;
                        entity.Enable       = model.Enable;

                        db.SysParam.Add(entity);
                    }
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Gets the specified access model.
        /// </summary>
        /// <param name="id">The access id</param>
        /// <returns>The model</returns>
        public static ParamEditModel GetById(Guid id)
        {
            ParamEditModel m = new ParamEditModel();

            m.Param = SysParam.GetSingle(id);

            return(m);
        }
Esempio n. 10
0
        public SysParam GetParamValue(string paramname)
        {
            SqlConnectionStringBuilder builder = ConnectionStringBuilder.GetConnectionStringBuilder();

            try
            {
                //sql connection object
                using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                {
                    //retrieve the SQL Server instance version
                    string query = @"SELECT e.PARAMID, e.PARAMNAME, e.PARAMVALUE
                    FROM INTTASPENSYSPARAM e
                    WHERE e.PARAMNAME = @p_paramname ;";
                    //define the SqlCommand object
                    SqlCommand cmd = new SqlCommand(query, connection);

                    var pname = new SqlParameter("p_paramname", SqlDbType.Char);
                    pname.Value = paramname;
                    cmd.Parameters.Add(pname);

                    //open connection
                    connection.Open();

                    //execute the SQLCommand
                    SqlDataReader dr = cmd.ExecuteReader();

                    //check if there are records
                    var result = new List <SysParam>();
                    if (dr.HasRows)
                    {
                        while (dr.Read())
                        {
                            var data = new SysParam();
                            data.PARAMNAME  = SafeGetString(dr, 1);
                            data.PARAMVALUE = SafeGetString(dr, 2);

                            result.Add(data);
                        }
                    }

                    //close data reader
                    dr.Close();

                    //close connection
                    connection.Close();
                    if (result.Count > 0)
                    {
                        return(result.FirstOrDefault());
                    }
                }
            }
            catch (Exception ex)
            {
                //display error message
                Console.WriteLine("Exception: " + ex.Message);
            }
            return(null);
        }
Esempio n. 11
0
        /// <summary>
        /// Triggered before an action is executed on the controller
        /// </summary>
        /// <param name="filterContext">The context</param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string permalink = Request["permalink"];
            bool   draft     = false;
            bool   cached    = false;

            // Check if we want to see the draft
            if (User.HasAccess("ADMIN_PAGE"))
            {
                if (!String.IsNullOrEmpty(Request["draft"]))
                {
                    try {
                        draft = Convert.ToBoolean(Request["draft"]);
                    } catch {}
                }
            }

            // Load the current page
            if (!String.IsNullOrEmpty(permalink))
            {
                page = Models.Page.GetByPermalink(permalink, draft);
            }
            else
            {
                page = Models.Page.GetStartpage(draft);
            }

            // Check permissions
            if (page.GroupId != Guid.Empty)
            {
                if (!User.IsMember(page.GroupId))
                {
                    SysParam param = SysParam.GetByName("LOGIN_PAGE");
                    if (param != null)
                    {
                        Response.Redirect(param.Value);
                    }
                    else
                    {
                        Response.Redirect("~/");
                    }
                }
                Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
            }
            else
            {
                // Only cache public pages
                DateTime mod = GetLastModified();
                cached = false;                 // ClientCache.HandleClientCache(HttpContext.Current, page.Id.ToString(), mod) ;
            }
            // Load the model if the page wasn't cached
            if (!cached)
            {
                model = PageModel.Get(page);
            }
            base.OnActionExecuting(filterContext);
        }
Esempio n. 12
0
    private void BindSysParam()
    {
        DataSet ds = SysParam.GetList("");

        if (ds != null)
        {
            this.grdInfo.DataSource = ds;
            this.grdInfo.DataBind();
        }
    }
Esempio n. 13
0
        private void SearchBtn_Click(object sender, EventArgs e)
        {
            string StrSearchTB = SearchTB.Text;

            if ("".Equals(StrSearchTB) || null == StrSearchTB)
            {
                MessageBox.Show("搜索时搜索框中的内容不能为空!");
                return;
            }
            SysParam.SearchListViewStr(PersonAlarmListView, StrSearchTB);
        }
Esempio n. 14
0
        /// <summary>
        /// Gets all available data.
        /// </summary>
        /// <returns>The model</returns>
        public static ParamListModel Get()
        {
            ParamListModel m = new ParamListModel();

            m.Params = SysParam.Get(new Params()
            {
                OrderBy = "sysparam_name"
            });

            return(m);
        }
Esempio n. 15
0
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());

            MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            FileOperation.WriteLog(DateTime.Now.ToString() + "\r\n" + str);
            //查看若发现异常是在设置软体上出现的,此时是需要我们做数据保存
            if (null != frm.MyParamSet)
            {
                SysParam.SaveAllInfor();
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Check if the current user has access to the action before continuing.
        /// </summary>
        /// <param name="context">The current context</param>
        protected override void OnActionExecuting(ActionExecutingContext context)
        {
            // Perform base class stuff
            base.OnActionExecuting(context);

            // Check permissions & client cache
            if (string.IsNullOrEmpty(CurrentPermalink))
            {
                return;
            }
            var page = Page.GetByPermalink(CurrentPermalink, IsDraft);

            if (page != null)
            {
                if (page.GroupId != Guid.Empty)
                {
                    if (!User.IsMember(page.GroupId))
                    {
                        SysParam param = SysParam.GetByName("LOGIN_PAGE");
                        if (param != null)
                        {
                            context.Result = Redirect(param.Value);
                        }
                        else
                        {
                            context.Result = Redirect("~/");
                        }
                    }
                    Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
                }
                else if (!IsDraft)
                {
                    // Only cache public non drafts
                    DateTime mod = page.LastModified;
                    Web.ClientCache.HandleClientCache(HttpContext.ApplicationInstance.Context,
                                                      WebPages.WebPiranha.GetCulturePrefix() + page.Id.ToString(), mod);
                }
                // Check for disabled groups
                if (page.DisabledGroups.Contains(User.GetProfile().GroupId))
                {
                    SysParam param = SysParam.GetByName("LOGIN_PAGE");
                    if (param != null)
                    {
                        context.Result = Redirect(param.Value);
                    }
                    else
                    {
                        context.Result = Redirect("~/");
                    }
                }
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Handles the current request.
        /// </summary>
        /// <param name="context">The current context</param>
        /// <param name="args">Optional url arguments passed to the handler</param>
        public virtual void HandleRequest(System.Web.HttpContext context, params string[] args)
        {
            var top   = Convert.ToInt32(SysParam.GetByName("RSS_NUM_POSTS").Value);
            var posts = Post.Get("post_draft = 0 AND post_rss = 1 AND post_template_id IN (SELECT posttemplate_id FROM posttemplate WHERE posttemplate_rss = 1)", new Params()
            {
                OrderBy = "post_published DESC", Top = top
            });

            Web.RssHelper.Generate(context,
                                   SysParam.GetByName("SITE_TITLE").Value,
                                   SysParam.GetByName("SITE_DESCRIPTION").Value,
                                   posts);
        }
Esempio n. 18
0
        /// <summary>
        /// Handles the current request.
        /// </summary>
        /// <param name="context">The current context</param>
        /// <param name="args">Optional url arguments passed to the handler</param>
        public virtual void HandleRequest(System.Web.HttpContext context, params string[] args)
        {
            var top   = Convert.ToInt32(SysParam.GetByName("RSS_NUM_POSTS").Value);
            var posts = Post.Get("post_draft = 0 AND post_rss = 1 AND post_template_id IN (SELECT posttemplate_id FROM posttemplate WHERE posttemplate_rss = 1)", new Params()
            {
                OrderBy = "post_published DESC", Top = top
            });

            Web.RssHelper.Generate(context,
                                   WebPages.WebPiranha.CurrentSite.MetaTitle,
                                   WebPages.WebPiranha.CurrentSite.MetaDescription,
                                   posts);
        }
Esempio n. 19
0
        /// <summary>
        /// Checks request headers against the given etag and last modification data and
        /// sets the correct response headers. Returns whether the file is client cached
        /// or should be loaded/rendered.
        /// </summary>
        /// <param name="context">The current context</param>
        /// <param name="id">The entity id</param>
        /// <param name="modified">Last nodification</param>
        /// <param name="noexpire">Whether to use persistent cookies or not</param>
        /// <param name="minutes">Optional minutes to cache the resource for</param>
        /// <returns>If the file is cached</returns>
        public static bool HandleClientCache(HttpContext context, string id, DateTime modified, bool noexpire = false, int?minutes = null)
        {
#if !DEBUG
            // Get expire & maxage
            int expires = 30, maxage = 30;
            try {
                expires = !minutes.HasValue ? Convert.ToInt32(SysParam.GetByName("CACHE_PUBLIC_EXPIRES").Value) : minutes.Value;
                maxage  = !minutes.HasValue ? Convert.ToInt32(SysParam.GetByName("CACHE_PUBLIC_MAXAGE").Value) : minutes.Value;
            } catch {}

            // Handle cache
            if (!context.Request.IsLocal && expires > 0)
            {
                try {
                    if (!minutes.HasValue)
                    {
                        modified = modified > SiteLastModified ? modified : SiteLastModified;
                    }
                } catch {}
                string etag = GenerateETag(id, modified);

                context.Response.Cache.SetETag(etag);
                context.Response.Cache.SetLastModified(modified <= DateTime.Now ? modified : DateTime.Now);
                context.Response.Cache.SetCacheability(System.Web.HttpCacheability.ServerAndPrivate);
                if (!noexpire)
                {
                    context.Response.Cache.SetExpires(DateTime.Now.AddMinutes(expires));
                    context.Response.Cache.SetMaxAge(new TimeSpan(0, maxage, 0));
                }
                else
                {
                    context.Response.Cache.SetExpires(DateTime.Now);
                }
                if (IsCached(context, modified, etag))
                {
                    context.Response.StatusCode      = 304;
                    context.Response.SuppressContent = true;
                    context.Response.EndClean();
                    return(true);
                }
            }
            else
            {
                context.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
            }
#else
            context.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
#endif
            return(false);
        }
Esempio n. 20
0
        /// <summary>
        /// Registers all of the hostnames configured in the database.
        /// </summary>
        public static void RegisterDefaultHostNames()
        {
            // Make sure we don't try to register the host names before
            // the database has been installed.
            if (SysParam.GetByName("SITE_VERSION") != null)
            {
                if (hostNames == null)
                {
                    hostNames = new Dictionary <string, Entities.SiteTree>();
                }

                HostNames.Clear();

                // We need to check version so we don't try to access the column sitetree_hostnames
                // before it's been created in the database.
                if (Data.Database.InstalledVersion > 26)
                {
                    using (var db = new DataContext()) {
                        var sites = db.SiteTrees.ToList();

                        foreach (var site in sites)
                        {
                            if (HttpContext.Current != null)
                            {
                                Page.InvalidateStartpage(site.Id);
                            }

                            if (!String.IsNullOrEmpty(site.HostNames))
                            {
                                var hostnames = site.HostNames.Split(new char[] { ',' });

                                foreach (var host in hostnames)
                                {
                                    if (HostNames.ContainsKey(host))
                                    {
                                        throw new Exception("Duplicates of the hostname [" + host + "] was found configured");
                                    }
                                    HostNames.Add(host.ToLower(), site);
                                }
                            }
                            if (site.Id == Config.DefaultSiteTreeId)
                            {
                                DefaultSite = site;
                            }
                        }
                    }
                }
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Outputs the rss feed on the given http context
        /// </summary>
        /// <param name="context">The current context</param>
        /// <param name="title">The feed title</param>
        /// <param name="description">The feed description</param>
        /// <param name="posts">The posts to output</param>
        public static void Generate(HttpContext context, string title, string description, IList <Post> posts)
        {
            // Read configuration
            var exerpt = SysParam.GetByName("RSS_USE_EXCERPT").Value == "1";

            // Create the feed
            context.Response.Clear();
            context.Response.ContentType     = "text/xml";
            context.Response.ContentEncoding = Encoding.UTF8;
            var feed = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8);

            // Open the feed
            feed.WriteStartDocument();
            feed.WriteStartElement("rss");
            feed.WriteAttributeString("version", "2.0");
            feed.WriteStartElement("channel");
            feed.WriteElementString("title", title);
            feed.WriteElementString("link", WebPages.WebPiranha.GetSiteUrl());
            feed.WriteElementString("description", description);
            feed.WriteElementString("generator", Generator());

            foreach (var post in posts)
            {
                feed.WriteStartElement("item");
                feed.WriteElementString("title", post.Title);
                if (exerpt)
                {
                    feed.WriteElementString("description", post.Excerpt);
                }
                else
                {
                    feed.WriteElementString("description", post.Body.ToString());
                }
                feed.WriteElementString("link", PublicLink(context.Request, post.Permalink));
                feed.WriteElementString("pubDate", post.Published.ToLongDateString());
                feed.WriteEndElement();
            }

            // Close the feed
            feed.WriteEndElement();
            feed.WriteEndElement();
            feed.WriteEndDocument();
            feed.Flush();
            feed.Close();
            context.Response.EndClean();
        }
Esempio n. 22
0
        public ActionResult ExecuteUpdate()
        {
            if (User.Identity.IsAuthenticated && User.HasAccess("ADMIN"))
            {
                // Execute all incremental updates in a transaction.
                using (IDbTransaction tx = Database.OpenTransaction()) {
                    for (int n = Data.Database.InstalledVersion + 1; n <= Data.Database.CurrentVersion; n++)
                    {
                        // Read embedded create script
                        Stream str = Assembly.GetExecutingAssembly().GetManifestResourceStream(Database.ScriptRoot + ".Updates." +
                                                                                               n.ToString() + ".sql");
                        String sql = new StreamReader(str).ReadToEnd();
                        str.Close();

                        // Split statements and execute
                        string[] stmts = sql.Split(new char[] { ';' });
                        foreach (string stmt in stmts)
                        {
                            if (!String.IsNullOrEmpty(stmt.Trim()))
                            {
                                SysUser.Execute(stmt.Trim(), tx);
                            }
                        }

                        // Check for update class
                        var utype = Type.GetType("Piranha.Data.Updates.Update" + n.ToString());
                        if (utype != null)
                        {
                            IUpdate update = (IUpdate)Activator.CreateInstance(utype);
                            update.Execute(tx);
                        }
                    }
                    // Now lets update the database version.
                    SysUser.Execute("UPDATE sysparam SET sysparam_value = @0 WHERE sysparam_name = 'SITE_VERSION'",
                                    tx, Data.Database.CurrentVersion);
                    SysParam.InvalidateParam("SITE_VERSION");
                    tx.Commit();
                }
                return(RedirectToAction("index", "account"));
            }
            else
            {
                return(RedirectToAction("update"));
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Initializes the web page.
        /// </summary>
        protected override void InitializePage()
        {
            base.InitializePage();

            ExecutePage();

            if (IsPost)
            {
                if (Request.Form.AllKeys.Contains("piranha_form_action"))
                {
                    MethodInfo m = GetType().GetMethod(Request.Form["piranha_form_action"],
                                                       BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase);
                    if (m != null)
                    {
                        // Check for access rules
                        var access = m.GetCustomAttribute <AccessAttribute>(true);
                        if (access != null)
                        {
                            if (!User.HasAccess(access.Function))
                            {
                                SysParam param = SysParam.GetByName("LOGIN_PAGE");
                                if (param != null)
                                {
                                    Response.Redirect(param.Value);
                                }
                                else
                                {
                                    Response.Redirect("~/");
                                }
                            }
                        }
                        // Bind model
                        List <object> args = new List <object>();
                        foreach (var param in m.GetParameters())
                        {
                            args.Add(ModelBinder.BindModel(param.ParameterType, param.Name));
                        }
                        m.Invoke(this, args.ToArray());
                    }
                }
            }
        }
Esempio n. 24
0
        public virtual bool Create(ref ValidationErrors errors, SysParamModel model)
        {
            try
            {
                SysParam entity = m_Rep.GetById(model.Id);
                if (entity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return(false);
                }
                entity              = new SysParam();
                entity.Id           = model.Id;
                entity.TypeCode     = model.TypeCode;
                entity.TypeName     = model.TypeName;
                entity.ParamCode    = model.ParamCode;
                entity.ParamName    = model.ParamName;
                entity.CreatePerson = model.CreatePerson;
                entity.CreateTime   = model.CreateTime;
                entity.ModifyPerson = model.ModifyPerson;
                entity.ModifyTime   = model.ModifyTime;
                entity.Sort         = model.Sort;
                entity.Enable       = model.Enable;


                if (m_Rep.Create(entity))
                {
                    return(true);
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return(false);
            }
        }
Esempio n. 25
0
        public virtual bool Edit(ref ValidationErrors errors, SysParamModel model)
        {
            try
            {
                SysParam entity = m_Rep.GetById(model.Id);
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return(false);
                }
                entity.Id           = model.Id;
                entity.TypeCode     = model.TypeCode;
                entity.TypeName     = model.TypeName;
                entity.ParamCode    = model.ParamCode;
                entity.ParamName    = model.ParamName;
                entity.CreatePerson = model.CreatePerson;
                entity.CreateTime   = model.CreateTime;
                entity.ModifyPerson = model.ModifyPerson;
                entity.ModifyTime   = model.ModifyTime;
                entity.Sort         = model.Sort;
                entity.Enable       = model.Enable;



                if (m_Rep.Edit(entity))
                {
                    return(true);
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return(false);
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Check if the current user has access to the action before continuing.
        /// </summary>
        /// <param name="context">The current context</param>
        protected override void OnActionExecuting(ActionExecutingContext context)
        {
            // Get the current permalink
            CurrentPermalink = Request["permalink"];

            // Authorize and execute
            if (Authorize(context.ActionDescriptor.ActionName))
            {
                base.OnActionExecuting(context);
            }
            else
            {
                var param = SysParam.GetByName("LOGIN_PAGE");
                if (param != null)
                {
                    context.Result = Redirect(param.Value);
                }
                else
                {
                    context.Result = Redirect("~/");
                }
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Generates the tags appropriate for the html head.
        /// </summary>
        /// <returns>The head information</returns>
        public IHtmlString Head()
        {
            StringBuilder str = new StringBuilder();

            str.AppendLine("<meta name=\"generator\" content=\"Piranha\" />");
            str.AppendLine("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\" />");

            /**
             * Basic meta tags
             */
            if (CurrentPage != null || CurrentPost != null)
            {
                var keywords    = CurrentPage != null ? CurrentPage.Keywords : CurrentPost.Keywords;
                var description = CurrentPage != null ? CurrentPage.Description :
                                  (!String.IsNullOrEmpty(CurrentPost.Description) ? CurrentPost.Description : CurrentPost.Excerpt);

                if (!String.IsNullOrEmpty(description))
                {
                    str.AppendLine("<meta name=\"description\" content=\"" + description + "\" />");
                }
                if (!String.IsNullOrEmpty(keywords))
                {
                    str.AppendLine("<meta name=\"keywords\" content=\"" + keywords + "\" />");
                }
            }

            /**
             * Open graph meta tags
             */
            str.AppendLine("<meta property=\"og:site_name\" content=\"" +
                           SysParam.GetByName("SITE_TITLE").Value + "\" />");
            str.AppendLine("<meta property=\"og:url\" content=\"" +
                           "http://" + Context.Request.Url.DnsSafeHost + Context.Request.RawUrl + "\" />");

            if (CurrentPage != null && CurrentPage.IsStartpage)
            {
                str.AppendLine("<meta property=\"og:type\" content=\"website\" />");
                str.AppendLine("<meta property=\"og:description\" content=\"" +
                               SysParam.GetByName("SITE_DESCRIPTION").Value + "\" />");
            }
            else if (CurrentPage != null || CurrentPost != null)
            {
                var title       = CurrentPage != null ? CurrentPage.Title : CurrentPost.Title;
                var description = CurrentPage != null ? CurrentPage.Description :
                                  (!String.IsNullOrEmpty(CurrentPost.Description) ? CurrentPost.Description : CurrentPost.Excerpt);

                str.AppendLine("<meta property=\"og:type\" content=\"article\" />");
                if (!String.IsNullOrEmpty(description))
                {
                    str.AppendLine("<meta property=\"og:description\" content=\"" + description + "\" />");
                }
                str.AppendLine("<meta property=\"og:title\" content=\"" + title + "\" />");
            }

            /**
             * RSS Feeds
             */
            str.AppendLine("<link rel=\"alternate\" type=\"application/rss+xml\" title=\"" +
                           SysParam.GetByName("SITE_TITLE").Value + "\" href=\"" + WebPages.WebPiranha.GetSiteUrl() + "/" +
                           WebPages.WebPiranha.GetUrlPrefixForHandlerId("rss") + "\" />");

            return(new HtmlString(str.ToString()));
        }
Esempio n. 28
0
 /// <summary>
 /// Updates the global last modified date for the site.
 /// </summary>
 /// <param name="tx">Optional transaction</param>
 public static void SetSiteLastModified(IDbTransaction tx = null)
 {
     SysParam.Execute("UPDATE sysparam SET sysparam_value = @0 WHERE sysparam_name = @1", tx,
                      DateTime.Now, "SITE_LAST_MODIFIED");
     SysParam.InvalidateParam("SITE_LAST_MODIFIED");
 }
Esempio n. 29
0
        /// <summary>
        /// Saves the page and all of it's related regions.
        /// </summary>
        /// <param name="publish">If the page should be published</param>
        /// <returns>If the operation succeeded</returns>
        public virtual bool SaveAll(bool draft = true)
        {
            using (IDbTransaction tx = Database.OpenConnection().BeginTransaction()) {
                try {
                    bool permalinkfirst = Page.IsNew;

                    // Save permalink first if the page is new
                    if (permalinkfirst)
                    {
                        if (Permalink.IsNew && String.IsNullOrEmpty(Permalink.Name))
                        {
                            Permalink.Name = Permalink.Generate(!String.IsNullOrEmpty(Page.NavigationTitle) ?
                                                                Page.NavigationTitle : Page.Title);
                            var param = SysParam.GetByName("HIERARCHICAL_PERMALINKS");
                            if (param != null && param.Value == "1" && Page.ParentId != Guid.Empty)
                            {
                                var parent = Page.GetSingle(Page.ParentId, true);
                                Permalink.Name = parent.Permalink + "/" + Permalink.Name;
                            }
                        }
                        Permalink.Save(tx);
                    }

                    // Save page
                    if (draft)
                    {
                        Page.Save(tx);
                    }
                    else
                    {
                        Page.SaveAndPublish(tx);
                    }

                    // Save regions & properties
                    Regions.ForEach(r => {
                        r.IsDraft = r.IsPageDraft = true;

                        // Call OnSave
                        r.Body.OnManagerSave(Page);

                        r.Save(tx);
                        if (!draft)
                        {
                            if (Region.GetScalar("SELECT COUNT(region_id) FROM region WHERE region_id=@0 AND region_draft=0", r.Id) == 0)
                            {
                                r.IsNew = true;
                            }
                            r.IsDraft = r.IsPageDraft = false;
                            r.Save(tx);
                        }
                    });
                    Properties.ForEach(p => {
                        p.IsDraft = true;
                        p.Save(tx);
                        if (!draft)
                        {
                            if (Property.GetScalar("SELECT COUNT(property_id) FROM property WHERE property_id=@0 AND property_draft=0", p.Id) == 0)
                            {
                                p.IsNew = true;
                            }
                            p.IsDraft = false;
                            p.Save(tx);
                        }
                    });

                    // Save extensions
                    foreach (var ext in Extensions)
                    {
                        // Call OnSave
                        ext.Body.OnManagerSave(Page);

                        ext.ParentId = Page.Id;
                        ext.Save(tx);
                        if (!draft)
                        {
                            if (Extension.GetScalar("SELECT COUNT(extension_id) FROM extension WHERE extension_id=@0 AND extension_draft=0", ext.Id) == 0)
                            {
                                ext.IsNew = true;
                            }
                            ext.IsDraft = false;
                            ext.Save(tx);
                        }
                    }

                    // Save permalink last if the page isn't new
                    if (!permalinkfirst)
                    {
                        Permalink.Save(tx);
                    }

                    // Change global last modified
                    if (!draft)
                    {
                        Web.ClientCache.SetSiteLastModified(tx);
                    }

                    // Clear cache for all post regions if we're publishing
                    if (!String.IsNullOrEmpty(Page.Permalink) && !draft)
                    {
                        foreach (var reg in Regions)
                        {
                            if (reg.Body is Extend.Regions.PostRegion)
                            {
                                ((Extend.Regions.PostRegion)reg.Body).ClearCache(Page, reg);
                            }
                        }
                    }

                    tx.Commit();

                    if (IsSite)
                    {
                        using (var db = new DataContext()) {
                            var site = db.SiteTrees.Where(s => s.Id == Page.SiteTreeId).Single();
                            site.MetaTitle       = SiteTree.MetaTitle;
                            site.MetaDescription = SiteTree.MetaDescription;
                            db.SaveChanges();
                        }
                        if (!draft)
                        {
                            PageModel.RemoveSitePageFromCache(Page.SiteTreeId);
                            WebPages.WebPiranha.RegisterDefaultHostNames();
                        }
                    }
                } catch { tx.Rollback(); throw; }
            }
            return(true);
        }
Esempio n. 30
0
        /// <summary>
        /// Handles the URL Rewriting for the application
        /// </summary>
        /// <param name="context">Http context</param>
        public static void BeginRequest(HttpContext context)
        {
            try {
                string path = context.Request.Path.Substring(context.Request.ApplicationPath.Length > 1 ?
                                                             context.Request.ApplicationPath.Length : 0);

                string[] args = path.Split(new char[] { '/' }).Subset(1);

                if (args.Length > 0)
                {
                    int pos = 0;

                    // Ensure database
                    if (args[0] == "" && SysParam.GetByName("SITE_VERSION") == null)
                    {
                        context.Response.Redirect("~/manager", false);
                        context.Response.EndClean();
                    }

                    // Check for culture prefix
                    if (Cultures.ContainsKey(args[0]))
                    {
                        System.Threading.Thread.CurrentThread.CurrentCulture       =
                            System.Threading.Thread.CurrentThread.CurrentUICulture = Cultures[args[0]];
                        pos = 1;
                    }
                    else
                    {
                        var def = (GlobalizationSection)WebConfigurationManager.GetSection("system.web/globalization");
                        if (def != null && !String.IsNullOrWhiteSpace(def.Culture) && !def.Culture.StartsWith("auto:"))
                        {
                            System.Threading.Thread.CurrentThread.CurrentCulture       =
                                System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(def.UICulture);
                        }
                    }

                    // Check for hostname extension. This feature can't be combined with culture prefixes
                    if (pos == 0)
                    {
                        var segments = context.Request.RawUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                        if (segments.Length > 0)
                        {
                            var hostExt = context.Request.Url.Host + "/" + segments[0];

                            if (HostNames.ContainsKey(hostExt))
                            {
                                RequestedSite = new ExtendedHostName()
                                {
                                    HostName  = context.Request.Url.Host,
                                    Extension = segments[0],
                                    SiteTree  = HostNames[hostExt]
                                };
                                if (segments[0] == args[0])
                                {
                                    pos = 1;

                                    // If this was the last argument, add an empty one
                                    if (args.Length == 1)
                                    {
                                        args = args.Concat(new string[] { "" }).ToArray();
                                    }
                                }
                            }
                        }
                    }

                    var handled = false;

                    // Find the correct request handler
                    foreach (var hr in Application.Current.Handlers)
                    {
                        if (hr.UrlPrefix.ToLower() == args[pos].ToLower())
                        {
                            if (hr.Id != "PERMALINK" || !Config.PrefixlessPermalinks)
                            {
                                // Don't execute permalink routing in passive mode
                                if ((hr.Id != "PERMALINK" && hr.Id != "STARTPAGE") || !Config.PassiveMode)
                                {
                                    // Execute the handler
                                    hr.Handler.HandleRequest(context, args.Subset(pos + 1));
                                    handled = true;
                                    break;
                                }
                            }
                        }
                    }

                    if (!handled && args[pos].ToLower() == "res.ashx")
                    {
                        Application.Current.Resources.HandleRequest(context, args.Subset(pos + 1));
                        handled = true;
                    }

                    // If no handler was found and we are using prefixless permalinks,
                    // route traffic to the permalink handler.
                    if (!Config.PassiveMode)
                    {
                        if (!handled && Config.PrefixlessPermalinks && args[pos].ToLower() != "manager" && String.IsNullOrEmpty(context.Request["permalink"]))
                        {
                            if (Permalink.GetByName(Config.SiteTreeNamespaceId, args[pos]) != null || Permalink.GetByName(Config.DefaultNamespaceId, args[pos]) != null)
                            {
                                var handler = Application.Current.Handlers["PERMALINK"];
                                handler.HandleRequest(context, args.Subset(pos));
                            }
                        }
                    }
                }
            } catch (ThreadAbortException) {
                // We simply swallow this exception as we don't want unhandled
                // exceptions flying around causing the app pool to die.
            } catch (Exception e) {
                // One catch to rule them all, and in the log file bind them.
                Application.Current.LogProvider.Error("WebPiranha.BeginRequest", "Unhandled exception", e);
                context.Response.StatusCode = 500;
                context.Response.EndClean();
            }
        }
Esempio n. 31
0
		/// <summary>
		/// Default constructor.
		/// </summary>
		public ParamEditModel() {
			Param = new SysParam();
		}