diff --git a/ADImportService/Rest/RestHelper.cs b/ADImportService/Rest/RestHelper.cs index c97bee9..d42f46f 100644 --- a/ADImportService/Rest/RestHelper.cs +++ b/ADImportService/Rest/RestHelper.cs @@ -4,39 +4,37 @@ namespace Kentico.ADImportService { - /// - /// Provides basic operation for manipulation with REST reposnes. - /// - public class RestHelper - { - /// - /// Get value of given attribute from REST response. - /// - /// Complete REST response. - /// Object attribute to retrieve. - public static string GetAttributeFromReponse(string response, string attributeName) - { - IEnumerable results = GetAttributesFromReponse(response, attributeName).ToList(); + /// + /// Provides basic operation for manipulation with REST reposnes. + /// + public class RestHelper + { + /// + /// Get value of given attribute from REST response. + /// + /// Complete REST response. + /// Object attribute to retrieve. + public static string GetAttributeFromReponse(string response, string attributeName) + { + return GetAttributesFromReponse(response, attributeName).FirstOrDefault(); + } - return results.FirstOrDefault(); - } + /// + /// Get values of given attribute from REST response. + /// + /// Complete REST response. + /// Object attribute to retrieve. + public static IEnumerable GetAttributesFromReponse(string response, string attributeName) + { + if (!string.IsNullOrEmpty(response) && !string.IsNullOrEmpty(attributeName)) + { + Regex idRegex = new Regex(string.Format(@"\<{0}\>(?[^\<\>]*)\", attributeName), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - /// - /// Get values of given attribute from REST response. - /// - /// Complete REST response. - /// Object attribute to retrieve. - public static IEnumerable GetAttributesFromReponse(string response, string attributeName) - { - if (!string.IsNullOrEmpty(response) && !string.IsNullOrEmpty(attributeName)) - { - Regex idRegex = new Regex(string.Format(@"\<{0}\>(?[^\<\>]*)\", attributeName), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + return idRegex.Matches(response).Cast().Select(m => m.Groups["id"].Value).ToList(); + } - return idRegex.Matches(response).Cast().Select(m => m.Groups["id"].Value).ToList(); - } - - return new List(); - } - } + return new List(); + } + } } diff --git a/ADImportService/Rest/RestSender.cs b/ADImportService/Rest/RestSender.cs index 197a057..8187cd9 100644 --- a/ADImportService/Rest/RestSender.cs +++ b/ADImportService/Rest/RestSender.cs @@ -1,516 +1,522 @@ using System; -using System.Linq; using System.Management.Instrumentation; namespace Kentico.ADImportService { - /// - /// Provides basic CMS operations with users and groups. - /// - public class RestSender : ISender - { - /// - /// REST provider object. - /// - public RestProvider Provider - { - get; - private set; - } - - - /// - /// Base URL used in REST requests. - /// - public string BaseUrl - { - get; - private set; - } - - - /// - /// Logger for tracking listener errors and actions. - /// - public Logger Logger - { - get; - private set; - } - - - /// - /// Fired when error occurrs. - /// - public event Action OnError; - - - /// - /// Fired when first changes are successfully sent to CMS. - /// - public event Action OnSuccess; - - - /// - /// Default constructor. - /// - /// Configuration used to construct REST provider. - /// Logger for logging events and errors. - public RestSender(RestConfiguration configuration, Logger logger) - { - Provider = new RestProvider(configuration.Encoding, configuration.UserName, configuration.Password, configuration.SslCertificateLocation); - BaseUrl = configuration.BaseUrl; - Logger = logger; - } - - - /// - /// Find out whether user with given GUID and name exists. - /// - /// Guid of user to check. - /// - public bool UserExists(Guid guid, string codeName) - { - if ((guid != Guid.Empty) && !string.IsNullOrEmpty(codeName)) - { - var response = Provider.MakeRequest(BaseUrl + "/rest/cms.user/all"); - return RestHelper.GetAttributesFromReponse(response, "UserGUID").Contains(guid.ToString("D"), StringComparer.InvariantCultureIgnoreCase) || RestHelper.GetAttributesFromReponse(response, "UserName").Contains(codeName, StringComparer.InvariantCultureIgnoreCase); - } - - return false; - } - - - /// - /// Find out whether user with given GUID exists. - /// - /// Guid of user to check. - public bool UserExists(Guid guid) - { - if (guid != Guid.Empty) - { - return - RestHelper.GetAttributesFromReponse(Provider.MakeRequest(BaseUrl + "/rest/cms.user/all"), "UserGUID").Contains(guid.ToString("D"), StringComparer.InvariantCultureIgnoreCase); - } - - return false; - } - - - /// - /// Get user XML representation. - /// - /// Guid of user to find. - public string GetUser(Guid guid) - { - if (guid != Guid.Empty) - { - try - { - // Get all users - return Provider.MakeRequest(BaseUrl + "/rest/cms.user/" + guid); - } - catch (InstanceNotFoundException) - { - // User doesn't exist - throw; - } - catch (Exception ex) - { - LogError("Retrieving user " + guid + " failed.", ex); - } - } - - return null; - } - - - /// - /// Add user to CMS. - /// - /// User to add - /// ID of added user. - public long? AddUser(User user) - { - if (user != null) - { - try - { - if (UserExists(user.Guid, user.CodeName)) - { - LogMessage("User " + user.CodeName + " was not added because it already exists."); - } - else - { - // Send REST request - var response = Provider.MakeRequest(BaseUrl + "/rest/cms.user", HttpVerb.Post, null,user.ToString()); - - var id = Convert.ToInt64(RestHelper.GetAttributeFromReponse(response, user.IdTagName)); - - LogMessage("User " + user.CodeName + " has been added."); - - if (OnSuccess != null) - { - OnSuccess(); - } - - return id; - } - } - catch (Exception ex) - { - LogError("Adding user " + user.CodeName + " failed.", ex); - } - } - - return null; - } - - - /// - /// Modify existing user in CMS. - /// - /// Modified user - /// ID of modified user. - public long? ModifyUser(User user) - { - if (user != null) - { - try - { - if (!UserExists(user.Guid)) - { - LogMessage("User " + user.CodeName + " was not modified because it doesn't exists."); - } - else - { - // Send REST request - var response = Provider.MakeRequest(BaseUrl + "/rest/cms.user/" + user.Guid, HttpVerb.Put, - null, user.ToString()); - - var id = Convert.ToInt64(RestHelper.GetAttributeFromReponse(response, user.IdTagName)); - - LogMessage("User " + user.CodeName + " has been modified."); - - if (OnSuccess != null) - { - OnSuccess(); - } - - return id; - } - } - catch (Exception ex) - { - LogError("Modifying user " + user.CodeName + " failed.", ex); - } - } - - return null; - } - - - /// - /// Remove user from CMS. - /// - /// User to delete. - public void RemoveUser(User user) - { - if (user != null) - { - try - { - // Send REST request - Provider.MakeRequest(BaseUrl + "/rest/cms.user/" + user.Guid.ToString("D"), HttpVerb.Delete); - - LogMessage("User " + user.CodeName + " has been removed."); - - if (OnSuccess != null) - { - OnSuccess(); - } - } - catch (Exception ex) - { - LogError("Removing user " + user.CodeName + " failed.", ex); - } - } - } - - - /// - /// Find out whether role with given GUID exist. - /// - /// Guid of role to check - public bool RoleExists(Guid guid) - { - try - { - var response = Provider.MakeRequest(BaseUrl + "/rest/cms.role/" + guid); - - return (!string.IsNullOrEmpty(response)); - } - catch (InstanceNotFoundException) - { - // Role doesn't exist - } - catch (Exception ex) - { - LogError("Retrieving role " + guid + " failed.", ex); - } - - return false; - } - - - /// - /// Get XML representation of given role. - /// - /// Id of role to find - public string GetRole(long id) - { - try - { - return Provider.MakeRequest(BaseUrl + "/rest/cms.role/" + id); - } - catch (InstanceNotFoundException) - { - // Role doesn't exist - throw; - } - catch (Exception ex) - { - LogError("Retrieving role " + id + " failed.", ex); - } - - return null; - } - - - /// - /// Find out whether role with given ID exist. - /// - /// Id of role to check - public bool RoleExists(long id) - { - try - { - return (!string.IsNullOrEmpty(GetRole(id))); - } - catch (InstanceNotFoundException) - { - // Role doesn't exist - } - catch (Exception ex) - { - LogError("Retrieving role " + id + " failed.", ex); - } - - return false; - } - - - /// - /// Add role to CMS. - /// - /// Role to add - /// ID of added role - public long? AddRole(Role role) - { - if (role != null) - { - try - { - if (RoleExists(role.Id)) - { - LogMessage("Role " + role.CodeName + " was not added because it already exists."); - } - else - { - // Send REST request - var response = Provider.MakeRequest(BaseUrl + "/rest/cms.role", HttpVerb.Post, null, - role.ToString()); - - var id = Convert.ToInt64(RestHelper.GetAttributeFromReponse(response, role.IdTagName)); - - LogMessage("Role " + role.CodeName + " has been added."); - - if (OnSuccess != null) - { - OnSuccess(); - } - - return id; - } - - } - catch (Exception ex) - { - LogError("Adding role " + role.CodeName + " failed.", ex); - } - - } - - return null; - } - - - /// - /// Modify existing role. - /// - /// Role to modify - public long? ModifyRole(Role role) - { - if (role != null) - { - try - { - if (!RoleExists(role.Id)) - { - LogMessage("Role " + role.CodeName + " was not modified because it doesn't exists."); - } - else - { - // Send REST request - var response = Provider.MakeRequest(BaseUrl + "/rest/cms.role/" + role.Id, HttpVerb.Put, - null, role.ToString()); - - var newId = Convert.ToInt64(RestHelper.GetAttributeFromReponse(response, role.IdTagName)); - - LogMessage("Role " + role.CodeName + " has been modified."); - - if (OnSuccess != null) - { - OnSuccess(); - } - - return newId; - } - } - catch (Exception ex) - { - LogError("Modifying role " + role.CodeName + " failed.", ex); - } - } - - return null; - } - - - /// - /// Remove role from CMS. - /// - /// Role to delete. - public void RemoveRole(Role role) - { - if (role != null) - { - try - { - // Send REST request - Provider.MakeRequest(BaseUrl + "/rest/cms.role/" + role.Guid.ToString("D"), HttpVerb.Delete); - - LogMessage("Role " + role.CodeName + " has been removed."); - - if (OnSuccess != null) - { - OnSuccess(); - } - } - catch (Exception ex) - { - LogError("Deleting role " + role.CodeName + " failed.", ex); - } - } - } - - - /// - /// Create user-role relationship. - /// - /// User to add to role - /// Role to assign - /// ID of added user-role relationship - public long? AddUserToRole(long userId, long roleId) - { - if ((userId > 0) && (roleId > 0)) - { - try - { - var userRole = new UserRoleBinding { UserId = userId, RoleId = roleId }; - - // Send REST request - var response = Provider.MakeRequest(BaseUrl + "/rest/cms.userrole", HttpVerb.Post, null, userRole.ToString()); - var id = Convert.ToInt64(RestHelper.GetAttributeFromReponse(response, userRole.IdTagName)); - - LogMessage("User " + userId + " has been added to role " + roleId + "."); - - if (OnSuccess != null) - { - OnSuccess(); - } - - return id; - - } - catch (Exception ex) - { - LogError("Adding user " + userId + " to role " + roleId + " failed.", ex); - } - } - - return null; - } - - - /// - /// Remove user-role relationship. - /// - /// User-role memberhip id. - public void RemoveUserFromRole(long id) - { - if (id > 0) - { - try - { - // Send REST request - Provider.MakeRequest(BaseUrl + "/rest/cms.userrole/" + id, HttpVerb.Delete); - - LogMessage("User membership " + id + " has been removed."); - - if (OnSuccess != null) - { - OnSuccess(); - } - } - catch (Exception ex) - { - LogError("Removing uer-role relationship with id " + id + " failed.", ex); - } - } - } - - - private void LogMessage(string message) - { - if (Logger != null) - { - Logger.LogMessage(message); - } - } - - - private void LogError(string message, Exception ex = null) - { - if (Logger != null) - { - Logger.LogError(message + "Check Kentico event log for more details.", ex); - } - - if (OnError != null) - { - OnError(); - } - } - } + /// + /// Provides basic CMS operations with users and groups. + /// + public class RestSender : ISender + { + /// + /// REST provider object. + /// + public RestProvider Provider + { + get; + } + + + /// + /// Base URL used in REST requests. + /// + public string BaseUrl + { + get; + } + + + /// + /// Logger for tracking listener errors and actions. + /// + public Logger Logger + { + get; + } + + + /// + /// Fired when error occurrs. + /// + public event Action OnError; + + + /// + /// Fired when first changes are successfully sent to CMS. + /// + public event Action OnSuccess; + + + /// + /// Default constructor. + /// + /// Configuration used to construct REST provider. + /// Logger for logging events and errors. + public RestSender(RestConfiguration configuration, Logger logger) + { + Provider = new RestProvider(configuration.Encoding, configuration.UserName, configuration.Password, configuration.SslCertificateLocation); + BaseUrl = configuration.BaseUrl; + Logger = logger; + } + + + /// + /// Find out whether user with given GUID and name exists. + /// + /// Guid of user to check. + /// + public bool UserExists(Guid guid, string codeName) + { + return UserExists(codeName) || UserExists(guid); + } + + + /// + /// Find out whether user with given name exists. + /// + /// + public bool UserExists(string codeName) + { + if (!string.IsNullOrEmpty(codeName)) + { + var response = Provider.MakeRequest(BaseUrl + "/rest/cms.user/" + codeName); + return string.Equals(RestHelper.GetAttributeFromReponse(response, "UserName"), codeName, StringComparison.InvariantCultureIgnoreCase); + } + + return false; + } + + + /// + /// Find out whether user with given GUID exists. + /// + /// Guid of user to check. + public bool UserExists(Guid guid) + { + if (guid != Guid.Empty) + { + var response = Provider.MakeRequest(BaseUrl + "/rest/cms.user/" + guid); + return string.Equals(RestHelper.GetAttributeFromReponse(response, "UserGUID"), guid.ToString("D"), StringComparison.InvariantCultureIgnoreCase); + } + + return false; + } + + + /// + /// Get user XML representation. + /// + /// Guid of user to find. + public string GetUser(Guid guid) + { + if (guid != Guid.Empty) + { + try + { + // Get all users + return Provider.MakeRequest(BaseUrl + "/rest/cms.user/" + guid); + } + catch (InstanceNotFoundException) + { + // User doesn't exist + throw; + } + catch (Exception ex) + { + LogError("Retrieving user " + guid + " failed.", ex); + } + } + + return null; + } + + + /// + /// Add user to CMS. + /// + /// User to add + /// ID of added user. + public long? AddUser(User user) + { + if (user != null) + { + try + { + if (UserExists(user.Guid, user.CodeName)) + { + LogMessage("User " + user.CodeName + " was not added because it already exists."); + } + else + { + // Send REST request + var response = Provider.MakeRequest(BaseUrl + "/rest/cms.user", HttpVerb.Post, null, user.ToString()); + + var id = Convert.ToInt64(RestHelper.GetAttributeFromReponse(response, user.IdTagName)); + + LogMessage("User " + user.CodeName + " has been added."); + + if (OnSuccess != null) + { + OnSuccess(); + } + + return id; + } + } + catch (Exception ex) + { + LogError("Adding user " + user.CodeName + " failed.", ex); + } + } + + return null; + } + + + /// + /// Modify existing user in CMS. + /// + /// Modified user + /// ID of modified user. + public long? ModifyUser(User user) + { + if (user != null) + { + try + { + if (!UserExists(user.Guid)) + { + LogMessage("User " + user.CodeName + " was not modified because it doesn't exists."); + } + else + { + // Send REST request + var response = Provider.MakeRequest(BaseUrl + "/rest/cms.user/" + user.Guid, HttpVerb.Put, + null, user.ToString()); + + var id = Convert.ToInt64(RestHelper.GetAttributeFromReponse(response, user.IdTagName)); + + LogMessage("User " + user.CodeName + " has been modified."); + + if (OnSuccess != null) + { + OnSuccess(); + } + + return id; + } + } + catch (Exception ex) + { + LogError("Modifying user " + user.CodeName + " failed.", ex); + } + } + + return null; + } + + + /// + /// Remove user from CMS. + /// + /// User to delete. + public void RemoveUser(User user) + { + if (user != null) + { + try + { + // Send REST request + Provider.MakeRequest(BaseUrl + "/rest/cms.user/" + user.Guid.ToString("D"), HttpVerb.Delete); + + LogMessage("User " + user.CodeName + " has been removed."); + + if (OnSuccess != null) + { + OnSuccess(); + } + } + catch (Exception ex) + { + LogError("Removing user " + user.CodeName + " failed.", ex); + } + } + } + + + /// + /// Find out whether role with given GUID exist. + /// + /// Guid of role to check + public bool RoleExists(Guid guid) + { + try + { + var response = Provider.MakeRequest(BaseUrl + "/rest/cms.role/" + guid); + + return (!string.IsNullOrEmpty(response)); + } + catch (InstanceNotFoundException) + { + // Role doesn't exist + } + catch (Exception ex) + { + LogError("Retrieving role " + guid + " failed.", ex); + } + + return false; + } + + + /// + /// Get XML representation of given role. + /// + /// Id of role to find + public string GetRole(long id) + { + try + { + return Provider.MakeRequest(BaseUrl + "/rest/cms.role/" + id); + } + catch (InstanceNotFoundException) + { + // Role doesn't exist + throw; + } + catch (Exception ex) + { + LogError("Retrieving role " + id + " failed.", ex); + } + + return null; + } + + + /// + /// Find out whether role with given ID exist. + /// + /// Id of role to check + public bool RoleExists(long id) + { + try + { + return (!string.IsNullOrEmpty(GetRole(id))); + } + catch (InstanceNotFoundException) + { + // Role doesn't exist + } + catch (Exception ex) + { + LogError("Retrieving role " + id + " failed.", ex); + } + + return false; + } + + + /// + /// Add role to CMS. + /// + /// Role to add + /// ID of added role + public long? AddRole(Role role) + { + if (role != null) + { + try + { + if (RoleExists(role.Id)) + { + LogMessage("Role " + role.CodeName + " was not added because it already exists."); + } + else + { + // Send REST request + var response = Provider.MakeRequest(BaseUrl + "/rest/cms.role", HttpVerb.Post, null, + role.ToString()); + + var id = Convert.ToInt64(RestHelper.GetAttributeFromReponse(response, role.IdTagName)); + + LogMessage("Role " + role.CodeName + " has been added."); + + if (OnSuccess != null) + { + OnSuccess(); + } + + return id; + } + + } + catch (Exception ex) + { + LogError("Adding role " + role.CodeName + " failed.", ex); + } + + } + + return null; + } + + + /// + /// Modify existing role. + /// + /// Role to modify + public long? ModifyRole(Role role) + { + if (role != null) + { + try + { + if (!RoleExists(role.Id)) + { + LogMessage("Role " + role.CodeName + " was not modified because it doesn't exists."); + } + else + { + // Send REST request + var response = Provider.MakeRequest(BaseUrl + "/rest/cms.role/" + role.Id, HttpVerb.Put, + null, role.ToString()); + + var newId = Convert.ToInt64(RestHelper.GetAttributeFromReponse(response, role.IdTagName)); + + LogMessage("Role " + role.CodeName + " has been modified."); + + if (OnSuccess != null) + { + OnSuccess(); + } + + return newId; + } + } + catch (Exception ex) + { + LogError("Modifying role " + role.CodeName + " failed.", ex); + } + } + + return null; + } + + + /// + /// Remove role from CMS. + /// + /// Role to delete. + public void RemoveRole(Role role) + { + if (role != null) + { + try + { + // Send REST request + Provider.MakeRequest(BaseUrl + "/rest/cms.role/" + role.Guid.ToString("D"), HttpVerb.Delete); + + LogMessage("Role " + role.CodeName + " has been removed."); + + if (OnSuccess != null) + { + OnSuccess(); + } + } + catch (Exception ex) + { + LogError("Deleting role " + role.CodeName + " failed.", ex); + } + } + } + + + /// + /// Create user-role relationship. + /// + /// User to add to role + /// Role to assign + /// ID of added user-role relationship + public long? AddUserToRole(long userId, long roleId) + { + if ((userId > 0) && (roleId > 0)) + { + try + { + var userRole = new UserRoleBinding { UserId = userId, RoleId = roleId }; + + // Send REST request + var response = Provider.MakeRequest(BaseUrl + "/rest/cms.userrole", HttpVerb.Post, null, userRole.ToString()); + var id = Convert.ToInt64(RestHelper.GetAttributeFromReponse(response, userRole.IdTagName)); + + LogMessage("User " + userId + " has been added to role " + roleId + "."); + + if (OnSuccess != null) + { + OnSuccess(); + } + + return id; + + } + catch (Exception ex) + { + LogError("Adding user " + userId + " to role " + roleId + " failed.", ex); + } + } + + return null; + } + + + /// + /// Remove user-role relationship. + /// + /// User-role memberhip id. + public void RemoveUserFromRole(long id) + { + if (id > 0) + { + try + { + // Send REST request + Provider.MakeRequest(BaseUrl + "/rest/cms.userrole/" + id, HttpVerb.Delete); + + LogMessage("User membership " + id + " has been removed."); + + if (OnSuccess != null) + { + OnSuccess(); + } + } + catch (Exception ex) + { + LogError("Removing uer-role relationship with id " + id + " failed.", ex); + } + } + } + + + private void LogMessage(string message) + { + if (Logger != null) + { + Logger.LogMessage(message); + } + } + + + private void LogError(string message, Exception ex = null) + { + if (Logger != null) + { + Logger.LogError(message + "Check Kentico event log for more details.", ex); + } + + if (OnError != null) + { + OnError(); + } + } + } }