Finalize(): Profiles from Afar

Finalize(): Profiles from Afar

have a friend with whom I have a never-ending IM conversation. You know what I mean: We never say “Hello” or “TTYL”. Conversations just gradually flow in and out, as in some extended stream of consciousness. Ever since I left Los Angeles, this friend and I can’t meet for lunch, take a hike up the hill, or a morning bike ride around Pasadena. We both miss these benefits of proximity and self-employment. So, we make do with IM.

The little IM popup window appears regularly with comments on a recent TV show (“I already miss West Wing”), the state of the dog (“Taking Max out for a walk”) or his owner (“Feeling kinda cruddy this morning”), and the important questions of life (“Should I have toast or a bagel this morning for breakfast?”), without introduction, greeting, or context. One morning, this one pops up (and, as you might imagine, acted as the germination of the idea for this article): “How can I retrieve Profile information from a class library called from a Web page?”

Amazingly, I had just completed a courseware chapter on the Profile features in ASP.NET, and so I figured I had to have something in there that would help. For those unclear on the concept, you can define a schema for user-oriented profile information by adding a section to your site’s Web.config file, like this:

                                                                     

At design time, the language compiler takes this information and generates an object of type ProfileCommon named Profile, with properties that match the properties defined in the configuration file (LastVisitedDate, FullName, PrivateInfo; of the type UserInfo, a class defined in my sample project, containing Birthdate and SSN properties; and LocationInfo, a “structure” of properties defined in web.config, containing State and PostalCode properties). In your site’s code, you can include code like this to retrieve and set properties of the current user’s profile:

   [Visual Basic]   If Profile.LastVisitedDate <> _      DateTime.MinValue Then      ' Only display the date if you've       ' already been through here.      lblLastDate.Text = "You last visited on " & _         Profile.LastVisitedDate.ToShortDateString()   End If   Profile.LastVisitedDate = DateTime.Today   [C#]   if (Profile.LastVisitedDate !=      DateTime.MinValue)   {      // Only display the date if you've       // already been through here.      lblLastDate.Text = "You last visited on " +         Profile.LastVisitedDate.ToShortDateString();   }   Profile.LastVisitedDate = DateTime.Today;

You can work with the auto-generated Profile object, loading a profile for any user (the ASP.NET profile management code stores each user’s profile information in a database-a SQL Express database named ASPNETDB.MDF, by default), using code like this:

   ' Call the DisplayData procedure like this:   ' DisplayData(Profile.GetProfile("Russ"))   Private Sub DisplayData( _      ByVal currentProfile As ProfileCommon)      ' Retrieve data from the selected profile, and display in      ' controls on the page.      txtName.Text = currentProfile.FullName      ' Display the rest of the data here...   End Sub

The real problem comes when you attempt to retrieve profile data in a project outside the current site. You define all the schema for the Profile object in web.config, but a class library project doesn’t have the web.config available to it, nor will Visual Studio automatically create the Profile object for you unless you’re in a Web project, and you’ve set up the schema in the configuration file.

What can you do to solve this problem? I first looked into the ProfileManager class, which almost seems to provide the information you might need. You could write code like this, in order to find a particular profile:

   ' Set a reference to System.Web, and add   ' the following to the top of the file:   Imports System.Web.Profile      ' or in C#:   ' using System.Web.Profile;      For Each info As ProfileInfo In _      ProfileManager.FindProfilesByUserName(      ProfileAuthenticationOption.Authenticated, "Ken")      System.Diagnostics.Debug.Print(info.UserName)   Next

The problem is that the ProfileInfo class provides only the minimum values for each profile, including the UserName, LastActivityDate, and a few other properties?it doesn’t include any of the properties added through the schema you define in web.config.

The answer, which my friend finally found on his own, is to use the System.Web.Profile.ProfileBase class to do the work. You can use this class’s Create method to retrieve the specified user’s profile information from the current data store, even though the currently running code (in a class library) doesn’t have direct access to the web.config schema. For example, you could write code like this to create a ProfileBase object and retrieve a profile property:

   [Visual Basic]   Public Function GetState( _      ByVal userName As String) As String      Dim profile As ProfileBase = _         ProfileBase.Create(userName)      Return profile("LocationInfo.State")   End Function      [C#]   public string GetState(string userName)   {     ProfileBase profile =        ProfileBase.Create(userName);     Return profile["LocationInfo.State"];   }

As you can tell, you’re on your own when retrieving information from the ProfileBase instance you create-the class exposes the profile values in a dictionary, so you supply the string index, and the class provides the corresponding value.

Is this a tip of earth-shattering importance? Probably not. On the other hand, it’s nearly impossible to retrieve the profile information from outside a running Web site by any other means, so it’s nice to know that this technique exists. (You’ll also find it useful to investigate the System.Profile.ProfileManager class, which provides lots of useful methods for managing profiles, including the important DeleteInactiveProfiles?otherwise, there’s no way to remove the myriad anonymous profiles you’ll find clogging your site’s ASPNETDB database.) And in the same IM conversation, I learned all sorts of other interesting, if not quite so useful, factoids. If only every IM thread was so fruitful.

devx-admin

devx-admin

Share the Post:
Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023,

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists