Exemplo n.º 1
0
        private void EditorModelEventManager_SendingContentModel(System.Web.Http.Filters.HttpActionExecutedContext sender, EditorModelEventArgs <Umbraco.Web.Models.ContentEditing.ContentItemDisplay> e)
        {
            var contentItemDisplay = e.Model;
            var context            = e.UmbracoContext;

            MakePropertiesReadOnly(contentItemDisplay, context);
        }
Exemplo n.º 2
0
        public void EndTransaction(System.Web.Http.Filters.HttpActionExecutedContext httpActionExecutedContext)
        {
            if (!CurrentSessionContext.HasBind(sessionFactory))
            {
                return;
            }

            var session = sessionFactory.GetCurrentSession();

            if (null == session)
            {
                return;
            }

            if (!session.Transaction.IsActive)
            {
                return;
            }

            if (httpActionExecutedContext.Exception == null)
            {
                session.Flush();
                session.Transaction.Commit();
            }
            else
            {
                session.Transaction.Rollback();
            }

            TransactionHandled = true;
        }
Exemplo n.º 3
0
 public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
 {
     //this.log.DebugFormat(
     //    "Executed action {0}.{1}",
     //    actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName,
     //    actionExecutedContext.ActionContext.ActionDescriptor.ActionName);
 }
Exemplo n.º 4
0
 public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext context)
 {
     if (!DisableTracing)
     {
         //Do something here before an action method starts executing
     }
 }
Exemplo n.º 5
0
        public static void EditorModelEventManager_SendingContentModel(System.Web.Http.Filters.HttpActionExecutedContext sender, EditorModelEventArgs <ContentItemDisplay> e)
        {
            if (e.Model is ContentItemDisplay contentModel)
            {
                var umbracoContext = Current.Factory.GetInstance <IUmbracoContextFactory>();

                if (umbracoContext != null)
                {
                    using (var cref = umbracoContext.EnsureUmbracoContext())
                    {
                        var contentItem = cref.UmbracoContext?.Content?.GetById(contentModel.Id);

                        // Hide Preview Button and URL's if no template assigned.
                        if (string.IsNullOrEmpty(contentModel.TemplateAlias))
                        {
                            contentModel.AllowPreview = false;
                            contentModel.Urls         = null;
                        }

                        // Hide Preview Button and URL's if inside data repository.
                        if (contentItem?.AncestorOrSelf <DataRepository>() != null)
                        {
                            contentModel.AllowPreview = false;
                            contentModel.Urls         = null;
                        }
                    }
                }
            }
        }
 public override void OnException(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
 {
     if (actionExecutedContext.Exception != null)
     {
         Elmah.ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception);
     }
     base.OnException(actionExecutedContext);
 }
Exemplo n.º 7
0
        private void EditorModelEventManagerSendingContentModel(System.Web.Http.Filters.HttpActionExecutedContext sender, EditorModelEventArgs <ContentItemDisplay> e)
        {
            var contentModel = e.Model;

            if (contentModel != null)
            {
                contentModel.AllowPreview = false;
            }
        }
 public override void OnException(
     System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
 {
     if (actionExecutedContext.Exception != null)
     {
         Elmah.ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception);
     }
     // Elmah.ErrorSignal.FromCurrentContext().Raise(new CustomException(actionExecutedContext.Exception.ToString, actionExecutedContext.Exception.InnerException));
     base.OnException(actionExecutedContext);
 }
Exemplo n.º 9
0
        /// <summary>
        /// Fill in default properties when creating an Articulate root node
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EditorModelEventManager_SendingContentModel(System.Web.Http.Filters.HttpActionExecutedContext sender, EditorModelEventArgs <Umbraco.Web.Models.ContentEditing.ContentItemDisplay> e)
        {
            var content = e.Model;

            if (!content.ContentTypeAlias.InvariantEquals(ArticulateContentTypeAlias))
            {
                return;
            }

            //if it's not new don't continue
            if (content.Id != default(int))
            {
                return;
            }

            var allProperties = content.Variants.SelectMany(x => x.Tabs.SelectMany(p => p.Properties));

            foreach (var prop in allProperties)
            {
                switch (prop.Alias)
                {
                case "theme":
                    prop.Value = "VAPOR";
                    break;

                case "pageSize":
                    prop.Value = 10;
                    break;

                case "categoriesUrlName":
                    prop.Value = "categories";
                    break;

                case "tagsUrlName":
                    prop.Value = "tags";
                    break;

                case "searchUrlName":
                    prop.Value = "search";
                    break;

                case "categoriesPageName":
                    prop.Value = "Categories";
                    break;

                case "tagsPageName":
                    prop.Value = "Tags";
                    break;

                case "searchPageName":
                    prop.Value = "Search results";
                    break;
                }
            }
        }
Exemplo n.º 10
0
        public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            actionExecutedContext.Response.Headers.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue
            {
                NoCache = true,
                MaxAge  = TimeSpan.FromSeconds(0),
                NoStore = true
            };

            base.OnActionExecuted(actionExecutedContext);
        }
Exemplo n.º 11
0
        public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            string urlConfigValue = ConfigurationManager.AppSettings["AllowUrls"];

            if (!string.IsNullOrEmpty(urlConfigValue))
            {
                if (!actionExecutedContext.Response.Headers.Contains("Access-Control-Allow-Origin"))
                {
                    actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", urlConfigValue);
                }
            }
        }
Exemplo n.º 12
0
 public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext) {
     var principal = actionExecutedContext.ActionContext.RequestContext.Principal;
     if(principal != null) {
         using (var db = new databaseContext()) {
             var dbUser = (from b in db.AspNetUsers
                         where b.UserName == principal.Identity.Name
                         select b).First();
             dbUser.LastActivity = DateTime.Now;
             db.SaveChanges();
         }
     }
 }
Exemplo n.º 13
0
        public async Task ExecuteExceptionFilterAsync(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            string msg   = "服务器忙,请联系管理员";
            var    error = actionExecutedContext.Exception as HaishanException;

            if (error != null)
            {
                msg = error.Message;
            }
            var data = ResultDataWrapper.Error(msg, actionExecutedContext.Exception.Message);

            actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(System.Net.HttpStatusCode.OK, data);
        }
Exemplo n.º 14
0
        public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            _stopWatch.Stop();

            var controller = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var action     = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;

            _metrics.Insert(new Core.Metrics {
                Controller = controller, Action = action, Miliseconds = _stopWatch.ElapsedMilliseconds
            });

            base.OnActionExecuted(actionExecutedContext);
        }
Exemplo n.º 15
0
        public override void OnException(System.Web.Http.Filters.HttpActionExecutedContext context)
        {
            var filteredException = context.Exception as FilteredException;

            if (filteredException != null)
            {
                context.Response = new HttpResponseMessage(filteredException.StatusCode)
                {
                    ReasonPhrase = filteredException.Message,
                    Content      = new StringContent(filteredException.Message),
                };
                context.Response.Headers.Add("filtered-exception", context.Exception.GetType().Name);
            }
        }
Exemplo n.º 16
0
    /*
     * Is this guaranteed to be called?
     *
     *
     */
    public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
    {
        if (_timer != null)
        {
            _timer.Dispose();
        }

        if (_tokenSource != null)
        {
            _tokenSource.Dispose();
        }

        base.OnActionExecuted(actionExecutedContext);
    }
Exemplo n.º 17
0
        private void EditorModelEventManager_SendingContentModel(System.Web.Http.Filters.HttpActionExecutedContext sender, EditorModelEventArgs <ContentItemDisplay> e)
        {
            // For the editor user, let's hide all the reserved tabs
            if (!e.UmbracoContext.Security.CurrentUser.IsAdmin())
            {
                e.Model.Variants.FirstOrDefault().Tabs = e.Model.Variants.FirstOrDefault().Tabs.Where(t => !_reservedTabs.Contains(t.Alias));
            }

            var bodyElements = e.Model.Variants.FirstOrDefault().Tabs.FirstOrDefault(f => f.Alias == "Content")?.Properties?.FirstOrDefault(f => f.Alias == "bodyElements");

            if (bodyElements != null)
            {
                //TODO: allow changing module names.
            }
        }
Exemplo n.º 18
0
        public override void OnException(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            base.OnException(actionExecutedContext);
            // 取得发生例外时的错误讯息
            var errorMessage = actionExecutedContext.Exception.Message;

            var result = new ApiResultModel()
            {
                Code = HttpStatusCode.BadRequest,
                Msg  = errorMessage
            };

            // 重新打包回传的讯息
            actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(result.Code, result);
        }
        private void EditorModelEventManager_SendingContentModel1(System.Web.Http.Filters.HttpActionExecutedContext sender, EditorModelEventArgs <global::Umbraco.Web.Models.ContentEditing.ContentItemDisplay> e)
        {
            var identity    = (UmbracoBackOfficeIdentity)System.Web.HttpContext.Current.User.Identity;
            var currentUSer = Current.Services.UserService.GetByProviderKey(identity.Id);

            var canSeeAdminTab = currentUSer.Groups.Any(x => x.Alias == "admin");

            if (!canSeeAdminTab)
            {
                foreach (var variant in e.Model.Variants)
                {
                    variant.Tabs = variant.Tabs.Where(x => x.Label != "Admin");
                }
            }
        }
Exemplo n.º 20
0
        public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext filterContext)
        {
            var request = filterContext.Request;
            var headers = request.Headers;

            if (headers.Contains("X-Requested-With") && headers.GetValues("X-Requested-With").FirstOrDefault() == "XMLHttpRequest")
            {
                var response = filterContext.ActionContext.Response;
                if (response != null)
                {
                    List <SessionMessage> sessionMessages = SessionMessageManager.GetMessage();
                    if (sessionMessages != null && sessionMessages.Count > 0)
                    {
                        string json     = null;
                        var    messages = sessionMessages.Where(x => x.Behavior == MessageBehaviors.StatusBar).Select(x => new SessionMessageJsonModal {
                            Message = x.Message, Type = Enum.GetName(typeof(MessageType), x.Type).ToLowerInvariant(), Key = x.Key
                        }).ToList();
                        if (messages != null && messages.Count > 0)
                        {
                            DataContractJsonSerializer ser = new DataContractJsonSerializer(messages.GetType());
                            using (MemoryStream ms = new MemoryStream())
                            {
                                ser.WriteObject(ms, messages);
                                json = Encoding.Default.GetString(ms.ToArray());
                                ms.Close();
                            }
                            response.Headers.Add("X-Message", json);
                        }
                        messages = sessionMessages.Where(x => x.Behavior == MessageBehaviors.Modal).Select(x => new SessionMessageJsonModal {
                            Message = x.Message, Type = Enum.GetName(typeof(MessageType), x.Type).ToLowerInvariant(), Key = x.Key
                        }).ToList();
                        if (messages != null && messages.Count > 0)
                        {
                            DataContractJsonSerializer ser = new DataContractJsonSerializer(messages.GetType());
                            using (MemoryStream ms = new MemoryStream())
                            {
                                ser.WriteObject(ms, messages);
                                json = Encoding.Default.GetString(ms.ToArray());
                                ms.Close();
                            }
                            response.Headers.Add("X-ModalMessage", json);
                        }
                        SessionMessageManager.Clear();
                    }
                }
            }
        }
Exemplo n.º 21
0
        public override void OnException(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Exception != null)
            {
                var originController = actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName;
                var originAction     = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
                var exp      = actionExecutedContext.Exception.Message;
                var innerExp = string.Empty;

                if (actionExecutedContext.Exception.InnerException != null)
                {
                    innerExp = actionExecutedContext.Exception.InnerException.Message;
                }
            }

            base.OnException(actionExecutedContext);
        }
        private void EditorModelEventManager_SendingMemberModel(System.Web.Http.Filters.HttpActionExecutedContext sender, EditorModelEventArgs <MemberDisplay> e)
        {
            if (e.Model is MemberDisplay memberDisplay)
            {
                var personalisationConfig = DependencyResolver.Current.GetService <PersonalisationConfig>();
                if (personalisationConfig == null)
                {
                    return;
                }

                if (!memberDisplay.Properties?.Any() ?? true)
                {
                    return;
                }
                var property = memberDisplay.Properties.FirstOrDefault(x => x.Alias == personalisationConfig.PropertyAlias);
                if (property == null)
                {
                    return;
                }

                var personalisationService = DependencyResolver.Current.GetService <IPersonalisationService>();
                if (personalisationService == null)
                {
                    return;
                }

                var tags = personalisationService.GetFromStore((int)memberDisplay.Id);
                if (tags?.Any() ?? false)
                {
                    var sb = new StringBuilder();
                    sb.Append("<table class=\"table\" style=\"max-width:800px;\">");
                    sb.Append($"<tr><th>{nameof(PersonalisationTag.Tag)}</th><th>{nameof(PersonalisationTag.Score)}</th></tr>");

                    foreach (var x in tags.OrderByDescending(x => x.Score))
                    {
                        sb.Append($"<tr><td>{x.Tag}</td><td>{x.Score}<td></tr>");
                    }

                    sb.Append("</table>");

                    property.Value    = sb.ToString();
                    property.Readonly = true;
                }
            }
        }
        public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            string actionName     = actionExecutedContext.ActionContext.RequestContext.RouteData.Values["Action"].ToString();
            string controllerName = actionExecutedContext.ActionContext.RequestContext.RouteData.Values["Controller"].ToString();

            string key = String.Format("NC-{0}-{1}", controllerName, actionName);

            if (_stopWatches.ContainsKey(key))
            {
                _stopWatches[key].Stop();
                try
                {
                    actionExecutedContext.Response.Headers.Add("MVC-API-ActionTime", _stopWatches[key].ElapsedMilliseconds.ToString() + "ms");
                }
                catch { }
            }
            base.OnActionExecuted(actionExecutedContext);
        }
Exemplo n.º 24
0
        public void LogAction(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext, ActionLogger actionLogger)
        {
            var log = new CSVLog
            {
                Action      = actionExecutedContext.ActionContext.ActionDescriptor.ActionName,
                Controller  = actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName,
                Date        = DateTime.UtcNow,
                Description = actionLogger.getDescription(actionExecutedContext),
                IP          = IPUtils.GetClientIp(actionExecutedContext.Request)
            };

            var user = Common.UserUtils.GetUser(actionExecutedContext.Request);

            if (user != null)
            {
                log.UserEmail = user.Email;
                log.Username  = user.UserName;
            }

            Log(log);
        }
        /// <summary>
        /// Override to intercept the output from method and log it using NLog.
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext == null) throw new ArgumentNullException("actionExecutedContext");
            // Implementation of logging logic for response from APIs is not finished yet.
            string logStatement = string.Empty;
            if (actionExecutedContext.Response != null && actionExecutedContext.Response.Content != null)
            {
                logStatement = Newtonsoft.Json.JsonConvert.SerializeObject
                    (((System.Net.Http.ObjectContent)(actionExecutedContext.Response.Content)).Value, // Need to decide whether to log just the value or whole content. More testing is required.
                    Newtonsoft.Json.Formatting.None,
                    new Newtonsoft.Json.JsonSerializerSettings() { ContractResolver = new TraceLogContractResolver() });

                Logger.Info(String.Format(CultureInfo.InvariantCulture, "[Response] [{0}] [{1}] [{2}] {3}", actionExecutedContext.Response.StatusCode.ToString(), actionExecutedContext.Request.Method.Method, actionExecutedContext.Request.RequestUri.ToString(), logStatement));
            }
            else
            {
                Logger.Info(String.Format(CultureInfo.InvariantCulture, "[Response] [{0}] [{1}] {2}", actionExecutedContext.Request.Method.Method, actionExecutedContext.Request.RequestUri.ToString(), "Response is null"));
            }

            base.OnActionExecuted(actionExecutedContext);
        }
Exemplo n.º 26
0
        public override void OnException(
            System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Exception != null)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception);
                try
                {
                    using (var dbcontext = new DbContextRepository())
                    {
                        ErrorLog errorLog = new ErrorLog();

                        errorLog.MethodName     = actionExecutedContext.Exception.TargetSite.Name;
                        errorLog.ControllerName = actionExecutedContext.Exception.TargetSite.DeclaringType.Name;
                        var customAtttribute = actionExecutedContext.Exception.TargetSite.CustomAttributes;
                        foreach (var attr in customAtttribute)
                        {
                            errorLog.VerbAttribute = attr.AttributeType.Name;
                            break;
                        }

                        errorLog.ErrorMessage = actionExecutedContext.Exception.Message;

                        errorLog.UserId                 = 1;
                        errorLog.CreatedDate            = DateTime.UtcNow;
                        dbcontext.Entry(errorLog).State = EntityState.Added;
                        dbcontext.ErrorLogs.Add(errorLog);
                        dbcontext.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                }
            }


            base.OnException(actionExecutedContext);
        }
Exemplo n.º 27
0
        public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
            ITransaction currentTransaction = DependencyResolver.Current.GetService <ISession>().Transaction;

            try
            {
                if (currentTransaction.IsActive)
                {
                    if (actionExecutedContext.Exception != null)
                    {
                        currentTransaction.Rollback();
                    }
                    else
                    {
                        currentTransaction.Commit();
                    }
                }
            }
            finally
            {
                currentTransaction.Dispose();
            }
        }
        /// <summary>
        /// Called after the action method executes.
        /// Saves the result to the cache.
        /// </summary>
        /// <param name="actionExecutedContext">The action executed context.</param>
        public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            var resultContent = actionExecutedContext.ActionContext.Response.Content.ReadAsStreamAsync();

            resultContent.Wait();
            var stream = resultContent.Result;

            stream.Position = 0;
            var content = new byte[stream.Length];

            stream.Read(content, 0, content.Length);

            this.cache.AddEntry(
                GetKey(actionExecutedContext.ActionContext.ActionDescriptor),
                new Response
            {
                StatusCode   = actionExecutedContext.ActionContext.Response.StatusCode,
                ReasonPhrase = actionExecutedContext.ActionContext.Response.ReasonPhrase,
                Version      = actionExecutedContext.ActionContext.Response.Version,
                Content      = content,
                ContentType  = actionExecutedContext.ActionContext.Response.Content.Headers.ContentType,
            },
                this.expirationTime);
        }
Exemplo n.º 29
0
        public override void OnException(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            base.OnException(actionExecutedContext);

            Exception    e = actionExecutedContext.Exception;
            ActionResult result;

            if (e is AccessDenyException)
            {
                result = ((AccessDenyException)e).toActionResult();
            }
            else if (e is MSGorillaBaseException)
            {
                result = ((MSGorillaBaseException)e).toActionResult();
            }
            else
            {
                result = new MSGorillaBaseException().toActionResult();
                Trace.TraceError("Server internal error.", e);
            }

            //System.Net.Http.HttpContent
            actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest, result);
        }
Exemplo n.º 30
0
        public override void OnException(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            HttpStatusCode statusCode = HttpStatusCode.BadRequest;

            if (actionExecutedContext.ActionContext.Response != null)
            {
                statusCode = actionExecutedContext.ActionContext.Response.StatusCode;
            }
            base.OnException(actionExecutedContext);
            ApiResultModel result = new ApiResultModel();

            // 取得由 API 返回的状态代码
            result.Status  = statusCode;
            result.Err     = actionExecutedContext.Exception.FullMessage();
            result.Content = new ApiResponse()
            {
                Code       = -1,
                Err        = actionExecutedContext.Exception.FullMessage(),
                StackTrace = actionExecutedContext.Exception.FullStackTrace()
            };
            MonitorLog MolLog = null;

            if (actionExecutedContext.Request.Properties.ContainsKey(Constants.Custom_LogInfoKey))
            {
                MolLog = actionExecutedContext.Request.Properties[Constants.Custom_LogInfoKey] as MonitorLog;
            }
            if (null != MolLog)
            {
                LoggerHelper.Error(MolLog.GetLoginfo());
            }
            else
            {
                LoggerHelper.Error(actionExecutedContext.Exception.FullMessage());
            }
            actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(result.Status, result);
        }