Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Collections.Specialized;
- using System.ComponentModel;
- using System.Data;
- using System.Diagnostics;
- using System.Drawing;
- using System.IO;
- using System.IO.Compression;
- using System.Linq;
- using System.Reflection;
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Security.Cryptography;
- using System.Text;
- using System.Threading;
- using System.Windows.Forms;
- using System.Xml;
- using System.Xml.Serialization;
- using Microsoft.Win32;
- namespace System.Windows.Forms {
- // Last updated Tuesday March 2,2010 1:49 PM
- [DefaultEvent("SettingsLoaded")]
- [DefaultProperty("Parent")]
- [ProvideProperty("WindowStateBinding",typeof(Control))]
- [ProvideProperty("WindowStateBindingProperty",typeof(Control))]
- public class WindowState:Component,IExtenderProvider {
- const WindowStateType GlobalWindowStateType_Default = WindowStateType.Registry;
- const bool GlobalEnabled_Default = true;
- public static WindowStateType GlobalWindowStateType { get; set; }
- public static bool GlobalEnabled { get; set; }
- public event EventHandler SettingsLoaded;
- public event EventHandler SettingsSaved;
- private Form _parent;
- private FormWindowState _lastWindowState;
- private ControlInfoDictionary _controlDictionary;
- private Dictionary<string,object> _settings;
- private WindowStateType _persistenceType;
- private bool _saveInAppData;
- private string _registryPath;
- private bool _allowSaveMinimized;
- private bool _allowSaveMaximized;
- private bool _enabled;
- private string _uniqueKey;
- private bool _loaded;
- private bool _ignoreHeightWidth;
- private bool _ignoreTopLeft;
- private bool _ignoreWindowState;
- private WindowStatePosition _normalPosition;
- private WindowStatePosition _originalPosition;
- private bool _eventsDetached;
- private Dictionary<string,ControlInfo> _bindedControls;
- private bool _encryptSettings;
- private System.ComponentModel.IContainer components = null;
- #region Properties
- [Browsable(true)]
- [Category("WindowState")]
- public Form Parent {
- get {
- return _parent;
- }
- set {
- _parent = value;
- // subscribe to parent form's events
- if(_parent != null)
- this.BindEventsToParent();
- }
- }
- [Browsable(true)]
- [Category("WindowState")]
- [DefaultValue(true)]
- public bool SaveInAppData {
- get {
- return _saveInAppData;
- }
- set {
- _saveInAppData = value;
- }
- }
- // registry key should be set in parent form's constructor
- [Browsable(false)]
- [Category("WindowState")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- public string RegistryPath {
- get {
- if(DesignMode)
- return null;
- if(string.IsNullOrEmpty(_registryPath))
- _registryPath = CreateRegistryKey();
- return _registryPath;
- }
- }
- [DefaultValue(false)]
- [Browsable(true)]
- [Category("WindowState")]
- public bool AllowSaveMinimized {
- get {
- return _allowSaveMinimized;
- }
- set {
- _allowSaveMinimized = value;
- }
- }
- [DefaultValue(false)]
- [Browsable(true)]
- [Category("WindowState")]
- public bool EncryptSettings {
- get {
- return _encryptSettings;
- }
- set {
- _encryptSettings = value;
- }
- }
- [DefaultValue(false)]
- [Browsable(true)]
- [Category("WindowState")]
- public bool AllowSaveMaximized {
- get {
- return _allowSaveMaximized;
- }
- set {
- _allowSaveMaximized = value;
- }
- }
- [DefaultValue(false)]
- [Browsable(true)]
- [Category("WindowState")]
- public bool IgnoreWindowState {
- get { return _ignoreWindowState; }
- set { _ignoreWindowState = value; }
- }
- [DefaultValue(false)]
- [Browsable(true)]
- [Category("WindowState")]
- public bool IgnoreTopLeft {
- get { return _ignoreTopLeft; }
- set { _ignoreTopLeft = value; }
- }
- [DefaultValue(false)]
- [Browsable(true)]
- [Category("WindowState")]
- public bool IgnoreHeightWidth {
- get { return _ignoreHeightWidth; }
- set { _ignoreHeightWidth = value; }
- }
- [DefaultValue(true)]
- [Browsable(true)]
- [Category("WindowState")]
- public bool Enabled {
- get { return _enabled; }
- set { _enabled = value; }
- }
- [DefaultValue("")]
- [Browsable(true)]
- [Category("WindowState")]
- [Description("")]
- public string UniqueKey {
- get { return _uniqueKey; }
- set { _uniqueKey = value; }
- }
- [Browsable(false)]
- [Category("WindowState")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- public bool IsLoaded {
- get { return _loaded; }
- set { _loaded = value; }
- }
- private WindowStateType PersistenceType {
- get { return _persistenceType; }
- set { _persistenceType = value; }
- }
- [Browsable(false)]
- [Category("WindowState")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- public WindowStatePosition NormalPosition {
- get {
- if(_normalPosition == null)
- _normalPosition = new WindowStatePosition();
- return _normalPosition;
- }
- private set { _normalPosition = value; }
- }
- [Browsable(false)]
- [Category("WindowState")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- public WindowStatePosition OriginalPosition {
- get {
- if(_originalPosition == null)
- _originalPosition = new WindowStatePosition();
- return _originalPosition;
- }
- private set { _originalPosition = value; }
- }
- #endregion
- #region Settings
- [Browsable(false)]
- [Category("WindowState")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [Description("A dictionary of Binded Controls")]
- public ControlInfoDictionary ControlDictionary {
- get {
- if(_controlDictionary == null)
- _controlDictionary = new ControlInfoDictionary();
- return _controlDictionary;
- }
- private set { _controlDictionary = value; }
- }
- [Browsable(false)]
- [Category("WindowState")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- [Description("Allows you to add/get data")]
- public Dictionary<string,object> Settings {
- get {
- if(_settings == null)
- _settings = new Dictionary<string,object>();
- return _settings;
- }
- private set { _settings = value; }
- }
- public void BindControl(Control ctrl,ExtendedControlProperties extProperties) {
- if(string.IsNullOrEmpty(extProperties.PropertyNames))
- BindControl(ctrl);
- else
- BindControl(ctrl,extProperties.PropertyNames);
- }
- public void BindControl(Control ctrl) {
- if(ctrl == null)
- throw new ArgumentNullException("cntrl");
- var propInfo = TypeDescriptor.GetDefaultProperty(ctrl);
- if(propInfo == null)
- return;
- BindControl(ctrl,propInfo.Name);
- }
- public void BindControl(Control ctrl,string propertyName) {
- if(ctrl == null)
- return;
- ControlInfo info = new ControlInfo(ctrl,propertyName);
- if(!_bindedControls.ContainsKey(info.Key))
- _bindedControls.Add(info.Key,info);
- }
- private void loadPersistedControls() {
- var infoList = getInfoFromSettings();
- foreach(var info in infoList) {
- var ctrl = _parent.Controls.Find(info.Name,true)
- .FirstOrDefault();
- if(ctrl == null)
- continue;
- setPropertyValue(ctrl,info.PropertyName,info.PropertyValue);
- }
- }
- private void savePersistedControls() {
- foreach(var info in _bindedControls.Values) {
- var ctrl = _parent.Controls.Find(info.Name,true)
- .FirstOrDefault();
- if(ctrl == null)
- continue;
- info.PropertyValue = getPropertyValue(ctrl,info.PropertyName);
- if(ControlDictionary.ContainsKey(info.Key))
- ControlDictionary.Remove(info.Key);
- ControlDictionary.Add(info.Key,info);
- }
- }
- private object getPropertyValue(object component,string propertyName) {
- PropertyDescriptor propInfo = null;
- if(string.IsNullOrEmpty(propertyName))
- propInfo = TypeDescriptor.GetDefaultProperty(component);
- else {
- foreach(PropertyDescriptor item in TypeDescriptor.GetProperties(component)) {
- if(item.Name == propertyName) {
- propInfo = item;
- break;
- }
- }
- }
- if(propInfo != null)
- return propInfo.GetValue(component);
- else
- return null;
- }
- private void setPropertyValue(object component,string propertyName,object value) {
- PropertyDescriptor propInfo = null;
- if(string.IsNullOrEmpty(propertyName))
- propInfo = TypeDescriptor.GetDefaultProperty(component);
- else {
- foreach(PropertyDescriptor item in TypeDescriptor.GetProperties(component)) {
- if(item.Name == propertyName) {
- propInfo = item;
- break;
- }
- }
- }
- if(propInfo != null)
- propInfo.SetValue(component,value);
- }
- private List<ControlInfo> getInfoFromSettings() {
- var infoList = ControlDictionary
- .Where(k => _bindedControls.ContainsKey(k.Key))
- .Select(v => v.Value)
- .Cast<ControlInfo>()
- .ToList();
- return infoList;
- }
- #region ControlInfo
- [Serializable]
- [XmlRoot("SettingInfo")]
- public class SettingInfo {
- [XmlAttribute]
- public string Key { get; set; }
- [XmlAttribute]
- public string TypeName { get; set; }
- [XmlAttribute]
- public bool IsSerializable { get; set; }
- [XmlElement(Type = typeof(string))]
- public object Value { get; set; }
- public SettingInfo() {
- }
- public SettingInfo(KeyValuePair<string,object> kv) {
- Key = kv.Key;
- Value = kv.Value;
- Value = SerializeSettingValue(this);
- }
- public static object SerializeSettingValue(SettingInfo info) {
- info.IsSerializable = false;
- if(info.Value == null) {
- return null;
- }
- object value = info.Value;
- Type type = value.GetType();
- info.TypeName = type.Name;
- if(type.Equals(typeof(string)))
- info.IsSerializable = false;
- else {
- if(type.IsArray)
- info.IsSerializable = true;
- else if(type.IsEnum)
- info.IsSerializable = true;
- else {
- if(type.IsSerializable)
- info.IsSerializable = !type.IsPrimitive;
- }
- }
- if(info.IsSerializable)
- return StatePersistance.SaveObjectToString(value);
- return value.ToString();
- }
- public static object DeserializeSettingValue(SettingInfo info) {
- if(info.Value == null)
- return null;
- if(info.Value.ToString() == string.Empty)
- return string.Empty;
- if(info.IsSerializable)
- return StatePersistance.ReadObjectFromString(info.Value.ToString());
- Type type = Type.GetType(info.TypeName,false);
- if(type == null)
- return info.Value;
- if(type.IsGenericType)
- return info.Value;
- return Convert.ChangeType(info.Value,type);
- }
- }
- [Serializable]
- [XmlRoot("ControlInfo")]
- public class ControlInfo {
- [XmlAttribute]
- public string Key { get; set; }
- [XmlAttribute]
- public string Name { get; set; }
- [XmlAttribute]
- public string PropertyName { get; set; }
- public object PropertyValue { get; set; }
- public ControlInfo() { }
- public ControlInfo(Control control,string propName) {
- Name = control.Name;
- PropertyName = propName;
- string keyFormat = "_ControlInfo_|{0}|{1}";
- Key = string.Format(keyFormat,Name,PropertyName);
- }
- }
- [Serializable]
- public class ControlInfoDictionary:Dictionary<string,WindowState.ControlInfo> {
- public static string ToXml(ControlInfoDictionary dictionary) {
- var items = dictionary.Values.ToArray();
- return XmlSerialization.Serialize<WindowState.ControlInfo[]>(items);
- }
- public static ControlInfoDictionary FromXml(string xml) {
- if(string.IsNullOrEmpty(xml))
- return new ControlInfoDictionary();
- var items = XmlSerialization.Deserialize<WindowState.ControlInfo[]>(xml);
- ControlInfoDictionary dictionary = new ControlInfoDictionary();
- foreach(var item in items) {
- dictionary.Add(item.Key,item);
- }
- return dictionary;
- }
- public ControlInfoDictionary() { }
- public ControlInfoDictionary(SerializationInfo info,StreamingContext context)
- : base(info,context) {
- }
- public object SyncRoot = new object();
- public object GetValue(string key) {
- return GetValue<object>(key,default(object));
- }
- public object GetValue(string key,object defaultValue) {
- return GetValue<object>(key,defaultValue);
- }
- public T GetValue<T>(string key) {
- return GetValue(key,default(T));
- }
- public T GetValue<T>(string key,T defaultValue) {
- object value = this[key];
- if(value == null)
- return defaultValue;
- return (T)value;
- }
- public new WindowState.ControlInfo this[string key] {
- get {
- if(key == null)
- return null;
- lock(SyncRoot) {
- if(this.ContainsKey(key) == false)
- return null;
- return base[key];
- }
- }
- set {
- if(key == null)
- return;
- lock(SyncRoot) {
- if(this.ContainsKey(key) == false)
- this.Add(key,value);
- else
- base[key] = value;
- }
- }
- }
- public WindowState.ControlInfo this[string key,WindowState.ControlInfo defaultValue] {
- get {
- if(key == null)
- return defaultValue;
- lock(SyncRoot) {
- if(this.ContainsKey(key) == false)
- return defaultValue;
- return base[key];
- }
- }
- }
- }
- #endregion
- public object GetSetting(string key) {
- if(!Settings.ContainsKey(key))
- return null;
- return this.Settings[key];
- }
- public object GetSetting(string key,object defaultValue) {
- if(!Settings.ContainsKey(key))
- return defaultValue;
- return Settings[key];
- }
- public T GetSetting<T>(string key) {
- object value = GetSetting(key);
- return (T)Convert.ChangeType(value,typeof(T));
- }
- public T GetSetting<T>(string key,T defaultValue) {
- if(!Settings.ContainsKey(key))
- return defaultValue;
- return GetSetting<T>(key);
- }
- public object this[string settingkey] {
- get {
- return GetSetting(settingkey);
- }
- set { Settings[settingkey] = value; }
- }
- public object this[string settingkey,object defaultValue] {
- get {
- return GetSetting(settingkey,defaultValue);
- }
- }
- #endregion
- #region ctr
- #region static
- static WindowState() {
- WindowState.GlobalWindowStateType = GlobalWindowStateType_Default;
- WindowState.GlobalEnabled = GlobalEnabled_Default;
- }
- #endregion
- private void InitializeComponent() {
- components = new System.ComponentModel.Container();
- _persistenceType = WindowStateType.Registry;
- _bindedControls = new Dictionary<string,ControlInfo>();
- _controlDictionary = new ControlInfoDictionary();
- _enabled = true;
- }
- public WindowState() {
- InitializeComponent();
- }
- public WindowState(IContainer container)
- : this() {
- container.Add(this);
- InitializeComponent();
- }
- #endregion
- #region events
- protected void OnSettingsLoaded(EventArgs args) {
- loadPersistedControls();
- if(SettingsLoaded != null)
- SettingsLoaded(this,args);
- }
- protected void OnSettingsSaved(EventArgs args) {
- savePersistedControls();
- if(SettingsSaved != null)
- SettingsSaved(this,args);
- }
- protected void DetachEvents() {
- if(Parent == null || Enabled == false || _eventsDetached == true)
- return;
- _eventsDetached = true;
- //detaches from parent form events
- Parent.Move -= new System.EventHandler(OnParentMove);
- Parent.ResizeEnd -= new EventHandler(OnParentResizeEnd);
- Parent.MaximizedBoundsChanged -= new System.EventHandler(OnParentMove);
- Parent.MinimumSizeChanged -= new System.EventHandler(OnParentMove);
- Parent.Load -= new System.EventHandler(OnLoadRegistry);
- Parent.FormClosed -= new FormClosedEventHandler(OnClosedRegistry);
- Parent.Load -= new System.EventHandler(OnLoadConfigFile);
- Parent.FormClosed -= new FormClosedEventHandler(OnClosedConfigFile);
- }
- #endregion
- #region Loading
- private void BindEventsToParent() {
- if(this.DesignMode)
- return;
- if(this.Enabled == false)
- return;
- if(_parent == null)
- throw new InvalidOperationException("Parent Property must be set for WindowState");
- this.PersistenceType = GlobalWindowStateType;
- if(this.PersistenceType == WindowStateType.Registry) {
- this.LoadRegistry();
- }
- else if(PersistenceType == WindowStateType.ConfigFile) {
- this.LoadConfigFile();
- }
- //attaches to parent form events
- Parent.Move += new System.EventHandler(OnParentMove);
- Parent.ResizeEnd += new EventHandler(OnParentResizeEnd);
- Parent.MaximizedBoundsChanged += new System.EventHandler(OnParentMove);
- Parent.MinimumSizeChanged += new System.EventHandler(OnParentMove);
- // get initial width and height in case form is never resized
- NormalPosition.Width = Parent.Width;
- NormalPosition.Height = Parent.Height;
- NormalPosition.Top = Parent.Top;
- NormalPosition.Left = Parent.Left;
- }
- #endregion
- #region Data Persistance
- #region Registry
- /// <summary>
- /// 0 always compress
- /// </summary>
- private const int COMPRESSED_MIN_SIZE = 0;
- private const string KEY_WINDOW_STATE = "WindowState";
- private const string KEY_COMPRESSED_FLAG = "CompressedFlg";
- //CompressionHelper
- private void LoadRegistry() {
- //attaches to parent form events
- Parent.Load += new System.EventHandler(OnLoadRegistry);
- Parent.FormClosed += new FormClosedEventHandler(OnClosedRegistry);
- }
- private void OnLoadRegistry(object sender,System.EventArgs e) {
- IsLoaded = true;
- this.OriginalPosition = new WindowStatePosition();
- using(RegistryKey regkey = Registry.CurrentUser.OpenSubKey(this.RegistryPath)) {
- try {
- if(regkey == null)
- return;
- object rawConfig = regkey.GetValue(KEY_WINDOW_STATE,null);
- if(rawConfig != null) {
- byte[] bytes = rawConfig as byte[];
- string xml = null;
- if(EncryptSettings) {
- try {
- byte[] decrypted = EncryptionHelper.Decrypt(bytes);
- xml = Encoding.Unicode.GetString(decrypted);
- }
- catch {
- xml = Encoding.Unicode.GetString(bytes);
- }
- }
- else {
- xml = Encoding.Unicode.GetString(bytes);
- }
- if(!string.IsNullOrEmpty(xml)) {
- WindowStateConfig config = WindowStateConfig.Deserialize(xml);
- LoadWindowStateConfig(config);
- }
- }
- }
- finally {
- // fire LoadState event
- this.OnSettingsLoaded(new EventArgs());
- if(regkey != null) {
- regkey.Close();
- }
- }
- }
- }
- // save position, size and state
- private void OnClosedRegistry(object sender,FormClosedEventArgs e) {
- this.OnSettingsSaved(new EventArgs());
- this.SetWindowState();
- this.DetachEvents();
- WindowStateConfig config = SetWindowStateConfig();
- var t = new Thread((state) => {
- try {
- this.SaveToRegistry(state as WindowStateConfig);
- }
- catch(Exception error) {
- System.Diagnostics.Trace.Write(error);
- }
- });
- t.Name = "WindowState.OnClosedRegistry => SaveToRegistry";
- t.Priority = ThreadPriority.Highest;
- t.Start(config);
- }
- private void SaveToRegistry(WindowStateConfig config) {
- using(RegistryKey regkey = Registry.CurrentUser.CreateSubKey(this.RegistryPath)) {
- try {
- string xml = WindowStateConfig.Serialize(config);
- byte[] data = Encoding.Unicode.GetBytes(xml);
- if(EncryptSettings) {
- byte[] encrypted = EncryptionHelper.Encrypt(data);
- regkey.SetValue(KEY_WINDOW_STATE,encrypted,RegistryValueKind.Binary);
- }
- else
- regkey.SetValue(KEY_WINDOW_STATE,data,RegistryValueKind.Binary);
- }
- finally {
- if(regkey != null)
- regkey.Close();
- }
- }
- }
- private string CreateRegistryKey() {
- string companyName = Application.CompanyName;
- string productName = Application.ProductName;
- string parentName = null;
- if(this.Parent != null)
- parentName = Parent.GetType().Name;
- string regkey = @"Software\" + companyName + @"\" + productName + @"\" + parentName + UniqueKey;
- return regkey;
- }
- #endregion
- #region ConfigFile
- private void LoadConfigFile() {
- Parent.Load += new System.EventHandler(OnLoadConfigFile);
- Parent.FormClosed += new FormClosedEventHandler(OnClosedConfigFile);
- }
- private void OnLoadConfigFile(object sender,System.EventArgs e) {
- IsLoaded = true;
- try {
- WindowStateConfig config = null;
- string settingsFileName = GetConfigFilename();
- if(File.Exists(settingsFileName) == false) {
- config = WindowStateConfig.GetDefault(this.Parent);
- LoadWindowStateConfig(config);
- return;
- }
- string data = null;
- if(EncryptSettings) {
- try {
- byte[] bytes = File.ReadAllBytes(settingsFileName);
- byte[] decrypted = EncryptionHelper.Decrypt(bytes);
- data = Encoding.Unicode.GetString(decrypted);
- }
- catch {
- data = File.ReadAllText(settingsFileName);
- }
- }
- else {
- data = File.ReadAllText(settingsFileName);
- }
- config = WindowStateConfig.Deserialize(data);
- if(config != null) {
- LoadWindowStateConfig(config);
- }
- }
- catch {
- var config = WindowStateConfig.GetDefault(this.Parent);
- LoadWindowStateConfig(config);
- }
- finally {
- // fire LoadState event
- this.OnSettingsLoaded(new EventArgs());
- }
- }
- private void SaveToConfigFile(WindowStateConfig config) {
- var data = WindowStateConfig.Serialize(config);
- if(EncryptSettings) {
- byte[] bytes = Encoding.Unicode.GetBytes(data);
- byte[] encrypted = EncryptionHelper.Encrypt(bytes);
- File.WriteAllBytes(config.FileName,encrypted);
- }
- else {
- File.WriteAllText(
- config.FileName,data
- );
- }
- }
- //save file
- private void OnClosedConfigFile(object sender,FormClosedEventArgs e) {
- this.OnSettingsSaved(new EventArgs());
- this.SetWindowState();
- this.DetachEvents();
- WindowStateConfig config = SetWindowStateConfig();
- var t = new Thread((state) => {
- try {
- SaveToConfigFile(state as WindowStateConfig);
- }
- catch(Exception error) {
- System.Diagnostics.Trace.Write(error);
- }
- });
- t.Name = "WindowState.OnClosedConfigFile => SaveToConfigFile";
- t.Priority = ThreadPriority.Highest;
- t.Start(config);
- }
- private string settingsToXml() {
- var items = Settings.Select(kv => new SettingInfo() {
- Key = kv.Key,
- Value = kv.Value
- }).ToArray();
- return XmlSerialization.Serialize<SettingInfo[]>(items);
- }
- private Dictionary<string,object> settingsFromXml(string xml) {
- if(string.IsNullOrEmpty(xml))
- return new Dictionary<string,object>();
- var items = XmlSerialization.Deserialize<SettingInfo[]>(xml)
- .Where(si => !string.IsNullOrEmpty(si.Key))
- .ToArray();
- var dictionary = new Dictionary<string,object>(items.Length);
- foreach(var item in items) {
- if(!dictionary.ContainsKey(item.Key))
- dictionary.Add(item.Key,item.Value);
- }
- return dictionary;
- }
- private string GetConfigFilename() {
- string winstateFileName = ".settings";
- string parentName = null;
- string companyName = Application.CompanyName;
- string productName = Application.ProductName;
- string winstatePath = "WindowState";
- if(this.Parent != null)
- parentName = Parent.GetType().Name;
- winstateFileName = parentName + winstateFileName;
- if(SaveInAppData) {
- string appPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
- appPath = Path.Combine(appPath,companyName);
- if(Directory.Exists(appPath) == false)
- Directory.CreateDirectory(appPath);
- appPath = Path.Combine(appPath,productName);
- if(Directory.Exists(appPath) == false)
- Directory.CreateDirectory(appPath);
- string filePath = Path.Combine(appPath,winstatePath);
- if(Directory.Exists(filePath) == false)
- Directory.CreateDirectory(filePath);
- string settingsFileName = Path.Combine(filePath,winstateFileName);
- return settingsFileName;
- }
- else {
- string exePath = Assembly.GetExecutingAssembly().Location;
- FileInfo exeInfo = new FileInfo(exePath);
- string appPath = exeInfo.Directory.FullName;
- string filePath = Path.Combine(appPath,winstatePath);
- if(Directory.Exists(filePath) == false)
- Directory.CreateDirectory(filePath);
- string settingsFileName = Path.Combine(filePath,winstateFileName);
- return settingsFileName;
- }
- }
- #endregion
- private void LoadWindowStateConfig(WindowStateConfig config) {
- this.OriginalPosition = config.Position;
- this.ControlDictionary.Clear();
- if(config.ControlData != null) {
- foreach(var item in config.ControlData) {
- if(!this.ControlDictionary.ContainsKey(item.Key))
- this.ControlDictionary.Add(item.Key,item);
- }
- }
- this.Settings.Clear();
- if(config.Settings != null) {
- foreach(var item in config.Settings) {
- if(!this.Settings.ContainsKey(item.Key))
- this.Settings.Add(item.Key,SettingInfo.DeserializeSettingValue(item));
- }
- }
- this.SetParentWindowPosition(config.Position);
- }
- private WindowStateConfig SetWindowStateConfig() {
- WindowStateConfig config = new WindowStateConfig();
- config.FileName = this.GetConfigFilename();
- config.Position = this.NormalPosition;
- config.ControlData = this.ControlDictionary
- .Where(kv => {
- if(kv.Value == null)
- return false;
- if(kv.Value.PropertyValue == null)
- return true;
- else
- return kv.Value.PropertyValue.GetType().IsSerializable;
- })
- .Select(kv => kv.Value).ToArray();
- config.Settings = Settings.Select(kv => new SettingInfo(kv)).ToArray();
- return config;
- }
- #endregion
- #region Parent Events
- private void SetWindowState() {
- // check if we are allowed to save the state as minimized (not normally)
- if(_allowSaveMinimized == false) {
- if(_lastWindowState == FormWindowState.Minimized) {
- if(_allowSaveMaximized == false) {
- _lastWindowState = FormWindowState.Normal;
- }
- }
- }
- if(_allowSaveMaximized == false) {
- if(_lastWindowState == FormWindowState.Maximized) {
- if(_allowSaveMinimized == false) {
- _lastWindowState = FormWindowState.Normal;
- }
- }
- }
- }
- private void OnParentResizeEnd(object sender,EventArgs e) {
- if(!this.Enabled)
- return;
- if(Parent.WindowState == FormWindowState.Normal) {
- NormalPosition.Width = Parent.Width;
- NormalPosition.Height = Parent.Height;
- NormalPosition.Top = Parent.Top;
- NormalPosition.Left = Parent.Left;
- }
- }
- private void OnParentMove(object sender,System.EventArgs e) {
- if(!this.Enabled)
- return;
- // save position
- if(Parent.WindowState == FormWindowState.Normal) {
- NormalPosition.Width = Parent.Width;
- NormalPosition.Height = Parent.Height;
- NormalPosition.Top = Parent.Top;
- NormalPosition.Left = Parent.Left;
- }
- // save state
- _lastWindowState = Parent.WindowState;
- }
- private void SetParentWindowPosition(WindowStatePosition position) {
- int left = position.Left;
- int top = position.Top;
- int width = position.Width;
- int height = position.Height;
- FormWindowState windowState = position.WindowState;
- this.SetParentWindowPosition(left,top,width,height,windowState);
- }
- private void SetParentWindowPosition(int left,int top,int width,int height,FormWindowState windowState) {
- if(Screen.PrimaryScreen.Bounds.Left > left)
- left = Screen.PrimaryScreen.Bounds.Left;
- if(Screen.PrimaryScreen.Bounds.Top > top)
- top = Screen.PrimaryScreen.Bounds.Top;
- if(!_ignoreTopLeft)
- Parent.Location = new Point(left,top);
- if(!_ignoreHeightWidth)
- Parent.Size = new Size(width,height);
- if(!_ignoreWindowState)
- Parent.WindowState = windowState;
- }
- private void SetParentWindowPosition(FormWindowState windowState) {
- if(!_ignoreWindowState)
- Parent.WindowState = windowState;
- }
- #endregion
- #region Extended Controls
- private Type[] _notSupportedControls = new Type[]
- {
- typeof(Form)
- };
- private Dictionary<Control,ExtendedControlProperties> _extendedControls = new Dictionary<Control,ExtendedControlProperties>();
- private Dictionary<Control,ExtendedControlProperties> ExtendedControls {
- get { return _extendedControls; }
- set { _extendedControls = value; }
- }
- public string GetWindowStateBindingProperty(Control control) {
- if(ExtendedControls.ContainsKey(control)) {
- ExtendedControlProperties extProperties = ExtendedControls[control];
- if(extProperties != null) {
- if(string.IsNullOrEmpty(extProperties.PropertyNames)) {
- var propInfo = TypeDescriptor.GetDefaultProperty(control);
- if(propInfo != null)
- extProperties.PropertyNames = propInfo.Name;
- }
- return extProperties.PropertyNames;
- }
- }
- return null;
- }
- public void SetWindowStateBindingProperty(Control control,string propertyName) {
- ExtendedControlProperties extProperties = null;
- if(ExtendedControls.ContainsKey(control)) {
- extProperties = ExtendedControls[control];
- }
- else {
- extProperties = new ExtendedControlProperties();
- extProperties.BindEnabled = true;
- ExtendedControls.Add(control,extProperties);
- }
- extProperties.PropertyNames = propertyName;
- if(extProperties.BindEnabled)
- BindControl(control,extProperties);
- }
- public bool GetWindowStateBinding(Control control) {
- if(ExtendedControls.ContainsKey(control)) {
- ExtendedControlProperties extProperties = ExtendedControls[control];
- if(extProperties != null)
- return extProperties.BindEnabled;
- }
- return false;
- }
- public void SetWindowStateBinding(Control control,bool bindingEnabled) {
- ExtendedControlProperties extProperties = null;
- if(ExtendedControls.ContainsKey(control)) {
- extProperties = ExtendedControls[control];
- }
- else {
- extProperties = new ExtendedControlProperties();
- ExtendedControls.Add(control,extProperties);
- }
- extProperties.BindEnabled = bindingEnabled;
- if(bindingEnabled)
- BindControl(control);
- }
- public bool CanExtend(object extendee) {
- if(!(extendee is Control))
- return false;
- if(_parent == null) {
- Control ctrl = extendee as Control;
- this.Parent = ctrl.FindForm();
- }
- return true;
- }
- private bool IsControlSupported(Control cnt) {
- if(cnt is Form)
- return false;
- return true;
- }
- public class ExtendedControlProperties {
- public bool BindEnabled { get; set; }
- public string PropertyNames { get; set; }
- }
- #endregion
- protected override void Dispose(bool disposing) {
- if(disposing && (components != null)) {
- DetachEvents();
- components.Dispose();
- }
- base.Dispose(disposing);
- }
- }
- #region Supporting Classes
- public class WindowStateConfig {
- public static WindowStateConfig GetDefault(Form parent) {
- WindowStateConfig config = new WindowStateConfig();
- config.Position = new WindowStatePosition();
- config.Position.Left = parent.Left;
- config.Position.Top = parent.Top;
- config.Position.Width = parent.Width;
- config.Position.Height = parent.Height;
- //if(!parent.MinimumSize.IsEmpty) {
- // if(parent.MinimumSize.Width > 0)
- // config.Position.Width = parent.MinimumSize.Width;
- // if(parent.MinimumSize.Height > 0)
- // config.Position.Height = parent.MinimumSize.Height;
- //}
- config.Position.WindowState = FormWindowState.Normal;
- return config;
- }
- //[XmlIgnore]
- public string FileName { get; set; }
- public static string Serialize(WindowStateConfig xmlObject) {
- return XmlSerialization.Serialize<WindowStateConfig>(xmlObject);
- }
- public static WindowStateConfig Deserialize(string xml) {
- return XmlSerialization.Deserialize<WindowStateConfig>(xml);
- }
- public WindowStatePosition Position { get; set; }
- public WindowState.SettingInfo[] Settings { get; set; }
- public WindowState.ControlInfo[] ControlData { get; set; }
- }
- public class WindowStatePosition {
- [XmlAttribute]
- public int Left { get; set; }
- [XmlAttribute]
- public int Top { get; set; }
- [XmlAttribute]
- public int Width { get; set; }
- [XmlAttribute]
- public int Height { get; set; }
- [XmlAttribute]
- public FormWindowState WindowState { get; set; }
- public void CopyTo(WindowStatePosition copied) {
- copied.Left = this.Left;
- copied.Top = this.Top;
- copied.Width = this.Width;
- copied.Height = this.Height;
- copied.WindowState = this.WindowState;
- }
- public WindowStatePosition Copy() {
- WindowStatePosition copied = new WindowStatePosition();
- copied.Left = this.Left;
- copied.Top = this.Top;
- copied.Width = this.Width;
- copied.Height = this.Height;
- copied.WindowState = this.WindowState;
- return copied;
- }
- }
- public enum WindowStateType {
- Registry,
- ConfigFile
- }
- public class StatePersistance {
- /// <summary>
- /// Deserializes an object from a Base64String string
- /// </summary>
- /// <param name="s">Base64String string</param>
- /// <returns>Returns the object that was serialize using the SaveObjectToString() method</returns>
- public static object ReadObjectFromString(string s) {
- using(MemoryStream memory = new MemoryStream(Convert.FromBase64String(s))) {
- return ReadObjectFromStream(memory);
- }
- }
- /// <summary>
- /// Deserializes an object from a stream
- /// </summary>
- /// <param name="s">stream that the object was serialized into</param>
- /// <returns>Returns the object that was serialize using the SaveObjectToStream() method</returns>
- public static object ReadObjectFromStream(Stream s) {
- s.Position = 0;
- return new BinaryFormatter().Deserialize(s);
- }
- /// <summary>
- /// Serializes an object into a memory stream
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static MemoryStream SaveObjectToStream(object obj) {
- MemoryStream memory = new MemoryStream();
- new BinaryFormatter().Serialize(memory,obj);
- return memory;
- }
- public static byte[] SaveObjectToBytes(object obj) {
- using(MemoryStream memory = new MemoryStream()) {
- new BinaryFormatter().Serialize(memory,obj);
- memory.Position = 0;
- return memory.ToArray();
- }
- }
- /// <summary>
- /// Serializes an object into a Base64 string
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static string SaveObjectToString(object obj) {
- using(MemoryStream memory = SaveObjectToStream(obj)) {
- memory.Position = 0;
- return Convert.ToBase64String(memory.ToArray());
- }
- }
- /// <summary>
- /// Deserilizes an object from a file
- /// </summary>
- /// <param name="FileName"></param>
- /// <returns></returns>
- public static object ReadObjectFromFile(string FileName) {
- using(Stream stm = File.Open(FileName,FileMode.Open,FileAccess.Read,FileShare.Read)) {
- BinaryFormatter bformatter = new BinaryFormatter();
- stm.Position = 0;
- if(stm.Length == 0)
- return null;
- return bformatter.Deserialize(stm);
- }
- }
- /// <summary>
- /// Serializes an object into a file
- /// </summary>
- /// <param name="Object"></param>
- /// <param name="FileName"></param>
- /// <returns></returns>
- public static bool SaveObjectToFile(object data,string FileName) {
- if(File.Exists(FileName))
- File.Delete(FileName);
- using(var stm = File.Open(FileName,FileMode.CreateNew,FileAccess.Write,FileShare.Write)) {
- BinaryFormatter bformatter = new BinaryFormatter();
- bformatter.Serialize(stm,data);
- return true;
- }
- }
- /// <summary>
- /// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
- /// </summary>
- /// <param name="characters">Unicode Byte Array to be converted to String</param>
- /// <returns>String converted from Unicode Byte Array</returns>
- private static String UTF8ByteArrayToString(byte[] characters) {
- UTF8Encoding encoding = new UTF8Encoding();
- string constructedString = encoding.GetString(characters);
- return (constructedString);
- }
- /// <summary>
- /// Converts the String to UTF8 Byte array and is used in De serialization
- /// </summary>
- /// <param name="pXmlString"></param>
- /// <returns></returns>
- private static Byte[] StringToUTF8ByteArray(string xml) {
- UTF8Encoding encoding = new UTF8Encoding();
- byte[] byteArray = encoding.GetBytes(xml);
- return byteArray;
- }
- public static String SerializeXmlObject(object pObject,Type objectType) {
- using(MemoryStream memoryStream = new MemoryStream()) {
- XmlSerializer xs = new XmlSerializer(objectType);
- XmlSerializerNamespaces xmlNamespace = new XmlSerializerNamespaces();
- xmlNamespace.Add(string.Empty,string.Empty);
- xs.Serialize(memoryStream,pObject,xmlNamespace);
- return UTF8ByteArrayToString(memoryStream.ToArray());
- }
- }
- /// <summary>
- /// Method to reconstruct an Object from XML string
- /// </summary>
- /// <param name="pXmlizedString"></param>
- /// <returns></returns>
- public static object DeserializeXmlObject(string xml,Type objectType) {
- XmlSerializer xs = new XmlSerializer(objectType);
- using(MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xml))) {
- XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream,Encoding.UTF8);
- return xs.Deserialize(memoryStream);
- }
- }
- }
- public static class CompressionUtility {
- public static string Compress(string data) {
- //byte[] before = ASCIIEncoding.Unicode.GetBytes(data);
- //byte[] compressed = Compress(ASCIIEncoding.Unicode.GetBytes(data));
- return Convert.ToBase64String(Compress(ASCIIEncoding.Unicode.GetBytes(data)));
- }
- public static string Decompress(string data) {
- //byte[] before = Convert.FromBase64String(data);
- //byte[] deCompressed = Decompress(Convert.FromBase64String(data));
- return ASCIIEncoding.Unicode.GetString(Decompress(Convert.FromBase64String(data)));
- }
- public static MemoryStream Compress(MemoryStream data) {
- MemoryStream output = new MemoryStream();
- using(GZipStream gzip = new GZipStream(output,CompressionMode.Compress,true)) {
- gzip.Write(data.ToArray(),0,(int)data.Length);
- gzip.Close();
- return output;
- }
- }
- public static MemoryStream Decompress(MemoryStream data) {
- using(MemoryStream input = new MemoryStream()) {
- input.Write(data.ToArray(),0,(int)data.Length);
- input.Position = 0;
- using(GZipStream gzip = new GZipStream(input,CompressionMode.Decompress,true)) {
- MemoryStream output = new MemoryStream();
- byte[] buff = new byte[64];
- int read = -1;
- read = gzip.Read(buff,0,buff.Length);
- while(read > 0) {
- output.Write(buff,0,read);
- read = gzip.Read(buff,0,buff.Length);
- }
- gzip.Close();
- return output;
- }
- }
- }
- public static byte[] Compress(byte[] data) {
- using(MemoryStream output = new MemoryStream()) {
- using(GZipStream gzip = new GZipStream(output,CompressionMode.Compress,true)) {
- gzip.Write(data,0,data.Length);
- gzip.Close();
- return output.ToArray();
- }
- }
- }
- public static byte[] Decompress(byte[] data) {
- using(MemoryStream input = new MemoryStream()) {
- input.Write(data,0,data.Length);
- input.Position = 0;
- using(GZipStream gzip = new GZipStream(input,CompressionMode.Decompress,true)) {
- using(MemoryStream output = new MemoryStream()) {
- byte[] buff = new byte[64];
- int read = -1;
- read = gzip.Read(buff,0,buff.Length);
- while(read > 0) {
- output.Write(buff,0,read);
- read = gzip.Read(buff,0,buff.Length);
- }
- gzip.Close();
- return output.ToArray();
- }
- }
- }
- }
- }
- public class EncryptionHelper {
- private static string _Salt = "fA2qiF3P`u[Oagbf4'x>0C%wBVy{8)1f";
- private static string _Password = @",!=K};zr*4j,CeHn5!q 0DbO^WGxz1dX";
- private static string Password {
- get { return _Password; }
- set { _Password = value; }
- }
- #region Encrypt/Decrypt
- public static string Encrypt(string dataToEncrypt) {
- return Encrypt(dataToEncrypt,Password,_Salt);
- }
- public static string Encrypt(string dataToEncrypt,string pwd) {
- return Encrypt(dataToEncrypt,pwd,_Salt);
- }
- public static string Encrypt(string dataToEncrypt,string pwd,string salt) {
- byte[] encrypted;
- return Encrypt(null,dataToEncrypt,pwd,salt,out encrypted);
- }
- public static byte[] Encrypt(byte[] bytes) {
- byte[] encrypted;
- Encrypt(bytes,null,Password,_Salt,out encrypted);
- return encrypted;
- }
- private static string Encrypt(byte[] bytes,string dataToEncrypt,string pwd,string salt,out byte[] encrypted) {
- if(pwd.IsNull())
- pwd = Password;
- if(salt.IsNull())
- salt = _Salt;
- string password = pwd;
- string plainText = dataToEncrypt;
- string encryptedData = null;
- byte[] plainBytes = bytes;
- if(plainBytes == null)
- plainBytes = Encoding.ASCII.GetBytes(plainText);
- //Rfc2898DeriveBytes: Used to Generate Strong Keys
- Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password,
- Encoding.ASCII.GetBytes(salt));//Non-English Alfhabets Will not Work on ASCII Encoding
- SymmetricAlgorithm Alg = new DESCryptoServiceProvider();
- Alg.Key = rfc.GetBytes(Alg.KeySize / 8);
- Alg.IV = rfc.GetBytes(Alg.BlockSize / 8);
- using(MemoryStream strCiphered = new MemoryStream()) {//To Store Encrypted Data
- CryptoStream strCrypto = new CryptoStream(strCiphered,
- Alg.CreateEncryptor(),CryptoStreamMode.Write);
- strCrypto.Write(plainBytes,0,plainBytes.Length);
- strCrypto.Close();
- if(bytes != null) {
- encrypted = strCiphered.ToArray();
- encryptedData = null;
- }
- else {
- encrypted = null;
- encryptedData = Convert.ToBase64String(strCiphered.ToArray());
- }
- strCiphered.Close();
- }
- return encryptedData;
- }
- public static string Decrypt(string dataToDecrypt) {
- return Decrypt(dataToDecrypt,Password,_Salt);
- }
- public static string Decrypt(string dataToDecrypt,string pwd) {
- return Decrypt(dataToDecrypt,pwd,_Salt);
- }
- public static string Decrypt(string dataToDecrypt,string pwd,string salt) {
- byte[] decrypted = null;
- return Decrypt(null,dataToDecrypt,pwd,salt,out decrypted);
- }
- public static byte[] Decrypt(byte[] bytes) {
- byte[] decrypted = null;
- Decrypt(bytes,null,Password,_Salt,out decrypted);
- return decrypted;
- }
- public static string Decrypt(byte[] bytes,string dataToDecrypt,string pwd,string salt,out byte[] decrypted) {
- if(pwd.IsNull())
- pwd = Password;
- if(salt.IsNull())
- salt = _Salt;
- string password = pwd;
- string cipheredText = dataToDecrypt;
- string decryptedData = null;
- byte[] cipheredBytes = bytes;
- if(cipheredBytes == null)
- cipheredBytes = Convert.FromBase64String(cipheredText);
- //Rfc2898DeriveBytes: Used to Generate Strong Keys
- Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password,
- Encoding.ASCII.GetBytes(salt));//Non-English Alfhabets Will not Work on ASCII Encoding
- SymmetricAlgorithm Alg = new DESCryptoServiceProvider();
- Alg.Key = rfc.GetBytes(Alg.KeySize / 8);
- Alg.IV = rfc.GetBytes(Alg.BlockSize / 8);
- using(MemoryStream strDeciphered = new MemoryStream()) {//To Store Decrypted Data
- CryptoStream strCrypto = new CryptoStream(strDeciphered,
- Alg.CreateDecryptor(),CryptoStreamMode.Write);
- strCrypto.Write(cipheredBytes,0,cipheredBytes.Length);
- strCrypto.Close();
- if(bytes != null) {
- decrypted = strDeciphered.ToArray();
- decryptedData = null;
- }
- else {
- decrypted = null;
- decryptedData = Encoding.ASCII.GetString(strDeciphered.ToArray());
- }
- strDeciphered.Close();
- }
- return decryptedData;
- }
- #endregion
- }
- #region Extentions
- //public static class Extensions {
- // public static bool IsNull(this string s) {
- // return IsNullOrEmptyTrim(s);
- // }
- // public static bool IsNullOrEmptyTrim(this string s) {
- // if(s == null)
- // return true;
- // if(string.IsNullOrEmpty(s))
- // return true;
- // if(s.Equals(Environment.NewLine))
- // return false;
- // if(string.IsNullOrEmpty(s.Trim()))
- // return true;
- // return false;
- // }
- // public static string ToSentenceCase(this string s) {
- // if(s == null)
- // return s;
- // if(s.Trim().Length == 0)
- // return s;
- // var sb = new StringBuilder(s.Length);
- // var parts = s.Split(" ".ToCharArray());
- // for(int i = 0;i < parts.Length;i++) {
- // char[] word = parts[i].ToCharArray();
- // if(word.Length == 1) {
- // if(char.IsWhiteSpace(word[0])) {
- // sb.Append(word[0]);
- // continue;
- // }
- // }
- // for(int j = 0;j < word.Length;j++) {
- // if(j == 0)
- // word[j] = char.ToUpperInvariant(word[j]);
- // else
- // word[j] = char.ToLowerInvariant(word[j]);
- // }
- // sb.Append(new string(word));
- // sb.Append(" ");
- // }
- // return sb.ToString().TrimEnd();
- // }
- // public static string ToToogleCase(this string s) {
- // if(s == null)
- // return s;
- // if(s.Trim().Length == 0)
- // return s;
- // var sb = new StringBuilder(s.Length);
- // var parts = s.Split(" ".ToCharArray());
- // for(int i = 0;i < parts.Length;i++) {
- // char[] word = parts[i].ToCharArray();
- // if(word.Length == 1) {
- // if(char.IsWhiteSpace(word[0])) {
- // sb.Append(word[0]);
- // continue;
- // }
- // }
- // for(int j = 0;j < word.Length;j++) {
- // if(char.IsUpper(word[j]))
- // word[j] = char.ToLowerInvariant(word[j]);
- // else if(char.IsLower(word[j]))
- // word[j] = char.ToUpperInvariant(word[j]);
- // }
- // sb.Append(new string(word));
- // sb.Append(" ");
- // }
- // return sb.ToString().TrimEnd();
- // }
- //}
- #endregion
- #endregion
- }
Advertisement
Add Comment
Please, Sign In to add comment