Advertisement
Guest User

Untitled

a guest
Jun 20th, 2009
527
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.51 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Drawing;
  5. using System.IO;
  6. using System.Net;
  7. using System.Reflection;
  8. using System.Windows.Forms;
  9. using EnvDTE;
  10. using Extensibility;
  11. using Microsoft.VisualStudio.CommandBars;
  12.  
  13. namespace PasteBin
  14. {
  15.     public class Connect : IDTExtensibility2, IDTCommandTarget
  16.     {
  17.         // Constants for command properties
  18.         private const string CommandName        = "PasteBin";
  19.         private const string CommandCaption     = "PasteBin";
  20.         private const string Url                = "http://pastebin.com";
  21.         private const string RequestParameters  = "parent_pid=&format={0}&code2={1}&poster=&paste=Send&expiry=f&email=";
  22.  
  23.         // Constants for file formats
  24.         private static readonly Dictionary<string, string> FileFormat = new Dictionary<string, string>
  25.                                                                             {
  26.                                                                               {"c","c"},
  27.                                                                               {"h","c"},
  28.                                                                               {"cpp","cpp"},
  29.                                                                               {"cs","csharp"}
  30.                                                                             };
  31.  
  32.         // Variables for IDE and add-in instances
  33.         private DTE _applicationObject;
  34.         private AddIn _addInInstance;
  35.  
  36.         // Buttons that will be created on built-in command bars of Visual Studio
  37.         // We must keep them at class level to remove them when the add-in is unloaded
  38.         private CommandBarButton _pasteBinButton;
  39.  
  40.         public void OnConnection(object application, ext_ConnectMode connectMode,
  41.            object addInInst, ref Array custom)
  42.         {
  43.             try
  44.             {
  45.                 _applicationObject = (DTE)application;
  46.                 _addInInstance = (AddIn)addInInst;
  47.  
  48.                 switch (connectMode)
  49.                 {
  50.                     case ext_ConnectMode.ext_cm_UISetup:
  51.  
  52.                         // Do nothing for this add-in with temporary user interface
  53.                         break;
  54.  
  55.                     case ext_ConnectMode.ext_cm_Startup:
  56.  
  57.                         // The add-in was marked to load on startup
  58.                         // Do nothing at this point because the IDE may not be fully initialized
  59.                         // Visual Studio will call OnStartupComplete when fully initialized
  60.                         break;
  61.  
  62.                     case ext_ConnectMode.ext_cm_AfterStartup:
  63.  
  64.                         // The add-in was loaded by hand after startup using the Add-In Manager
  65.                         // Initialize it in the same way that when is loaded on startup
  66.                         AddUI();
  67.                         break;
  68.                 }
  69.             }
  70.             catch (Exception e)
  71.             {
  72.                 MessageBox.Show(e.ToString());
  73.             }
  74.         }
  75.  
  76.         public void OnStartupComplete(ref Array custom)
  77.         {
  78.             AddUI();
  79.         }
  80.  
  81.         private void AddUI()
  82.         {
  83.             // Constants for names of built-in command bars of Visual Studio
  84.             const string vsCodeWindowCommandbarName = "Code Window";
  85.  
  86.             // The only command that will be created. We will create several buttons from it
  87.             Command myCommand = null;
  88.  
  89.             // Built-in command bars of Visual Studio
  90.             CommandBar codeCommandBar;
  91.  
  92.             // Other variables
  93.             var contextUIGuids = new object[] { };
  94.  
  95.             try
  96.             {
  97.  
  98.                 // The collection of Visual Studio command bars
  99.  
  100.                 // ------------------------------------------------------------------------------------
  101.  
  102.                 // Try to retrieve the command, just in case it was already created, ignoring the
  103.                 // exception that would happen if the command was not created yet.
  104.                 try
  105.                 {
  106.                     myCommand = _applicationObject.Commands.Item(_addInInstance.ProgID + "." + CommandName, -1);
  107.                 }
  108.                 catch (Exception e)
  109.                 {
  110.                     Debug.Write(e.ToString());
  111.                 }
  112.  
  113.                 // Add the command if it does not exist
  114.                 if (myCommand == null)
  115.                 {
  116.                     myCommand = _applicationObject.Commands.AddNamedCommand(_addInInstance,
  117.                        CommandName, CommandCaption, null, true, 59, ref contextUIGuids,
  118.                        (int)(vsCommandStatus.vsCommandStatusSupported | vsCommandStatus.vsCommandStatusEnabled));
  119.                 }
  120.                 // ------------------------------------------------------------------------------------
  121.  
  122.                 // Retrieve the collection of command bars
  123.                 // Note:
  124.                 // - In VS.NET 2002/2003 (which uses the Office.dll reference)
  125.                 //   DTE.CommandBars returns directly a CommandBars type, so a cast
  126.                 //   to CommandBars is redundant
  127.                 // - In VS 2005 or higher (which uses the new Microsoft.VisualStudio.CommandBars.dll reference)
  128.                 //   DTE.CommandBars returns an Object type, so we do need a cast to CommandBars
  129.                 var commandBars = (CommandBars)_applicationObject.CommandBars;
  130.  
  131.                 // Retrieve some built-in command bars
  132.                 codeCommandBar = commandBars[vsCodeWindowCommandbarName];
  133.  
  134.                 // ------------------------------------------------------------------------------------
  135.  
  136.                 // Create the buttons from the commands
  137.                 // Note:
  138.                 // - In VS.NET 2002/2003 (which uses the Office.dll reference)
  139.                 //   Command.AddControl returns directly a CommandBarControl type, so a cast
  140.                 //   to CommandBarControl is redundant
  141.                 // - In VS 2005 or higher (which uses the new Microsoft.VisualStudio.CommandBars.dll reference)
  142.                 //   Command.AddControl returns an Object type, so we do need a cast to CommandBarControl
  143.  
  144.                 string ns = GetType().Namespace;
  145.                 Assembly currentAssembly = GetType().Assembly;
  146.  
  147.                 Stream
  148.                     imgStreamPic = currentAssembly.GetManifestResourceStream(ns + "." + "klipper.png"),
  149.                     imgStreamMask = currentAssembly.GetManifestResourceStream(ns + "." + "klipper-mask.png");
  150.  
  151.                 if (imgStreamPic != null && imgStreamMask != null)
  152.                 {
  153.                     Image
  154.                         pasteBinImage = Image.FromStream(imgStreamPic),
  155.                         pasteBinImageMask = Image.FromStream(imgStreamMask);
  156.  
  157.                     // ------------------------------------------------------------------------------------
  158.                     // Button on the "Code Window" context menu
  159.                     // ------------------------------------------------------------------------------------
  160.  
  161.                     // Add a button to the built-in "Code Window" context menu
  162.                     _pasteBinButton = (CommandBarButton) myCommand.AddControl(codeCommandBar,
  163.                                                                               codeCommandBar.Controls.Count + 1);
  164.  
  165.                     // Change some button properties
  166.                     _pasteBinButton.Caption = CommandCaption;
  167.                     _pasteBinButton.BeginGroup = true; // Separator line above button
  168.  
  169.                     _pasteBinButton.Style = MsoButtonStyle.msoButtonIconAndCaption; // It could be also msoButtonIcon
  170.                     _pasteBinButton.Picture = (stdole.StdPicture) ImageConverter.ImageToIpicture(pasteBinImage);
  171.                     _pasteBinButton.Mask = (stdole.StdPicture) ImageConverter.ImageToIpicture(pasteBinImageMask);
  172.                 }
  173.             }
  174.             catch (Exception e)
  175.             {
  176.                 MessageBox.Show(e.ToString());
  177.             }
  178.         }
  179.  
  180.         public void OnDisconnection(ext_DisconnectMode removeMode, ref Array custom)
  181.         {
  182.             try
  183.             {
  184.                 switch (removeMode)
  185.                 {
  186.                     case ext_DisconnectMode.ext_dm_HostShutdown:
  187.                     case ext_DisconnectMode.ext_dm_UserClosed:
  188.  
  189.  
  190.                         if ((_pasteBinButton != null))
  191.                         {
  192.                             _pasteBinButton.Delete(true);
  193.                         }
  194.  
  195.                         break;
  196.                 }
  197.             }
  198.             catch (Exception e)
  199.             {
  200.                 MessageBox.Show(e.ToString());
  201.             }
  202.         }
  203.  
  204.         public void OnBeginShutdown(ref Array custom)
  205.         {
  206.         }
  207.  
  208.         public void OnAddInsUpdate(ref Array custom)
  209.         {
  210.         }
  211.  
  212.         public void Exec(string cmdName, vsCommandExecOption executeOption, ref object varIn,
  213.            ref object varOut, ref bool handled)
  214.         {
  215.  
  216.             handled = false;
  217.  
  218.             if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
  219.             {
  220.                 if (cmdName == string.Format("{0}.{1}", _addInInstance.ProgID, CommandName))
  221.                 {
  222.                     handled = true;
  223.                     if (!((TextSelection)_applicationObject.ActiveDocument.Selection).IsEmpty)
  224.                     {
  225.                         // parameters: name1=value1&name2=value2   
  226.                         var webRequest = (HttpWebRequest)WebRequest.Create(Url);
  227.  
  228.                         webRequest.ContentType = "application/x-www-form-urlencoded";
  229.                         webRequest.Method = "POST";
  230.  
  231.                         // formatting request string from document type and selection
  232.                         string request = string.Format(RequestParameters,
  233.                             FileFormat[_applicationObject.ActiveDocument.Name.Split('.')[1]],
  234.                             System.Web.HttpUtility.UrlEncode(((TextSelection)_applicationObject.ActiveDocument.Selection).Text));
  235.  
  236.                         Stream os = null;
  237.  
  238.                         try
  239.                         { // send the POST
  240.                             webRequest.ContentLength = request.Length;  //Length of request to send
  241.                             os = webRequest.GetRequestStream();
  242.                             os.Write(System.Text.Encoding.GetEncoding("windows-1251").GetBytes(request), 0, request.Length);    //Send it
  243.                         }
  244.                         catch (WebException ex)
  245.                         {
  246.                             MessageBox.Show(ex.Message, "HttpPost: Request error",
  247.                                MessageBoxButtons.OK, MessageBoxIcon.Error);
  248.                         }
  249.                         finally
  250.                         {
  251.                             if (os != null)
  252.                             {
  253.                                 os.Close();
  254.                             }
  255.                         }
  256.  
  257.                         try
  258.                         { // get the response
  259.                             var webResponse = (HttpWebResponse)webRequest.GetResponse();
  260.                             if (webResponse != null)
  261.                             { // copy to clipboard
  262.                                 Clipboard.SetText(webResponse.ResponseUri.ToString());
  263.                                 MessageBox.Show("Upload successfully. Url is copied in your clipboard.");
  264.                             }
  265.                         }
  266.                         catch (WebException ex)
  267.                         {
  268.                             MessageBox.Show(ex.Message, "HttpPost: Response error",
  269.                                MessageBoxButtons.OK, MessageBoxIcon.Error);
  270.                         }
  271.                     }
  272.                 }
  273.             }
  274.         }
  275.  
  276.         public void QueryStatus(string cmdName, vsCommandStatusTextWanted neededText,
  277.            ref vsCommandStatus statusOption, ref object commandText)
  278.         {
  279.             if (neededText != vsCommandStatusTextWanted.vsCommandStatusTextWantedNone) return;
  280.             if (cmdName == string.Format("{0}.{1}", _addInInstance.ProgID, CommandName))
  281.             {
  282.                 statusOption = vsCommandStatus.vsCommandStatusEnabled |
  283.                                vsCommandStatus.vsCommandStatusSupported;
  284.             }
  285.             else
  286.             {
  287.                 statusOption = vsCommandStatus.vsCommandStatusUnsupported;
  288.             }
  289.         }
  290.     }
  291.  
  292. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement