Determining the Active Network Interface Adapter Programmatically

The Network Interface Adapter is part of the physical system and you could find it on a Windows system by going into the control panel but what if you need to find the active NIC programmatically?

There is a function in .NET that can enumerate all of the network adapters on the system called GetAllNetworkInterfaces. Once you enumerate all of the adapters, you need to find which one is active. The following code can find the active adapter by using a UDPClient to get the local IP address and then matching it on the list of adapters.

public string ActiveNetworkInterface()
            string TwitterIP = "";
            UdpClient u = new UdpClient(TwitterIP, 1);
            IPAddress localAddr = ((IPEndPoint)u.Client.LocalEndPoint).Address;

            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
                IPInterfaceProperties ipProps = nic.GetIPProperties();
                foreach (UnicastIPAddressInformation addrinfo in ipProps.UnicastAddresses)
                    if (localAddr.Equals(addrinfo.Address))
                        return nic.Description;
            return "Adapter not found.";

Thanks to the author of an answer to the following question on stackoverflow.

Tagged with: ,
Posted in Development

Discovering MongoDB

MongoDB is an open source document oriented database engine developed and supported by 10gen. MongoDB can be downloaded from The documents are stored as JSON objects although they can be XML. Documents that are stored can be accessed using a REST based notation. When working with MongoDB the terminology is simiar to SQL although there are differences. Tables are collections and Rows are documents and columns are fields as shown in this comparison: The documentation shows that client queries working with MongoDB use Javasscript rather than SQL syntax. MongoDB was written in C++. Avoid the 32 bit version since it has a 2 Gb limit.  There is an online tutorial here:  The FAQs are here: MongoDB FAQ

Tagged with: ,
Posted in Development

Viewing Comments from a Completed Code Review in TFS

Long after a Code Review Request is completed, you may want to go back and look at the comments to make sure that all of the issues are still covered in the latest code. How do you do this since the Code Review is no longer available on the Work pane in Team Explorer?


Make sure that you have a query that can list all of the closed Code Review Responses that you have received. Your query should have a Work Item Type of Code Review Response and an Assigned To value of @Me.


  1. In the Team Explorer pane in Visual Studio open the Code Review Requests query from above to list the Code reviews.
  2. Find the Code Review that you are interested in and double-click on it.
  3. When the Code Review opens, click on the “Open Code Review in Team Explorer” link at the top left.
  4. View the comments in Team Explorer.




Tagged with:
Posted in Development

Automating Deployment of SQL Server Maintenance Plans


SQL Server maintenance plans provide automated backups of SQL Server databases. What if you want the same maintenance plan to be deployed to one or more additional servers? The deployment can be automated as explained here using SQL Server 2012 for the examples.


The artifacts that you need for the deployment are a DTSX package that defines the work of the plan and a T-SQL script to schedule the job that runs the plan. Do the following to create these artifacts.

  1. First manually create the maintenance plan that you want using SQL Server Management Studio. Open the server node, open Management, right-click on Maintenance Plans and select New Maintenance Plan. Set up the maintenance plan how you want it and then save the plan. See for more information on using the Maintenance Plan Wizard.
  2. Export the plan that you created as a file. Connect to Integration Services on the same server. Open the Stored Packages node, then the MSDB node, then Maintenance Plans. Find the plan that you created and right-click on it and select Export Package. Leave the default value of File System for the Package Location. Browse to a folder to save the file. You could name it MyMaintenancePlan.dtsx. See for more information about importing and exporting packages.
  3. Modify the maintenance plan that you created to schedule a job. You may have noticed that by default the plan was not scheduled. It could only be run on demand. To do this connect to the database engine and open the Management node and then the Maintenance Plans node. Find the plan that you created and right-click on it and select Modify. Click on the calendar icon in the Schedule column.  Setup the parameters on the  New Job Schedule window and save the job schedule.
  4. Create the T-SQL script by opening the SQL Server Agent node and then the Jobs node. Find the job that you scheduled in the previous step and right-click on it and select Script Job As/CREATE To/File and choose a file name like ScheduleMyMaintenancePlan.sql. Edit the script to remove the @owner_login_name parameter from the sp_add_job procedure so that the job will be created with a default owner on the target server. Also add additional script to create a subplan entry in the MSDB database placed before the commit transaction as follows.
    EXEC @ReturnCode = msdb.dbo.sp_maintplan_update_subplan
    @subplan_id = '{00000000-0000-0000-0000-000000000}',
    @plan_id = '{00000000-0000-0000-0000-000000000}',
    @name = 'My Maintenance Plan',
    @description = 'My Maintenance Plan',
    @job_id = @jobId,
    @allow_create = 1
    IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

    This script is to prevent errors during execution of the maintenance plan caused by the OnPreExecute event in the subplan. Remember to replace the zero guids for @subplan_id and @plan_id with the actual guids generated for your plan and subplan in your DTSX package. Do not attempt to insert into sysmaintplan_plans since it is a view not a table. For more information about using T-SQL to create a job schedule, see

At this point you should have two files (MyMaintenancePlan.dtsx and ScheduleMyMaintenacePlan.sql) that you can use for the deployment.


For the deployment the goal is to transfer the files to a new server and then install the package and create the job schedule. The installation can be automated using batch files, PowerShell or MSBuild.

  1. Deploy the MyMaintenancePlan.dtsx and ScheduleMyMaintenancePlan.sql files to the new server.
  2. Before installing the package ensure that the SQL Server Agent is enabled and running.
    sc config SQLSERVERAGENT start= auto
    net start SQLSERVERAGENT
    The space in front of auto is important. Use net to start the service instead of sc in order to wait for completion.
  3. Deploy the package to the new SQL Server using dtutil. It is possible to use PowerShell, however it may not be available on the target system due to security. Run the following.
    "$(ProgramFiles)\Microsoft SQL Server\110\DTS\Binn\dtutil.exe" /FILE MyMaintenancePlan.dtsx /DestServer sqlServerName /COPY SQL;"\Maintenance Plans\MyMaintenancePlan"
    For maintenance plans, it is better to install the package directly to the SQL Server rather than going through Integration Services since you may have named instances.
  4. Run a T-SQL script to create the job schedule.
    sqlcmd -S sqlServerName -i ScheduleMyMaintenancePlan.sql -x
    The -x parameter is needed to prevent sqlcmd from interpreting macros that are in the script.
  5. Verify that everything was installed correctly using SQL Server Management Studio.

Lastly ensure that you have scripted these deployment steps so that you can copy the files and the script to another server and then run the script.

Tagged with: , , , , ,
Posted in Development

Rebuilding Indexes on SQL Server

It is quite rare to need to rebuild the indexes on an SQL Server but it does happen. When it does, it is quite easy to rebuild an index using SQL Server Management Studio.

Open up the node for the tables in the database and right click on the Indexes folder and select “Rebuild All”. That presents a window with a list of indexes showing the fragmentation. Click on OK to rebuild all the indexes.

If you need to rebuild all of the indexes in a database with many tables, the following simple script performs the rebuild for each table.

   EXEC sp_MSforeachtable 'ALTER INDEX ALL ON ? REINDEX'

If you want to rebuild all the indexes with a custom fill factor then see the script in the following article.

Tagged with:
Posted in Development

Open Environments in Software Development

Open environments are becoming all the rage these days but how effective or appropriate are they for software development?

Open environment with close proximity

Open environment with close proximity

An open environment is a work environment where there are no walls surrounding the workstations. This is opposed to the traditional office layout of having individual offices for each worker.

Collaboration versus Distraction

An open environment can be brought into an office layout with the motivation of increased collaboration which is supposed to improve productivity. While collaboration is a relatable and understandable goal, how much collaboration is actually required in the practice of software development? After developers have met with BA’s and discussed what they are going to do, someone has to sit down and actually write code according to the requirements. This is an activity that requires more focus and concentration. I don’t know what the average percentage of time is spent in collaboration versus coding but for example: if a developer spends half an hour in meetings discussing the requirements and the rest of the day coding alone then that is only 6% of the time spent in collaboration. If that is typical then one would get more benefit from optimizing the 94% of time coding. This would more reasonably lead to office layouts and workstation designs that support the coding activity rather than the collaboration activity. Once placed in open environments, developers may increase collaboration but then suffer productivity loss during design and coding. The loss in productivity far outweighs the gain from collaboration. The extent of the loss depends on the attentiveness of the developer. Some can remain focussed in any kind of environment but many are easily distracted. It is also possible for collaboration itself to be reduced in open environments, since a developer placed in close range to peers could decided not to ask questions out loud but favour sending an email for fear of being heard asking a stupid question. This is a collaboration anti-pattern in my observations that worsens with the shyness of the developer and inversely with the confidence of the developer. How distracting can an open environment be for a developer that is easily distracted? I would like to give you an idea of some elements of an open environment that can be distracting to developers.


– talking

– cell phones

– UPS alarms sounding

– paging

– impromptu meetings

– people taking to themselves

– whining and complaining

– chatting

– phones ringing

– coughing

– sneezing

– clearing throats

– blowing noses

– crunching

– slurping coffee

– chairs squeaking

– chairs banging against the desk

– keyboard typing

– desk tapping

– pens dropping

– door bells

– headphones on too loud

– fans/blowers

– call to meetings

– vacuuming

– construction

– scraping and painting

– rearranging furniture

– blood pressure monitors

– crickets


– stretching

– yawning

– walking

– waving for attention

– looking through papers

– writing with a pen

– head scratching

– drinking water or coffee

– eating snacks

– cleaning

– throwing out garbage

– text messaging

– leaning back/forward

– moving chairs

– putting on headphones

– pacing


– fish

– indian curry

– burnt toast

– cheese

– popcorn

Collaboration versus Watching

When a development work environment is too open, developers may question the real motivation for that kind of environment no matter how much management touts the official reason of collaboration. It would be obvious to everyone in the environment that you can see who is working and who is not, so it is not that far of a reach to imagine that management wants to watch over their employees more closely. In that case the developers may feel disrespected. After going through education, training, certification and additional self-study and gaining experience in the trade, a developer may expect to be treated like a professional and not like a flea market vendor.

Open office

Office with glass barrier

Continued Momentum

Why do open environments continue on in the face of lost productivity, stress, turnover and even illness? Could it be that collaboration is such a valuable intangible benefit that it outweighs the consequences? Could there be such a rush of creativity and out of the box thinking to make it worthwhile? Despite the speculation there would have to be management objectives to support the practice whether or not they are apparent to all. Another theory is that management may be reluctant to accept feedback from employees or just not aware of drawbacks due to lack of quantitative metrics. What do you do if you are responsible for creating an open environment for developers after learning about the problems? One way to relieve the stress is through diversity as is in the case of Google (GOOG). They found that with a such a diverse workforce they needed diversity in their work environments. They have many different spaces, from open to closed, formal to informal, professional to recreational. This worked much better than the one size fits all model of office layout planning. Most importantly, obtain a professional design for your office layout and workstation design rather than just leaving it up to internal staff with some home renovation experience.

“If you think it’s too expensive to hire a professional, wait until you hire an amateur”. Red Adair

Developer Adaptation

What can you do as a developer when you find yourself placed in an open environment that you are not happy with. The first priority is to keep a positive attitude. If you let your attitude slip then it just makes the situation worse. Next work on improving your focus through exercising discipline. As it was said in the movie The Karate Kid, “Your focus needs more focus!” Following that try earplugs, headphones with soothing music or no sound at all. You can also try strategic placement of desk equipment to block out distractions. Get up out of your chair a walk a bit. Make sure that you have your lunch away from your desk in order to have a change of environment. Lastly try to find someone in management that is receptive to get concessions for your workstation or provide alternate areas or allowances to work from home.

Tagged with: , ,
Posted in Development

Adding to the Send to Menu on Windows 7

The Send to menu provides the ability to send files that you select in Windows explorer to applications that take the file type as a parameter. What if you want to send files to your own application or another application that does not have this context sensitive option?

To add your own Send to menu items on Windows 7 open up an Explorer window and paste the following into the address bar.


You should see shortcuts for the existing Send to items. Create your own shortcut in this folder with a target for the application you want. Next, to try it out, open another Explorer window and right-click on a file. You should see your item on the list.

Thanks to the How To Geek for an explanation.

Tagged with:
Posted in Uncategorized

SQL Server 2014 CTP1 Released

I hope you got plenty of use out of your SQL Server 2012 because SQL Server 2014 CTP1 has been released. You can dowload a trial here.

Performance is the first word mentioned in the improvements. Following that availability and reliability are next on the list but the interesting thing to me is disaster recovery since I’ve been chatting about it recently. It looks like you can backup your databases on Azure and then recover from there in the event of a disaster.

Next of interest to me is the in-memory OLTP which would give you great performance without installing any add-ons.

Tagged with:
Posted in Development

Microsoft Access DDL Types

When you are scripting data changes in Microsoft Access databases you may need to create temporary tables in order to update the data. This requires using DDL statements like CREATE TABLE. I usually need to lookup the field types since it doesn’t happen very often. Here is a table of types that you can use.

Desired Type DDL Syntax
Text TEXT(50)
AutoNumber COUNTER
ReplicaID GUID
Binary BINARY(50)

I got these types from the following Microsoft Support article.

Tagged with: ,
Posted in Development

Linq Query with Multiple Order Fields in Method Syntax

Ordering your sequences is simple using comprehension syntax with your Linq queries, but what if you want to use method syntax?

Here is a simple example with multiple fields in the order by statement.

var movies = from m in Movies
orderby m.CategoryID, m.Name
select m;

Now to accomplish the same thing in method syntax you just use apply a second ordering method like so.

var movies = db.Movies.Orderby(c => c.Category).ThenBy(n => n.Name);

Here is where I found an example for this on stackoverflow.

Tagged with:
Posted in Development