Exception handling consolidation in command handlers.

Use Context.Output to write error messages when you handle an Exception or an error case. If you can't recover afterwards, just return.
Don't throw an exception from within the handler unless necessary.
-> If you want to throw due to an inner exception, throw an OrchardException. Add an error message and the exception as the innerexception of your OrchardException.
Your exception will be caught by the command executive, an error message will indicate which command failed, and the inner exceptions will be displayed.
Also, do not return values from commands, they are not services.

--HG--
branch : 1.x
extra : transplant_source : %5Ej%123%DA%E0%28%A7l%F5%F9%A4%B0z%05%EB%E4%21%FD%DC
This commit is contained in:
Suha Can
2011-06-10 13:34:29 -07:00
parent 95c0ac69e6
commit dbe908a717
13 changed files with 121 additions and 108 deletions

View File

@@ -27,12 +27,12 @@ namespace Orchard.Core.Settings.Commands {
"If 'Force' is true, set the site base url even if it is already set. " + "If 'Force' is true, set the site base url even if it is already set. " +
"The default behavior is to not override the setting.")] "The default behavior is to not override the setting.")]
[OrchardSwitches("BaseUrl,Force")] [OrchardSwitches("BaseUrl,Force")]
public string SetBaseUrl() { public void SetBaseUrl() {
// Don't do anything if set and not forcing // Don't do anything if set and not forcing
if (!string.IsNullOrEmpty(_siteService.GetSiteSettings().BaseUrl)) { if (!string.IsNullOrEmpty(_siteService.GetSiteSettings().BaseUrl)) {
if (!Force) { if (!Force) {
Context.Output.WriteLine(T("'BaseUrl' site setting is already set. Use the 'Force' flag to override.")); Context.Output.WriteLine(T("'BaseUrl' site setting is already set. Use the 'Force' flag to override."));
return null; return;
} }
} }
@@ -40,7 +40,7 @@ namespace Orchard.Core.Settings.Commands {
if (string.IsNullOrEmpty(BaseUrl)) { if (string.IsNullOrEmpty(BaseUrl)) {
if (_httpContextAccessor.Current() == null) { if (_httpContextAccessor.Current() == null) {
Context.Output.WriteLine(T("No HTTP request available to determine the base url of the site")); Context.Output.WriteLine(T("No HTTP request available to determine the base url of the site"));
return null; return;
} }
var request = _httpContextAccessor.Current().Request; var request = _httpContextAccessor.Current().Request;
BaseUrl = request.ToApplicationRootUrlString(); BaseUrl = request.ToApplicationRootUrlString();
@@ -49,7 +49,6 @@ namespace Orchard.Core.Settings.Commands {
// Update base url // Update base url
_siteService.GetSiteSettings().As<SiteSettingsPart>().BaseUrl = BaseUrl; _siteService.GetSiteSettings().As<SiteSettingsPart>().BaseUrl = BaseUrl;
Context.Output.WriteLine(T("'BaseUrl' site setting set to '{0}'", BaseUrl)); Context.Output.WriteLine(T("'BaseUrl' site setting set to '{0}'", BaseUrl));
return null;
} }
} }
} }

View File

@@ -60,18 +60,20 @@ namespace Orchard.Blogs.Commands {
[CommandName("blog create")] [CommandName("blog create")]
[CommandHelp("blog create /Slug:<slug> /Title:<title> [/Owner:<username>] [/Description:<description>] [/MenuText:<menu text>] [/Homepage:true|false]\r\n\t" + "Creates a new Blog")] [CommandHelp("blog create /Slug:<slug> /Title:<title> [/Owner:<username>] [/Description:<description>] [/MenuText:<menu text>] [/Homepage:true|false]\r\n\t" + "Creates a new Blog")]
[OrchardSwitches("Slug,Title,Owner,Description,MenuText,Homepage")] [OrchardSwitches("Slug,Title,Owner,Description,MenuText,Homepage")]
public string Create() { public void Create() {
if (String.IsNullOrEmpty(Owner)) { if (String.IsNullOrEmpty(Owner)) {
Owner = _siteService.GetSiteSettings().SuperUser; Owner = _siteService.GetSiteSettings().SuperUser;
} }
var owner = _membershipService.GetUser(Owner); var owner = _membershipService.GetUser(Owner);
if ( owner == null ) { if (owner == null) {
throw new OrchardException(T("Invalid username: {0}", Owner)); Context.Output.WriteLine(T("Invalid username: {0}", Owner));
return;
} }
if(!IsSlugValid(Slug)) { if(!IsSlugValid(Slug)) {
throw new OrchardException(T("Invalid Slug provided. Blog creation failed.")); Context.Output.WriteLine(T("Invalid Slug {0} provided. Blog creation failed.", Slug));
return;
} }
var blog = _contentManager.New("Blog"); var blog = _contentManager.New("Blog");
@@ -90,41 +92,43 @@ namespace Orchard.Blogs.Commands {
} }
_contentManager.Create(blog); _contentManager.Create(blog);
return "Blog created successfully"; Context.Output.WriteLine(T("Blog created successfully"));
} }
[CommandName("blog import")] [CommandName("blog import")]
[CommandHelp("blog import /Slug:<slug> /FeedUrl:<feed url> /Owner:<username>\r\n\t" + "Import all items from <feed url> into the blog at the specified <slug>")] [CommandHelp("blog import /Slug:<slug> /FeedUrl:<feed url> /Owner:<username>\r\n\t" + "Import all items from <feed url> into the blog at the specified <slug>")]
[OrchardSwitches("FeedUrl,Slug,Owner")] [OrchardSwitches("FeedUrl,Slug,Owner")]
public string Import() { public void Import() {
var owner = _membershipService.GetUser(Owner); var owner = _membershipService.GetUser(Owner);
if(owner == null) { if(owner == null) {
throw new OrchardException(T("Invalid username: {0}", Owner)); Context.Output.WriteLine(T("Invalid username: {0}", Owner));
return;
} }
XDocument doc; XDocument doc;
try { try {
Context.Output.WriteLine("Loading feed..."); Context.Output.WriteLine(T("Loading feed..."));
doc = XDocument.Load(FeedUrl); doc = XDocument.Load(FeedUrl);
Context.Output.WriteLine("Found {0} items", doc.Descendants("item").Count()); Context.Output.WriteLine(T("Found {0} items", doc.Descendants("item").Count()));
} }
catch ( Exception ex ) { catch (Exception ex) {
throw new OrchardException(T("An error occured while loading the file: {0}", ex.Message)); throw new OrchardException(T("An error occured while loading the feed at {0}.", FeedUrl), ex);
} }
var blog = _blogService.Get(Slug); var blog = _blogService.Get(Slug);
if ( blog == null ) { if ( blog == null ) {
throw new OrchardException(T("Blog not found at specified slug: {0}", Slug)); Context.Output.WriteLine(T("Blog not found at specified slug: {0}", Slug));
return;
} }
foreach ( var item in doc.Descendants("item") ) { foreach ( var item in doc.Descendants("item") ) {
if (item != null) { if (item != null) {
var postName = item.Element("title").Value; var postName = item.Element("title").Value;
Context.Output.WriteLine("Adding post: {0}...", postName.Substring(0, Math.Min(postName.Length, 40))); Context.Output.WriteLine(T("Adding post: {0}...", postName.Substring(0, Math.Min(postName.Length, 40))));
var post = _contentManager.New("BlogPost"); var post = _contentManager.New("BlogPost");
post.As<ICommonPart>().Owner = owner; post.As<ICommonPart>().Owner = owner;
post.As<ICommonPart>().Container = blog; post.As<ICommonPart>().Container = blog;
@@ -137,7 +141,7 @@ namespace Orchard.Blogs.Commands {
} }
} }
return "Import feed completed."; Context.Output.WriteLine(T("Import feed completed."));
} }
private static string Slugify(string slug) { private static string Slugify(string slug) {

View File

@@ -54,12 +54,12 @@ namespace Orchard.CodeGeneration.Commands {
[CommandName("codegen datamigration")] [CommandName("codegen datamigration")]
public void CreateDataMigration(string featureName) { public void CreateDataMigration(string featureName) {
Context.Output.WriteLine(T("Creating Data Migration for {0}", featureName)); Context.Output.WriteLine(T("Creating Data Migration for {0}", featureName));
ExtensionDescriptor extensionDescriptor = _extensionManager.AvailableExtensions().FirstOrDefault(extension => DefaultExtensionTypes.IsModule(extension.ExtensionType) && ExtensionDescriptor extensionDescriptor = _extensionManager.AvailableExtensions().FirstOrDefault(extension => DefaultExtensionTypes.IsModule(extension.ExtensionType) &&
extension.Features.Any(feature => String.Equals(feature.Id, featureName, StringComparison.OrdinalIgnoreCase))); extension.Features.Any(feature => String.Equals(feature.Id, featureName, StringComparison.OrdinalIgnoreCase)));
if (extensionDescriptor == null) { if (extensionDescriptor == null) {
throw new OrchardException(T("Creating data migration failed: target Feature {0} could not be found.", featureName)); Context.Output.WriteLine(T("Creating data migration failed: target Feature {0} could not be found.", featureName));
return;
} }
string dataMigrationFolderPath = HostingEnvironment.MapPath("~/Modules/" + extensionDescriptor.Id + "/"); string dataMigrationFolderPath = HostingEnvironment.MapPath("~/Modules/" + extensionDescriptor.Id + "/");
@@ -72,7 +72,8 @@ namespace Orchard.CodeGeneration.Commands {
} }
if (File.Exists(dataMigrationFilePath)) { if (File.Exists(dataMigrationFilePath)) {
throw new OrchardException(T("Data migration already exists in target Module {0}.", extensionDescriptor.Id)); Context.Output.WriteLine(T("Data migration already exists in target Module {0}.", extensionDescriptor.Id));
return;
} }
List<SchemaCommand> commands = _schemaCommandGenerator.GetCreateFeatureCommands(featureName, false).ToList(); List<SchemaCommand> commands = _schemaCommandGenerator.GetCreateFeatureCommands(featureName, false).ToList();
@@ -115,7 +116,8 @@ namespace Orchard.CodeGeneration.Commands {
Context.Output.WriteLine(T("Creating Module {0}", moduleName)); Context.Output.WriteLine(T("Creating Module {0}", moduleName));
if ( _extensionManager.AvailableExtensions().Any(extension => String.Equals(moduleName, extension.Name, StringComparison.OrdinalIgnoreCase)) ) { if ( _extensionManager.AvailableExtensions().Any(extension => String.Equals(moduleName, extension.Name, StringComparison.OrdinalIgnoreCase)) ) {
throw new OrchardException(T("Creating Module {0} failed: a module of the same name already exists", moduleName)); Context.Output.WriteLine(T("Creating Module {0} failed: a module of the same name already exists", moduleName));
return;
} }
IntegrateModule(moduleName); IntegrateModule(moduleName);
@@ -128,14 +130,16 @@ namespace Orchard.CodeGeneration.Commands {
public void CreateTheme(string themeName) { public void CreateTheme(string themeName) {
Context.Output.WriteLine(T("Creating Theme {0}", themeName)); Context.Output.WriteLine(T("Creating Theme {0}", themeName));
if (_extensionManager.AvailableExtensions().Any(extension => String.Equals(themeName, extension.Id, StringComparison.OrdinalIgnoreCase))) { if (_extensionManager.AvailableExtensions().Any(extension => String.Equals(themeName, extension.Id, StringComparison.OrdinalIgnoreCase))) {
throw new OrchardException(T("Creating Theme {0} failed: an extention of the same name already exists", themeName)); Context.Output.WriteLine(T("Creating Theme {0} failed: an extention of the same name already exists", themeName));
return;
} }
if (!string.IsNullOrEmpty(BasedOn)) { if (!string.IsNullOrEmpty(BasedOn)) {
if (!_extensionManager.AvailableExtensions().Any(extension => if (!_extensionManager.AvailableExtensions().Any(extension =>
string.Equals(extension.ExtensionType, DefaultExtensionTypes.Theme, StringComparison.OrdinalIgnoreCase) && string.Equals(extension.ExtensionType, DefaultExtensionTypes.Theme, StringComparison.OrdinalIgnoreCase) &&
string.Equals(BasedOn, extension.Id, StringComparison.OrdinalIgnoreCase))) { string.Equals(BasedOn, extension.Id, StringComparison.OrdinalIgnoreCase))) {
throw new OrchardException(T("Creating Theme {0} failed: base theme named {1} was not found.", themeName, BasedOn)); Context.Output.WriteLine(T("Creating Theme {0} failed: base theme named {1} was not found.", themeName, BasedOn));
return;
} }
} }
IntegrateTheme(themeName, BasedOn); IntegrateTheme(themeName, BasedOn);
@@ -151,7 +155,8 @@ namespace Orchard.CodeGeneration.Commands {
string.Equals(moduleName, extension.Name, StringComparison.OrdinalIgnoreCase)); string.Equals(moduleName, extension.Name, StringComparison.OrdinalIgnoreCase));
if (extensionDescriptor == null) { if (extensionDescriptor == null) {
throw new OrchardException(T("Creating Controller {0} failed: target Module {1} could not be found.", controllerName, moduleName)); Context.Output.WriteLine(T("Creating Controller {0} failed: target Module {1} could not be found.", controllerName, moduleName));
return;
} }
string moduleControllersPath = HostingEnvironment.MapPath("~/Modules/" + extensionDescriptor.Id + "/Controllers/"); string moduleControllersPath = HostingEnvironment.MapPath("~/Modules/" + extensionDescriptor.Id + "/Controllers/");
@@ -163,7 +168,8 @@ namespace Orchard.CodeGeneration.Commands {
Directory.CreateDirectory(moduleControllersPath); Directory.CreateDirectory(moduleControllersPath);
} }
if (File.Exists(controllerPath)) { if (File.Exists(controllerPath)) {
throw new OrchardException(T("Controller {0} already exists in target Module {1}.", controllerName, moduleName)); Context.Output.WriteLine(T("Controller {0} already exists in target Module {1}.", controllerName, moduleName));
return;
} }
string controllerText = File.ReadAllText(templatesPath + "Controller.txt"); string controllerText = File.ReadAllText(templatesPath + "Controller.txt");

View File

@@ -8,7 +8,6 @@ using Orchard.Environment.Extensions;
using Orchard.Security; using Orchard.Security;
namespace Orchard.Experimental.Commands { namespace Orchard.Experimental.Commands {
[OrchardFeature("Profiling")] [OrchardFeature("Profiling")]
public class ProfilingCommands : DefaultOrchardCommandHandler { public class ProfilingCommands : DefaultOrchardCommandHandler {
private readonly IContentManager _contentManager; private readonly IContentManager _contentManager;
@@ -20,11 +19,10 @@ namespace Orchard.Experimental.Commands {
} }
[CommandName("add profiling data")] [CommandName("add profiling data")]
public string AddProfilingData() { public void AddProfilingData() {
var admin = _membershipService.GetUser("admin"); var admin = _membershipService.GetUser("admin");
for (var index = 0; index != 5; ++index) { for (var index = 0; index != 5; ++index) {
var pageName = "page" + index; var pageName = "page" + index;
var page = _contentManager.Create("Page", VersionOptions.Draft); var page = _contentManager.Create("Page", VersionOptions.Draft);
page.As<ICommonPart>().Owner = admin; page.As<ICommonPart>().Owner = admin;
@@ -61,18 +59,19 @@ namespace Orchard.Experimental.Commands {
//} //}
} }
return "AddProfilingData completed"; Context.Output.WriteLine(T("Finished adding profiling data"));
} }
[CommandName("add users")] [CommandName("add users")]
public string AddUsers() { public void AddUsers() {
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
var user = _membershipService.CreateUser(new CreateUserParams("user" + i, "1234567", "user" + i + "@orchardproject.net", null, null, true)); var user = _membershipService.CreateUser(new CreateUserParams("user" + i, "1234567", "user" + i + "@orchardproject.net", null, null, true));
if (user == null) if (user == null) {
throw new OrchardException(T("The authentication provider returned an error")); Context.Output.WriteLine(T("Creating user failed. The authentication provider returned an error. Aborting..."));
return;
}
} }
return "Success"; Context.Output.WriteLine(T("Adding users completed successfully"));
} }
} }
} }

View File

@@ -33,26 +33,25 @@ namespace Orchard.Indexing.Commands {
[CommandName("index update")] [CommandName("index update")]
[CommandHelp("index update\r\n\t" + "Updates the search index")] [CommandHelp("index update\r\n\t" + "Updates the search index")]
public string Update() { public void Update() {
_indexingService.UpdateIndex(SearchIndexName); _indexingService.UpdateIndex(SearchIndexName);
Context.Output.WriteLine(T("Index is now being updated..."));
return T("Index is now being updated...").Text;
} }
[CommandName("index rebuild")] [CommandName("index rebuild")]
[CommandHelp("index rebuild \r\n\t" + "Rebuilds the search index")] [CommandHelp("index rebuild \r\n\t" + "Rebuilds the search index")]
public string Rebuild() { public void Rebuild() {
_indexingService.RebuildIndex(SearchIndexName); _indexingService.RebuildIndex(SearchIndexName);
Context.Output.WriteLine(T("Index is now being rebuilt..."));
return T("Index is now being rebuilt...").Text;
} }
[CommandName("index search")] [CommandName("index search")]
[CommandHelp("index search /Query:<query>\r\n\t" + "Searches the specified <query> terms in the search index")] [CommandHelp("index search /Query:<query>\r\n\t" + "Searches the specified <query> terms in the search index")]
[OrchardSwitches("Query")] [OrchardSwitches("Query")]
public string Search() { public void Search() {
if ( !_indexManager.HasIndexProvider() ) { if ( !_indexManager.HasIndexProvider() ) {
throw new OrchardException(T("No index available")); Context.Output.WriteLine(T("No index available"));
return;
} }
var searchBuilder = _indexManager.GetSearchIndexProvider().CreateSearchBuilder(SearchIndexName); var searchBuilder = _indexManager.GetSearchIndexProvider().CreateSearchBuilder(SearchIndexName);
var results = searchBuilder.Parse( new [] {"body", "title"}, Query).Search(); var results = searchBuilder.Parse( new [] {"body", "title"}, Query).Search();
@@ -73,48 +72,51 @@ namespace Orchard.Indexing.Commands {
Context.Output.WriteLine("└──────────────────────────────────────────────────────────────┴────────┘"); Context.Output.WriteLine("└──────────────────────────────────────────────────────────────┴────────┘");
Context.Output.WriteLine(); Context.Output.WriteLine();
return T("End of search results").Text; Context.Output.WriteLine(T("End of search results"));
} }
[CommandName("index stats")] [CommandName("index stats")]
[CommandHelp("index stats\r\n\t" + "Displays some statistics about the search index")] [CommandHelp("index stats\r\n\t" + "Displays some statistics about the search index")]
[OrchardSwitches("IndexName")] [OrchardSwitches("IndexName")]
public string Stats() { public void Stats() {
if ( !_indexManager.HasIndexProvider() ) { if ( !_indexManager.HasIndexProvider() ) {
throw new OrchardException(T("No index available")); Context.Output.WriteLine(T("No index available"));
return;
} }
return T("Number of indexed documents: {0}", _indexManager.GetSearchIndexProvider().NumDocs(SearchIndexName)).Text; Context.Output.WriteLine(T("Number of indexed documents: {0}", _indexManager.GetSearchIndexProvider().NumDocs(SearchIndexName)));
} }
[CommandName("index refresh")] [CommandName("index refresh")]
[CommandHelp("index refresh /ContentItem:<content item id> \r\n\t" + "Refreshes the index for the specifed <content item id>")] [CommandHelp("index refresh /ContentItem:<content item id> \r\n\t" + "Refreshes the index for the specifed <content item id>")]
[OrchardSwitches("ContentItem")] [OrchardSwitches("ContentItem")]
public string Refresh() { public void Refresh() {
int contentItemId; int contentItemId;
if ( !int.TryParse(ContentItem, out contentItemId) ) { if ( !int.TryParse(ContentItem, out contentItemId) ) {
throw new OrchardException(T("Invalid content item id. Not an integer.")); Context.Output.WriteLine(T("Invalid content item id. Not an integer."));
return;
} }
var contentItem = _contentManager.Get(contentItemId); var contentItem = _contentManager.Get(contentItemId);
_indexingTaskManager.CreateUpdateIndexTask(contentItem); _indexingTaskManager.CreateUpdateIndexTask(contentItem);
return T("Content Item marked for reindexing").Text; Context.Output.WriteLine(T("Content Item marked for reindexing"));
} }
[CommandName("index delete")] [CommandName("index delete")]
[CommandHelp("index delete /ContentItem:<content item id>\r\n\t" + "Deletes the specifed <content item id> from the index")] [CommandHelp("index delete /ContentItem:<content item id>\r\n\t" + "Deletes the specifed <content item id> from the index")]
[OrchardSwitches("ContentItem")] [OrchardSwitches("ContentItem")]
public string Delete() { public void Delete() {
int contentItemId; int contentItemId;
if(!int.TryParse(ContentItem, out contentItemId)) { if(!int.TryParse(ContentItem, out contentItemId)) {
throw new OrchardException(T("Invalid content item id. Not an integer.")); Context.Output.WriteLine(T("Invalid content item id. Not an integer."));
return;
} }
var contentItem = _contentManager.Get(contentItemId); var contentItem = _contentManager.Get(contentItemId);
_indexingTaskManager.CreateDeleteIndexTask(contentItem); _indexingTaskManager.CreateDeleteIndexTask(contentItem);
return T("Content Item marked for deletion").Text; Context.Output.WriteLine(T("Content Item marked for deletion"));
} }
} }

View File

@@ -1,5 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using Orchard.Commands; using Orchard.Commands;
using Orchard.Data.Migration; using Orchard.Data.Migration;
@@ -22,24 +21,22 @@ namespace Orchard.Migrations.Commands {
[CommandName("upgrade database")] [CommandName("upgrade database")]
[CommandHelp("upgrade database <feature-name-1> ... <feature-name-n> \r\n\t" + "Upgrades or create the database tables for the <feature-name> or all features if not available")] [CommandHelp("upgrade database <feature-name-1> ... <feature-name-n> \r\n\t" + "Upgrades or create the database tables for the <feature-name> or all features if not available")]
public string UpgradeDatabase(params string[] featureNames) { public void UpgradeDatabase(params string[] featureNames) {
var features = featureNames.Any()
? featureNames
: _extensionManager.AvailableExtensions()
.SelectMany(ext => ext.Features)
.Select(f => f.Id);
try { try {
IEnumerable<string> features = featureNames.Any()
? featureNames
: _extensionManager.AvailableExtensions()
.SelectMany(ext => ext.Features)
.Select(f => f.Id);
foreach(var feature in features) { foreach(var feature in features) {
_dataMigrationManager.Update(feature); _dataMigrationManager.Update(feature);
} }
} }
catch ( Exception ex ) { catch ( Exception ex ) {
Context.Output.WriteLine(T("An error occured while upgrading the database: " + ex.Message)); throw new OrchardException(T("An error occured while upgrading the database."), ex);
return "Upgrade terminated.";
} }
return "Database upgraded"; Context.Output.WriteLine(T("Database upgraded"));
} }
} }
} }

View File

@@ -24,42 +24,40 @@ namespace Orchard.Migrations.Commands {
[CommandName("update database")] [CommandName("update database")]
[CommandHelp("update database \r\n\t" + "Automatically updates the database schema according to the defintion of the \"Record\" types in code for the enabled features.")] [CommandHelp("update database \r\n\t" + "Automatically updates the database schema according to the defintion of the \"Record\" types in code for the enabled features.")]
public string UpdateDatabase() { public void UpdateDatabase() {
try { try {
_schemaCommandGenerator.UpdateDatabase(); _schemaCommandGenerator.UpdateDatabase();
} }
catch ( Exception ex ) { catch ( Exception ex ) {
Context.Output.WriteLine(T("An error occured while updating the database: " + ex.Message)); throw new OrchardException(T("An error occured while updating the database."), ex);
return "Update terminated.";
} }
return "Database updated"; Context.Output.WriteLine(T("Database updated"));
} }
[CommandName("create tables")] [CommandName("create tables")]
[CommandHelp("create tables <feature-name> [/Drop:true|false] \r\n\t" + "Creates the database tables according to the defintion of the \"Record\" types in code for the <feature-name> and optionally drops them before if specified.")] [CommandHelp("create tables <feature-name> [/Drop:true|false] \r\n\t" + "Creates the database tables according to the defintion of the \"Record\" types in code for the <feature-name> and optionally drops them before if specified.")]
[OrchardSwitches("Drop")] [OrchardSwitches("Drop")]
public string CreateTables(string featureName) { public void CreateTables(string featureName) {
var stringInterpreter = new StringCommandInterpreter(Context.Output); var stringInterpreter = new StringCommandInterpreter(Context.Output);
try { try {
var commands = _schemaCommandGenerator.GetCreateFeatureCommands(featureName, Drop).ToList(); var commands = _schemaCommandGenerator.GetCreateFeatureCommands(featureName, Drop).ToList();
if ( commands.Any() ) { if ( commands.Any() ) {
foreach (var command in commands) { foreach (var command in commands) {
stringInterpreter.Visit(command); stringInterpreter.Visit(command);
_dataMigrationInterpreter.Visit(command); _dataMigrationInterpreter.Visit(command);
} }
} }
else { else {
return "There are no tables to create for this feature."; Context.Output.WriteLine(T("There are no tables to create for feature {0}.", featureName));
return;
} }
} }
catch ( Exception ex ) { catch ( Exception ex ) {
Context.Output.WriteLine(T("An error occured while creating the tables: " + ex.Message)); throw new OrchardException(T("An error occured while creating the tables."), ex);
return "Tables creation terminated.";
} }
return "Tables created"; Context.Output.WriteLine(T("Tables created"));
} }
} }
} }

View File

@@ -32,7 +32,8 @@ namespace Orchard.Packaging.Commands {
public void CreatePackage(string extensionName, string path) { public void CreatePackage(string extensionName, string path) {
var packageData = _packageManager.Harvest(extensionName); var packageData = _packageManager.Harvest(extensionName);
if (packageData == null) { if (packageData == null) {
throw new OrchardException(T("Module or Theme \"{0}\" does not exist in this Orchard installation.", extensionName)); Context.Output.WriteLine(T("Module or Theme \"{0}\" does not exist in this Orchard installation.", extensionName));
return;
} }
// append "Orchard.[ExtensionType]" to prevent conflicts with other packages (e.g, TinyMce, jQuery, ...) // append "Orchard.[ExtensionType]" to prevent conflicts with other packages (e.g, TinyMce, jQuery, ...)
@@ -62,14 +63,15 @@ namespace Orchard.Packaging.Commands {
public void InstallPackage(string packageId, string location) { public void InstallPackage(string packageId, string location) {
try { try {
_packageManager.Install(packageId, Version, Path.GetFullPath(location), ApplicationPath); _packageManager.Install(packageId, Version, Path.GetFullPath(location), ApplicationPath);
foreach (var message in _notifier.List()) {
Context.Output.WriteLine(message.Message);
}
} }
catch(Exception e) { catch(Exception e) {
// Exceptions area thrown by NuGet as error messages // Exceptions area thrown by NuGet as error messages
Context.Output.WriteLine(HttpUtility.HtmlDecode(T("Could not install the package: {0}", e.Message).Text)); Context.Output.WriteLine(HttpUtility.HtmlDecode(T("Could not install the package: {0}", e.Message).Text));
return;
}
foreach (var message in _notifier.List()) {
Context.Output.WriteLine(message.Message);
} }
} }
@@ -83,13 +85,15 @@ namespace Orchard.Packaging.Commands {
try { try {
_packageManager.Uninstall(packageId, ApplicationPath); _packageManager.Uninstall(packageId, ApplicationPath);
foreach ( var message in _notifier.List() ) {
Context.Output.WriteLine(message.Message);
}
} }
catch(Exception e) { catch(Exception e) {
// Exceptions area thrown by NuGet as error messages // Exceptions area thrown by NuGet as error messages
throw new OrchardException(T(HttpUtility.HtmlDecode(T("Could not uninstall the package: {0}", e.Message).Text))); Context.Output.WriteLine(T(HttpUtility.HtmlDecode(T("Could not unintall the package: {0}", e.Message).Text)));
return;
}
foreach (var message in _notifier.List()) {
Context.Output.WriteLine(message.Message);
} }
} }
} }

View File

@@ -24,12 +24,14 @@ namespace Orchard.Recipes.Commands {
public void HarvestRecipes(string extensionId) { public void HarvestRecipes(string extensionId) {
ExtensionDescriptor extensionDescriptor = _extensionManager.GetExtension(extensionId); ExtensionDescriptor extensionDescriptor = _extensionManager.GetExtension(extensionId);
if (extensionDescriptor == null) { if (extensionDescriptor == null) {
throw new OrchardException(T("Could not discover recipes because module '{0}' was not found.", extensionId)); Context.Output.WriteLine(T("Could not discover recipes because module '{0}' was not found.", extensionId));
return;
} }
IEnumerable<Recipe> recipes = _recipeHarvester.HarvestRecipes(extensionId); IEnumerable<Recipe> recipes = _recipeHarvester.HarvestRecipes(extensionId);
if (recipes.Count() == 0) { if (recipes.Count() == 0) {
throw new OrchardException(T("No recipes found for extension {0}.", extensionId)); Context.Output.WriteLine(T("No recipes found for extension {0}.", extensionId));
return;
} }
Context.Output.WriteLine(T("List of available recipes")); Context.Output.WriteLine(T("List of available recipes"));
@@ -51,27 +53,24 @@ namespace Orchard.Recipes.Commands {
public void ExecuteRecipe(string extensionId, string recipeName) { public void ExecuteRecipe(string extensionId, string recipeName) {
ExtensionDescriptor extensionDescriptor = _extensionManager.GetExtension(extensionId); ExtensionDescriptor extensionDescriptor = _extensionManager.GetExtension(extensionId);
if (extensionDescriptor == null) { if (extensionDescriptor == null) {
throw new OrchardException(T("Could not discover recipes because module '{0}' was not found.", extensionId)); Context.Output.WriteLine(T("Could not discover recipes because module '{0}' was not found.", extensionId));
return;
} }
IEnumerable<Recipe> recipes = _recipeHarvester.HarvestRecipes(extensionId); IEnumerable<Recipe> recipes = _recipeHarvester.HarvestRecipes(extensionId);
if (recipes.Count() == 0) { if (recipes.Count() == 0) {
throw new OrchardException(T("No recipes found for extension {0}.", extensionId)); Context.Output.WriteLine(T("No recipes found for extension {0}.", extensionId));
return;
} }
Recipe recipe = recipes.FirstOrDefault(r => r.Name.Equals(recipeName, StringComparison.OrdinalIgnoreCase)); Recipe recipe = recipes.FirstOrDefault(r => r.Name.Equals(recipeName, StringComparison.OrdinalIgnoreCase));
if (recipe == null) { if (recipe == null) {
throw new OrchardException(T("Invalid recipe name {0}.", recipeName)); Context.Output.WriteLine(T("Invalid recipe name {0}.", recipeName));
return;
} }
try { _recipeManager.Execute(recipe);
_recipeManager.Execute(recipe); Context.Output.WriteLine(T("Recipe scheduled for execution successfully.").Text);
Context.Output.WriteLine(T("Recipe scheduled for execution successfully.").Text);
}
catch {
Context.Output.WriteLine(T("Recipe failed to execute.").Text);
}
} }
} }
} }

View File

@@ -44,8 +44,8 @@ namespace Orchard.Setup.Commands {
[OrchardSwitches("SiteName,AdminUsername,AdminPassword,DatabaseProvider,DatabaseConnectionString,DatabaseTablePrefix,EnabledFeatures,Recipe")] [OrchardSwitches("SiteName,AdminUsername,AdminPassword,DatabaseProvider,DatabaseConnectionString,DatabaseTablePrefix,EnabledFeatures,Recipe")]
public void Setup() { public void Setup() {
IEnumerable<string> enabledFeatures = null; IEnumerable<string> enabledFeatures = null;
if (!string.IsNullOrEmpty(this.EnabledFeatures)) { if (!string.IsNullOrEmpty(EnabledFeatures)) {
enabledFeatures = this.EnabledFeatures enabledFeatures = EnabledFeatures
.Split(',') .Split(',')
.Select(s => s.Trim()) .Select(s => s.Trim())
.Where(s => !string.IsNullOrEmpty(s)); .Where(s => !string.IsNullOrEmpty(s));

View File

@@ -29,21 +29,24 @@ namespace Orchard.Users.Commands {
[CommandName("user create")] [CommandName("user create")]
[CommandHelp("user create /UserName:<username> /Password:<password> /Email:<email>\r\n\t" + "Creates a new User")] [CommandHelp("user create /UserName:<username> /Password:<password> /Email:<email>\r\n\t" + "Creates a new User")]
[OrchardSwitches("UserName,Password,Email")] [OrchardSwitches("UserName,Password,Email")]
public string Create() { public void Create() {
if (!_userService.VerifyUserUnicity(UserName, Email)) { if (!_userService.VerifyUserUnicity(UserName, Email)) {
throw new OrchardException(T("User with that username and/or email already exists.")); Context.Output.WriteLine(T("User with that username and/or email already exists."));
return;
} }
if (Password == null || Password.Length < MinPasswordLength) { if (Password == null || Password.Length < MinPasswordLength) {
throw new OrchardException(T("You must specify a password of {0} or more characters.", MinPasswordLength)); Context.Output.WriteLine(T("You must specify a password of {0} or more characters.", MinPasswordLength));
return;
} }
var user = _membershipService.CreateUser(new CreateUserParams(UserName, Password, Email, null, null, true)); var user = _membershipService.CreateUser(new CreateUserParams(UserName, Password, Email, null, null, true));
if (user == null) { if (user == null) {
throw new OrchardException(T("The authentication provider returned an error")); Context.Output.WriteLine(T("Could not create user {0}. The authentication provider returned an error", UserName));
return;
} }
return T("User created successfully").ToString(); Context.Output.WriteLine(T("User created successfully"));
} }
int MinPasswordLength { int MinPasswordLength {

View File

@@ -15,15 +15,15 @@ namespace Orchard.Warmup.Commands {
[CommandName("warmup generate")] [CommandName("warmup generate")]
[CommandHelp("warmup generate [/Force:true] \r\n\t Generates all the static pages for the warmup feature.")] [CommandHelp("warmup generate [/Force:true] \r\n\t Generates all the static pages for the warmup feature.")]
[OrchardSwitches("Force")] [OrchardSwitches("Force")]
public string Generate() { public void Generate() {
if(Force) { if(Force) {
_warmupUpdater.Generate(); _warmupUpdater.Generate();
} }
else { else {
_warmupUpdater.EnsureGenerate(); _warmupUpdater.EnsureGenerate();
} }
return "Generation finished"; Context.Output.WriteLine(T("Generation finished"));
} }
} }
} }

View File

@@ -55,14 +55,16 @@ namespace Orchard.Widgets.Commands {
public void Create(string type) { public void Create(string type) {
var widgetTypeNames = _widgetsService.GetWidgetTypeNames(); var widgetTypeNames = _widgetsService.GetWidgetTypeNames();
if (!widgetTypeNames.Contains(type)) { if (!widgetTypeNames.Contains(type)) {
throw new OrchardException(T("Creating widget failed : type {0} was not found. Supported widget types are: {1}.", Context.Output.WriteLine(T("Creating widget failed : type {0} was not found. Supported widget types are: {1}.",
type, type,
widgetTypeNames.Aggregate(String.Empty, (current, widgetType) => current + " " + widgetType))); widgetTypeNames.Aggregate(String.Empty, (current, widgetType) => current + " " + widgetType)));
return;
} }
var layer = GetLayer(Layer); var layer = GetLayer(Layer);
if (layer == null) { if (layer == null) {
throw new OrchardException(T("Creating widget failed : layer {0} was not found.", Layer)); Context.Output.WriteLine(T("Creating widget failed : layer {0} was not found.", Layer));
return;
} }
var widget = _widgetsService.CreateWidget(layer.ContentItem.Id, type, T(Title).Text, Position, Zone); var widget = _widgetsService.CreateWidget(layer.ContentItem.Id, type, T(Title).Text, Position, Zone);