(Part I) Removing the unhandled "catch" from module controllers. If there are "expected" exceptions, move them closer to the APIs where they occur.

--HG--
branch : 1.x
extra : transplant_source : %C9q%EC%E3%C3%E3%98QL%27%2B%D68%A9x%DD%40J%93A
This commit is contained in:
Suha Can
2011-06-08 16:26:58 -07:00
parent 51e43a624a
commit d83d922a6b
5 changed files with 319 additions and 382 deletions

View File

@@ -50,42 +50,37 @@ namespace Orchard.Comments.Controllers {
// Filtering
IContentQuery<CommentPart, CommentPartRecord> comments;
try {
switch (options.Filter) {
case CommentIndexFilter.All:
comments = _commentService.GetComments();
break;
case CommentIndexFilter.Approved:
comments = _commentService.GetComments(CommentStatus.Approved);
break;
case CommentIndexFilter.Pending:
comments = _commentService.GetComments(CommentStatus.Pending);
break;
case CommentIndexFilter.Spam:
comments = _commentService.GetComments(CommentStatus.Spam);
break;
default:
throw new ArgumentOutOfRangeException();
}
var pagerShape = Shape.Pager(pager).TotalItemCount(comments.Count());
var entries = comments
.OrderByDescending<CommentPartRecord, DateTime?>(cpr => cpr.CommentDateUtc)
.Slice(pager.GetStartIndex(), pager.PageSize)
.ToList()
.Select(comment => CreateCommentEntry(comment.Record));
var model = new CommentsIndexViewModel {
Comments = entries.ToList(),
Options = options,
Pager = pagerShape
};
return View(model);
} catch (Exception exception) {
this.Error(exception, T("Listing comments failed: {0}", exception.Message), Logger, Services.Notifier);
return View(new CommentsIndexViewModel());
switch (options.Filter) {
case CommentIndexFilter.All:
comments = _commentService.GetComments();
break;
case CommentIndexFilter.Approved:
comments = _commentService.GetComments(CommentStatus.Approved);
break;
case CommentIndexFilter.Pending:
comments = _commentService.GetComments(CommentStatus.Pending);
break;
case CommentIndexFilter.Spam:
comments = _commentService.GetComments(CommentStatus.Spam);
break;
default:
throw new ArgumentOutOfRangeException();
}
var pagerShape = Shape.Pager(pager).TotalItemCount(comments.Count());
var entries = comments
.OrderByDescending<CommentPartRecord, DateTime?>(cpr => cpr.CommentDateUtc)
.Slice(pager.GetStartIndex(), pager.PageSize)
.ToList()
.Select(comment => CreateCommentEntry(comment.Record));
var model = new CommentsIndexViewModel {
Comments = entries.ToList(),
Options = options,
Pager = pagerShape
};
return View(model);
}
[HttpPost]
@@ -94,51 +89,45 @@ namespace Orchard.Comments.Controllers {
var viewModel = new CommentsIndexViewModel { Comments = new List<CommentEntry>(), Options = new CommentIndexOptions() };
UpdateModel(viewModel);
try {
IEnumerable<CommentEntry> checkedEntries = viewModel.Comments.Where(c => c.IsChecked);
switch (viewModel.Options.BulkAction) {
case CommentIndexBulkAction.None:
break;
case CommentIndexBulkAction.MarkAsSpam:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
return new HttpUnauthorizedResult();
//TODO: Transaction
foreach (CommentEntry entry in checkedEntries) {
_commentService.MarkCommentAsSpam(entry.Comment.Id);
}
break;
case CommentIndexBulkAction.Unapprove:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
return new HttpUnauthorizedResult();
//TODO: Transaction
foreach (CommentEntry entry in checkedEntries) {
_commentService.UnapproveComment(entry.Comment.Id);
}
break;
case CommentIndexBulkAction.Approve:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
return new HttpUnauthorizedResult();
//TODO: Transaction
foreach (CommentEntry entry in checkedEntries) {
_commentService.ApproveComment(entry.Comment.Id);
}
break;
case CommentIndexBulkAction.Delete:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment")))
return new HttpUnauthorizedResult();
IEnumerable<CommentEntry> checkedEntries = viewModel.Comments.Where(c => c.IsChecked);
switch (viewModel.Options.BulkAction) {
case CommentIndexBulkAction.None:
break;
case CommentIndexBulkAction.MarkAsSpam:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
return new HttpUnauthorizedResult();
//TODO: Transaction
foreach (CommentEntry entry in checkedEntries) {
_commentService.MarkCommentAsSpam(entry.Comment.Id);
}
break;
case CommentIndexBulkAction.Unapprove:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
return new HttpUnauthorizedResult();
//TODO: Transaction
foreach (CommentEntry entry in checkedEntries) {
_commentService.UnapproveComment(entry.Comment.Id);
}
break;
case CommentIndexBulkAction.Approve:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
return new HttpUnauthorizedResult();
//TODO: Transaction
foreach (CommentEntry entry in checkedEntries) {
_commentService.ApproveComment(entry.Comment.Id);
}
break;
case CommentIndexBulkAction.Delete:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment")))
return new HttpUnauthorizedResult();
foreach (CommentEntry entry in checkedEntries) {
_commentService.DeleteComment(entry.Comment.Id);
}
break;
foreach (CommentEntry entry in checkedEntries) {
_commentService.DeleteComment(entry.Comment.Id);
}
break;
default:
throw new ArgumentOutOfRangeException();
}
} catch (Exception exception) {
this.Error(exception, T("Editing comments failed: {0}", exception.Message), Logger, Services.Notifier);
return RedirectToAction("Index", "Admin", new { options = viewModel.Options });
default:
throw new ArgumentOutOfRangeException();
}
return RedirectToAction("Index");
@@ -151,37 +140,31 @@ namespace Orchard.Comments.Controllers {
// Filtering
IContentQuery<CommentPart, CommentPartRecord> comments;
try {
switch (options.Filter) {
case CommentDetailsFilter.All:
comments = _commentService.GetCommentsForCommentedContent(id);
break;
case CommentDetailsFilter.Approved:
comments = _commentService.GetCommentsForCommentedContent(id, CommentStatus.Approved);
break;
case CommentDetailsFilter.Pending:
comments = _commentService.GetCommentsForCommentedContent(id, CommentStatus.Pending);
break;
case CommentDetailsFilter.Spam:
comments = _commentService.GetCommentsForCommentedContent(id, CommentStatus.Spam);
break;
default:
throw new ArgumentOutOfRangeException();
}
var entries = comments.List().Select(comment => CreateCommentEntry(comment.Record)).ToList();
var model = new CommentsDetailsViewModel {
Comments = entries,
Options = options,
DisplayNameForCommentedItem = _commentService.GetDisplayForCommentedContent(id) == null ? "" : _commentService.GetDisplayForCommentedContent(id).DisplayText,
CommentedItemId = id,
CommentsClosedOnItem = _commentService.CommentsDisabledForCommentedContent(id),
};
return View(model);
} catch (Exception exception) {
this.Error(exception, T("Listing comments failed: {0}", exception.Message), Logger, Services.Notifier);
return RedirectToAction("Index");
switch (options.Filter) {
case CommentDetailsFilter.All:
comments = _commentService.GetCommentsForCommentedContent(id);
break;
case CommentDetailsFilter.Approved:
comments = _commentService.GetCommentsForCommentedContent(id, CommentStatus.Approved);
break;
case CommentDetailsFilter.Pending:
comments = _commentService.GetCommentsForCommentedContent(id, CommentStatus.Pending);
break;
case CommentDetailsFilter.Spam:
comments = _commentService.GetCommentsForCommentedContent(id, CommentStatus.Spam);
break;
default:
throw new ArgumentOutOfRangeException();
}
var entries = comments.List().Select(comment => CreateCommentEntry(comment.Record)).ToList();
var model = new CommentsDetailsViewModel {
Comments = entries,
Options = options,
DisplayNameForCommentedItem = _commentService.GetDisplayForCommentedContent(id) == null ? "" : _commentService.GetDisplayForCommentedContent(id).DisplayText,
CommentedItemId = id,
CommentsClosedOnItem = _commentService.CommentsDisabledForCommentedContent(id),
};
return View(model);
}
[HttpPost]
@@ -190,51 +173,45 @@ namespace Orchard.Comments.Controllers {
var viewModel = new CommentsDetailsViewModel { Comments = new List<CommentEntry>(), Options = new CommentDetailsOptions() };
UpdateModel(viewModel);
try {
IEnumerable<CommentEntry> checkedEntries = viewModel.Comments.Where(c => c.IsChecked);
switch (viewModel.Options.BulkAction) {
case CommentDetailsBulkAction.None:
break;
case CommentDetailsBulkAction.MarkAsSpam:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
return new HttpUnauthorizedResult();
//TODO: Transaction
foreach (CommentEntry entry in checkedEntries) {
_commentService.MarkCommentAsSpam(entry.Comment.Id);
}
break;
case CommentDetailsBulkAction.Unapprove:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
return new HttpUnauthorizedResult();
IEnumerable<CommentEntry> checkedEntries = viewModel.Comments.Where(c => c.IsChecked);
switch (viewModel.Options.BulkAction) {
case CommentDetailsBulkAction.None:
break;
case CommentDetailsBulkAction.MarkAsSpam:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
return new HttpUnauthorizedResult();
//TODO: Transaction
foreach (CommentEntry entry in checkedEntries) {
_commentService.MarkCommentAsSpam(entry.Comment.Id);
}
break;
case CommentDetailsBulkAction.Unapprove:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
return new HttpUnauthorizedResult();
foreach (CommentEntry entry in checkedEntries) {
_commentService.UnapproveComment(entry.Comment.Id);
}
break;
case CommentDetailsBulkAction.Approve:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
return new HttpUnauthorizedResult();
foreach (CommentEntry entry in checkedEntries) {
_commentService.UnapproveComment(entry.Comment.Id);
}
break;
case CommentDetailsBulkAction.Approve:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
return new HttpUnauthorizedResult();
foreach (CommentEntry entry in checkedEntries) {
_commentService.ApproveComment(entry.Comment.Id);
}
break;
case CommentDetailsBulkAction.Delete:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment")))
return new HttpUnauthorizedResult();
foreach (CommentEntry entry in checkedEntries) {
_commentService.ApproveComment(entry.Comment.Id);
}
break;
case CommentDetailsBulkAction.Delete:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment")))
return new HttpUnauthorizedResult();
foreach (CommentEntry entry in checkedEntries) {
_commentService.DeleteComment(entry.Comment.Id);
}
break;
foreach (CommentEntry entry in checkedEntries) {
_commentService.DeleteComment(entry.Comment.Id);
}
break;
default:
throw new ArgumentOutOfRangeException();
}
} catch (Exception exception) {
this.Error(exception, T("Editing comments failed: {0}", exception.Message), Logger, Services.Notifier);
return Details(viewModel.CommentedItemId, viewModel.Options);
default:
throw new ArgumentOutOfRangeException();
}
return RedirectToAction("Index");
@@ -242,133 +219,108 @@ namespace Orchard.Comments.Controllers {
[HttpPost]
public ActionResult Disable(int commentedItemId, string returnUrl) {
try {
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't disable comments")))
return new HttpUnauthorizedResult();
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't disable comments")))
return new HttpUnauthorizedResult();
_commentService.DisableCommentsForCommentedContent(commentedItemId);
} catch (Exception exception) {
this.Error(exception, T("Disabling Comments failed: {0}", exception.Message), Logger, Services.Notifier);
}
_commentService.DisableCommentsForCommentedContent(commentedItemId);
return this.RedirectLocal(returnUrl, () => RedirectToAction("Index"));
}
[HttpPost]
public ActionResult Enable(int commentedItemId, string returnUrl) {
try {
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't enable comments")))
return new HttpUnauthorizedResult();
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't enable comments")))
return new HttpUnauthorizedResult();
_commentService.EnableCommentsForCommentedContent(commentedItemId);
} catch (Exception exception) {
this.Error(exception, T("Enabling Comments failed: {0}", exception.Message), Logger, Services.Notifier);
}
_commentService.EnableCommentsForCommentedContent(commentedItemId);
return this.RedirectLocal(returnUrl, () => RedirectToAction("Index"));
}
public ActionResult Edit(int id) {
try {
CommentPart commentPart = _commentService.GetComment(id);
var viewModel = new CommentsEditViewModel {
CommentText = commentPart.Record.CommentText,
Email = commentPart.Record.Email,
Id = commentPart.Record.Id,
Name = commentPart.Record.Author,
SiteName = commentPart.Record.SiteName,
Status = commentPart.Record.Status,
};
return View(viewModel);
CommentPart commentPart = _commentService.GetComment(id);
if (commentPart == null)
return new HttpNotFoundResult();
} catch (Exception exception) {
this.Error(exception, T("Editing comment failed: {0}", exception.Message), Logger, Services.Notifier);
return RedirectToAction("Index");
}
var viewModel = new CommentsEditViewModel {
CommentText = commentPart.Record.CommentText,
Email = commentPart.Record.Email,
Id = commentPart.Record.Id,
Name = commentPart.Record.Author,
SiteName = commentPart.Record.SiteName,
Status = commentPart.Record.Status,
};
return View(viewModel);
}
[HttpPost]
public ActionResult Edit(FormCollection input) {
var viewModel = new CommentsEditViewModel();
try {
UpdateModel(viewModel);
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't edit comment")))
return new HttpUnauthorizedResult();
UpdateModel(viewModel);
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't edit comment")))
return new HttpUnauthorizedResult();
_commentService.UpdateComment(viewModel.Id, viewModel.Name, viewModel.Email, viewModel.SiteName, viewModel.CommentText, viewModel.Status);
return RedirectToAction("Index");
} catch (Exception exception) {
this.Error(exception, T("Editing comment failed: {0}", exception.Message), Logger, Services.Notifier);
return View(viewModel);
}
_commentService.UpdateComment(viewModel.Id, viewModel.Name, viewModel.Email, viewModel.SiteName, viewModel.CommentText, viewModel.Status);
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Approve(int id, string returnUrl) {
try {
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't approve comment")))
return new HttpUnauthorizedResult();
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't approve comment")))
return new HttpUnauthorizedResult();
int commentedOn = _commentService.GetComment(id).Record.CommentedOn;
_commentService.ApproveComment(id);
var commentPart = _commentService.GetComment(id);
if (commentPart == null)
return new HttpNotFoundResult();
return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn }));
} catch (Exception exception) {
this.Error(exception, T("Approving comment failed: {0}", exception.Message), Logger, Services.Notifier);
int commentedOn = commentPart.Record.CommentedOn;
_commentService.ApproveComment(id);
return this.RedirectLocal(returnUrl, () => RedirectToAction("Index"));
}
return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn }));
}
[HttpPost]
public ActionResult Unapprove(int id, string returnUrl) {
try {
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't unapprove comment")))
return new HttpUnauthorizedResult();
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't unapprove comment")))
return new HttpUnauthorizedResult();
int commentedOn = _commentService.GetComment(id).Record.CommentedOn;
_commentService.UnapproveComment(id);
var commentPart = _commentService.GetComment(id);
if (commentPart == null)
return new HttpNotFoundResult();
return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn }));
} catch (Exception exception) {
this.Error(exception, T("Unapproving comment failed: {0}", exception.Message), Logger, Services.Notifier);
int commentedOn = commentPart.Record.CommentedOn;
_commentService.UnapproveComment(id);
return this.RedirectLocal(returnUrl, () => RedirectToAction("Index"));
}
return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn }));
}
[HttpPost]
public ActionResult MarkAsSpam(int id, string returnUrl) {
try {
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't mark comment as spam")))
return new HttpUnauthorizedResult();
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't mark comment as spam")))
return new HttpUnauthorizedResult();
int commentedOn = _commentService.GetComment(id).Record.CommentedOn;
_commentService.MarkCommentAsSpam(id);
var commentPart = _commentService.GetComment(id);
if (commentPart == null)
return new HttpNotFoundResult();
return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn }));
} catch (Exception exception) {
this.Error(exception, T("Marking comment as spam failed: {0}", exception.Message), Logger, Services.Notifier);
int commentedOn = commentPart.Record.CommentedOn;
_commentService.MarkCommentAsSpam(id);
return this.RedirectLocal(returnUrl, () => RedirectToAction("Index"));
}
return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn }));
}
[HttpPost]
public ActionResult Delete(int id, string returnUrl) {
try {
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment")))
return new HttpUnauthorizedResult();
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment")))
return new HttpUnauthorizedResult();
int commentedOn = _commentService.GetComment(id).Record.CommentedOn;
_commentService.DeleteComment(id);
var commentPart = _commentService.GetComment(id);
if (commentPart == null)
return new HttpNotFoundResult();
return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn }));
} catch (Exception exception) {
this.Error(exception, T("Deleting comment failed: {0}", exception.Message), Logger, Services.Notifier);
int commentedOn = commentPart.Record.CommentedOn;
_commentService.DeleteComment(id);
return this.RedirectLocal(returnUrl, () => RedirectToAction("Index"));
}
return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn }));
}
private CommentEntry CreateCommentEntry(CommentPartRecord commentPart) {

View File

@@ -50,23 +50,18 @@ namespace Orchard.Experimental.Controllers {
if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to use the web console")))
return new HttpUnauthorizedResult();
try {
using (var writer = new StringWriter()) {
var commandLine = model.CommandLine.Trim();
CommandParameters parameters = GetCommandParameters(commandLine, writer);
using (var writer = new StringWriter()) {
var commandLine = model.CommandLine.Trim();
CommandParameters parameters = GetCommandParameters(commandLine, writer);
_commandManager.Execute(parameters);
model.History = (model.History ?? Enumerable.Empty<string>())
.Concat(new[] {model.CommandLine})
.Distinct()
.ToArray();
model.Results = writer.ToString();
}
} catch(Exception exception) {
this.Error(exception, T("Error executing command: {0}", exception.Message), Logger, Services.Notifier);
Services.TransactionManager.Cancel();
_commandManager.Execute(parameters);
model.History = (model.History ?? Enumerable.Empty<string>())
.Concat(new[] {model.CommandLine})
.Distinct()
.ToArray();
model.Results = writer.ToString();
}
return View(model);
}

View File

@@ -36,19 +36,17 @@ namespace Orchard.ImportExport.Controllers {
if (!Services.Authorizer.Authorize(Permissions.Import, T("Not allowed to import.")))
return new HttpUnauthorizedResult();
try {
if (String.IsNullOrEmpty(Request.Files["RecipeFile"].FileName)) {
throw new ArgumentException(T("Please choose a recipe file to import.").Text);
}
_importExportService.Import(new StreamReader(Request.Files["RecipeFile"].InputStream).ReadToEnd());
if (String.IsNullOrEmpty(Request.Files["RecipeFile"].FileName)) {
ModelState.AddModelError("RecipeFile", T("Please choose a recipe file to import.").Text);
Services.Notifier.Error(T("Please choose a recipe file to import."));
}
if (ModelState.IsValid) {
_importExportService.Import(new StreamReader(Request.Files["RecipeFile"].InputStream).ReadToEnd());
Services.Notifier.Information(T("Your recipe has been imported."));
return RedirectToAction("Import");
}
catch (Exception exception) {
Services.Notifier.Error(T("Import failed: {0}", exception.Message));
return View();
}
return RedirectToAction("Import");
}
public ActionResult Export() {
@@ -66,21 +64,15 @@ namespace Orchard.ImportExport.Controllers {
var viewModel = new ExportViewModel { ContentTypes = new List<ContentTypeEntry>() };
try {
UpdateModel(viewModel);
var contentTypesToExport = viewModel.ContentTypes.Where(c => c.IsChecked).Select(c => c.ContentTypeName);
var exportOptions = new ExportOptions { ExportMetadata = viewModel.Metadata, ExportSiteSettings = viewModel.SiteSettings };
if (viewModel.Data) {
exportOptions.ExportData = true;
exportOptions.VersionHistoryOptions = (VersionHistoryOptions)Enum.Parse(typeof(VersionHistoryOptions), viewModel.DataImportChoice, true);
}
var exportFilePath = _importExportService.Export(contentTypesToExport, exportOptions);
return File(exportFilePath, "text/xml", "export.xml");
}
catch (Exception exception) {
Services.Notifier.Error(T("Export failed: {0}", exception.Message));
return View(viewModel);
UpdateModel(viewModel);
var contentTypesToExport = viewModel.ContentTypes.Where(c => c.IsChecked).Select(c => c.ContentTypeName);
var exportOptions = new ExportOptions { ExportMetadata = viewModel.Metadata, ExportSiteSettings = viewModel.SiteSettings };
if (viewModel.Data) {
exportOptions.ExportData = true;
exportOptions.VersionHistoryOptions = (VersionHistoryOptions)Enum.Parse(typeof(VersionHistoryOptions), viewModel.DataImportChoice, true);
}
var exportFilePath = _importExportService.Export(contentTypesToExport, exportOptions);
return File(exportFilePath, "text/xml", "export.xml");
}
}
}

View File

@@ -37,22 +37,22 @@ namespace Orchard.Media.Controllers {
[HttpPost]
public ActionResult Index(FormCollection input) {
try {
foreach (string key in input.Keys) {
if (key.StartsWith("Checkbox.") && input[key] == "true") {
string folderName = key.Substring("Checkbox.".Length);
if (!Services.Authorizer.Authorize(Permissions.ManageMedia, T("Couldn't delete media folder")))
return new HttpUnauthorizedResult();
foreach (string key in input.Keys) {
if (key.StartsWith("Checkbox.") && input[key] == "true") {
string folderName = key.Substring("Checkbox.".Length);
if (!Services.Authorizer.Authorize(Permissions.ManageMedia, T("Couldn't delete media folder")))
return new HttpUnauthorizedResult();
try {
_mediaService.DeleteFolder(folderName);
}
catch (Exception exception) {
Services.Notifier.Error(T("Deleting Folder failed: {0}", exception.Message));
return View();
}
}
return RedirectToAction("Index");
}
catch (Exception exception) {
this.Error(exception, T("Deleting Folder failed: {0}", exception.Message), Logger, Services.Notifier);
return View();
}
return RedirectToAction("Index");
}
public ActionResult Create(string mediaPath) {
@@ -65,19 +65,18 @@ namespace Orchard.Media.Controllers {
return new HttpUnauthorizedResult();
var viewModel = new MediaFolderCreateViewModel();
UpdateModel(viewModel);
try {
UpdateModel(viewModel);
_mediaService.CreateFolder(viewModel.MediaPath, viewModel.Name);
Services.Notifier.Information(T("Media folder created"));
return RedirectToAction("Index");
}
catch (Exception exception) {
this.Error(exception, T("Creating Folder failed: {0}", exception.Message), Logger, Services.Notifier);
catch(ArgumentException argumentException) {
Services.Notifier.Error(T("Creating Folder failed: {0}", argumentException.Message));
return View(viewModel);
}
return RedirectToAction("Index");
}
public ActionResult Edit(string name, string mediaPath) {
@@ -87,41 +86,45 @@ namespace Orchard.Media.Controllers {
var model = new MediaFolderEditViewModel { FolderName = name, MediaFiles = mediaFiles, MediaFolders = mediaFolders, MediaPath = mediaPath };
return View(model);
}
catch (Exception exception) {
this.Error(exception, T("Editing failed: {0}", exception.Message), Logger, Services.Notifier);
catch(ArgumentException exception) {
Services.Notifier.Error(T("Editing failed: {0}", exception.Message));
return RedirectToAction("Index");
}
}
[HttpPost]
public ActionResult Edit(FormCollection input) {
try {
foreach (string key in input.Keys) {
if (key.StartsWith("Checkbox.File.") && input[key] == "true") {
string fileName = key.Substring("Checkbox.File.".Length);
string folderName = input[fileName];
if (!Services.Authorizer.Authorize(Permissions.ManageMedia, T("Couldn't delete media file")))
return new HttpUnauthorizedResult();
_mediaService.DeleteFile(folderName, fileName);
foreach (string key in input.Keys) {
if (key.StartsWith("Checkbox.File.") && input[key] == "true") {
string fileName = key.Substring("Checkbox.File.".Length);
string folderName = input[fileName];
if (!Services.Authorizer.Authorize(Permissions.ManageMedia, T("Couldn't delete media file")))
return new HttpUnauthorizedResult();
try {
_mediaService.DeleteFile(folderName, fileName);
Services.Notifier.Information(T("Media file deleted"));
}
else if (key.StartsWith("Checkbox.Folder.") && input[key] == "true") {
string folderName = key.Substring("Checkbox.Folder.".Length);
string folderPath = input[folderName];
if (!Services.Authorizer.Authorize(Permissions.ManageMedia, T("Couldn't delete media folder")))
return new HttpUnauthorizedResult();
_mediaService.DeleteFolder(folderPath);
catch (ArgumentException argumentException) {
Services.Notifier.Error(T("Deleting failed: {0}", argumentException.Message));
}
}
else if (key.StartsWith("Checkbox.Folder.") && input[key] == "true") {
string folderName = key.Substring("Checkbox.Folder.".Length);
string folderPath = input[folderName];
if (!Services.Authorizer.Authorize(Permissions.ManageMedia, T("Couldn't delete media folder")))
return new HttpUnauthorizedResult();
try {
_mediaService.DeleteFolder(folderPath);
Services.Notifier.Information(T("Media folder deleted"));
}
catch(ArgumentException argumentException) {
Services.Notifier.Error(T("Deleting failed: {0}", argumentException.Message));
}
}
return RedirectToAction("Index");
} catch (Exception exception) {
this.Error(exception, T("Deleting failed: {0}", exception.Message), Logger, Services.Notifier);
return RedirectToAction("Index");
}
return RedirectToAction("Index");
}
public ActionResult EditProperties(string folderName, string mediaPath) {
@@ -136,18 +139,17 @@ namespace Orchard.Media.Controllers {
return new HttpUnauthorizedResult();
var viewModel = new MediaFolderEditPropertiesViewModel();
UpdateModel(viewModel);
try {
UpdateModel(viewModel);
_mediaService.DeleteFolder(viewModel.MediaPath);
Services.Notifier.Information(T("Media folder deleted"));
return RedirectToAction("Index");
} catch (Exception exception) {
this.Error(exception, T("Deleting media folder failed: {0}", exception.Message), Logger, Services.Notifier);
}
catch(ArgumentException argumentException) {
Services.Notifier.Error(T("Deleting media folder failed: {0}", argumentException.Message));
return View(viewModel);
}
return RedirectToAction("Index");
}
[HttpPost, ActionName("EditProperties")]
@@ -157,18 +159,17 @@ namespace Orchard.Media.Controllers {
return new HttpUnauthorizedResult();
var viewModel = new MediaFolderEditPropertiesViewModel();
UpdateModel(viewModel);
try {
UpdateModel(viewModel);
_mediaService.RenameFolder(viewModel.MediaPath, viewModel.Name);
Services.Notifier.Information(T("Media folder properties modified"));
return RedirectToAction("Index");
} catch (Exception exception) {
this.Error(exception, T("Modifying media folder properties failed: {0}", exception.Message), Logger, Services.Notifier);
}
catch(ArgumentException argumentException) {
Services.Notifier.Error(T("Modifying media folder properties failed: {0}", argumentException.Message));
return View(viewModel);
}
return RedirectToAction("Index");
}
public ActionResult Add(string folderName, string mediaPath) {
@@ -182,27 +183,28 @@ namespace Orchard.Media.Controllers {
return new HttpUnauthorizedResult();
var viewModel = new MediaItemAddViewModel();
try {
UpdateModel(viewModel);
if(String.IsNullOrWhiteSpace(Request.Files[0].FileName)) {
ModelState.AddModelError("File", T("Select a file to upload").ToString());
}
UpdateModel(viewModel);
if (!ModelState.IsValid)
return View(viewModel);
if(String.IsNullOrWhiteSpace(Request.Files[0].FileName)) {
ModelState.AddModelError("File", T("Select a file to upload").ToString());
}
foreach (string fileName in Request.Files) {
if (!ModelState.IsValid)
return View(viewModel);
foreach (string fileName in Request.Files) {
try {
_mediaService.UploadMediaFile(viewModel.MediaPath, Request.Files[fileName], viewModel.ExtractZip);
}
Services.Notifier.Information(T("Media file(s) uploaded"));
return RedirectToAction("Edit", new { name = viewModel.FolderName, mediaPath = viewModel.MediaPath });
} catch (Exception exception) {
this.Error(exception, T("Uploading media file failed:"), Logger, Services.Notifier);
return View(viewModel);
catch (ArgumentException argumentException) {
Services.Notifier.Error(T("Uploading media file failed:"));
return View(viewModel);
}
}
Services.Notifier.Information(T("Media file(s) uploaded"));
return RedirectToAction("Edit", new { name = viewModel.FolderName, mediaPath = viewModel.MediaPath });
}
[HttpPost]
@@ -211,27 +213,27 @@ namespace Orchard.Media.Controllers {
return Content(string.Format("<script type=\"text/javascript\">var result = {{ error: \"{0}\" }};</script>", T("ERROR: You don't have permission to upload media files")));
var viewModel = new MediaItemAddViewModel();
UpdateModel(viewModel);
if (Request.Files.Count < 1 || Request.Files[0].ContentLength == 0)
return Content(string.Format("<script type=\"text/javascript\">var result = {{ error: \"{0}\" }};</script>", T("HEY: You didn't give me a file to upload")));
try {
UpdateModel(viewModel);
_mediaService.GetMediaFiles(viewModel.MediaPath);
}
catch //media api needs a little work, like everything else of course ;) <- ;) == my stuff included. to clarify I need a way to know if the path exists or have UploadMediaFile create paths as necessary but there isn't the time to hook that up in the near future
{
_mediaService.CreateFolder("", viewModel.MediaPath);
}
if (Request.Files.Count < 1 || Request.Files[0].ContentLength == 0)
return Content(string.Format("<script type=\"text/javascript\">var result = {{ error: \"{0}\" }};</script>", T("HEY: You didn't give me a file to upload")));
try {
_mediaService.GetMediaFiles(viewModel.MediaPath);
}
catch //media api needs a little work, like everything else of course ;) <- ;) == my stuff included. to clarify I need a way to know if the path exists or have UploadMediaFile create paths as necessary but there isn't the time to hook that up in the near future
{
_mediaService.CreateFolder("", viewModel.MediaPath);
}
var file = Request.Files[0];
var file = Request.Files[0];
try {
var publicUrl = _mediaService.UploadMediaFile(viewModel.MediaPath, file, viewModel.ExtractZip);
return Content(string.Format("<script type=\"text/javascript\">var result = {{ url: \"{0}\" }};</script>", publicUrl));
}
catch (Exception exception) {
return Content(string.Format("<script type=\"text/javascript\">var result = {{ error: \"{0}\" }};</script>", T("ERROR: Uploading media file failed: {0}", exception.Message)));
catch (ArgumentException argumentException) {
return Content(string.Format("<script type=\"text/javascript\">var result = {{ error: \"{0}\" }};</script>", T("ERROR: Uploading media file failed: {0}", argumentException.Message)));
}
}
@@ -247,18 +249,17 @@ namespace Orchard.Media.Controllers {
return new HttpUnauthorizedResult();
var viewModel = new MediaItemEditViewModel();
UpdateModel(viewModel);
try {
UpdateModel(viewModel);
_mediaService.DeleteFile(viewModel.Name, viewModel.MediaPath);
Services.Notifier.Information(T("Media deleted"));
return RedirectToAction("Edit", new { name = viewModel.FolderName, mediaPath = viewModel.MediaPath });
} catch (Exception exception) {
this.Error(exception, T("Removing media file failed: {0}", exception.Message), Logger, Services.Notifier);
}
catch (ArgumentException argumentException) {
Services.Notifier.Error(T("Removing media file failed: {0}", argumentException.Message));
return View(viewModel);
}
return RedirectToAction("Edit", new { name = viewModel.FolderName, mediaPath = viewModel.MediaPath });
}
[HttpPost, ActionName("EditMedia")]
@@ -268,28 +269,28 @@ namespace Orchard.Media.Controllers {
return new HttpUnauthorizedResult();
var viewModel = new MediaItemEditViewModel();
try {
UpdateModel(viewModel);
string viewModelName = viewModel.Name;
UpdateModel(viewModel);
string viewModelName = viewModel.Name;
// Rename
if (!String.Equals(viewModel.Name, input["NewName"], StringComparison.OrdinalIgnoreCase)) {
// Rename
if (!String.Equals(viewModel.Name, input["NewName"], StringComparison.OrdinalIgnoreCase)) {
try {
_mediaService.RenameFile(viewModel.MediaPath, viewModel.Name, input["NewName"]);
viewModelName = input["NewName"];
}
catch (ArgumentException argumentException) {
Services.Notifier.Error(T("Editing media file failed."));
return EditMedia(viewModel);
}
viewModelName = input["NewName"];
}
Services.Notifier.Information(T("Media information updated"));
return RedirectToAction("EditMedia", new { name = viewModelName,
caption = viewModel.Caption,
lastUpdated = viewModel.LastUpdated,
size = viewModel.Size,
folderName = viewModel.FolderName,
mediaPath = viewModel.MediaPath });
}
catch (Exception exception) {
this.Error(exception, T("Editing media file failed."), Logger, Services.Notifier);
return EditMedia(viewModel);
}
Services.Notifier.Information(T("Media information updated"));
return RedirectToAction("EditMedia", new { name = viewModelName,
caption = viewModel.Caption,
lastUpdated = viewModel.LastUpdated,
size = viewModel.Size,
folderName = viewModel.FolderName,
mediaPath = viewModel.MediaPath });
}
}
}

View File

@@ -1,13 +1,10 @@
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using Orchard.Localization;
using Orchard.Media;
using Orchard.Media.Models;
using Orchard.Media.Services;
using Orchard.Media.ViewModels;
using Orchard.Security;
using Orchard.Themes;
namespace Orchard.MediaPicker.Controllers {