Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Silverlight » State Management is Silverlight using Isolated Storage

State Management is Silverlight using Isolated Storage

State management is the process to maintain state and page information over multiple requests for the same or different pages. State management in Silverlight 2 can be done using the concept of Isolated storage.

Author Rank:
Technologies: ASP.NET 3.5, Silverlight, XAML,Visual C# .NET
Total downloads : 94
Total page views :  3599
Rating :
 4.5/5
This article has been rated :  2 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
SilverlightStateManagement.zip
 
ArticleAd
Become a Sponsor



State management is the process to maintain state and page information over multiple requests for the same or different pages. Web applications are based on stateless HTTP protocol so web form pages do not automatically indicate whether the requests in a sequence are all from the same client or even whether a single browser instance is still actively viewing a page or site. A new instance of the Web page class is created each time the page is requested and with each round trip to the server pages are destroyed and re-created.

ASP.NET includes several options that help to preserve data on both a per-page basis and an application-wide basis.

Client-Side Method State Management

1. View state 2.Control state 3.Hidden fields 4.Cookies 5. Query string

Server-Side Method State Management

1. Application state 2.Session state 3.Profile properties 4. Database support

State management in Silverlight 2 can be done using the concept of Isolated storage. In Silverlight application everything is compiled in one XAP file and when a user requests this is copied to the client machine. So there are no server round trips and page request every time, this reduces the need of maintaining the use or application state. But in typical business application state management may be required.

Silverlight Isolated Storage

Isolated storage is a data storage mechanism that helps in storing data on the client machine in a hidden folder outside the browser’s cache. Silverlight Applications runs as partial trust but isolated storage API is allowed to create and access files that are stored in an Isolated Storage area which act as non volatile cache and is shared across the browsers. Every application has its own portion of the isolated storage with a default size of 1MB and can be used to store user specific information as name, preferences and skins etc. It can be used as Client-Side state management.

Demo

Location of Isolated Storage in Vista
%:\Users\%\AppData\LocalLow\Microsoft\Silverlight\is

Location of Isolated Storage in Windows XP
%:\Documents and Settings\%\Local Settings\Application Data\Microsoft\Silverlight\is

Retrieve Isolated Storage Information (Quota, Available Space)
private void ButtonShowInfo_Click(object sender, RoutedEventArgs e)

        {

            try

            {

                using (var store = IsolatedStorageFile.GetUserStoreForApplication())

                {

                    string spaceUsed = (store.Quota - store.AvailableFreeSpace).ToString();

                    string spaceAvailable = store.AvailableFreeSpace.ToString();

                    string currentQuota = store.Quota.ToString();

                    string message = String.Format("Quota: {0} bytes, Used: {1} bytes, Available: {2} bytes", currentQuota, spaceUsed, spaceAvailable);

                    TextBoxResults.Text = message;

                    SaveLogToIsolatedStorage(message);

                }

            }

            catch (IsolatedStorageException)

            {

                TextBoxResults.Text = "Unable to access Isolated Storage.";

                SaveLogToIsolatedStorage("Unable to access Isolated Storage.");

            }

        }

Create a variable for IsolatedStorageSettings
//Create a variable for IsolatedStorageSettings

//IsolatedStorageSettings contains the contents of the application IsolatedStorageFile scoped at the application level

        private IsolatedStorageSettings isoStorSettings = IsolatedStorageSettings.ApplicationSettings;

Save information in Isolated Storage
private void ButtonSave_Click(object sender, RoutedEventArgs e)

        {

            try

            {

                User user = new User();

                user.Name = TextBoxName.Text;

                user.Designation = TextBoxDesignation.Text;

                user.Address = TextBoxAddress.Text;

                user.City = TextBoxCity.Text;

                isoStorSettings.Add("UserDetail", user);

                TextBoxResults.Text = "User Detaild stored.";

                SaveLogToIsolatedStorage("User Detaild stored.");

            }

            catch (ArgumentException ex)

            {

                TextBoxResults.Text = ex.Message;

                SaveLogToIsolatedStorage(ex.Message);

            }

        }

Retrieve information from Isolated Storage
private void ButtonRetrieve_Click(object sender, RoutedEventArgs e)

        {

            try

            {

                User user = (User)isoStorSettings["UserDetail"];

                TextBoxName.Text = user.Name;

                TextBoxDesignation.Text = user.Designation;

                TextBoxAddress.Text = user.Address;

                TextBoxCity.Text = user.City;

                TextBoxResults.Text = "User Details retrieved.";

                SaveLogToIsolatedStorage("User Details retrieved.");

            }

            catch (System.Collections.Generic.KeyNotFoundException ex)

            {

                TextBoxResults.Text = ex.Message;

                SaveLogToIsolatedStorage(ex.Message);

                ClearTextBoxes();

            }

        }

Delete from Isolated Storage
private void ButtonDelete_Click(object sender, RoutedEventArgs e)

        {

            isoStorSettings.Remove("UserDetail");

            TextBoxResults.Text = "User Detaild deleted.";

            SaveLogToIsolatedStorage("User Detaild deleted.");

            ClearTextBoxes();

        }

Increase the Isolated Storage space
private void ButtonIncreaseAllocation_Click(object sender, RoutedEventArgs e)

        {

            try

            {

                using (var store = IsolatedStorageFile.GetUserStoreForApplication())

                {

                    // Request more space in bytes.

                    Int64 spaceToAdd = 1 * 1024 * 1024;

                    Int64 currentAvailable = store.AvailableFreeSpace;

 

                    // If available space is less than requested, then increase.

                    if (currentAvailable < spaceToAdd)

                    {

                        // Request more quota space.

                        if (!store.IncreaseQuotaTo(store.Quota + spaceToAdd))

                        {

                            // The user clicked NO to the host's prompt to approve the quota increase.

                            TextBoxResults.Text = "User declined to approve Quota inrease";

                            SaveLogToIsolatedStorage("User declined to approve Quota inrease");

                        }

                        else

                        {

                            // The user clicked YES to the host's prompt to approve the quota increase.

                            TextBoxResults.Text = "Quota inreased";

                            SaveLogToIsolatedStorage("Quota inreased");

                        }

                    }

                    else

                    {

                        string messge = String.Format("{0:0.00} MB is still available.", (decimal)currentAvailable / 1024 / 1024);

                        TextBoxResults.Text = messge;

                        SaveLogToIsolatedStorage(messge);

                    }

                }

            }

            catch (IsolatedStorageException ex)

            {

                TextBoxResults.Text = ex.Message;

                SaveLogToIsolatedStorage(ex.Message);

            }

        }

Isolated Storage space also let applications to read/write files without special permissions. The IsolatedStorageFileStream class provides methods to access files in the Isolated Storage and performs operations on them.

Save data in the Isolated Storage File
private void SaveLogToIsolatedStorage(string message)

        {

            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())

            {

                using (IsolatedStorageFileStream isoStream =

                    isoStore.OpenFile("Log.txt", FileMode.Append, FileAccess.Write))

                {

                    using (StreamWriter writer = new StreamWriter(isoStream))

                    {

                        writer.WriteLine(message);

                    }

                }

            }

        }

Read data from isolated Storage File
private void ButtonReadLog_Click(object sender, RoutedEventArgs e)

        {

            TextBoxResults.Text = ReadLogFromIsolatedStorage();           

        }
private string ReadLogFromIsolatedStorage()

        {

            string content = string.Empty;

            try

            {

                using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())

                {

                    using (IsolatedStorageFileStream isoStream =

                        new IsolatedStorageFileStream("Log.txt", FileMode.Open, isoFile))

                    {

                        using (StreamReader sr = new StreamReader(isoStream))

                        {

                            content = sr.ReadToEnd();

                        }

                    }

                }

            }

            catch (IsolatedStorageException ex)

            {

                TextBoxResults.Text = ex.Message;

                return "";

            }

            return content;

        }

 

Further if you want any information to be globally available to all the users (Server-Side State Management) then one of the options is Application Resource. Anything added to the Application resource acts similar to Application State in ASP.NET (information will same throughout the application for all users).

Add object to the App Resource (in App.xaml.cs)
private void Application_Startup(object sender, StartupEventArgs e)

        {

            this.RootVisual = new Page();

            User user = new User();

            user.Name = "Nipun Tomar";

            user.Designation = "Project Lead";

            user.Address = "";

            user.City = "Philadelphia";

            App.Current.Resources.Add("UserInfo", user);

        }

Retrieve Information from App Resource (in Page.xaml.cs)
private void ButtonAppState_Click(object sender, RoutedEventArgs e)

        {

            try

            {

                User user = (User)App.Current.Resources["UserInfo"];

                TextBoxName.Text = user.Name;

                TextBoxDesignation.Text = user.Designation;

                TextBoxAddress.Text = user.Address;

                TextBoxCity.Text = user.City;

                TextBoxResults.Text = "User Details retrieved from Application Resources.";

                SaveLogToIsolatedStorage("User Details retrieved from Application Resources.");

            }

            catch (Exception ex)

            {

                TextBoxResults.Text = ex.Message;

                SaveLogToIsolatedStorage(ex.Message);

                ClearTextBoxes();

            }           

        }

 


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Nipun Tomar
Nipun has 5 years working experience in .NET technologies. He holds Bachelor's and Master's degree in Computer Science. Currently working on ASP.NET 2.0/3.5, VB.NET, C#.NET, AJAX, SQL Server 2005, WPF, WCF and Silverlight.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
SilverlightStateManagement.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved