(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 // Filtering
IContentQuery<CommentPart, CommentPartRecord> comments; IContentQuery<CommentPart, CommentPartRecord> comments;
try { switch (options.Filter) {
switch (options.Filter) { case CommentIndexFilter.All:
case CommentIndexFilter.All: comments = _commentService.GetComments();
comments = _commentService.GetComments(); break;
break; case CommentIndexFilter.Approved:
case CommentIndexFilter.Approved: comments = _commentService.GetComments(CommentStatus.Approved);
comments = _commentService.GetComments(CommentStatus.Approved); break;
break; case CommentIndexFilter.Pending:
case CommentIndexFilter.Pending: comments = _commentService.GetComments(CommentStatus.Pending);
comments = _commentService.GetComments(CommentStatus.Pending); break;
break; case CommentIndexFilter.Spam:
case CommentIndexFilter.Spam: comments = _commentService.GetComments(CommentStatus.Spam);
comments = _commentService.GetComments(CommentStatus.Spam); break;
break; default:
default: throw new ArgumentOutOfRangeException();
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());
} }
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] [HttpPost]
@@ -94,51 +89,45 @@ namespace Orchard.Comments.Controllers {
var viewModel = new CommentsIndexViewModel { Comments = new List<CommentEntry>(), Options = new CommentIndexOptions() }; var viewModel = new CommentsIndexViewModel { Comments = new List<CommentEntry>(), Options = new CommentIndexOptions() };
UpdateModel(viewModel); UpdateModel(viewModel);
try { IEnumerable<CommentEntry> checkedEntries = viewModel.Comments.Where(c => c.IsChecked);
IEnumerable<CommentEntry> checkedEntries = viewModel.Comments.Where(c => c.IsChecked); switch (viewModel.Options.BulkAction) {
switch (viewModel.Options.BulkAction) { case CommentIndexBulkAction.None:
case CommentIndexBulkAction.None: break;
break; case CommentIndexBulkAction.MarkAsSpam:
case CommentIndexBulkAction.MarkAsSpam: if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) return new HttpUnauthorizedResult();
return new HttpUnauthorizedResult(); //TODO: Transaction
//TODO: Transaction foreach (CommentEntry entry in checkedEntries) {
foreach (CommentEntry entry in checkedEntries) { _commentService.MarkCommentAsSpam(entry.Comment.Id);
_commentService.MarkCommentAsSpam(entry.Comment.Id); }
} break;
break; case CommentIndexBulkAction.Unapprove:
case CommentIndexBulkAction.Unapprove: if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) return new HttpUnauthorizedResult();
return new HttpUnauthorizedResult(); //TODO: Transaction
//TODO: Transaction foreach (CommentEntry entry in checkedEntries) {
foreach (CommentEntry entry in checkedEntries) { _commentService.UnapproveComment(entry.Comment.Id);
_commentService.UnapproveComment(entry.Comment.Id); }
} break;
break; case CommentIndexBulkAction.Approve:
case CommentIndexBulkAction.Approve: if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) return new HttpUnauthorizedResult();
return new HttpUnauthorizedResult(); //TODO: Transaction
//TODO: Transaction foreach (CommentEntry entry in checkedEntries) {
foreach (CommentEntry entry in checkedEntries) { _commentService.ApproveComment(entry.Comment.Id);
_commentService.ApproveComment(entry.Comment.Id); }
} break;
break; case CommentIndexBulkAction.Delete:
case CommentIndexBulkAction.Delete: if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment")))
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment"))) return new HttpUnauthorizedResult();
return new HttpUnauthorizedResult();
foreach (CommentEntry entry in checkedEntries) { foreach (CommentEntry entry in checkedEntries) {
_commentService.DeleteComment(entry.Comment.Id); _commentService.DeleteComment(entry.Comment.Id);
} }
break; break;
default: default:
throw new ArgumentOutOfRangeException(); 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 });
} }
return RedirectToAction("Index"); return RedirectToAction("Index");
@@ -151,37 +140,31 @@ namespace Orchard.Comments.Controllers {
// Filtering // Filtering
IContentQuery<CommentPart, CommentPartRecord> comments; IContentQuery<CommentPart, CommentPartRecord> comments;
try { switch (options.Filter) {
switch (options.Filter) { case CommentDetailsFilter.All:
case CommentDetailsFilter.All: comments = _commentService.GetCommentsForCommentedContent(id);
comments = _commentService.GetCommentsForCommentedContent(id); break;
break; case CommentDetailsFilter.Approved:
case CommentDetailsFilter.Approved: comments = _commentService.GetCommentsForCommentedContent(id, CommentStatus.Approved);
comments = _commentService.GetCommentsForCommentedContent(id, CommentStatus.Approved); break;
break; case CommentDetailsFilter.Pending:
case CommentDetailsFilter.Pending: comments = _commentService.GetCommentsForCommentedContent(id, CommentStatus.Pending);
comments = _commentService.GetCommentsForCommentedContent(id, CommentStatus.Pending); break;
break; case CommentDetailsFilter.Spam:
case CommentDetailsFilter.Spam: comments = _commentService.GetCommentsForCommentedContent(id, CommentStatus.Spam);
comments = _commentService.GetCommentsForCommentedContent(id, CommentStatus.Spam); break;
break; default:
default: throw new ArgumentOutOfRangeException();
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");
} }
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] [HttpPost]
@@ -190,51 +173,45 @@ namespace Orchard.Comments.Controllers {
var viewModel = new CommentsDetailsViewModel { Comments = new List<CommentEntry>(), Options = new CommentDetailsOptions() }; var viewModel = new CommentsDetailsViewModel { Comments = new List<CommentEntry>(), Options = new CommentDetailsOptions() };
UpdateModel(viewModel); UpdateModel(viewModel);
try { IEnumerable<CommentEntry> checkedEntries = viewModel.Comments.Where(c => c.IsChecked);
IEnumerable<CommentEntry> checkedEntries = viewModel.Comments.Where(c => c.IsChecked); switch (viewModel.Options.BulkAction) {
switch (viewModel.Options.BulkAction) { case CommentDetailsBulkAction.None:
case CommentDetailsBulkAction.None: break;
break; case CommentDetailsBulkAction.MarkAsSpam:
case CommentDetailsBulkAction.MarkAsSpam: if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) return new HttpUnauthorizedResult();
return new HttpUnauthorizedResult(); //TODO: Transaction
//TODO: Transaction foreach (CommentEntry entry in checkedEntries) {
foreach (CommentEntry entry in checkedEntries) { _commentService.MarkCommentAsSpam(entry.Comment.Id);
_commentService.MarkCommentAsSpam(entry.Comment.Id); }
} break;
break; case CommentDetailsBulkAction.Unapprove:
case CommentDetailsBulkAction.Unapprove: if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) return new HttpUnauthorizedResult();
return new HttpUnauthorizedResult();
foreach (CommentEntry entry in checkedEntries) { foreach (CommentEntry entry in checkedEntries) {
_commentService.UnapproveComment(entry.Comment.Id); _commentService.UnapproveComment(entry.Comment.Id);
} }
break; break;
case CommentDetailsBulkAction.Approve: case CommentDetailsBulkAction.Approve:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment")))
return new HttpUnauthorizedResult(); return new HttpUnauthorizedResult();
foreach (CommentEntry entry in checkedEntries) { foreach (CommentEntry entry in checkedEntries) {
_commentService.ApproveComment(entry.Comment.Id); _commentService.ApproveComment(entry.Comment.Id);
} }
break; break;
case CommentDetailsBulkAction.Delete: case CommentDetailsBulkAction.Delete:
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment"))) if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment")))
return new HttpUnauthorizedResult(); return new HttpUnauthorizedResult();
foreach (CommentEntry entry in checkedEntries) { foreach (CommentEntry entry in checkedEntries) {
_commentService.DeleteComment(entry.Comment.Id); _commentService.DeleteComment(entry.Comment.Id);
} }
break; break;
default: default:
throw new ArgumentOutOfRangeException(); 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);
} }
return RedirectToAction("Index"); return RedirectToAction("Index");
@@ -242,133 +219,108 @@ namespace Orchard.Comments.Controllers {
[HttpPost] [HttpPost]
public ActionResult Disable(int commentedItemId, string returnUrl) { public ActionResult Disable(int commentedItemId, string returnUrl) {
try { if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't disable comments")))
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't disable comments"))) return new HttpUnauthorizedResult();
return new HttpUnauthorizedResult();
_commentService.DisableCommentsForCommentedContent(commentedItemId); _commentService.DisableCommentsForCommentedContent(commentedItemId);
} catch (Exception exception) {
this.Error(exception, T("Disabling Comments failed: {0}", exception.Message), Logger, Services.Notifier);
}
return this.RedirectLocal(returnUrl, () => RedirectToAction("Index")); return this.RedirectLocal(returnUrl, () => RedirectToAction("Index"));
} }
[HttpPost] [HttpPost]
public ActionResult Enable(int commentedItemId, string returnUrl) { public ActionResult Enable(int commentedItemId, string returnUrl) {
try { if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't enable comments")))
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't enable comments"))) return new HttpUnauthorizedResult();
return new HttpUnauthorizedResult();
_commentService.EnableCommentsForCommentedContent(commentedItemId); _commentService.EnableCommentsForCommentedContent(commentedItemId);
} catch (Exception exception) {
this.Error(exception, T("Enabling Comments failed: {0}", exception.Message), Logger, Services.Notifier);
}
return this.RedirectLocal(returnUrl, () => RedirectToAction("Index")); return this.RedirectLocal(returnUrl, () => RedirectToAction("Index"));
} }
public ActionResult Edit(int id) { public ActionResult Edit(int id) {
try { CommentPart commentPart = _commentService.GetComment(id);
CommentPart commentPart = _commentService.GetComment(id); if (commentPart == null)
var viewModel = new CommentsEditViewModel { return new HttpNotFoundResult();
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);
} catch (Exception exception) { var viewModel = new CommentsEditViewModel {
this.Error(exception, T("Editing comment failed: {0}", exception.Message), Logger, Services.Notifier); CommentText = commentPart.Record.CommentText,
Email = commentPart.Record.Email,
return RedirectToAction("Index"); Id = commentPart.Record.Id,
} Name = commentPart.Record.Author,
SiteName = commentPart.Record.SiteName,
Status = commentPart.Record.Status,
};
return View(viewModel);
} }
[HttpPost] [HttpPost]
public ActionResult Edit(FormCollection input) { public ActionResult Edit(FormCollection input) {
var viewModel = new CommentsEditViewModel(); var viewModel = new CommentsEditViewModel();
try { UpdateModel(viewModel);
UpdateModel(viewModel); if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't edit comment")))
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't edit comment"))) return new HttpUnauthorizedResult();
return new HttpUnauthorizedResult();
_commentService.UpdateComment(viewModel.Id, viewModel.Name, viewModel.Email, viewModel.SiteName, viewModel.CommentText, viewModel.Status); _commentService.UpdateComment(viewModel.Id, viewModel.Name, viewModel.Email, viewModel.SiteName, viewModel.CommentText, viewModel.Status);
return RedirectToAction("Index"); return RedirectToAction("Index");
} catch (Exception exception) {
this.Error(exception, T("Editing comment failed: {0}", exception.Message), Logger, Services.Notifier);
return View(viewModel);
}
} }
[HttpPost] [HttpPost]
public ActionResult Approve(int id, string returnUrl) { public ActionResult Approve(int id, string returnUrl) {
try { if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't approve comment")))
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't approve comment"))) return new HttpUnauthorizedResult();
return new HttpUnauthorizedResult();
int commentedOn = _commentService.GetComment(id).Record.CommentedOn; var commentPart = _commentService.GetComment(id);
_commentService.ApproveComment(id); if (commentPart == null)
return new HttpNotFoundResult();
return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn })); int commentedOn = commentPart.Record.CommentedOn;
} catch (Exception exception) { _commentService.ApproveComment(id);
this.Error(exception, T("Approving comment failed: {0}", exception.Message), Logger, Services.Notifier);
return this.RedirectLocal(returnUrl, () => RedirectToAction("Index")); return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn }));
}
} }
[HttpPost] [HttpPost]
public ActionResult Unapprove(int id, string returnUrl) { public ActionResult Unapprove(int id, string returnUrl) {
try { if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't unapprove comment")))
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't unapprove comment"))) return new HttpUnauthorizedResult();
return new HttpUnauthorizedResult();
int commentedOn = _commentService.GetComment(id).Record.CommentedOn; var commentPart = _commentService.GetComment(id);
_commentService.UnapproveComment(id); if (commentPart == null)
return new HttpNotFoundResult();
return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn })); int commentedOn = commentPart.Record.CommentedOn;
} catch (Exception exception) { _commentService.UnapproveComment(id);
this.Error(exception, T("Unapproving comment failed: {0}", exception.Message), Logger, Services.Notifier);
return this.RedirectLocal(returnUrl, () => RedirectToAction("Index")); return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn }));
}
} }
[HttpPost] [HttpPost]
public ActionResult MarkAsSpam(int id, string returnUrl) { public ActionResult MarkAsSpam(int id, string returnUrl) {
try { if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't mark comment as spam")))
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't mark comment as spam"))) return new HttpUnauthorizedResult();
return new HttpUnauthorizedResult();
int commentedOn = _commentService.GetComment(id).Record.CommentedOn; var commentPart = _commentService.GetComment(id);
_commentService.MarkCommentAsSpam(id); if (commentPart == null)
return new HttpNotFoundResult();
return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn })); int commentedOn = commentPart.Record.CommentedOn;
} catch (Exception exception) { _commentService.MarkCommentAsSpam(id);
this.Error(exception, T("Marking comment as spam failed: {0}", exception.Message), Logger, Services.Notifier);
return this.RedirectLocal(returnUrl, () => RedirectToAction("Index")); return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn }));
}
} }
[HttpPost] [HttpPost]
public ActionResult Delete(int id, string returnUrl) { public ActionResult Delete(int id, string returnUrl) {
try { if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment")))
if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment"))) return new HttpUnauthorizedResult();
return new HttpUnauthorizedResult();
int commentedOn = _commentService.GetComment(id).Record.CommentedOn; var commentPart = _commentService.GetComment(id);
_commentService.DeleteComment(id); if (commentPart == null)
return new HttpNotFoundResult();
return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn })); int commentedOn = commentPart.Record.CommentedOn;
} catch (Exception exception) { _commentService.DeleteComment(id);
this.Error(exception, T("Deleting comment failed: {0}", exception.Message), Logger, Services.Notifier);
return this.RedirectLocal(returnUrl, () => RedirectToAction("Index")); return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn }));
}
} }
private CommentEntry CreateCommentEntry(CommentPartRecord commentPart) { 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"))) if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to use the web console")))
return new HttpUnauthorizedResult(); return new HttpUnauthorizedResult();
try { using (var writer = new StringWriter()) {
using (var writer = new StringWriter()) { var commandLine = model.CommandLine.Trim();
var commandLine = model.CommandLine.Trim(); CommandParameters parameters = GetCommandParameters(commandLine, writer);
CommandParameters parameters = GetCommandParameters(commandLine, writer);
_commandManager.Execute(parameters); _commandManager.Execute(parameters);
model.History = (model.History ?? Enumerable.Empty<string>()) model.History = (model.History ?? Enumerable.Empty<string>())
.Concat(new[] {model.CommandLine}) .Concat(new[] {model.CommandLine})
.Distinct() .Distinct()
.ToArray(); .ToArray();
model.Results = writer.ToString(); model.Results = writer.ToString();
}
} catch(Exception exception) {
this.Error(exception, T("Error executing command: {0}", exception.Message), Logger, Services.Notifier);
Services.TransactionManager.Cancel();
} }
return View(model); return View(model);
} }

View File

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

View File

@@ -37,22 +37,22 @@ namespace Orchard.Media.Controllers {
[HttpPost] [HttpPost]
public ActionResult Index(FormCollection input) { public ActionResult Index(FormCollection input) {
try { foreach (string key in input.Keys) {
foreach (string key in input.Keys) { if (key.StartsWith("Checkbox.") && input[key] == "true") {
if (key.StartsWith("Checkbox.") && input[key] == "true") { string folderName = key.Substring("Checkbox.".Length);
string folderName = key.Substring("Checkbox.".Length); if (!Services.Authorizer.Authorize(Permissions.ManageMedia, T("Couldn't delete media folder")))
if (!Services.Authorizer.Authorize(Permissions.ManageMedia, T("Couldn't delete media folder"))) return new HttpUnauthorizedResult();
return new HttpUnauthorizedResult();
try {
_mediaService.DeleteFolder(folderName); _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) { public ActionResult Create(string mediaPath) {
@@ -65,19 +65,18 @@ namespace Orchard.Media.Controllers {
return new HttpUnauthorizedResult(); return new HttpUnauthorizedResult();
var viewModel = new MediaFolderCreateViewModel(); var viewModel = new MediaFolderCreateViewModel();
UpdateModel(viewModel);
try { try {
UpdateModel(viewModel);
_mediaService.CreateFolder(viewModel.MediaPath, viewModel.Name); _mediaService.CreateFolder(viewModel.MediaPath, viewModel.Name);
Services.Notifier.Information(T("Media folder created")); Services.Notifier.Information(T("Media folder created"));
return RedirectToAction("Index");
} }
catch (Exception exception) { catch(ArgumentException argumentException) {
this.Error(exception, T("Creating Folder failed: {0}", exception.Message), Logger, Services.Notifier); Services.Notifier.Error(T("Creating Folder failed: {0}", argumentException.Message));
return View(viewModel); return View(viewModel);
} }
return RedirectToAction("Index");
} }
public ActionResult Edit(string name, string mediaPath) { 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 }; var model = new MediaFolderEditViewModel { FolderName = name, MediaFiles = mediaFiles, MediaFolders = mediaFolders, MediaPath = mediaPath };
return View(model); return View(model);
} }
catch (Exception exception) { catch(ArgumentException exception) {
this.Error(exception, T("Editing failed: {0}", exception.Message), Logger, Services.Notifier); Services.Notifier.Error(T("Editing failed: {0}", exception.Message));
return RedirectToAction("Index"); return RedirectToAction("Index");
} }
} }
[HttpPost] [HttpPost]
public ActionResult Edit(FormCollection input) { public ActionResult Edit(FormCollection input) {
try { foreach (string key in input.Keys) {
foreach (string key in input.Keys) { if (key.StartsWith("Checkbox.File.") && input[key] == "true") {
if (key.StartsWith("Checkbox.File.") && input[key] == "true") { string fileName = key.Substring("Checkbox.File.".Length);
string fileName = key.Substring("Checkbox.File.".Length); string folderName = input[fileName];
string folderName = input[fileName]; if (!Services.Authorizer.Authorize(Permissions.ManageMedia, T("Couldn't delete media file")))
if (!Services.Authorizer.Authorize(Permissions.ManageMedia, T("Couldn't delete media file"))) return new HttpUnauthorizedResult();
return new HttpUnauthorizedResult();
_mediaService.DeleteFile(folderName, fileName);
try {
_mediaService.DeleteFile(folderName, fileName);
Services.Notifier.Information(T("Media file deleted")); Services.Notifier.Information(T("Media file deleted"));
} }
else if (key.StartsWith("Checkbox.Folder.") && input[key] == "true") { catch (ArgumentException argumentException) {
string folderName = key.Substring("Checkbox.Folder.".Length); Services.Notifier.Error(T("Deleting failed: {0}", argumentException.Message));
string folderPath = input[folderName]; }
if (!Services.Authorizer.Authorize(Permissions.ManageMedia, T("Couldn't delete media folder"))) }
return new HttpUnauthorizedResult(); else if (key.StartsWith("Checkbox.Folder.") && input[key] == "true") {
_mediaService.DeleteFolder(folderPath); 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")); 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) { public ActionResult EditProperties(string folderName, string mediaPath) {
@@ -136,18 +139,17 @@ namespace Orchard.Media.Controllers {
return new HttpUnauthorizedResult(); return new HttpUnauthorizedResult();
var viewModel = new MediaFolderEditPropertiesViewModel(); var viewModel = new MediaFolderEditPropertiesViewModel();
UpdateModel(viewModel);
try { try {
UpdateModel(viewModel);
_mediaService.DeleteFolder(viewModel.MediaPath); _mediaService.DeleteFolder(viewModel.MediaPath);
Services.Notifier.Information(T("Media folder deleted")); Services.Notifier.Information(T("Media folder deleted"));
return RedirectToAction("Index"); }
} catch (Exception exception) { catch(ArgumentException argumentException) {
this.Error(exception, T("Deleting media folder failed: {0}", exception.Message), Logger, Services.Notifier); Services.Notifier.Error(T("Deleting media folder failed: {0}", argumentException.Message));
return View(viewModel); return View(viewModel);
} }
return RedirectToAction("Index");
} }
[HttpPost, ActionName("EditProperties")] [HttpPost, ActionName("EditProperties")]
@@ -157,18 +159,17 @@ namespace Orchard.Media.Controllers {
return new HttpUnauthorizedResult(); return new HttpUnauthorizedResult();
var viewModel = new MediaFolderEditPropertiesViewModel(); var viewModel = new MediaFolderEditPropertiesViewModel();
UpdateModel(viewModel);
try { try {
UpdateModel(viewModel);
_mediaService.RenameFolder(viewModel.MediaPath, viewModel.Name); _mediaService.RenameFolder(viewModel.MediaPath, viewModel.Name);
Services.Notifier.Information(T("Media folder properties modified")); Services.Notifier.Information(T("Media folder properties modified"));
return RedirectToAction("Index"); }
} catch (Exception exception) { catch(ArgumentException argumentException) {
this.Error(exception, T("Modifying media folder properties failed: {0}", exception.Message), Logger, Services.Notifier); Services.Notifier.Error(T("Modifying media folder properties failed: {0}", argumentException.Message));
return View(viewModel); return View(viewModel);
} }
return RedirectToAction("Index");
} }
public ActionResult Add(string folderName, string mediaPath) { public ActionResult Add(string folderName, string mediaPath) {
@@ -182,27 +183,28 @@ namespace Orchard.Media.Controllers {
return new HttpUnauthorizedResult(); return new HttpUnauthorizedResult();
var viewModel = new MediaItemAddViewModel(); var viewModel = new MediaItemAddViewModel();
try {
UpdateModel(viewModel);
if(String.IsNullOrWhiteSpace(Request.Files[0].FileName)) { UpdateModel(viewModel);
ModelState.AddModelError("File", T("Select a file to upload").ToString());
}
if (!ModelState.IsValid) if(String.IsNullOrWhiteSpace(Request.Files[0].FileName)) {
return View(viewModel); 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); _mediaService.UploadMediaFile(viewModel.MediaPath, Request.Files[fileName], viewModel.ExtractZip);
} }
catch (ArgumentException argumentException) {
Services.Notifier.Information(T("Media file(s) uploaded")); Services.Notifier.Error(T("Uploading media file failed:"));
return RedirectToAction("Edit", new { name = viewModel.FolderName, mediaPath = viewModel.MediaPath }); return View(viewModel);
} catch (Exception exception) { }
this.Error(exception, T("Uploading media file failed:"), Logger, Services.Notifier);
return View(viewModel);
} }
Services.Notifier.Information(T("Media file(s) uploaded"));
return RedirectToAction("Edit", new { name = viewModel.FolderName, mediaPath = viewModel.MediaPath });
} }
[HttpPost] [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"))); 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(); 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 { 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) var file = Request.Files[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 {
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 publicUrl = _mediaService.UploadMediaFile(viewModel.MediaPath, file, viewModel.ExtractZip); var publicUrl = _mediaService.UploadMediaFile(viewModel.MediaPath, file, viewModel.ExtractZip);
return Content(string.Format("<script type=\"text/javascript\">var result = {{ url: \"{0}\" }};</script>", publicUrl)); return Content(string.Format("<script type=\"text/javascript\">var result = {{ url: \"{0}\" }};</script>", publicUrl));
} }
catch (Exception exception) { catch (ArgumentException argumentException) {
return Content(string.Format("<script type=\"text/javascript\">var result = {{ error: \"{0}\" }};</script>", T("ERROR: Uploading media file failed: {0}", exception.Message))); 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(); return new HttpUnauthorizedResult();
var viewModel = new MediaItemEditViewModel(); var viewModel = new MediaItemEditViewModel();
UpdateModel(viewModel);
try { try {
UpdateModel(viewModel);
_mediaService.DeleteFile(viewModel.Name, viewModel.MediaPath); _mediaService.DeleteFile(viewModel.Name, viewModel.MediaPath);
Services.Notifier.Information(T("Media deleted")); Services.Notifier.Information(T("Media deleted"));
return RedirectToAction("Edit", new { name = viewModel.FolderName, mediaPath = viewModel.MediaPath }); }
} catch (Exception exception) { catch (ArgumentException argumentException) {
this.Error(exception, T("Removing media file failed: {0}", exception.Message), Logger, Services.Notifier); Services.Notifier.Error(T("Removing media file failed: {0}", argumentException.Message));
return View(viewModel); return View(viewModel);
} }
return RedirectToAction("Edit", new { name = viewModel.FolderName, mediaPath = viewModel.MediaPath });
} }
[HttpPost, ActionName("EditMedia")] [HttpPost, ActionName("EditMedia")]
@@ -268,28 +269,28 @@ namespace Orchard.Media.Controllers {
return new HttpUnauthorizedResult(); return new HttpUnauthorizedResult();
var viewModel = new MediaItemEditViewModel(); var viewModel = new MediaItemEditViewModel();
try { UpdateModel(viewModel);
UpdateModel(viewModel); string viewModelName = viewModel.Name;
string viewModelName = viewModel.Name;
// Rename // Rename
if (!String.Equals(viewModel.Name, input["NewName"], StringComparison.OrdinalIgnoreCase)) { if (!String.Equals(viewModel.Name, input["NewName"], StringComparison.OrdinalIgnoreCase)) {
try {
_mediaService.RenameFile(viewModel.MediaPath, viewModel.Name, input["NewName"]); _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")); Services.Notifier.Information(T("Media information updated"));
return RedirectToAction("EditMedia", new { name = viewModelName, return RedirectToAction("EditMedia", new { name = viewModelName,
caption = viewModel.Caption, caption = viewModel.Caption,
lastUpdated = viewModel.LastUpdated, lastUpdated = viewModel.LastUpdated,
size = viewModel.Size, size = viewModel.Size,
folderName = viewModel.FolderName, folderName = viewModel.FolderName,
mediaPath = viewModel.MediaPath }); mediaPath = viewModel.MediaPath });
}
catch (Exception exception) {
this.Error(exception, T("Editing media file failed."), Logger, Services.Notifier);
return EditMedia(viewModel);
}
} }
} }
} }

View File

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