Create a Visual Studio add-in with contextmenu and selected text as input

by Pieter Brinkman 25. February 2010 09:58

Create a Visual Studio add-in with contextmenu and selected text as input

When working with a new way of storing settings in a database. I was frustrated how much work it was to check the value of setting from code. So I deceided to make my life a bit easier by creating a VS2008 contextmenu add-in. With this add-in I can select text within VS and use the value of the selected text within the add-in popup. The hardest part was figuring out how to create a contextmenu and how to use the selected text as input value.

In this blogpost I will show how to create a Visual Studio contextmenu add-in and pass the selected text to the pop-up. I’m not going to explain how to create an add-in you can easily find articles about this on MSDN or blogs (just try Google).

Now let’s get started. Create an new Visual Studio add-in project and add the following code to the OnConnetion Method within the Connect.cs. This code will insert add the contextmenu.


[code:c#]
_applicationObject = (DTE2)application;
CommandBars cBars = (CommandBars)_applicationObject.CommandBars;

CommandBar editorCommandBar = (CommandBar)cBars["Editor Context Menus"];
CommandBarPopup editPopUp = (CommandBarPopup)editorCommandBar.Controls["Code Window"];

Command command = commands.AddNamedCommand2(_addInInstance,
 "GetSetting", "Bekijk Setting", "Executes the command for test", true, 733, ref contextGUIDS,
 (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled,
 (int)vsCommandStyle.vsCommandStylePictAndText,
 vsCommandControlType.vsCommandControlTypeButton);
[/code]


Then to get the selected text I use the following method within the Exec of the Connect.cs and pass the selected text (return value) to a property of a Windows Form pop-up.

[code:c#]
private string GetSelection()
{
    string setting = "";

    //Check active document
    if (_applicationObject.ActiveDocument != null)
    {
        //Get active document
        TextDocument objTextDocument = (TextDocument)_applicationObject.ActiveDocument.Object("");
        TextSelection objTextSelection = objTextDocument.Selection;

        if (!String.IsNullOrEmpty(objTextSelection.Text))
        {
 //Get selected text
            setting = objTextSelection.Text;
        }
    }
    return setting;
}
[/code]


Hope it helps.

Cheers,
Pieter

Categories: C# | Controls | Visual Studio

Asp.Net: DataPager problem with Listview

by Pieter Brinkman 23. December 2009 06:48

When using the Datapager with a ListView I had the following problem. When clicking a paging button for the first time nothing happens.But when I click a button the second time, then the page from the first click loads.

I search the internet for a solution and found that you need to add some code to the OnPagePropertiesChanging event of the list view to reload the DataPager.

The following code is the solution to my problem. Including a fix that the data doesn't get loaded two times.

[code:c#]

private List<Product> productList;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        fillGrid();
}

private void fillGrid()
{
    if(productList == null)
        productList = getproducts();
    ListView1.DataSource = productList;
    ListView1.DataBind();
    DataPager1.DataBind();
}

public List<Product> getproducts()
{
    using (AdventureWrksDataContext db = new AdventureWrksDataContext())
    {
        return db.Products.ToList();
    }
}

protected void lvproducts_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
    DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
    fillGrid();
}

[/code]


You can download the solution (PagingExample.zip (83.05 kb))

Cheers,

Pieter

Categories: ASP.Net | Controls

Add meta data (keywords, description) dynamicly

by Pieter Brinkman 6. July 2009 06:02

Add meta-data dynamically to your page by adding a HtmlMeta control to your Header. In this example I dynamically add a keyword string to the page.

[code:c#]

string keyWords = "metatags, html, dynamic, generate";

HtmlMeta keywords = new HtmlMeta();
keywords.Name = "keywords";
keywords.Content = keyWords;
Page.Header.Controls.Add(keywords); 

[/code]


You can do the same for other meta-data like description.

  

Categories: ASP.Net | Controls

Using the ViewState within the SelectMethod of a ObjectDataSource

by Pieter Brinkman 3. June 2009 07:32

By default it is not possible to use the ViewState within methods of a ObjectDataSource. Because the DataSource doesn't run within the current page instance, it just fires the method that you specified.

You can set the page instance for the DataSourceby setting the ObjectInstance property in the ObjectCreating event of the DataSource.

[code:html]

<asp:ObjectDataSource ID="odsListing" runat="server" SelectMethod="getItems" TypeName="YOUR.NAMESPACE" OnObjectCreating="ObjectDataSource_ObjectCreating" DataObjectTypeName="List&lt;Item>">

[/code]

protected void ObjectDataSource_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
 e.ObjectInstance = this;
}

Now you can use the ViewState in you DataSourceMethod (getItems() in this example).

 

Categories: ASP.Net | Controls

Asp.Net: Clear inputfields after form submit

by Pieter Brinkman 15. April 2009 02:56

Every time a form is successful summited I need to clear all input-fields to the default values and give feedback to the user. I wrote a method ClearControl that can have a control as input parameter. This method will set the control based on his type back to the defaultvalue.

 public static void ClearControl(Control control)
{
 switch (control.GetType().Name)
 {
  case "TextBox":
   TextBox txtBox = (TextBox)control;
   txtBox.Text = "";
   break;
  case "DropDownList":
   DropDownList ddl = (DropDownList)control;
   ddl.SelectedIndex = 0;
   break;
  case "CheckBox":
   CheckBox chk = (CheckBox)control;
   chk.Checked = false;
   break;
  case "CheckBoxList":
   CheckBoxList chkList = (CheckBoxList)control;
   foreach (ListItem li in chkList.Items)
    li.Selected = false;
   break;
  case "Panel":
   ClearFields((Panel)control);
   break;
  case "RadioButtonList":
   RadioButtonList rbl = (RadioButtonList)control;
   rbl.SelectedIndex = -1;
   break;
 }
}

 

To use this method I wrote a method 'ClearFields' that accepts a View or Container control. You can add every type of control that has the .Controls property.

public static void ClearFields(Panel container)
{
 foreach (Control control in container.Controls)
 {
  ClearControl(control);
 }
}

public static void ClearFields(View container)
{
 foreach (Control control in container.Controls)
 {
  ClearControl(control);
 }
}

 

When I have some time left I will try to implement the ClearFields Method as a ExtensionMethod.

Cheers,

Pieter

 

Categories: ASP.Net | Controls

Sitecore: itemlist with ObjectDataSource, Listview and DataPager

by Pieter Brinkman 8. April 2009 05:22

For a new project I started working with Sitecore again.

I needed to create a listing of items with paging. I implemented a Listview with a ObjectDataSource and the DataPager control.

 

<asp:ListView ID="lvListing" runat="server" DataSourceID="odsListing" onitemdatabound="lvListing_ItemDataBound">
    <ItemTemplate>
         <li class="clearfix">
            <a class="thumb" ID="thumnailLink" runat="server" > 
                <sc:Image Field="Thumbnail" ID="thumbnailImage" MaxWidth="120" runat="server" />
            </a>
            <h2><asp:HyperLink runat="server" ID="hlTitle" /></a></h2>
            <span class="date"> <sc:Date ID="listingDate" runat="server" Format="dd-MM-yyyy" /> <asp:Literal Visible="false" runat="server" ID="litDateField" /></span>
            <%# Eval("Fields[\"IntroText\"]") %>
            <asp:HyperLink runat="server" CssClass="url" ID="hlNavigationUrl" />
     </li>
    </ItemTemplate>
    <EmptyDataTemplate>
        Geen artikelen
    </EmptyDataTemplate>
    <LayoutTemplate>
        <ul ID="itemPlaceholderContainer" runat="server" style="">
            <li ID="itemPlaceholder" runat="server" />
        </ul>
    </LayoutTemplate>
    <ItemSeparatorTemplate>
        <br />
    </ItemSeparatorTemplate>
</asp:ListView>

<ul>
  <li class="paging">
        <asp:DataPager ID="DataPager1" PagedControlID="lvListing" runat="server" PageSize="10" >
         <Fields>
             <asp:nextpreviouspagerfield ButtonCssClass="paging-previous" PreviousPageText="Vorige" ButtonType="Link"  ShowPreviousPageButton="True" ShowNextPageButton="False"/>
                <asp:nextpreviouspagerfield ButtonCssClass="paging-next" NextPageText="Volgende" ButtonType="Link" ShowPreviousPageButton="False" ShowNextPageButton="True" />
             <asp:NumericPagerField ButtonType="Link" NextPageText="VOLGENDE" PreviousPageText="VORIGE" RenderNonBreakingSpacesBetweenControls="true" />
         </Fields>
        </asp:DataPager>
    </li>
</ul> 

<asp:ObjectDataSource ID="odsListing" runat="server" SelectMethod="GetItems"
        TypeName="MyNameSpace.MyUsercontrol"
        DataObjectTypeName="Sitecore.Collections.ChildList">
</asp:ObjectDataSource>

 

 


In the code behind I created the public method GetItems which returns a ChildListCollection.

namespace MyNameSpace
{
    public partial class MyUsercontrol: System.Web.UI.UserControl
    {
     
       public Sitecore.Collections.ChildList GetItems()
       {
          return Sitecore.Context.Item.GetChildren();
        }
     }


The PagedControlID property of the datapager control is set to the ID of the Listview.  

 

 

 

Categories: ASP.Net | Controls

Asp.Net: Wizard control highlight selected step

by Pieter Brinkman 26. March 2009 06:42

You can highlight the selected stap of the wizard control by editing the SideBarTemplate within the asp:Wizard control.

<SideBarTemplate>                        
    <asp:datalist runat="Server" id="SideBarList">
        <ItemTemplate>
          <asp:linkbutton runat="server" ID="SideBarButton"/>
       </ItemTemplate>
       <SelectedItemTemplate>
           <asp:LinkButton ID="SideBarButton" runat="server" CssClass="selected">LinkButton</asp:LinkButton>
       </SelectedItemTemplate>
   </asp:datalist>
</SideBarTemplate>


The ItemTemplate and the SelectedItemTemplate need to have a Button with ID SideBarButton.

 

Categories: ASP.Net | Controls

Asp.Net: Handle Usercontrol ClickEvent in Page

by Pieter Brinkman 24. March 2009 04:01

In this article we're going to create a usercontrol with a button. Place this usercontrol on a page and handle the clickEvent on that page.

Step 1, the UserControl

Create a usercontrol with a button called  'clickMeButton'.

In the codebehind of your UserControl define a delegate.

public delegate void ButtonClickedEventHandler(object sender, EventArgs e);


Then create a public EvenHandler.

public event ButtonClickedEventHandler ButtonClickedEvent;


Now add a click event to the button and on the click event fire tje ButtonClickedEvent.

protected void clickMeButton_Click(object sender, EventArgs e)
{
   ButtonClickedEvent(sender, e);
}

And the usercontrol is finished, now create a page to use the usercontrol.


Step 2, the Page

Create a new page. Add the usercontrol to the page, in the codebehind (Page_Load) attach your page to the ButtonClickedEvent.

UcWithClickEvent1.ButtonClickedEvent += new UcWithClickEvent.ButtonClickedEventHandler(UcWithClickEvent1_ButtonClickedEvent);


Press tab twice to generate the following Method.

void UcWithClickEvent1_ButtonClickedEvent(object sender, EventArgs e)
{
   throw new NotImplementedException();
}


Lets implement some basic logic to the event to test if the event is working

void UcWithClickEvent1_ButtonClickedEvent(object sender, EventArgs e)
{
   Response.Write("Button clicked");
}


Step3, the result

Here is the result after the user clicked the button within the usercontrol. As aspect-ed the Button Clicked text is shown.


You can download the example here (blogExamples.rar (17.87 kb))

Hope it helps!

Categories: ASP.Net | Controls

Asp.Net: Charting Control (Error ChartImg.axd)

by Pieter Brinkman 3. March 2009 02:49

After installing and playing with the Asp.Net Charting control I decided to use it for a customer. When integrating the control to the project I got the following error

"Error executing child request for ChartImg.axd"

This error occurred because I did not update my web.config file. You have to add the following appSettingkey, httpHandler and handler.

<appSettings>
    <add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFilesDit\;" />
</appSettings>
<httpHandlers>
    <add path="ChartImg.axd" verb="GET,HEAD" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" />
</httpHandlers>


<handlers>
    <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</handlers>

More info about the Charting control:
http://weblogs.asp.net/scottgu/archive/2008/11/24/new-asp-net-charting-control-lt-asp-chart-runat-quot-server-quot-gt.aspx

Enjoy charting,
Pieter

Categories: ASP.Net | Controls | Microsoft

Asp.Net: Menu control remove MenuItem (MenuItemDataBound)

by Pieter Brinkman 26. February 2009 07:58

For a project I needed to remove menu items to the pages in the folder 'Subscriberpages' when a the user is in the Role of 'Marketing' and 'AccountManagement'. To do this I added the following code to the MenuItemDataBound event.

[code:c#]
protected void mainMenu_MenuItemDataBound(object sender, MenuEventArgs e)
{
 SiteMapNode node = e.Item.DataItem as SiteMapNode;

 if (node.Url.Contains("Subscriberpages"))
 {
  if (HttpContext.Current.User.IsInRole("Marketing") || HttpContext.Current.User.IsInRole("AccountManagement'"))
  {
   // Get menu.
   Menu topMenu = (Menu)sender;


   // Remove dataitem from menu.
   topMenu.Items.Remove(e.Item);
  }
 }
}
[/code]


To generate the menu I used the Web.sitemap and the asp:Menu control.

 

Categories: ASP.Net | Controls

Asp.Net: Using the OnCommand Event with CommandArgument

by Pieter Brinkman 4. February 2009 08:53

When using a button, linkbutton or imagebutton with CommandArguments or CommandName you can use the OnCommand event instead of the OnClick event. Using the OnCommand Event you use less code to extract the CommandArgument and CommandName from the Event comparing to the OnClick event (because you don't need to cast the control).


Code example

The Aspx:

[code:html]

<asp:ImageButton ImageUrl="~/Includes/Images/delete_icon.gif" runat="server" ID="ibtDeleteClip" OnCommand="ibtDeleteClip_Command" CommandArgument='<%# Eval("ClipId") %>' />

[/code]

 

And the codebehind (C#):

[code:c#]


protected void ibtDeleteClip_Command(object sender, CommandEventArgs e)
{
   string commandArg = e.CommandArgument;
}

 

Categories: ASP.Net | Controls

Asp.Net: Databinding a array of strings

by Pieter Brinkman 30. January 2009 03:47

You can use a string array as datasource and view the string values by using the Container.DataItem property.

Code example

Codebehind:

string[] testData = {"1","two","3","4"};
rptDemo.DataSource = testData;
rptDemo.DataBind();


And in the .aspx:

<asp:Repeater runat="server" ID="rptDemo">
    <ItemTemplate>
        <%# Container.DataItem %>
    </ItemTemplate>
</asp:Repeater>
Categories: ASP.Net | Controls