Beispiel #1
0
        public object SaveComment(string commentText, string snippetId)
        {
            if (string.IsNullOrEmpty(commentText))
            {
                throw new InvalidOperationException("Please enter some comment text before submitting.");
            }

            using (busCodeSnippet Snippet = new busCodeSnippet())
            {
                if (Snippet.Load(snippetId) == null)
                {
                    throw new InvalidOperationException("Invalid snippet specified");
                }

                if (string.IsNullOrEmpty(this.AppUserState.Name))
                {
                    throw new UnauthorizedAccessException("You have to be signed in in order to add comments.");
                }

                if (!Snippet.AddComment(commentText, this.AppUserState.UserId))
                {
                    throw new ApplicationException("Couldn't add comment: " + Snippet.ErrorMessage);
                }
            }

            return(new
            {
                commentText = HtmlUtils.DisplayMemoEncoded(commentText),
                headerText = "by " + this.AppUserState.Name + "  " + TimeUtils.FriendlyDateString(DateTime.Now, true)
            });
        }
Beispiel #2
0
        /// <summary>
        /// /list/recent
        /// /list/tag/C#
        /// </summary>
        /// <param name="listAction"></param>
        /// <param name="listFilter"></param>
        /// <returns></returns>
        public ActionResult List(string listAction, string listFilter)
        {
            if (listAction == "MySnippets")
            {
                return(MySnippets());
            }
            else if (listAction == "MyFavorites")
            {
                return(MyFavorites());
            }

            using (busCodeSnippet busSnippet = new busCodeSnippet())
            {
                var snippetList = busSnippet.GetSnippetList(listAction, listFilter);
                busSnippet.Dispose();


                //if (listAction == "recent")
                //{
                //    // keep the snippetlist short
                //    if (snippetList != null)
                //        snippetList = snippetList.Take(20).ToList();
                //}
                this.ViewData["busSnippet"]  = busSnippet;
                this.ViewData["SnippetList"] = snippetList;

                if (listAction == "tag")
                {
                    this.ViewData["PageTitle"] = "Recent snippets matching tags of " + listFilter;
                    if (snippetList.Count < 1)
                    {
                        Response.StatusCode = 404;
                        ErrorController.ShowErrorPage("Invalid tag", "You've entered a tag that is not valid or has no related entries.");
                    }
                }
                else if (listAction == "language")
                {
                    this.ViewData["PageTitle"] = "Recent snippets matching language of " + listFilter;
                }
                else if (listAction == "user")
                {
                    if (snippetList.Count > 0)
                    {
                        this.ViewData["PageTitle"] = "Recent snippets for: " + snippetList.First().Author;
                    }
                    else
                    {
                        this.ViewData["PageTitle"] = "Recent snippets for user: "******"List"));
            }
        }
Beispiel #3
0
        public string SaveCode(string snippetId, string code)
        {
            using (busCodeSnippet busSnippet = new busCodeSnippet())
            {
                if (busSnippet.Load(snippetId) == null)
                {
                    throw new ArgumentException("Invalid snippetId passed.");
                }
                if (!IsEditAllowed(busSnippet.Entity) && !this.AppUserState.IsAdmin)
                {
                    throw new AccessViolationException("You are not allowed to edit this snippet.");
                }
                busSnippet.Entity.Code = StringUtils.NormalizeIndentation(code);

                if (busSnippet.IsSpam())
                {
                    throw new InvalidOperationException("Invalid content.");
                }

                if (!busSnippet.Save())
                {
                    throw new InvalidOperationException("Unable to save snippet: " + busSnippet.ErrorMessage);
                }
            }
            return("ok");
        }
Beispiel #4
0
 /// <summary>
 /// Returns a list of snippets for a given user's id
 /// </summary>
 /// <param name="userId">User id to return snippets for</param>
 /// <param name="count">Number of records to return. 0 returns 10 times default list size.</param>
 /// <returns></returns>
 public List <CodeSnippetListItem> GetSnippetsForUser(string userId, int count)
 {
     using (busCodeSnippet codeSnippet = CodePasteFactory.GetCodeSnippet())
     {
         return(codeSnippet.GetSnippetsForUser(userId, count));
     }
 }
Beispiel #5
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public ActionResult MyFavorites()
        {
            if (string.IsNullOrEmpty(this.AppUserState.UserId))
            {
                List <CodeSnippetListItem> snippetListEmpty = new List <CodeSnippetListItem>();
                this.ViewData["SnippetList"] = snippetListEmpty;
                this.ErrorDisplay.ShowError("You have to log in to see your favorites.");
                return(View());
            }

            using (busCodeSnippet busSnippet = new busCodeSnippet())
            {
                this.ViewData["busSnippet"] = busSnippet;
                var snippetList = busSnippet.GetFavorites(this.AppUserState.UserId);
                this.ViewData["SnippetList"] = snippetList;
                this.ViewData["PageTitle"]   = "My Favorites";
                ActionResult actionResult = this.ApiResult(snippetList);
                if (actionResult != null)
                {
                    return(actionResult);
                }
            }

            return(View());
        }
Beispiel #6
0
 /// <summary>
 /// Allows searching of snippets by providing a search parameter structure
 /// </summary>
 /// <returns></returns>
 public List <CodeSnippetListItem> SearchSnippets(CodeSnippetSearchParameters searchParameters)
 {
     using (busCodeSnippet codeSnippet = CodePasteFactory.GetCodeSnippet())
     {
         return(codeSnippet.GetSearchList(searchParameters).ToList());
     }
 }
Beispiel #7
0
 public List <CodeSnippetListItem> ListSnippets(string filter, string filterParameter)
 {
     using (busCodeSnippet codeSnippet = CodePasteFactory.GetCodeSnippet())
     {
         List <CodeSnippetListItem> snippets = codeSnippet.GetSnippetList(filter, filterParameter);
         return(snippets);
     }
 }
Beispiel #8
0
 /// <summary>
 /// Returns a list of recent snippets
 /// </summary>
 /// <returns></returns>
 public List <CodeSnippetListItem> GetRecentSnippets()
 {
     using (busCodeSnippet codeSnippet = CodePasteFactory.GetCodeSnippet())
     {
         List <CodeSnippetListItem> items = codeSnippet.GetSnippetList("recent", null);
         return(items);
     }
 }
Beispiel #9
0
 private void Scheduler_ExecuteScheduledEvent(object sender, EventArgs e)
 {
     try
     {
         var admin = new busCodeSnippet();
         admin.ClearAnonymousSnippets(App.Configuration.HoursToDeleteAnonymousSnippets, 9999999);
     }
     catch { }
 }
Beispiel #10
0
        public ActionResult AbuseSnippets()
        {
            var busSnippet = new busCodeSnippet();

            ViewBag.busSnippet = busSnippet;

            this.ViewModel.SnippetList = busSnippet.GetAbuseReportedSnippets();

            return View(this.ViewModel);
        }
Beispiel #11
0
        public ActionResult AbuseSnippets()
        {
            var busSnippet = new busCodeSnippet();

            ViewBag.busSnippet = busSnippet;

            ViewModel.SnippetList = busSnippet.GetAbuseReportedSnippets();

            return(View(ViewModel));
        }
Beispiel #12
0
 public string GetCode(string snippetId)
 {
     using (busCodeSnippet busSnippet = new busCodeSnippet())
     {
         if (busSnippet.Load(snippetId) == null)
         {
             throw new ArgumentException("Invalid snippetId passed.");
         }
         return(busSnippet.Entity.Code);
     }
 }
Beispiel #13
0
 /// <summary>
 /// Returns a new empty snippet to the client. The snippet
 /// contains a new id
 /// </summary>
 /// <returns></returns>
 public CodeSnippet GetNewSnippet()
 {
     using (busCodeSnippet codesnippet = CodePasteFactory.GetCodeSnippet())
     {
         if (codesnippet.NewEntity() == null)
         {
             this.ThrowException("Unable to load new snippet: " + codesnippet.ErrorMessage);
         }
         return(codesnippet.Entity);
     }
 }
Beispiel #14
0
        public bool AddFavorite(string title, string snippetId)
        {
            if (AppUserState.IsEmpty())
            {
                return(false);
            }

            using (var snippetBus = new busCodeSnippet())
            {
                return(snippetBus.AddFavorite(title, snippetId, AppUserState.UserId));
            }
        }
Beispiel #15
0
 /// <summary>
 /// Returns an individual snippet based on an id
 /// </summary>
 /// <param name="snippetId"></param>
 /// <returns></returns>
 public CodeSnippet GetSnippet(string id)
 {
     using (busCodeSnippet codesnippet = CodePasteFactory.GetCodeSnippet())
     {
         if (codesnippet.Load(id) == null)
         {
             this.ThrowException("Invalid code snippet id");
         }
         codesnippet.GetComments();
         codesnippet.StripSensitiveUserInformation();
         return(codesnippet.Entity);
     }
 }
Beispiel #16
0
 public ActionResult Feed()
 {
     using (busCodeSnippet busSnippet = new busCodeSnippet())
     {
         this.ViewData["busSnippet"] = busSnippet;
         var snippetList = busSnippet.GetSnippetList("recent", App.Configuration.MaxListDisplayCount.ToString());
         string format = Request.QueryString["Format"];
         if (string.IsNullOrEmpty(format))
             this.Format = "rss";
         ActionResult actionResult = this.ApiResult(snippetList);
         return actionResult;
     }
 }
Beispiel #17
0
 public ActionResult Feed()
 {
     using (busCodeSnippet busSnippet = new busCodeSnippet())
     {
         this.ViewData["busSnippet"] = busSnippet;
         var    snippetList = busSnippet.GetSnippetList("recent", App.Configuration.MaxListDisplayCount.ToString());
         string format      = Request.QueryString["Format"];
         if (string.IsNullOrEmpty(format))
         {
             this.Format = "rss";
         }
         ActionResult actionResult = this.ApiResult(snippetList);
         return(actionResult);
     }
 }
 public string SaveTitle(string snippetId,string newTitle)
 {
     using (busCodeSnippet busSnippet = new busCodeSnippet())
     {
         if (busSnippet.Load(snippetId) == null)
             throw new ArgumentException("Invalid snippetId passed.");
         if (!IsEditAllowed(busSnippet.Entity) && !AppUserState.IsAdmin)
             throw new AccessViolationException("You are not allowed to edit this snippet.");
         busSnippet.Entity.Title = newTitle;
         if (!busSnippet.Validate())
             throw new InvalidOperationException(busSnippet.ErrorMessage);
         if (!busSnippet.Save())
             throw new InvalidOperationException(busSnippet.ErrorMessage);
         return !string.IsNullOrEmpty(busSnippet.Entity.Title) ? busSnippet.Entity.Title : "No Title";
     }
 }
Beispiel #19
0
        public ActionResult ClearAnonymousSnippets()
        {
            busCodeSnippet codeSnippet = CodePasteFactory.GetCodeSnippet();
            int            result      = codeSnippet.ClearAnonymousSnippets(App.Configuration.HoursToDeleteAnonymousSnippets,
                                                                            App.Configuration.MinViewBeforeDeleteAnonymousSnippets);

            if (result < 0)
            {
                ErrorDisplay.ShowError(codeSnippet.ErrorMessage);
            }
            else
            {
                ErrorDisplay.ShowMessage((result).ToString() + " old snippets have been cleared out.");
            }

            return(View("Index", ViewModel));
        }
Beispiel #20
0
        /// <summary>
        /// Allows deletion of an individual snippet by the author.
        /// </summary>
        /// <param name="snippetId"></param>
        /// <param name="?"></param>
        /// <returns></returns>
        public bool DeleteSnippet(string snippetId, string sessionKey)
        {
            User user = this.ValidateToken(sessionKey);

            using (busCodeSnippet codeSnippet = CodePasteFactory.GetCodeSnippet())
            {
                if (codeSnippet.Load(snippetId) == null)
                {
                    this.ThrowException("Invalid snippet specified");
                }
                if (codeSnippet.Entity.UserId != user.Id)
                {
                    this.ThrowException("Access denied: You can only delete snippets you posted with this user account");
                }
                return(codeSnippet.Delete());
            }
        }
Beispiel #21
0
        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);


            //.RewriteRoutesForTesting(RouteTable.Routes);

            //JSONSerializer.DefaultJsonParserType = SupportedJsonParserTypes.JavaScriptSerializer;

            // Create a log manager based on setting in config file
            LogManager.Create();

            // Clear out expired anonymous snippets whenever app starts
            busCodeSnippet Snippet = new busCodeSnippet();

            Snippet.ClearAnonymousSnippets(App.Configuration.DaysToDeleteAnonymousSnippets,
                                           App.Configuration.MinViewBeforeDeleteAnonymousSnippets);
        }
Beispiel #22
0
        /// <summary>
        /// Allows posting of a new code snippet.
        /// </summary>
        /// <param name="snippet"></param>
        /// <param name="sessionKey"></param>
        /// <returns></returns>
        public CodeSnippet PostNewCodeSnippet(CodeSnippet snippet, string sessionKey)
        {
            User user = this.ValidateToken(sessionKey);

            using (busCodeSnippet codeSnippet = CodePasteFactory.GetCodeSnippet())
            {
                if (snippet == null)
                {
                    this.ThrowException("Invalid snippet instance data passed");
                }
                CodeSnippet newSnippet = codeSnippet.NewEntity();
                // Force userId regardless of what the user has set
                newSnippet.UserId = user.Id;
                newSnippet.Author = user.Name;
                if (string.IsNullOrEmpty(newSnippet.Author))
                {
                    newSnippet.Author = snippet.Author;
                }

                if (string.IsNullOrEmpty(snippet.Language))
                {
                    snippet.Language = "NoFormat";
                }

                DataUtils.CopyObjectData(snippet, newSnippet, "Id,UserId,Entered,Views,UserId,User,Author,Comments");

                if (!codeSnippet.Validate())
                {
                    this.ThrowException("Snippet validation failed: " + codeSnippet.ValidationErrors.ToString());
                }

                if (codeSnippet.IsSpam())
                {
                    this.ThrowException("Invalid Content.");
                }

                if (!codeSnippet.Save())
                {
                    this.ThrowException("Failed to save snippet: " + codeSnippet.ErrorMessage);
                }
                return(newSnippet);
            }
        }
Beispiel #23
0
        /// <summary>
        /// Displays a snippet as raw HTML
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ShowHtml(string id)
        {
            using (busCodeSnippet busSnippet = new busCodeSnippet())
            {
                var snippet = busSnippet.Load(id);

                if (snippet == null)
                {
                    return(new HttpNotFoundResult());
                }

                if (snippet.Language.ToLower() != "html")
                {
                    return(new HttpNotFoundResult("Invalid snippet type"));
                }

                return(this.Content(snippet.Code));
            }
        }
Beispiel #24
0
        public bool RemoveSnippet(string snippetId)
        {
            using (busCodeSnippet Snippet = new busCodeSnippet())
            {
                if (Snippet.Load(snippetId) == null)
                {
                    throw new InvalidOperationException("Unable to delete snippet");
                }

                if (!AppUserState.IsAdmin && !this.IsEditAllowed(Snippet.Entity))
                {
                    throw new UnauthorizedAccessException("Unauthorized Access: You have to be signed in as an administrator in delete snippets.");
                }

                Snippet.Delete();
            }

            return(true);
        }
Beispiel #25
0
 public string SaveLanguage(string snippetId, string lang)
 {
     using (busCodeSnippet busSnippet = new busCodeSnippet())
     {
         if (busSnippet.Load(snippetId) == null)
         {
             throw new ArgumentException("Invalid snippetId passed.");
         }
         if (!IsEditAllowed(busSnippet.Entity) && !AppUserState.IsAdmin)
         {
             throw new AccessViolationException("You are not allowed to edit this snippet.");
         }
         busSnippet.Entity.Language = lang;
         if (!busSnippet.Save())
         {
             throw new InvalidOperationException("Unable to save snippet: " + busSnippet.ErrorMessage);
         }
         return("ok");
     }
 }
Beispiel #26
0
 public string SaveTags(string snippetId, string tags)
 {
     using (busCodeSnippet busSnippet = new busCodeSnippet())
     {
         if (busSnippet.Load(snippetId) == null)
         {
             throw new ArgumentException("Invalid snippetId passed.");
         }
         if (!IsEditAllowed(busSnippet.Entity) && !AppUserState.IsAdmin)
         {
             throw new AccessViolationException("You are not allowed to edit this snippet.");
         }
         busSnippet.Entity.Tags = tags;
         if (!busSnippet.Save())
         {
             throw new InvalidOperationException("Unable to save snippet: " + busSnippet.ErrorMessage);
         }
         string tagResult = busSnippet.GetTagLinkList(tags);
         return(tagResult);
     }
 }
Beispiel #27
0
 public bool ReportAbuse(string snippetId)
 {
     using (busCodeSnippet busSnippet = new busCodeSnippet())
     {
         if (busSnippet.Load(snippetId) == null)
         {
             throw new ArgumentException("Invalid snippetId passed.");
         }
         var snippet = busSnippet.Entity;
         // switch value
         snippet.IsAbuse = !snippet.IsAbuse;
         if (snippet.IsAbuse)
         {
             AppWebUtils.SendEmail("CodePaste.NET Abuse: " + busSnippet.Entity.Title, "Abuse reported for this snippet \r\n\r\n" + WebUtils.ResolveServerUrl("~/" + busSnippet.Entity.Id), App.Configuration.AdminEmailAddress);
         }
         if (!busSnippet.Save())
         {
             throw new ApplicationException(busSnippet.ErrorMessage);
         }
         return(snippet.IsAbuse);
     }
 }
Beispiel #28
0
        public ActionResult CodeOnly(string id)
        {
            ShowSnippetViewModel model = new ShowSnippetViewModel(this);

            model.AppUserState = this.AppUserState;

            // Since this is our default handler anything invalid will
            // run through here. No path - go to new
            if (string.IsNullOrEmpty(id) || id == "0")
            {
                return(this.New());
            }

            using (busCodeSnippet busSnippet = new busCodeSnippet())
            {
                if (busSnippet.Load(id) == null)
                {
                    ErrorDisplay.ShowError("Invalid snippet id specified.");
                    model.Snippet = new CodeSnippet();
                    return(View(model));
                }

                model.Snippet = busSnippet.Entity;

                // Update the code so it's formatted
                model.FormattedCode = busSnippet.Entity.FormattedCode;

                if (!string.IsNullOrEmpty(AppUserState.UserId) && AppUserState.UserId == busSnippet.Entity.UserId || AppUserState.IsAdmin)
                {
                    model.AllowEdit = true;
                }

                ActionResult result = View(model);
                string       output = result.ToString();

                return(result);
            }
        }
Beispiel #29
0
        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);


            //.RewriteRoutesForTesting(RouteTable.Routes);

            //JSONSerializer.DefaultJsonParserType = SupportedJsonParserTypes.JavaScriptSerializer;

            // Create a log manager based on setting in config file
            LogManager.Create();

            // Clear out expired anonymous snippets whenever app starts
            busCodeSnippet Snippet = new busCodeSnippet();

            Snippet.ClearAnonymousSnippets(App.Configuration.HoursToDeleteAnonymousSnippets,
                                           App.Configuration.MinViewBeforeDeleteAnonymousSnippets);

            // Clear Anonymous snippets
            scheduler = new Scheduler();
            scheduler.CheckFrequency         = 3600 * 1000;
            scheduler.ExecuteScheduledEvent += Scheduler_ExecuteScheduledEvent;
        }
Beispiel #30
0
        public string SaveMainComment(string snippetId, string comment)
        {
            busCodeSnippet busSnippet = new busCodeSnippet();

            if (busSnippet.Load(snippetId) == null)
            {
                throw new ArgumentException("Invalid snippetId passed.");
            }

            if (!IsEditAllowed(busSnippet.Entity) && !AppUserState.IsAdmin)
            {
                throw new AccessViolationException("You are not allowed to edit this snippet.");
            }

            busSnippet.Entity.Comment = comment.Replace("\n", "\r\n");
            if (!busSnippet.Save())
            {
                throw new InvalidOperationException("Unable to save snippet: " + busSnippet.ErrorMessage);
            }

            string tagResult = HtmlUtils.DisplayMemo(comment);

            return(tagResult);
        }
Beispiel #31
0
 public string SaveTitle(string snippetId, string newTitle)
 {
     using (busCodeSnippet busSnippet = new busCodeSnippet())
     {
         if (busSnippet.Load(snippetId) == null)
         {
             throw new ArgumentException("Invalid snippetId passed.");
         }
         if (!IsEditAllowed(busSnippet.Entity) && !AppUserState.IsAdmin)
         {
             throw new AccessViolationException("You are not allowed to edit this snippet.");
         }
         busSnippet.Entity.Title = newTitle;
         if (!busSnippet.Validate())
         {
             throw new InvalidOperationException(busSnippet.ErrorMessage);
         }
         if (!busSnippet.Save())
         {
             throw new InvalidOperationException(busSnippet.ErrorMessage);
         }
         return(!string.IsNullOrEmpty(busSnippet.Entity.Title) ? busSnippet.Entity.Title : "No Title");
     }
 }
 public string SaveLanguage(string snippetId, string lang)
 {
     using (busCodeSnippet busSnippet = new busCodeSnippet())
     {
         if (busSnippet.Load(snippetId) == null)
             throw new ArgumentException("Invalid snippetId passed.");
         if (!IsEditAllowed(busSnippet.Entity) && !AppUserState.IsAdmin)
             throw new AccessViolationException("You are not allowed to edit this snippet.");
         busSnippet.Entity.Language = lang;
         if (!busSnippet.Save())
             throw new InvalidOperationException("Unable to save snippet: " + busSnippet.ErrorMessage);
         return "ok";
     }
 }
        /// <summary>
        /// Displays a snippet as raw HTML
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ShowHtml(string id)
        {
            using (busCodeSnippet busSnippet = new busCodeSnippet())
            {
                var snippet = busSnippet.Load(id);

                if (snippet == null)
                    return new HttpNotFoundResult();

                if (snippet.Language.ToLower() != "html")
                    return new HttpNotFoundResult("Invalid snippet type");

                return this.Content(snippet.Code);
            }
        }
Beispiel #34
0
        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);

            
            //.RewriteRoutesForTesting(RouteTable.Routes);

            //JSONSerializer.DefaultJsonParserType = SupportedJsonParserTypes.JavaScriptSerializer;

            // Create a log manager based on setting in config file
            LogManager.Create();

            // Clear out expired anonymous snippets whenever app starts
            busCodeSnippet Snippet = new busCodeSnippet();
            Snippet.ClearAnonymousSnippets(App.Configuration.DaysToDeleteAnonymousSnippets,
                                           App.Configuration.MinViewBeforeDeleteAnonymousSnippets);
        }
Beispiel #35
0
        public ActionResult Search(FormCollection formVars)
        {
            ListSnippetViewModel model = new ListSnippetViewModel(this);

            model.AppUserState = this.AppUserState;
            model.ErrorDisplay = this.ErrorDisplay;
            model.PageTitle    = "Search Code Snippets";

            model.SearchOrderItems = AppWebUtils.GetSelectListFromEnum(typeof(SearchOrderTypes), "Entered");

            using (busCodeSnippet busSnippet = new busCodeSnippet())
            {
                model.Controller = this;
                model.busSnippet = busSnippet;

                model.Parameters = new CodeSnippetSearchParameters();

                this.TryUpdateModel(model.Parameters);

                var snippetList      = busSnippet.GetSearchList(model.Parameters);
                int snippetListCount = 0;
                if (snippetList != null)
                {
                    snippetListCount = snippetList.Count();
                }

                if (formVars.Count > 0)
                {
                    if (snippetList == null)
                    {
                        this.ErrorDisplay.ShowError("Please provide at least one search criterion.");
                    }
                    else if (snippetListCount < 1)
                    {
                        this.ErrorDisplay.ShowError("No matches found for your search criteria.");
                    }
                }

                if (snippetList != null)
                {
                    model.Paging           = new PagingDetails();
                    model.Paging.PageCount = (int)Math.Ceiling(Convert.ToDecimal(snippetListCount) / Convert.ToDecimal(model.Paging.PageSize));

                    int.TryParse(Request.Params["page"] ?? "1", out model.Paging.Page);

                    if (model.Paging.Page > 0 && snippetListCount > model.Paging.PageSize)
                    {
                        snippetList = snippetList.Skip((model.Paging.Page - 1) * model.Paging.PageSize)
                                      .Take(model.Paging.PageSize);
                    }
                    model.SnippetList = snippetList.ToList();
                }
                else
                {
                    model.SnippetList = new List <CodeSnippetListItem>();
                }


                ActionResult result = this.ApiResult(model.SnippetList);
                if (result != null)
                {
                    return(result);
                }
            }

            return(View("Search", model));
        }
        public ActionResult ShowUrl()
        {
            string url = Request.QueryString["url"];
            string lang = Request.QueryString["language"];
            if (string.IsNullOrEmpty(lang))
                lang = Request.QueryString["lang"] ?? string.Empty;

            if (lang.ToLower() == "csharp")
                lang = "C#";                

            ShowSnippetViewModel model = new ShowSnippetViewModel(this);
            model.AppUserState = this.AppUserState;

            ViewData["originalUrl"] = url;
            ViewData["fileName"] = Path.GetFileName(url);
            ViewData["language"] = lang;

            if (string.IsNullOrEmpty(url))
            {
                ViewData["languageList"] = this.GetLanguageList(lang);
                return View(model);
            }

            HttpClient client = new HttpClient();
            client.Timeout = 4000;
            
            string result = client.DownloadString(url);

            if (result == null)            
                return 
                    this.DisplayErrorPage("Unable to retrieve Code Url", client.ErrorMessage, null);

            if (result.Length > App.Configuration.MaxCodeLength)
                return this.DisplayErrorPage("Snippet is too large", "Your code snippet to display is too long. Snippets can be no larger than " + App.Configuration.MaxCodeLength.ToString("n0") + " bytes.",null);

            busCodeSnippet snippetBusiness = new busCodeSnippet();

            if (string.IsNullOrEmpty(lang))
            {
                string extension = Path.GetExtension(url).ToLower();
                
                if (extension.StartsWith("."))
                    lang = extension.Substring(1);
            }

            model.FormattedCode = snippetBusiness.GetFormattedCode(result, lang, false, false);
            
            snippetBusiness.Dispose();

            return this.View(model);
        }
        /// <summary>
        /// /list/recent
        /// /list/tag/C#        
        /// </summary>
        /// <param name="listAction"></param>
        /// <param name="listFilter"></param>
        /// <returns></returns>        
        public ActionResult List(string listAction, string listFilter)
        {
            if (listAction == "MySnippets")
                return MySnippets();
            else if (listAction == "MyFavorites")
                return MyFavorites();

            using (busCodeSnippet busSnippet = new busCodeSnippet())
            {
                var snippetList = busSnippet.GetSnippetList(listAction, listFilter);
                busSnippet.Dispose();

                this.ViewData["busSnippet"] = busSnippet;
                this.ViewData["SnippetList"] = snippetList;

                if (listAction == "tag")
                {
                    this.ViewData["PageTitle"] = "Recent snippets matching tags of " + listFilter;
                    if (snippetList.Count < 1)
                    {
                        Response.StatusCode = 404;
                        ErrorController.ShowErrorPage("Invalid tag", "You've entered a tag that is not valid or has no related entries.");
                    }
                }
                else if (listAction == "language")
                    this.ViewData["PageTitle"] = "Recent snippets matching language of " + listFilter;
                else if (listAction == "user")
                {
                    if (snippetList.Count > 0)
                        this.ViewData["PageTitle"] = "Recent snippets for: " + snippetList.First().Author;
                    else
                        this.ViewData["PageTitle"] = "Recent snippets for user: "******"List");
            }
        }
Beispiel #38
0
        public ActionResult Show(string id)
        {
            ShowSnippetViewModel model = new ShowSnippetViewModel(this);

            model.AppUserState = AppUserState;

            // Since this is our default handler anything invalid will
            // run through here. No path - go to new
            if (string.IsNullOrEmpty(id) || id == "0")
            {
                return(this.New());
            }

            using (busCodeSnippet busSnippet = new busCodeSnippet())
            {
                var snippet = busSnippet.Load(id);
                if (snippet == null)
                {
                    return(this.DisplayErrorPage("Invalid Snippet Id specified",
                                                 "You specified a snippet id or link that is invalid and cannot be displayed. " +
                                                 "Please using the <a href='./recent' class='hoverbutton'>Recent Snippets</a> or " +
                                                 "<a href='mysnippets' class='hoverbutton'>My Snippets</a> buttons to look up valid snippets.", null));
                }

                bool allowWordWrap   = false;
                bool showLineNumbers = busSnippet.Entity.ShowLineNumbers;

                string ua = Request.UserAgent.ToLower();
                if (ua.Contains("iphone") ||
                    ua.Contains("blackberry") ||
                    ua.Contains("mobile"))
                {
                    allowWordWrap   = true;
                    showLineNumbers = false;
                }


                // Update the code so it's formatted
                model.FormattedCode = busSnippet.Entity.FormattedCode;
                if (!AppUserState.IsEmpty())
                {
                    model.IsFavoritedByUser = busSnippet.IsFavorite(busSnippet.Entity.Id, AppUserState.UserId);
                }


                if (!string.IsNullOrEmpty(AppUserState.UserId) &&
                    AppUserState.UserId == busSnippet.Entity.UserId || AppUserState.IsAdmin)
                {
                    model.AllowEdit = true;
                }

                // explicitly load up comments
                busSnippet.Entity.Comments = busSnippet.GetComments();

                // For API result we have to make sure email and password are not included
                if (!string.IsNullOrEmpty(Format) && snippet.User != null)
                {
                    busSnippet.StripSensitiveUserInformation();
                }
                if (snippet.User != null)
                {
                    if (!string.IsNullOrEmpty(snippet.User.Theme))
                    {
                        model.Theme = snippet.User.Theme;
                    }
                }

                ActionResult actionResult = this.ApiResult(busSnippet.Entity);
                if (actionResult != null)
                {
                    return(actionResult);
                }

                model.Snippet = busSnippet.Entity;

                // Fix up for Ace Editor
                model.Snippet.Language = busSnippet.FixUpLanguage(model.Snippet.Language).ToLower();

                // Log views for all but poster
                if (model.Snippet.User == null ||
                    model.Snippet.User.Id != AppUserState.UserId)
                {
                    busSnippet.LogSnippetView(busSnippet.Entity.Id, Request.UserHostAddress, Request.UserAgent);
                }

                return(View("Show", model));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult MyFavorites()
        {
            if (string.IsNullOrEmpty(this.AppUserState.UserId))
            {
                List<CodeSnippetListItem> snippetListEmpty = new List<CodeSnippetListItem>();
                this.ViewData["SnippetList"] = snippetListEmpty;
                this.ErrorDisplay.ShowError("You have to log in to see your favorites.");
                return View();
            }

            using (busCodeSnippet busSnippet = new busCodeSnippet())
            {
                this.ViewData["busSnippet"] = busSnippet;
                var snippetList = busSnippet.GetFavorites(this.AppUserState.UserId);
                this.ViewData["SnippetList"] = snippetList;
                this.ViewData["PageTitle"] = "My Favorites";
                ActionResult actionResult = this.ApiResult(snippetList);
                if (actionResult != null)
                    return actionResult;
            }

            return View();
        }
        public string SaveCode(string snippetId, string code )
        {
            using (busCodeSnippet busSnippet = new busCodeSnippet())
            {
                if (busSnippet.Load(snippetId) == null)
                    throw new ArgumentException("Invalid snippetId passed.");
                if (!IsEditAllowed(busSnippet.Entity) && !this.AppUserState.IsAdmin)
                    throw new AccessViolationException("You are not allowed to edit this snippet.");
                busSnippet.Entity.Code = StringUtils.NormalizeIndentation(code);

                if (busSnippet.IsSpam())
                    throw new InvalidOperationException("Invalid content.");

                if (!busSnippet.Save())
                    throw new InvalidOperationException("Unable to save snippet: " + busSnippet.ErrorMessage);
            }
            return "ok";
        }
 public bool ReportAbuse(string snippetId)
 {
     using (busCodeSnippet busSnippet = new busCodeSnippet())
     {
         if (busSnippet.Load(snippetId) == null)
             throw new ArgumentException("Invalid snippetId passed.");
         var snippet = busSnippet.Entity;
         // switch value
         snippet.IsAbuse = !snippet.IsAbuse;
         if (snippet.IsAbuse)
         {
             AppWebUtils.SendEmail("CodePaste.NET Abuse: " + busSnippet.Entity.Title, "Abuse reported for this snippet \r\n\r\n" + WebUtils.ResolveServerUrl("~/" + busSnippet.Entity.Id), App.Configuration.AdminEmailAddress);
         }
         if (!busSnippet.Save())
             throw new ApplicationException(busSnippet.ErrorMessage);
         return snippet.IsAbuse;
     }
 }
        public object SaveComment(string commentText, string snippetId)
        {
            if (string.IsNullOrEmpty(commentText))
                throw new InvalidOperationException("Please enter some comment text before submitting.");

            using (busCodeSnippet Snippet = new busCodeSnippet())
            {
                if (Snippet.Load(snippetId) == null)
                    throw new InvalidOperationException("Invalid snippet specified");

                if (string.IsNullOrEmpty(this.AppUserState.Name))
                    throw new UnauthorizedAccessException("You have to be signed in in order to add comments.");

                if (!Snippet.AddComment(commentText, this.AppUserState.UserId))
                    throw new ApplicationException("Couldn't add comment: " + Snippet.ErrorMessage);
            }

            return  new
            {
                commentText = HtmlUtils.DisplayMemoEncoded(commentText),
                headerText = "by " + this.AppUserState.Name + " &nbsp;" + TimeUtils.FriendlyDateString(DateTime.Now,true)
            };
        }
        public bool RemoveSnippet(string snippetId)
        {
            using (busCodeSnippet Snippet = new busCodeSnippet())
            {
                if (Snippet.Load(snippetId) == null)
                    throw new InvalidOperationException("Unable to delete snippet");

                if (!this.AppUserState.IsAdmin && !this.IsEditAllowed(Snippet.Entity))
                    throw new UnauthorizedAccessException("Unauthorized Access: You have to be signed in as an administrator in delete snippets.");

                Snippet.Delete();
            }

            return true;
        }
        public ActionResult CodeOnly(string id)
        {
            ShowSnippetViewModel model = new ShowSnippetViewModel(this);
            model.AppUserState = this.AppUserState;

            // Since this is our default handler anything invalid will
            // run through here. No path - go to new
            if (string.IsNullOrEmpty(id) || id == "0")
                return this.New();

            using (busCodeSnippet busSnippet = new busCodeSnippet())
            {
                if (busSnippet.Load(id) == null)
                {
                    ErrorDisplay.ShowError("Invalid snippet id specified.");
                    model.Snippet = new CodeSnippet();
                    return View(model);
                }

                model.Snippet = busSnippet.Entity;

                // Update the code so it's formatted
                model.FormattedCode = busSnippet.Entity.FormattedCode;

                if (!string.IsNullOrEmpty(AppUserState.UserId) && AppUserState.UserId == busSnippet.Entity.UserId || AppUserState.IsAdmin)
                    model.AllowEdit = true;

                ActionResult result = View(model);
                string output = result.ToString();

                return result;
            }
        }
 public string SaveTags(string snippetId, string tags)
 {
     using (busCodeSnippet busSnippet = new busCodeSnippet())
     {
         if (busSnippet.Load(snippetId) == null)
             throw new ArgumentException("Invalid snippetId passed.");
         if (!IsEditAllowed(busSnippet.Entity) && !AppUserState.IsAdmin)
             throw new AccessViolationException("You are not allowed to edit this snippet.");
         busSnippet.Entity.Tags = tags;
         if (!busSnippet.Save())
             throw new InvalidOperationException("Unable to save snippet: " + busSnippet.ErrorMessage);
         string tagResult = busSnippet.GetTagLinkList(tags);
         return tagResult;
     }
 }
        public ActionResult New(FormCollection formValues)
        {
            ViewData["UserState"] = AppUserState;
            ViewData["languageList"] = this.GetLanguageList();

            busCodeSnippet busSnippet = new busCodeSnippet();
            CodeSnippet snippet = busSnippet.NewEntity();
            if (snippet == null)
            {
                ErrorDisplay.ShowError("Couldn't load snippet");
                return View(new CodeSnippet());
            }

            UpdateModel(snippet);                      

            if (!ValidateForSpam(snippet))
            {
                this.ErrorDisplay.ShowError("Invalid data posted back.");
                return View(snippet);
            }
            
            if (!busSnippet.Validate())
            {
                foreach (ValidationError error in busSnippet.ValidationErrors)
                {
                    this.ErrorDisplay.AddMessage(error.Message, error.ControlID);
                }
                this.ErrorDisplay.ShowError("Please correct the following:");
                return View(snippet);
            }

            // Assign the user from the authenticated user if any - otherwise blank
            // in which case the user can't edit entries.
            snippet.UserId = this.AppUserState.UserId;

            // 
            if (!string.IsNullOrEmpty(snippet.UserId))
            {
                var userBus = new busUser();
                var user = userBus.Load(snippet.UserId);
                if (user.InActive)
                {
                    ErrorDisplay.HtmlEncodeMessage = false;
                    ErrorDisplay.ShowError(
@"Your email address has not been validated yet so you
can't create posts for this account yet. Please click 
the following link and then check your email for a
message to validate your email.<br><br>
<a href='" +  Url.Content("~/Account/ResetEmailValidation") + 
"' target='emailreset'>Send Validation Request Email</a>");

                    return View(snippet);
                }
            }

            // strip of leading indentation always when capturing a new snippet
            snippet.Code = StringUtils.NormalizeIndentation(snippet.Code);                            
                       
            if (!busSnippet.Save())
            {
                this.ErrorDisplay.ShowError("Couldn't save snippet: " + busSnippet.ErrorMessage);
                return View(snippet);
            }

            return this.RedirectToAction("Show", new { id = busSnippet.Entity.Id });
        }
        public string SaveMainComment(string snippetId, string comment)
        {
            busCodeSnippet busSnippet = new busCodeSnippet();
            if (busSnippet.Load(snippetId) == null)
                throw new ArgumentException("Invalid snippetId passed.");

            if (!IsEditAllowed(busSnippet.Entity) && !AppUserState.IsAdmin)
                throw new AccessViolationException("You are not allowed to edit this snippet.");

            busSnippet.Entity.Comment = comment.Replace("\n","\r\n");
            if (!busSnippet.Save())
                throw new InvalidOperationException("Unable to save snippet: " + busSnippet.ErrorMessage);

            string tagResult = HtmlUtils.DisplayMemo(comment);
            return tagResult;
        }
        public ActionResult Show(string id)
        {
            ShowSnippetViewModel model = new ShowSnippetViewModel(this);
            model.AppUserState = AppUserState;
            
            // Since this is our default handler anything invalid will
            // run through here. No path - go to new
            if (string.IsNullOrEmpty(id) || id == "0")
                return this.New();

            using (busCodeSnippet busSnippet = new busCodeSnippet())
            {
                var snippet = busSnippet.Load(id);
                if (snippet == null)
                {
                    return this.DisplayErrorPage("Invalid Snippet Id specified",
                        "You specified a snippet id or link that is invalid and cannot be displayed. " +
                        "Please using the <a href='./recent' class='hoverbutton'>Recent Snippets</a> or " +
                        "<a href='mysnippets' class='hoverbutton'>My Snippets</a> buttons to look up valid snippets.", null);
                }

                bool allowWordWrap = false;
                bool showLineNumbers = busSnippet.Entity.ShowLineNumbers;

                string ua = Request.UserAgent.ToLower();
                if (ua.Contains("iphone") ||
                    ua.Contains("blackberry") ||
                    ua.Contains("mobile"))
                {
                    allowWordWrap = true;
                    showLineNumbers = false;
                }
                

                // Update the code so it's formatted
                model.FormattedCode = busSnippet.Entity.FormattedCode;
                if (!AppUserState.IsEmpty())
                    model.IsFavoritedByUser = busSnippet.IsFavorite(busSnippet.Entity.Id, AppUserState.UserId);


                if (!string.IsNullOrEmpty(AppUserState.UserId) &&
                    AppUserState.UserId == busSnippet.Entity.UserId || AppUserState.IsAdmin)
                    model.AllowEdit = true;

                // explicitly load up comments
                busSnippet.Entity.Comments = busSnippet.GetComments();

                // For API result we have to make sure email and password are not included            
                if (!string.IsNullOrEmpty(Format) && snippet.User != null)
                {
                    busSnippet.StripSensitiveUserInformation();  
                }
                if (snippet.User != null)
                {
                    if (!string.IsNullOrEmpty(snippet.User.Theme))
                        model.Theme = snippet.User.Theme;
                }

                ActionResult actionResult = this.ApiResult(busSnippet.Entity);
                if (actionResult != null)
                    return actionResult;

                model.Snippet = busSnippet.Entity;

                // Fix up for Ace Editor
                model.Snippet.Language = busSnippet.FixUpLanguage(model.Snippet.Language).ToLower();

                // Log views for all but poster
                if (model.Snippet.User == null ||
                    model.Snippet.User.Id != AppUserState.UserId)
                    busSnippet.LogSnippetView(busSnippet.Entity.Id, Request.UserHostAddress, Request.UserAgent);

                return View("Show",model);
            }
        }
 public string GetCode(string snippetId)
 {
     using (busCodeSnippet busSnippet = new busCodeSnippet())
     {
         if (busSnippet.Load(snippetId) == null)
             throw new ArgumentException("Invalid snippetId passed.");
         return busSnippet.Entity.Code;
     }
 }
        public ActionResult Search(FormCollection formVars)
        {
            ListSnippetViewModel model = new ListSnippetViewModel(this);
            model.AppUserState = this.AppUserState;
            model.ErrorDisplay = this.ErrorDisplay;
            model.PageTitle = "Search Code Snippets";
            
            model.SearchOrderItems = AppWebUtils.GetSelectListFromEnum(typeof(SearchOrderTypes), "Entered");

            using (busCodeSnippet busSnippet = new busCodeSnippet())
            {
                model.Controller = this;
                model.busSnippet = busSnippet;

                model.Parameters = new CodeSnippetSearchParameters();

                this.TryUpdateModel(model.Parameters);

                var snippetList = busSnippet.GetSearchList(model.Parameters);
                int snippetListCount = 0;
                if (snippetList != null)
                    snippetListCount = snippetList.Count();

                if (formVars.Count > 0)
                {
                    if (snippetList == null)
                        this.ErrorDisplay.ShowError("Please provide at least one search criterion.");
                    else if (snippetListCount < 1)
                        this.ErrorDisplay.ShowError("No matches found for your search criteria.");
                }

                if (snippetList != null)
                {
                    model.Paging = new PagingDetails();
                    model.Paging.PageCount = (int)Math.Ceiling(Convert.ToDecimal(snippetListCount) / Convert.ToDecimal(model.Paging.PageSize));

                    int.TryParse(Request.Params["page"] ?? "1", out model.Paging.Page);

                    if (model.Paging.Page > 0 && snippetListCount > model.Paging.PageSize)
                    {
                        snippetList = snippetList.Skip((model.Paging.Page - 1) * model.Paging.PageSize)
                                                 .Take(model.Paging.PageSize);
                    }
                    model.SnippetList = snippetList.ToList();
                }
                else
                    model.SnippetList = new List<CodeSnippetListItem>();


                ActionResult result = this.ApiResult(model.SnippetList);
                if (result != null)
                    return result;
            }

            return View("Search",model);
        }
        public bool AddFavorite(string title, string snippetId)
        {
            if (AppUserState.IsEmpty())
                return false;

            using (var snippetBus = new busCodeSnippet())
            {
                return snippetBus.AddFavorite(title, snippetId, AppUserState.UserId);
            }
        }