Exforsys
+ Reply to Thread
Results 1 to 2 of 2

Web Parts

This is a discussion on Web Parts within the Microsoft .NET forums, part of the Programming Talk category; Is it possible to store the attributes of web parts in own database tables rather than sql express 2005 tables? ...

  1. #1
    RanvijaySingh is offline Junior Member Array
    Join Date
    Jul 2006
    Answers
    1

    Web Parts

    Is it possible to store the attributes of web parts in own database tables rather than sql express 2005 tables? I can include the tables of sql express database (ASPNETDB) in my own database but I don't want to do this. I want to create my own tables for saving properties or even XML file will do.


  2. #2
    techvinny is offline Moderator Array
    Join Date
    Dec 2010
    Answers
    56
    Hi Ranvijay...the dependency on database or any persistence model while using Web Parts comes into picture only when you are making use of Personalization (which by default is turned ON). To turn it off, simply turn off personalization in your WebPartManager like this:



    However, coming onto your main question of using your own database apart from ASPNETDB. It is very much possible to have your own database or your own custom persistence/storage model for saving the personalization details.

    You will have to basically define your custom Web Parts Personalization Provider. The fundamental job of a Web Parts personalization provider is to provide persistent storage for personalization state-state regarding the content and layout of Web Parts pages-generated by the Web Parts personalization service.

    You will have to derive your Custom Personalization Provider class from System.Web.UI.WebControls.WebParts.PersonalizationProvider which comes with default implementations for most of its methods. You may wish to override few of those methods for which you want to write your own implementation.

    Here's a sample code from MSDN that uses a Text file in the application's ~/App_Data/Personalization_Data directory for storing Personalization details:

    Code:
    using System;
    using System.Configuration.Provider;
    using System.Security.Permissions;
    using System.Web;
    using System.Web.UI.WebControls.WebParts;
    using System.Collections.Specialized;
    using System.Security.Cryptography;
    using System.Text;
    using System.IO;
    
    public class TextFilePersonalizationProvider : PersonalizationProvider
    {
        public override string ApplicationName
        {
            get { throw new NotSupportedException(); }
            set { throw new NotSupportedException(); }
        }
    
        public override void Initialize(string name,
            NameValueCollection config)
        {
            // Verify that config isn't null
            if (config == null)
                throw new ArgumentNullException("config");
    
            // Assign the provider a default name if it doesn't have one
            if (String.IsNullOrEmpty(name))
                name = "TextFilePersonalizationProvider";
    
            // Add a default "description" attribute to config if the
            // attribute doesn't exist or is empty
            if (string.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description",
                    "Text file personalization provider");
            }
    
            // Call the base class's Initialize method
            base.Initialize(name, config);
    
            // Throw an exception if unrecognized attributes remain
            if (config.Count > 0)
            {
                string attr = config.GetKey(0);
                if (!String.IsNullOrEmpty(attr))
                    throw new ProviderException
                        ("Unrecognized attribute: " + attr);
            }
    
            // Make sure we can read and write files in the
            // ~/App_Data/Personalization_Data directory
            FileIOPermission permission = new FileIOPermission
                (FileIOPermissionAccess.AllAccess,
                HttpContext.Current.Server.MapPath
                ("~/App_Data/Personalization_Data"));
            permission.Demand();
        }
    
        protected override void LoadPersonalizationBlobs
            (WebPartManager webPartManager, string path, string userName,
            ref byte[] sharedDataBlob, ref byte[] userDataBlob)
        {
            // Load shared state
            StreamReader reader1 = null;
            sharedDataBlob = null;
    
            try
            {
                reader1 = new StreamReader(GetPath(null, path));
                sharedDataBlob =
                    Convert.FromBase64String(reader1.ReadLine());
            }
            catch (FileNotFoundException)
            {
                // Not an error if file doesn't exist
            }
            finally
            {
                if (reader1 != null)
                    reader1.Close();
            }
    
            // Load private state if userName holds a user name
            if (!String.IsNullOrEmpty (userName))
            {
                StreamReader reader2 = null;
                userDataBlob = null;
    
                try
                {
                    reader2 = new StreamReader(GetPath(userName, path));
                    userDataBlob =
                        Convert.FromBase64String(reader2.ReadLine());
                }
                catch (FileNotFoundException)
                {
                    // Not an error if file doesn't exist
                }
                finally
                {
                    if (reader2 != null)
                        reader2.Close();
                }
            }
        }
    
        protected override void ResetPersonalizationBlob
            (WebPartManager webPartManager, string path, string userName)
        {
            // Delete the specified personalization file
            try
            {
                File.Delete(GetPath(userName, path));
            }
            catch (FileNotFoundException) {}
        }
    
        protected override void SavePersonalizationBlob
            (WebPartManager webPartManager, string path, string userName,
            byte[] dataBlob)
        {
            StreamWriter writer = null;
    
            try
            {
                writer = new StreamWriter(GetPath (userName, path), false);
                writer.WriteLine(Convert.ToBase64String(dataBlob));
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
        }
    
        public override PersonalizationStateInfoCollection FindState
            (PersonalizationScope scope, PersonalizationStateQuery query,
            int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotSupportedException();
        }
    
        public override int GetCountOfState(PersonalizationScope scope,
            PersonalizationStateQuery query)
        {
            throw new NotSupportedException();
        }
    
        public override int ResetState(PersonalizationScope scope,
            string[] paths, string[] usernames)
        {
            throw new NotSupportedException();
        }
    
        public override int ResetUserState(string path,
            DateTime userInactiveSinceDate)
        {
            throw new NotSupportedException();
        }
    
        private string GetPath(string userName, string path)
        {
            SHA1CryptoServiceProvider sha =
                new SHA1CryptoServiceProvider(); 
            UnicodeEncoding encoding = new UnicodeEncoding ();
            string hash = Convert.ToBase64String(sha.ComputeHash
                (encoding.GetBytes (path))).Replace ('/', '_');
            
            if (String.IsNullOrEmpty(userName))
                return HttpContext.Current.Server.MapPath
    (String.Format("~/App_Data/Personalization_Data/{0}_Personalization.txt",
                    hash));
            else
            {
                // NOTE: Consider validating the user name here to prevent
                // malicious user names such as "../Foo" from targeting
                // directories other than ~/App_Data/Personalization_Data
    
                return HttpContext.Current.Server.MapPath
    (String.Format("~/App_Data/Personalization_Data/{0}_{1}_Personalization.txt",
                    userName.Replace('\\', '_'), hash));
            }
        }
    }
    And here's how the web.config will look like for using your custom TextFilePersonalizationProvider class

    HTML Code:
    <configuration>
      <system.web>
        <webParts>
          <personalization
            defaultProvider="AspNetTextFilePersonalizationProvider">
            <providers>
              <add name="AspNetTextFilePersonalizationProvider"
                type="TextFilePersonalizationProvider, CustomProviders"/>
            </providers>
          </personalization>
        </webParts>
    </configuration>



Latest Article

Network Security Risk Assessment and Measurement

Read More...