public void HandleError(RequestContext context, int code, HttpException exception)
        {
            if (ShouldLogException(code))
            {
                HandleExceptionWithElmah(exception);
            }
            Entities.Documents.Web.Webpage webpage = _getErrorPage.GetPage(code);
            if (webpage != null)
            {
                HttpContextBase httpContext = context.HttpContext;
                httpContext.ClearError();
                httpContext.Response.Clear();
                httpContext.Response.StatusCode             = code;
                httpContext.Response.TrySkipIisCustomErrors = true;

                CurrentRequestData.CurrentPage = webpage;
                System.Web.Mvc.Controller controller = _controllerManager.GetController(context, webpage, httpContext.Request.HttpMethod);

                IAsyncController asyncController = (controller as IAsyncController);
                asyncController.BeginExecute(new RequestContext(httpContext, controller.RouteData), asyncController.EndExecute, null);
            }
            else
            {
                throw exception;
            }
        }
Example #2
0
        //JDR: Set path for user to be redirected after loggin, this is also used to send user to a page they atempted to acces but was not loggedIn
        public static void SetLoggedInPathLocation(System.Web.Mvc.Controller CurrentController)
        {
            string Controller = CurrentController.ControllerContext.RouteData.Values["controller"].ToString();
            string Action     = CurrentController.ControllerContext.RouteData.Values["action"].ToString();

            UserAccount.SetLoggedInPathLocation(Controller, Action);
        }
Example #3
0
        public static SqlConnection OpenConnection(this System.Web.Mvc.Controller controller)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

            con.Open();
            return(con);
        }
Example #4
0
        /// <summary>
        /// 在后台组合where 条件
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string BindWhere(this System.Web.Mvc.Controller controller, Type type)
        {
            List <string> wherelist = new List <string>();//where 列表

            var propertys = type.GetProperties();

            foreach (var p in propertys)
            {
                object[] alist = p.GetCustomAttributes(typeof(SearchAttribute), false);
                if (alist.Length > 0)
                {
                    SearchAttribute sa = alist[0] as SearchAttribute;
                    if (sa == null)
                    {
                        continue;
                    }
                    string w = sa.getWhere(p, controller.Request);
                    if (string.IsNullOrWhiteSpace(w))
                    {
                        continue;
                    }
                    wherelist.Add(w);//获取类型绑定的search对象
                }
            }

            return(string.Join(" AND ", wherelist.ToArray()));
        }
    public static string GetViewPageHtml(object model, string viewName)
    {
        System.Web.Mvc.Controller controller = CreateController <TestController>();

        ViewEngineResult result = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);

        if (result.View == null)
        {
            throw new Exception(string.Format("View Page {0} was not found", viewName));
        }

        controller.ViewData.Model = model;
        StringBuilder sb = new StringBuilder();

        using (StringWriter sw = new StringWriter(sb))
        {
            using (System.Web.UI.HtmlTextWriter output = new System.Web.UI.HtmlTextWriter(sw))
            {
                ViewContext viewContext = new ViewContext(controller.ControllerContext, result.View, controller.ViewData, controller.TempData, output);
                result.View.Render(viewContext, output);
            }
        }

        return(sb.ToString());
    }
Example #6
0
        /// <summary>
        /// Save photo to disk, used by Edit and Register with two different models.
        /// </summary>
        /// <param name="photo">HttpPostedFileWrapper</param>
        /// <param name="controller">Controller calling</param>
        /// <returns>Path where photo is stored with it's calculated filename, or default photo "BlankPhoto.jpg" or null on error</returns>
        public static string SavePhotoFileToDisk(object myphoto, System.Web.Mvc.Controller controller, string oldPhotoUrl, bool isNoPhotoChecked)
        {
            HttpPostedFileBase photo = (HttpPostedFileBase)myphoto;

            string photoPath = string.Empty;
            string fileName  = string.Empty;

            // If photo is uploaded calculate his name
            if (photo != null)
            {
                fileName = Guid.NewGuid().ToString() + "_" + photo.FileName;
            }
            else
            {
                // if user want to remove his photo
                if (oldPhotoUrl != null && isNoPhotoChecked == true)
                {
                    if (!oldPhotoUrl.Contains("BlankPhoto.jpg"))
                    {
                        string   fileToDelete = Path.GetFileName(oldPhotoUrl);
                        var      path         = Path.Combine(controller.Server.MapPath("~/Content/Avatars"), fileToDelete);
                        FileInfo fi           = new FileInfo(path);
                        if (fi.Exists)
                        {
                            fi.Delete();
                        }
                    }
                }

                // If no previews photo it's a new user who don't provide photo
                if (oldPhotoUrl == null || isNoPhotoChecked == true)
                {
                    fileName = "BlankPhoto.jpg";
                }
                else
                {
                    // User don't want to change his photo
                    return(oldPhotoUrl);
                }
            }
            // We save the new/first photo on disk
            try
            {
                string path;
                path      = Path.Combine(controller.Server.MapPath("~/Content/Avatars"), fileName);
                photoPath = Path.Combine(HttpRuntime.AppDomainAppVirtualPath, "Content/Avatars", fileName);
                // We save the new/first photo or nothing because BlankPhoto is in the folder
                if (photo != null)
                {
                    photo.SaveAs(path);
                }
            }
            catch (Exception ex)
            {
                // Handled exception catch code
                Helpers.Utils.SignalExceptionToElmahAndTrace(ex, controller);
                return(null);
            }
            return(photoPath);
        }
 public static System.Web.Mvc.JsonResult LargeJson(this System.Web.Mvc.Controller controlador, object data)
 {
     return(new System.Web.Mvc.JsonResult()
     {
         Data = data,
         MaxJsonLength = MaxJsonLength,
     });
 }
Example #8
0
        public static System.IO.StreamReader OpenExcelTemplate(this System.Web.Mvc.Controller controller, string name)
        {
            ResourceSqlLoader excelLoader = new ResourceSqlLoader("excel-template-loader", "ExcelTemplate", typeof(PIControllerExtensions).Assembly);

            excelLoader.Extensions.Clear();
            excelLoader.AddExtension("xlsx");
            return(excelLoader.GetStream(name));
        }
Example #9
0
        public List <Common.AccordionItem> GetCurrentUserMenu(System.Web.Mvc.Controller controller)
        {
            List <AccordionItem> menulist = new List <AccordionItem>();
            IList <SmartBox.Console.Common.Privilege> list = GetList(controller);

            if (list != null)
            {
                var topmenu = list.Where(x => x.ParentID == "0");

                if (topmenu != null)
                {
                    foreach (SmartBox.Console.Common.Privilege p in topmenu)
                    {
                        AccordionItem item = new AccordionItem();
                        item.Text     = p.PrivilegeName;
                        item.Code     = p.PrivilegeCode;
                        item.IsExpand = false;
                        item.Url      = p.Uri;
                        item.ID       = p.ID;
                        item.IcoSrc   = "";
                        SmartBox.Console.Common.Privilege privilege = p;
                        var child = list.Where(x => x.ParentID == privilege.ID.ToString());
                        if (child != null)
                        {
                            foreach (SmartBox.Console.Common.Privilege pc in child)
                            {
                                AccordionItem citem = new AccordionItem();
                                citem.Text   = pc.PrivilegeName;
                                citem.Code   = pc.PrivilegeCode;
                                citem.Url    = pc.Uri;
                                citem.IcoSrc = "";
                                citem.ID     = pc.ID;
                                citem.Type   = pc.PrivilegeType.ToString();

                                //检查citem的节点,如有则添加
                                SmartBox.Console.Common.Privilege lefprivilege = pc;
                                var childleaf = list.Where(x => x.ParentID == pc.ID.ToString());
                                foreach (SmartBox.Console.Common.Privilege pcleaf in childleaf)
                                {
                                    AccordionItem litem = new AccordionItem();
                                    litem.Text   = pcleaf.PrivilegeName;
                                    litem.Code   = pcleaf.PrivilegeCode;
                                    litem.Url    = pcleaf.Uri;
                                    litem.IcoSrc = "";
                                    litem.ID     = pcleaf.ID;

                                    citem.Children.Add(litem);
                                }

                                item.Children.Add(citem);
                            }
                        }
                        menulist.Add(item);
                    }
                }
            }
            return(menulist);
        }
 public static System.Web.Mvc.JsonResult LargeJson(this System.Web.Mvc.Controller controlador, object data, System.Web.Mvc.JsonRequestBehavior behavior)
 {
     return(new System.Web.Mvc.JsonResult()
     {
         Data = data,
         JsonRequestBehavior = behavior,
         MaxJsonLength = MaxJsonLength
     });
 }
Example #11
0
        //public static dynamic ToJSON(this PackageElement package)
        //{
        //    return new
        //    {
        //        name = package.ID,
        //        title = package.Title != null ? package.Title.Text : package.ID,
        //        desc =package.Description!=null ? package.Description.Text : "",
        //        version = package.Version,
        //        published = package.Published,
        //        //author =null,
        //        licenses = package.Licenses.Select(l => new
        //        {
        //            title = l.Text,
        //            url = l.Source
        //        }),
        //        images = package.Images.Select(i => new
        //        {
        //            title = i.Title,
        //            url = i.Source //, //package.ResolveUrl(i.Url),
        //            //width = i.Width,
        //            //height = i.Height
        //        }),
        //        links = package.Links.Select(l => new
        //        {
        //            title = l.Title,
        //            url = l.NavigateUrl
        //        })
        //    };
        //}

        //public static string GeneratePermalink(this WebPage page, string webName, IWebPageRepository repository)
        //{
        //    string path = TextUtility.Slug(page.Title);
        //    if ((string.IsNullOrEmpty(webName)) || webName.Equals("home", StringComparison.OrdinalIgnoreCase))
        //        path = "~/sites/home/" + path;
        //    else
        //        path = "~/sites/" + webName.ToLower() + "/" + path;

        //    if (!repository.IsExists(path.ToLower() + ".html"))
        //        path += ".html";
        //    else
        //        path += "-" + DateTime.Now.ToString("yyMMddHHmm") + ".html";
        //    page.Path = path;
        //    return path;
        //}

        public static string CurrentWebName(this System.Web.Mvc.Controller ctrl)
        {
            var website = "home";

            if (ctrl.RouteData.Values.ContainsKey("website"))
            {
                website = ctrl.RouteData.Values["website"] as string;
            }
            return(website);
        }
Example #12
0
        /// <summary>
        /// 显示消息提示对话框,并进行页面跳转
        /// </summary>
        /// <param name="page">当前页面指针,一般为this</param>
        /// <param name="msg">提示信息</param>
        /// <param name="url">跳转的目标URL</param>
        public static void ShowAndRedirect(System.Web.Mvc.Controller page, string msg, string url)
        {
            StringBuilder Builder = new StringBuilder();

            Builder.Append("<script language='javascript' defer>");
            Builder.AppendFormat("alert('{0}');", msg);
            Builder.AppendFormat("location.href='{0}'", url);
            Builder.Append("</script>");
            page.Response.Write(Builder.ToString());
        }
Example #13
0
 public override string GetUserId(System.Web.Mvc.Controller controller)
 {
     //var user = controller.Session["user"];
     //if (user == null)
     //{
     //    user = Guid.NewGuid();
     //    controller.Session["user"] = user;
     //}
     //return user.ToString();
     return("TestUser");
 }
Example #14
0
 public static void MakeCategoryFolder(string category, System.Web.Mvc.Controller controller)
 {
     if (category != string.Empty)
     {
         var folder = controller.Server.MapPath("~/Medias/_Photos/" + category);
         if (!Directory.Exists(folder))
         {
             Directory.CreateDirectory(folder);
         }
     }
 }
        public override string GetUserId(System.Web.Mvc.Controller controller)
        {
            var user = controller.Session["user"];

            if (user == null)
            {
                user = Guid.NewGuid();
                controller.Session["user"] = user;
            }
            return(user.ToString());
        }
Example #16
0
        public static void SignalExceptionToElmahAndTrace(Exception ex, System.Web.Mvc.Controller lui)
        {
            MyTracer.MyTrace(
                System.Diagnostics.TraceLevel.Error,
                lui.GetType(),
                lui.ControllerContext.RouteData.Values["controller"].ToString(),
                lui.ControllerContext.RouteData.Values["action"].ToString(),
                ex.Message, ex);

            //Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //ELMAH Signaling
        }
Example #17
0
        protected void SetupIdentity(System.Web.Mvc.Controller controller, string userId)
        {
            GenericIdentity identity = new GenericIdentity("test");

            identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userId));

            IPrincipal fakePrincipal = A.Fake <IPrincipal>();

            A.CallTo(() => fakePrincipal.Identity).Returns(identity);

            A.CallTo(() => controller.ControllerContext.HttpContext.User).Returns(fakePrincipal);
        }
Example #18
0
 /// <summary>
 /// 提示信息
 /// </summary>
 /// <param name="_MvcController">MvcController</param>
 /// <param name="msg">msg</param>
 /// <param name="IsRedirect">是否跳转到其它页面</param>
 public static void AlertMessage(System.Web.Mvc.Controller _MvcController, string msg, bool IsRedirect)
 {
     msg = msg.Replace("\"", "");
     if (!IsRedirect)
     {
         _MvcController.ViewData["AlertMessage"] = msg;
     }
     else
     {
         _MvcController.TempData["AlertMessage"] = msg;
     }
 }
Example #19
0
        //JDR: Overload 2: Verify if active user in seccion, also set loggedInPathLocation
        public static bool IsLoggedIn(System.Web.Mvc.Controller CurrentController)
        {
            if (UserAccount.IsLoggedIn())
            {
                return(true);
            }

            //JDR: user is not loggedIn so Set LoggedInLocation for when he logges in
            UserAccount.SetLoggedInPathLocation(CurrentController);

            return(false);
        }
        public Cart GetCart(System.Web.Mvc.Controller controller)
        {
            var cart = controller.Session["Cart"] as Cart;

            if (cart != null)
            {
                return(cart);
            }
            cart = new Cart();
            controller.Session["Cart"] = cart;
            return(cart);
        }
Example #21
0
 /// <summary>
 /// Ajax helper for sending ajax response.
 /// Data contain 4 keys:
 /// 1. success (boolean): indicate operation status
 /// 2. data (object): the data to be sent
 /// 3. errors (hash array): key value pair of errors (if any), the key is property of model class
 /// 4. html (string): html page (instead of object in data)
 /// </summary>
 /// <typeparam name="T">data type of input/output</typeparam>
 /// <param name="controller"></param>
 /// <param name="data">response data</param>
 /// <param name="success">indicate operation status</param>
 /// <param name="statusCode">HTTP status code</param>
 /// <param name="html">additional HTML code for response</param>
 /// <param name="errors">validation error fields</param>
 /// <returns></returns>
 public static System.Web.Mvc.JsonResult Ajax <T>(this System.Web.Mvc.Controller controller, T data, bool success, int statusCode = 200, string html = "", Dictionary <string, string[]> errors = null)
     where T : class
 {
     controller.HttpContext.Response.StatusCode = statusCode;
     return(new System.Web.Mvc.JsonResult
     {
         JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet,
         ContentType = "application/json",
         Data = new { success, data, errors, html },
         RecursionLimit = 5
     });
 }
Example #22
0
 public static void StoreClientInSession(Client client, System.Web.Mvc.Controller controller)
 {
     controller.Session[Client.FieldName.UID]                   = client.UID;
     controller.Session[Client.FieldName.ABN]                   = client.ABN;
     controller.Session[Client.FieldName.Name]                  = client.Name;
     controller.Session[Client.FieldName.Address]               = client.Address;
     controller.Session[Client.FieldName.Phone]                 = client.Phone;
     controller.Session[Client.FieldName.Fax]                   = client.Fax;
     controller.Session[Client.FieldName.EmailAddress]          = client.EmailAddress;
     controller.Session[Client.FieldName.MainContactPersonName] = client.MainContactPersonName;
     controller.Session[Client.FieldName.IsVoid]                = client.IsVoid;
     controller.Session[Client.FieldName.DisplayLogo]           = client.DisplayLogo;
 }
        public static Item GetItem(this System.Web.Mvc.Controller controller)
        {
            var rc = RenderingContext.CurrentOrNull;

            if (rc != null && rc.Rendering != null)
            {
                if (!string.IsNullOrEmpty(rc.Rendering.DataSource))
                {
                    return(Sitecore.Context.Database.GetItem(rc.Rendering.DataSource));
                }
            }
            return(Sitecore.Context.Item);
        }
Example #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="viewName"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static PartialViewResult PartialExtView(this System.Web.Mvc.Controller controller, string viewName, object model)
        {
            if (model != null)
            {
                controller.ViewData.Model = model;
            }

            return(new PartialViewResult
            {
                ViewName = viewName,
                ViewData = controller.ViewData,
                TempData = controller.TempData
            });
        }
Example #25
0
        public static string GetHostName(System.Web.Mvc.Controller controller, string url)
        {
            Uri  videoUri;
            bool isAbsoluteUrl = Uri.TryCreate(url, UriKind.Absolute, out videoUri);

            if (isAbsoluteUrl)
            {
                return(videoUri.GetLeftPart(UriPartial.Authority));
            }
            else
            {
                return(controller.Request.Url.GetLeftPart(UriPartial.Authority));
            }
        }
Example #26
0
        public static string SoleErrorMessage(this System.Web.Mvc.Controller controller, string modelKey)
        {
            Console.Write("Keys:");
            foreach (var key in controller.ModelState.Keys)
            {
                Console.Write(" " + key);
            }
            var errors = controller.ModelState[modelKey]?.Errors;

            if (errors != null && errors.Any())
            {
                return(errors.First().ErrorMessage);
            }
            return("*** No errors ***");
        }
Example #27
0
        public DHXScheduler(System.Web.Mvc.Controller parent)
            : this()
        {
            string name   = parent.GetType().Name;
            int    length = nameof(Controller).Length;

            if (name.Length > length && name.EndsWith(nameof(Controller)))
            {
                this.Controller = name.Substring(0, name.Length - length);
            }
            else
            {
                this.Controller = name;
            }
        }
Example #28
0
        public static string GetPhysicalFolder(System.Web.Mvc.Controller controller, string url)
        {
            Uri  videoUri;
            bool isAbsoluteUrl = Uri.TryCreate(url, UriKind.Absolute, out videoUri);

            if (isAbsoluteUrl)
            {
                string currentDomain = videoUri.GetLeftPart(UriPartial.Authority);
                return(System.Configuration.ConfigurationManager.AppSettings[currentDomain]);
            }
            else
            {
                return(controller.Server.MapPath("~/"));
            }
        }
Example #29
0
        public static async Task <bool> InitializeAsync(System.Web.Mvc.Controller c)
        {
            c.ViewBag.myPerms = await userPerms(My.id);

            c.ViewBag.UserNewsNegareshFlows = await UserNegareshFlowsAsync("خبر");

            c.ViewBag.UserPageNegareshFlows = await UserNegareshFlowsAsync("صفحه");

            var ninboxCount = await NoSql.Instance.RunCommandAsync <BsonDocument>("{count:'pages',query:{touser:'******'}}");

            c.ViewBag.pinboxCount = ninboxCount["n"].AsInt32;
            var pinboxCount = await NoSql.Instance.RunCommandAsync <BsonDocument>("{count:'news',query:{touser:'******'}}");

            c.ViewBag.ninboxCount = pinboxCount["n"].AsInt32;
            return(true);
        }
Example #30
0
        public static string GetPhysicalPath(System.Web.Mvc.Controller controller, string url)
        {
            Uri  videoUri;
            bool isAbsoluteUrl = Uri.TryCreate(url, UriKind.Absolute, out videoUri);

            if (isAbsoluteUrl)
            {
                string currentDomain = videoUri.GetLeftPart(UriPartial.Authority);
                string filePath      = System.Configuration.ConfigurationManager.AppSettings[currentDomain] + System.Net.WebUtility.UrlDecode(videoUri.AbsolutePath);
                return(filePath);
            }
            else
            {
                return(controller.Server.MapPath(url));
            }
        }