2012-05-07 5 views
2

У меня ошибка Ошибка ProfileCommon не может быть найдена в моем коде. Я не знаю, как исправить ошибку. Я помещаю пространство имен, используя system.Web.Profile, но ошибка все еще здесь. Может ли кто-нибудь помочь, как это сделать? Пожалуйста, помогите мне, если вы знаете. СпасибоProfileCommon не может быть найден

public partial class UserProfile : System.Web.UI.UserControl 
{ 
    private string _userName = ""; 
    public string UserName 
    { 
     get { return _userName; } 

     set { _userName = value; } 
    } 

    protected void Page_Init(object sender, EventArgs e) 
    { 
     this.Page.RegisterRequiresControlState(this); 
    } 

    protected override void LoadControlState(object savedState) 
    { 
     object[] ctlState = (object[])savedState; 
     base.LoadControlState(ctlState[0]); 
     _userName = (string)ctlState[1]; 
    } 

    protected override object SaveControlState() 
    { 
     object[] ctlState = new object[2]; 
     ctlState[0] = base.SaveControlState(); 
     ctlState[1] = _userName; 
     return ctlState; 
    } 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!this.IsPostBack) 
     { 
      // if the UserName property contains an emtpy string, retrieve the profile 
      // for the current user, otherwise for the specified user 
      ProfileCommon profile = this.Profile; 
      if (this.UserName.Length > 0) 
       profile = this.Profile.GetProfile(this.UserName); 
      txtFirstName.Text = profile.FirstName; 
      txtLastName.Text = profile.LastName; 
      ddlGenders.SelectedValue = profile.Gender; 
      if (profile.BirthDate != DateTime.MinValue) 
       txtBirthDate.Text = profile.BirthDate.ToShortDateString(); 
      ddlOccupations.SelectedValue = profile.Occupation; 
      txtWebsite.Text = profile.Website; 
      txtStreet.Text = profile.Address.Street; 
      txtCity.Text = profile.Address.City; 
      txtPostalCode.Text = profile.Address.PostalCode; 
      txtState.Text = profile.Address.State; 
      txtPhone.Text = profile.Contacts.Phone; 
      txtFax.Text = profile.Contacts.Fax; 
     } 
    } 
    public void Save() 
    { 
     // if the UserName property contains an emtpy string, save the current user's 
     // profile, othwerwise save the profile for the specified user 
     ProfileCommon profile = this.Profile; 
     if (this.UserName.Length > 0) 
      profile = this.Profile.GetProfile(this.UserName); 
     profile.FirstName = txtFirstName.Text; 
     profile.LastName = txtLastName.Text; 
     profile.Gender = ddlGenders.SelectedValue; 
     if (txtBirthDate.Text.Trim().Length > 0) 
      profile.BirthDate = DateTime.Parse(txtBirthDate.Text); 
     profile.Occupation = ddlOccupations.SelectedValue; 
     profile.Website = txtWebsite.Text; 
     profile.Address.Street = txtStreet.Text; 
     profile.Address.City = txtCity.Text; 
     profile.Address.PostalCode = txtPostalCode.Text; 
     profile.Address.State = txtState.Text; 
     profile.Contacts.Phone = txtPhone.Text; 
     profile.Contacts.Fax = txtFax.Text; 
     profile.Save(); 
    } 

} 

ответ

1

По этим ссылкам (link1, link2)

Веб-приложения не поддерживают генерацию объекта ProfileCommon

Первое звено затем дать авто ссылка, до VS Addin и инструкций с кодом how to incorporate it into the build process, чтобы устранить проблему

+0

Я загружаю генератор веб-профиля, но я не понимаю, как связать его с моим проектом? – Smitka

+0

@ Смитка вы посмотрели на соответствующую статью, она дает инструкции по ее включению. Также просмотрите статьи, созданные IrishCheiftain. –

2

Как отметил Марк, профили работают только с готовым шаблоном веб-сайта, и у меня есть инструкции по использованию плагина для облегчения использования профилей для проекта веб-приложения:

http://www.codersbarn.com/post/2008/07/10/ASPNET-PayPal-Subscriptions-IPN.aspx

можно сделать это самостоятельно, а вот полностью рабочий реализации, которые вы можете скачать:

http://leedumond.com/blog/asp-net-profiles-in-web-application-projects/

0

Существует очень простой работы вокруг этого, для всех кодеров, которые просто хотят взломать вещи. Вы можете получить тип ProfileBase и загрузить профиль в это, но вы потеряете сильную типизацию. Если вы контролируете данные в профиле или уверены, что данные в профиле имеют определенный тип, вам хорошо идти.

string user = "Steve"; // The username you are trying to get the profile for. 
    bool isAuthenticated = false; 

     MembershipUser mu = Membership.GetUser(user); 

     if (mu != null) 
     { 
      // User exists - Try to load profile 

      ProfileBase pb = ProfileBase.Create(user, isAuthenticated); 

      if (pb != null) 
      { 
       // Profile loaded - Try to access profile data element. 
       // ProfileBase stores data as objects in (I assume) a Dictionary 
       // so you have to cast and check that the cast succeeds. 

       string myData = (string)pb["MyKey"]; 

       if (!string.IsNullOrWhiteSpace(myData))   
       { 
        // Woo-hoo - We're in data city, baby! 
        Console.WriteLine("Is this your card? " + myData + " - Ta Dah!"); 
       } 
      }  
     } 
+0

В дополнение к этому, если вы хотите сохранить обратно в профиль, isAuthenticated должен быть правдой. Если объект MembershipUser не является нулевым, то вы знаете, что пользователь аутентифицирован, и безопасно установить это значение true. –

Смежные вопросы