Monday, May 11, 2009

isolates storage

Introduction
Many programmers use the config file to keep the application configuration data. But one disadvantage with this is, it is a read only mechanism. You cannot update data in application config files, using the ConfigurationSettings classes in .NET. In earlier days, .ini files or registry was used to save application specific data.
Of course, we can use regular files to save application data. But now the question is how to protect the data, where to save it and all other mess!
Isolated Storage
.NET introduces a concept called Isolated Storage. Isolated Storage is a kind of virtual folder. Users never need to know where exactly the file is stored. All you do is, tell the .NET framework to store your file in Isolated Storage. The physical location of Isolated Storage varies for each Operating System. But your application simply uses the .NET classes to create and access files, without bothering where it is physically located. And you can have Isolated Storage specific to each Assembly or each Windows user.
The following code sample demonstrates the basic create, write and read operations with Isolated Storage.
Make sure you include the following directives on top of your file:
using System.IO;
using System.IO.IsolatedStorage;
using System.Diagnostics;

System.IO.IsolatedStorage Namespace
The System.IO.IsolatedStorage namespace contains types for creating and using a virtual file system. Isolated storage provides safe client-side storage for partial-trust applications. In Silverlight, all I/O operations are restricted to isolated storage and do not use the file system of the operating system.
Classes
Class Description

IsolatedStorageException
The exception that is thrown when an operation in isolated storage fails.

IsolatedStorageFile
Represents an isolated storage area containing files and directories.

IsolatedStorageFileStream
Exposes a file within isolated storage.












Code sample:
const string ISOLATED_FILE_NAME = "MyIsolatedFile.txt";

//-------------------------------------------------------

// Check if the file already exists in isolated storage.

//-------------------------------------------------------

IsolatedStorageFile isoStore =
IsolatedStorageFile.GetStore( IsolatedStorageScope.User
| IsolatedStorageScope.Assembly, null, null );

string[] fileNames = isoStore.GetFileNames( ISOLATED_FILE_NAME );

foreach ( string file in fileNames )
{
if ( file == ISOLATED_FILE_NAME )
{
Debug.WriteLine("The file already exists!");
}
}

//-------------------------------------------------------

// Write some text into the file in isolated storage.

//-------------------------------------------------------

IsolatedStorageFileStream oStream =
new IsolatedStorageFileStream( ISOLATED_FILE_NAME,
FileMode.Create, isoStore );

StreamWriter writer = new StreamWriter( oStream );
writer.WriteLine( "This is my first line in the isolated storage file." );
writer.WriteLine( "This is second line." );
writer.Close();

//-------------------------------------------------------

// Read all lines from the file in isolated storage.

//-------------------------------------------------------

IsolatedStorageFileStream iStream =
new IsolatedStorageFileStream( ISOLATED_FILE_NAME,
FileMode.Open, isoStore );

StreamReader reader = new StreamReader( iStream );
String line;

while ( (line = reader.ReadLine()) != null )
{
Debug.WriteLine( line );
}

reader.Close();
Visit here to read my C# Tutorial collection.

License
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
Silverlight Tip of the Day #19: Using Isolated Storage
Silverlight uses Isolated Storage as a virtual file system to store data in a hidden folder on your machine. It breaks up the data into two separate sections: Section #1 contains administrative information such as disk quota and section #2 contains the actual data. Each Silverlight application is allocated its own portion of the storage with the current quota set to be 1 MB per application.
Advantages:
1. Isolated Storage is a great alterative to using cookies (as discussed in Tip of the Day #18) especially if you are working with large sets of data. Examples of use include undo functionality for your app, shopping cart items, window settings and any other setting your application can call up the next time it loads.
2. Isolated storage stores by user allowing server applications to dedicate unique settings per individual user.
Possible Pitfalls:
1. Administrators can set disk quota per user and assembly which means there is no guarantee on space available. For this reason, it is important to add exception handling to your code.
2. Even though Isolated Storage is placed in a hidden folder it is possible, with a bit of effort, to find the folder. Therefore the data stored is not completely secure as users can change or remove files. It should be noted though that you can use the cryptography classes to the encrypt data stored in isolated storage preventing users from changing it.
3. Machines can be locked down by administrative security policies preventing applications from writing to the IsolatedStorage. More specifically, code must have the IsolatedStorageFilePermission to work with isolated storage.
All that said, let’s take a look at how we save and load data. Note that you will need to add a using statement to reference the namespace System.IO.IsolatedStorage as well as System.IO.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.IO;

namespace SilverlightApplication10
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
SaveData("Hello There", "MyData.txt");
string test = LoadData("MyData.txt");
}

private void SaveData(string data, string fileName)
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf))
{
using (StreamWriter sw = new StreamWriter(isfs))
{
sw.Write(data);
sw.Close();
}
}
}
}

private string LoadData(string fileName)
{
string data = String.Empty;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Open, isf))
{
using (StreamReader sr = new StreamReader(isfs))
{
string lineOfData = String.Empty;
while ((lineOfData = sr.ReadLine()) != null)
data += lineOfData;
}
}
}
return data;
}
}
}

INI files and the Windows registry were a step in the right direction, but isolated storage is the best option for persisting application-specific user settings in .NET programs.
The question of where to store user-specific application settings has plagued developers since the dawn of the PC. Prior to Windows 3.1, applications typically stored settings in a configuration file in the application directory. Windows 3.1 introduced the concept of initialization (.INI) files, and their associated headaches—corruption of WIN.INI, INI droppings all over the Windows directory, and inadvertent corruption or deletion of other applications' INI files. The Win32 platform introduced the registry—a system-wide configuration database in which developers were encouraged to store application settings. However, it's a bad idea to store large amounts of data in the registry, and giving just anybody write access to the registry poses a serious security risk. The registry is a fine place to store application configuration data that system administrators control, but it's not a good place for user-specific application settings. In .NET programs, those settings belong in isolated storage.
What Is Isolated Storage?
According to the .NET definition, "Isolated storage is a storage mechanism that provides isolation and safety by defining standardized ways of associating code with saved data." The isolated storage subsystem standardizes access methods, provides security by preventing other programs and users from accessing application-specific data, and supplies tools that help system administrators configure and control the storage space. Isolated storage provides a standard, flexible, and (to an extent) secure location for an application to store its settings—a place where other applications can't inadvertently overwrite or delete.
How Isolated Is It?
Access to an isolated storage file is always restricted to the user who created the file. This setup prevents users from inadvertently overwriting or deleting application settings that were created by other users or programs. The .NET runtime uses the operating system user-identity mechanism to support this isolation. In addition to user isolation, storage can be isolated based on the assembly (a DLL that contains all kinds of .NET-specific stuff), or on the combined application domain and assembly. () By combining user, domain, and assembly, the .NET framework provides these two types of storage isolation:
• Isolation by user and assembly. Data isolated by user and assembly can be accessed only by the user who originally created it, and only from code that resides in a particular assembly. This type of isolation is useful if you have multiple applications that need to access the same configuration data for a particular user. If you create a separate assembly that accesses the isolated storage, any application that calls the assembly can access the data for that user.
• Isolation by user, domain, and assembly. Isolation by user, domain, and assembly is more restrictive. In addition to restricting access based on user and assembly, the runtime ensures that the only application that can access the data is the application that originally created it. This type of isolation prevents data leakage between applications, as well as data corruption by other applications.
When To Use Isolated Storage
With the few exceptions noted below, you should use isolated storage anytime you need to store user-specific application settings. These situations cover a wide range of possibilities:
• Downloaded controls. Controls downloaded from the Internet don't have permissions to access the file system, but they do have isolated storage permissions. Isolated storage is the only way that these controls can persist user-specific data without requiring that the system administrator grant more permissions to the code.
• Web application storage. Web applications have the same I/O limitations as downloaded controls, and so must use isolated storage for any kind of persistent data storage.
• Shared component storage. As I pointed out earlier, isolated storage is an ideal way to persist data between multiple applications that all use the same settings for a particular user.
• Standalone client application storage. Although standalone applications typically have full access to the file system and the registry, isolated storage is usually a better choice for user-specific settings because using it prevents inadvertent corruption of one user's data by another user. It also provides a standard location for settings, thereby making it easier to secure application directories.
• Server application storage. Server applications can impersonate the logged-in user to persist user-specific settings. This provides the same level of isolation for server applications as for standalone client applications, preventing data leakage between users.
• Roaming. Because isolated storage data is stored in a user's profile directory, enabling roaming profiles makes all of the user's application-specific storage available to that user, regardless of the computer on which the user is logged in.
Of course, there are a few situations in which you shouldn't use isolated storage:
• Storing high-value secrets. Don't use isolated storage to persist unencrypted keys or passwords, or other secret information. Isolated storage files are stored on disk (see the Microsoft documentation for the location), where they're vulnerable to snooping or corruption by unmanaged code, highly trusted code, and trusted computer users.
• Administrator settings. You shouldn't use isolated storage to persist configuration and deployment settings that are controlled by administrators.
Silverlight Isolated Storage Best Practices
When you use isolated storage, following these guidelines will help you avoid problems and make the most of the protection isolated storage provides.
• Wrap all calls to isolated storage within try/catch blocks to be resilient to potential IsolatedStorageExceptions, which can be thrown if isolated storage is disabled or if the store has been deleted.
• If your Silverlight application needs to store a lot of data in isolated storage, consider hosting it on its own site so that it won't affect other applications on the site and other applications won't affect it.
• If you have a group of Silverlight applications that need to share data on the client, host them on the same site.
• Keep isolated storage paths as small as possible to prevent the internal full path from reaching the 260-character limit.
• Encrypt sensitive data stored in isolated storage.
• Use IsolatedStorageSettings to store objects and simple settings in isolated storage.
• Use IsolatedStorageFile if you want to use file and stream-based APIs, are storing large amounts of data, or need fine-grained control over the contents of isolated storage

No comments:

Post a Comment