Monday, January 31, 2011

Notify Icon Implementation

Form Designer Code :

namespace NotifyIconExample
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
            this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.Restore = new System.Windows.Forms.ToolStripMenuItem();
            this.CloseApplication = new System.Windows.Forms.ToolStripMenuItem();
            this.contextMenuStrip1.SuspendLayout();
            this.SuspendLayout();
            //
            // notifyIcon1
            //
            this.notifyIcon1.ContextMenuStrip = this.contextMenuStrip1;
            this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));
            this.notifyIcon1.Text = "HideApp";
            this.notifyIcon1.Visible = true;
            this.notifyIcon1.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.notifyIcon1_MouseDoubleClick);
            //
            // contextMenuStrip1
            //
            this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.Restore,
            this.CloseApplication});
            this.contextMenuStrip1.Name = "contextMenuStrip1";
            this.contextMenuStrip1.Size = new System.Drawing.Size(168, 48);
            //
            // Restore
            //
            this.Restore.Name = "Restore";
            this.Restore.Size = new System.Drawing.Size(167, 22);
            this.Restore.Text = "Restore";
            //
            // CloseApplication
            //
            this.CloseApplication.Name = "CloseApplication";
            this.CloseApplication.Size = new System.Drawing.Size(167, 22);
            this.CloseApplication.Text = "Close Application";
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Resize += new System.EventHandler(this.Form1_Resize);
            this.contextMenuStrip1.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.NotifyIcon notifyIcon1;
        private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
        private System.Windows.Forms.ToolStripMenuItem Restore;
        private System.Windows.Forms.ToolStripMenuItem CloseApplication;
    }
}



Form Backend Code :

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;

namespace NotifyIconExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == WindowState)
                Hide();

        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            Show();
            WindowState = FormWindowState.Normal;
        }
    }
}

Friday, January 28, 2011

Create windows service with file system watcher running in the background

1. First create an empty project.
2. Add a class and inherit from the  System.ServiceProcess.ServiceBase.
3. You might have to add references of System.dll and System.ServiceProcess.dll.
4. Change the class like this :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace WsEg1
{
   public  class UserService1 : System.ServiceProcess.ServiceBase
    {
       public UserService1()
       {
           this.ServiceName = "MyService2";
           this.CanStop = true;
           this.CanPauseAndContinue = true;
           this.AutoLog = true;
       }
       public static void Main()
       {
           System.ServiceProcess.ServiceBase.Run(new UserService1());
       }
       protected override void OnStart(string[] args)
       {
           // Insert code here to define processing.
           //FileStream fs = new FileStream(@"C:\Users\sameer\Desktop\Skill Trac\ServiceInfo.txt", FileMode.OpenOrCreate);
           //StreamWriter sw = new StreamWriter(fs);
           //sw.WriteLine("Service has been started at " + System.DateTime.Now);
           //sw.Close();
           //fs.Close();
           FileWatcher.Run();
       }

       protected override void OnStop()
       {
           //FileStream fs = new FileStream(@"C:\Users\sameer\Desktop\Skill Trac\ServiceInfo.txt", FileMode.OpenOrCreate);
           //StreamWriter sw = new StreamWriter(fs);
           //sw.WriteLine("Service has been stopped at " + System.DateTime.Now);
           //sw.Close();
           //fs.Close();
           FileWatcher.Close();
       }

       private void InitializeComponent()
       {
           //
           // UserService1
           //
           this.ServiceName = "SamService";

       }




    }
}

5. Add ProjectInstaller by opening Service in design view, right click and add installer.
6. After that add setup project and add project output to be primary output of solution.
7. Thats it you are done.

Below is the code of FileWatcher Class, which performs the snooping of folders :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace WsEg1
{
    public class FileWatcher
    {
        public static void Run()
        {
            FileSystemWatcher Watcher = new FileSystemWatcher(Environment.GetEnvironmentVariable("USERPROFILE"));
            Watcher.Path = @"C:\Users\sameer\Desktop\Skill Trac";
            Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            Watcher.Filter = "*.txt";

            //Add event handlers for all the events
            Watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
            Watcher.Renamed += new RenamedEventHandler(Watcher_Renamed);
            Watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);

            Watcher.EnableRaisingEvents = true;
           

        }

        public static void Close()
        {
           
           
        }

        static void Watcher_Deleted(object sender, FileSystemEventArgs e)
        {
           
            //FileStream fs = new FileStream(@"C:\Users\sameer\Desktop\Skill Trac\ServiceInfo.txt", FileMode.OpenOrCreate);
            //StreamWriter sw = new StreamWriter(fs);

            StreamWriter sw = File.AppendText(@"C:\Users\sameer\Desktop\Sam Sync\ServiceInfo.txt");
           
            sw.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
            sw.Close();
            //fs.Close();
       
        }

        static void Watcher_Renamed(object sender, RenamedEventArgs e)
        {

            StreamWriter sw = File.AppendText(@"C:\Users\sameer\Desktop\Sam Sync\ServiceInfo.txt");

            sw.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
            sw.Close();
        }

        static void Watcher_Changed(object sender, FileSystemEventArgs e)
        {
            StreamWriter sw = File.AppendText(@"C:\Users\sameer\Desktop\Sam Sync\ServiceInfo.txt");

            sw.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
            sw.Close();
        }
    }
}

Wednesday, January 5, 2011

Create a text document and write data to the text document

  public static void WriteUserDetails(string data, string FileName)
        {
          
            try
            {

                FileStream fs = File.Open(FileName, FileMode.CreateNew, FileAccess.Write);



                // generate a file stream with UTF8 characters

                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);

                sw.WriteLine(data);
                sw.Flush();
                sw.Close();
            }
            catch
            {
               
                //GlobalData.SetApplicationExitState(true);
               
            }
        }

How to close open office documents

In the below code, we have a sample for opening any openoffice document as well as CLOSE method provides closing statements for the documents.

//////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TTA.Util;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.beans;

namespace TTA.Util
{
  public class OpenOffice
  {
    XComponent xComponent;
    XComponentLoader componentLoader;
    unoidl.com.sun.star.lang.XMultiServiceFactory multiServiceFactory;
    unoidl.com.sun.star.uno.XComponentContext localContext;

    public OpenOffice(string FileName, string fileType)
    {
      localContext = uno.util.Bootstrap.bootstrap();
      multiServiceFactory = (unoidl.com.sun.star.lang.XMultiServiceFactory)localContext.getServiceManager();
      componentLoader = (XComponentLoader)multiServiceFactory.createInstance("com.sun.star.frame.Desktop");
      PropertyValue[] loadDesc = new PropertyValue[1];
      loadDesc[0] = new PropertyValue();

      loadDesc[0].Name = "Hidden";
      loadDesc[0].Value = new uno.Any(true);
      xComponent = componentLoader.loadComponentFromURL(fileType, "_blank", 0, loadDesc);
      ((XStorable)xComponent).storeToURL(General.PathConverter(FileName), new unoidl.com.sun.star.beans.PropertyValue[0]);
      xComponent.dispose();
      xComponent = componentLoader.loadComponentFromURL(General.PathConverter(FileName), "_blank", 0, new unoidl.com.sun.star.beans.PropertyValue[0]);
    }

    public bool Close()
    {
      try
      {
        ((XStorable)xComponent).store();
        xComponent.dispose();
        return true;
      }
      catch
      {
        return false;
      }
    }
  }
}

How to close running instance of Word,Excel and Powerpoint

  public static void CloseWord(MySettings settings)
        {
            if (System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application") != null)
            {
                try
                {
                    Object oMissing = System.Reflection.Missing.Value;

                    //True and false objects
                    Object oTrue = true;
                    Object oFalse = false;

                    Microsoft.Office.Interop.Word.Application oWordApp = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
                    int i = 0;
                    foreach (Microsoft.Office.Interop.Word.Document document in oWordApp.Documents)
                    {
                        i++;
                        string num = i.ToString();
                        Object oSaveAsFileWord = General.GetAppString("UserDocuments") + GlobalData.GetStudentInfo()[0].ToString().Trim() + "_" + GlobalData.GetUserName() + settings.FileExtension;
                        oWordApp.ActiveDocument.SaveAs(ref oSaveAsFileWord, ref oMissing, ref oMissing, ref oMissing,
                                ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                        object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
                        oWordApp.ActiveDocument.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);


                    }
                   
                    oWordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                }

                 

                catch
                {
                }
            }
        }

        public static void CloseExcel(MySettings settings)
        {
            try
            {
              
                Excel.Workbook xlwkbook;

                string workbookPath = General.GetAppString("UserDocuments") + GlobalData.GetStudentInfo()[0].ToString().Trim() + "_" + GlobalData.GetUserName() + settings.FileExtension;
                xlwkbook = (Excel.Workbook)System.Runtime.InteropServices.Marshal.BindToMoniker(workbookPath);
                xlwkbook.Save();

                xlwkbook.Application.Quit();

            }

            catch
            {
                return;
            }

           
          


        }

        public static void ClosePowerPoint(MySettings settings)
        {
            try
            {
                Microsoft.Office.Interop.PowerPoint.Application PowerApp = (Microsoft.Office.Interop.PowerPoint.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Powerpoint.Application");

                PowerApp.ActivePresentation.Save();
                int num = PowerApp.Windows.Count;
                PowerApp.Quit();
            }
            catch
            {
                return;
            }

        }

How to open Word,Excel,PowerPoint in C#

static void word(MySettings settings)
        {
            Microsoft.Office.Interop.Word.ApplicationClass WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            object fileName = General.GetAppString("Resources") + General.GetAppString("DefaultWordTemplate");
            object DestFilename = General.GetAppString("UserDocuments") + GlobalData.GetStudentInfo()[0].ToString().Trim() + "_" + GlobalData.GetUserName() + settings.FileExtension;
            object readOnly = false;
            object isVisible = false;
            // Here is the way to handle parameters you don't care about in .NET
            object missing = System.Reflection.Missing.Value;
            // Make word visible, so you can see what's happening
            WordApp.Visible = false;

            // Open the document that was chosen by the dialog
            Microsoft.Office.Interop.Word.Document aDoc = WordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);
            // Activate the document so it shows up in front

            aDoc.SaveAs(ref DestFilename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            isVisible = true;
           
            //Microsoft.Office.Interop.Word.Document aDoc = WordApp.Documents.Open(ref DestFilename, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);
            WordApp.Visible = true;
            aDoc.Activate();
            Documents[Impress.AppCount] = DestFilename.ToString();
         


        }

        static void OpenExcel(MySettings settings)
        {
            object missing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            excelApp.Visible = false;
            Microsoft.Office.Interop.Excel.Workbook newWorkbook = excelApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            string workbookPath = General.GetAppString("UserDocuments") + GlobalData.GetStudentInfo()[0].ToString().Trim() + "_" + GlobalData.GetUserName() + settings.FileExtension;
          
            newWorkbook.SaveAs(workbookPath, missing, missing, missing, true, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
            excelApp.Quit();

            excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            excelApp.Visible = true;
            Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
                0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);

            Documents[Impress.AppCount] = workbookPath;
       
       
        }

        static void PowerpointWindow(MySettings settings)
        {
            PowerPoint.Application objApp;
            PowerPoint.Presentations objPresSet;
            PowerPoint._Presentation objPres;

            string fileName = General.GetAppString("Resources") + General.GetAppString("DefaultPowerPointTemplate");
            string DestFilename = General.GetAppString("UserDocuments") + GlobalData.GetStudentInfo()[0].ToString().Trim() + "_" + GlobalData.GetUserName() + settings.FileExtension;

            //Create a new presentation based on a template.
            objApp = new PowerPoint.Application();
            objApp.Visible = MsoTriState.msoTrue;
            objPresSet = objApp.Presentations;
            objPres = objPresSet.Open(fileName, MsoTriState.msoCTrue, MsoTriState.msoTrue, MsoTriState.msoTrue);
          

           
            objPres.SaveAs(DestFilename, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoTrue);
          
            objApp.Visible = MsoTriState.msoTrue;
           
            objApp.Activate();

            Documents[Impress.AppCount] = DestFilename.ToString();


        }

Tuesday, December 21, 2010

Creating Custom Sections in App.Config File

/////Config File////
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

    <section name ="Application" type="CustomSectionsExample.MyHandler, CustomSectionsExample"/>
  </configSections>
  <Application>
    <Name>POWERPNT</Name>
    <Runtime>1</Runtime>
    <Message>Say Hey to Word application</Message>
    <MessageTime>1</MessageTime>
  </Application >
 
</configuration>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Create Custom Handler
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration.Install;
using System.Configuration;

namespace CustomSectionsExample
{
    public class MySettings
    {
        public string Name;
        public MySettings()
        {
        }
    }
   public  class MyHandler: IConfigurationSectionHandler
    {
        public MyHandler()
        {
          
           
        }
       
      
       

        #region IConfigurationSectionHandler Members

        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            MySettings Settings = new MySettings();
            Settings.Name = section.SelectSingleNode("Name").InnerText;
            return Settings;
        }

        #endregion
    }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Finally Read from App.Config
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace CustomSectionsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            MySettings settings = (MySettings)ConfigurationManager.GetSection("Application");
            Console.WriteLine(settings.Name);
            Console.ReadKey();
        }
    }
}