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

C#: Remove line from textfile

by Pieter Brinkman 26. January 2010 03:29

With the following code you can remove a line from a textfile (web.config). If the string is within a line the line will be removed.

[code:c#]

string configFile = @"C:\dev\web.config";
List<string> lineList = File.ReadAllLines(configFile).ToList();
lineList = lineList.Where(x => x.IndexOf("<!--") <= 0).ToList();
File.WriteAllLines(configFile, lineList.ToArray());

[/code]

 

Tags: , ,
Categories: ASP.Net | Linq | C#

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

Comments disabled

by Pieter Brinkman 23. December 2009 05:06

I disabled the comments because of the huge amounts of spam I'm receiving. So if you have any questions you can contact me trough linked-in.

Sorry for the inconvenience.

Tags:
Categories:

TypeMock: Mock Unittest examples

by Pieter Brinkman 21. October 2009 06:45

In this example I will show how to create a Unit Test with TypeMock.

First I have created some basic dummy classes for the example

[code:c#]

public sealed class ServiceFactory
{
    public static ExpireDateService CreateExpireDateService()
    {
        ExpireDateService expireDateService = new ExpireDateService();
        expireDateService.administration = new SqlAdministration("connectionstring");
        return expireDateService;
    }
}


/// <summary>
/// SqlAdministrion creates connection and managed queries with SQL
/// </summary>

public class SqlAdministration
{
    private static DateTime LoadParameterPrivate()
    {
        return DateTime.Parse("01-01-1980");

    }

    public SqlAdministration(string connectionString)
    {
        //Create connection to sql 
    }

    public static DateTime LoadParameter(string expireDateType)
    {
        //GET expireDate from Database:
         SqlAdministratie.LoadParameter("expireDateType");
        // Load Date from Private method for other mocking examples

        return LoadParameterPrivate();
    }
}

public class ExpireDateService
{
    public SqlAdministration administration;

    public DateTime GetDate(string expireDateType)
    {
        DateTime expireDate = SqlAdministration.LoadParameter(expireDateType);

        return expireDate;
    }
}

public class CheckDate
{
    public static bool CheckExpireDateBooking()
    {
        ExpireDateService expireDateService = ServiceFactory.CreateExpireDateService();
        DateTime expireDate = expireDateService.GetDate("expireDateDateFirst");
        return DateTime.Parse("01-01-2000") < expireDate;
    }
}

[/code]

With the following Unit test I will test the code written above. I don't want to change my code or add code for testing purpose. That's where Mocking comes in. With TypeMock I will mock the outcome of specified methods.

The first example is a standard unit test. No Mocking there.

[code:c#]

/// <summary>
/// Checks the expiredate from 'database' 01-01-1980
/// with a hardcoded date 01-01-2000
/// </summary>

[TestMethod()]
public void TestMethodWithoutTypeMock()
{
    Assert.IsFalse(CheckDate.CheckExpireDateBooking());

[/code]

 Now I want to mock the method GetDate to return a date specified by me (01-01-2010).

[code:c#]

/// <summary>
/// Checks the expiredate from database (01-01-1980)
/// with a hardcoded date provided by TypeMock (01-01-2010)
/// </summary>

[Isolated]
[TestMethod()]
public void TestMethodWithTypeMockIsolate()
{
    //Create a dummy version of the ExpireDateService object to use for Mocking

    ExpireDateService expireDateService = new ExpireDateService();
    expireDateService.administration = new SqlAdministration("dummyConnectionString");

    //Return the declared expireDateService when method CreateExpireDateService is called

    Isolate.WhenCalled(() => ServiceFactory.CreateExpireDateService())
        .WillReturn(expireDateService);

    //Isolate the call to method expireDateService.GetDate with parameter 'expireDateDateFirst' and return 01-01-2010

    Isolate.WhenCalled(() => expireDateService.GetDate("expireDateDateFirst"))
        .WillReturn(DateTime.Parse("01-01-2010"));

    Assert.IsTrue(CheckDate.CheckExpireDateBooking());
}

[/code]

For the latest example I wanted to Mock a Private method.

[code:c#]

/// <summary>
/// Checks the expiredate from database (01-01-1980)
/// with a hardcoded date provided by TypeMock on privatemethod(01-01-2010)
/// </summary>

[Isolated]
[TestMethod()]
public void TestMethodWithTypeMockIsolatePrivate()
{
    Isolate.NonPublic.WhenCalled(typeof(SqlAdministration), "LoadParameterPrivate")
        .WillReturn(DateTime.Parse("01-01-2010"));

    Assert.IsTrue(CheckDate.CheckExpireDateBooking());

[/code]

You can download the source here:
MockingWithTypeMockExampleSource.zip (44.47 kb)

Hope it helps.

Cheers,

Pieter

Categories: ASP.Net

Asp.net: DateTime Eval String formatting

by Pieter Brinkman 24. September 2009 07:13

With the following code you can format a DateTime within a Databind.

[code:c#]

<%# DateTime.Parse(Eval("DateModified").ToString()).ToString("MM-dd-yyyy")%> 

[/code]

 

Tags: ,
Categories: ASP.Net

Realization corporate website hu.nl

by Pieter Brinkman 7. September 2009 03:27

For Evident Interactive I was Lead-developer on the hu.nl project. With a team of 5 professionals we build 23 websites in 5 months. All the websites where implemented within one instance of Sitecore CMS.

The websites containing Flash, Silverlight, GoogleMaps, Flick and Youtube.

The project was successfully realized within the deadline.

 

 

Categories: Portfolio

TSQL: Nested Select with multiple results to one (comma separated) string

by Pieter Brinkman 25. August 2009 03:22

For this example I will use the default asp.net Membership tables.

Let say: I need to return all users with their roles (comma separated) in one query. After a long time Googling I found the following solution.

[code:tsql]

select
  UserName,
  (select roles.RoleName + ', '
    FROM aspnet_Roles roles
    join aspnet_UsersInRoles usersInRole on roles.RoleId = usersInRole.RoleId
    WHERE usersInRole.UserId = aspUser.UserId
    for xml path('')) as roles
from
    aspnet_Users aspUser

[/code]

Don't know if this is the best way, but it works.

Categories: TSQL

TSQL: Use common table expression

by Pieter Brinkman 23. August 2009 03:04

With common table expressions you can save the results to a temporary result set and use this results set for other queries.

[code:tsql]

WITH temporaryNamedResultSet
AS
(
  select UserName from aspnet_Users
)
select * from temporaryNamedResultSet

[/code]

 

Categories: TSQL

Asp.Net: invoke WCF method with WCF Test Client

by Pieter Brinkman 20. August 2009 02:53

When deploying a Silverlight application we ran into problems a WCF web-service, to find out what the problem was I wanted to invoke the method.

Microsoft shipped an application for invoking methods from your Windows PC (WCFtestclient.exe). The following steps explain how to use WCFtestclient.exe.

First startup Visual Studio 2008 Command Prompt. In the command prompt type wcftestclient, the application will startup.

Now we need to add the Service. Click File and Add Service.

 Add Service to wcftestclient


Add the URL to your service in the pop-up and pres ok. The service will now add all methods from your service. You can add multiple service URLs.

Double click the method you want to invoke from the tree on the left pane. Enter the values that are required for the Invoke and press Invoke. The method will be invoked.

Invoke WCF method


The right bottom pane will show the response. In my case this shows the Stack-trace because of the error. Normally this will show the web-service response (XML).

With the stack-trace I could located the error and fix it.

Hope this helps,

Pieter

 

XSL: for-each with max items

by Pieter Brinkman 5. August 2009 09:21

While working with Umbraco and Sitecore I learned some Xsl tricks.

The following example shows how to show the first 10 items in a HTML list.

[code:xml]
<ul>
  <xsl:for-each select="*">
    <xsl:if test="position()&lt;='9'">
      <li>
 <a href="{@link}">
   <xsl:value-of select="@name"/>
  </a>
      </li>
    </xsl:if>
  </xsl:for-each>
</ul>
[/code]

 

Categories: XSL

LINQ: Creating a if statement in Linq query

by Pieter Brinkman 30. July 2009 10:24

A lot of times I need to check a statement within my LINQ-query and I wish there was a possibility of a IF statement within LINQ.

The following code is the solution to my IF problem. I use a temporary variable (let isOlderThen30) to check if a statement is true. Then in my WHERE statement I use the temporary variable in a INFLINE IF.

For this example I use my Blogger class with some data

[code:c#]

public class Blogger
{
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public int Age { get; set; }
 public string Blog { get; set; }
}


List<Blogger> personList = new List<Blogger>{
 new Blogger { FirstName = "Pieter", LastName = "Brinkman", Age = 27, Blog = "http://blog.newguid.net" },
 new Blogger { FirstName = "Mark", LastName = "van Aalst", Age = 26, Blog = "http://www.markvanaalst.com" },
 new Blogger { FirstName = "Bas", LastName = "Hammendorp", Age = 32, Blog = "http://www.hammendorp.net" }
};

[/code]

It's kind of hard to think of a easy good example, but here it is. In this example I want to set the Age property to "Older then 30" when the Blogger is older then 30 (how useful!).

[code:c#]

//If a blogger is older then set Age text to "Older then 30"

var rawList = from item in personList
  let isOlderThen30 = item.Age > 30
  select new
  {
   Name = item.FirstName,
   Age = (isOlderThen30 ? "Older then 30" : item.Age.ToString()),
  };


//GENERATE OUTPUT

foreach (var item in rawList)
{
 Response.Write(item.Name + " (" + item.Age + ")<br/>");
}

//OUTPUT
//Pieter (27)
//Mark (26)
//Bas (Older then 30)

[/code]

Hope that the example is clear. If you have any questions let me know.

---------- UPDATE (3 aug 2009)----------

I thought about the codeexample and offcourse you can do it shorter (but less readable with complex queries).

[code:c#]

var rawList = from item in personList
  select new
  {
   Name = item.FirstName,
   Age = (item.Age > 30 ? "Older then 30" : item.Age.ToString()),
  };

[/code]

 

Tags: , ,
Categories: ASP.Net | Linq