andrew4582

WindowState

Mar 19th, 2012
316
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 58.49 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Collections.Specialized;
  5. using System.ComponentModel;
  6. using System.Data;
  7. using System.Diagnostics;
  8. using System.Drawing;
  9. using System.IO;
  10. using System.IO.Compression;
  11. using System.Linq;
  12. using System.Reflection;
  13. using System.Runtime.Serialization;
  14. using System.Runtime.Serialization.Formatters.Binary;
  15. using System.Security.Cryptography;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Windows.Forms;
  19. using System.Xml;
  20. using System.Xml.Serialization;
  21. using Microsoft.Win32;
  22.  
  23. namespace System.Windows.Forms {
  24.     // Last updated Tuesday March 2,2010 1:49 PM
  25.     [DefaultEvent("SettingsLoaded")]
  26.     [DefaultProperty("Parent")]
  27.     [ProvideProperty("WindowStateBinding",typeof(Control))]
  28.     [ProvideProperty("WindowStateBindingProperty",typeof(Control))]
  29.     public class WindowState:Component,IExtenderProvider {
  30.  
  31.         const WindowStateType GlobalWindowStateType_Default = WindowStateType.Registry;
  32.         const bool GlobalEnabled_Default = true;
  33.  
  34.         public static WindowStateType GlobalWindowStateType { get; set; }
  35.         public static bool GlobalEnabled { get; set; }
  36.         public event EventHandler SettingsLoaded;
  37.         public event EventHandler SettingsSaved;
  38.  
  39.         private Form _parent;
  40.         private FormWindowState _lastWindowState;
  41.         private ControlInfoDictionary _controlDictionary;
  42.         private Dictionary<string,object> _settings;
  43.         private WindowStateType _persistenceType;
  44.         private bool _saveInAppData;
  45.         private string _registryPath;
  46.         private bool _allowSaveMinimized;
  47.         private bool _allowSaveMaximized;
  48.         private bool _enabled;
  49.         private string _uniqueKey;
  50.         private bool _loaded;
  51.         private bool _ignoreHeightWidth;
  52.         private bool _ignoreTopLeft;
  53.         private bool _ignoreWindowState;
  54.         private WindowStatePosition _normalPosition;
  55.         private WindowStatePosition _originalPosition;
  56.         private bool _eventsDetached;
  57.         private Dictionary<string,ControlInfo> _bindedControls;
  58.         private bool _encryptSettings;
  59.         private System.ComponentModel.IContainer components = null;
  60.  
  61.         #region Properties
  62.         [Browsable(true)]
  63.         [Category("WindowState")]
  64.         public Form Parent {
  65.             get {
  66.                 return _parent;
  67.             }
  68.             set {
  69.                 _parent = value;
  70.                 // subscribe to parent form's events
  71.                 if(_parent != null)
  72.                     this.BindEventsToParent();
  73.             }
  74.         }
  75.         [Browsable(true)]
  76.         [Category("WindowState")]
  77.         [DefaultValue(true)]
  78.         public bool SaveInAppData {
  79.             get {
  80.                 return _saveInAppData;
  81.             }
  82.             set {
  83.                 _saveInAppData = value;
  84.             }
  85.         }
  86.         // registry key should be set in parent form's constructor
  87.         [Browsable(false)]
  88.         [Category("WindowState")]
  89.         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  90.         public string RegistryPath {
  91.             get {
  92.                 if(DesignMode)
  93.                     return null;
  94.                 if(string.IsNullOrEmpty(_registryPath))
  95.                     _registryPath = CreateRegistryKey();
  96.                 return _registryPath;
  97.             }
  98.         }
  99.         [DefaultValue(false)]
  100.         [Browsable(true)]
  101.         [Category("WindowState")]
  102.         public bool AllowSaveMinimized {
  103.             get {
  104.                 return _allowSaveMinimized;
  105.             }
  106.             set {
  107.                 _allowSaveMinimized = value;
  108.             }
  109.         }
  110.         [DefaultValue(false)]
  111.         [Browsable(true)]
  112.         [Category("WindowState")]
  113.         public bool EncryptSettings {
  114.             get {
  115.                 return _encryptSettings;
  116.             }
  117.             set {
  118.                 _encryptSettings = value;
  119.             }
  120.         }
  121.         [DefaultValue(false)]
  122.         [Browsable(true)]
  123.         [Category("WindowState")]
  124.         public bool AllowSaveMaximized {
  125.             get {
  126.                 return _allowSaveMaximized;
  127.             }
  128.             set {
  129.                 _allowSaveMaximized = value;
  130.             }
  131.         }
  132.         [DefaultValue(false)]
  133.         [Browsable(true)]
  134.         [Category("WindowState")]
  135.         public bool IgnoreWindowState {
  136.             get { return _ignoreWindowState; }
  137.             set { _ignoreWindowState = value; }
  138.         }
  139.         [DefaultValue(false)]
  140.         [Browsable(true)]
  141.         [Category("WindowState")]
  142.         public bool IgnoreTopLeft {
  143.             get { return _ignoreTopLeft; }
  144.             set { _ignoreTopLeft = value; }
  145.         }
  146.         [DefaultValue(false)]
  147.         [Browsable(true)]
  148.         [Category("WindowState")]
  149.         public bool IgnoreHeightWidth {
  150.             get { return _ignoreHeightWidth; }
  151.             set { _ignoreHeightWidth = value; }
  152.         }
  153.         [DefaultValue(true)]
  154.         [Browsable(true)]
  155.         [Category("WindowState")]
  156.         public bool Enabled {
  157.             get { return _enabled; }
  158.             set { _enabled = value; }
  159.         }
  160.         [DefaultValue("")]
  161.         [Browsable(true)]
  162.         [Category("WindowState")]
  163.         [Description("")]
  164.         public string UniqueKey {
  165.             get { return _uniqueKey; }
  166.             set { _uniqueKey = value; }
  167.         }
  168.         [Browsable(false)]
  169.         [Category("WindowState")]
  170.         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  171.         public bool IsLoaded {
  172.             get { return _loaded; }
  173.             set { _loaded = value; }
  174.         }
  175.         private WindowStateType PersistenceType {
  176.             get { return _persistenceType; }
  177.             set { _persistenceType = value; }
  178.         }
  179.         [Browsable(false)]
  180.         [Category("WindowState")]
  181.         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  182.         public WindowStatePosition NormalPosition {
  183.             get {
  184.                 if(_normalPosition == null)
  185.                     _normalPosition = new WindowStatePosition();
  186.                 return _normalPosition;
  187.             }
  188.             private set { _normalPosition = value; }
  189.         }
  190.         [Browsable(false)]
  191.         [Category("WindowState")]
  192.         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  193.         public WindowStatePosition OriginalPosition {
  194.             get {
  195.                 if(_originalPosition == null)
  196.                     _originalPosition = new WindowStatePosition();
  197.                 return _originalPosition;
  198.             }
  199.             private set { _originalPosition = value; }
  200.         }
  201.         #endregion
  202.  
  203.         #region Settings
  204.         [Browsable(false)]
  205.         [Category("WindowState")]
  206.         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  207.         [Description("A dictionary of Binded Controls")]
  208.         public ControlInfoDictionary ControlDictionary {
  209.             get {
  210.                 if(_controlDictionary == null)
  211.                     _controlDictionary = new ControlInfoDictionary();
  212.                 return _controlDictionary;
  213.             }
  214.             private set { _controlDictionary = value; }
  215.         }
  216.         [Browsable(false)]
  217.         [Category("WindowState")]
  218.         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  219.         [Description("Allows you to add/get data")]
  220.         public Dictionary<string,object> Settings {
  221.             get {
  222.                 if(_settings == null)
  223.                     _settings = new Dictionary<string,object>();
  224.                 return _settings;
  225.             }
  226.             private set { _settings = value; }
  227.         }
  228.         public void BindControl(Control ctrl,ExtendedControlProperties extProperties) {
  229.             if(string.IsNullOrEmpty(extProperties.PropertyNames))
  230.                 BindControl(ctrl);
  231.             else
  232.                 BindControl(ctrl,extProperties.PropertyNames);
  233.         }
  234.         public void BindControl(Control ctrl) {
  235.             if(ctrl == null)
  236.                 throw new ArgumentNullException("cntrl");
  237.  
  238.             var propInfo = TypeDescriptor.GetDefaultProperty(ctrl);
  239.             if(propInfo == null)
  240.                 return;
  241.             BindControl(ctrl,propInfo.Name);
  242.         }
  243.         public void BindControl(Control ctrl,string propertyName) {
  244.             if(ctrl == null)
  245.                 return;
  246.             ControlInfo info = new ControlInfo(ctrl,propertyName);
  247.             if(!_bindedControls.ContainsKey(info.Key))
  248.                 _bindedControls.Add(info.Key,info);
  249.         }
  250.         private void loadPersistedControls() {
  251.             var infoList = getInfoFromSettings();
  252.             foreach(var info in infoList) {
  253.                 var ctrl = _parent.Controls.Find(info.Name,true)
  254.                     .FirstOrDefault();
  255.  
  256.                 if(ctrl == null)
  257.                     continue;
  258.                 setPropertyValue(ctrl,info.PropertyName,info.PropertyValue);
  259.             }
  260.         }
  261.         private void savePersistedControls() {
  262.             foreach(var info in _bindedControls.Values) {
  263.                 var ctrl = _parent.Controls.Find(info.Name,true)
  264.                     .FirstOrDefault();
  265.  
  266.                 if(ctrl == null)
  267.                     continue;
  268.                 info.PropertyValue = getPropertyValue(ctrl,info.PropertyName);
  269.                 if(ControlDictionary.ContainsKey(info.Key))
  270.                     ControlDictionary.Remove(info.Key);
  271.                 ControlDictionary.Add(info.Key,info);
  272.             }
  273.         }
  274.         private object getPropertyValue(object component,string propertyName) {
  275.             PropertyDescriptor propInfo = null;
  276.             if(string.IsNullOrEmpty(propertyName))
  277.                 propInfo = TypeDescriptor.GetDefaultProperty(component);
  278.             else {
  279.                 foreach(PropertyDescriptor item in TypeDescriptor.GetProperties(component)) {
  280.                     if(item.Name == propertyName) {
  281.                         propInfo = item;
  282.                         break;
  283.                     }
  284.                 }
  285.             }
  286.             if(propInfo != null)
  287.                 return propInfo.GetValue(component);
  288.             else
  289.                 return null;
  290.         }
  291.         private void setPropertyValue(object component,string propertyName,object value) {
  292.             PropertyDescriptor propInfo = null;
  293.             if(string.IsNullOrEmpty(propertyName))
  294.                 propInfo = TypeDescriptor.GetDefaultProperty(component);
  295.             else {
  296.                 foreach(PropertyDescriptor item in TypeDescriptor.GetProperties(component)) {
  297.                     if(item.Name == propertyName) {
  298.                         propInfo = item;
  299.                         break;
  300.                     }
  301.                 }
  302.             }
  303.             if(propInfo != null)
  304.                 propInfo.SetValue(component,value);
  305.         }
  306.         private List<ControlInfo> getInfoFromSettings() {
  307.             var infoList = ControlDictionary
  308.                  .Where(k => _bindedControls.ContainsKey(k.Key))
  309.                .Select(v => v.Value)
  310.                .Cast<ControlInfo>()
  311.                .ToList();
  312.  
  313.             return infoList;
  314.         }
  315.  
  316.         #region ControlInfo
  317.         [Serializable]
  318.         [XmlRoot("SettingInfo")]
  319.         public class SettingInfo {
  320.             [XmlAttribute]
  321.             public string Key { get; set; }
  322.             [XmlAttribute]
  323.             public string TypeName { get; set; }
  324.             [XmlAttribute]
  325.             public bool IsSerializable { get; set; }
  326.             [XmlElement(Type = typeof(string))]
  327.             public object Value { get; set; }
  328.  
  329.             public SettingInfo() {
  330.  
  331.             }
  332.             public SettingInfo(KeyValuePair<string,object> kv) {
  333.                 Key = kv.Key;
  334.                 Value = kv.Value;
  335.                 Value = SerializeSettingValue(this);
  336.             }
  337.             public static object SerializeSettingValue(SettingInfo info) {
  338.                 info.IsSerializable = false;
  339.                 if(info.Value == null) {
  340.                     return null;
  341.                 }
  342.                 object value = info.Value;
  343.                 Type type = value.GetType();
  344.                 info.TypeName = type.Name;
  345.  
  346.                 if(type.Equals(typeof(string)))
  347.                     info.IsSerializable = false;
  348.                 else {
  349.                     if(type.IsArray)
  350.                         info.IsSerializable = true;
  351.                     else if(type.IsEnum)
  352.                         info.IsSerializable = true;
  353.                     else {
  354.                         if(type.IsSerializable)
  355.                             info.IsSerializable = !type.IsPrimitive;
  356.                     }
  357.                 }
  358.                 if(info.IsSerializable)
  359.                     return StatePersistance.SaveObjectToString(value);
  360.                 return value.ToString();
  361.             }
  362.             public static object DeserializeSettingValue(SettingInfo info) {
  363.                 if(info.Value == null)
  364.                     return null;
  365.                 if(info.Value.ToString() == string.Empty)
  366.                     return string.Empty;
  367.                 if(info.IsSerializable)
  368.                     return StatePersistance.ReadObjectFromString(info.Value.ToString());
  369.  
  370.                 Type type = Type.GetType(info.TypeName,false);
  371.  
  372.                 if(type == null)
  373.                     return info.Value;
  374.                 if(type.IsGenericType)
  375.                     return info.Value;
  376.                 return Convert.ChangeType(info.Value,type);
  377.             }
  378.         }
  379.         [Serializable]
  380.         [XmlRoot("ControlInfo")]
  381.         public class ControlInfo {
  382.             [XmlAttribute]
  383.             public string Key { get; set; }
  384.             [XmlAttribute]
  385.             public string Name { get; set; }
  386.             [XmlAttribute]
  387.             public string PropertyName { get; set; }
  388.             public object PropertyValue { get; set; }
  389.             public ControlInfo() { }
  390.             public ControlInfo(Control control,string propName) {
  391.                 Name = control.Name;
  392.                 PropertyName = propName;
  393.  
  394.                 string keyFormat = "_ControlInfo_|{0}|{1}";
  395.                 Key = string.Format(keyFormat,Name,PropertyName);
  396.             }
  397.         }
  398.         [Serializable]
  399.         public class ControlInfoDictionary:Dictionary<string,WindowState.ControlInfo> {
  400.             public static string ToXml(ControlInfoDictionary dictionary) {
  401.                 var items = dictionary.Values.ToArray();
  402.                 return XmlSerialization.Serialize<WindowState.ControlInfo[]>(items);
  403.             }
  404.             public static ControlInfoDictionary FromXml(string xml) {
  405.                 if(string.IsNullOrEmpty(xml))
  406.                     return new ControlInfoDictionary();
  407.  
  408.                 var items = XmlSerialization.Deserialize<WindowState.ControlInfo[]>(xml);
  409.                 ControlInfoDictionary dictionary = new ControlInfoDictionary();
  410.                 foreach(var item in items) {
  411.                     dictionary.Add(item.Key,item);
  412.                 }
  413.                 return dictionary;
  414.             }
  415.  
  416.             public ControlInfoDictionary() { }
  417.             public ControlInfoDictionary(SerializationInfo info,StreamingContext context)
  418.                 : base(info,context) {
  419.             }
  420.             public object SyncRoot = new object();
  421.             public object GetValue(string key) {
  422.                 return GetValue<object>(key,default(object));
  423.             }
  424.             public object GetValue(string key,object defaultValue) {
  425.                 return GetValue<object>(key,defaultValue);
  426.             }
  427.             public T GetValue<T>(string key) {
  428.                 return GetValue(key,default(T));
  429.             }
  430.             public T GetValue<T>(string key,T defaultValue) {
  431.                 object value = this[key];
  432.                 if(value == null)
  433.                     return defaultValue;
  434.                 return (T)value;
  435.             }
  436.             public new WindowState.ControlInfo this[string key] {
  437.                 get {
  438.                     if(key == null)
  439.                         return null;
  440.                     lock(SyncRoot) {
  441.                         if(this.ContainsKey(key) == false)
  442.                             return null;
  443.                         return base[key];
  444.                     }
  445.                 }
  446.                 set {
  447.                     if(key == null)
  448.                         return;
  449.                     lock(SyncRoot) {
  450.                         if(this.ContainsKey(key) == false)
  451.                             this.Add(key,value);
  452.                         else
  453.                             base[key] = value;
  454.                     }
  455.                 }
  456.             }
  457.             public WindowState.ControlInfo this[string key,WindowState.ControlInfo defaultValue] {
  458.                 get {
  459.                     if(key == null)
  460.                         return defaultValue;
  461.                     lock(SyncRoot) {
  462.                         if(this.ContainsKey(key) == false)
  463.                             return defaultValue;
  464.                         return base[key];
  465.                     }
  466.                 }
  467.             }
  468.         }
  469.         #endregion
  470.  
  471.         public object GetSetting(string key) {
  472.             if(!Settings.ContainsKey(key))
  473.                 return null;
  474.             return this.Settings[key];
  475.         }
  476.         public object GetSetting(string key,object defaultValue) {
  477.             if(!Settings.ContainsKey(key))
  478.                 return defaultValue;
  479.             return Settings[key];
  480.         }
  481.         public T GetSetting<T>(string key) {
  482.             object value = GetSetting(key);
  483.             return (T)Convert.ChangeType(value,typeof(T));
  484.         }
  485.         public T GetSetting<T>(string key,T defaultValue) {
  486.             if(!Settings.ContainsKey(key))
  487.                 return defaultValue;
  488.             return GetSetting<T>(key);
  489.         }
  490.         public object this[string settingkey] {
  491.             get {
  492.                 return GetSetting(settingkey);
  493.             }
  494.             set { Settings[settingkey] = value; }
  495.         }
  496.         public object this[string settingkey,object defaultValue] {
  497.             get {
  498.                 return GetSetting(settingkey,defaultValue);
  499.             }
  500.         }
  501.         #endregion
  502.  
  503.         #region ctr
  504.         #region static
  505.         static WindowState() {
  506.             WindowState.GlobalWindowStateType = GlobalWindowStateType_Default;
  507.             WindowState.GlobalEnabled = GlobalEnabled_Default;
  508.         }
  509.         #endregion
  510.  
  511.         private void InitializeComponent() {
  512.             components = new System.ComponentModel.Container();
  513.             _persistenceType = WindowStateType.Registry;
  514.             _bindedControls = new Dictionary<string,ControlInfo>();
  515.             _controlDictionary = new ControlInfoDictionary();
  516.             _enabled = true;
  517.         }
  518.         public WindowState() {
  519.             InitializeComponent();
  520.         }
  521.         public WindowState(IContainer container)
  522.             : this() {
  523.             container.Add(this);
  524.             InitializeComponent();
  525.         }
  526.         #endregion
  527.  
  528.         #region events
  529.         protected void OnSettingsLoaded(EventArgs args) {
  530.             loadPersistedControls();
  531.             if(SettingsLoaded != null)
  532.                 SettingsLoaded(this,args);
  533.         }
  534.         protected void OnSettingsSaved(EventArgs args) {
  535.             savePersistedControls();
  536.             if(SettingsSaved != null)
  537.                 SettingsSaved(this,args);
  538.         }
  539.         protected void DetachEvents() {
  540.             if(Parent == null || Enabled == false || _eventsDetached == true)
  541.                 return;
  542.             _eventsDetached = true;
  543.             //detaches from parent form events
  544.             Parent.Move -= new System.EventHandler(OnParentMove);
  545.             Parent.ResizeEnd -= new EventHandler(OnParentResizeEnd);
  546.             Parent.MaximizedBoundsChanged -= new System.EventHandler(OnParentMove);
  547.             Parent.MinimumSizeChanged -= new System.EventHandler(OnParentMove);
  548.  
  549.             Parent.Load -= new System.EventHandler(OnLoadRegistry);
  550.             Parent.FormClosed -= new FormClosedEventHandler(OnClosedRegistry);
  551.             Parent.Load -= new System.EventHandler(OnLoadConfigFile);
  552.             Parent.FormClosed -= new FormClosedEventHandler(OnClosedConfigFile);
  553.         }
  554.         #endregion
  555.  
  556.         #region Loading
  557.  
  558.         private void BindEventsToParent() {
  559.             if(this.DesignMode)
  560.                 return;
  561.             if(this.Enabled == false)
  562.                 return;
  563.             if(_parent == null)
  564.                 throw new InvalidOperationException("Parent Property must be set for WindowState");
  565.  
  566.             this.PersistenceType = GlobalWindowStateType;
  567.             if(this.PersistenceType == WindowStateType.Registry) {
  568.                 this.LoadRegistry();
  569.             }
  570.             else if(PersistenceType == WindowStateType.ConfigFile) {
  571.                 this.LoadConfigFile();
  572.             }
  573.             //attaches to parent form events
  574.             Parent.Move += new System.EventHandler(OnParentMove);
  575.             Parent.ResizeEnd += new EventHandler(OnParentResizeEnd);
  576.             Parent.MaximizedBoundsChanged += new System.EventHandler(OnParentMove);
  577.             Parent.MinimumSizeChanged += new System.EventHandler(OnParentMove);
  578.  
  579.             // get initial width and height in case form is never resized
  580.             NormalPosition.Width = Parent.Width;
  581.             NormalPosition.Height = Parent.Height;
  582.             NormalPosition.Top = Parent.Top;
  583.             NormalPosition.Left = Parent.Left;
  584.         }
  585.         #endregion
  586.  
  587.         #region Data Persistance
  588.  
  589.         #region Registry
  590.         /// <summary>
  591.         /// 0 always compress
  592.         /// </summary>
  593.         private const int COMPRESSED_MIN_SIZE = 0;
  594.         private const string KEY_WINDOW_STATE = "WindowState";
  595.         private const string KEY_COMPRESSED_FLAG = "CompressedFlg";
  596.         //CompressionHelper
  597.         private void LoadRegistry() {
  598.             //attaches to parent form events
  599.             Parent.Load += new System.EventHandler(OnLoadRegistry);
  600.             Parent.FormClosed += new FormClosedEventHandler(OnClosedRegistry);
  601.         }
  602.         private void OnLoadRegistry(object sender,System.EventArgs e) {
  603.             IsLoaded = true;
  604.             this.OriginalPosition = new WindowStatePosition();
  605.  
  606.             using(RegistryKey regkey = Registry.CurrentUser.OpenSubKey(this.RegistryPath)) {
  607.                 try {
  608.                     if(regkey == null)
  609.                         return;
  610.  
  611.                     object rawConfig = regkey.GetValue(KEY_WINDOW_STATE,null);
  612.                     if(rawConfig != null) {
  613.                         byte[] bytes = rawConfig as byte[];
  614.                         string xml = null;
  615.                         if(EncryptSettings) {
  616.                             try {
  617.                                 byte[] decrypted = EncryptionHelper.Decrypt(bytes);
  618.                                 xml = Encoding.Unicode.GetString(decrypted);
  619.                             }
  620.                             catch {
  621.                                 xml = Encoding.Unicode.GetString(bytes);
  622.                             }
  623.                         }
  624.                         else {
  625.                             xml = Encoding.Unicode.GetString(bytes);
  626.                         }
  627.                         if(!string.IsNullOrEmpty(xml)) {
  628.                             WindowStateConfig config = WindowStateConfig.Deserialize(xml);
  629.                             LoadWindowStateConfig(config);
  630.                         }
  631.                     }
  632.                 }
  633.                 finally {
  634.                     // fire LoadState event
  635.                     this.OnSettingsLoaded(new EventArgs());
  636.                     if(regkey != null) {
  637.                         regkey.Close();
  638.                     }
  639.                 }
  640.             }
  641.         }
  642.         // save position, size and state
  643.         private void OnClosedRegistry(object sender,FormClosedEventArgs e) {
  644.             this.OnSettingsSaved(new EventArgs());
  645.             this.SetWindowState();
  646.             this.DetachEvents();
  647.  
  648.             WindowStateConfig config = SetWindowStateConfig();
  649.             var t = new Thread((state) => {
  650.                 try {
  651.                     this.SaveToRegistry(state as WindowStateConfig);
  652.                 }
  653.                 catch(Exception error) {
  654.                     System.Diagnostics.Trace.Write(error);
  655.                 }
  656.             });
  657.             t.Name = "WindowState.OnClosedRegistry => SaveToRegistry";
  658.             t.Priority = ThreadPriority.Highest;
  659.             t.Start(config);
  660.         }
  661.         private void SaveToRegistry(WindowStateConfig config) {
  662.             using(RegistryKey regkey = Registry.CurrentUser.CreateSubKey(this.RegistryPath)) {
  663.                 try {
  664.                     string xml = WindowStateConfig.Serialize(config);
  665.  
  666.                     byte[] data = Encoding.Unicode.GetBytes(xml);
  667.                     if(EncryptSettings) {
  668.                         byte[] encrypted = EncryptionHelper.Encrypt(data);
  669.                         regkey.SetValue(KEY_WINDOW_STATE,encrypted,RegistryValueKind.Binary);
  670.                     }
  671.                     else
  672.                         regkey.SetValue(KEY_WINDOW_STATE,data,RegistryValueKind.Binary);
  673.                 }
  674.                 finally {
  675.                     if(regkey != null)
  676.                         regkey.Close();
  677.                 }
  678.             }
  679.         }
  680.         private string CreateRegistryKey() {
  681.             string companyName = Application.CompanyName;
  682.             string productName = Application.ProductName;
  683.             string parentName = null;
  684.             if(this.Parent != null)
  685.                 parentName = Parent.GetType().Name;
  686.             string regkey = @"Software\" + companyName + @"\" + productName + @"\" + parentName + UniqueKey;
  687.             return regkey;
  688.         }
  689.         #endregion
  690.  
  691.         #region ConfigFile
  692.         private void LoadConfigFile() {
  693.             Parent.Load += new System.EventHandler(OnLoadConfigFile);
  694.             Parent.FormClosed += new FormClosedEventHandler(OnClosedConfigFile);
  695.         }
  696.         private void OnLoadConfigFile(object sender,System.EventArgs e) {
  697.             IsLoaded = true;
  698.             try {
  699.                 WindowStateConfig config = null;
  700.                 string settingsFileName = GetConfigFilename();
  701.                 if(File.Exists(settingsFileName) == false) {
  702.                     config = WindowStateConfig.GetDefault(this.Parent);
  703.                     LoadWindowStateConfig(config);
  704.                     return;
  705.                 }
  706.                 string data = null;
  707.  
  708.                 if(EncryptSettings) {
  709.                     try {
  710.                         byte[] bytes = File.ReadAllBytes(settingsFileName);
  711.                         byte[] decrypted = EncryptionHelper.Decrypt(bytes);
  712.                         data = Encoding.Unicode.GetString(decrypted);
  713.                     }
  714.                     catch {
  715.                         data = File.ReadAllText(settingsFileName);
  716.                     }
  717.                 }
  718.                 else {
  719.                     data = File.ReadAllText(settingsFileName);
  720.                 }
  721.                 config = WindowStateConfig.Deserialize(data);
  722.                 if(config != null) {
  723.                     LoadWindowStateConfig(config);
  724.                 }
  725.             }
  726.             catch {
  727.                 var config = WindowStateConfig.GetDefault(this.Parent);
  728.                 LoadWindowStateConfig(config);
  729.             }
  730.             finally {
  731.                 // fire LoadState event
  732.                 this.OnSettingsLoaded(new EventArgs());
  733.             }
  734.         }
  735.         private void SaveToConfigFile(WindowStateConfig config) {
  736.             var data = WindowStateConfig.Serialize(config);
  737.             if(EncryptSettings) {
  738.                 byte[] bytes = Encoding.Unicode.GetBytes(data);
  739.                 byte[] encrypted = EncryptionHelper.Encrypt(bytes);
  740.                 File.WriteAllBytes(config.FileName,encrypted);
  741.             }
  742.             else {
  743.                 File.WriteAllText(
  744.                     config.FileName,data
  745.                 );
  746.             }
  747.         }
  748.         //save file
  749.         private void OnClosedConfigFile(object sender,FormClosedEventArgs e) {
  750.             this.OnSettingsSaved(new EventArgs());
  751.             this.SetWindowState();
  752.             this.DetachEvents();
  753.  
  754.             WindowStateConfig config = SetWindowStateConfig();
  755.  
  756.             var t = new Thread((state) => {
  757.                 try {
  758.                     SaveToConfigFile(state as WindowStateConfig);
  759.                 }
  760.                 catch(Exception error) {
  761.                     System.Diagnostics.Trace.Write(error);
  762.                 }
  763.             });
  764.             t.Name = "WindowState.OnClosedConfigFile => SaveToConfigFile";
  765.             t.Priority = ThreadPriority.Highest;
  766.             t.Start(config);
  767.         }
  768.         private string settingsToXml() {
  769.             var items = Settings.Select(kv => new SettingInfo() {
  770.                 Key = kv.Key,
  771.                 Value = kv.Value
  772.             }).ToArray();
  773.             return XmlSerialization.Serialize<SettingInfo[]>(items);
  774.         }
  775.         private Dictionary<string,object> settingsFromXml(string xml) {
  776.             if(string.IsNullOrEmpty(xml))
  777.                 return new Dictionary<string,object>();
  778.  
  779.             var items = XmlSerialization.Deserialize<SettingInfo[]>(xml)
  780.                 .Where(si => !string.IsNullOrEmpty(si.Key))
  781.                 .ToArray();
  782.  
  783.             var dictionary = new Dictionary<string,object>(items.Length);
  784.             foreach(var item in items) {
  785.                 if(!dictionary.ContainsKey(item.Key))
  786.                     dictionary.Add(item.Key,item.Value);
  787.             }
  788.             return dictionary;
  789.         }
  790.  
  791.         private string GetConfigFilename() {
  792.             string winstateFileName = ".settings";
  793.             string parentName = null;
  794.             string companyName = Application.CompanyName;
  795.             string productName = Application.ProductName;
  796.             string winstatePath = "WindowState";
  797.             if(this.Parent != null)
  798.                 parentName = Parent.GetType().Name;
  799.  
  800.             winstateFileName = parentName + winstateFileName;
  801.  
  802.             if(SaveInAppData) {
  803.                 string appPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
  804.  
  805.                 appPath = Path.Combine(appPath,companyName);
  806.                 if(Directory.Exists(appPath) == false)
  807.                     Directory.CreateDirectory(appPath);
  808.                 appPath = Path.Combine(appPath,productName);
  809.                 if(Directory.Exists(appPath) == false)
  810.                     Directory.CreateDirectory(appPath);
  811.  
  812.                 string filePath = Path.Combine(appPath,winstatePath);
  813.                 if(Directory.Exists(filePath) == false)
  814.                     Directory.CreateDirectory(filePath);
  815.                 string settingsFileName = Path.Combine(filePath,winstateFileName);
  816.                 return settingsFileName;
  817.             }
  818.             else {
  819.  
  820.                 string exePath = Assembly.GetExecutingAssembly().Location;
  821.                 FileInfo exeInfo = new FileInfo(exePath);
  822.                 string appPath = exeInfo.Directory.FullName;
  823.                 string filePath = Path.Combine(appPath,winstatePath);
  824.                 if(Directory.Exists(filePath) == false)
  825.                     Directory.CreateDirectory(filePath);
  826.                 string settingsFileName = Path.Combine(filePath,winstateFileName);
  827.                 return settingsFileName;
  828.             }
  829.  
  830.         }
  831.         #endregion
  832.  
  833.         private void LoadWindowStateConfig(WindowStateConfig config) {
  834.             this.OriginalPosition = config.Position;
  835.             this.ControlDictionary.Clear();
  836.             if(config.ControlData != null) {
  837.                 foreach(var item in config.ControlData) {
  838.                     if(!this.ControlDictionary.ContainsKey(item.Key))
  839.                         this.ControlDictionary.Add(item.Key,item);
  840.                 }
  841.             }
  842.  
  843.             this.Settings.Clear();
  844.             if(config.Settings != null) {
  845.                 foreach(var item in config.Settings) {
  846.                     if(!this.Settings.ContainsKey(item.Key))
  847.                         this.Settings.Add(item.Key,SettingInfo.DeserializeSettingValue(item));
  848.                 }
  849.             }
  850.             this.SetParentWindowPosition(config.Position);
  851.         }
  852.         private WindowStateConfig SetWindowStateConfig() {
  853.             WindowStateConfig config = new WindowStateConfig();
  854.             config.FileName = this.GetConfigFilename();
  855.             config.Position = this.NormalPosition;
  856.             config.ControlData = this.ControlDictionary
  857.                 .Where(kv => {
  858.                     if(kv.Value == null)
  859.                         return false;
  860.                     if(kv.Value.PropertyValue == null)
  861.                         return true;
  862.                     else
  863.                         return kv.Value.PropertyValue.GetType().IsSerializable;
  864.                 })
  865.                 .Select(kv => kv.Value).ToArray();
  866.             config.Settings = Settings.Select(kv => new SettingInfo(kv)).ToArray();
  867.             return config;
  868.         }
  869.         #endregion
  870.  
  871.         #region Parent Events
  872.         private void SetWindowState() {
  873.             // check if we are allowed to save the state as minimized (not normally)
  874.             if(_allowSaveMinimized == false) {
  875.                 if(_lastWindowState == FormWindowState.Minimized) {
  876.                     if(_allowSaveMaximized == false) {
  877.                         _lastWindowState = FormWindowState.Normal;
  878.  
  879.                     }
  880.                 }
  881.             }
  882.             if(_allowSaveMaximized == false) {
  883.                 if(_lastWindowState == FormWindowState.Maximized) {
  884.                     if(_allowSaveMinimized == false) {
  885.                         _lastWindowState = FormWindowState.Normal;
  886.  
  887.                     }
  888.                 }
  889.             }
  890.         }
  891.         private void OnParentResizeEnd(object sender,EventArgs e) {
  892.             if(!this.Enabled)
  893.                 return;
  894.             if(Parent.WindowState == FormWindowState.Normal) {
  895.                 NormalPosition.Width = Parent.Width;
  896.                 NormalPosition.Height = Parent.Height;
  897.                 NormalPosition.Top = Parent.Top;
  898.                 NormalPosition.Left = Parent.Left;
  899.             }
  900.         }
  901.         private void OnParentMove(object sender,System.EventArgs e) {
  902.             if(!this.Enabled)
  903.                 return;
  904.             // save position
  905.             if(Parent.WindowState == FormWindowState.Normal) {
  906.                 NormalPosition.Width = Parent.Width;
  907.                 NormalPosition.Height = Parent.Height;
  908.                 NormalPosition.Top = Parent.Top;
  909.                 NormalPosition.Left = Parent.Left;
  910.             }
  911.             // save state
  912.             _lastWindowState = Parent.WindowState;
  913.         }
  914.         private void SetParentWindowPosition(WindowStatePosition position) {
  915.             int left = position.Left;
  916.             int top = position.Top;
  917.             int width = position.Width;
  918.             int height = position.Height;
  919.             FormWindowState windowState = position.WindowState;
  920.             this.SetParentWindowPosition(left,top,width,height,windowState);
  921.         }
  922.         private void SetParentWindowPosition(int left,int top,int width,int height,FormWindowState windowState) {
  923.             if(Screen.PrimaryScreen.Bounds.Left > left)
  924.                 left = Screen.PrimaryScreen.Bounds.Left;
  925.             if(Screen.PrimaryScreen.Bounds.Top > top)
  926.                 top = Screen.PrimaryScreen.Bounds.Top;
  927.             if(!_ignoreTopLeft)
  928.                 Parent.Location = new Point(left,top);
  929.             if(!_ignoreHeightWidth)
  930.                 Parent.Size = new Size(width,height);
  931.             if(!_ignoreWindowState)
  932.                 Parent.WindowState = windowState;
  933.         }
  934.         private void SetParentWindowPosition(FormWindowState windowState) {
  935.             if(!_ignoreWindowState)
  936.                 Parent.WindowState = windowState;
  937.         }
  938.  
  939.         #endregion
  940.  
  941.         #region Extended Controls
  942.         private Type[] _notSupportedControls = new Type[]
  943.         {
  944.             typeof(Form)
  945.         };
  946.         private Dictionary<Control,ExtendedControlProperties> _extendedControls = new Dictionary<Control,ExtendedControlProperties>();
  947.         private Dictionary<Control,ExtendedControlProperties> ExtendedControls {
  948.             get { return _extendedControls; }
  949.             set { _extendedControls = value; }
  950.         }
  951.         public string GetWindowStateBindingProperty(Control control) {
  952.             if(ExtendedControls.ContainsKey(control)) {
  953.                 ExtendedControlProperties extProperties = ExtendedControls[control];
  954.                 if(extProperties != null) {
  955.                     if(string.IsNullOrEmpty(extProperties.PropertyNames)) {
  956.                         var propInfo = TypeDescriptor.GetDefaultProperty(control);
  957.                         if(propInfo != null)
  958.                             extProperties.PropertyNames = propInfo.Name;
  959.                     }
  960.                     return extProperties.PropertyNames;
  961.                 }
  962.             }
  963.             return null;
  964.         }
  965.         public void SetWindowStateBindingProperty(Control control,string propertyName) {
  966.             ExtendedControlProperties extProperties = null;
  967.             if(ExtendedControls.ContainsKey(control)) {
  968.                 extProperties = ExtendedControls[control];
  969.             }
  970.             else {
  971.                 extProperties = new ExtendedControlProperties();
  972.                 extProperties.BindEnabled = true;
  973.                 ExtendedControls.Add(control,extProperties);
  974.             }
  975.             extProperties.PropertyNames = propertyName;
  976.             if(extProperties.BindEnabled)
  977.                 BindControl(control,extProperties);
  978.         }
  979.         public bool GetWindowStateBinding(Control control) {
  980.             if(ExtendedControls.ContainsKey(control)) {
  981.                 ExtendedControlProperties extProperties = ExtendedControls[control];
  982.                 if(extProperties != null)
  983.                     return extProperties.BindEnabled;
  984.             }
  985.             return false;
  986.         }
  987.         public void SetWindowStateBinding(Control control,bool bindingEnabled) {
  988.             ExtendedControlProperties extProperties = null;
  989.             if(ExtendedControls.ContainsKey(control)) {
  990.                 extProperties = ExtendedControls[control];
  991.             }
  992.             else {
  993.                 extProperties = new ExtendedControlProperties();
  994.                 ExtendedControls.Add(control,extProperties);
  995.             }
  996.             extProperties.BindEnabled = bindingEnabled;
  997.             if(bindingEnabled)
  998.                 BindControl(control);
  999.         }
  1000.         public bool CanExtend(object extendee) {
  1001.             if(!(extendee is Control))
  1002.                 return false;
  1003.             if(_parent == null) {
  1004.                 Control ctrl = extendee as Control;
  1005.                 this.Parent = ctrl.FindForm();
  1006.             }
  1007.             return true;
  1008.         }
  1009.         private bool IsControlSupported(Control cnt) {
  1010.             if(cnt is Form)
  1011.                 return false;
  1012.             return true;
  1013.         }
  1014.         public class ExtendedControlProperties {
  1015.             public bool BindEnabled { get; set; }
  1016.             public string PropertyNames { get; set; }
  1017.         }
  1018.         #endregion
  1019.  
  1020.         protected override void Dispose(bool disposing) {
  1021.             if(disposing && (components != null)) {
  1022.                 DetachEvents();
  1023.                 components.Dispose();
  1024.             }
  1025.             base.Dispose(disposing);
  1026.         }
  1027.     }
  1028.  
  1029.     #region Supporting Classes
  1030.  
  1031.     public class WindowStateConfig {
  1032.         public static WindowStateConfig GetDefault(Form parent) {
  1033.             WindowStateConfig config = new WindowStateConfig();
  1034.             config.Position = new WindowStatePosition();
  1035.             config.Position.Left = parent.Left;
  1036.             config.Position.Top = parent.Top;
  1037.             config.Position.Width = parent.Width;
  1038.             config.Position.Height = parent.Height;
  1039.             //if(!parent.MinimumSize.IsEmpty) {
  1040.             //    if(parent.MinimumSize.Width > 0)
  1041.             //        config.Position.Width = parent.MinimumSize.Width;
  1042.             //    if(parent.MinimumSize.Height > 0)
  1043.             //        config.Position.Height = parent.MinimumSize.Height;
  1044.             //}
  1045.             config.Position.WindowState = FormWindowState.Normal;
  1046.             return config;
  1047.         }
  1048.         //[XmlIgnore]
  1049.         public string FileName { get; set; }
  1050.  
  1051.         public static string Serialize(WindowStateConfig xmlObject) {
  1052.             return XmlSerialization.Serialize<WindowStateConfig>(xmlObject);
  1053.         }
  1054.         public static WindowStateConfig Deserialize(string xml) {
  1055.             return XmlSerialization.Deserialize<WindowStateConfig>(xml);
  1056.         }
  1057.         public WindowStatePosition Position { get; set; }
  1058.         public WindowState.SettingInfo[] Settings { get; set; }
  1059.         public WindowState.ControlInfo[] ControlData { get; set; }
  1060.     }
  1061.     public class WindowStatePosition {
  1062.         [XmlAttribute]
  1063.         public int Left { get; set; }
  1064.         [XmlAttribute]
  1065.         public int Top { get; set; }
  1066.         [XmlAttribute]
  1067.         public int Width { get; set; }
  1068.         [XmlAttribute]
  1069.         public int Height { get; set; }
  1070.         [XmlAttribute]
  1071.         public FormWindowState WindowState { get; set; }
  1072.  
  1073.         public void CopyTo(WindowStatePosition copied) {
  1074.             copied.Left = this.Left;
  1075.             copied.Top = this.Top;
  1076.             copied.Width = this.Width;
  1077.             copied.Height = this.Height;
  1078.             copied.WindowState = this.WindowState;
  1079.         }
  1080.         public WindowStatePosition Copy() {
  1081.             WindowStatePosition copied = new WindowStatePosition();
  1082.             copied.Left = this.Left;
  1083.             copied.Top = this.Top;
  1084.             copied.Width = this.Width;
  1085.             copied.Height = this.Height;
  1086.             copied.WindowState = this.WindowState;
  1087.             return copied;
  1088.         }
  1089.     }
  1090.     public enum WindowStateType {
  1091.         Registry,
  1092.         ConfigFile
  1093.     }
  1094.     public class StatePersistance {
  1095.         /// <summary>
  1096.         /// Deserializes an object from a Base64String string
  1097.         /// </summary>
  1098.         /// <param name="s">Base64String string</param>
  1099.         /// <returns>Returns the object that was serialize using the SaveObjectToString() method</returns>
  1100.         public static object ReadObjectFromString(string s) {
  1101.             using(MemoryStream memory = new MemoryStream(Convert.FromBase64String(s))) {
  1102.                 return ReadObjectFromStream(memory);
  1103.             }
  1104.         }
  1105.         /// <summary>
  1106.         /// Deserializes an object from a stream
  1107.         /// </summary>
  1108.         /// <param name="s">stream that the object was serialized into</param>
  1109.         /// <returns>Returns the object that was serialize using the SaveObjectToStream() method</returns>
  1110.         public static object ReadObjectFromStream(Stream s) {
  1111.             s.Position = 0;
  1112.             return new BinaryFormatter().Deserialize(s);
  1113.         }
  1114.  
  1115.         /// <summary>
  1116.         /// Serializes an object into a memory stream
  1117.         /// </summary>
  1118.         /// <param name="obj"></param>
  1119.         /// <returns></returns>
  1120.         public static MemoryStream SaveObjectToStream(object obj) {
  1121.             MemoryStream memory = new MemoryStream();
  1122.             new BinaryFormatter().Serialize(memory,obj);
  1123.             return memory;
  1124.         }
  1125.  
  1126.         public static byte[] SaveObjectToBytes(object obj) {
  1127.             using(MemoryStream memory = new MemoryStream()) {
  1128.                 new BinaryFormatter().Serialize(memory,obj);
  1129.                 memory.Position = 0;
  1130.                 return memory.ToArray();
  1131.             }
  1132.         }
  1133.         /// <summary>
  1134.         /// Serializes an object into a Base64 string
  1135.         /// </summary>
  1136.         /// <param name="obj"></param>
  1137.         /// <returns></returns>
  1138.         public static string SaveObjectToString(object obj) {
  1139.             using(MemoryStream memory = SaveObjectToStream(obj)) {
  1140.                 memory.Position = 0;
  1141.                 return Convert.ToBase64String(memory.ToArray());
  1142.             }
  1143.         }
  1144.         /// <summary>
  1145.         /// Deserilizes an object from a file
  1146.         /// </summary>
  1147.         /// <param name="FileName"></param>
  1148.         /// <returns></returns>
  1149.         public static object ReadObjectFromFile(string FileName) {
  1150.             using(Stream stm = File.Open(FileName,FileMode.Open,FileAccess.Read,FileShare.Read)) {
  1151.                 BinaryFormatter bformatter = new BinaryFormatter();
  1152.                 stm.Position = 0;
  1153.                 if(stm.Length == 0)
  1154.                     return null;
  1155.                 return bformatter.Deserialize(stm);
  1156.             }
  1157.         }
  1158.         /// <summary>
  1159.         /// Serializes an object into a file
  1160.         /// </summary>
  1161.         /// <param name="Object"></param>
  1162.         /// <param name="FileName"></param>
  1163.         /// <returns></returns>
  1164.         public static bool SaveObjectToFile(object data,string FileName) {
  1165.             if(File.Exists(FileName))
  1166.                 File.Delete(FileName);
  1167.             using(var stm = File.Open(FileName,FileMode.CreateNew,FileAccess.Write,FileShare.Write)) {
  1168.                 BinaryFormatter bformatter = new BinaryFormatter();
  1169.                 bformatter.Serialize(stm,data);
  1170.                 return true;
  1171.             }
  1172.         }
  1173.         /// <summary>
  1174.         /// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
  1175.         /// </summary>
  1176.         /// <param name="characters">Unicode Byte Array to be converted to String</param>
  1177.         /// <returns>String converted from Unicode Byte Array</returns>
  1178.         private static String UTF8ByteArrayToString(byte[] characters) {
  1179.             UTF8Encoding encoding = new UTF8Encoding();
  1180.             string constructedString = encoding.GetString(characters);
  1181.             return (constructedString);
  1182.         }
  1183.         /// <summary>
  1184.         /// Converts the String to UTF8 Byte array and is used in De serialization
  1185.         /// </summary>
  1186.         /// <param name="pXmlString"></param>
  1187.         /// <returns></returns>
  1188.         private static Byte[] StringToUTF8ByteArray(string xml) {
  1189.             UTF8Encoding encoding = new UTF8Encoding();
  1190.             byte[] byteArray = encoding.GetBytes(xml);
  1191.             return byteArray;
  1192.         }
  1193.         public static String SerializeXmlObject(object pObject,Type objectType) {
  1194.             using(MemoryStream memoryStream = new MemoryStream()) {
  1195.                 XmlSerializer xs = new XmlSerializer(objectType);
  1196.                 XmlSerializerNamespaces xmlNamespace = new XmlSerializerNamespaces();
  1197.                 xmlNamespace.Add(string.Empty,string.Empty);
  1198.                 xs.Serialize(memoryStream,pObject,xmlNamespace);
  1199.                 return UTF8ByteArrayToString(memoryStream.ToArray());
  1200.             }
  1201.         }
  1202.         /// <summary>
  1203.         /// Method to reconstruct an Object from XML string
  1204.         /// </summary>
  1205.         /// <param name="pXmlizedString"></param>
  1206.         /// <returns></returns>
  1207.         public static object DeserializeXmlObject(string xml,Type objectType) {
  1208.             XmlSerializer xs = new XmlSerializer(objectType);
  1209.             using(MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xml))) {
  1210.                 XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream,Encoding.UTF8);
  1211.                 return xs.Deserialize(memoryStream);
  1212.             }
  1213.         }
  1214.     }
  1215.     public static class CompressionUtility {
  1216.         public static string Compress(string data) {
  1217.             //byte[] before = ASCIIEncoding.Unicode.GetBytes(data);
  1218.             //byte[] compressed = Compress(ASCIIEncoding.Unicode.GetBytes(data));
  1219.             return Convert.ToBase64String(Compress(ASCIIEncoding.Unicode.GetBytes(data)));
  1220.         }
  1221.         public static string Decompress(string data) {
  1222.             //byte[] before = Convert.FromBase64String(data);
  1223.             //byte[] deCompressed = Decompress(Convert.FromBase64String(data));
  1224.             return ASCIIEncoding.Unicode.GetString(Decompress(Convert.FromBase64String(data)));
  1225.         }
  1226.         public static MemoryStream Compress(MemoryStream data) {
  1227.             MemoryStream output = new MemoryStream();
  1228.             using(GZipStream gzip = new GZipStream(output,CompressionMode.Compress,true)) {
  1229.                 gzip.Write(data.ToArray(),0,(int)data.Length);
  1230.                 gzip.Close();
  1231.                 return output;
  1232.             }
  1233.         }
  1234.         public static MemoryStream Decompress(MemoryStream data) {
  1235.             using(MemoryStream input = new MemoryStream()) {
  1236.                 input.Write(data.ToArray(),0,(int)data.Length);
  1237.                 input.Position = 0;
  1238.                 using(GZipStream gzip = new GZipStream(input,CompressionMode.Decompress,true)) {
  1239.                     MemoryStream output = new MemoryStream();
  1240.                     byte[] buff = new byte[64];
  1241.                     int read = -1;
  1242.                     read = gzip.Read(buff,0,buff.Length);
  1243.                     while(read > 0) {
  1244.                         output.Write(buff,0,read);
  1245.                         read = gzip.Read(buff,0,buff.Length);
  1246.                     }
  1247.                     gzip.Close();
  1248.                     return output;
  1249.                 }
  1250.             }
  1251.         }
  1252.         public static byte[] Compress(byte[] data) {
  1253.             using(MemoryStream output = new MemoryStream()) {
  1254.                 using(GZipStream gzip = new GZipStream(output,CompressionMode.Compress,true)) {
  1255.                     gzip.Write(data,0,data.Length);
  1256.                     gzip.Close();
  1257.                     return output.ToArray();
  1258.                 }
  1259.             }
  1260.         }
  1261.         public static byte[] Decompress(byte[] data) {
  1262.             using(MemoryStream input = new MemoryStream()) {
  1263.                 input.Write(data,0,data.Length);
  1264.                 input.Position = 0;
  1265.                 using(GZipStream gzip = new GZipStream(input,CompressionMode.Decompress,true)) {
  1266.                     using(MemoryStream output = new MemoryStream()) {
  1267.                         byte[] buff = new byte[64];
  1268.                         int read = -1;
  1269.                         read = gzip.Read(buff,0,buff.Length);
  1270.                         while(read > 0) {
  1271.                             output.Write(buff,0,read);
  1272.                             read = gzip.Read(buff,0,buff.Length);
  1273.                         }
  1274.                         gzip.Close();
  1275.                         return output.ToArray();
  1276.                     }
  1277.                 }
  1278.             }
  1279.         }
  1280.     }
  1281.     public class EncryptionHelper {
  1282.         private static string _Salt = "fA2qiF3P`u[Oagbf4'x>0C%wBVy{8)1f";
  1283.         private static string _Password = @",!=K};zr*4j,CeHn5!q 0DbO^WGxz1dX";
  1284.         private static string Password {
  1285.             get { return _Password; }
  1286.             set { _Password = value; }
  1287.         }
  1288.         #region Encrypt/Decrypt
  1289.         public static string Encrypt(string dataToEncrypt) {
  1290.             return Encrypt(dataToEncrypt,Password,_Salt);
  1291.         }
  1292.         public static string Encrypt(string dataToEncrypt,string pwd) {
  1293.             return Encrypt(dataToEncrypt,pwd,_Salt);
  1294.         }
  1295.         public static string Encrypt(string dataToEncrypt,string pwd,string salt) {
  1296.             byte[] encrypted;
  1297.             return Encrypt(null,dataToEncrypt,pwd,salt,out encrypted);
  1298.         }
  1299.         public static byte[] Encrypt(byte[] bytes) {
  1300.             byte[] encrypted;
  1301.             Encrypt(bytes,null,Password,_Salt,out encrypted);
  1302.             return encrypted;
  1303.         }
  1304.         private static string Encrypt(byte[] bytes,string dataToEncrypt,string pwd,string salt,out byte[] encrypted) {
  1305.             if(pwd.IsNull())
  1306.                 pwd = Password;
  1307.             if(salt.IsNull())
  1308.                 salt = _Salt;
  1309.             string password = pwd;
  1310.             string plainText = dataToEncrypt;
  1311.             string encryptedData = null;
  1312.             byte[] plainBytes = bytes;
  1313.             if(plainBytes == null)
  1314.                 plainBytes = Encoding.ASCII.GetBytes(plainText);
  1315.  
  1316.             //Rfc2898DeriveBytes: Used to Generate Strong Keys
  1317.             Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password,
  1318.                 Encoding.ASCII.GetBytes(salt));//Non-English Alfhabets Will not Work on ASCII Encoding
  1319.  
  1320.             SymmetricAlgorithm Alg = new DESCryptoServiceProvider();
  1321.  
  1322.             Alg.Key = rfc.GetBytes(Alg.KeySize / 8);
  1323.             Alg.IV = rfc.GetBytes(Alg.BlockSize / 8);
  1324.  
  1325.             using(MemoryStream strCiphered = new MemoryStream()) {//To Store Encrypted Data
  1326.  
  1327.                 CryptoStream strCrypto = new CryptoStream(strCiphered,
  1328.                     Alg.CreateEncryptor(),CryptoStreamMode.Write);
  1329.  
  1330.                 strCrypto.Write(plainBytes,0,plainBytes.Length);
  1331.                 strCrypto.Close();
  1332.  
  1333.                 if(bytes != null) {
  1334.                     encrypted = strCiphered.ToArray();
  1335.                     encryptedData = null;
  1336.                 }
  1337.                 else {
  1338.                     encrypted = null;
  1339.                     encryptedData = Convert.ToBase64String(strCiphered.ToArray());
  1340.                 }
  1341.                 strCiphered.Close();
  1342.             }
  1343.             return encryptedData;
  1344.         }
  1345.         public static string Decrypt(string dataToDecrypt) {
  1346.             return Decrypt(dataToDecrypt,Password,_Salt);
  1347.         }
  1348.         public static string Decrypt(string dataToDecrypt,string pwd) {
  1349.             return Decrypt(dataToDecrypt,pwd,_Salt);
  1350.         }
  1351.         public static string Decrypt(string dataToDecrypt,string pwd,string salt) {
  1352.             byte[] decrypted = null;
  1353.             return Decrypt(null,dataToDecrypt,pwd,salt,out decrypted);
  1354.         }
  1355.         public static byte[] Decrypt(byte[] bytes) {
  1356.             byte[] decrypted = null;
  1357.             Decrypt(bytes,null,Password,_Salt,out decrypted);
  1358.             return decrypted;
  1359.         }
  1360.         public static string Decrypt(byte[] bytes,string dataToDecrypt,string pwd,string salt,out byte[] decrypted) {
  1361.             if(pwd.IsNull())
  1362.                 pwd = Password;
  1363.             if(salt.IsNull())
  1364.                 salt = _Salt;
  1365.             string password = pwd;
  1366.             string cipheredText = dataToDecrypt;
  1367.             string decryptedData = null;
  1368.             byte[] cipheredBytes = bytes;
  1369.             if(cipheredBytes == null)
  1370.                 cipheredBytes = Convert.FromBase64String(cipheredText);
  1371.  
  1372.             //Rfc2898DeriveBytes: Used to Generate Strong Keys
  1373.             Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password,
  1374.                 Encoding.ASCII.GetBytes(salt));//Non-English Alfhabets Will not Work on ASCII Encoding
  1375.  
  1376.             SymmetricAlgorithm Alg = new DESCryptoServiceProvider();
  1377.  
  1378.             Alg.Key = rfc.GetBytes(Alg.KeySize / 8);
  1379.             Alg.IV = rfc.GetBytes(Alg.BlockSize / 8);
  1380.  
  1381.             using(MemoryStream strDeciphered = new MemoryStream()) {//To Store Decrypted Data
  1382.  
  1383.                 CryptoStream strCrypto = new CryptoStream(strDeciphered,
  1384.                     Alg.CreateDecryptor(),CryptoStreamMode.Write);
  1385.  
  1386.                 strCrypto.Write(cipheredBytes,0,cipheredBytes.Length);
  1387.                 strCrypto.Close();
  1388.                 if(bytes != null) {
  1389.                     decrypted = strDeciphered.ToArray();
  1390.                     decryptedData = null;
  1391.                 }
  1392.                 else {
  1393.                     decrypted = null;
  1394.                     decryptedData = Encoding.ASCII.GetString(strDeciphered.ToArray());
  1395.                 }
  1396.                 strDeciphered.Close();
  1397.             }
  1398.             return decryptedData;
  1399.         }
  1400.         #endregion
  1401.     }
  1402.     #region Extentions
  1403.     //public static class Extensions {
  1404.  
  1405.     //    public static bool IsNull(this string s) {
  1406.     //        return IsNullOrEmptyTrim(s);
  1407.     //    }
  1408.     //    public static bool IsNullOrEmptyTrim(this string s) {
  1409.     //        if(s == null)
  1410.     //            return true;
  1411.     //        if(string.IsNullOrEmpty(s))
  1412.     //            return true;
  1413.     //        if(s.Equals(Environment.NewLine))
  1414.     //            return false;
  1415.     //        if(string.IsNullOrEmpty(s.Trim()))
  1416.     //            return true;
  1417.     //        return false;
  1418.     //    }
  1419.  
  1420.     //    public static string ToSentenceCase(this string s) {
  1421.     //        if(s == null)
  1422.     //            return s;
  1423.     //        if(s.Trim().Length == 0)
  1424.     //            return s;
  1425.  
  1426.     //        var sb = new StringBuilder(s.Length);
  1427.     //        var parts = s.Split(" ".ToCharArray());
  1428.  
  1429.     //        for(int i = 0;i < parts.Length;i++) {
  1430.     //            char[] word = parts[i].ToCharArray();
  1431.     //            if(word.Length == 1) {
  1432.     //                if(char.IsWhiteSpace(word[0])) {
  1433.     //                    sb.Append(word[0]);
  1434.     //                    continue;
  1435.     //                }
  1436.     //            }
  1437.     //            for(int j = 0;j < word.Length;j++) {
  1438.     //                if(j == 0)
  1439.     //                    word[j] = char.ToUpperInvariant(word[j]);
  1440.     //                else
  1441.     //                    word[j] = char.ToLowerInvariant(word[j]);
  1442.     //            }
  1443.     //            sb.Append(new string(word));
  1444.     //            sb.Append(" ");
  1445.     //        }
  1446.     //        return sb.ToString().TrimEnd();
  1447.     //    }
  1448.     //    public static string ToToogleCase(this string s) {
  1449.     //        if(s == null)
  1450.     //            return s;
  1451.     //        if(s.Trim().Length == 0)
  1452.     //            return s;
  1453.  
  1454.     //        var sb = new StringBuilder(s.Length);
  1455.     //        var parts = s.Split(" ".ToCharArray());
  1456.     //        for(int i = 0;i < parts.Length;i++) {
  1457.     //            char[] word = parts[i].ToCharArray();
  1458.     //            if(word.Length == 1) {
  1459.     //                if(char.IsWhiteSpace(word[0])) {
  1460.     //                    sb.Append(word[0]);
  1461.     //                    continue;
  1462.     //                }
  1463.     //            }
  1464.     //            for(int j = 0;j < word.Length;j++) {
  1465.     //                if(char.IsUpper(word[j]))
  1466.     //                    word[j] = char.ToLowerInvariant(word[j]);
  1467.     //                else if(char.IsLower(word[j]))
  1468.     //                    word[j] = char.ToUpperInvariant(word[j]);
  1469.     //            }
  1470.     //            sb.Append(new string(word));
  1471.     //            sb.Append(" ");
  1472.     //        }
  1473.     //        return sb.ToString().TrimEnd();
  1474.     //    }
  1475.     //}
  1476.     #endregion
  1477.  
  1478.  
  1479.     #endregion
  1480. }
Advertisement
Add Comment
Please, Sign In to add comment