# Data Persistence

## Overview

<table><thead><tr><th width="281">Feature</th><th>Description</th></tr></thead><tbody><tr><td>Rating Save Path</td><td>The <code>RatingSavePath</code> property specifies the file system location where the rating data is stored.</td></tr><tr><td>Save and Load Rating Methods</td><td>Methods such as <code>SaveRating()</code>, <code>LoadRating()</code>, <code>SaveRatingWithPath(string filePath)</code>, and <code>LoadRatingWithPath(string filePath)</code> allow developers to persist and retrieve the current rating state.</td></tr><tr><td>File-Based Persistence</td><td>The control uses simple file I/O operations to write and read the rating (an integer value) for data persistence.</td></tr></tbody></table>

***

### Key Points

<table><thead><tr><th width="230">Aspect</th><th>Description</th></tr></thead><tbody><tr><td>Simple File Operations</td><td>The control leverages standard file I/O to save and load rating data as plain text, ensuring compatibility and ease of use.</td></tr><tr><td>Flexible Storage Options</td><td>Developers can use the default <code>RatingSavePath</code> or provide a custom file path for storing rating data.</td></tr><tr><td>Immediate UI Reflection</td><td>Changes to the rating trigger a call to <code>Invalidate()</code>, ensuring that the control's appearance is updated immediately after loading or saving data.</td></tr></tbody></table>

***

### Best Practices

<table><thead><tr><th width="270">Practice</th><th>Recommendation</th></tr></thead><tbody><tr><td>Use a Valid File Path</td><td>Always set a valid and accessible file path for <code>RatingSavePath</code> to avoid file I/O errors during save/load operations.</td></tr><tr><td>Handle Exceptions Gracefully</td><td>Implement error handling around file operations to manage scenarios where the file may be inaccessible or corrupted.</td></tr><tr><td>Synchronize Data Persistence</td><td>Ensure that rating data is saved at appropriate times (e.g., on application exit or after a rating change) to maintain data consistency.</td></tr><tr><td>Validate Saved Data</td><td>When loading rating data, validate that the content can be parsed into an integer within the expected range.</td></tr></tbody></table>

***

### Common Pitfalls

<table><thead><tr><th width="192">Pitfall</th><th>Explanation</th><th>How to Avoid</th></tr></thead><tbody><tr><td>Invalid File Path</td><td>An incorrect or inaccessible file path may prevent the rating from being saved or loaded successfully.</td><td>Always verify and test the <code>RatingSavePath</code> or use the custom methods with a known valid file path.</td></tr><tr><td>Data Corruption</td><td>Manually editing or corrupting the save file could result in an invalid rating value when loaded.</td><td>Validate the file content when reading and implement fallback behavior (e.g., setting a default rating) if parsing fails.</td></tr><tr><td>Lack of Exception Handling</td><td>Not handling exceptions during file I/O may cause the application to crash if a file operation fails.</td><td>Wrap file operations in try-catch blocks to manage exceptions and log errors for troubleshooting.</td></tr><tr><td>Inconsistent Data Synchronization</td><td>Saving data at irregular intervals might lead to outdated or inconsistent rating information.</td><td>Establish clear triggers for when rating data should be saved, such as on user confirmation or form exit.</td></tr></tbody></table>

***

### Usage Scenarios

<table><thead><tr><th width="222">Scenario</th><th>Description</th></tr></thead><tbody><tr><td>Persistent User Ratings</td><td>Save user ratings so that when the application is restarted, the last selected rating is restored automatically.</td></tr><tr><td>Feedback Aggregation</td><td>In applications that aggregate feedback over time, file-based persistence ensures that rating data is not lost between sessions.</td></tr><tr><td>Offline Data Storage</td><td>Use data persistence to store user interactions locally when the application operates in offline mode, ensuring that data is retained until synchronization.</td></tr></tbody></table>

#### Code Sample: Basic Data Persistence

```csharp
// Initialize the rating control and set the file path for rating persistence
SiticoneRatingEmoji ratingControl = new SiticoneRatingEmoji();
ratingControl.RatingSavePath = "userRating.txt";

// Set a default rating (e.g., fourth emoji, zero-based index 3)
ratingControl.SelectedIndex = 3;

// Save the current rating to the file
ratingControl.SaveRating();

// Load the rating from the file at a later time (e.g., on form load)
ratingControl.LoadRating();

// Display the loaded rating value (should show 4)
Console.WriteLine("Loaded Rating Value: " + ratingControl.RatingValue);
```

#### Code Sample: Using Custom Save and Load Paths

```csharp
// Define a custom file path for storing the rating data
string customPath = @"C:\MyAppData\ratings.txt";

// Save the current rating using the custom file path
ratingControl.SaveRatingWithPath(customPath);

// Later, load the rating from the same custom file path
ratingControl.LoadRatingWithPath(customPath);
Console.WriteLine("Custom Loaded Rating Value: " + ratingControl.RatingValue);
```

***

### Real Life Usage Scenarios

<table><thead><tr><th width="248">Scenario</th><th>Description</th></tr></thead><tbody><tr><td>Customer Feedback Forms</td><td>In customer feedback forms, persist the rating selected by the user so that their feedback is available for future sessions or analysis.</td></tr><tr><td>Survey Applications</td><td>Store and retrieve survey responses across sessions, ensuring that users can continue where they left off or that data is available for aggregation.</td></tr><tr><td>Offline Mode Applications</td><td>In scenarios where the application might be offline, use data persistence to cache user ratings until a connection is available for synchronization.</td></tr></tbody></table>

#### Code Sample: Persisting Ratings in a Feedback Form

```csharp
// On form closing, save the current rating to ensure it is preserved for the next session
private void FeedbackForm_FormClosing(object sender, FormClosingEventArgs e)
{
    ratingControl.RatingSavePath = @"C:\FeedbackApp\ratings.txt";
    ratingControl.SaveRating();
}

// On form load, load the previously saved rating
private void FeedbackForm_Load(object sender, EventArgs e)
{
    ratingControl.RatingSavePath = @"C:\FeedbackApp\ratings.txt";
    ratingControl.LoadRating();
    feedbackLabel.Text = $"Welcome back! Your previous rating was: {ratingControl.RatingValue}";
}
```

***

### Troubleshooting Tips

<table><thead><tr><th width="284">Tip</th><th>Recommendation</th></tr></thead><tbody><tr><td>File Not Found or Inaccessible</td><td>Ensure that the file path specified in <code>RatingSavePath</code> is valid and that the application has the necessary file system permissions.</td></tr><tr><td>Parsing Errors or Invalid Data</td><td>Validate the file content when loading data; if parsing fails, reset the rating to a default value and log the error for further investigation.</td></tr><tr><td>No Visual Update After Loading</td><td>If the control does not reflect the loaded rating, verify that the <code>LoadRating()</code> or <code>LoadRatingWithPath()</code> methods are being called correctly and that the control is being invalidated after loading.</td></tr><tr><td>Data Synchronization Issues</td><td>Ensure that the rating is saved at appropriate times (e.g., immediately after change or on application exit) to avoid discrepancies.</td></tr></tbody></table>

***

### Review

<table><thead><tr><th width="254">Aspect</th><th>Comments</th></tr></thead><tbody><tr><td>Simplicity and Effectiveness</td><td>The data persistence mechanism is straightforward, using simple file I/O to store and retrieve an integer value, making it easy to implement and understand.</td></tr><tr><td>Flexibility</td><td>The option to use a default save path or specify a custom file path offers flexibility in various deployment scenarios.</td></tr><tr><td>Integration Ease</td><td>Integration with other control features (such as selection and visual updates) is seamless, ensuring that saved data immediately reflects in the UI.</td></tr><tr><td>Robustness</td><td>Although simple, the implementation requires proper exception handling to ensure that file I/O errors do not disrupt application functionality.</td></tr></tbody></table>

***

### Summary

<table><thead><tr><th width="248">Summary Point</th><th>Explanation</th></tr></thead><tbody><tr><td>Persistent Rating Storage</td><td>The control supports saving and loading rating data through file-based persistence, ensuring that user selections are maintained across sessions.</td></tr><tr><td>Customizable Save Paths</td><td>Developers can use the default <code>RatingSavePath</code> or specify a custom file path, allowing for flexible integration with various application architectures.</td></tr><tr><td>Simple Implementation</td><td>Using basic file I/O operations, the persistence feature is easy to implement and integrate, with methods provided for both saving and loading the rating.</td></tr><tr><td>Critical for User Experience</td><td>Data persistence is crucial for applications that rely on user feedback, ensuring that ratings are not lost between sessions and can be used for further analysis.</td></tr></tbody></table>

***

### Additional Resources

<table><thead><tr><th width="240">Resource</th><th>Description</th></tr></thead><tbody><tr><td>Code Example Repository</td><td>Refer to the provided code samples for practical examples of how to integrate data persistence into your application.</td></tr><tr><td>API Reference</td><td>Consult the source code documentation for detailed information on the behavior and constraints of the <code>SaveRating()</code> and <code>LoadRating()</code> methods.</td></tr><tr><td>File I/O Best Practices</td><td>Review guidelines on file I/O operations in .NET to ensure that your implementation handles exceptions and file access correctly.</td></tr><tr><td>Debugging Tools</td><td>Utilize logging and debugging tools to track file operations and diagnose issues with data persistence during development and testing.</td></tr></tbody></table>

***

The Data Persistence feature is designed to ensure that user ratings are saved and restored reliably between application sessions. By following the best practices and usage scenarios provided in this documentation, developers can effectively integrate data persistence into their applications, creating a consistent and user-friendly experience.
