Quantcast
Channel: Visual Studio Integrate forum
Viewing all articles
Browse latest Browse all 4410

VSPackage - null AddInInstance in CreateToolWindow2

$
0
0

Hi,

I am trying to converting addin to vspackage. After certain point of time, I am getting an error of 'Object reference not set'. After debug, I found that AddInInstance is null which is used in CreateToolWindow2 function. 

How can I solve this issue?

I am attaching addin code, vsix code & the code where I am getting error for your reference.

ADDIN => Connect.cs

using System;
using Extensibility;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.CommandBars;
using System.Resources;
using System.Reflection;
using System.Globalization;
using System.Windows.Forms;
using GForgeTrackerAddIn.Properties;

namespace GForgeTrackerAddIn
{
    /// <summary>The object for implementing an Add-in.</summary>
    /// <seealso class='IDTExtensibility2' />
    public class Connect : IDTExtensibility2, IDTCommandTarget
    {
        private Window toolWindow;
        public static DTE2 Application;
        public static AddIn AddInInstance;

        /// <summary>Implements the constructor for the Add-in object. Place your initialization code within this method.</summary>
        public Connect()
        {
        }

        /// <summary>Implements the OnConnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being loaded.</summary>
        /// <param term='application'>Root object of the host application.</param>
        /// <param term='connectMode'>Describes how the Add-in is being loaded.</param>
        /// <param term='addInInst'>Object representing this Add-in.</param>
        /// <seealso class='IDTExtensibility2' />
        public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
        {
            Application = (DTE2)application;
            AddInInstance = (AddIn)addInInst;

            if (connectMode == ext_ConnectMode.ext_cm_UISetup)
            {
                object[] contextGUIDS = new object[] { };
                Commands2 commands = (Commands2)Application.Commands;
                string menuName;
                Microsoft.VisualStudio.CommandBars.CommandBar menuBarCommandBar;
                CommandBarControl toolsControl;
                CommandBarPopup toolsPopup;

                try
                {
                    //If you would like to move the command to a different menu, change the word "View" to the
                    //  English version of the menu. This code will take the culture, append on the name of the menu
                    //  then add the command to that menu. You can find a list of all the top-level menus in the file
                    //  CommandBar.resx.
                    ResourceManager resourceManager = new ResourceManager("GForgeTrackerAddIn.CommandBar", Assembly.GetExecutingAssembly());
                    CultureInfo cultureInfo = new System.Globalization.CultureInfo(Application.LocaleID);
                    string resourceName = String.Concat(cultureInfo.TwoLetterISOLanguageName, "Tools");
                    menuName = resourceManager.GetString(resourceName);
                    //Place the command on the tools menu.
                    //Find the MenuBar command bar, which is the top-level command bar holding all the main menu items:
                    menuBarCommandBar = ((Microsoft.VisualStudio.CommandBars.CommandBars)Application.CommandBars)["MenuBar"];

                    //Find the Tools command bar on the MenuBar command bar:
                    toolsControl = menuBarCommandBar.Controls[menuName];
                    toolsPopup = (CommandBarPopup)toolsControl;
                }
                catch
                {
                    //We tried to find a localized version of the word Tools, but one was not found.
                    //  Default to the en-US word, which may work for the current culture.
                    menuName = "Tools";

                    //Place the command on the tools menu.
                    //Find the MenuBar command bar, which is the top-level command bar holding all the main menu items:
                    menuBarCommandBar = ((Microsoft.VisualStudio.CommandBars.CommandBars)Application.CommandBars)["MenuBar"];

                    //Find the Tools command bar on the MenuBar command bar:
                    toolsControl = menuBarCommandBar.Controls[menuName];
                    toolsPopup = (CommandBarPopup)toolsControl;
                }



                //This try/catch block can be duplicated if you wish to add multiple commands to be handled by your Add-in,
                //  just make sure you also update the QueryStatus/Exec method to include the new command names.
                try
                {
                    //Add a command to the Commands collection:
                    Command command = commands.AddNamedCommand2(
                        AddInInstance,
                        "GForge","GForge","GForge AS Add-In",
                        false,
                        Properties.Resources.favicon_16.GetHbitmap(),
                        ref contextGUIDS,
                        (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled,
                        (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton
                    );

                    //Add a control for the command to the tools menu:
                    if ((command != null) && (toolsPopup != null)) {
                        command.AddControl(toolsPopup.CommandBar, 1);
                    }
                }
                catch
                {
                }
                /*catch (System.ArgumentException)
                {
                    //If we are here, then the exception is probably because a command with that name
                    //  already exists. If so there is no need to recreate the command and we can
                    //  safely ignore the exception.
                }*/
            }

            if (toolWindow == null)
            {
                // Add our TrackerList to the window
                object objTemp = null;
                string guidstr = "{95C832DC-391A-48ba-94B8-C22BB2B1B988}";

                Windows2 w = (Windows2)Application.Windows;
                toolWindow = w.CreateToolWindow2(
                    AddInInstance,
                    System.Reflection.Assembly.GetExecutingAssembly().Location,
                    "GForgeTrackerAddIn.GForgeControl",
#if ATMEL"Atmel Spaces",
#else"GForge AS",
#endif
                    guidstr,
                    ref objTemp
                );
                try
                {
                    //This will throw an exception at compile time due to a bug in .NET
                    //simply ignore it, see:
                    //http://social.msdn.microsoft.com/Forums/en-SG/vsx/thread/8dddfb45-c119-4de0-855c-5e18a6daa89a
                    toolWindow.SetTabPicture(Resources.favicon_16.GetHbitmap());
                    toolWindow.IsFloating = false;
                    toolWindow.Linkable = true;
                }
                catch
                {
                }
            }
        }

        /// <summary>Implements the OnDisconnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being unloaded.</summary>
        /// <param term='disconnectMode'>Describes how the Add-in is being unloaded.</param>
        /// <param term='custom'>Array of parameters that are host application specific.</param>
        /// <seealso class='IDTExtensibility2' />
        public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)
        {
            if (toolWindow != null)
                toolWindow.Visible = false;
        }

        /// <summary>Implements the OnAddInsUpdate method of the IDTExtensibility2 interface. Receives notification when the collection of Add-ins has changed.</summary>
        /// <param term='custom'>Array of parameters that are host application specific.</param>
        /// <seealso class='IDTExtensibility2' />
        public void OnAddInsUpdate(ref Array custom)
        {
        }

        /// <summary>Implements the OnStartupComplete method of the IDTExtensibility2 interface. Receives notification that the host application has completed loading.</summary>
        /// <param term='custom'>Array of parameters that are host application specific.</param>
        /// <seealso class='IDTExtensibility2' />
        public void OnStartupComplete(ref Array custom)
        {
        }

        /// <summary>Implements the OnBeginShutdown method of the IDTExtensibility2 interface. Receives notification that the host application is being unloaded.</summary>
        /// <param term='custom'>Array of parameters that are host application specific.</param>
        /// <seealso class='IDTExtensibility2' />
        public void OnBeginShutdown(ref Array custom)
        {
        }

        /// <summary>Implements the QueryStatus method of the IDTCommandTarget interface. This is called when the command's availability is updated</summary>
        /// <param term='commandName'>The name of the command to determine state for.</param>
        /// <param term='neededText'>Text that is needed for the command.</param>
        /// <param term='status'>The state of the command in the user interface.</param>
        /// <param term='commandText'>Text requested by the neededText parameter.</param>
        /// <seealso class='Exec' />
        public void QueryStatus(string commandName, vsCommandStatusTextWanted neededText, ref vsCommandStatus status, ref object commandText)
        {
            if (neededText == vsCommandStatusTextWanted.vsCommandStatusTextWantedNone)
            {
                if (commandName == "GForgeTrackerAddIn.Connect.GForge")
                {
                    status = (vsCommandStatus)vsCommandStatus.vsCommandStatusSupported | vsCommandStatus.vsCommandStatusEnabled;
                    return;
                }
            }
        }

        /// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>
        /// <param term='commandName'>The name of the command to execute.</param>
        /// <param term='executeOption'>Describes how the command should be run.</param>
        /// <param term='varIn'>Parameters passed from the caller to the command handler.</param>
        /// <param term='varOut'>Parameters passed from the command handler to the caller.</param>
        /// <param term='handled'>Informs the caller if the command was handled or not.</param>
        /// <seealso class='Exec' />
        public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
        {
            handled = false;
            if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
            {
                if (commandName == "GForgeTrackerAddIn.Connect.GForge")
                {
                    handled = true;
                    // make the window reappear
                    if (toolWindow != null)
                        toolWindow.Visible = true;
                    else
                    {
                        Array custom = null;
                        this.OnConnection(Application, ext_ConnectMode.ext_cm_UISetup, AddInInstance, ref custom);
                        toolWindow.Visible = true;
                    }
                    return;
                }
            }
        }
    }
}

VSIX => Command.cs

using System;
using System.ComponentModel.Design;
using System.Globalization;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using GForgeTrackerAddIn;
using EnvDTE80;
using EnvDTE;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Reflection;
using System.Collections.Generic;
using System.Text;

namespace GForgeVSIX
{
    /// <summary>
    /// Command handler
    /// </summary>
    internal sealed class Command
    {
        Connect objConnect = new Connect();

        /// <summary>
        /// Command ID.
        /// </summary>
        public const int CommandId = 0x0100;

        /// <summary>
        /// Command menu group (command set GUID).
        /// </summary>
        public static readonly Guid CommandSet = new Guid("e5730661-67f3-4f7d-ae14-4dce82709f8a");

        /// <summary>
        /// VS Package that provides this command, not null.
        /// </summary>
        private readonly Package package;

        /// <summary>
        /// Initializes a new instance of the <see cref="Command"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        private Command(Package package)
        {
            if (package == null)
            {
                throw new ArgumentNullException("package");
            }

            this.package = package;

            OleMenuCommandService commandService = this.ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (commandService != null)
            {
                var menuCommandID = new CommandID(CommandSet, CommandId);
                var menuItem = new MenuCommand(this.MenuItemCallback, menuCommandID);
                commandService.AddCommand(menuItem);
            }
        }

        /// <summary>
        /// Gets the instance of the command.
        /// </summary>
        public static Command Instance
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the service provider from the owner package.
        /// </summary>
        private IServiceProvider ServiceProvider
        {
            get
            {
                return this.package;
            }
        }

        /// <summary>
        /// Initializes the singleton instance of the command.
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        public static void Initialize(Package package)
        {
            Instance = new Command(package);
        }

        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            Connect.Application = (DTE2)this.ServiceProvider.GetService(typeof(Connect));
            Forms.GForgeForms obj = new Forms.GForgeForms();
            obj.ShowDialog();
        }

    }
}

Getting error on double click of above given tree node (trackerView_DoubleClick) => TrackerListControl.cs which is in addin project

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using EnvDTE;
using EnvDTE80;
using GForgeTrackerAddIn.GforgeService;
using System.Diagnostics;

namespace GForgeTrackerAddIn
{
    /// <summary>
    /// Summary description for UserControl1.
    /// </summary>
    public class TrackerListControl : System.Windows.Forms.UserControl
    {
        private GForgeControl hostControl;
        private System.Windows.Forms.Panel panel;
        private System.Windows.Forms.TreeView trackerView;
        private ToolStripButton logoutButton;
        private ToolStrip toolStrip;
        private ToolStripButton refreshButton;
        private ImageList icons;
        private IContainer components;
        public Group[] projects;
        private ContextMenuStrip contextMenuStrip1;
        private ToolStripMenuItem addFolderToolStripMenuItem;
        private ToolStripMenuItem deleteFolderToolStripMenuItem;

        public ArrayList trackerWindows = new ArrayList();

        public TrackerListControl(GForgeControl host)
        {
            hostControl = host;

            // This call is required by the Windows.Forms Form Designer.
            InitializeComponent();

            // TODO: Add any initialization after the InitializeComponent call

        }

        public void LoadTrackers()
        {
            // Show visual indicators that the add-in is "working"
            Cursor.Current = Cursors.WaitCursor;

            GForgeService service = GForgeService.getInstance();

            trackerView.Nodes.Clear();
            trackerView.BeforeExpand += this.checkTreeBeforeExpand;

            try
            {
                projects = service.getProjects();

                foreach (Group project in projects)
                {

                    TreeNode projNode = new TreeNode(project.group_name);
                    projNode.ImageKey = "ProjectBMP";
                    projNode.SelectedImageKey = "ProjectBMP";
                    projNode.Tag = project;
                    //

                    trackerView.Nodes.Add(projNode);

                    // Add a trackers node to the project
                    TreeNode treeNode = new TreeNode("Trackers");
                    treeNode.ImageKey = "TrackerBMP";
                    treeNode.SelectedImageKey = "TrackerBMP";
                    treeNode.Tag = project;
                    treeNode.Nodes.Add("xxxyyyzzz123321!!!");
                    projNode.Nodes.Add(treeNode);

                    // Add a documents node to the project
                    treeNode = new TreeNode("Documents");
                    treeNode.ImageKey = "Folder";
                    treeNode.SelectedImageKey = "Folder";
                    treeNode.Tag = project;
                    projNode.Nodes.Add(treeNode);
                    treeNode.Nodes.Add("123321zzzyyyxxx!!!");


                    /*
                     * Tracker are now loaded when expanded.
                     * try {
                        Tracker[] trackers = service.getTrackers(project.group_id);
                        foreach(Tracker tracker in trackers) {
                            tracker.Group = project;
                            TreeNode trackNode = new TreeNode(tracker.Name);
                            trackNode.ImageKey = "TrackerBMP";
                            trackNode.SelectedImageKey = "TrackerBMP";
                            trackNode.Tag = tracker;
                            projNode.Nodes.Add(trackNode);
                        }
                    }
                    catch {
                    }*/
                }
            }
            catch (System.Web.Services.Protocols.SoapException e)
            {
                MessageBox.Show(e.Message, "Add-in Error");
            }
            catch (System.Net.WebException)
            {
                MessageBox.Show("Unable to connect to server", "Add-in Error");
            }
            catch (LoggedOutException)
            {
                MessageBox.Show("Not logged in: please log in.", "Add-in Error");
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        #region Component 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(TrackerListControl));
            this.panel = new System.Windows.Forms.Panel();
            this.toolStrip = new System.Windows.Forms.ToolStrip();
            this.refreshButton = new System.Windows.Forms.ToolStripButton();
            this.logoutButton = new System.Windows.Forms.ToolStripButton();
            this.trackerView = new System.Windows.Forms.TreeView();
            this.icons = new System.Windows.Forms.ImageList(this.components);
            this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.addFolderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.deleteFolderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.panel.SuspendLayout();
            this.toolStrip.SuspendLayout();
            this.contextMenuStrip1.SuspendLayout();
            this.SuspendLayout();
            //
            // panel
            //
            this.panel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.panel.Controls.Add(this.toolStrip);
            this.panel.Controls.Add(this.trackerView);
            this.panel.Location = new System.Drawing.Point(0, 0);
            this.panel.Name = "panel";
            this.panel.Size = new System.Drawing.Size(150, 150);
            this.panel.TabIndex = 0;
            //
            // toolStrip
            //
            this.toolStrip.AllowMerge = false;
            this.toolStrip.GripMargin = new System.Windows.Forms.Padding(0);
            this.toolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
            this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.refreshButton,
            this.logoutButton});
            this.toolStrip.Location = new System.Drawing.Point(0, 0);
            this.toolStrip.Name = "toolStrip";
            this.toolStrip.Size = new System.Drawing.Size(150, 25);
            this.toolStrip.TabIndex = 1;
            this.toolStrip.Text = "toolStrip1";
            //
            // refreshButton
            //
            this.refreshButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.refreshButton.Image = ((System.Drawing.Image)(resources.GetObject("refreshButton.Image")));
            this.refreshButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.refreshButton.Name = "refreshButton";
            this.refreshButton.Size = new System.Drawing.Size(23, 22);
            this.refreshButton.Text = "Refresh List";
            this.refreshButton.Click += new System.EventHandler(this.refreshButton_Click);
            //
            // logoutButton
            //
            this.logoutButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.logoutButton.Image = ((System.Drawing.Image)(resources.GetObject("logoutButton.Image")));
            this.logoutButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.logoutButton.Name = "logoutButton";
            this.logoutButton.Size = new System.Drawing.Size(23, 22);
            this.logoutButton.Text = "Log Out";
            this.logoutButton.Click += new System.EventHandler(this.logoutButton_Click);
            //
            // trackerView
            //
            this.trackerView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.trackerView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.trackerView.ForeColor = System.Drawing.SystemColors.InfoText;
            this.trackerView.ImageIndex = 0;
            this.trackerView.ImageList = this.icons;
            this.trackerView.LabelEdit = true;
            this.trackerView.Location = new System.Drawing.Point(0, 26);
            this.trackerView.Name = "trackerView";
            this.trackerView.SelectedImageIndex = 0;
            this.trackerView.Size = new System.Drawing.Size(150, 124);
            this.trackerView.TabIndex = 0;
            this.trackerView.AfterLabelEdit += new System.Windows.Forms.NodeLabelEditEventHandler(this.trackerView_AfterLabelEdit);
            this.trackerView.DoubleClick += new System.EventHandler(this.trackerView_DoubleClick);
            this.trackerView.BeforeLabelEdit += new System.Windows.Forms.NodeLabelEditEventHandler(this.trackerView_BeforeLabelEdit);
            this.trackerView.Click += new System.EventHandler(this.trackerView_Click);
            //
            // icons
            //
            this.icons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("icons.ImageStream")));
            this.icons.TransparentColor = System.Drawing.Color.Magenta;
            this.icons.Images.SetKeyName(0, "ProjectBMP");
            this.icons.Images.SetKeyName(1, "TrackerBMP");
            this.icons.Images.SetKeyName(2, "Cog");
            this.icons.Images.SetKeyName(3, "Folder");
            this.icons.Images.SetKeyName(4, "Task");
            //
            // contextMenuStrip1
            //
            this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.addFolderToolStripMenuItem,
            this.deleteFolderToolStripMenuItem});
            this.contextMenuStrip1.Name = "contextMenuStrip1";
            this.contextMenuStrip1.Size = new System.Drawing.Size(153, 70);
            //
            // addFolderToolStripMenuItem
            //
            this.addFolderToolStripMenuItem.Name = "addFolderToolStripMenuItem";
            this.addFolderToolStripMenuItem.Size = new System.Drawing.Size(137, 22);
            this.addFolderToolStripMenuItem.Text = "Add Folder";
            this.addFolderToolStripMenuItem.Click += new System.EventHandler(this.addFolder_Click);
            //
            // deleteFolderToolStripMenuItem
            //
            this.deleteFolderToolStripMenuItem.Name = "deleteFolderToolStripMenuItem";
            this.deleteFolderToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
            this.deleteFolderToolStripMenuItem.Text = "Delete Folder";
            this.deleteFolderToolStripMenuItem.Click += new System.EventHandler(this.deleteFolder_Click);
            //
            // TrackerListControl
            //
            this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(242)))), ((int)(((byte)(242)))), ((int)(((byte)(242)))));
            this.Controls.Add(this.panel);
            this.Name = "TrackerListControl";
            this.panel.ResumeLayout(false);
            this.panel.PerformLayout();
            this.toolStrip.ResumeLayout(false);
            this.toolStrip.PerformLayout();
            this.contextMenuStrip1.ResumeLayout(false);
            this.ResumeLayout(false);

        }
        #endregion

        private void logoutButton_Click(object sender, EventArgs e)
        {
            GForgeService service = GForgeService.getInstance();

            try
            {
                service.logout();
            }
            catch (System.Net.WebException)
            {
            }
            Window[] windows = (Window[])trackerWindows.ToArray(typeof(Window));
            foreach (Window w in windows)
            {
                if (w != null)
                {
                    w.Close(vsSaveChanges.vsSaveChangesNo);
                }
                trackerWindows.Remove(w);
            }
            trackerWindows.Clear();
            trackerView.Nodes.Clear();
            hostControl.ShowLogin();
        }

        private void refreshButton_Click(object sender, EventArgs e)
        {
            this.LoadTrackers();
        }

        private void trackerView_DoubleClick(object sender, EventArgs eventArgs)
        {

            TreeNode selected = trackerView.SelectedNode;

            if (selected == null || selected.Level == 0)
                return;

            if (selected.Tag.GetType() == typeof(Tracker))
            {

                Tracker tracker = (Tracker)selected.Tag;

                // Capture the selectedtext so that we can revert back
                string trackerName = selected.Text;

                // Show visual indicators that the add-in is "working"
                Cursor.Current = Cursors.WaitCursor;
                selected.Text = trackerName + " (loading...)";
                this.Refresh();

                try
                {
                    // Download the bugs - done in form load of trackercontrol now - for asynch purposes
                    //GForgeService service = GForgeService.getInstance();
                    //Bug[] bugList = service.getBugs(tracker.GroupID, tracker.ID);

                    // Add our Tracker window
                    object objTemp = null;
                    string guidstr = Guid.NewGuid().ToString("B");

                    Windows2 w = (Windows2)Connect.Application.Windows;
                    Window toolWindow = w.CreateToolWindow2(
                        Connect.AddInInstance,
                        System.Reflection.Assembly.GetExecutingAssembly().Location,
                        "GForgeTrackerAddIn.TrackerControl","GForge Trackers", guidstr, ref objTemp
                    );

                    TrackerControl control = (TrackerControl)objTemp;

                    //control.LoadTracker(toolWindow, tracker, bugList);
                    control.LoadTracker(toolWindow, tracker, null);
                    control.setTrackerListControl(this);

                    toolWindow.Caption = selected.Parent.Text + ": " + trackerName;
                    toolWindow.IsFloating = false;
                    toolWindow.Linkable = false;
                    toolWindow.Visible = true;
                    trackerWindows.Add(toolWindow);
                    selected.Expand();
                }
                catch (System.Web.Services.Protocols.SoapException e)
                {
                    MessageBox.Show(e.Message, "Add-in Error");
                }
                catch (System.Net.WebException)
                {
                    MessageBox.Show("Unable to connect to server", "Add-in Error");
                }
                catch (LoggedOutException)
                {
                    MessageBox.Show("Not logged in: please log in.", "Add-in Error");
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                    trackerView.SelectedNode.Text = trackerName;
                }
            }
            else if (selected.Tag.GetType() == typeof(gforge5.DocmanFolder))
            {

                gforge5.DocmanFolder docFolder = (gforge5.DocmanFolder)selected.Tag;

                // Capture the selectedtext so that we can revert back
                string docFolderName = selected.Text;

                // Show visual indicators that the add-in is "working"
                Cursor.Current = Cursors.WaitCursor;
                selected.Text = docFolderName + " (loading...)";
                this.Refresh();

                try
                {
                    // Add our DocFolder window
                    object objTemp = null;
                    string guidstr = Guid.NewGuid().ToString("B");

                    Windows2 w = (Windows2)Connect.Application.Windows;
                    Window toolWindow = w.CreateToolWindow2(
                        Connect.AddInInstance,
                        System.Reflection.Assembly.GetExecutingAssembly().Location,
                        "GForgeTrackerAddIn.DocFolderControl","GForge Document Folder", guidstr, ref objTemp
                    );

                    DocFolderControl control = (DocFolderControl)objTemp;

                    control.LoadDocFolder(toolWindow, docFolder);
                    control.setTrackerListControl(this);

                    toolWindow.Caption = selected.Parent.Text + ": " + docFolderName;
                    toolWindow.IsFloating = false;
                    toolWindow.Linkable = false;
                    toolWindow.Visible = true;
                    trackerWindows.Add(toolWindow);
                    selected.Expand();
                }
                catch (System.Web.Services.Protocols.SoapException e)
                {
                    MessageBox.Show(e.Message, "Add-in Error");
                }
                catch (System.Net.WebException)
                {
                    MessageBox.Show("Unable to connect to server", "Add-in Error");
                }
                catch (LoggedOutException)
                {
                    MessageBox.Show("Not logged in: please log in.", "Add-in Error");
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                    trackerView.SelectedNode.Text = docFolderName;
                }
            }

        }

        private void trackerView_Click(object sender, EventArgs eventArgs)
        {

            MouseEventArgs mea = (MouseEventArgs)eventArgs;
            if (mea.Button == MouseButtons.Right)
            {

                TreeNode selected = trackerView.GetNodeAt(mea.Location);
                trackerView.SelectedNode = selected;

                if (selected.Level == 0)
                    return;

                if (selected.Tag.GetType() == typeof(gforge5.DocmanFolder))
                {
                    contextMenuStrip1.Show((Control)sender, mea.Location);
                    deleteFolderToolStripMenuItem.Enabled = true;
                }
                else if(selected.Tag.GetType() == typeof(Group) && selected.Text=="Documents")
                {
                    checkTreeBeforeExpand(selected);
                    deleteFolderToolStripMenuItem.Enabled = false;
                    contextMenuStrip1.Show((Control)sender, mea.Location);
                }
            }

        }

        private void addFolder_Click(object sender, EventArgs e)
        {
            TreeNode selected = trackerView.SelectedNode;

            if (selected.Level == 0)
                return;

            if (selected.Tag.GetType() == typeof(gforge5.DocmanFolder))
            {
                gforge5.DocmanFolder docParentFolder = (gforge5.DocmanFolder) selected.Tag;
                gforge5.DocmanFolder docFolder = new gforge5.DocmanFolder();
                docFolder.folder_name="New Folder";
                docFolder.docman_folder_id = 0;
                docFolder.project_id = docParentFolder.project_id;
                docFolder.parent_folder_id = docParentFolder.docman_folder_id;
                docFolder.sort_order = docParentFolder.sort_order;

                TreeNode docNode = new TreeNode(docFolder.folder_name);
                docNode.ImageKey = "Folder";
                docNode.SelectedImageKey = "Folder";
                docNode.Tag = docFolder;

                selected.Nodes.Add(docNode);
                selected.Expand();
                trackerView.SelectedNode = docNode;

                docNode.BeginEdit();

                //gforge5.DocmanFolder docFolder = (gforge5.DocmanFolder)selected.Tag;

            }
            else if (selected.Tag.GetType() == typeof(Group) && selected.Text == "Documents")
            {
                Group project = (Group)selected.Tag;
                gforge5.DocmanFolder docFolder = new gforge5.DocmanFolder();
                docFolder.folder_name = "New Folder";
                docFolder.docman_folder_id = 0;
                docFolder.project_id = project.group_id;
                docFolder.parent_folder_id = 0;
                docFolder.sort_order = 0;

                TreeNode docNode = new TreeNode(docFolder.folder_name);
                docNode.ImageKey = "Folder";
                docNode.SelectedImageKey = "Folder";
                docNode.Tag = docFolder;

                selected.Nodes.Add(docNode);
                selected.Expand();
                trackerView.SelectedNode = docNode;

                docNode.BeginEdit();
            }
        }

        private void checkTreeBeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            TreeNode currNode = e.Node;
            checkTreeBeforeExpand(currNode);
        }

        private void checkTreeBeforeExpand(TreeNode currNode)
        {
            if (currNode.Tag.GetType() == typeof(Group))
            {
                if (currNode.Nodes.Count == 1 && currNode.Nodes[0].Text == "xxxyyyzzz123321!!!")
                {
                    currNode.Nodes.Clear();
                    Group project = (Group)currNode.Tag;
                    GForgeService service = GForgeService.getInstance();

                    try
                    {
                        Tracker[] trackers = service.getTrackers(project.group_id);
                        foreach (Tracker tracker in trackers)
                        {
                            tracker.Group = project;
                            TreeNode trackNode = new TreeNode(tracker.Name);
                            if (tracker.DataType == Tracker.ISSUE_TYPE)
                            {
                                trackNode.ImageKey = "Cog";
                                trackNode.SelectedImageKey = "Cog";
                            }
                            else
                            {
                                trackNode.ImageKey = "Task";
                                trackNode.SelectedImageKey = "Task";
                            }
                            trackNode.Tag = tracker;
                            currNode.Nodes.Add(trackNode);
                        }
                    }
                    catch
                    {
                    }
                }
                else if (currNode.Nodes.Count == 1 && currNode.Nodes[0].Text == "123321zzzyyyxxx!!!")
                {
                    currNode.Nodes.Clear();
                    Group project = (Group)currNode.Tag;
                    GForgeService service = GForgeService.getInstance();
                    gforge5.DocmanFolder[] docFolders = service.getDocmanFolders(project.group_id);
                    foreach (gforge5.DocmanFolder docFolder in docFolders)
                    {
                        TreeNode docNode = new TreeNode(docFolder.folder_name);
                        docNode.ImageKey = "Folder";
                        docNode.SelectedImageKey = "Folder";
                        docNode.Tag = docFolder;

                        if (docFolder.parent_folder_id == 0)
                        {
                            currNode.Nodes.Add(docNode);
                        }
                        else
                        {
                            foreach (TreeNode node in currNode.Nodes)
                            {
                                gforge5.DocmanFolder docf = (gforge5.DocmanFolder)node.Tag;
                                if (docf.docman_folder_id == docFolder.parent_folder_id)
                                {
                                    node.Nodes.Add(docNode);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        private void trackerView_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (e.Node.Tag.GetType() != typeof(gforge5.DocmanFolder))
            {
                e.CancelEdit=true;
            }
        }

        private void trackerView_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (e.Node.Tag.GetType() == typeof(gforge5.DocmanFolder))
            {
                gforge5.DocmanFolder docFolder = (gforge5.DocmanFolder)e.Node.Tag;
                if (e.Label != null && e.Label != "")
                {
                    docFolder.folder_name = e.Label;

                    GForgeService service = GForgeService.getInstance();

                    if (docFolder.docman_folder_id == 0)
                    {
                        docFolder.docman_folder_id = service.addDocmanFolder(docFolder.project_id, docFolder.folder_name, docFolder.is_public, docFolder.parent_folder_id, docFolder.sort_order);
                    }
                    else
                    {
                        service.updateDocmanFolder(docFolder.docman_folder_id, docFolder.folder_name, docFolder.is_public, docFolder.parent_folder_id, docFolder.sort_order);

                        //Update name in open tab
                        foreach (Window w in trackerWindows)
                        {
                            if (w.Object.GetType() == typeof(DocFolderControl))
                            {
                                DocFolderControl dfc = (DocFolderControl)w.Object;
                                if (dfc.docFolder.docman_folder_id == docFolder.docman_folder_id)
                                {
                                    w.Caption = e.Node.Parent.Text + ": " + docFolder.folder_name;
                                }
                            }
                        }
                    }
                }
            }
        }

        private void deleteFolder_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure?", "Delete Folder and subfolders", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                TreeNode selected = trackerView.SelectedNode;

                if (selected.Level == 0)
                    return;

                GForgeService service = GForgeService.getInstance();

                if (selected.Tag.GetType() == typeof(gforge5.DocmanFolder))
                {
                    gforge5.DocmanFolder docFolder = (gforge5.DocmanFolder) selected.Tag;
                    service.deleteDocmanFolder(docFolder.docman_folder_id);
                    removeFolderAndFilesWindows(selected);
                    selected.Remove();
                }
            }
        }

        private void removeFolderAndFilesWindows(TreeNode node)
        {
            //Remove all files and folders that were in there.
            gforge5.DocmanFolder docFolder = (gforge5.DocmanFolder)node.Tag;
            foreach (Window w in trackerWindows)
            {
                if (w.Object.GetType() == typeof(DocFileViewControl))
                {
                    DocFileViewControl dfvc = (DocFileViewControl)w.Object;
                    if (dfvc.docFile.docman_folder_id == docFolder.docman_folder_id)
                    {
                        w.Close(vsSaveChanges.vsSaveChangesNo);
                    }
                }
                else if (w.Object.GetType() == typeof(DocFolderControl))
                {
                    DocFolderControl dfc = (DocFolderControl)w.Object;
                    if (dfc.docFolder.docman_folder_id == docFolder.docman_folder_id)
                    {
                        w.Close(vsSaveChanges.vsSaveChangesNo);
                    }
                }
            }

            foreach (TreeNode n in node.Nodes) removeFolderAndFilesWindows(n);
        }
    }
}

http://stackoverflow.com/questions/35913376/vs2013-addin-into-vs2015-vspackage-how-can-i-create-toolwindow2


Viewing all articles
Browse latest Browse all 4410

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>