Sitecore User Profile Settings not saved when created programmatically - asp.net

I'm building a registration component on a Sitecore Site (Sitecore 7.0 ) and while the users are being created, none of the custom profile or role is being created. There are no errors in the logs. The user that is created has the correct user name and domain, but does not have the custom profile and lacks the full name, email address, role and additional custom fields. Has anyone encountered any related difficulties achieving this?
N.b. using email address as username if that will make any difference. I've updated the config to allow this. I've also added some logging underneath, which all outputs the correct information.
Here's a sample of the code:
try
{
if (!User.Exists(userEntity.EmailAddress))
{
var user = Membership.CreateUser(CreateUserName(userEntity), userEntity.Password,
userEntity.EmailAddress);
User scUser = User.FromName(userEntity.EmailAddress, true);
if (Role.Exists(Constants.Roles.ExampleRole) && !scUser.IsInRole(Constants.Roles.ExampleRole))
{
Roles.AddUserToRole(userEntity.EmailAddress, Constants.Roles.ExampleRole);
}
if (scUser != null)
{
using (new Sitecore.SecurityModel.SecurityDisabler())
{
scUser.Profile.FullName = userEntity.FirstName + " " + userEntity.LastName;
scUser.Profile.ProfileItemId = Constants.CustomUserProfile.ToString();
scUser.Profile.SetCustomProperty(UserFields.FirstName, userEntity.FirstName);
scUser.Profile.SetCustomProperty(UserFields.LastName, userEntity.LastName);
scUser.Profile.SetCustomProperty(UserFields.EmailAddress, userEntity.EmailAddress);
scUser.Profile.SetCustomProperty(UserFields.TelephoneNumber, userEntity.TelephoneNumber);
scUser.Profile.SetCustomProperty(UserFields.CompanyName, userEntity.CompanyName);
scUser.Profile.SetCustomProperty(UserFields.Sector, userEntity.Sector);
scUser.Profile.SetCustomProperty(UserFields.AddressLine1, userEntity.AddressLine1);
scUser.Profile.SetCustomProperty(UserFields.AddressLine2, userEntity.AddressLine2);
scUser.Profile.SetCustomProperty(UserFields.City, userEntity.City);
scUser.Profile.SetCustomProperty(UserFields.PostCode, userEntity.Postcode);
scUser.Profile.SetCustomProperty(UserFields.State, userEntity.State);
scUser.Profile.SetCustomProperty(UserFields.Country, CountryUtility.GetCountryNameById(userEntity.SelectedCountryId));
scUser.Profile.Save();
result = true;
}
Membership.UpdateUser(user);
Log.Info(scUser.Profile.FullName, new object());
Log.Info(scUser.Profile.ProfileItemId, new object());
Log.Info(scUser.Profile.GetCustomProperty(UserFields.FirstName), new object());
Log.Info(scUser.Profile.GetCustomProperty(UserFields.City), new object());
Log.Info(scUser.Profile.GetCustomProperty(UserFields.Country), new object());
Log.Info(scUser.IsInRole(Constants.Roles.ExampleRole) ? "true" : "false", new object());
}
}
else
{
throw new Exception(Nodes.Dictionary.Fields[DictionaryFields.RegistrationForm.UsernameExists].Value);
}
}
catch (Exception exception)
{
Log.Error(exception.Message, "RegistrationController");
}

I think you need to use the fully qualified user name when loading the user from Sitecore, like this (assuming extranet domain):
User scUser = User.FromName("extranet\\" + userEntity.EmailAddress, true);
The reason everything seems to work in your code is because you get a user back from User.FromName(...) wether the user actually exists or not.

Related

asp.net basic routing not working

I'm working on asp.net web forms and i got some issue with routing, following route is not working:
RouteTable.Routes.Add(new Route("{resource}.axd/{*pathInfo}", new StopRoutingHandler()));
RouteTable.Routes.MapPageRoute("category", "en/Product/{ProductName}", "~/en/index.aspx");
url i'm tring is:
http://localhost:5562/en/Product.aspx?ProductName=Laptop
Try http://localhost:5562/en/Product/Laptop as your browser route.
Then, based on your comments, if you want to forbid a value, do this in your code that reads the value, within index.aspx (or product.aspx if you're using that):
string value = Page.RouteData.Values("ProductName"); // get the product being searched for from the URL
List<string> forbiddenValues = new List<string> { "Computer", "BadWord2", "BadWord3" }; // put your forbidden terms in here
if (forbiddenValues.Contains(s, StringComparer.CurrentCultureIgnoreCase)) // case-insensitive
{
// Bad value detect - throw error or do something
MyLiteral.Text = "Bad term found. Cannot continue";
} else
{
// do you database stuff here and get the products
}

Restricting email notification for private site in alfresco

I have added a script to send mail whenever a site is created. How to restrict the email notification if the site created is a private site. Here is my java script
var mail = actions.create("mail");
var node = people.getGroup("GROUP_EMAIL_CONTRIBUTORS");
if(node){
var members = people.getMembers(node);
}
mail.parameters.from = "Administrator#community.com"
mail.parameters.subject=" A new site called " + document.properties.name+" is created";
mail.parameters.text="Click http://sameer_w7:8080/share/page/site/" + document.properties.name + "/dashboard" + " to join the site";
for(var i=0;i<members.length;i++)
{
mail.parameters.to = members[i].properties.email;
//execute action against a document
mail.execute(document);
}
You can get the siteVisibility state of a site.
Take a look at the SiteService Wiki page.
Something like this should work:
if (document.properties["st:siteVisibility"] != "PRIVATE"){
<your email action here>
}
Be sure you have selected type is st:site in your rule, otherwise add an extra check on that.

Google Gmail API - Auth

I already have code which works fine, but for security reason I want to make other way of Auth.
In this case, user writes his username and password, but I want to make like "Allow demo.com to access your information's" click button.
How to change this code:
//Provide Login Information
Google.GData.Client.RequestSettings rsLoginInfo = new Google.GData.Client
.RequestSettings("", txtEmail.Text, txtPassword.Text);
rsLoginInfo.AutoPaging = true;
// Fetch contacts and dislay them in ListBox
Google.Contacts.ContactsRequest cRequest = new ContactsRequest(rsLoginInfo);
Google.GData.Client.Feed<Google.Contacts.Contact> feedContacts = cRequest
.GetContacts();
foreach (Google.Contacts.Contact gmailAddresses in feedContacts.Entries) {
Console.WriteLine("\t" + gmailAddresses.Title);
lstContacts.Items.Add(gmailAddresses.Title);
foreach (EMail emailId in gmailAddresses.Emails) {
Console.WriteLine("\t" + emailId.Address);
lstContacts.Items.Add(" " + emailId.Address);
}
}
It seems like you're trying to do 3-Legged OAuth. .NET samples for performing 3-Legged OAuth 1.0a are documented here:
http://code.google.com/apis/gdata/docs/auth/oauth.html#Examples

Active Directory Authentication

I am have made one web application in asp.net.In my project Authentication was done by matching the username and password in database.But now client ask me for the auto login in application with the help Of Active Directory authentication. Client ask suggest me to use the Email Id of user in AD for the authentication.
I tried to fetch the records in the AD, I could fetch the Fullname of user but I couldn't get the Email id,
I tried the code:
System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
string[] a = Context.User.Identity.Name.Split('\\');
System.DirectoryServices.DirectoryEntry ADEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + a[0] + "/" + a[1]);
string Name = ADEntry.Properties["FullName"].Value.ToString();
Further more I Use DirectorySearcher but it genterates Error that Coulnot search the record in the client server..
I had the exact same situation while making a portal for a company.
If they dont want you to get into their AD then what you can do is to request for the NTLogins of the people who will be given access to the portal. make a simple table which have their NTLogin and simply authenticate using the system from which the portal is being accessed.
Check out the sample code i used.
// Checking if the user opening this page is listed in the allowed user list against their NT login.
String sUser = Request.ServerVariables["LOGON_USER"].ToLower();
sUser = sUser.Replace("wt\\", "");
//Authentication using a custom auth method.
DatabaseOperations authenticateUser = new DatabaseOperations();
if (!authenticateUser.authenticate(sUser))
{
//unauthorized users will be redirected to access denied page.
Server.Transfer("AccessDenied.aspx", true);
}
And making sure that you have authentication mode to windows in your web.config file
<authentication mode="Windows"></authentication>
Hope this helps.
For reading AD data, i use this class. It is setup for our AD, but basically you can just pass in all the "fields" you want to find, in the params.
But you need to know what field holds the email address. Sysinternals made a pretty good tool for browsing AD, to figure out what you are looking for, called ADExplorer.
But I don't understand why you need to look in the AD? Can you not assume that the user is already authenticated, if they are on the network, and then rely on the windows identity?
public static Hashtable GetAttributes(string initials, params string[] Attribute)
{
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://ADNAME");
DirectorySearcher ADSearcher = new DirectorySearcher(directoryEntry);
ADSearcher.Filter = "(sAMAccountName=" + initials + ")";
foreach (string para in Attribute)
{
ADSearcher.PropertiesToLoad.Add(para);
}
SearchResult adSearchResult = ADSearcher.FindOne();
Hashtable hshReturns = new Hashtable();
foreach (string para in Attribute)
{
string strReturn = "";
if (adSearchResult.Properties[para].Count == 0)
strReturn = "";
else
strReturn = ((ResultPropertyValueCollection)adSearchResult.Properties[para])[0].ToString();
hshReturns.Add(para, strReturn);
}
return hshReturns;
}

storing logger information asp.net

i am building site where there are three types of user. Admin,Merchant and Assitant User.
Where to store information so that my application will know which user has logged on( whether it is admin or assitant user or merchant)
Thank you
You want to look at ASP.NET Membership and Roles.
string path = DateTime.Today.ToString("dd-mm-yy") + ".txt";
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
{
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
{
w.WriteLine("\r\nLog Entry : ");
w.WriteLine("Membership.GetUser().UserName);
w.Flush();
w.Close();
}

Resources