Feeds:
Posts
Comments

I bought a refurbished vaio NR38M earlier 2 months ago. It is a nice laptop with good price and has Vista installed with lots of other programs. I wanted to use Windows 7 on it, and usually windows 7 performs better than Vista.

I can find all drivers, but it is very difficult to find a utility programs that enable keyboard function key. I don’t understand why Sony did in this way, using special program to enable function key.

A day later, I found that the above drivers page has links to Vaio’s driver and utility repository ftp.

You can see all originally installed drivers and utilities. Keyboard shortcuts are manaaged by a program called “Vaio Event Service.” I managed to figure it out using process explorer, thought some other guys on Internet already mentioned it. You can find Event service installation program from the above ftp link. I tried a seeminglyl latest one

옛날에 마소에 기고했던 글인데 인터넷에 pdf 파일이 떠돌기에 아예 내 블로그에 올려버렸다. 마침 동아일보의 손영일 기자님과 우연한 기회에 인터뷰도 하게되기도 했고.

I have installed office 2007, but the product key was used too many times, and the office failed in activation. I received another product key, but was not sure if I could change it wihtout reinstalling it. A simple google search takes me to http://bloggingabout.net/blogs/mglaser/archive/2006/12/12/Change-Office-2007-Product-Key.aspx. I tried and succeeded in changing the product key and activation. Thanks google.

References

Since last year, I have used Selenium IDE and core. I love Selenium IDE as it is so easy and handy to record the test cases and also to run test cases one by one by clicking on it. A colleague of mine used Selenium RC with C# but it did not impress me much because he started RC server first, then executed NUnit to lanuch the test suite. Also, I did not like coding in C# selenium test cases. How simple and elegant those html test caes are!

Then today, a bit shame to say, I realised I can use html test suite on Selenium RC. Oh how fantastic Selenium RC is. My scrum team had scores of accumulated html test cases, and we can use them as they are.

First, let’s see how to install Selenium RC

  1. You download Selenium RC from http://seleniumhq.org/download/
  2. Unzip it into local hard drive, for example, c:\Selenium. Because Selenium RC is written in Java, you need to install java runtime if you do not have it.

selenium-server.jar is the main engine that runs test suite. You can run it on command prompt, but it is very handy to create a batch file to run it as the above reference link showes it.

For IE

cd \
cd C:\Selenium\selenium-server-1.0-beta-2
java -jar selenium-server.jar -port 4545  -htmlSuite *iehta "http://www.sekyee.com" "C:\Selenium\Test_Suite.html" "C:\Selenium\Results.html"
pause

For firefox


cd \
cd C:\Selenium\selenium-server-1.0-beta-2
java -jar selenium-server.jar -port 4545  -htmlSuite *chrome "http://www.totaljobs.com" "C:\Selenium\Test_Suite.html" "C:\Selenium\Results.html"
pause  

A simple selenium-server.jar usage is like this.
selenium-server.jar -port {your port number} -htmlSuite {firefox or ie} {base url} {absolute path for your test suite} {absolute path for your test result file}

I’m not sure why * is required befire iehta, yet without the *, it does not find testsuite. Also, Results.html must exist before you run this even though it is an empty file.
I find {base url} very handly, so you can put relative path in your test cases. This enables you to use the same test cases to test on different environments such as Dev, Int, Staging, and Live.

Hoep this helps

References

SEO is becoming more and more important issue these days, and your site root url can lose its SEO rank if there are too many different query string attached such as www.yoursite.com/?a=b&b=c and www.yoursite.com/default.aspx?wt=129. It will be nice you can keep the site root clean lik www.yoursite.com

My company employed Scrum from this year and in March sprint, the above was one of the user stories I worked on.

The implementation logic is like this

  • If the url has any query string, store query string values into cookie and redirect it to site root without query string.
  • If there is no query string, then check if cookie has any query string. If the cookie exists, then manually populate Request.QueryString object with the values from cookie.

One tricky bit is Request.QueryString is read only property. So you need to find a private value that the property uses inside. I could do that using .Net reflector and it is _queryString. Using Reflection, you can set the value of a private variable.

The followings are the codes I wrote for this. Of course, I could not write this without the help from the above links.

        protected override void OnInit(EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString.Count > 0)
                    RedirectToCleanSiteRootUrl();

                if(Request.Cookies["QS"]!= null)
                    PopulateQueryStringFromCookie();
            }

            base.OnInit (e);
        }

        private void RedirectToCleanSiteRootUrl()
        {
            HttpCookie cookie = new HttpCookie(“QS”);
            foreach (string key in Request.QueryString.AllKeys)
            {
                cookie.Values[key] = Request.QueryString[key];
                cookie.Expires = DateTime.Now.AddDays(1d);
            }
            Response.Cookies.Add(cookie);

            PageUtility.RedirectPermanent(“/”);
        }

        private void PopulateQueryStringFromCookie()
        {
            NameValueCollection collection = (NameValueCollection) Request.GetType().GetField(“_queryString”,
                BindingFlags.NonPublic | BindingFlags.Instance).GetValue(Request);
            PropertyInfo readOnlyInfo = collection.GetType().GetProperty(“IsReadOnly”,
                BindingFlags.NonPublic | BindingFlags.Instance);
            readOnlyInfo.SetValue(collection,false,null);

            collection.Add(Request.Cookies["QS"].Values);
            Response.Cookies["QS"].Expires = DateTime.Now.AddDays(-1d);
        }

Resources

I work for one of the popular job board companies and we still have some many projects written in .Net 1.1. I often use Visual Studio 2003, and whenever I use it, I miss all handy commands on Visual Studio 2008 such as “Open the containing folder.”As a developer who loves developing small program for his use, I myself finally decided to add “Open the containing folder” and a few other stuff to Visual Studio 2003.

First, you have to figure out the window name. You can do that using “Command Browser” which is one of those useful visual studio.net add-on development samples. The name for source code editor tab is “Easy MDI Document Window.”

Opening a folder is relatively easy. You can just call Process.Start like this

System.Diagnostics.Process.Start(_application.ActiveDocument.Path);

The tricky thing was to add command to the tab. I used AddNamedCommand(…). Often, it returned an error similar to “The name already exists” error. So, I tried commands.Item(…) to check if the command already exist, yet this returned an error if the command does not exsit. I had to next try and catch blocks on connect.

try
{
    _iisRecycleCommand = commands.Item(“ExtVS2003.Connect.ExtVS2003″, -1);
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
    try
    {
        if (_iisRecycleCommand == null)
        {
            _iisRecycleCommand = commands.AddNamedCommand(addInInstance, “ExtVS2003″, “Recycle IIS App pools”, “Reset IIS”, true, bitmapNo,
                ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported+(int)vsCommandStatus.vsCommandStatusEnabled);
            CommandBar cbTools = commandBars["Tools"];
            //commandBars["Tools"].Controls[0].Caption
            CommandBarControl cbcTools = _iisRecycleCommand.AddControl(cbTools, 1);
        }
    }
    catch (Exception ex) { Console.WriteLine(ex.Message);}
}

try
{
    _openContainingFolderCommand = commands.Item(“ExtVS2003.Connect.OpenContainingFolder”, -1);
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
    try
    {
        if (_openContainingFolderCommand == null)
        {
            _openContainingFolderCommand = commands.AddNamedCommand(addInInstance, “OpenContainingFolder”, “Open the containing folder”,
                “Open the containing folder”, true, 0, ref contextGUIDS,
                (int) vsCommandStatus.vsCommandStatusSupported +
                (int) vsCommandStatus.vsCommandStatusEnabled);
            CommandBar cbEasyMDIWindow = commandBars["Easy MDI Document Window"];
            CommandBarControl cbcEasyMDIWIndow = _openContainingFolderCommand.AddControl(cbEasyMDIWindow, 1);
        }
    }
    catch (Exception ex) { Console.WriteLine(ex.Message);}
}

It finally works now and this is the full source code

using System.DirectoryServices;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace ExtVS2003
{
    using System;
    using Microsoft.Office.Core;
    using Extensibility;
    using System.Runtime.InteropServices;
    using EnvDTE;

    #region Read me for Add-in installation and setup information.
    // When run, the Add-in wizard prepared the registry for the Add-in.
    // At a later time, if the Add-in becomes unavailable for reasons such as:
    //   1) You moved this project to a computer other than which is was originally created on.
    //   2) You chose ‘Yes’ when presented with a message asking if you wish to remove the Add-in.
    //   3) Registry corruption.
    // you will need to re-register the Add-in by building the MyAddin21Setup project
    // by right clicking the project in the Solution Explorer, then choosing install.
    #endregion

    ///


    ///   The object for implementing an Add-in.
    ///

    ///
    [GuidAttribute("594C22F4-C9ED-40B1-9CC7-2D095D68AD97"), ProgId("ExtVS2003.Connect")]
    public class Connect : Object, IDTExtensibility2, IDTCommandTarget
    {
        const string OUTPUTWINDOWGUID = “{1BD8A850-02D1-11D1-BEE7-00A0C913D1F8}”;
        private _DTE _application;
        private AddIn addInInstance;
        private Command _iisRecycleCommand, _openContainingFolderCommand;
        private OutputWindowPane _outputWindowPane;
        private BuildEvents _buildEvents;

        ///


        ///        Implements the constructor for the Add-in object.
        ///        Place your initialization code within this method.
        ///

        public Connect()
        {
        }

        ///


        ///      Implements the OnConnection method of the IDTExtensibility2 interface.
        ///      Receives notification that the Add-in is being loaded.
        ///

        ///

        ///      Root object of the host application.
        ///         ///

        ///      Describes how the Add-in is being loaded.
        ///         ///

        ///      Object representing this Add-in.
        ///         ///
        public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
        {
            int bitmapNo = 59;
            _application = (_DTE)application;
            addInInstance = (AddIn)addInInst;

            SetBuildEvent();
            SetOutputWindowPane();

            if (connectMode == ext_ConnectMode.ext_cm_Startup)
            {
                object []contextGUIDS = new object[] { };
                Commands commands = _application.Commands;
                _CommandBars commandBars = _application.CommandBars;

                // When run, the Add-in wizard prepared the registry for the Add-in.
                // At a later time, the Add-in or its commands may become unavailable for reasons such as:
                //   1) You moved this project to a computer other than which is was originally created on.
                //   2) You chose ‘Yes’ when presented with a message asking if you wish to remove the Add-in.
                //   3) You add new commands or modify commands already defined.
                // You will need to re-register the Add-in by building the ExtVS2003Setup project,
                // right-clicking the project in the Solution Explorer, and then choosing install.
                // Alternatively, you could execute the ReCreateCommands.reg file the Add-in Wizard generated in
                // the project directory, or run ‘devenv /setup’ from a command prompt.
                try
                {

                    try
                    {
                        _iisRecycleCommand = commands.Item(“ExtVS2003.Connect.ExtVS2003″, -1);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        try
                        {
                            if (_iisRecycleCommand == null)
                            {
                                _iisRecycleCommand = commands.AddNamedCommand(addInInstance, “ExtVS2003″, “Recycle IIS App pools”, “Reset IIS”, true, bitmapNo,
                                    ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported+(int)vsCommandStatus.vsCommandStatusEnabled);
                                CommandBar cbTools = commandBars["Tools"];
                                //commandBars["Tools"].Controls[0].Caption
                                CommandBarControl cbcTools = _iisRecycleCommand.AddControl(cbTools, 1);
                            }
                        }
                        catch (Exception ex) { Console.WriteLine(ex.Message);}
                    }

                    try
                    {
                        _openContainingFolderCommand = commands.Item(“ExtVS2003.Connect.OpenContainingFolder”, -1);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        try
                        {
                            if (_openContainingFolderCommand == null)
                            {
                                _openContainingFolderCommand = commands.AddNamedCommand(addInInstance, “OpenContainingFolder”, “Open the containing folder”,
                                    “Open the containing folder”, true, 0, ref contextGUIDS,
                                    (int) vsCommandStatus.vsCommandStatusSupported +
                                    (int) vsCommandStatus.vsCommandStatusEnabled);
                                CommandBar cbEasyMDIWindow = commandBars["Easy MDI Document Window"];
                                CommandBarControl cbcEasyMDIWIndow = _openContainingFolderCommand.AddControl(cbEasyMDIWindow, 1);
                            }
                        }
                        catch (Exception ex) { Console.WriteLine(ex.Message);}
                    }

                }
                catch(Exception ex)
                {
                    MessageBox.Show(“Cant’t place toolbutton, error: ” + ex.Message, “error”, MessageBoxButtons.OK);
                }
            }

        }

        private void SetOutputWindowPane()
        {
            OutputWindow outputWindow = (OutputWindow)_application.Windows.Item(Constants.vsWindowKindOutput).Object;
            _outputWindowPane = outputWindow.OutputWindowPanes.Item(OUTPUTWINDOWGUID);
        }

        private void SetBuildEvent()
        {
            _buildEvents = _application.Events.BuildEvents;
            _buildEvents.OnBuildDone += new _dispBuildEvents_OnBuildDoneEventHandler(_buildEvents_OnBuildDone);
            _buildEvents.OnBuildProjConfigDone += new _dispBuildEvents_OnBuildProjConfigDoneEventHandler(_buildEvents_OnBuildProjConfigDone);
        }

        ///


        ///     Implements the OnDisconnection method of the IDTExtensibility2 interface.
        ///     Receives notification that the Add-in is being unloaded.
        ///

        ///

        ///      Describes how the Add-in is being unloaded.
        ///         ///

        ///      Array of parameters that are host application specific.
        ///         ///
        public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)
        {
            try
            {
                _iisRecycleCommand.Delete();
                _openContainingFolderCommand.Delete();
            }
            catch (Exception ex)
            {
                MessageBox.Show(“Error in Disconnect: ” + ex.Message, “Error”, MessageBoxButtons.OK);
            }

        }

        ///


        ///      Implements the OnAddInsUpdate method of the IDTExtensibility2 interface.
        ///      Receives notification that the collection of Add-ins has changed.
        ///

        ///

        ///      Array of parameters that are host application specific.
        ///         ///
        public void OnAddInsUpdate(ref Array custom)
        {
        }

        ///


        ///      Implements the OnStartupComplete method of the IDTExtensibility2 interface.
        ///      Receives notification that the host application has completed loading.
        ///

        ///

        ///      Array of parameters that are host application specific.
        ///         ///
        public void OnStartupComplete(ref Array custom)
        {
        }

        ///


        ///      Implements the OnBeginShutdown method of the IDTExtensibility2 interface.
        ///      Receives notification that the host application is being unloaded.
        ///

        ///

        ///      Array of parameters that are host application specific.
        ///         ///
        public void OnBeginShutdown(ref Array custom)
        {
        }

        ///


        ///      Implements the QueryStatus method of the IDTCommandTarget interface.
        ///      This is called when the command’s availability is updated
        ///

        ///

        ///        The name of the command to determine state for.
        ///         ///

        ///        Text that is needed for the command.
        ///         ///

        ///        The state of the command in the user interface.
        ///         ///

        ///        Text requested by the neededText parameter.
        ///         ///
        public void QueryStatus(string commandName, vsCommandStatusTextWanted neededText, ref vsCommandStatus status, ref object commandText)
        {
            if(neededText == vsCommandStatusTextWanted.vsCommandStatusTextWantedNone)
            {
                switch (commandName)
                {
                    case “ExtVS2003.Connect.ExtVS2003″:
                        status = (vsCommandStatus)vsCommandStatus.vsCommandStatusSupported|vsCommandStatus.vsCommandStatusEnabled;
                        break;

                    case “ExtVS2003.Connect.OpenContainingFolder”:
                        status  = (vsCommandStatus)vsCommandStatus.vsCommandStatusSupported|vsCommandStatus.vsCommandStatusEnabled;
                        break;
                }
            }
        }

        ///


        ///      Implements the Exec method of the IDTCommandTarget interface.
        ///      This is called when the command is invoked.
        ///

        ///

        ///        The name of the command to execute.
        ///         ///

        ///        Describes how the command should be run.
        ///         ///

        ///        Parameters passed from the caller to the command handler.
        ///         ///

        ///        Parameters passed from the command handler to the caller.
        ///         ///

        ///        Informs the caller if the command was handled or not.
        ///         ///
        public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
        {
            handled = false;
            if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
            {
                switch (commandName)
                {
                    case “ExtVS2003.Connect.ExtVS2003″:
                        RecycleAllApplicationPools();
                        handled = true;
                        break;

                    case “ExtVS2003.Connect.OpenContainingFolder”:
                        OpenContainingFolder();
                        handled = true;
                        break;
                }
            }
        }

        private void OpenContainingFolder()
        {
            System.Diagnostics.Process.Start(_application.ActiveDocument.Path);
        }

        private void _buildEvents_OnBuildDone(vsBuildScope Scope, vsBuildAction Action)
        {
            if (IsBuildingGACProject())
            {
                RecycleAllApplicationPools();
            }
        }

        private void _buildEvents_OnBuildProjConfigDone(string Project, string ProjectConfig, string Platform, string SolutionConfig,
            bool Success)
        {
            if (!Success)
            {
                _application.ExecuteCommand(“Build.Cancel”, string.Empty);
            }
        }

        private bool IsBuildingGACProject()
        {
            Regex GACRegex = new Regex(“PJB.UI|PJB.Business”, RegexOptions.IgnoreCase);
            Projects projects = _application.Solution.Projects;

            foreach (Project project in projects)
            {
                if (GACRegex.Match(project.Name).Success)
                {
                    return true;
                }
            }
            return false;
        }

        private void RecycleAllApplicationPools()
        {
            DirectoryEntry appPools = new DirectoryEntry(“IIS://localhost/W3SVC/AppPools”);
            _outputWindowPane.OutputString(“——————————————-\n”);
            _outputWindowPane.OutputString(“Start recycling application pools.”);
            foreach (DirectoryEntry appPool in appPools.Children)
            {
                appPool.Invoke(“Recycle”, null);
                _outputWindowPane.OutputString(“.”);
            }
            _outputWindowPane.OutputString(” completed.\n”);
        }

    }
}

Today, I had an automated build failure on the test server. I spent half a day to fix the issue and discovered that someone changed the CopyLocal property of reference to false. Of course, if you reference a dll in GAC, you need to set it to false, so that you reference the dll in GAC. But if you reference another project within the same solution, you need to set it to true. Setting CopyLocal to false locks the dll and often project build fails because the output dll cannot be overwritten. To me, referencing another project in the same solution and setting the property to false is plainly wrong.

I googled a little bit and came with the following guideline. (MSDN CopyLocal property)

  • if the reference is another project within the same solution, set it to true.
  • if the referenced assembly is in GAC (Global Assembly Cache), set it to false
  • As a special case, the value for the mscorlib.dll reference is false.
  • If the assembly is found in the Framework SDK folder, then the value is false.

Hope this is clear.

Often, I need to deploy an website change to a production server. It can be a simple change like creating a virtual directory and rather rarely very big like setting up a new site. We export iis website setting, delete everything but the change, and import the change using vbscript.  The command is like this.

Set IIsComputer = GetObject("winmgmts://localhost/root/MicrosoftIISv2:IIsComputer='LM'")
...
IIsComputer.Import "", strFilePath, strSourceMetabasePath, strDestinationMetabasePath, intFlags

The xml file only contains the part that changed and has a basic skeleton tags

<?xml version="1.0" ?>
<configuration xmlns="urn:microsoft-catalog:XML_Metabase_V64_0">
<MBProperty>
<IIS_Global	Location ="."
		SessionKey="......."
	>
</IIS_Global>
<IIsWebServer	Location ="/LM/W3SVC/00"></IIsWebServer>
<IIsWebDirectory	Location ="/LM/W3SVC/00/ROOT/jsk"
   ...
	>
</IIsWebDirectory>
</MBProperty>
</configuration>

마침 김창준님의 블로그 RSS를 구독하던 터라 김창준님의 presentation을 보게 되었습니다. 많은 생각을 하게 하는 presentation이였습니다. 먼저 presentation zen을 언급하셨는데, 저역시 이책을 읽고 이에 따라 prensetation을 하려고 애쓰던 중이라 약간 뜨끔했습니다. 하지만 창준님이 가지고 나오신 한장 짜리 슬라이드는 동영상으로는 눈에 잘 안들어 오더군요. 역시 슬라이드에는 그림이나 사진이 들어가야 제맛인게 아닐까요?^^

엥겔바르트와 Allan Kay. 개발자이지만 저도 잘 몰랐다는 사실이 좀 부끄럽습니다. 컴퓨터와 붓 (혹은 연필)이 같은 도구라는 그런 명언을 알란 케이가 했다니. 확 깨는, 생각이 전환되는 순가이었습니다. Kay가 말했던 것처럼 컴퓨터를 똑똑하게 하는 것보다 컴퓨터를 통해 사람이 똑똑해지는 것이 올바른 방향이요, 무궁무진한 가능성이 있는 방향이란 생각이 듭니다.

쉬운 것을 하는 것, 어려운 것을 하는 것, 불가능한 것을 하는 것보다 더 위의 단계가 아무도 생각하지 못했던 (혹은 않았던) 것을 하는 것이란 말에 다시 한번 무릎을 치게 되었습니다. 정말 맞는 말인 것 같습니다. 비즈니스를 하시는 아는 분을 위해 Invoice를 관리할 수 있는 간단한 웹 애플리케이션을 만들고 있는 중인데, 단순히 게시판을 만들게 아니라 wiki의 개념을 도입하여 의사소통을 도와주는 프로그램을 만들어야 겠다는 생각이 들었습니다.

“어떻게 하고 싶다는 것보다 무엇을 왜 하고 싶은지를 알려달라” 이 말도 가슴에 와 닿았습니다. 그냥 뻔한 길을 따라가기 보다 진정으로 내가 원하는 것을 이룰 수 있는 길을 찾아야 겠다는 생각이 들었습니다.

비영리 단체를 찾아가며 강의하시는 모습도 좋았습니다. 저도 제 삶의 일부를 그런식으로 사회에 공헌하고 싶습니다.

“삶의 진정한 전장은 집이다” 외부와 무엇인가를 하기전에 먼저 자신을, 내부를 똑똑하게 만들라는 말에 깊이 공감하였습니다. 특히 외부와의 소통을 위한 홈페이지를 만들기 전에 먼저 내부의 소통을 위해 위키를 사용한 예는 정말 마음에 들었습니다. 저도 먼저 남편과 아빠로서 자신을 갈고 닦아야 할 것 같습니다.

30분이지만 많은 것들에 대해 생각하도록 해주는 멋진 presentation이였습니다.

This is my 2nd visual studio-in. What it does is to recycle all application pools in IIS to make sure GAC is refreshed with newly built dlls.

There were a few things to tweak. This is an add-in for visual studio 2003, so it may not be suitable for vs 2005 or 2008 in some details.

  1. connectMode == ext_ConnectMode.ext_cm_Startup
    When the add-in wizard creates the skeleton code, ext_ConnectMode.ext_cm_UISetup is used. UISetup is only once when you set up the add-in, so the add-in is not loaded when you run this in debug-mode. Change it to …_Startup.
  2. _application.Solution.Projects
    In order to get projects I first tried ActiveSolutionProjects which worked perfectly fine in vs macro, but it did not work at all in add-in. ActiveSolutionProjects returned null if you build a solution. It returned only one project if you build a specific project. I used Solution.Projects and it worked as it is expected.

This is the code for recycling application pools.

private void RecycleAllApplicationPools()
{
    DirectoryEntry appPools = new DirectoryEntry(“IIS://localhost/W3SVC/AppPools”);
    _outputWindowPane.OutputString(“——————————————-\n”);
    _outputWindowPane.OutputString(“Start recycling application pools\n”);
    foreach (DirectoryEntry appPool in appPools.Children)
    {
        appPool.Invoke(“Recycle”, null);
        _outputWindowPane.OutputString(“.”);
    }
    _outputWindowPane.OutputString(“\nRecycling is complete.\n”);
}

The following is the full code

using System.DirectoryServices;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace ExtVS2003
{
using System;
using Microsoft.Office.Core;
using Extensibility;
using System.Runtime.InteropServices;
using EnvDTE;

#region Read me for Add-in installation and setup information.
// When run, the Add-in wizard prepared the registry for the Add-in.
// At a later time, if the Add-in becomes unavailable for reasons such as:
//   1) You moved this project to a computer other than which is was originally created on.
//   2) You chose ‘Yes’ when presented with a message asking if you wish to remove the Add-in.
//   3) Registry corruption.
// you will need to re-register the Add-in by building the MyAddin21Setup project
// by right clicking the project in the Solution Explorer, then choosing install.
#endregion

///


///   The object for implementing an Add-in.
///

///
[GuidAttribute("594C22F4-C9ED-40B1-9CC7-2D095D68AD97"), ProgId("ExtVS2003.Connect")]
public class Connect : Object, IDTExtensibility2, IDTCommandTarget
{
    const string OUTPUTWINDOWGUID = “{1BD8A850-02D1-11D1-BEE7-00A0C913D1F8}”;
    private _DTE _application;
    private AddIn addInInstance;
    private Command _command;
    private OutputWindowPane _outputWindowPane;
    private BuildEvents _buildEvents;

    ///


    ///        Implements the constructor for the Add-in object.
    ///        Place your initialization code within this method.
    ///

    public Connect()
    {
    }

    ///


    ///      Implements the OnConnection method of the IDTExtensibility2 interface.
    ///      Receives notification that the Add-in is being loaded.
    ///

    ///

    ///      Root object of the host application.
    ///     ///

    ///      Describes how the Add-in is being loaded.
    ///     ///

    ///      Object representing this Add-in.
    ///     ///
    public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
    {
        int bitmapNo = 59;
        _application = (_DTE)application;
        addInInstance = (AddIn)addInInst;

        SetBuildEvent();
        SetOutputWindowPane();

        if (connectMode == ext_ConnectMode.ext_cm_Startup)
        {
            object []contextGUIDS = new object[] { };
            Commands commands = _application.Commands;
            _CommandBars commandBars = _application.CommandBars;

            // When run, the Add-in wizard prepared the registry for the Add-in.
            // At a later time, the Add-in or its commands may become unavailable for reasons such as:
            //   1) You moved this project to a computer other than which is was originally created on.
            //   2) You chose ‘Yes’ when presented with a message asking if you wish to remove the Add-in.
            //   3) You add new commands or modify commands already defined.
            // You will need to re-register the Add-in by building the ExtVS2003Setup project,
            // right-clicking the project in the Solution Explorer, and then choosing install.
            // Alternatively, you could execute the ReCreateCommands.reg file the Add-in Wizard generated in
            // the project directory, or run ‘devenv /setup’ from a command prompt.
            try
            {
                _command = commands.AddNamedCommand(addInInstance, “ExtVS2003″, “Recycle IIS App pools”, “Reset IIS”, true, bitmapNo,
                    ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported+(int)vsCommandStatus.vsCommandStatusEnabled);
                CommandBar commandBar = commandBars["Tools"];
                CommandBarControl commandBarControl = _command.AddControl(commandBar, 1);
            }
            catch(Exception ex)
            {
                MessageBox.Show(“Cant’t place toolbutton, error: ” + ex.Message, “error”, MessageBoxButtons.OK);
            }
        }

    }

    private void SetOutputWindowPane()
    {
        OutputWindow outputWindow = (OutputWindow)_application.Windows.Item(Constants.vsWindowKindOutput).Object;
        _outputWindowPane = outputWindow.OutputWindowPanes.Item(OUTPUTWINDOWGUID);
    }

    private void SetBuildEvent()
    {
        _buildEvents = _application.Events.BuildEvents;
        _buildEvents.OnBuildDone += new _dispBuildEvents_OnBuildDoneEventHandler(_buildEvents_OnBuildDone);
    }

    ///


    ///     Implements the OnDisconnection method of the IDTExtensibility2 interface.
    ///     Receives notification that the Add-in is being unloaded.
    ///

    ///

    ///      Describes how the Add-in is being unloaded.
    ///     ///

    ///      Array of parameters that are host application specific.
    ///     ///
    public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)
    {
        try
        {
            _command.Delete();
        }
        catch (Exception ex)
        {
            MessageBox.Show(“Error in Disconnect: ” + ex.Message, “Error”, MessageBoxButtons.OK);
        }

    }

    ///


    ///      Implements the OnAddInsUpdate method of the IDTExtensibility2 interface.
    ///      Receives notification that the collection of Add-ins has changed.
    ///

    ///

    ///      Array of parameters that are host application specific.
    ///     ///
    public void OnAddInsUpdate(ref Array custom)
    {
    }

    ///


    ///      Implements the OnStartupComplete method of the IDTExtensibility2 interface.
    ///      Receives notification that the host application has completed loading.
    ///

    ///

    ///      Array of parameters that are host application specific.
    ///     ///
    public void OnStartupComplete(ref Array custom)
    {
    }

    ///


    ///      Implements the OnBeginShutdown method of the IDTExtensibility2 interface.
    ///      Receives notification that the host application is being unloaded.
    ///

    ///

    ///      Array of parameters that are host application specific.
    ///     ///
    public void OnBeginShutdown(ref Array custom)
    {
    }

    ///


    ///      Implements the QueryStatus method of the IDTCommandTarget interface.
    ///      This is called when the command’s availability is updated
    ///

    ///

    ///        The name of the command to determine state for.
    ///     ///

    ///        Text that is needed for the command.
    ///     ///

    ///        The state of the command in the user interface.
    ///     ///

    ///        Text requested by the neededText parameter.
    ///     ///
    public void QueryStatus(string commandName, vsCommandStatusTextWanted neededText, ref vsCommandStatus status, ref object commandText)
    {
        if(neededText == vsCommandStatusTextWanted.vsCommandStatusTextWantedNone)
        {
            if(commandName == “ExtVS2003.Connect.ExtVS2003″)
            {
                status = (vsCommandStatus)vsCommandStatus.vsCommandStatusSupported|vsCommandStatus.vsCommandStatusEnabled;
            }
        }
    }

    ///


    ///      Implements the Exec method of the IDTCommandTarget interface.
    ///      This is called when the command is invoked.
    ///

    ///

    ///        The name of the command to execute.
    ///     ///

    ///        Describes how the command should be run.
    ///     ///

    ///        Parameters passed from the caller to the command handler.
    ///     ///

    ///        Parameters passed from the command handler to the caller.
    ///     ///

    ///        Informs the caller if the command was handled or not.
    ///     ///
    public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
    {
        handled = false;
        if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
        {
            if(commandName == “ExtVS2003.Connect.ExtVS2003″)
            {
                RecycleAllApplicationPools();
                handled = true;
                return;
            }
        }
    }

    private void _buildEvents_OnBuildDone(vsBuildScope Scope, vsBuildAction Action)
    {
        if (IsBuildingGACProject())
        {
            RecycleAllApplicationPools();
        }
    }

    private bool IsBuildingGACProject()
    {
        Regex GACRegex = new Regex(“PJB.UI|PJB.Business”, RegexOptions.IgnoreCase);
        Projects projects = _application.Solution.Projects;

        foreach (Project project in projects)
        {
            if (GACRegex.Match(project.Name).Success)
            {
                return true;
            }
        }
        return false;
    }

    private void RecycleAllApplicationPools()
    {
        DirectoryEntry appPools = new DirectoryEntry(“IIS://localhost/W3SVC/AppPools”);
        _outputWindowPane.OutputString(“——————————————-\n”);
        _outputWindowPane.OutputString(“Start recycling application pools\n”);
        foreach (DirectoryEntry appPool in appPools.Children)
        {
            appPool.Invoke(“Recycle”, null);
            _outputWindowPane.OutputString(“.”);
        }
        _outputWindowPane.OutputString(“\nRecycling is complete.\n”);
    }
}
}

« Newer Posts - Older Posts »