How to create my custom RegularExpressionValidator that gets the RegularExpression and ErrorMessage from Resource file?
[RegularExpression(#"\d{5}(-\d{4})?",
ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "regExpValforPostal_ErrorMessage")]
public string PostalCode { get; set; }
The resource file name is Global :
Global.resx, Global.zh.resx, Global.fr-ca.resx
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class LocalizedRegexAttribute : RegularExpressionAttribute
{
static LocalizedRegexAttribute()
{
// necessary to enable client side validation
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalizedRegexAttribute), typeof(RegularExpressionAttributeAdapter));
}
public LocalizedRegexAttribute(string _RegularExpression, string _ErrorMessageResourceName, Type _ErrorMessageResourceType)
: base(LoadRegex(_RegularExpression))
{
ErrorMessageResourceType = _ErrorMessageResourceType;
ErrorMessageResourceName = _ErrorMessageResourceName;
}
private static string LoadRegex(string key)
{
var resourceManager = new ResourceManager(typeof(Water.Localization.Resources.Global));
return resourceManager.GetString(key);
}
In your model class you need to pass 3 parameters with the custom data
annotation as follows:
[LocalizedRegex("regExpValforPostal_ValidationExpression", "regExpValforPostal_ErrorMessage", typeof(Global))]
public string PostalCode { get; set; }
if your resources file called Validations.he.resx
and inside it you have both 'RegexExpression' and 'ErrorMessage' you should use this:
UPDATE #1: Option 2 added
Option 1:
public class LocalizedRegexAttribute :RegularExpressionAttribute
{
public LocalizedRegexAttribute () : base(Validations.RegexExpression)
{
}
public override string FormatErrorMessage(string name)
{
return base.FormatErrorMessage(ValidationStrings.ErrorMessage);
}
}
Option 2:
public class EmailAddressAttribute :ValidationAttribute {
public EmailAddressAttribute()
{
}
public override bool IsValid(object value)
{
Regex regex = new Regex(Validations.RegexExpression);
return regex.IsMatch(value.ToString());
}
public override string FormatErrorMessage(string name)
{
return base.FormatErrorMessage(ValidationStrings.ErrorMessage);
} }
than you will use it like this:
[LocalizedRegexAttribute]
public string PostalCode { get; set; }
Related
I am writing a Provider Hosted APP using SP 2013 and I have a data layer which uses REST to CRUD on sharepoint lists. Now I got the List items in JSON format but I am not able to iterate through the list data can you please help in doing that? (is there any class for List Items which I can deserialize into?)
This is the code
public JToken GetListData(string webUrl, string userName, SecureString password, string listTitle)
{
using (var client = new WebClient())
{
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Credentials = new SharePointOnlineCredentials(userName, password);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json;odata=verbose");
client.Headers.Add(HttpRequestHeader.Accept, "application/json;odata=verbose");
var endpointUri = new Uri(new Uri(webUrl), string.Format("/sites/DTF/_api/web/lists/getbytitle('{0}')/Items", listTitle));
var result = client.DownloadString(endpointUri);
var t = JToken.Parse(result);
return t["d"];
}
}
You need to use the DataContractJsonSerializer class to deserialize the data as is demonstrated here:
http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET
To make this work though you have to create classes that match the structure of the Json. The easiest way to do this copying a raw Json response into a tool which will generate the classes like this one:
http://json2csharp.com/
The actual classes you will need to generate varies based on the structure of the data you are getting in your REST response. Here is an example I created that demonstrates making a request, parsing the Json Response and downloading a file based on the result:
public class JsonHelper
{
/// JSON Serialization
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
/// JSON Deserialization
public static T JsonDeserialize<T>(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
}
//Custom Json Classes
public class RootObject
{
public D d { get; set; }
}
public class D
{
public GetContextWebInformation GetContextWebInformation { get; set; }
public List<Result> results { get; set; }
}
public class GetContextWebInformation
{
public int FormDigestTimeoutSeconds { get; set; }
public string FormDigestValue { get; set; }
public string LibraryVersion { get; set; }
public string SiteFullUrl { get; set; }
public string WebFullUrl { get; set; }
}
public class Result
{
public ContentType ContentType { get; set; }
public string EncodedAbsUrl { get; set; }
public string FileLeafRef { get; set; }
public Folder Folder { get; set; }
public int FileSystemObjectType { get; set; }
public int Id { get; set; }
public string ContentTypeId { get; set; }
public string Title { get; set; }
public int? ImageWidth { get; set; }
public int? ImageHeight { get; set; }
public string ImageCreateDate { get; set; }
public object Description { get; set; }
public object Keywords { get; set; }
public string OData__dlc_DocId { get; set; }
public int ID { get; set; }
public string Created { get; set; }
public int AuthorId { get; set; }
public string Modified { get; set; }
public int EditorId { get; set; }
public object OData__CopySource { get; set; }
public int? CheckoutUserId { get; set; }
public string OData__UIVersionString { get; set; }
public string GUID { get; set; }
}
//SharePoint Calls
class Program
{
static void Main()
{
string url = "https://sharepoint.wilsonconst.com/";
string filename = "2010-07-23 13.32.22.jpg";
string digest = "";
HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
string cmd = "_api/contextinfo";
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json");
client.DefaultRequestHeaders.Add("ContentLength", "0");
StringContent httpContent = new StringContent("");
HttpResponseMessage response = client.PostAsync(cmd, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
RootObject sp = JsonHelper.JsonDeserialize<RootObject>(content);
digest = sp.d.GetContextWebInformation.FormDigestValue;
}
client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
client.DefaultRequestHeaders.Add("X-HTTP-Method", "GET");
string uri = "_api/web/lists/GetByTitle('Wilson Pictures')/Items?$select=ID,FileLeafRef,EncodedAbsUrl&$filter=FileLeafRef eq '" + filename + "'";
HttpResponseMessage response2 = client.GetAsync(uri).Result;
response2.EnsureSuccessStatusCode();
if (response2.IsSuccessStatusCode)
{
string listItems = response2.Content.ReadAsStringAsync().Result;
RootObject sp = JsonHelper.JsonDeserialize<RootObject>(listItems);
foreach (Result result in sp.d.results)
{
MemoryStream stream = (MemoryStream)client.GetAsync(result.EncodedAbsUrl).Result.Content.ReadAsStreamAsync().Result;
using(FileStream fileStream = System.IO.File.Create(#"C:\" + result.FileLeafRef))
{
stream.WriteTo(fileStream);
}
}
}
else
{
var content = response.Content.ReadAsStringAsync();
}
}
This seems like a lot of complexity, but really it makes working with Json objects quite easy and takes only moments to setup before you can start calling your custom objects to easily manipulate the data.
Assuming that you want to retrieve data from SharePoint Online the following example demonstrates how to consume SharePoint REST Interface via WebClient Class:
using (var client = new SPRestClient(webUri.ToString()))
{
client.Credentials = GetCredentials(webUri,userName,password);
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
var data = client.GetJson("/_api/lists/getbytitle('Tasks')/items"); //get list items
//print list item's title
foreach (var item in data["d"]["results"])
{
Console.WriteLine(item["Title"]);
}
}
where
public static SharePointOnlineCredentials GetCredentials(Uri webUri, string userName, string password)
{
var securePassword = new SecureString();
foreach (var ch in password) securePassword.AppendChar(ch);
return new SharePointOnlineCredentials(userName, securePassword);
}
and
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace SharePoint.Client
{
public class SPRestClient : WebClient
{
public SPRestClient(string webUri)
{
BaseAddress = webUri;
FormatType = JsonFormatType.Verbose;
}
public JObject GetJson(string requestUri)
{
return ExecuteJson(requestUri, HttpMethod.Get, null, default(string));
}
public JObject ExecuteJson<T>(string requestUri, HttpMethod method, IDictionary<string, string> headers, T data)
{
string result;
var uri = BaseAddress + requestUri;
if (headers != null)
{
foreach (var key in headers.Keys)
{
Headers.Add(key, headers[key]);
}
}
EnsureRequest(method);
switch (method.Method)
{
case "GET":
result = DownloadString(uri);
break;
case "POST":
if (data != null)
{
var payload = JsonConvert.SerializeObject(data);
result = UploadString(uri, method.Method, payload);
}
else
{
result = UploadString(uri, method.Method);
}
break;
default:
throw new NotSupportedException(string.Format("Method {0} is not supported", method.Method));
}
return JObject.Parse(result);
}
private void EnsureRequest(HttpMethod method)
{
var mapping = new Dictionary<JsonFormatType, string>();
mapping[JsonFormatType.Verbose] = "application/json;odata=verbose";
mapping[JsonFormatType.MinimalMetadata] = "application/json; odata=minimalmetadata";
mapping[JsonFormatType.NoMetadata] = "application/json; odata=nometadata";
Headers.Add(HttpRequestHeader.ContentType, mapping[FormatType]);
Headers.Add(HttpRequestHeader.Accept, mapping[FormatType]);
if (method == HttpMethod.Post)
{
Headers.Add("X-RequestDigest", RequestFormDigest());
}
}
private string RequestFormDigest()
{
var endpointUrl = string.Format("{0}/_api/contextinfo", BaseAddress);
var result = UploadString(endpointUrl, "Post");
var contentJson = JObject.Parse(result);
return contentJson["FormDigestValue"].ToString();
}
public JsonFormatType FormatType { get; set; }
}
public enum JsonFormatType
{
Verbose,
MinimalMetadata,
NoMetadata
}
}
SPRestClient.cs
I have created a bunch of custom templates to store items (such as Industries, Subindustries, etc.) in Sitecore. I now want to go about loading these into my Sitecore MVC model.
The lists are located in sitecore > Content > Lists. For example inside the Lists folder there is a folder called Country. I want to get back all the items within the Country folder and populate them as unordered list in my view.
UPDATE: I implemented the Glass.Mapper.Sc method suggested below. It is fully operational now.
This is what my working model looks like now:
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.Configuration.Attributes;
using Sitecore.Data.Items;
using Sitecore.Mvc.Presentation;
using System;
using System.Collections.Generic;
namespace Sitecore.Web.Models
{
public class Registration: IRenderingModel
{
public Rendering Rendering { get; set; }
public Item Item { get; set; }
public Item PageItem { get; set; }
public IEnumerable<CountryChildItem> CountryList { get; set; }
[SitecoreType(AutoMap = true)]
public class CountryItem
{
public virtual IEnumerable<CountryChildItem> Children { get; set; }
}
[SitecoreType(AutoMap = true)]
public class CountryChildItem
{
[SitecoreId]
public virtual Guid Id { get; set; }
[SitecoreInfo(SitecoreInfoType.Path)]
public virtual string Path { get; set; }
[SitecoreField]
public virtual string DisplayName { get; set; }
[SitecoreField]
public virtual string Abbreviation { get; set; }
}
public void Initialize(Rendering rendering)
{
Rendering = rendering;
Item = rendering.Item;
PageItem = PageContext.Current.Item;
}
}
}
and this is what my working contoller looks like:
using Glass.Mapper.Sc;
using Sitecore.Web.Models;
using System.Web.Mvc;
namespace Sitecore.Web.Controllers
{
public class RegistrationController : Controller
{
Registration registrationModel = new Registration();
public ActionResult Index()
{
ISitecoreContext sitecoreContext = new SitecoreContext();
ISitecoreService service = new SitecoreService(sitecoreContext.Database);
Registration.CountryItem countryItem = service.GetItem<Registration.CountryItem>("/sitecore/content/Lists/Country");
registrationModel.CountryList = countryItem.Children;
return View(registrationModel);
}
}
}
and a snippet of my working view:
<ul class="select-menu-options dropdown-menu">
#foreach (var country in Model.CountryList)
{
<li>#country.DisplayName</li>
}
</ul>
If I were in your position I'd look into Glassmapper for Sitecore.
It's a fairly lightweight ORM for Sitecore.
http://www.glass.lu/Mapper/Sc
I'd also suggest moving the lists located in
sitecore > Templates > User Defined > Lists > Content
to some where under either
sitecore > Content
or
sitecore > System
(whichever makes more sence)
UPDATE:
Try adding this above your class:
[SitecoreType(AutoMap = true)]
public class CountryItem
{
//...
}
If you change your CountryItem and other model classes to inherit from SearchResultItem like that:
[PredefinedQuery("TemplateID", ComparisonType.Equal, "{ID-OF-CountryItem-TEMPLATE}", typeof(ID))]
public class CountryItem : Sitecore.ContentSearch.SearchTypes.SearchResultItem
{
[IndexField("_displayname")]
public virtual string DisplayName { get; set; }
[IndexField("abbreviation")]
public string Abbreviation { get; set; }
}
You should be able to use Sitecore indexes to retrieve all the countries and other lists like that:
private static string IndexName
{
get
{
return string.Format("sitecore_{0}_index", (Context.ContentDatabase ?? Context.Database).Name);
}
}
private static string Language { get { return Context.Language.Name; } }
public IEnumerable<CountryItem> GetCountries()
{
using (var context = ContentSearchManager.GetIndex(IndexName).CreateSearchContext())
{
IQueryable<CountryItem> queryable = context.GetQueryable<CountryItem>();
queryable = queryable.Where(i => i.Language == Language);
queryable = queryable.Where(i => i.LatestVersion);
// ... maybe excluding standard values or some other filters
var searchResults = queryable.GetResults();
return queryable.ToList();
}
}
Please be aware that this is just an example. You need to test it and most probably adapt to your solution.
And as Dar Brett mentioned, you should not keep any data items under the Templates node.
I have the following structure as Template in visual studio :
Under a page, i have one or more link root
[SitecoreType(TemplateId = "{4AAA9A10-36C2-484F-A648-2BEF349F0052}", AutoMap = true)]
public class LinkRoot : IBaseTemplate
{
[SitecoreChildren(InferType = true)]
public virtual IEnumerable<LinkItem> Children { get; set; }
[SitecoreInfo(SitecoreInfoType.TemplateId)]
public virtual Guid TemplateId { get; set; }
public Guid Id { get; set; }
public string Language { get; set; }
public ItemUri Uri { get; set; }
public int Version { get; private set; }
}
Under the link root i've LinkItems
[SitecoreType(AutoMap = true)]
public class LinkItem : IBaseTemplate
{
[SitecoreField("Link Name")]
public virtual string LinkName { get; set; }
[SitecoreField("Link")]
public virtual Link Link { get; set; }
public Guid Id { get; set; }
public string Language { get; set; }
public ItemUri Uri { get; set; }
public int Version { get; private set; }
}
I display those items in a view like that :
#foreach (var link in Model.Children.Where(o => o.TemplateId.Equals(TemplateIDs.LinksRoot.Guid)))
{
foreach (var linkChildren in link.Children)
{
using (BeginRenderLink(linkChildren, x => x.Link, isEditable: true))
{
#Editable(linkChildren, x => x.LinkName)
}
}
}
It works great, i can see my links with the good name etc, but when i go to the page editor i got this error :
Value cannot be null. Parameter name: objectToSwitchTo
at Sitecore.Diagnostics.Assert.ArgumentNotNull(Object argument, String argumentName)
at Sitecore.Common.Switcher2.Enter(TValue objectToSwitchTo)
at Sitecore.Data.Items.ContextItemSwitcher..ctor(Item item)
at Glass.Mapper.Sc.GlassHtml.MakeEditable[T](Expression1 field, Expression`1 standardOutput, T model, Object parameters, Context context, Database database, TextWriter writer)
Does someone already experienced that or have an idea why i have this error ?
Thanks
I think it means that Glass can't resolve the template of the LinkItem model.
Instead of:
[SitecoreType(AutoMap = true)]
public class LinkItem : IBaseTemplate
Try to explicitly define the template ID:
[SitecoreType(TemplateId = "{your-template-guid}", AutoMap = true)]
public class LinkItem : IBaseTemplate
I think this might be a bug, can you log it on github as an issue.
I have a Apicontroller Which has dependency on unit of work object. How to write a test case for mocking ApiController Which has dependency on unit of work implemented in ApiController constructor.
Here is the code:
ApiController:
public class UserController : ApiController
{
public IUoW UoW { get; set; }
// GET api/user
public UserController(IUoW uow)
{
UoW = uow;
}
public IEnumerable<Users> Get()
{
return UoW.Users.Getall();
}
}
The Test case :
[TestMethod]
public void TestApiController()
{
var userManager = new Mock<IUoW>();
userManager.Setup(s => s.Users);
var controller = new UserController(userManager.Object);
var values = controller.Get();
Assert.IsNotNull(values);
}
The Users Class which has been mentioned here in UoW.Users is
public class UoW:IUoW,IDisposable
{
private MvcWebApiContext DbContext { get; set; }
protected IRepositoryProvider RepositoryProvider { get; set; }
private IRepository<T> GetStandardRepo<T>() where T : class
{
return RepositoryProvider.GetRepositoryForEntityType<T>();
}
public IRepository<Users> Users
{
get { return GetStandardRepo<Users>(); }
}
}
and the Users class itself is
[Table("UserProfile")]
public class Users
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
[DataType(DataType.PhoneNumber)]
public long Mobile { get; set; }
}
When I am trying to debug the test case , the Test case shows the object UoW.Users is null in UserController. Its obvious its not initializing through WebActivator since global.asax isnt invoked here through mock. Now how to write a successful test scenario in this context so that the WebApicontroller returns me the users object with data ?
Are you using Moq?
As I cannot see what type the UoW.Users property is I cannot demo how to mock it properly (updated IRepository) but that should be mocked and the GetAll method stubbed to return a sample list of users.
Updated
var userManager = new Mock<IUoW>();
userManager.Setup(s => s.Users).Returns(()=>
{
var userReposisitory = new Mock<IRepository<Users>>();
userReposisitory.Setup(ur => ur.GetAll()).Returns(()=> {
var listOfUsers = new List<Users>();
listOfUsers.Add(new Users { FirstName = "Example" });
return listOfUsers.AsQueryable();
});
return userReposisitory.Object;
});
var controller = new UserController(userManager.Object);
var result = controller.Get();
Assert.IsNotNull(result);
Assert.IsTrue(result.Count() > 0);
I want to manage users and Roles in the cliente side, but i cannot find the way to accomplish this. Links or code will be very appreciated.
Sorry for this abandoned question, i have solved this issue many days ago now, and i fill i should post the answer here because i couldnt find a complete answer in the web and this can help some soul in distress over there. Except for a link that i cannot remember right now but,my apologise to the blog owner for not remember even his name, however, here is the full history:
First create a class to wrap MembershipUser and another one to wrap MembsershipRole:
public class MembershipServiceUser
{
public string Comment { get; set; }
[Editable(false)]
public DateTime CreationDate { get; set; }
[Key]
[Editable(false, AllowInitialValue = true)]
public string Email { get; set; }
public bool IsApproved { get; set; }
[Editable(false)]
public bool IsLockedOut { get; set; }
[Editable(false)]
public bool IsOnline { get; set; }
public DateTime LastActivityDate { get; set; }
[Editable(false)]
public DateTime LastLockoutDate { get; set; }
public DateTime LastLoginDate { get; set; }
[Editable(false)]
public DateTime LastPasswordChangedDate { get; set; }
[Editable(false)]
public string PasswordQuestion { get; set; }
[Key]
[Editable(false, AllowInitialValue = true)]
public string UserName { get; set; }
public MembershipServiceUser() { }
public MembershipServiceUser(MembershipUser user)
{
this.FromMembershipUser(user);
}
public void FromMembershipUser(MembershipUser user)
{
this.Comment = user.Comment;
this.CreationDate = user.CreationDate;
this.Email = user.Email;
this.IsApproved = user.IsApproved;
this.IsLockedOut = user.IsLockedOut;
this.IsOnline = user.IsOnline;
this.LastActivityDate = user.LastActivityDate;
this.LastLockoutDate = user.LastLockoutDate;
this.LastLoginDate = user.LastLoginDate;
this.LastPasswordChangedDate = user.LastPasswordChangedDate;
this.PasswordQuestion = user.PasswordQuestion;
this.UserName = user.UserName;
}
public MembershipUser ToMembershipUser()
{
MembershipUser user = Membership.GetUser(this.UserName);
if (user.Comment != this.Comment) user.Comment = this.Comment;
if (user.IsApproved != this.IsApproved) user.IsApproved = this.IsApproved;
if (user.LastActivityDate != this.LastActivityDate) user.LastActivityDate = this.LastActivityDate;
if (user.LastLoginDate != this.LastLoginDate) user.LastLoginDate = this.LastLoginDate;
return user;
}
}
//Roles
public class MembershipServiceRole {
public MembershipServiceRole() { }
public MembershipServiceRole(string rolename) {
RoleName = rolename;
}
[Key]
[Editable(true, AllowInitialValue = true)]
public string RoleName { get; set; }
}
Second, create a class derived from DomainService to manipulate users and roles wrappers:
[EnableClientAccess(RequiresSecureEndpoint = false /* This should be set to true before the application is deployed */)]
public class MembershipService : DomainService
{
protected override void OnError(DomainServiceErrorInfo errorInfo)
{
TimeoutHelper.HandleAuthenticationTimeout(errorInfo, this.ServiceContext.User);
}
[RequiresRole("Administrator")]
public IEnumerable<MembershipServiceUser> GetUsers()
{
return Membership.GetAllUsers().Cast<MembershipUser>().Select(u => new MembershipServiceUser(u));
}
[RequiresRole("Administrator")]
public IEnumerable<MembershipServiceUser> GetUsersByEmail(string email)
{
return Membership.FindUsersByEmail(email).Cast<MembershipUser>().Select(u => new MembershipServiceUser(u));
}
[RequiresRole("Administrator")]
public MembershipServiceUser GetUsersByName(string userName)
{
MembershipServiceUser retVal = null;
retVal = Membership.FindUsersByName(userName)
.Cast<MembershipUser>()
.Select(u => new MembershipServiceUser(u))
.FirstOrDefault();
return retVal;
}
[Invoke(HasSideEffects = true)]
public void CreateUser(MembershipServiceUser user, string password)
{
if (string.IsNullOrEmpty(user.Email)) {
user.Email = "cambiar#dominio.com";
}
Membership.CreateUser(user.UserName, password, user.Email);
}
[RequiresRole("Administrator")]
public void DeleteUser(MembershipServiceUser user)
{
Membership.DeleteUser(user.UserName);
}
[RequiresRole("Administrator")]
public void UpdateUser(MembershipServiceUser user)
{
Membership.UpdateUser(user.ToMembershipUser());
}
[RequiresRole("Administrator")]
[Update(UsingCustomMethod = true)]
public void ChangePassword(MembershipServiceUser user, string newPassword)
{
MembershipUser u = user.ToMembershipUser();
u.ChangePassword(u.ResetPassword(), newPassword);
}
[RequiresRole("Administrator")]
public void ResetPassword(MembershipServiceUser user)
{
user.ToMembershipUser().ResetPassword();
}
[RequiresRole("Administrator")]
public void UnlockUser(MembershipServiceUser user)
{
user.ToMembershipUser().UnlockUser();
}
#region Roles
[RequiresRole("Administrator")]
public IEnumerable<MembershipServiceRole> GetRoles() {
return Roles.GetAllRoles().Cast<string>().Select(r => new MembershipServiceRole(r));
}
[RequiresRole("Administrator")]
public IEnumerable<MembershipServiceRole> GetRolesForUser(string userName) {
return Roles.GetRolesForUser(userName).Cast<string>().Select(r => new MembershipServiceRole(r));
}
[RequiresRole("Administrator")]
public void CreateRole(MembershipServiceRole role) {
Roles.CreateRole(role.RoleName);
}
[RequiresRole("Administrator")]
public void DeleteRole(MembershipServiceRole role) {
Roles.DeleteRole(role.RoleName);
}
[RequiresRole("Administrator")][Invoke]
public void AddUserToRole(string userName, string roleName) {
if (!Roles.IsUserInRole(userName,roleName))
Roles.AddUserToRole(userName, roleName);
}
[RequiresRole("Administrator")]
[Invoke]
public void RemoveUserFromRole(string userName, string roleName) {
if (Roles.IsUserInRole(userName, roleName))
Roles.RemoveUserFromRole(userName, roleName);
}
#endregion //Roles
}
Third: Use the service the same way you do for your domains clases
Cheers!!!