I am not getting the 'Profile' property in the code behind - asp.net

hai ,
I have added some profile properties to my web.config:
<profile automaticSaveEnabled ="true">
<properties>
<add name="NumVisits" type="System.Int32"/>
<add name="UserName" type="System.String"/>
<add name="Gender" type="bool"/>
<add name="Birthday" type="System.DateTime"/>
</properties>
</profile>
However when I try to access the property in a code behind it does not
exist. The following code does not work (says firstname is not a property):
Profile.Gender
And In the Asp.net Configuration 'Profile tab ' Is not showing.
I have rebuilt the solution. I am using VB.NET(3.5)

Another way to retrieve Profile properties value is like below.
object obj = HttpContext.Current.Profile["PropertyName"]; (C# code).

Related

When finished create user using (CreateUserWizard control) add profile information in the same process

When I try this code it's give this error message
This property cannot be set for anonymous users.
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
Roles.AddUserToRole((sender as CreateUserWizard).UserName, "Admin");
Control ctrl = CreateUserWizard1.CreateUserStep.ContentTemplateContainer;
TextBox txtAdminAddress= (TextBox)ctrl.FindControl("txtAdminAddress");
TextBox txtAdminCountry= (TextBox)ctrl.FindControl("txtAdminCountry");
TextBox txtAdminCity= (TextBox)ctrl.FindControl("txtAdminCity");
HttpContext.Current.Profile.GetProfileGroup("AdminGroup").SetPropertyValue("AdminAddress", txtAdminAddress.Text);
HttpContext.Current.Profile.GetProfileGroup("AdminGroup").SetPropertyValue("AdminCountry", txtAdminCountry.Text);
HttpContext.Current.Profile.GetProfileGroup("AdminGroup").SetPropertyValue("AdminCity", txtAdminCity.Text);
HttpContext.Current.Profile.Save();
}
Config:
<profile defaultProvider="AspNetSqlProfileProvider">
<properties>
<group name="AdminGroup">
<add name="AdminAddress" type="System.String"/>
<add name="AdminCountry" type="System.String"/>
<add name="AdminCity" type="System.String"/>
</group>
</properties>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="MyConnectionString" applicationName="/"/>
</providers>
</profile>
After creating the User, You need to fetch the profile of recently created user to start updating values. Since No profile is Loaded, it won't allow to set these values for anonymous users.
string strUsername = (sender as CreateUserWizard).UserName;
ProfileCommon p = Profile.GetProfile(strUsername);
//update the field and save
p.AdminAddress= txtAdminAddress.Text;
p.Save();
The ProfileBase object (provided by the Page.Profile property) includes a useful GetProfile() function that retrieves, by user name, the profile information for a specific user.
GetProfile() returns a ProfileCommon object.
[ Note: The profile properties set in Config file doesn't allow setting values for Anonymous users. If you want to allow this for anonymous users also use:
<add name="AdminAddress" type="System.String" allowAnonymous="true"/>
]

No access to user profiles

I am using mySQL as ny db and have all the asp membership configuration in place.
I have set additional profile proerties in my web.comfig file as shown below;
<profile defaultProvider="MySQLProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
<remove name="MySQLProfileProvider" />
<add name="MySQLProfileProvider" type="MySql.Web.Profile.MySQLProfileProvider, MySql.Web, Version=6.6.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" applicationName="/" description="" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="False" autogenerateschema="True" enableExpireCallback="False" />
</providers>
<properties>
<add name="AccountConfirmationId" type="System.String" />
<add name="FullName" type="System.String" />
<add name="CompanyName" type="System.String" />
<add name="CompanyLocationName" type="System.String" />
</properties>
</profile>
My first question is where are the profile values actually stored? There is no additional columns created in my membership profile table.
Secondly, I am using the method outlined below to store the entered values in the registration process into the profile, from the "Next" button click event.
Protected Sub RegisterUser_NextButtonClick(sender As Object, e As WizardNavigationEventArgs) Handles RegisterUser.NextButtonClick
'set Profile object and give it its property values
Dim userProfile As ProfileCommon = TryCast(ProfileCommon.Create(RegisterUser.UserName), ProfileCommon)
userProfile.AccountConfirmationId = Guid.NewGuid().ToString()
userProfile.SetPropertyValue("FullName", FullName.Text)
userProfile.SetPropertyValue("FullName", CompanyName.Text)
userProfile.SetPropertyValue("FullName", CompanyLocationName.Text)
userProfile.Save()
Session("rolerequest") = ddlRegisterAs.SelectedItem.ToString()
Session("acctconfid") = userProfile.AccountConfirmationId
Session("completename") = FullName.Text
Session("compname") = CompanyName.Text
Session("compnamelocation") = CompanyLocationName.Text
End Sub
I try to retrieve the profile values on my admin user management page with the following method ( triggered by username selection from a dropdownlist)
Protected Sub ddlSiteUsers_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlSiteUsers.SelectedIndexChanged
Try
Dim userProfile As ProfileCommon = Profile.GetProfile(ddlSiteUsers.SelectedItem.ToString())
tbProfileUserFullname.Text = userProfile.GetPropertyValue("FullName").ToString()
tbProfileCompany.Text = userProfile.GetPropertyValue("CompanyName").ToString()
tbProfileCompLoc.Text = userProfile.GetPropertyValue("CompanyLocationName").ToString()
Catch ex As Exception
lblSiteUserErrMessage.Text = "User profile not found... " & ex.Message.ToString()
lblSiteUserErrMessage.Visible = True
End Try
End Sub
All values come up as empty strings. Any help appreciated.
I am using a website project not a web application.
To answer your first question, the property names and values are serialized and stored in the existing table columns. See this blog post for more details:
How ASP.NET Profile Properties are serialized in the database using Sql Profile Provider
These are the (auto-generated) columns in the profile table for my web app:
[UserId] [uniqueidentifier] NOT NULL,
[PropertyNames] [nvarchar](4000) NOT NULL,
[PropertyValueStrings] [nvarchar](4000) NOT NULL,
[PropertyValueBinary] [image] NOT NULL,
[LastUpdatedDate] [datetime] NOT NULL,
In short, the profile properties are not directly accessible for querying outside of the Profile provider. For that reason I have seen several recommendations to not use the default Profile provider and instead store User details in a separate UserDetails table. I ended up adding columns directly to the Users table, which has so far worked fine for me, but may not be the best choice for some applications.

Asp.net Membership Profile FirstName and LastName (Not declared. It may be inaccessible due to its protection level )

When i created a profile and when i add items it always says not declared in the code behind!!
I tried to change the Framework of the project from Framework 4.0 to Framework 3.5 and it still didn't work.
It says FirstNamep , LastNamep are not declared .
And in the Web.config :
<profile defaultProvider="CustomProfileProvider" enabled="true">
<providers>
</providers>
<!-- Define the properties for Profile... -->
<properties>
<add name="FirstNamep" type="String" />
<add name="LastNamep" type="String" />
</properties>
</profile>
Behind the Code:
Profile.FirstNamep = FirstNameTextBox.Text
Profile.LastNamep = LastNameTextBox.Text
The properties are dynamically generated at runtime, which means you can't access them from code-behind. What you can do is access them from your .ASPX pages using a script block (if that works for you). Like this.
<%# Page Language="C#" %>
<script runat="server">
public void Page_Init()
{
Profile.FirstNamep = "some dood";
}
</script>
<div>Your name is <%= Profile.FirstNamep %></div>
It seems to be sort of "by design" that the Profile is available to .aspx pages, but not to the code behind.
If you've defined the default provider as CustomProfileProvider, then that has to be a class that inherits System.Web.Profile.ProfileProvider. Otherwise, you should use the default SQL profile provider.
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
</connectionStrings>
<membership>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
   

How to implement Google reCaptcha in an MVC3 application?

Can anyone explain how to have reCaptcha functionality like stackoverflow in my MVC3 application.
And how can you customize that?
I use the Google ReCaptcha and it works very well and is very simple to implement.
Note that if you are using Https be sure you have the current version of the dll (1.0.5.0 at this time)
You need to create an account on the Google Recaptcha site and get a set of public and private keys. Add the keys to your web project main web.config file:
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="ReCaptchaPrivateKey" value="put your private key value here" />
<add key="ReCaptchaPublicKey" value="put your public key value here" />
</appSettings>
Now use NuGet and install the reCAPTCHA plugin for .NET
Then, go to your web.config file inside of your VIEWS folder. Add this line:
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="Recaptcha"/>
</namespaces>
Then, in your view that you want to show the captcha, add the using statement at the top of your file
#using Recaptcha;
then add this to your view:
<div class="editor-label">
Are you a human?
</div>
<div class="editor-field">
#Html.Raw(Html.GenerateCaptcha("captcha", "clean"))
#Html.ValidationMessage("captcha")
</div>
In your controller action you will need to modify the signature to accept the captcha results:
[HttpPost]
[RecaptchaControlMvc.CaptchaValidator]
public ActionResult ForgotPassword(CheckUsernameViewModel model, bool captchaValid, string captchaErrorMessage) {
if (!Membership.EnablePasswordReset)
throw new Exception("Password reset is not allowed\r\n");
if(ModelState.IsValid) {
if(captchaValid) {
return RedirectToAction("AnswerSecurityQuestion", new { username = model.Username });
}
ModelState.AddModelError("", captchaErrorMessage);
}
return View(model);
}
Following those steps have allowed me to implement captcha on several pages and it works smoothly. Note that the parameter names on the controller action MUST BE NAMED CORRECTLY:
bool captchaValid, string captchaErrorMessage
If you changed these parameter names you WILL get an error at runtime when your form posts back to the controller action.
I would recommend using a Honeypot Captcha. The experience for your users is MUCH better. There is one fore ASP.NET MVC here http://nuget.org/packages/SimpleHoneypot.MVC
PM> Install-Package SimpleHoneypot.MVC4
There is a WiKi on how to get it up here: https://github.com/webadvanced/Honeypot-MVC/wiki
Just start out with the Getting Started section.
You can read more about the general idea of a Honeypot Captcha here: http://haacked.com/archive/2007/09/11/honeypot-captcha.aspx

ConfigurationSettings.AppSettings - this method is obsolete error

I am trying to set the row limit for my gridview webpart on sharepoint site in the appsettings of the web.config file.
<appSettings>
<add key ="RowLimit" value="6"/>
<add key="FeedCacheTime" value="300" />
<add key="FeedPageUrl" value="/_layouts/feed.aspx?" />
<add key="FeedXsl1" value="/Style Library/Xsl Style Sheets/Rss.xsl" />
<add key="ReportViewerMessages" value="Microsoft.SharePoint.Portal.Analytics.UI.ReportViewerMessages, Microsoft.SharePoint.Portal, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
and then in my code file i am using the below statement
string x = ConfigurationSettings.AppSettings["RowLimit"];
this line is giving an error stating ConfigurationSettings.AppSettings "This method is obsolete",
What is that i am doing wrong? Please let me know.
You should be using the ConfigurationManager class instead. ConfigurationSettings was deprecated in .NET 2.0. Use it the same way as you would use ConfigurationSettings, but be aware that you will have to add a reference to System.Configuration, if you don't have it already.
The replacement is System.Configuration.ConfigurationManager.AppSettings.
Example:
using System.Configuration;
...
string x = ConfigurationManager.AppSettings["RowLimit"];

Resources