Thursday, January 24, 2013

Marianz Scratch Pad (Scratchpad Program in Windows Form Application Using DevEx Controls)





using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Diagnostics;
using DevExpress.XtraEditors;
using DevExpress.Skins;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Ribbon.Gallery;
using DevExpress.Utils.Drawing;
using DevExpress.Utils;
using DevExpress.Tutorials.Controls;
using DevExpress.XtraEditors.Controls;
using DevExpress.LookAndFeel;
namespace MarianzScratchPad 
{
    public partial class frmMain :RibbonForm 
    {
        public frmMain() 
        {
           .
           .
           .
        }
        int documentIndex = 0;
        ColorPopup cp;
        frmFind dlgFind = null;
        frmReplace dlgReplace = null;
        GalleryItem fCurrentFontItem, fCurrentColorItem;
        string DocumentName { get { return string.Format("New Document {0}", documentIndex); } }
        void CreateNewDocument() {
            CreateNewDocument(null);
        }
        void InitEditors() {
            try
            {
                riicStyle.Items.Add(new ImageComboBoxItem("Office 2007", RibbonControlStyle.Office2007, -1));
                riicStyle.Items.Add(new ImageComboBoxItem("Office 2010", RibbonControlStyle.Office2010, -1));
                biStyle.EditValue = ribbonControl1.RibbonStyle;
            }
            catch { }
        }
        public void ShowHideFormatCategory() {
            RibbonPageCategory selectionCategory = Ribbon.PageCategories[0] as RibbonPageCategory;
            if(selectionCategory == null) return;
            if(CurrentRichTextBox == null)
                selectionCategory.Visible = false;
            else
                selectionCategory.Visible = CurrentRichTextBox.SelectionLength != 0;
            if(selectionCategory.Visible) Ribbon.SelectedPage = selectionCategory.Pages[0];
        }
        void CreateNewDocument(string fileName) {
            documentIndex++;
            frmPad pad = new frmPad();
            if(fileName != null)
                pad.LoadDocument(fileName);
            else
                pad.DocName = DocumentName;
            pad.MdiParent = this;
            pad.Closed += new EventHandler(Pad_Closed);
            pad.ShowPopupMenu += new EventHandler(Pad_ShowPopupMenu);
            pad.Show();
            InitNewDocument(pad.RTBMain);
        }
        void Pad_Closed(object sender, EventArgs e) {
            CloseFind();
        }
        void Pad_ShowPopupMenu(object sender, EventArgs e) {
            pmMain.ShowPopup(Control.MousePosition);
        }
        void CloseFind() {
            if(dlgFind != null && dlgFind.RichText != CurrentRichTextBox) {
                dlgFind.Close();
                dlgFind = null;
            }
            if(dlgReplace != null && dlgReplace.RichText != CurrentRichTextBox) {
                dlgReplace.Close();
                dlgReplace = null;
            }
        }
        private void CreateColorPopup(PopupControlContainer container) {
            cp = new ColorPopup(container, iFontColor, this);
        }
        #region Init
        private void frmMain_Activated(object sender, System.EventArgs e) {
            InitPaste();
        }
        public void UpdateText() {
            ribbonControl1.ApplicationCaption = "Marianz Scratch Pad";
            ribbonControl1.ApplicationDocumentCaption = CurrentDocName + (CurrentModified ? "*" : "");
            siDocName.Caption = string.Format("  {0}", CurrentDocName);
        }
        void ChangeActiveForm() {
            UpdateText();
            InitCurrentDocument(CurrentRichTextBox);
            rtPad_SelectionChanged(CurrentRichTextBox, EventArgs.Empty);
            CloseFind();
        }
        private void frmMain_MdiChildActivate(object sender, System.EventArgs e) {
            ChangeActiveForm();
        }
        void rtPad_SelectionChanged(object sender, System.EventArgs e) {
            ShowHideFormatCategory();
            RichTextBox rtPad = sender as RichTextBox;
            InitFormat();
            int line = 0, col = 0;
            if(rtPad != null) {
                InitEdit(rtPad.SelectionLength > 0);
                line = rtPad.GetLineFromCharIndex(rtPad.SelectionStart) + 1;
                col = rtPad.SelectionStart + 1;
            }
            else {
                InitEdit(false);
            }
            siPosition.Caption = string.Format("   Line: {0}  Position: {1}   ", line, col);
            CurrentFontChanged();
        }
        void rtPad_TextChanged(object sender, System.EventArgs e) {
            if(CurrentForm == null) return;
            CurrentForm.Modified = true;
            InitCurrentDocument(CurrentRichTextBox);
        }
        protected void InitFormat() {
            iBold.Enabled = SelectFont != null;
            iItalic.Enabled = SelectFont != null;
            iUnderline.Enabled = SelectFont != null;
            iFont.Enabled = SelectFont != null;
            iFontColor.Enabled = SelectFont != null;
            if(SelectFont != null) {
                iBold.Down = SelectFont.Bold;
                iItalic.Down = SelectFont.Italic;
                iUnderline.Down = SelectFont.Underline;
            }
            bool enabled = CurrentRichTextBox != null;
            iProtected.Enabled = enabled;
            iBullets.Enabled = enabled;
            iAlignLeft.Enabled = enabled;
            iAlignRight.Enabled = enabled;
            iCenter.Enabled = enabled;
            rgbiFont.Enabled = enabled;
            rgbiFontColor.Enabled = enabled;
            ribbonPageGroup9.ShowCaptionButton = enabled;
            rpgFont.ShowCaptionButton = enabled;
            rpgFontColor.ShowCaptionButton = enabled;
            if(!enabled) ClearFormats();
            if(CurrentRichTextBox != null) {
                iProtected.Down = CurrentRichTextBox.SelectionProtected;
                iBullets.Down = CurrentRichTextBox.SelectionBullet;
                switch(CurrentRichTextBox.SelectionAlignment) {
                    case HorizontalAlignment.Left:
                        iAlignLeft.Down = true;
                        break;
                    case HorizontalAlignment.Center:
                        iCenter.Down = true;
                        break;
                    case HorizontalAlignment.Right:
                        iAlignRight.Down = true;
                        break;
                }
            }
        }
        void ClearFormats() {
            iBold.Down = false;
            iItalic.Down = false;
            iUnderline.Down = false;
            iProtected.Down = false;
            iBullets.Down = false;
            iAlignLeft.Down = false;
            iAlignRight.Down = false;
            iCenter.Down = false;
        }
        protected void InitPaste() {
            bool enabledPase = CurrentRichTextBox != null && CurrentRichTextBox.CanPaste(DataFormats.GetFormat(0));
            iPaste.Enabled = enabledPase;
            sbiPaste.Enabled = enabledPase;
        }
        void InitUndo() {
            iUndo.Enabled = CurrentRichTextBox != null ? CurrentRichTextBox.CanUndo : false;
            iLargeUndo.Enabled = iUndo.Enabled;
        }
        protected void InitEdit(bool enabled) {
            iCut.Enabled = enabled;
            iCopy.Enabled = enabled;
            iClear.Enabled = enabled;
            iSelectAll.Enabled = CurrentRichTextBox != null ? CurrentRichTextBox.CanSelect : false;
            InitUndo();
        }
        void InitNewDocument(RichTextBox rtbControl) {
            rtbControl.SelectionChanged += new System.EventHandler(this.rtPad_SelectionChanged);
            rtbControl.TextChanged += new System.EventHandler(this.rtPad_TextChanged);
        }
        void InitCurrentDocument(RichTextBox rtbControl) {
            bool enabled = rtbControl != null;
            iSaveAs.Enabled = enabled;
            iClose.Enabled = enabled;
            iPrint.Enabled = enabled;
            sbiSave.Enabled = enabled;
            sbiFind.Enabled = enabled;
            iFind.Enabled = enabled;
            iReplace.Enabled = enabled;
            iSave.Enabled = CurrentModified;
            SetModifiedCaption();
            InitPaste();
            InitFormat();
        }
        void SetModifiedCaption() {
            if(CurrentForm == null) {
                siModified.Caption = "";
                return;
            }
            siModified.Caption = CurrentModified ? "   Modified   " : "";
        }
        #endregion
        #region Properties
        frmPad CurrentForm {
            get {
                if(this.ActiveMdiChild == null) return null;
                if(xtraTabbedMdiManager1.ActiveFloatForm != null)
                    return xtraTabbedMdiManager1.ActiveFloatForm as frmPad;
                return this.ActiveMdiChild as frmPad;
            }
        }
        public RichTextBox CurrentRichTextBox {
            get {
                if(CurrentForm == null) return null;
                return CurrentForm.RTBMain;
            }
        }
        string CurrentDocName {
            get {
                if(CurrentForm == null) return "";
                return CurrentForm.DocName;
            }
        }
        bool CurrentModified {
            get {
                if(CurrentForm == null) return false;
                return CurrentForm.Modified;
            }
        }
        #endregion
        #region File
        void idNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            CreateNewDocument();
        }
        void iClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            if(CurrentForm != null) CurrentForm.Close();
        }
        void OpenFile() {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Rich Text Files (*.rtf)|*.rtf";
            dlg.Title = "Open";
            if(dlg.ShowDialog() == DialogResult.OK) {
                OpenFile(dlg.FileName);
            }
        }
        void OpenFile(string name) {
            CreateNewDocument(name);
            AddToMostRecentFiles(name, arMRUList);
        }
        void iOpen_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            OpenFile();
        }
        void iSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            Save();
        }
        void iSaveAs_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            SaveAs();
        }
        void Save() {
            if(CurrentForm == null) return;
            if(CurrentForm.NewDocument) {
                SaveAs();
            }
            else {
                CurrentRichTextBox.SaveFile(CurrentDocName, RichTextBoxStreamType.RichText);
                CurrentForm.Modified = false;
            }
            SetModifiedCaption();
        }
        void SaveAs() {
            if(CurrentForm != null) {
                string s = CurrentForm.SaveAs();
                if(s != string.Empty)
                    AddToMostRecentFiles(s, arMRUList);
                UpdateText();
            }
        }
        private void iExit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            Close();
        }
        private void frmMain_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
        }
        private void ribbonPageGroup1_CaptionButtonClick(object sender, DevExpress.XtraBars.Ribbon.RibbonPageGroupEventArgs e) {
            OpenFile();
        }
        private void ribbonPageGroup9_CaptionButtonClick(object sender, DevExpress.XtraBars.Ribbon.RibbonPageGroupEventArgs e) {
            SaveAs();
        }
        #endregion
        #region Format
        private FontStyle rtPadFontStyle() {
            FontStyle fs = new FontStyle();
            if(iBold.Down) fs |= FontStyle.Bold;
            if(iItalic.Down) fs |= FontStyle.Italic;
            if(iUnderline.Down) fs |= FontStyle.Underline;
            return fs;
        }
        private void iBullets_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            if(CurrentRichTextBox == null) return;
            CurrentRichTextBox.SelectionBullet = iBullets.Down;
            InitUndo();
        }
        private void iFontStyle_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            if(CurrentRichTextBox == null) return;
            CurrentRichTextBox.SelectionFont = new Font(SelectFont, rtPadFontStyle());
        }
        private void iProtected_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            if(CurrentRichTextBox == null) return;
            CurrentRichTextBox.SelectionProtected = iProtected.Down;
        }
        private void iAlign_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            if(CurrentRichTextBox == null) return;
            if(iAlignLeft.Down)
                CurrentRichTextBox.SelectionAlignment = HorizontalAlignment.Left;
            if(iCenter.Down)
                CurrentRichTextBox.SelectionAlignment = HorizontalAlignment.Center;
            if(iAlignRight.Down)
                CurrentRichTextBox.SelectionAlignment = HorizontalAlignment.Right;
            InitUndo();
        }
        protected Font SelectFont {
            get {
                if(CurrentRichTextBox != null)
                    return CurrentRichTextBox.SelectionFont;
                return null;
            }
        }
        void ShowFontDialog() {
            if(CurrentRichTextBox == null) return;
            Font dialogFont = null;
            if(SelectFont != null)
                dialogFont = (Font)SelectFont.Clone();
            else dialogFont = CurrentRichTextBox.Font;
            XtraFontDialog dlg = new XtraFontDialog(dialogFont);
            if(dlg.ShowDialog() == DialogResult.OK) {
                CurrentRichTextBox.SelectionFont = dlg.ResultFont;
                beiFontSize.EditValue = dlg.ResultFont.Size;
            }
        }
        private void iFont_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            ShowFontDialog();
        }
        private void iFontColor_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            if(CurrentRichTextBox == null) return;
            CurrentRichTextBox.SelectionColor = cp.ResultColor;
        }
        #endregion
        #region Edit
        private void iUndo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            if(CurrentRichTextBox == null) return;
            CurrentRichTextBox.Undo();
            CurrentForm.Modified = CurrentRichTextBox.CanUndo;
            SetModifiedCaption();
            InitUndo();
            InitFormat();
        }
        private void iCut_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            if(CurrentRichTextBox == null) return;
            CurrentRichTextBox.Cut();
            InitPaste();
        }
        private void iCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            if(CurrentRichTextBox == null) return;
            CurrentRichTextBox.Copy();
            InitPaste();
        }
        private void iPaste_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            if(CurrentRichTextBox == null) return;
            CurrentRichTextBox.Paste();
        }
        private void iClear_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            if(CurrentRichTextBox == null) return;
            CurrentRichTextBox.SelectedRtf = "";
        }
        private void iSelectAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            if(CurrentRichTextBox == null) return;
            CurrentRichTextBox.SelectAll();
        }
        private void ribbonPageGroup2_CaptionButtonClick(object sender, DevExpress.XtraBars.Ribbon.RibbonPageGroupEventArgs e) {
            pmMain.ShowPopup(ribbonControl1.Manager, MousePosition);
        }
        #endregion
        #region SkinGallery
        void InitSkinGallery() {
            SimpleButton imageButton = new SimpleButton();
            foreach(SkinContainer cnt in SkinManager.Default.Skins) {
                imageButton.LookAndFeel.SetSkinStyle(cnt.SkinName);
                GalleryItem gItem = new GalleryItem();
                int groupIndex = 0;
                if(cnt.SkinName.Contains("Office")) groupIndex = 1;
                if(DevExpress.DXperience.Demos.LookAndFeelMenu.IsBonusSkin(cnt.SkinName)) groupIndex = 2;
                rgbiSkins.Gallery.Groups[groupIndex].Items.Add(gItem);
                gItem.Caption = cnt.SkinName;
                gItem.Image = GetSkinImage(imageButton, 32, 17, 2);
                gItem.HoverImage = GetSkinImage(imageButton, 70, 36, 5);
                gItem.Caption = cnt.SkinName;
                gItem.Hint = cnt.SkinName;
            }
            rgbiSkins.Gallery.Groups[1].Visible = false;
            rgbiSkins.Gallery.Groups[2].Visible = false;
        }
        Bitmap GetSkinImage(SimpleButton button, int width, int height, int indent) {
            Bitmap image = new Bitmap(width, height);
            using(Graphics g = Graphics.FromImage(image)) {
                StyleObjectInfoArgs info = new StyleObjectInfoArgs(new GraphicsCache(g));
                info.Bounds = new Rectangle(0, 0, width, height);
                button.LookAndFeel.Painter.GroupPanel.DrawObject(info);
                button.LookAndFeel.Painter.Border.DrawObject(info);
                info.Bounds = new Rectangle(indent, indent, width - indent * 2, height - indent * 2);
                button.LookAndFeel.Painter.Button.DrawObject(info);
            }
            return image;
        }
        private void rgbiSkins_Gallery_ItemClick(object sender, DevExpress.XtraBars.Ribbon.GalleryItemClickEventArgs e) {
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(e.Item.Caption);
        }
        private void rgbiSkins_Gallery_InitDropDownGallery(object sender, DevExpress.XtraBars.Ribbon.InplaceGalleryEventArgs e) {
            e.PopupGallery.CreateFrom(rgbiSkins.Gallery);
            e.PopupGallery.AllowFilter = false;
            e.PopupGallery.ShowItemText = true;
            e.PopupGallery.ShowGroupCaption = true;
            e.PopupGallery.AllowHoverImages = false;
            foreach(GalleryItemGroup galleryGroup in e.PopupGallery.Groups)
                foreach(GalleryItem item in galleryGroup.Items)
                    item.Image = item.HoverImage;
            e.PopupGallery.ColumnCount = 2;
            e.PopupGallery.ImageSize = new Size(70, 36);
        }
        #endregion
        #region FontGallery
        Image GetFontImage(int width, int height, string fontName, int fontSize) {
            Rectangle rect = new Rectangle(0, 0, width, height);
            Image fontImage = new Bitmap(width, height);
            try {
                using(Font fontSample = new Font(fontName, fontSize)) {
                    Graphics g = Graphics.FromImage(fontImage);
                    g.FillRectangle(Brushes.White, rect);
                    using(StringFormat fs = new StringFormat()) {
                        fs.Alignment = StringAlignment.Center;
                        fs.LineAlignment = StringAlignment.Center;
                        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                        g.DrawString("Aa", fontSample, Brushes.Black, rect, fs);
                        g.Dispose();
                    }
                }
            }
            catch { }
            return fontImage;
        }
        void InitFont(GalleryItemGroup groupDropDown, GalleryItemGroup galleryGroup) {
            FontFamily[] fonts = FontFamily.Families;
            for(int i = 0; i < fonts.Length; i++) {
                if(!FontFamily.Families[i].IsStyleAvailable(FontStyle.Regular)) continue;
                string fontName = fonts[i].Name;
                GalleryItem item = new GalleryItem();
                item.Caption = fontName;
                item.Image = GetFontImage(32, 28, fontName, 12);
                item.HoverImage = item.Image;
                item.Description = fontName;
                item.Hint = fontName;
                try {
                    item.Tag = new Font(fontName, 9);
                    if(DevExpress.Utils.ControlUtils.IsSymbolFont((Font)item.Tag)) {
                        item.Tag = new Font(DevExpress.Utils.AppearanceObject.DefaultFont.FontFamily, 9);
                        item.Description += " (Symbol Font)";
                    }
                }
                catch {
                    continue;
                }
                groupDropDown.Items.Add(item);
                galleryGroup.Items.Add(item);
            }
        }
        void InitFontGallery() {
            InitFont(gddFont.Gallery.Groups[0], rgbiFont.Gallery.Groups[0]);
            beiFontSize.EditValue = 8;
        }
        void SetFont(string fontName, GalleryItem item) {
            if(CurrentRichTextBox == null) return;
            CurrentRichTextBox.SelectionFont = new Font(fontName, Convert.ToInt32(beiFontSize.EditValue), rtPadFontStyle());
            if(item != null) CurrentFontItem = item;
        }
        private void gddFont_Gallery_ItemClick(object sender, DevExpress.XtraBars.Ribbon.GalleryItemClickEventArgs e) {
            SetFont(e.Item.Caption, e.Item);
        }
        private void rpgFont_CaptionButtonClick(object sender, DevExpress.XtraBars.Ribbon.RibbonPageGroupEventArgs e) {
            ShowFontDialog();
        }
        private void rgbiFont_Gallery_ItemClick(object sender, DevExpress.XtraBars.Ribbon.GalleryItemClickEventArgs e) {
            SetFont(e.Item.Caption, e.Item);
        }
        private void gddFont_Gallery_CustomDrawItemText(object sender, GalleryItemCustomDrawEventArgs e) {
            DevExpress.XtraBars.Ribbon.ViewInfo.GalleryItemViewInfo itemInfo = e.ItemInfo as DevExpress.XtraBars.Ribbon.ViewInfo.GalleryItemViewInfo;
            itemInfo.PaintAppearance.ItemDescription.DrawString(e.Cache, e.Item.Description, itemInfo.DescriptionBounds);
            AppearanceObject app = itemInfo.PaintAppearance.ItemCaption.Clone() as AppearanceObject;
            app.Font = (Font)e.Item.Tag;
            try {
                e.Cache.Graphics.DrawString(e.Item.Caption, app.Font, app.GetForeBrush(e.Cache), itemInfo.CaptionBounds);
            }
            catch { }
            e.Handled = true;
        }
        #endregion
        #region ColorGallery
        void InitColorGallery() {
            gddFontColor.BeginUpdate();
            foreach(Color color in DevExpress.XtraEditors.Popup.ColorListBoxViewInfo.WebColors) {
                if(color == Color.Transparent) continue;
                GalleryItem item = new GalleryItem();
                item.Caption = color.Name;
                item.Tag = color;
                item.Hint = color.Name;
                gddFontColor.Gallery.Groups[0].Items.Add(item);
                rgbiFontColor.Gallery.Groups[0].Items.Add(item);
            }
            foreach(Color color in DevExpress.XtraEditors.Popup.ColorListBoxViewInfo.SystemColors) {
                GalleryItem item = new GalleryItem();
                item.Caption = color.Name;
                item.Tag = color;
                gddFontColor.Gallery.Groups[1].Items.Add(item);
            }
            gddFontColor.EndUpdate();
        }
        private void gddFontColor_Gallery_CustomDrawItemImage(object sender, GalleryItemCustomDrawEventArgs e) {
            Color clr = (Color)e.Item.Tag;
            using(Brush brush = new SolidBrush(clr)) {
                e.Cache.FillRectangle(brush, e.Bounds);
                e.Handled = true;
            }
        }
        void SetResultColor(Color color, GalleryItem item) {
            if(CurrentRichTextBox == null) return;
            cp.ResultColor = color;
            CurrentRichTextBox.SelectionColor = cp.ResultColor;
            if(item != null) CurrentColorItem = item;
        }
        private void gddFontColor_Gallery_ItemClick(object sender, DevExpress.XtraBars.Ribbon.GalleryItemClickEventArgs e) {
            SetResultColor((Color)e.Item.Tag, e.Item);
        }
        private void rpgFontColor_CaptionButtonClick(object sender, DevExpress.XtraBars.Ribbon.RibbonPageGroupEventArgs e) {
            if(CurrentRichTextBox == null) return;
            if(cp == null)
                CreateColorPopup(popupControlContainer1);
            popupControlContainer1.ShowPopup(ribbonControl1.Manager, MousePosition);
        }
        private void rgbiFontColor_Gallery_ItemClick(object sender, DevExpress.XtraBars.Ribbon.GalleryItemClickEventArgs e) {
            SetResultColor((Color)e.Item.Tag, e.Item);
        }
        #endregion
        private void iFind_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            if(CurrentRichTextBox == null) return;
            if(dlgReplace != null) dlgReplace.Close();
            if(dlgFind != null) dlgFind.Close();
            dlgFind = new frmFind(CurrentRichTextBox, Bounds);
            AddOwnedForm(dlgFind);
            dlgFind.Show();
        }
        private void iReplace_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            if(CurrentRichTextBox == null) return;
            if(dlgReplace != null) dlgReplace.Close();
            if(dlgFind != null) dlgFind.Close();
            dlgReplace = new frmReplace(CurrentRichTextBox, Bounds);
            AddOwnedForm(dlgReplace);
            dlgReplace.Show();
        }
        private void iAbout_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            DevExpress.Utils.About.frmAbout dlg = new DevExpress.Utils.About.frmAbout("Ribbon Demo for the XtraBars by Developer Express Inc.");
            dlg.ShowDialog();
        }
        string TextByCaption(string caption) {
            return caption.Replace("&", "");
        }
        private void frmMain_Load(object sender, System.EventArgs e) {
            arMRUList = new MRUArrayList(pcAppMenuFileLabels, imageCollection3.Images[0], imageCollection3.Images[1]);
            arMRUList.LabelClicked += new EventHandler(OnLabelClicked);
            InitMostRecentFiles(arMRUList);
            ribbonControl1.ForceInitialize();
            foreach(DevExpress.Skins.SkinContainer skin in DevExpress.Skins.SkinManager.Default.Skins) {
                BarCheckItem item = ribbonControl1.Items.CreateCheckItem(skin.SkinName, false);
                item.Tag = skin.SkinName;
                item.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(OnPaintStyleClick);
                iPaintStyle.ItemLinks.Add(item);
            }
            CreateNewDocument();
            barEditItem1.Caption = "Copyright© Marianz, 2013";        
        }
        void OnPaintStyleClick(object sender, ItemClickEventArgs e) {
            defaultLookAndFeel1.LookAndFeel.SetSkinStyle(e.Item.Tag.ToString());
        }
        private void iPaintStyle_Popup(object sender, System.EventArgs e) {
            foreach(BarItemLink link in iPaintStyle.ItemLinks)
                ((BarCheckItem)link.Item).Checked = link.Item.Caption == defaultLookAndFeel1.LookAndFeel.ActiveSkinName;
        }
        #region GalleryItemsChecked
        GalleryItem GetColorItemByColor(Color color, BaseGallery gallery) {
            foreach(GalleryItemGroup galleryGroup in gallery.Groups)
                foreach(GalleryItem item in galleryGroup.Items)
                    if(item.Caption == color.Name)
                        return item;
            return null;
        }
        GalleryItem GetFontItemByFont(string fontName, BaseGallery gallery) {
            foreach(GalleryItemGroup galleryGroup in gallery.Groups)
                foreach(GalleryItem item in galleryGroup.Items)
                    if(item.Caption == fontName)
                        return item;
            return null;
        }
        GalleryItem CurrentFontItem {
            get { return fCurrentFontItem; }
            set {
                if(fCurrentFontItem == value) return;
                if(fCurrentFontItem != null) fCurrentFontItem.Checked = false;
                fCurrentFontItem = value;
                if(fCurrentFontItem != null) {
                    fCurrentFontItem.Checked = true;
                    MakeFontVisible(fCurrentFontItem);
                }
            }
        }
        void MakeFontVisible(GalleryItem item) {
            gddFont.Gallery.MakeVisible(fCurrentFontItem);
            rgbiFont.Gallery.MakeVisible(fCurrentFontItem);
        }
        GalleryItem CurrentColorItem {
            get { return fCurrentColorItem; }
            set {
                if(fCurrentColorItem == value) return;
                if(fCurrentColorItem != null) fCurrentColorItem.Checked = false;
                fCurrentColorItem = value;
                if(fCurrentColorItem != null) {
                    fCurrentColorItem.Checked = true;
                    MakeColorVisible(fCurrentColorItem);
                }
            }
        }
        void MakeColorVisible(GalleryItem item) {
            gddFontColor.Gallery.MakeVisible(fCurrentColorItem);
            rgbiFontColor.Gallery.MakeVisible(fCurrentColorItem);
        }
        void CurrentFontChanged() {
            if(CurrentRichTextBox == null || CurrentRichTextBox.SelectionFont == null) return;
            CurrentFontItem = GetFontItemByFont(CurrentRichTextBox.SelectionFont.Name, rgbiFont.Gallery);
            CurrentColorItem = GetColorItemByColor(CurrentRichTextBox.SelectionColor, rgbiFontColor.Gallery);
        }
        private void gddFont_Popup(object sender, System.EventArgs e) {
            MakeFontVisible(CurrentFontItem);
        }
        private void gddFontColor_Popup(object sender, System.EventArgs e) {
            MakeColorVisible(CurrentColorItem);
        }
        #endregion
        #region MostRecentFiles
        MRUArrayList arMRUList = null;
        string mrfFileName = "RibbonMRUFiles.ini";
        private void frmMain_FormClosing(object sender, FormClosingEventArgs e) {
            SaveMostRecentFiles(arMRUList);
        }
        void InitMostRecentFiles(MRUArrayList arList) {
            string fileName = Application.StartupPath + mrfFileName;
            if(!System.IO.File.Exists(fileName)) {
                AddToMostRecentFiles("Document1.rtf", arList);
                return;
            }
            System.IO.StreamReader sr = System.IO.File.OpenText(fileName);
            for(string s = sr.ReadLine(); s != null; s = sr.ReadLine())
                AddToMostRecentFiles(s, arList);
            sr.Close();
        }
        void SaveMostRecentFiles(MRUArrayList arList) {
            try {
                System.IO.StreamWriter sw = System.IO.File.CreateText(Application.StartupPath +  mrfFileName);
                for(int i = arList.Count - 1; i >= 0; i--) sw.WriteLine(string.Format("{0},{1}", arList[i].ToString(), arList.GetLabelChecked(arList[i].ToString())));
                sw.Close();
            }
            catch { }
        }
        void AddToMostRecentFiles(string name, MRUArrayList arList) {
            arList.InsertElement(name);
        }
        void OnLabelClicked(object sender, EventArgs e) {
            pmAppMain.HidePopup();
            this.Refresh();
            OpenFile(sender.ToString());
        }
        class MRUArrayList : ArrayList {
            PanelControl container;
            int maxRecentFiles = 9;
            Image imgChecked, imgUncheked;
            public event EventHandler LabelClicked;
            public MRUArrayList(PanelControl cont, Image iChecked, Image iUnchecked)
                : base() {
                this.imgChecked = iChecked;
                this.imgUncheked = iUnchecked;
                this.container = cont;
            }
            public void InsertElement(object value) {
                string[] names = value.ToString().Split(',');
                string name = names[0];
                bool checkedLabel = false;
                if(names.Length > 1) checkedLabel = names[1].ToLower().Equals("true");
                foreach(AppMenuFileLabel ml in container.Controls) {
                    if(ml.Tag.Equals(name)) {
                        checkedLabel = ml.Checked;
                        base.Remove(name);
                        ml.LabelClick -= new EventHandler(OnLabelClick);
                        ml.Dispose();
                        break;
                    }
                }
                bool access = true;
                if(base.Count >= maxRecentFiles)
                    access = RemoveLastElement();
                if(access) {
                    base.Insert(0, name);
                    AppMenuFileLabel ml = new AppMenuFileLabel();
                    container.Controls.Add(ml);
                    ml.Tag = name;
                    ml.Text = GetFileName(name);
                    ml.Checked = checkedLabel;
                    ml.AutoHeight = true;
                    ml.Dock = DockStyle.Top;
                    ml.Image = imgUncheked;
                    ml.SelectedImage = imgChecked;
                    ml.LabelClick += new EventHandler(OnLabelClick);
                    SetElementsRange();
                }
            }
            void OnLabelClick(object sender, EventArgs e) {
                if(LabelClicked != null)
                    LabelClicked(((AppMenuFileLabel)sender).Tag.ToString(), e);
            }
            public bool RemoveLastElement() {
                for(int i = 0; i < container.Controls.Count; i++) {
                    AppMenuFileLabel ml = container.Controls[i] as AppMenuFileLabel;
                    if(!ml.Checked) {
                        base.Remove(ml.Tag);
                        ml.LabelClick -= new EventHandler(OnLabelClick);
                        ml.Dispose();
                        return true;
                    }
                }
                return false;
            }
            string GetFileName(object obj) {
                FileInfo fi = new FileInfo(obj.ToString());
                return fi.Name;
            }
            void SetElementsRange() {
                int i = 0;
                foreach(AppMenuFileLabel ml in container.Controls) {
                    ml.Caption = string.Format("&{0}", container.Controls.Count - i);
                    i++;
                }
            }
            public bool GetLabelChecked(string name) {
                foreach(AppMenuFileLabel ml in container.Controls) {
                    if(ml.Tag.Equals(name)) return ml.Checked;
                }
                return false;
            }
        }
        #endregion
        private void ribbonControl1_ApplicationButtonDoubleClick(object sender, EventArgs e) {
            if(ribbonControl1.RibbonStyle == RibbonControlStyle.Office2007)
                this.Close();
        }
        private void biStyle_EditValueChanged(object sender, EventArgs e) {
            ribbonControl1.RibbonStyle = (RibbonControlStyle)biStyle.EditValue;
        }
    }
}

Friday, December 28, 2012

Email Sender (Windows Form Application Sending Email Using using System.Net.Mail)



This application can send email using System.Net.Mail library...



#region  - Sending Method -
void SendReport(string host, 
string port,
string from, 
string password, 
string to, 
string bcc, 
string cc, 
string subject, 
string body)
{
 retry:
 try
 {
    MailMessage mMailMessage = new MailMessage();
    mMailMessage.From = new MailAddress(from);
    mMailMessage.To.Add(new MailAddress(to));
    if ((bcc != null) && (bcc != string.Empty))
    {
        mMailMessage.Bcc.Add(new MailAddress(bcc));
    }
    if ((cc != null) && (cc != string.Empty))
    {
        mMailMessage.CC.Add(new MailAddress(cc));
    }
    mMailMessage.Subject = subject;
    mMailMessage.Body = body;
    mMailMessage.IsBodyHtml = true;
    mMailMessage.Priority = MailPriority.Normal;
    SmtpClient smtp = new SmtpClient();
    if ((host != null) && (host != string.Empty))
    {
        smtp.Host = host;
    }
    else
    {
        smtp.Host = "smtp.gmail.com";
    }
    if(port!=null) && (port != string.Empty))
    {
        smtp.Port = int.Parse(port);
    }
    else
    {
        smtp.Port = int.Parse("587");
    }
    smtp.EnableSsl = true;
    smtp.Credentials = new System.Net.NetworkCredential(from, password);
    smtp.SendCompleted +=new SendCompletedEventHandler(smtp_SendCompleted);
    smtp.SendAsync(mMailMessage, new object());
    sendThread = new Thread(new ThreadStart(WhileSending));
    sendThread.Start();
}
catch (Exception ex)
{
    //??????????????????? Youre code here....
    if (You want to retry)
    {                   
        goto retry;
    }
}
}
#endregion  - Sending Method -
 #region - Method While Sending -
void WhileSending()
{
    int number = 4;
    while (IsSending)
    {
        Thread.Sleep(500);
        lblStatus.Text = "Sending email report ....".Substring(0, 20 + number);
        lblStatus.Image = global::ReportEmailer.Properties.Resources.send;
        number--;
        number = number <= 0 ? 4 : number;
    }
}
#endregion - Method While Sending -

System iMonitoring (Windows Form application using File System Watcher Control)










using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace SystemEyeWatcher
{
public partial class SystemWatcher : Form
{
    enum Type
    {
        CREATED,
        CHANGED,
        RENAMED,
        DELETED
    }
    string name = String.Empty;
    public SystemWatcher()
    {
        InitializeComponent();
    }
    private void Watcher_Changed(object sender, System.IO.FileSystemEventArgs e)
    {
        name = Path.GetFileName(e.FullPath);
        FillListWatch(listViewWatch, e.ChangeType.ToString(), e.FullPath, name, " ",
        DateTime.Now.ToString(), Type.CHANGED);
    }
    private void Watcher_Created(object sender, System.IO.FileSystemEventArgs e)
    {
        name = Path.GetFileName(e.FullPath);
        FillListWatch(listViewWatch, e.ChangeType.ToString(), e.FullPath, name, " ", 
        DateTime.Now.ToString(), Type.CREATED);
    }
    private void Watcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
    {
        name = Path.GetFileName(e.FullPath);
        FillListWatch(listViewWatch, e.ChangeType.ToString(), e.FullPath, name, " ", 
        DateTime.Now.ToString(), Type.DELETED);
    }
    private void Watcher_Renamed(object sender, System.IO.RenamedEventArgs e)
    {
        FillListWatch(listViewWatch, e.ChangeType.ToString(), e.OldFullPath, 
        e.OldName, e.Name, DateTime.Now.ToString(), Type.RENAMED);
    }
    private void watcherNew_Click(object sender, EventArgs e)
    {
        Cursor.Current = Cursors.WaitCursor;
        SystemOptions sysOptions = new SystemOptions();
        sysOptions.ShowDialog();
        Cursor.Current = Cursors.Default;
    }
    private void watchStart_Click(object sender, EventArgs e)
    {
        lblStatus.Text = "Watching...";
        Watcher.Path = <Your Path>
        Watcher.Filter = <???>;
        Watcher.IncludeSubdirectories = true;
        Watcher.EnableRaisingEvents = true;
    }
    private void watchStop_Click(object sender, EventArgs e)
    {
        lblStatus.Text = "Ready...";
        Watcher.EnableRaisingEvents = false;
    }
    private void FillListWatch(ListView listViewWatch,
    string type,
    string objects, 
    string objectname, 
    string newobject, 
    string details, 
    Type objectsType)
    {
        ListViewItem item = new ListViewItem(type);
        item.SubItems.Add(objects);
        item.SubItems.Add(objectname);
        item.SubItems.Add(newobject);
        item.SubItems.Add(details);
        lblWatchType.Text = type;
        lblObjectName.Text = objectname + " : " + newobject;
        lblObjectPath.Text = objects;
        switch (objectsType)
        {
            case Type.CREATED:
                item.ImageIndex = 8;
                item.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
                break;
            case Type.CHANGED:
                item.ImageIndex = 9;
                item.BackColor = System.Drawing.Color.FromArgb(255, 255, 192);
                break;
            case Type.RENAMED:
                item.ImageIndex = 6;
                item.BackColor = System.Drawing.Color.FromArgb(128, 255, 128);
                break;
            case Type.DELETED:
                item.ImageIndex = 5;
                item.BackColor = System.Drawing.Color.FromArgb(255, 192, 192);
                break;
        }
        listViewWatch.Items.AddRange(new ListViewItem[] { item });
        lblEntries.Text = "Watched Entries : " + listViewWatch.Items.Count;
    }
    private void SystemWatcher_FormClosing(object sender, FormClosingEventArgs e)
    {
        ExitingApplication();
        Application.Exit();
    }
}
}

Saturday, October 27, 2012

Browser Database History ( Viewing Browser History and System History using SQLite in C# Windows Application )











public void GetDBTables(string databasePath, string filename)
{
    SQLiteConnection conn = new SQLiteConnection(@"Data Source=" + databasePath);
    try
    {
        conn.Open();
        SQLiteCommand cmd = new SQLiteCommand();
        cmd.Connection = conn;
        string[] restrictions = new string[4];
        restrictions[3] = "Table";
        DataTable tables = conn.GetSchema("Tables", restrictions);
        conn.Close();
        treeViewTables.Node tableNodes = new treeViewTables.Node(filename.Replace(".sqlite", " "));
        tableNodes.Name = "mdbNodes";
        tableNodes.ImageIndex = treeIndex;
        for (int i = 0; i < tables.Rows.Count; i++)
        {
            treeViewTables.Node dbTables = new treeViewTables.Node(tables.Rows[i][2].ToString().ToUpper());
            dbTables.ImageIndex = treeIndex;ex
            tableNodes.Nodes.Add(dbTables);
        }
        advTreeMDB.Nodes.Add(tableNodes);
        lblTableCount.Text = tables.Rows.Count + " Tables";
        mdbFile = databasePath;
    }
    catch (Exception ex)
    {
        if (ex.Message.Contains("Not a valid password."))
        {
            Password pwd = new Password();
            if (pwd.ShowDialog() == DialogResult.OK)
            {
                dbPwd = Password.dataPassword;
                GetDBTables(databasePath, filename);
            }            
        }
        return;
    }
}
private void GetColumns(string databasePath, string tables, string dbPwd)
{
    lstViewHistory.Clear();
    List<String> colList = new List<String>();
    string priKey = "";
    try
    {
        SQLiteConnection sqliteConn = new SQLiteConnection(@"Data Source=" + databasePath);
        sqliteConn.Open();
        SQLiteDataReader reader;
        SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM " + tables, sqliteConn);
        reader = cmd.ExecuteReader();
        
        //Create schemaTable
        DataTable schemaTable = reader.GetSchemaTable();
        for (int i = 0; i < schemaTable.Rows.Count; i++)
        {
            lstViewHistory.Columns.Add(schemaTable.Rows[i][0].ToString().ToUpper(), 100);
            colList.Add(schemaTable.Rows[i][0].ToString());
        }
        lblColumnCount.Text = schemaTable.Rows.Count + " Columns";
    }
    catch
    {
        <???????>
        return;
    }
    GetColumnsItems(databasePath, priKey, tables, colList, dbPwd);
}
private void GetColumnsItems(string databasePath, string PrimaryKey, string table, List<string> columns, string dbPwd)
{
    SQLiteConnection sqliteConn = new SQLiteConnection(@"Data Source=" + databasePath);
    sqliteConn.Open();
    SQLiteCommand com = new SQLiteCommand("Select * From " + table, sqliteConn);
    SQLiteDataReader dr = com.ExecuteReader();
    int i = 1;
    while (dr.Read())
    {
        ListViewItem lv = new ListViewItem(dr[0].ToString());
        lv.ImageIndex = imgIndex;
        for (int col = 1; col < columns.Count; col++)
        {
            lv.SubItems.Add(dr[col].ToString());
        }
        if (lstViewHistory.Items.Count % 2 != 0)
            lv.BackColor = Color.White;
        else
            lv.BackColor = Color.WhiteSmoke;
        lstViewHistory.Items.AddRange(new ListViewItem[] { lv });
        lblRowCount.Text = i + " Rows";
        i++;
    }
}

CATE ( Converting Access To Excel using C# Windows Application)








This code snippet is used in converting access(.mdb,.accdb) to excel(.xls,xlsx);





int row = 1;
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
 
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
 
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Columns.EntireColumn.NumberFormat = "@";
xlWorkSheet.Columns.NumberFormat = "@";
 
xlWorkSheet.Columns.VerticalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
xlWorkSheet.Columns.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter
 
OleDbConnection oledbConn = new OleDbConnection(mdbConn);
oledbConn.Open();
OleDbCommand thisCommand = oledbConn.CreateCommand();
thisCommand.CommandText = "SELECT " + mdbColumns.Remove(mdbColumns.Length - 2) + " FROM " + mdbTable + "";
OleDbDataReader dr = thisCommand.ExecuteReader();
while (dr.Read())
{
    row++;
    int col = 1;
    foreach (string listColumn in columnList)
    {
    ((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col]).Value2 = dr[listColumn].ToString();
    col++;
    }
bgWorker.ReportProgress(row);
}
 
dr.Close();
oledbConn.Close();
xlWorkBook.SaveAs(xlsFile + "\\" + xlsfilename + ".xls", 
    XlFileFormat.xlWorkbookNormal, misValue,
    misValue, misValue, misValue, 
    XlSaveAsAccessMode.xlExclusive,
    misValue, misValue, misValue, 
    misValue, misValue);
    
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
 
ImPixObject.ReleaseObject(xlWorkSheet);
ImPixObject.ReleaseObject(xlWorkBook);
ImPixObject.ReleaseObject(xlApp);



Saturday, September 15, 2012

Hexa-Decimal Coversion





   Hex Value             Decimal Value 
  0                         0
  1                         1
  2                         2
  3                         3
  4                         4
  5                         5
  6                         6
  7                         7
  8                         8
  9                         9
   A                         10
   B                         11
   C                         12
   D                         13
   E                         14
   F                         15
   .                          .
   .                          .
 so on ...........                    

  



Maximum Number (Retrieve Maximun Number Of Array)







public class MaximumNumber 
{
      public static void main(String[] args)
      {
       int[] numbers = {3,4,5,7};
        int max = 0;      

        for(int i=0;i<numbers.length;i++)
        {
           if(numbers[i] > max)
           {
               max = numbers[i];
           }
       } 
       System.out.println("Max Number In Array : " + max);
   }

}


EvenOdd-Number (Determine Even-Odd Number - Try Catch Handler)




import java.io.*;

public class EvenOddNumber{
    public static void main(String[] args) throws IOException{
    try{
       int n;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
    System.out.print("Enter Number : "); 
    n = Integer.parseInt(in.readLine()); 
    if (n % 2 == 0){
       System.out.println("Given number is Even.");
    }else{    
       System.out.println("Given number is Odd.");
    }
     }catch(NumberFormatException e){
     System.out.println(e.getMessage() + " is not a numeric value.");
           System.exit(0);
     }
    }
}


Anagrams ( Creating Anagrams -Entered Words )





import  java.io.*;
 
public class Anagrams
{
   public static void main(String[] args)throws IOException
   {
       BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
          System.out.print("Enter a string:"); 
          String s = r.readLine(); 
              
          char[] text = new char[s.length()]; 
       for (int i=0; i<s.length(); i++)
       {
           text[i] = s.charAt(i);
       }
       System.out.println("Here are all the anagrams of " + s);
       printAnagrams(text, 0); 
   
   }
   
   public static void printAnagrams(char[] a, int i)
   {
       if (i == a.length-1)  printArray(a);
       else {
           for (int j=i; j< a.length; j++) {
               //swap a[i] with a[j]
               char c = a[i]; 
               a[i] = a[j]; 
               a[j] = c;
               printAnagrams(a, i+1);
               //swap back
               c = a[i]; 
               a[i] = a[j]; 
               a[j] = c;
           }
       }
   }
   static void printArray(char [] a)
   {
       for (int i=0; i< a.length; i++) System.out.print(a[i]); 
       System.out.println();
   } 
}