Tech Talk A software developer on all things tech, and then some


Calling a PowerShell script from command line with parameters

Whether you need to setup a scheduled task or set up a build event in TFS, you most likely will need to know how to call a PowerShell script via the command prompt with parameters. The syntax is pretty easy, but if you miss a switch or two, it can have you scratching your head for a few minutes.

Your first step is to create the example PowerShell script so we can call it from the command prompt.

"Hello '$FirstName' and '$LastName'"

The Param keyword will tell the PowerShell script to accept these parameters. More information can be found here. Go ahead and save the code to a script so you can call via the command line.

Now comes the command line call. I'm going to give you the full call, then identify the pieces afterwards.

Powershell.exe -ExecutionPolicy Bypass -File "[PathToFile]\[FileName].ps1" -FirstName "Jacob" -LastName "Saylor"
  • Powershell.exe - This tells the command prompt to execute the following with PowerShell. If you get an error similar to 'Powershell.exe' is not recognized as an internal or external command, operable program or batch file. make sure you have PowerShell in your system path. You can specify the PowerShell executable path, but if your calling PowerShell on a regular basis, you are going to want to add this to your path.
  • -ExecutionPolicy Bypass - This tells PowerShell to run the script even though the script is not signed.
  • -File "[PathToFile]\[FileName].ps1" - This is the script you would like to run. If your path has spaces in it, you will need to surround it with quotes.
  • -FirstName "Jacob" -LastName "Saylor" - These are your parameters. You can omit the -ParameterName, but I would advise against it in case you change the order of parameters, add any additional ones, remove any, etc...

That's all there is to it!

Tagged as: , No Comments

C# Order of Operators (C# 6)

In hopes to better understand the order of operators in C# (6 & 7, but most will work for lower versions too), I decided to make a cheat sheet for myself in a table format. The list / section on the MSDN was helpful, but I wanted something a little more pleasing to my eyes... anyway, thought I'd share!


Visual Studio 2012 Keeps Crashing

VS2012 Crashing

When attempting to debug some SSIS applications, I encountered a quite annoying issue with my Visual Studio crashing anytime I tried to open a package. To hopefully help someone encountering a similar issue, I decided to list the steps here. Most of these steps are self inclusive, so feel free to try Visual Studio after each step to see if it worked for you.

View the Logs

Before you do anything, let's check the logs to see if we can find the root cause of the issue before we proceed with the steps below.


Visual Studio has an XML log which you can traverse and determine if there were any issues. This is also helpful to send to Microsoft, StackOverflow, etc...  in case of all else fails.

  1. Navigate to %APPDATA%\Microsoft\VisualStudio\11.0
  2. Open and review ActivityLog.xml
  3. Search for <type>Error</type>

Since the error most likely will be very tailored to you, Googling any errors will be your best bet.

Event Viewer

Another source of error log information will be the Event Viewer.

  1. Go to Run (Or Win + R)
  2. Enter eventvwr

Similar to above, this most likely will be unique for you. Hit Google and see if you can find your resolution.

Repair Visual Studio

Find your original installation media and run a repair on your Visual Studio installation. This will be the best first pass at repairing any corrupted files that might exist.

Remove the ComponentModelCache

If a component is failing to load, clearing out and forcing Visual Studio to recompile your components might fix the issue

  1. Navigate to %localappdata%\Microsoft\VisualStudio\11.0\
  2. Zip / backup the ComponentModelCache folder
  3. Delete the ComponentModelCache folder

Open Visual Studio in Safe Mode

If one of your extensions are failing, running Visual Studio in safe mode will load just the bare minimum.

  1. Navigate to %ProgramFiles(x86)%\Microsoft Visual Studio 11.0\Common7\IDE in an elevated command prompt.
  2. Enter devenv.exe /safemode

Reset User & Visual Studio Settings

Sometimes clearing out all of your setting might clean up something that is preventing Visual Studio to load correctly

  1. Navigate to %ProgramFiles(x86)%\Microsoft Visual Studio 11.0\Common7\IDE in an elevated command prompt.
  2. Enter devenv.exe /resetuserdata
  3. Enter devenv.exe /resetsettings



Fixing “There is an invalid number of result bindings returned for the ResultSetType: ResultSetType_SingleRow”

Sometimes when rushing through setting up a project we tend to forget to configure things, then are perplexed by the error messages since they don't always give you exactly where to look or what property you missed. This recently happened to me in SSIS with the Execute SQL Task. I had created an Execute SQL Task and set the Result Set to Single Row.

I then closed out of the editor dialog, lost focus on another development task, then came back and ran my package. I then got the following error message:

"There is an invalid number of result bindings returned for the ResultSetType: ResultSetType_SingleRow"

Which basically means I didn't map the result set. To fix this, just go the Result Set tab, then set the result set to a valid variable. You can set the Result Name to 0 if you wish since you are only working with a single value.

Filed under: SSIS No Comments

MembershipProvider.ValidateUser Always Returning False

Working with a legacy authentication system, I was attempting to get a login working for an application hosted locally. I was calling ValidateUser with the correct username and password within our system but noticed I was still getting false back from the method.

Here is a list of things I tried & looked for in case this might be your issue:

  • User is not locked out
  • User is approved
  • Ensure you are using the correct password format (Hash vs Encrypted)

Everything seemed correct and I was still getting false. Running out of places to look, I searched for any errors in the Event Viewer. I noticed I kept getting an error for the failed attempts:

Event code: 4006
Event message: Membership credential verification failed.
Process name: iisexpress.exe

This was different than what I've seen before. In searching for that specific message, I tried the following as well:

  • Added an Application Name to the Membership connection string - Peter Kellner
  • Adding hashAlgorithmType="SHA1" to my connection string - stackoverflow
  • Ensured everything had the proper permissions

So, what it ended up being was a mismatch from what I had in my applicationName in my provider connection string and what was in the application name field in my database. The applicationName in the provider connection string actually looks at the LoweredApplicationName column, not the ApplicationName column. After changing to match, everything worked as expected!



Common NuGet Package Manager Console Commands You Should Know

Within Visual Studio there is a console window that many know little about. I myself have finally started researching ways to improve my productivity via this console window, the Package Manager Console. In doing my research and using some of these commands on a daily or weekly basis, I figured I'd jot these down for my own notes, and anybody that uses NuGet.

Update Package

The update package without a project name will iteratively progress through your solution, find the package by the specified name, then re-install that package of the same version. This is my favorite command to run when pulling up a project from a freshly created branch.

Update-Package –reinstall [PackageName]

When you include a project name, the console will install the packages just within that project. Useful when you have one project causing an issue and you don't want to run the reinstall command of the entire solution.

Update-Package –reinstall -project [ProjectName]

Install Package

If you know the package name already you want to include in your project, the following command will be a quick alternative to the GUI of the NuGet Package Manager.

Install-Package [PackageName] [ProjectName]

Get Package

If you want to view the available packages via a supplied filter (There are thousands of packages), the following command will do just that!

Get-Package -ListAvailable -Filter [PackageName]


Additional Reference:

Want to learn some more Powershell / NuGet commands to speed up the NuGet experience? Take a look at the documentation on NuGet's site.



Grouping Objects by using GroupBy using LINQ in C#

Ever need to group by a property and want to use LINQ to do so? Happened to me recently and decided to explore the really simple way to group objects using LINQ using GroupBy.

I started off by creating a simple class for a person and created a list

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleSandbox
    public class Person
        public int PersonId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime Birthday { get; set; }

    public class GroupByExample
        public void GroupByDate()
            var people = new List<Person>
                new Person { PersonId = 1, FirstName = "John", LastName = "Doe", Birthday = new DateTime(1986, 12, 27) },
                new Person { PersonId = 2, FirstName = "Jane", LastName = "Smith", Birthday = new DateTime(1990, 6, 26) },
                new Person { PersonId = 3, FirstName = "Jamaal", LastName = "Charles", Birthday = new DateTime(1986, 12, 27)},
                new Person { PersonId = 4, FirstName = "Iman", LastName = "Shumpert", Birthday = new DateTime(1990, 6, 26)}

            // Our code will go here

Next add the following line

var groupedList = people.GroupBy(p => p.Birthday.Date);

This will group your list, people by the property Birthday. This command will result as IGrouping<TKey, TElement>. If this is your first time using this interface, imagine a Dictionary<key, value> where multiple values can be stored for each key. To iterate over the groupings, a couple of simple foreachs will work. In real scenarios, I would suggest maybe giving the resultSelector a try.

foreach (var group in groupedList)
    foreach (var person in group)
        Debug.WriteLine(string.Format("{0} {1}", person.FirstName, person.LastName));


Tagged as: , , No Comments

Resolving- Error: System.BadImageFormatException: Could not load file or assembly ‘*’ -When running Unit Tests

When attempting to run for the first time on a new machine the unit tests of a project, I got the following error message:

Unable to get type (Test method name), (Test project), Version=, Culture=neutral, PublicKeyToken=null.

Error: System.BadImageFormatException: Could not load file or assembly (Test project assembly information) or one of its dependencies.
An attempt was made to load a program with an incorrect format.

When attempting to resolve this issue, I came across a few solutions and decided to list what I found in hopes of helping someone else down the road

Changing the Test Settings

Go to Test -> Edit Test Settings -> Local

2015-05-15 09_32_42-ServiceNet.WebServices.Payment - Microsoft Visual Studio (Administrator)





Then  go to Hosts. Make sure Run tests in 64 bit process on 64 bit machine is selected.

2015-05-15 09_30_42-ServiceNet.WebServices.Payment - Microsoft Visual Studio (Administrator)







Note : The menu options might be different in the different versions of Visual Studio, but should be very similar to the above process.

Standardize the Build Platform

Another solution to try is to set your build platform to the same across the board. Go to your solution, right click, and select properties







Select platform -> Select Any CPU.

Your next best bet is to go into the test project's properties causing the error and explicitly set this as Any CPU. Even when selecting from above, it doesn't change the build still.







Don't Reference a Higher .NET Version

In your solution navigator, click the References project folder, and select the dlls in the project that is throwing the exception. Ensure the .NET versions referenced is either equal to or less then your hosting project.


Between the solutions above, I've solved this issue. That's not to say though there is another solution not listed. If you do happen to find another solution, please leave a comment and I will add as soon as possible. Thanks!


Filed under: Uncategorized No Comments

Problems Installing Internet Explorer 11

Microsoft has a few suggestions on how to go about fixing the installation issues when attempting to install Internet Explorer 11. To save you all some time you happened to land here before transversing those several pages, I went ahead and summarized the tips & suggestions to save some time.

  • Download and run Microsoft's Fix it tool. This might solve your problem without having to try the below methods.
  • Check that you meettheminimum operating system requirements and have the prerequisites installed.
    • For the most part, if you are running windows Vista or above, you should be able to handle ie 11 fine.
  • Make sure that your video card driver is compatible
    • Again, if you are running Vista or above, you should be fine here.
  • Check that there are no other updates or restarts waiting.
    • Start -> Type Windows Update to see a list of waiting updates
  • Temporarily turn off your antispyware and antivirus software.
  • Try another installer :
  • If for some reason the installer didn't finish installation, and Internet Explorer 11 shows installed, uninstall and try the installer again
  • Visit the following Microsoft's page and download the required updates.
  • Look up the install log. Google the error message andthereshould be at least a few posts containing a similar error message.
    • Go to the following location and search for exit codes, errors, etc... C:\Windows\IE11_main.log
  • A superuser question had a interesting fix, using pkgmgr to update the older and current version of ie.




Combining Objects in C#

There has been a few times I've need to copy models to view models, or very similar classes to each other, but wanted to clean up the code in the process. The result of that is a start to a helper method below to "combine" objects in C#. Code will stay static on this post. To retrieve updated code, visit via GitHub.

public static class ObjectJoin
        /// <summary>
        /// Attempts to combine values from two different objects with the same property names into one object
        /// </summary>
        /// <param name="firstObject">The object in which we will return with combined values</param>
        /// <param name="secondObject">The object in which we will be pulling values from</param>
        /// <param name="sourceOverwrite">If we overwrite the value from the first object if one already exists (Default is true)</param>
        /// <returns>The first object with combined values from the second object</returns>
        public static object JoinObjects(object firstObject, object secondObject, bool sourceOverwrite = true)
            if(firstObject == null || secondObject == null)
                throw new ArgumentException("One of the objects passed to JoinObjects is null");

            // Read in first object information
            var firstObjectHash = GetObjectPropertyHash(firstObject);

            // Read in the second object information
            var secondObjectHash = GetObjectPropertyHash(secondObject);

            foreach (var item in firstObjectHash)
                if (secondObjectHash.ContainsKey(item.Key) && (secondObjectHash[item.Key] != null || sourceOverwrite))
                    SetObjectProperty(ref firstObject, item.Key, secondObjectHash[item.Key]);
            return firstObject;

        /// <summary>
        /// Retrieves the parameter and value list of an inputed object
        /// </summary>
        /// <param name="obj">The object which to identify the properties and values</param>
        /// <returns>A dictionary of the parameter names as the key, and property values as values</returns>
        private static Dictionary<string,object> GetObjectPropertyHash(object obj)
            Type objType = obj.GetType();
            Dictionary<string, object> hashTable = new Dictionary<string, object>();
            foreach (PropertyInfo property in objType.GetProperties())
                hashTable.Add(property.Name, property.GetValue(obj, null));
            return hashTable;

        /// <summary>
        /// Attempts to set a value to a property dynamically 
        /// </summary>
        /// <param name="obj">The object which you are dynamically setting a property to</param>
        /// <param name="propertyName">The name of the objects property to assign the value to</param>
        /// <param name="value">The value to assign to the object's property</param>
        private static void SetObjectProperty(ref object obj, string propertyName, object value)
            PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName);            
            if (propertyInfo != null && value != null && propertyInfo.GetSetMethod() != null)
                    if (value.GetType().GetInterface("IConvertible") != null)
                        value = value.GetType().FullName == propertyInfo.PropertyType.FullName ? value : Convert.ChangeType(value, propertyInfo.PropertyType);
                        propertyInfo.SetValue(obj, value);
                    throw new Exception(string.Format("An error occurred when attempting to set the value of {0} of type {1}", propertyName, obj.ToString()));
Tagged as: , , No Comments

10 Ways To Improve Your Code Right Now

You may already be doing one or more of these tips, so this post might not be for everybody. But if you feel like you could improve your code even by a little bit, read on! Hopefully I can help make your code cleaner and easier to read. Also note, I didn't title this "Top 10 Ways..." because there might be different steps for different languages, as well as my own error. I'm still learning, and continue every day, these steps are some of what I have learned so far.

Also, this was meant to be a quick read... for a longer version of this article that goes further in depth and contains code examples, check out my other post on this subject, Writing Clean and Readable Code (C# Examples). (Still under development, posting soon!)

Step 1 : Learn the Language

"Think about cookbooks in the original sense. Although great cooks own cookbooks, no one who relies upon cookbooks can be a great cook. A great cook understands ingredients, preparation methods, and cooking methods and knows how they can be combined to make great meals. All a great cook needs to produce a tasty meal is a fully stocked kitchen. In the same way, a great programmer understands language syntax, application frameworks, algorithms, and software engineering principles and knows how they can be combined to make great programs. Give a great programmer a list of specifications , turn him loose with a fully stocked programming environment, and great things will happen." - Author,V. Anton Spraul (2012) Think Like a Programmer: An Introduction to Creative Problem Solving. Location: No Starch Press

That quote really sums it up. If you are looking to improve your code readability or performance, this is a great place to start. Knowing all the nooks and crannies of a language will allow you to use the language to its full potential. To take this a step further, learn about the different ways to perform a single task, and research the best for each situation. Again, let's think about this in cooking terms. A knife will still cut, but knowing which knife to use at what time can severely affect the end product.

Step 2 : Refactor Your Method At Least Once, Right Away

We've all been there when writing a complex method... You copy and paste code, create variables such as temp1, temp2, etc... and not a single comment is the end result. While the method and logic is still fresh in your mind, take a second before moving on to the unit test, next requirement, etc... and refactor right away. Remember back in highschool or college when you wrote multiple drafts before submitting an original? Yes, the general topic the paper is covering stays the same, but how you explain and structure that paper should increase with quality after each pass. That is how you should approach a complex method in which you just completed.

Step 3 : Look at Every Way To Solve a Problem

For simpler methods, this is not much of an issue. However when approaching larger, more complex methods, or even figuring out the architecture of a future project, one must go through almost every possibility to ensure that you are writing the method or class the best way you can. This step will not only reduce the amount of refactoring you will need to in the future since you have considered a plethora of possibilities, but also reduce the amount of technical debt you create by producing an incorrect or cumbersome solution.

Step 4 : Commenting Your Code

There are two main different comments you should include in your code. The first being in-line comments which serve as a code description for logic or business reason in a method. One way to include them for sure in your end product is to pseudocode your new methods with in-line comments. This will not only increase the readability of the code, but helps you logically set up the method you are about to write.

The second is XML documentation, usually at the top of a class, property, or method. These are important for three different reasons. The first is to describe what a class, property, or method does. This can be quite useful to somebody supporting your code so they don't have to logically walk through the method to find out what it is doing. The second is to create documentation in intellisense when you are referencing a class or property you made. When created using Microsoft's recommended tags, you can allow supporting engineers to quickly understand that method you wrote and what it was intended for vs having to navigate to its definition. The final reason is to be able to generate XML from your XML documentation for various uses.

Step 5 : Measure twice, cut once

"The carpenter’s saying, “Measure twice, cut once” is highly relevant to the construction part of software development, which can account for as much as 65 percent of the total project costs." - Author, Steve McConnell (2004). Code Complete, Second Edition. Location: Microsoft Press

This is in reference to the process before writing the code, the project planning stage. Project planning and gathering accurate business requirements is essential for medium to large projects for clean and easy to follow code. If you try and omit this in your project, you will end up with spaghetti code that will be near impossible to manage later on in the project. A common rule of thumb is specify at least 80% of the business rules up front. If you can stick to this, you can have less surprises, and less spaghetti code.

Step 6 : Generate Programming Standards, and Stick To It!

Another item you and your team can do right off the bat is to generate coding standards for your team to follow. In C#, Microsoft has already started this for you. This will make sure not only you, but your team as well will start outputting cleaner code. Make sure to implement code reviews to find issues before they even hit production environments.

Make sure to post in a general location and to keep updated with new versions of your language's framework.

Step 7 : Recognize Code Smell

For those of you not familiar with what Code Smell is, it's basically when code screams to be refactored. This can be when a method is too long, code is duplicated, excessively nested loops, etc... In the beginning of your programming career or learning a new programming language, you might have made a few of these mistakes and didn't recognize the code smell right away. However, after a few years and beyond these issues should become quite obvious to you. Fix these before you even move on to another method.

Step 8 : Make Methods and Classes as Small as Possible

One way to make your code easy to follow on a project level is the Top Down Design approach. Take your bigger issues and tasks and break down to smaller and smaller components until each method or property covers only a single operation. This will prevent you from creating "god classes" which contains way too much functionality for you or support staff to follow. Creating a very large class or method is common Anti-Pattern.

Step 9 : Using "White Space" To Your Advantage

A pretty obvious step, but one I wanted to make sure I mentioned. The way that we use white space when laying out code changes the way quite a bit of how we perceive a method. Items that are grouped together, for example instantiating local variables, shouldn't have a line space between the code. However, when you are working with local variables, then a foreach / if then else logic, then you want to make sure you have a blank line in between so your brain can quickly observe the different 'parts' of your method. This will help increase productivity of you and the support staff when scanning through a larger class or method.

Step 10 : Explain Your Logic to a Rubber Ducky

The final step is something called Rubber Ducking. Even though usually used when debugging code, I find you can use the same concept when writing new code. When you finish a method, and before you start your first refactoring pass (See Step 2) explain your logic to a rubber duck, or any inanimate object, on your desk. This will have you walk through your own code and catch logic errors you had accidentally scanned over when your first completed the method. This step in conjunction with stepping through executing code greatly decrease the amount of errors, and help you refactor your code to become organized logically.


In Closing

Again, I hope I helped in some soft of way. If you have other suggestions or comments, please feel free to leave a comment below.


%d bloggers like this: