program story

프로필 값을 할당하는 방법?

inputbox 2020. 7. 30. 10:24
반응형

프로필 값을 할당하는 방법?


누락 된 내용을 모르지만 Web.config 파일에 프로필 속성을 추가했지만 프로필에 액세스 할 수 없습니다. 항목 코드 또는 새 프로필을 만들 수 있습니다.


나는 오늘 같은 문제가 있었고 많은 것을 배웠다.

Visual Studio에는 "웹 사이트 프로젝트"와 "웹 응용 프로그램 프로젝트"라는 두 가지 종류의 프로젝트가 있습니다. 나에게 완전한 미스터리 인 이유로, 웹 애플리케이션 프로젝트는 프로파일을 사용할 수 없습니다 . 직접 ... 강력하게 형식화 된 클래스는 Web.config 파일에서 마술처럼 생성되지 않으므로 직접 롤링해야합니다.

MSDN의 샘플 코드는 사용자가 웹 사이트 프로젝트를 사용한다고 가정 하고 property 와 함께 <profile>섹션을 추가하고 웹 애플리케이션 프로젝트에서는 작동하지 않는다고 알려줍니다.Web.configProfile.

자신의 롤을 선택할 수있는 두 가지 선택 사항이 있습니다.

(1) 웹 프로파일 빌더를 사용하십시오 . Web.config의 정의에서 필요한 프로필 개체를 자동으로 생성하는 Visual Studio에 추가하는 사용자 지정 도구입니다.

코드를 컴파일하기 위해이 추가 도구에 의존하지 않기 때문에이 작업을 수행하지 않기로 선택했습니다.

(2) ProfileBase사용자 정의 프로파일을 나타내는 파생 클래스를 만드십시오 . 이것은 생각보다 쉽습니다. 다음은 "FullName"문자열 프로파일 필드를 추가하는 매우 간단한 예입니다.

web.config에서 :

<profile defaultProvider="SqlProvider" inherits="YourNamespace.AccountProfile">

<providers>
     <clear />
     <add name="SqlProvider"
          type="System.Web.Profile.SqlProfileProvider"
          connectionStringName="sqlServerMembership" />
</providers>

</profile>

AccountProfile.cs라는 파일에서 :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.Web.Security;

namespace YourNamespace
{
    public class AccountProfile : ProfileBase
    {
        static public AccountProfile CurrentUser
        {
            get { return (AccountProfile)
                         (ProfileBase.Create(Membership.GetUser().UserName)); }
        }

        public string FullName
        {
            get { return ((string)(base["FullName"])); }
            set { base["FullName"] = value; Save(); }
        }

        // add additional properties here
    }
}

프로필 값을 설정하려면

AccountProfile.CurrentUser.FullName = "Snoopy";

프로필 값을 얻으려면

string x = AccountProfile.CurrentUser.FullName;

웹 애플리케이션 프로젝트는 여전히 ProfileCommon 오브젝트를 사용할 수 있지만 런타임시에만 사용할 수 있습니다. 코드는 프로젝트 자체에서 생성되지 않지만 클래스는 ASP.Net에 의해 생성되며 런타임에 존재합니다.

객체를 얻는 가장 간단한 방법은 아래에 설명 된대로 동적 유형을 사용하는 것입니다.

Web.config 파일에서 프로파일 특성을 선언하십시오.

<profile ...
 <properties>
   <add name="GivenName"/>
   <add name="Surname"/>
 </properties>

그런 다음 속성에 액세스하십시오.

dynamic profile = ProfileBase.Create(Membership.GetUser().UserName);
string s = profile.GivenName;
profile.Surname = "Smith";

프로파일 특성에 대한 변경 사항을 저장하려면 다음을 수행하십시오.

profile.Save();

동적 유형을 사용하는 것이 편하고 컴파일 타임 검사 및 인텔리전스의 부족을 신경 쓰지 않으면 위의 내용이 올바르게 작동합니다.

ASP.Net MVC와 함께 사용하는 경우 HTML 도우미 메서드가 동적 인 "model"개체와 잘 작동하지 않으므로 동적 프로필 개체를 뷰에 전달하면 추가 작업을 수행해야합니다. HTML 도우미 메서드에 전달하기 전에 정적 속성 변수에 프로필 속성을 할당해야합니다.

// model is of type dynamic and was passed in from the controller
@Html.TextBox("Surname", model.Surname) <-- this breaks

@{ string sn = model.Surname; }
@Html.TextBox("Surname", sn); <-- will work

Joel이 위에서 설명한대로 사용자 정의 프로파일 클래스를 작성하면 ASP.Net은 여전히 ​​ProfileCommon 클래스를 생성하지만 사용자 정의 프로파일 클래스에서 상속합니다. 사용자 정의 프로파일 클래스를 지정하지 않으면 ProfileCommon은 System.Web.Profile.ProfileBase에서 상속됩니다.

고유 한 프로파일 클래스를 작성하는 경우 사용자 정의 프로파일 클래스에서 이미 선언 한 Web.config 파일에 프로파일 특성을 지정하지 않아야합니다. ASP.Net을 사용하면 ProfileCommon 클래스를 생성하려고 할 때 컴파일러 오류가 발생합니다.


웹 응용 프로그램 프로젝트에서도 프로필을 사용할 수 있습니다. 디자인 타임에 또는 프로그래밍 방식으로 Web.config에서 속성을 정의 할 수 있습니다. Web.config에서 :

<profile enabled="true" automaticSaveEnabled="true" defaultProvider="AspNetSqlProfileProvider">
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="TestRolesNProfiles"/>
      </providers>
      <properties>
        <add name="FirstName"/>
        <add name="LastName"/>
        <add name ="Street"/>
        <add name="Address2"/>
        <add name="City"/>
        <add name="ZIP"/>
        <add name="HomePhone"/>
        <add name="MobilePhone"/>
        <add name="DOB"/>

      </properties>
    </profile>

또는 프로그래밍 방식으로 ProfileSection 을 인스턴스화하고 ProfilePropertySettingsProfilePropertySettingsColletion을 사용하여 개별 속성을 생성하여 프로필 섹션을 만듭니다 ( 모두 System.Web.Configuration 네임 스페이스에 있음). 프로파일의 해당 특성을 사용하려면 System.Web.Profile.ProfileBase 오브젝트를 사용하십시오. 프로파일로 프로파일 특성에 액세스 할 수 없습니다 . 위에서 언급 한대로 구문을 작성하지만 다음과 같이 ProfileBase를 인스턴스화하고 SetPropertyValue ( " PropertyName ") 및 GetPropertyValue { " PropertyName ")를 사용하여 쉽게 수행 할 수 있습니다 .

ProfileBase curProfile = ProfileBase.Create("MyName");

또는 현재 사용자의 프로필에 액세스하려면

ProfileBase curProfile = ProfileBase.Create(System.Web.Security.Membership.GetUser().UserName);



        curProfile.SetPropertyValue("FirstName", this.txtName.Text);
        curProfile.SetPropertyValue("LastName", this.txtLname.Text);
        curProfile.SetPropertyValue("Street", this.txtStreet.Text);
        curProfile.SetPropertyValue("Address2", this.txtAdd2.Text);
        curProfile.SetPropertyValue("ZIP", this.txtZip.Text);
        curProfile.SetPropertyValue("MobilePhone", txtMphone.Text);
        curProfile.SetPropertyValue("HomePhone", txtHphone.Text);
        curProfile.SetPropertyValue("DOB", txtDob.Text);
        curProfile.Save();

Visual Studio에서 새 웹 사이트 프로젝트를 만들면 프로필에서 반환되는 개체가 자동으로 생성됩니다. 웹 응용 프로그램 프로젝트 또는 MVC 프로젝트를 만들 때는 직접 롤백해야합니다.

이것은 아마도 그보다 더 어려워 보인다. 다음을 수행해야합니다.

  • aspnet_regsql.exe를 사용하여 데이터베이스 생성 이 도구는 .NET 프레임 워크와 함께 설치됩니다.
  • ProfileGroupBase에서 파생 된 클래스를 작성하거나 Web.Config의 정의에서 클래스를 생성 할 수있는 WPB (Web Profile Builder)를 설치하십시오. 나는 지금까지 WPB를 사용하여 왔으며 지금까지 예상했던 일을 끝냈습니다. 많은 속성이있는 경우 WPB를 사용하면 시간을 상당히 절약 할 수 있습니다.
  • Web.Config에서 데이터베이스 연결이 올바르게 구성되어 있는지 확인하십시오.
  • Now you are set to create an instance of your profile class (in the controller)
  • You will probably need the profile property values in your views. I like to pass the profile object itself along to the view (not individual properties).

If you are using a web application project, you cannot access the Profile object at design-time out-of-the-box. Here is a utility that supposedly does it for you: http://weblogs.asp.net/joewrobel/archive/2008/02/03/web-profile-builder-for-web-application-projects.aspx. Personally, that utility caused an error in my project so I ended up rolling my own profile class to inherit from ProfileBase. It was not hard to do at all.


MSDN walkthrough for creating a custom class (a.k.a. Joel's method):
http://msdn.microsoft.com/en-us/magazine/cc163624.aspx


나는 또한 같은 문제를 겪고 있었다. 그러나 ProfileBase에서 상속되는 클래스를 만드는 대신 HttpContext를 사용했습니다.

다음과 같이 web.config 파일에서 특성을 지정하십시오.- ProfilePropertyWeb.config

이제 다음 코드를 작성하십시오.-

Code Behind Profile Properties

코드를 컴파일하고 실행하십시오. 다음과 같은 출력이 나타납니다.-

Output


웹 프로필 Builder는 나를 위해 큰 일했습니다. 생성 된 클래스는 Joel의 게시물에 설명 된 것보다 훨씬 더 많이 포함되어 있습니다. 실제로 필요한지 여부는 알지 못합니다.

어쨌든 클래스를 생성하는 쉬운 방법을 찾고 있지만 외부 빌드 도구 종속성을 원하지 않는 사람들은 언제든지 할 수 있습니다

  • 웹 프로파일 빌더를 사용하십시오.
  • 그것의 모든 흔적을 삭제하십시오!
  • 생성 된 프로파일 클래스를 계속 사용하십시오.

또는 (예상되지 않았지만 작동 할 수 있음)

  • 사이트 프로젝트 만들기
  • 당신의 요소를 만들
  • snap the generated class and copy it over to your web project project

if this second approach does work can someone let me know for future reference


Just want to add to Joel Spolsky's answer

I implemented his solution, working brilliantly btw - Cudos!

For anyone wanting to get a user profile that's not the logged in user I used:

web.config:

  <connectionStrings>
    <clear />
    <add name="LocalSqlConnection" connectionString="Data Source=***;Database=***;User Id=***;Password=***;Initial Catalog=***;Integrated Security=false" providerName="System.Data.SqlClient" />
  </connectionStrings>

and

<profile defaultProvider="SqlProvider" inherits="NameSpace.AccountProfile" enabled="true">
  <providers>
    <clear/>
    <add name="SqlProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="LocalSqlConnection"/>
  </providers>

And then my custom class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.Web.Security;

namespace NameSpace
{
    public class AccountProfile : ProfileBase
    {
        static public AccountProfile CurrentUser
        {
            get
            {
                return (AccountProfile)
                 (ProfileBase.Create(Membership.GetUser().UserName));
            }
        }

        static public AccountProfile GetUser(MembershipUser User)
        {
            return (AccountProfile)
                (ProfileBase.Create(User.UserName));
        }

        /// <summary>
        /// Find user with matching barcode, if no user is found function throws exception
        /// </summary>
        /// <param name="Barcode">The barcode to compare against the user barcode</param>
        /// <returns>The AccountProfile class with matching barcode or null if the user is not found</returns>
        static public AccountProfile GetUser(string Barcode)
        {
            MembershipUserCollection muc = Membership.GetAllUsers();

            foreach (MembershipUser user in muc)
            {
                if (AccountProfile.GetUser(user).Barcode == Barcode)
                {
                    return (AccountProfile)
                        (ProfileBase.Create(user.UserName));
                }
            }
            throw new Exception("User does not exist");
        }

        public bool isOnJob
        {
            get { return (bool)(base["isOnJob"]); }
            set { base["isOnJob"] = value; Save(); }
        }

        public string Barcode
        {
            get { return (string)(base["Barcode"]); }
            set { base["Barcode"] = value; Save(); }
        }
    }
}

Works like a charm...


Great post,

Just a note on the web.config if you dont specify the inherit attribute in the profile element you will need to specify each indiviudal profile property inside the profile element on the web.config as below

 <properties>
    <clear/>
    <add name="property-name-1" />
    <add name="property-name-2" />
    ..........

 </properties>

참고URL : https://stackoverflow.com/questions/426609/how-to-assign-profile-values

반응형