Programmers Unlimited

Knowledge is power

  • PostSharp Principals
  • My Articles
  • Projects
  • Archives
  • About

Indexing DataTables

Posted by programmersunlimited on January 24, 2012
Posted in: General. Leave a Comment

That’s right, I’m still using DataTables. Why? Because they best fit the requirements for what I am doing. I’m also taking advantage of parallel processing via the TPL. A lot of the operations I need to do would be much easier via PLINQ and POCO’s such as joins, grouping and searching.

Because I’m working with many disparate DataTables and the join predicates are complex it just isn’t feasible (performance wise) to use DataRelation. To get a working prototype I decided to just use nested loops to find matching DataRows but I’ve found that nested loops when using the TPL results in poor performance and is generally a bad idea when working with large item sets anyway.

Normally I would build a HashTable and create a key from each row based on the columns in the predicate, then use that to match rows with a single loop. However, when using parallel loops, one has to take care to avoid concurrency/multi-threading issues that arise with non thread safe collections. Dictionary<K,V> is normally satisfactory when using them, but they are not thread safe. ConcurrentDictionary<K,V> would seem like an obvious candidate to replace the normal dictionary, but it buckles under the pressure. Memory consumption goes through the roof even for simple, small data processing and performance takes a serious hit.

Another issue with my row key by column approach is that the code has to be written each time and normally I use string concatenation for the keys. Instead, I wanted a nice way to build an index that I can easily query, but I also wanted a generic solution so any key could be used.

I went with the following method

public static Dictionary<TKey, List<DataRow>> BuildIndex<TKey>(this DataTable source, Func<DataRow, TKey> processRow)
{
    ConcurrentBag<Index<TKey, DataRow>> indexBag = new ConcurrentBag<Index<TKey, DataRow>>();

    Parallel.For(0, source.Rows.Count, new Action<int>((i) =>
        {
            indexBag.Add(new Index<TKey, DataRow>()
            {
                Key = processRow(source.Rows[i]),
                Row = source.Rows[i]
            });

        }));

    var result = (from i in indexBag
                    group i by i.Key into g
                    select g
                        ).ToDictionary(c => c.Key, d => d.Select(e=>e.Row).ToList() );

    return result;
}

private class Index<TKey, URow>
{
    public TKey Key { get; set; }
    public URow Row { get; set; }
}

This method  takes in a generic type TKey to define the index key and then requires a predicate to build the key from each row. The performance of this is excellent. The generic Index model is simply a nice way to organize the keys as things are being built. I chose to return a dictionary because I’m satisfied with the performance and functionality and since it’s only being used for reading and not writing, we don’t need a thread safe collection. I could have easily went with a IEnumerable<Index<TKey,URow>> but why bother?

Since this ends up as an extension method, using it is pretty simple.

private void Loop(DataTable table1, DataTable table2)
{
    //Build index for table2
    var idx = table2.BuildIndex<Tuple<int, long, int>>((dr) =>
    {
        return new Tuple<int, long, int>(
            dr.Field<int>("userid"),
            dr.Field<long>("orderid"),
            dr.Field<int>("domainid"));
    });

    //Loop over table1
    Parallel.For(0, table1.Rows.Count, new Action<int>((i) =>
    {
        var rowKey = new Tuple<int, long, int>(
            table1.Rows[i].Field<int>("userid"),
            table1.Rows[i].Field<long>("orderid"),
            table1.Rows[i].Field<int>("domainid"));

        if (idx.ContainsKey(rowKey))
        {
            //Exists
        }
        else
        {
            //Doesn't exist
        }
    }));
}

private void Join(DataTable table1, DataTable table2)
{
    //Build index for table1
    var idx1 = table1.BuildIndex<Tuple<int, long, int>>((dr) =>
    {
        return new Tuple<int, long, int>(
            dr.Field<int>("userid"),
            dr.Field<long>("orderid"),
            dr.Field<int>("domainid"));
    });

    //Build index for table2
    var idx2 = table2.BuildIndex<Tuple<int, long, int>>((dr) =>
    {
        return new Tuple<int, long, int>(
            dr.Field<int>("userid"),
            dr.Field<long>("orderid"),
            dr.Field<int>("domainid"));
    });

    //Do a join
    var joined = from i in idx1
                    join j in idx2 on i.Key equals j.Key
                    select new { Key = i.Key, t1Rows = i.Value, t2Rows = j.Value };

}

Tuples are great to use as keys because they’re immutable and have a smaller footprint than strings (generally speaking).

Conclusion: If I could use POCOs instead of DataTables I certainly would but for now I do what I can. I find the indexing method I’ve come up with a great way to work around performance and threading issues (even when only reading) of DataTables.

I’m interested in hearing your thoughts.

  • More

Like this:

Like
Be the first to like this post.

Learn T4 with my PluralSight course

Posted by programmersunlimited on January 18, 2012
Posted in: General. Leave a Comment

My new course on T4 (Text Template Transformation Toolkit) has gone live and it’s ready for your viewing pleasure. If you have any feed back, please send it to me.

T4 Templates on PluralSight.com

This course introduces T4, Microsoft’s code generation tool that comes with Visual Studio. The Text Template Transformation Toolkit dynamically produces text of any type and is used for code and document generation.

Discover how to reduce development time, bugs and maintenance by building reusable templates. This course covers T4 template building blocks, extending templates with custom functionality and debugging the template execution process.

MVC and Entity Framework, among others, can be customized and extended through T4 templates. It also covers, how to customize MVC controllers using the default templates and the MVCScaffolding package, and customizing entities by adding validation attributes.

Dustin tops it all off with real world uses of T4 including generating, and automatically synchronizing, code based on external resources, and combining T4 with other technologies to produce powerful templates.

  • More

Like this:

Like
Be the first to like this post.

Exposing internal methods in 3rd party assemblies for external use

Posted by programmersunlimited on August 16, 2011
Posted in: General. Leave a Comment

To start out, I’m going to state that I don’t condone this, but if you need it then you need it. I expect to get some nasty comments about pattern violation this or encapsulation that so go ahead and send them in. This is just an extension of my previous post about modifying 3rd party assemblies and the power of PostSharp.

The Evil API

I was working with an API recently that had me using ILSpy to figure anything out. At some point I needed to make use of some code while inheriting a class and overriding a virtual method. So I copied out some code from ILSpy into Visual Studio when I realized that an important method call was broken because that method was internal only. DOH! Due to reasons I won’t explain, I didn’t actually modify the assembly, I just went another way, but if I could have I would have just exposed the method.

Here is our own little evil API

namespace Example.API
{
    public class Calculator
    {
        public int ProcessValue(int x)
        {
            return SuperSpecialCalculation(x, x);
        }

        internal int SuperSpecialCalculation(int x, int y)
        {
            return x + y;
        }

    }
}

Two methods, a public and an internal. We need access to the internal!

The Apsect and Provider

I’m sure there are better ways, but I decided to just introduce a public method using the same signature as the internal method and it will just act as a wrapper. So we need an aspect that imports the expected internal method (target) and introduces our wrapper method. Then we need a provider to tell PostSharp where to apply our aspect. For more information on aspect providers, see PostSharp Principals day 12 & day 13. For more information on introduction, see PostSharp Principals day 13 & day 14.

namespace InternalToPublic
{
    //Aspect Provider
    public class AspectProvider : IAspectProvider
    {
        public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
        {
            List<AspectInstance> targets = new List<AspectInstance>();

            var targetType = ((Assembly)targetElement).GetTypes().FirstOrDefault(c => c.Name.Equals("Calculator"));

            if (targetType == null) { return targets; }

            targets.Add(new AspectInstance(targetType, new ExposeSuperSpecialCalculation()));

            return targets;
        }

    }

    //Aspect
    [Serializable]
    public class ExposeSuperSpecialCalculation : InstanceLevelAspect
    {
        [ImportMember("SuperSpecialCalculation", IsRequired = true, Order = ImportMemberOrder.BeforeIntroductions)]
        public Func<int, int, int> InternalMethod;

        [IntroduceMember]
        public int SuperSpecialCalculationPublic(int x, int y)
        {
            return InternalMethod(x, y);
        }
    }
}

Modify!

Just as in the previous post, we run a batch file to do the modifications to the assembly.

@"C:\Program Files (x86)\PostSharp 2.1\Release\postsharp.4.0-x86-cil.exe" "Example.API.dll" /p:AspectProviders=InternalToPublic.AspectProvider,InternalToPublic /p:Output=output\Example.API.dll
@copy /y InternalToPublic.dll .\Output
@copy /y PostSharp.dll .\Output
@pause

Test

Now we just need to make sure it’s all working. Create a new project and reference the modified Example.API.dll, InternalToPublic.dll and PostSharp.dll.

namespace Example.TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Example.API.Calculator c = new API.Calculator();
            Console.WriteLine(c.ProcessValue(10));
            Console.WriteLine(c.SuperSpecialCalculationPublic(10, 20));
            Console.ReadKey();
        }
    }
}

The output is as expected

20
30

kick it on DotNetKicks.com

  • More

Like this:

Like
Be the first to like this post.

PostSharp: Why are my arguments null?!

Posted by programmersunlimited on August 1, 2011
Posted in: General. Leave a Comment

I see this question a lot. The developer has created an aspect and when they are stepping through they are seeing that the advice method arguments are null. The most common example of this is the MethodExecutionArgs.Exception. We can easily reproduce this “issue”.

Example

If you compile this code and step through it, the args parameter will be null.

[LogAspect]
class Program
{
    static void Main(string[] args)
    {
        throw new Exception("test exception");
    }
}

[Serializable]
public class LogAspect : OnExceptionAspect
{
    public override void OnException(MethodExecutionArgs args)
    {
        Console.Write("There was an error");
    }
}

PostSharpNullArgs1

So what’s going on? Well if you use ILSpy and look at the compiled result, you’ll see that PostSharp uses optimizations that include ignoring unused properties.

PostSharpNullArgsILSpy1

See how the OnException method has been decorated with multiple MethodExecutionAdviceOptimizations flags? The entire list for this aspect is:

MethodExecutionAdviceOptimization(
MethodExecutionAdviceOptimizations.IgnoreGetMethod 
| MethodExecutionAdviceOptimizations.IgnoreSetFlowBehavior
| MethodExecutionAdviceOptimizations.IgnoreGetArguments
| MethodExecutionAdviceOptimizations.IgnoreSetArguments
| MethodExecutionAdviceOptimizations.IgnoreGetInstance 
| MethodExecutionAdviceOptimizations.IgnoreSetInstance
| MethodExecutionAdviceOptimizations.IgnoreGetException 
| MethodExecutionAdviceOptimizations.IgnoreGetReturnValue
| MethodExecutionAdviceOptimizations.IgnoreSetReturnValue 
| MethodExecutionAdviceOptimizations.IgnoreGetMethodExecutionTag
| MethodExecutionAdviceOptimizations.IgnoreSetMethodExecutionTag 
| MethodExecutionAdviceOptimizations.IgnoreEventArgs
)

Notice the IgnoreGetException flag? That’s why it’s null when stepping through the aspect. Change the aspect to

[LogAspect]
class Program
{
    static void Main(string[] args)
    {
        throw new Exception("test exception");
    }
}

[Serializable]
public class LogAspect : OnExceptionAspect
{
    public override void OnException(MethodExecutionArgs args)
    {
        Exception e = args.Exception; //Now we're using Exception so it won't be null
        Console.Write("There was an error");
    }
}

and rebuild. When you step through this time, args is not null and neither is args.Exception.

PostSharpNullArgs2

Looking at ILSpy again, you no longer see the IgnoreGetException flag.

MethodExecutionAdviceOptimization(
MethodExecutionAdviceOptimizations.IgnoreGetMethod
| MethodExecutionAdviceOptimizations.IgnoreSetFlowBehavior
| MethodExecutionAdviceOptimizations.IgnoreGetArguments
| MethodExecutionAdviceOptimizations.IgnoreSetArguments
| MethodExecutionAdviceOptimizations.IgnoreGetInstance
| MethodExecutionAdviceOptimizations.IgnoreSetInstance
| MethodExecutionAdviceOptimizations.IgnoreGetReturnValue
| MethodExecutionAdviceOptimizations.IgnoreSetReturnValue
| MethodExecutionAdviceOptimizations.IgnoreGetMethodExecutionTag
| MethodExecutionAdviceOptimizations.IgnoreSetMethodExecutionTag
)

Answer

So why are the arguments null? Because you’re not using them.

kick it on DotNetKicks.com

  • More

Like this:

Like
Be the first to like this post.

Applying aspects to 3rd party assemblies using PostSharp

Posted by programmersunlimited on July 27, 2011
Posted in: General. 6 comments

[Related Article: Introduction to Aspect Oriented Programming and PostSharp]

There is undocumented functionality in PostSharp 2.1 (2.1.2.3 or higher) that allows us to apply aspects to assemblies that we don’t have the source code for. I’m going to show you how this works, but first I have state that this functionality is undocumented because it isn’t officially supported by PostSharp. Proceed at your own risk.

Setup

If you do not have PostSharp 2.1.2.3 (at this point it’s CTP 3) then get it and install it. We will create two projects, a console project that we’ll be using as our dummy and a class library that is going to hold our aspect provider. I highly recommend that you read through the PostSharp Principals series if you are not familiar with PostSharp or aspect providers.

We will also have a folder called ‘Lab’ which we’ll store all our needed files in. Create the Lab folder and then create a subfolder under Lab called Output.

Note: I’m targeting .NET 4.0.

Code

The proceeding code is going to be our dummy executable that we will apply aspects to. Go ahead and start a new console project in Visual Studio called DummyApp. No need to reference PostSharp or any other assemblies. Replace the code in Program.cs with the following:

namespace DummyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ExampleClass ec = new ExampleClass();

            ec.Method1();
            ec.Method2();

            Console.ReadKey();
        }
    }

    public class ExampleClass
    {
        public void Method1()
        {
            Console.WriteLine("Method1()");
        }

        public void Method2()
        {
            Console.WriteLine("Method2()");
        }
    }
}

Build the project and copy DummyApp.exe to the Lab folder.

Now for the aspect provider. Create a new class library project and call it MyProviders. Add a reference to PostSharp. Add a new class file and name it TraceAspect.cs. Add the following code:

[Serializable]
public class SomeTracingAspect : IOnMethodBoundaryAspect
{
    public void OnEntry(MethodExecutionArgs args)
    {
        Console.WriteLine("Entering method: {0}.{1}", args.Method.DeclaringType.Name, args.Method.Name);
    }

    public void OnException(MethodExecutionArgs args)
    {
    }

    public void OnExit(MethodExecutionArgs args)
    {
        Console.WriteLine("Exiting method: {0}.{1}", args.Method.DeclaringType.Name, args.Method.Name);
    }

    public void OnSuccess(MethodExecutionArgs args)
    {
    }

    public void RuntimeInitialize(MethodBase method)
    {
    }

}

Our aspect is nothing special, just an aspect that implements IOnMethodBoundary and we are just adding code to the OnEntry and OnExit advices.

Add another class file and name it TraceAspectProvider.cs then add the following code:

public class TraceAspectProvider : IAspectProvider
{
    readonly SomeTracingAspect aspectToApply = new SomeTracingAspect();

    public IEnumerable ProvideAspects(object targetElement)
    {
        Assembly assembly = (Assembly)targetElement;

        List instances = new List();
        foreach (Type type in assembly.GetTypes())
        {
            ProcessType(type, instances);
        }

        return instances;
    }

    private void ProcessType(Type type, List instances)
    {
        foreach (MethodInfo targetMethod in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly))
        {
            instances.Add(new AspectInstance(targetMethod, aspectToApply));
        }

        foreach (Type nestedType in type.GetNestedTypes())
        {
            ProcessType(nestedType, instances);
        }
    }
}
 

This is how we tell PostSharp what targets to work with and what aspects to apply to those targets. We implement the IAspectProvider interface and satisfy its required ProvideAspects method. PostSharp invokes the ProvideAspects method passing in a System.Reflection.Assembly instance for the target assembly we’re trying to modify. Using reflection, we’ll get all of the types in the target assembly and process each one by calling our ProcessType method.

In the ProcessType method, we again use reflection to discover all of the methods in the given type that are public and not static. For each applicable method we create a new AspectInstance and add it to the instances list that we’ll be giving back to PostSharp for processing. Then we do some recursion to process any nested types.

When we create a new AspectInstance, we’re passing in to the first parameter the System.Reflection.MethodInfo instance we received from GetMethods(). This parameter can take System.Type, most of the System.Reflection types such as FieldInfo, EventInfo etc and also PostSharp.Reflection.LocationInfo. If we were attempting to apply a LocationInterception aspect, we would pass in a System.Reflection.PropertyInfo type for our intended target.

The second parameter requires an instance of IAspect that will be applied to the target. This is where we supply our desired aspect. We’ve declared and instantiated a class member of type SomeTracingAspect for this purpose so we supply this instance to satisfy the parameter.

Build the project and copy the MyProviders.dll and PostSharp.dll to the Lab folder.

Modify!

Now we’re all ready to go. The last step is to actually perform the transformations. To do this we just need to run the PostSharp command line interface with some specific options. I recommend creating a batch file to do this because it could be a lot of typing.

@"C:\Program Files (x86)\PostSharp 2.1\Release\postsharp.4.0-x64-cil.exe" "DummyApp.exe" /p:AspectProviders=MyProviders.TraceAspectProvider,MyProviders /p:Output=output\DummyApp.exe /attach
@copy /y MyProviders.dll .\Output
@copy /y PostSharp.dll .\Output
@pause

Your PostSharp path may vary. You will also need to choose the correct version of PostSharp CIL executable to run. If you’re working with assemblies targeting .NET 3.5 then use the 2.0 version. If you’re working with assemblies targeting .NET 4.0 then use the 4.0 version and of course, choose the appropriate architecture type (x86, x64). For example:

  • postsharp.2.0-x86-cil.exe
  • postsharp.2.0-x64-cil.exe
  • postsharp.4.0-x86-cil.exe
  • postsharp.4.0-x64-cil.exe

The first argument we pass in is the path to the target, DummyApp.exe. The target doesn’t have to be an executable, it can be a library (DLL).

Next we tell PostSharp which aspect provider to use. We do this using the /P argument which allows us to set PostSharp properties (Usage: /P:name=value). Of course we want to use the aspect provider we just built so we specify the fully qualified type name followed by a comma then the assembly name.

PostSharp requires an Output to be provided so we use the /P argument again this time setting the ‘Output’ property to our destination. We don’t want to modify the source so we tell PostSharp to put the result in the output folder.

Optionally we can specify the /attach argument which allows us to attach to Visual Studio to step through the provider (in case there are issues).

When we run the batch file, PostSharp goes to work. When it’s done we see that the output folder has a copy of DummyApp.exe. When we run it we see that our aspect has been applied.

Entering method: ExampleClass.Method1
Method1()
Exiting method: ExampleClass.Method1
Entering method: ExampleClass.Method2
Method2()
Exiting method: ExampleClass.Method2

We can also use ILSpy to look at the resulting assembly.

DummyApp-ILSpy

In another post we’ll go over applying an EventInterceptionAspect based aspect and how to setup project build options to automatically run this process.

kick it on DotNetKicks.com

  • More

Like this:

Like
2 bloggers like this post.
  • programmersunlimited
  • Hattan

Most Valuable Member 2010-2011

Posted by programmersunlimited on July 13, 2011
Posted in: General, User Group. 1 comment

badgeeventbriteEvery July, the Inland Empire .NET User’s Group holds its annual Most Valuable Member event to honor the group’s members who have gone above and beyond for their group and community. The MVM content uses a points based system where any member can submit points for one or more qualifying activities such as helping to setup a meeting and speaking at a user group.

I’ve been a member of the Inland Empire .NET User’s Group since 2008 but only since July 2010 have I participated in the MVM contest. I spent the entire year speaking at user groups and code camp, attending meetings and helping with setup and tear down, writing book reviews and whatever else I could do to help out the community and earn MVM points. It paid off. I blew away the competition.

So what does it mean to win the Most Valuable Member content? It means recognition, notoriety and a huge bag of loot & swag that equates to a king’s ransom. Thanks to James Johnson, the group’s founder and president, the prize packages awarded to the top three members are nothing less than overwhelming. James has some magic voodoo that he uses to woo the group’s sponsors into generously filling the loot bags and providing a catered meal at a fancy hotel.

In addition to a nicely framed award, the winners received laptop bags with a nicely embroidered Visual Studio logo on them (thanks to Microsoft) that were filled with goods. Since I was the Most Valuable Member, my bag was the heaviest. Here is what was in my bag

Swag

Pens, stickers, t-shirts and thumb drives from the group’s many sponsors including Red-Gate, ComponentOne, DevExpress and Telerik.

Books

I would estimate that I received 200lbs of books from our book sponsors, Wrox, Apress and O`Reilly. Not only did I get a laptop bag full of books, but I was also handed a giant box full of more books (they wouldn’t fit in the bag is what James told me).

imagejpeg_4
Left to right: Ayyappan, Oscar, Myself, James.

In addition to all of those books I also received certificates for 10 books of my choosing from each publisher. That’s an additional 30 books. O`Reilly also provided a 1 year subscription to Safari Books Online.

Total book count: 42

IMAG0247

Software

What would a user group be without software to give away? In my bag were countless envelopes each containing a license for a software package from each of the group’s sponsors.

  • Red-Gate Developers Bundle
  • JetBrains dotTrace
  • TechSmith Camtasia Studio
  • EmailVerify.net
  • PluralSight annual subscription
  • DevExpress DXperience Enterprise subscription
  • Telerik Ultimate Collection
  • SharpCrafters PostSharp Professional License
  • Infragistics Net Advantage

If all of that weren’t enough, James had some very nice words to say about me and the other winners.

What an excellent night. Thanks to James for putting it all together and making it happen, year after year!

  • More

Like this:

Like
Be the first to like this post.

Review: .NET Windows Development: Everyday Tips, Tricks & Optimization

Posted by programmersunlimited on June 7, 2011
Posted in: General. Leave a Comment

.NET Windows Development: Everyday Tips, Tricks & Optimization

By Alberto Población

“What comes after the “…For Dummies” book? There is a big gap between the introductory/beginner books and the rest of them. Beginners looking for that next step usually find it to be a steep climb. This book helps to fill that gap.” – Dustin Davis

Amazon: $37.00

I recently received my copy of “.NET Windows Development: Everyday Tips, Tricks & Optimization”. I was pleasantly surprised when I saw how thin it was. There is only about 250 pages which is exactly how I like my tech books. Some readers like the bible style books with 1000+ pages, but this isn’t that type of book.

“.NET Windows Development: Everyday Tips, Tricks & Optimization” is packed with problem/solution/better solution sections with necessary details where required. There is little, if any, fluff or filler in this book and I appreciate that. Reading is time-consuming and I dislike wasting my time on filler. I usually skim over what I think is wasteful material and try to get back to the good stuff, but sometimes I end up missing something.

The book contains seven chapters of which each is dedicated to its own topic. There is no lead-in so you can jump around the chapters in any order you wish. As the title suggests, each chapter contains either tips & tricks for solving some common issues or improving performance or right-to-the-point introductory text of a feature set.

  • Accessing Data - this chapter focuses on data access and performance using easy to implement techniques. I especially found the use of SqlBulkCopy helpful.
  • New features in Windows 7 – I found this chapter very interesting as it shows how your applications can integrate with all of the new Windows 7 features such as jump lists and icon overlays.
  • Using Graphics - This chapter focuses on GDI via the System.Drawing namespace.
  • Creative Use of Serialization - This is one of those chapters where beginners will benefit. The author introduces serialization (Xml, Binary, Soap) and when to use each and then dives into the how by exploring some uses for serialization.
  • Some Uses for Reflection – Just as the previous chapter, an introduction that wastes no time.
  • Various Techniques that Should Be Well Known, But Sometimes Aren’t – Various techniques including encoding.
  • A Few Tips for Windows Forms Applications – Various topics concerning Windows Forms. I enjoyed reading about the new Windows 7 dialogs.

Since this book focuses on Windows Forms instead of WPF,it might be considered outdated even though it was written in 2010. On the contrary, I believe this is what gives the book more respectability. Getting to the point without worrying about the latest and greatest is so refreshing. The contents of this book are still relevant to today’s development and just about everyone can find something to take away and apply to their daily work.

The price for the book is a bit steep at $37.00 (from Amazon), but overall I recommend this book especially to beginners who need that next step to be a small one.

Amazon
http://www.amazon.com/NET-Windows-Development-Everyday-Optimization/dp/8493548936/ref=sr_1_1?ie=UTF8&s=books&qid=1307458970&sr=1-1

CampusMVP
http://campusmvp.net/

  • More

Like this:

Like
Be the first to like this post.

VS2010 Startup Error: The operation could not be completed.

Posted by programmersunlimited on May 16, 2011
Posted in: General. Tagged: Visual Studio. 6 comments

All of the sudden Visual Studio 2010 decided to not work. The install was on a laptop I had not touched since I last did a presentation at a user group (about 2-3 weeks). I go to start it up to test out the code for my presentation (that night) and got a lovely error message when trying to start Visual Studio, “The operation could not be completed” and that was it.

I tried safe mode start-up ”devenv.exe /safemode” and also removing all add-ins and extensions. I also tried resetting user settings “devenv.exe /resetsettings” and all the other switches I could find. Nothing. This was a random out of the blue problem.

I tried to install SP1 but got the same error which caused SP1 install to fail. I uninstalled all Visual Studio items and did a reinstall. Same problem.

Finally I found an MSDN post where the poster said he solved it by renaming “%ProgramFiles%\Common Files\Microsoft Shared\VS7DEBUG” to something else. I changed it to VS7DEBUG1.

After that, it started working just fine. What the original problem was, I have no idea.

  • More

Like this:

Like
Be the first to like this post.

dFactor 0.6 released

Posted by programmersunlimited on April 29, 2011
Posted in: General. Leave a Comment

For those who don’t know what dFactor is, it’s a Visual Studio add-in I developed that provides convenience refactoring/code generation options such as implementing INotifyPropertyChanged interface on a class or converting a class to a singleton. See a list of features below.

This new release includes a new feature that Visual Studio SHOULD have by default, but doesn’t. That feature is the ability to collapse all projects at once in the solution explorer. Working with large solutions from source control can cause the solution explorer to expand all projects when you load it up. Projects I’ve worked on have been up to 80+ projects which takes a long time to collapse manually each time.

dFactor is now in the Visual Studio Gallery (supports VS2010 only) and is free. If you would like to have features added, please let me know.
 
Download from Visual Studio Gallery
Download from Codeplex

Solution & Project

  • Collapse/Expand all projects in Solution Explorer 
  • Collapse/Expand Project and Project Items
Properties
  • Add backing – Adds a backing field to default property style.
  • Add backing with change notification – Adds a backing field and includes a call to OnPropertyChange()
  • Include change notification – Includes a call to OnPropertyChange() for a property that already has a backing
Fields
  • Encapsulate – Converts field to private and builds a public property
  • Encapsulate with change notification – Converts field to private and builds a public property with a call to OnPropertyChange()
  • Convert to property – Converts a field to a property (default style)
Classes
  • IDisposable pattern – Implements IDisposable pattern on a class. Detects class members that implement IDisposable and automatically includes disposing of those members in the Dispose() method
  • INotifyPropertyChanged pattern – Implements INotifyPropertyChanged pattern. Includes a working OnPropertyChanged() method
  • Convert to singleton – Changed the class to implement the singleton pattern. Adds a static instance property (lazy loaded) and converts all constructors to private.
Methods
  • Generate argument null checks (all) – Generates null argument checks for all reference and string type parameters, inserted at top of method body
  • Generate argument null check – Generates null argument check for a selected parameter (reference or string type), inserted at top of method body
  • Wrap with Try/Catch – Wraps the method with a Try/Catch block. Does not require any text selection.
  • Wrap with Try/Finally- Wraps the method with a Try/Finally block. Does not require any text selection.
  • Wrap with Try/Catch/Finally – Wraps the method with a Try/Catch/Finally block. Does not require any text selection.
  • More

Like this:

Like
Be the first to like this post.

Whole Tomato Visual Assist X Review Part 3

Posted by programmersunlimited on April 8, 2011
Posted in: General, Products. Tagged: Visual Assist X, Visual Studio, Whole Tomato. Leave a Comment

Finally I was able to get around to re-evaluating Whole Tomato Visual Assist X (10.6.1845.0). Here is my final opinion.

I used the points mentioned in the email to me from Kevin Sikes (See review #2) as a starting point and working through a project to get a feel for the other features.

What was good or better

Open File in Solution
This feature doesn’t seem like much when used on a small solution so I made sure to use an extremely large solution and it was excellent. Normally when I need to get to a specific file I have to navigate the solution tree. Since I over organize my projects this means going down a few levels. When the solution has 10 or more projects this can become time consuming.

Using the Open File in Solution feature of Visual Assist X it was extremely simple to find the file I wanted to open. The dialog initializes with an entire list of files in the solution and as you type what you want it narrows down the list using a ‘contains’ type of search so even if you’re not 100% sure what the file name is, you still have a good chance of finding it.

Encapsulate Field
Visual Studio already has this feature built in and includes a bunch of options that Visual Assist X doesn’t. However, the Visual Studio implementation is annoying and cumbersome. Visual Assist X quickly encapsulates a field without any annoying dialogs. The end result isn’t exactly how I like to encapsulate my fields since I like to rename the private field prefixed with an underscore and then set the property name to the original field name. Visual Assist X uses a proper case version of the field name. The problem is that if the field is already proper case, you will get a dialog asking what to call it.

You can change the snippet for the encapsulation using the ‘Edit VA Snippets’ dialog so you can add your modifications as you see fit.

Note: For those familiar with dFactor, the Visual Studio add-in I developed, you know that I prefer to rename the field using an underscore prefix. This prevents any possible name collisions. I also added many variates of this method such ‘Add Backing’ for properties with no backing. I would like to see more of these features available in Visual Assist X.

Spell Check
As I stated in previous reviews, I like the spell check. It seemed kind of silly at first, but it isn’t. After typing long strings for error messages, you start to wonder if you’ve spelled everything correctly. Visual Assist X checks your strings for misspelled words and provides red squiggles when you have a misspelling. Spell check is smart enough to know when you’ve entered the name of a member which is nice because if you’ve ever typed code into Word, you know that member names usually get red squiggles.

Comments: /* */
If you’ve ever needed to comment out just a portion of code you have either used the ‘Comment out the selected lines’ option in Visual Studio or you’ve surrounded the code with /* */ manually. Visual Studio doesn’t allow commenting portions of code. It comments out the entire line(s) using //. Highlighting a bit of code and pressing the * key, Visual Assist X will surround the bits with /* */ for you. Very convenient.

Refactoring code using VA Outline
The VA outline window gives you a view of the class definition (methods, properties, regions, etc). The VA Outline window allows you to select multiple methods at a time. From the ‘Surround’ context menu, you can wrap the selected methods in a region or comment them out. Other options include copy/cut/paste items as well as deleting them.

This is extremely helpful if you are trying to remove or comment out large methods or you’re trying to organize code using regions. The overall refactoring options are a bit limited but the ones that are there are very useful.

Reordering code using VA Outline
Using the VA Outline window, you can drag & drop members of the class to change the physical location of the declarations in the class file. The most beneficial part of this is that the VA Outline window shows regions. You can drag multiple members into the regions right from the VA Outline window. Doing this manually in code is usually time consuming and painful if you have large classes.

VA Navigation bar & List Methods
Visual Studio already has this functionality, but only to a certain degree. Where Visual assist X shines is that it gives you an outline of the members in the file, not just the current class, but it also shows you where you are inside of a construct. For example, if you’re deep inside of nested if/else/loops etc it gives you an indication of which construct you’re in. Kind of like a ‘You are here’ feature. For example, if you’re inside of an if/else if/else statement that is 100 lines long, you can click on a line of code and see which construct the code is contained in. My only complaint is that it doesn’t show the hierarchy, just the current location. I would like to see not only which construct I’m in, but also the construct parent and siblings so I can navigate quickly to the other constructs.

Snippets Editor
This is great because Visual Studio doesn’t have a snippets editor and Visual Assist X gives you a nice dialog to edit or create new snippets and assign the shortcut keys. No more manually editing files. Although the editor does give syntax highlighting, there is no intellisense but you can get a list of macros that can be inserted by right clicking in the code window or you can find a list on their web site http://www.wholetomato.com/products/features/vasnippets.asp.

Visual Assist X does have more features than Visual Studio does such as the ability to place the cursor after the snippet has been inserted, access to the clipboard, inserting date/time and even creating GUIDs. With the extended functionality VA Snippets provide, they are very powerful.

Improved Intellisense
I liked this feature the more I used it even though it functions the same as Visual Studio intellisense, by default it limits what you see to the current solution. For example, in a small project containing a few classes I typed ‘S’. Visual Studio gave me a large list of items containing ‘S’ where as Visual Assist X only showed me a list of 5 items. However, if I’m needing to ‘search’ or ‘browse’ intellisense to find an item, Visual Studio intellisense is a better choice. Visual Assist X allows you to switch to the Visual Studio intellisense using ctrl+space.

What was questionable

Change Definition features
These features don’t offer anything special for .NET developers and are still more for C++ developers.

What was a fail

Still not dark theme friendly
I turned off the default syntax highlighting to give me back my original theme, but there were still some issues such as the brace matching turns the curly braces black so I can’t see them. This was easily fixed in the config by setting ‘Display’ option to ‘min’.

Create Similar Member
When using the refactor option ‘Create Similar Member’ for a constructor, it doesn’t work the same as it does on a method or field. It adds a declaration to the current class like it was a field. By default if my constructor/class is called ‘SimpleClass1′ and I used Create Similar Member on it, it would add to the bottom of the class

class SimpleClass1;

If I remove ‘class’ from the declaration it still adds the new member in the same way just without the ‘class’ bit. Create Similar Member doesn’t work on properties either. Not sure why, but it doesn’t.

Conclusion

Overall, Visual Assist X is getting more useful for .NET developers. Whole Tomato is going in the right direction, but I think they should focus on providing features Visual Studio doesn’t have. At the end of the day, you’re going to have to give it a try yourself and see if it’s worth the investment or not.

Visit http://www.wholetomato.com to get a trial or Visual Assist X.

  • More

Like this:

Like
Be the first to like this post.

Posts navigation

← Older Entries
Newer Entries →
  • Microsoft MVP, MCTS, PostSharp MVP,
    PluralSight author, MashThis podcast
  • My Videos

    Isolating Code - A quick intro to Typemock Isolator

    Introduction to T4 Templates (series)
  • RSS MashThis Podcast

    • Building a Better API with Neil Mansilla
      Neil Mansilla, Director of Developer Products at Mashery, talks to the Mash This team (along with special guest host John Sheehan) and provides several great tips for building a better API.
    • State of the API Ecosystem with Adam DuVander
      Adam DuVander, Executive Editor of ProgrammableWeb.com, joins our hosts to talk about what’s hot in the world of APIs. We discuss current trends, emerging API genres, and where the best untapped potential lies for the future of mashup development.
    • ASP.NET Web API and Open Source with Brad Wilson
      Brad Wilson, Senior Developer on the ASP.NET team, talks about ASP.NET Web API, Microsoft’s newest framework for building HTTP and RESTful services. He also gives us a revealing look behind the scenes -- explaining Microsoft’s bold decision to open-source ASP.NET MVC, Web API, and Razor WebPages, and what that means for web developers and for the future of t […]
  • PostSharp Principals

    Day 1 – OnExceptionAspect

    Day 2 - Applying Aspects with Multicasting Part 1

    Day 3 - Applying Aspects with Multicasting Part 2

    Day 4 - OnMethodBoundaryAspect

    Day 5 - Visual Studio Add-ins

    Day 6 Your code after PostSharp

    Day 7 Interception Aspects – Part 1

    Day 8 Interception Aspects – Part 2

    Day 9 Aspect Lifetime & Scope Part 1

    Day 10 Aspect Lifetime & Scope Part 2

    Day 11 – EventInterceptionAspect

    Day 12 – Aspect Providers, Part 1

    Day 13 – Aspect Providers, Part 2

    Day 14 – Introducing Members and Interfaces, Part 1

    Day 15 – Introducing Members and Interfaces, Part 2

Blog at WordPress.com. Theme: Parament by Automattic.
Follow

Get every new post delivered to your Inbox.

Join 241 other followers

Powered by WordPress.com