Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
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 :
Page Views : 12968
Downloads : 309
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
SilverlightStateManagement.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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();

            }           

        }

 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Nipun Tomar

Nipun is competent and experienced "project leader", with "8 years" of experience in managing multi-disciplinary teams of varying sizes and complex programs of work. Has the ability to build strong relationships with all stakeholders and to turn proposals into reality.

"Especially successful in management roles that demand rigor, a high level of drive and dedication and a focus on delivering business outcomes through the use of methodologies".

Strengths include successful analysis and problem-solving expertise, highly rated oral and written communications skills, and proven project management experience. Strong background in "C#, Visual Studio 2010, ASP.NET, Windows Forms, WPF, WCF, Silverlight and SQL Server".

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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Reg: Applicaion Resources by praba On January 20, 2011
Is it possible to get the application resources from one application to another application using adding reference from one application to another application? When page refreshes, is it possible to get the updated application resources.
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.