Showing posts with label visual studio 2013. Show all posts
Showing posts with label visual studio 2013. Show all posts

Wednesday, November 23, 2016

Project Professional 2013 Add-in using Visual Studio

In this article, I will walk through creation of a simple Add-in for Project Pro 2013 using Visual Studio 2013 and C# to add a new task when project load and also on a custom button click in Ribbon.

Step 1: Open Visual Studio 2013 and Create New Project, Select ‘Project 2013 Add-in’ from Installed -> Templates -> Visual C# -> Office/Sharepoint ->Office Add-ins

Step 2: Provide a Name for the project and click on Ok.

Project 2013 Add-in solution is created and it comes up with ‘ThisAddIn.cs’ class file and also the class has 2 default event handlers one is to trigger on Add-in Startup and other is on shut down.
 
Step 3: As one of our requirement here is to create a new task when Project loaded, let us create a method to add new task with defaults and attach this method to Project Load event handler in Startup method.
 

And the code is as below.
 //Method  
 void AddTask(MSProject.Project pj)  
 {  
    MSProject.Task newTask = pj.Tasks.Add  
       ("This text was added by using code on addin startup", missing);  
    newTask.Start = DateTime.Now;  
    newTask.Duration = "3";  
 }  
   
 //To add the above method to event handler  
 this.Application.NewProject += new   Microsoft.Office.Interop.MSProject._EProjectApp2_NewProjectEventHandler(AddTask);  

Step 4: As the other requirement is to create a task on button click in ribbon, let us add ribbon tab to this project. To do this, click on add new Item to the solution in Solution Explorer and under Installed -> Visual C# Items -> office/Sharepoint Select ‘Ribbon (Visual Designer)’. With Visual designer option, we will be able to drag controls from toolbox.

Step 5: with this, CustomRibbon class file and corresponding designer file are added to solution and it appears as below
 
Here we can rename label of ribbon and also the group name using properties window of corresponding control.

Step 6: Using toolbox, from Office ribbon controls section select button. There are lots of other controls and also we can add more tabs by right clicking on design screen in tab area.

Step 7: Add Image to button and also label the button from property screen and finally it appears as below 

Step 8: By double clicking on the button, it redirects to class file with button click event handler created and attached to the corresponding button. This can also be done through properties window.
In the event handler method, let us write the required code to add a new task to the current plan loaded 

And the code is as below,
 MSProject.Project currProject = Globals.ThisAddIn.Application.ActiveProject;   
 MSProject.Task newTask = currProject.Tasks.Add  
    ("This text was added by using code on button click",Type.Missing);  
 newTask.Start = DateTime.Now;  
 newTask.Duration = "3";  
With these steps, we completed the implementation and to test it, click on ‘Start Debugging’ and it opens up the Project Pro. Select the environment and click on a “New project” or select an existing project.


Note: Once we run the solution, it creates a set of registry entries and also some security settings are configured to enable this add in.
So, once tested, remove the above created entries and changes by cleaning the solution.

Thursday, April 28, 2016

Windows Service using C# in Visual Studio 2013

Here, I will walk through step by step process for creating and deploying Windows Service using Visual Studio 2013 in C#.

Before we go in details, just to understand on a high level, a Windows Service is a computer program that runs in the background with out End User interference. It can be started automatically when the system boots.


Mainly we use Windows Service to run Scheduled Jobs, like sending Daily Report emails to Managers , Newsletters to the team.

In this demo, I created Windows Service in C# using Visual studio 2013 and scheduled it for every minute.

Step 1: Open Visual Studio and Create a New ‘Windows Service’ Project available in Visual C#, Windows Category.

Step 2:  In the Project solution, we will be able to see multiple files, one of them is Service1.cs. Rename it as per the functionality we are going to implement.

Step 3: Go to Code View screen by clicking on 'click here to switch to code view'.

Here we would see 3 methods auto populated. The first one is on Initiation of the service.
OnStart method is executed when we start the Service, this could be automated or manual event.
OnStop method is executed when the service is stopped, could be manual by end user or when syste m shuts down or some automated process.
Step 4: Here we have to add the timer to schedule the functionality or job which we want to execute at regular interval. Below is the sample code
using System;
using System.IO;
using System.ServiceProcess;

namespace TimesheetTaskCreation
{
    public partial class TaskCreation : ServiceBase
    {
        public TaskCreation()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            WriteLog("Service Started.");

            // Set up a timer to trigger every minute.
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 60000 * 1; //1 min
            timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
            timer.Start();

        }

        public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
        {
            // TODO: Insert monitoring activities here.
            WriteLog("Performing Service Action.");

            //Perform the actions here
        }

        protected override void OnStop()
        {
            WriteLog("Service Stopped.");
        }

        private void WriteLog(string text)
        {
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "LogFile.txt", true);
                sw.WriteLine(DateTime.Now.ToString() + ":" + text);
                sw.Flush();
                sw.Close();
            }
            catch (Exception e)
            {

            }
        }
    }
}


"WriteLog" is a function used to update Log file maintained in the installation folder location.
"OnTimer" is the event handler fired upon reaching configured duration
And, the timer is setup in OnStart method, so when the service is started, Timer will be started and the job is scheduled.

Step 5: Now, we need to add an installer to the service. To do this, right click on the Service.cs file and click on 'Add Installer'
A new file Projectinstaller.cs is added and it has 2 controls, 'SerivceInstaller' and 'ServiceProcessInstaller'
Step 6: Go to Properties of ServiceInstaller and provide Service name and description. Also, Change start type to Manual.

Step 7: Now, go to properties of SercieProcessInstaller and set Account to LocalService. The service will be running on this account. Based on your job's access requirements, use the Account.

Step 8: With these steps, the Windows service is ready and we need to Deploy / Install it. To do this, Build the solution and in the Bin folder, we will have an EXE file as in below image

Step 9: Now, open Visual Studio Command Prompt and go to the file location where we have the exe file as in above step. And to install, the command we use is 'InstallUtil.exe <exe file>'



Step 10: After we execute above command, we get successfully installed message on command prompt and then open the System services to view installed service. To open, run 'Services.msc' in System Run .
Upon clicking on Start, the service will be started the job is scheduled. We can see the logs in the Log file created in same folder.
To uninstall the Service, the command we use is 'InstallUtil.exe /u <exe file>'. To execute this command, go to the same folder where we have the exe file.

Happy Coding! :-)