Dot Net Core Project Renaming Issue

Summary

I’m going to quickly demonstrate a bug that can occur in .Net Core and how to fix it quickly.  The error produced is:

The dependency LibraryName >= 1.0.0-* could not be resolved.

Where “LibraryName” is a project in your solution that you have another project linked to.

Setup

Create a new .Net Core project and add a library to it named “SampleLibrary”.  I named my soluion DotNetCoreIssue01.  Now add a .Net Core console project to the solution and name it “SampleConsole”.  Next, right-click on the “references” of the console application and add Reference.  Click the check box next to “SampleLibrary” and click the Ok button.  Now your project should build.

Next, rename your library to “SampleLibraryRenamed” and go into your project.json file for your console and change the dependencies to “SampleLibraryRenamed”.  Now rebuild.  The project is now broken.

Your project.json will look like this:

projectjson


And your Error List box will look like this:

errorlist



How To Fix This

First, you’ll need to close Visual Studio.  Then navigate to the src directory of your solution and rename the SampleLibrary directory to SampleLibraryRenamed.  

Next, you’ll need to edit the src file.  This fill is located in the root solution directory (same directory that the src directory is located.  It should be named “DotNetCoreIssue01.sln” if you named your solution the same name as I mentioned above.  Look for a line containing the directory that you just renamed.  It should look something like this (sorry for the word wrap):

Project(“{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}”) = “SampleLibraryRenamed”, “srcSampleLibrarySampleLibraryRenamed.xproj”, “{EEB3F210-4933-425F-8775-F702192E8988}”

As you can see the path to the SampleLibraryRenamed project is srcSampleLibrary which was just renamed.  Make that the same as the directory just changed: srcSampleLibraryRenamed

Now open your solution in Visual Studio and all will be well.

 

Side by Side Error

Summary

In this blog post I’m going to demonstrate how to generate an error that is difficult to find.

The Error

The error message that I’m going to show can be caused by a lot of different things.  The cause of this error will be the use of an “&” symbol inside the app.config file.  The error message you get will be:

The application has failed to start because its side-by-side configuration is incorrect.  Please see the application event log or use the command-line sxstrace.exe tool for more detail.

If you get this error, you’ll need to go to the control panel and open up the event viewer.  Then look under the applications section and look for a side-by-side error message.  This message will probably point you in the right direction.  Now I’m going to show how to generate this error with a few lines of code.  First, I’m going to create a console program in C# with Visual Studio 2015:

using System;
using System.Configuration;

namespace SideBySideBlogPost
{
    class Program
    {
        static void Main(string[] args)
        {
            string temp = ConfigurationManager.AppSettings[“test“];

            Console.WriteLine(“test output“);
            Console.ReadKey();
        }
    }
}

Then I’m going to create an app.config file and add the following inside the <configuration> section:

<appSettings>
    <add key=”testvalue=”test output & more testing“/>
</appSettings>

If you are using Visual Studio 2015, you’ll notice that you can’t compile the program because the “&” symbol is not allowed.  So I removed the symbol, compiled the program and edited it in the resulting app.config file in the bin/debug directory.  Then ran the program.  Here’s what the event viewer looks like:

 

 

The Cloud

This post is going to be a bit different from the usual.  I’m going to talk a little about cloud computing.  Specifically about Amazon’s cloud and what you should consider if you are thinking about using a cloud-based system.  This article will be geared more toward the business end of cloud computing, though I’m going to describe some technical details up front.

Some History

When the cloud was first offered, I was a bit skeptical about using it.  At the time I was working for a company that hosted their own equipment.  Internet connection bandwidth was not like it is today (I think we had a 5 megabit connection back then).  The cloud was new and virtualization was new and expensive.  There were a lot of questions about how to do it.  If I were to startup a new system for a company like that today, I’d recommend the cloud.

Any IT person who installs equipment for a data center today knows about cloud computing.  I have now worked for two companies that have hosted their equipment at a major data center, using virtual hosts.  The advantages of hosting equipment at a data center verses providing your own facility are numerous.  Off the top of my head are: Cooling, backup power, data bandwidth to the internet, and physical security to the site.  The cloud provides additional benefits: Pay for equipment as you need it, avoid delay required to order new equipment.

Amazon Web Services (AWS)

I examined a few different cloud services and I’ll blog about other services as I get time to gain some experience.  The reason I started with AWS is due to the fact that they have a 1 year trial for free.  That is marketing genius right there!  First, they encourage software developers to sign up and learn their system.  That allows them to get their foot in the door of companies that might start using cloud computing and abandon their physical data centers.  All because they have developers on staff that already know the technology.  Second, a year is a lot of time to experiment.  A person can get really good at understanding the services or they can attempt to build a new product using their service to see how it operates.

I signed up and it does require a credit card to complete the sign up.  That sends off a few alarms in the back of my head because technically, they could charge my card without me knowing it.  So the first thing I did was find out where I can review any charges.  I also noticed that there are warning messages that tell me when I’m attempting to setup a service that does not apply to the free tier (which means that I’ll get charged).  The great unknown is what happens if I accidentally get a flood of traffic for a test application that I’ve posted?  I guess I’ll find out, or hopefully not.

Anyway, here’s what the billing screen looks like:


This is accessible from the drop-down menu above with your name on the account (“Frank DeCaire” for my account).

There are a lot of services on AWS and their control panel is rather large:

Where to start?  I started with Elastic Beanstalk.  Amazon uses the word “Elastic” in all kinds of services.  At first, I thought it was just a cute word they used to describe their product the way that Microsoft uses the word “Azure”.  I began to read some documents on their services and the word “Elastic” refers to the fact that you can program your cloud to provision new servers or tear-down servers according to trigger points.  So you can cause more servers to be put on line if your load becomes too high.  Conversely you can automatically tear-down servers if the load gets too low (so you don’t have to pay for servers you don’t need during low volume times).  This is where the term “Elastic” comes in.  The number of servers you apply to your product is elastic.  

Back to Beanstalk.  The Elastic Beanstalk application has a web server and an optional database server.  So I clicked into the Beanstalk app and created an IIS server (there are several web server types to choose from).  Then I added a SQL Server Express database under RDS.  The database server required an id and password.  Once that was created there is a configuration details screen and it contains a url under the section named Endpoint,  This is the connection url that can be used by SQL Server Management Studio.  Once connected, I was able to manipulate SQL Server the same as a local instance.  I created tables and inserted data to make sure it worked.


IIS

The IIS server control panel looks like this:



You can click on the blue link to pop-up the website url that points to this web server (or server farm).  I have intentionally obscured the id by replacing it with “abcdefgh”, so the id above will not work.  You’ll need to create your own account and a random id will be generated for your own server.

Next, you need to download the tool kit for Visual Studio (click here).  I installed it on VS 2015, so I know it works on the newest version of Visual Studio.  I also tested on VS 2013.  There are a few gotchas that I ran into.  First, I ran into an error when attempting to deploy to AWS.  The error I received was that the URL validation failed (“Error during URL validation; check URL and try again”).  This turned out to be a false error.  What I discovered was that there was a permissions problem with access to IIS.  This can be found in the Identity and Access Management console (IAM).  I had a user created, but I did not assign a group to the user.  The IAM console is rather complex and requires some head-scratching.  Stack overflow is where I found the best answer to troubleshooting this issue:

aws-error-error-during-url-validation-check-url-and-try-again

My next problem gave an error “The type initializer for ‘Microsoft.Web.Deployment.DeploymentManager’ threw an exception.” which was just as cryptic.  As it turned out there are registry entries that SQL Server doesn’t remove when uninstalling older versions of SQL Server that interfere with the deployment software in Visual Studio.  The keys are:

HKLMSoftwareMicrosoftIIS Extensionsmsdeploy3extensibility
HKLMSoftwareWow6432NodeMicrosoftIIS Extensionsmsdeploy3extensibility


They both should be removed.  I also found that information from stack overflow:

Web deployment task failed. (The type initializer for ‘Microsoft.Web.Deployment.DeploymentManager’ threw an exception.)

At that point I was able to deploy my application and get a “Hello World” program running.  Once this capability is in place you can focus on the development process and not deal with configuration details until you need more capabilities.


Real World Application

Now that I have the basics down, I still need to test some of the other features of AWS (like their EC2 virtual servers).  However, I have enough knowledge to actually use AWS for a production system.  If you’re analyzing this service as a migration of an existing system, then there are a lot of things you still need to consider.  The first thing you’ll need to do is find out how much it’ll cost to store the amount of data that you already use.  How much web traffic are you using?  How many servers do you currently use?  These are going to go into an equation of cost.  When you compute those costs it should be lower than what you are currently paying for your equipment, data connection and facility.  If not, then you should not move your system.

If you are contemplating a start-up, you’ll have other factors to consider.  First and foremost, assuming you haven’t created your software yet, you’ll need to decide which web platform and database engine you’ll use.  If you’re not experienced with working at a company that has a large database system, you might not realize how much licenses can cost when you need to scale out.  In the early stages of development priority might be placed on how easy it is to get the site up and running.  This will haunt you in the long run if your user base grows.  I would seriously consider using free or open-source software where you can.  AWS has MySql and Apache with Java, Python or PHP.  Ruby is another option.  If you lock yourself into IIS and SQL Server, you’ll need to pay the extra licensing fees when your application outgrows the Express edition.  Once you have created thousands of stored procedures in SQL, you’re locked in, with a re-development cost that is astronomical or license fees that are almost as bad.

Another factor to contemplate in a start-up is the cost of getting your business going.  If you have seed capital, then you’re probably set for a fixed period of time.  If you are doing this on your own, then you’re probably worried about how much it will cost until you get enough customers to cover your fees.  You’ll need to compute this information ahead of time.  You need to ask yourself: “How many paying customers do I need in order to break even.”  If you are providing a two-tier website that has a free component (which is a great way to hook people) and a paid component that has powerful features, you’ll need to figure out what the ratio of paid vs. free customers there will be.  If you’re conservative with your figures, you’ll come out ahead.  I would start with a 5%/95% and compute what you need.  That means you’ll need to pay for 100% of your customer’s data and bandwidth usage, but you’ll only collect money from the 5% that are paying.  If you plan to sell advertisements, you’ll need to compute that.

Now you’re probably thinking “how do I know what these numbers are going to be?”  Well, that’s where this free AWS service is handy.  If you’re clever, you’ll get your application up and running before you sign up for AWS, or if your application is expected to be small and easy to build, you can build it directly on AWS.  When you’re ready to do some usage testing, you can put it on line and get it into the search engines.  At first you’ll end up with 100% free users.  Your traffic should increase.  You’ll have to take an educated guess at what to charge for the advanced features.  Too much, and nobody will see the value.  Too cheap and you’ll go broke.  The ideal price point would be something that seems cheap for what the customer receives, but enough to cover costs and earn a profit.  What that price point is, depends on what your application does.

AWS has a system for taking credit care information and keeping track of accounting information.  You’ll need this type of system in order to keep track of who has paid and how much they have paid for.  This service is called DevPay.  The goal is to automate the process of collecting payment information, activating accounts and deactivating accounts.  That’s a task that can overwhelm a person in no time if your product becomes successful.  Here’s the basic information on DevPay:

What is Amazon DevPay?


Other Considerations

Once you launch your application and it becomes established, you’ll need to consider your growth rate.  If your income is large enough, you can plan for new versions of your software according to how many developers you can keep on staff or contract.  In the cloud scenario, there is no need to pay for office space.  Technically, you can run the entire operation from your home.  Avoid adding the cost of an expensive facility until you really need it.  

Keep your eyes open on other cloud providers.  Google or Microsoft (and others) can provide equivalent services.  If their pricing structure makes your product cheaper to operate, consider porting to their cloud.  If you keep this in mind when you’re small, you can keep your application in a format that can be re-deployed quickly.  If you build in too many Amazon specific features you might be stuck until you can redesign a feature (Yes, I mentioned this fact after I talked about DevPay in the previous paragraph).  Another option is to use a cloud provider specific feature long enough to design your own non-cloud provider specific feature.  In other words, use DevPay for your application until you can hire developers or put in the development time to write your own (or possibly use another 3rd party product).  Always keep your application capable of being moved.  Otherwise, you’ll be hostage to a provider that someday may become hostile to your business.

Deployment tools are another feature you should get familiar with.  Automate your deployment as much as possible.  AWS has deployment tools that allow the developer to clone a production web server in isolation and to deploy a development version of your application for testing purposes.  If you need to do a lot of manual steps to get your application tested and deployed, you’ll be wasting valuable developer time.  Time that is very expensive.

Get familiar with the security features.  If you hire outside contractors to perform maintenance or development tasks, you’ll need to be able to shut off their accounts quickly if something goes wrong.  Make sure you understand what capabilities you are giving to another person.  Don’t allow a rogue programmer to put in back-doors and open holes to the internet that you don’t know exist.  Always monitor what is going on with your system.

I could go on all day, but at this point you should go to the AWS site and sign up for free usage.  Get some experience.  Click here.  When you get a “Hello World” program deployed and working, try some new features.  I would also recommend seeking out other cloud products from other vendors.  Google and Microsoft come to mind but there are others like AT&T, EMC, IBM, etc.

  

 

Giving Your DLL a Strong Name

Summary

In this post I’m going to talk a little about strong naming a dll and some of the gotchas associated with strong naming.

About Strong Names

If you’ve written .Net programs as long as I have, you’ve run into a problem where a dll does not have a strong name (also known as a signed dll).  Most dlls produced by Microsoft or downloaded using NuGet are already strong named and you don’t have to worry about them.  If you are creating a .Net program without using COM then you probably will also not have to worry about this problem.  If, however, you are creating a COM interface in order to use .Net code for your legacy non-.Net code, then you’ll need to strong-name your COM module as well as any dll that the COM library is dependent on (that is not already strong named).

How to Strong Name or Sign a DLL

Making your project create a strong-named dll is easy.  First you’ll need to generate a snk file.  There is an sn utility that is used to create this file and you can probably use the following syntax to generate the file (I have tested this on Windows 7, 10 and 2008R2):

“C:Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\sn” -k YourProjectName.snk

Technically, you can name this file anything you want, but I like to make it the project name to keep the file naming consistent with each project.  Now you need to link this to your project.  Right-click on your project, select “Add”, “Existing Item…”.

You’ll need to change your file type filter list to show all files (All files *.*).  Click on the snk file you created (don’t double-click).  The trick at this point is to click on the little down triangle next to the “Add” button and choose “Add as Link”. Then your snk file will be added as a link.

Now you need to right-click on the project again and select properties.  In the list of tabs on the left of the properties screen, select “Signing”.

Now click on the check box labeled “Sign the assembly”.  Then select your snk file from the drop-down list box and click on the save button (the floppy icon, or ctrl-s).

Now you can re-build your library and a strong-named dll will be created.

Checking DLL Strong Name

After you add a project or dll to another project, you can look in the references to find your dll.  Click on that dll and check the properties window.  You’ll see a property named “Strong Name”.  This should be set to “True”:

As I mentioned before, most dlls that ship with Visual Studio are already strong-named, but you might run into a situation where a package from NuGet is not strong-named.  In that instance you might have to find the source (probably GitHub or BitBucket) and download the source and perform the steps above to make it strong-named.

 

 

Using Assembly in Visual Studio 2013

Summary

In this blog post I’m going to demonstrate how to create an assembly language subroutine and call it from a C++ program.

Assembly Language

It’s been a few years since I’ve created any assembly language.  In fact, the last time I wrote a real assembly language program the tool to use was Borland’s Turbo Assembler in DOS.  Those were the good ol’ days.  

So I was browsing the web looking for a subject to blog about and I stumbled across this article about writing assembly in Visual Studio.  The web page is old (i.e. Visual Studio 2003 days) and it was setup for a computer science class at the University of Virginia.  They probably forgot that the page exists and I’m betting that it doesn’t connect to their website.  Google didn’t forget.  So here’s the link: Guide to Using Assembly in Visual Studio .NET.

I ran into a couple of issues with the instructions.  First,  $(InputPath) has been deprecated.  It’s now $(ProjectPath) and $(InputName) has been depricated and has been replaced by $(ProjectName).  Even with these changes the build does not work.  So I coded the name of the file since it is attached to the property of that file.

Here’s what my settings look like:

 

Assembly File Setup

Here are the step-by-step instructions for setting up an asm file in your c++ program.

Step 1: Create a C++ Project

I’m using Visual Studio 2013 in this example.  Go to File -> New -> Project.  Then you’ll need to go to “Other Languages” and open the “Visual C++” branch.  Click on the Win32 branch and click on “WIn32 Console Application”:


 Give your project a name and click the “OK” button.

 Next, you’ll have to right-click on the source files directory and create a new CPP file (add -> new item -> C++ File), name it “main.cpp”.

Now paste this main program in the main.cpp file:

extern “C” {
    void clear();
}

int main(int argc, char *argv[])
{
    clear();
    return 1;
}

We’re going to create an assembly program with a function named “clear”, which explains the “extern” directive.  You can name your functions anything you like, but you’ll need to change the extern directive to match.

Step 2: Add Assembly Code

Right-click on the source files folder again and add a text file (you can add another cpp file and just change the filename).  Name the file factorial.asm.

Copy and paste this assembly code from the University of Virginia example that clears the EAX and EBX registers:

.586              ;Target processor.  Use instructions for Pentium class machines
.MODEL FLAT, C    ;Use the flat memory model. Use C calling conventions
.STACK            ;Define a stack segment of 1KB (Not required for this example)
.DATA             ;Create a near data segment.  Local variables are declared after
                  ;this directive (Not required for this example)
.CODE             ;Indicates the start of a code segment.

clear PROC
   xor eax, eax
   xor ebx, ebx
   ret
clear ENDP
END 


Step 3: Setup Custom Build Commands


Right-click on your asm file and select “properties”.  You’ll see a Configuration Properties setup.  Change the Item Type to “Custom Build Tool” and Content to “Yes”:


You’ll see a new tree branch created on the left side of the window that has a “Custom Build Tool” branch.  Once that appears, you can click on it to enter your build parameters:

You can copy this line and paste it into the Command Line of your window:

“C:Program Files (x86)Microsoft Visual Studio 12.0VCbinml” /c /Cx /coff factorial.asm

That assumes that you installed Visual Studio 2013 with the default install settings.  Make sure you set your “Outputs” to “factorial.obj” because that will be the name of the file that hte linker expects.  Also, change “Link Objects” to “Yes”.  Apply your changes.

Now you should be able to build and run your application.


Troubleshooting

As the University of Virginia article mentions, troubleshooting requires you to put a breakpoint on the clear(); command in the c++ main file.  Then run your program to that point.  Next open the disassembly window (Debug -> Windows -> Disassembly).  

To see the CPU registers, you’ll need to open the Registers window (Debug -> WIndows -> Registers).

I shrunk the width of the registers window to force the registers to wrap vertically.  When you’re viewing the disassembly window you can use F11 to step into your assembly function and F10 to step through each assembly instruction.  Your Registers window will show changes to the CPU registers by turning them red:


Also, you can right-click inside the Registers window to add MMX registers and other data points.

You can also right-click on the disassembly window and show line numbers.  This will show the line numbers that occur in the C++ program itself.


Here’s the actual assembly program which clears the EAX and EBX by Xoring each register with itself, followed by a return:


Summary

Intel has an introduction to x64 assembly language, click here.

For the assembly language reference, click here.

University of Virginia currently has a good intro for x86 assembly, click here.




 

 

Visual Studio Project File

Summary

This blog post is written for developers that are new to Visual Studio, or have not ventured outside the programming environment itself.  I’m going to show a few handy features that are available in the project file itself.

The Project File

Any time you create a new project a project file gets created.  Your first project will be inside of the solution folder and be contained inside the solution.  Each project you add to a solution will create a new project folder and project file.  The project file extension for a C# project is “csproj”.  This file is an xml file which you can edit with any text editor.

The solution file can also be edited and this can be handy if you have to fix a problem.  One problem that occurs quite often is if you rename a project folder from windows.  You can just edit the .sln file and change the project directory name.


BeforeBuild and AfterBuild

Back to the project file…

At the bottom of the project file is a commented section called BeforeBuild and AfterBuild.  The purpose of this section is to add commands to perform tasks before a build starts or after a build ends.  I have used this section to copy the newly built dlls into the destination directory.  First, you’ll need to remove the comments:

<!– To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets.
<Target Name=”BeforeBuild”>
</Target>
<Target Name=”AfterBuild”>
</Target>
–>



Next, you can add a copy command inside the AfterBuild xml tags:

<Target Name=”BeforeBuild”>
</Target>
<Target Name=”AfterBuild”>

<Copy SourceFiles=”$(TargetDir)$(ProjectName).exe” 
  DestinationFolder=”.” ContinueOnError=”true” />
</Target>

The current directory specified will be the project directory.  By using the $(TargetDir) variable, you can grab the dll or exe file from the directory that it was just built to.  Otherwise you’ll need to know if it went into the BinDebug or BinRelease folder.  Using the $(ProjectName) variable guarentees that the filename is correct, since this will be the name of the exe.  However, if you want to copy other dlls or files, you’ll need specify them directly.

What is a good use for the BeforeBuild?

Now you might be contemplating why you would want to put anything in the BeforeBuild section.  You might have a project where you would generate some C# source code depending on data in a database.  An instance is similar to an ORM generator such as the NHibernate code generator that I developed (see some of my previous blog posts).  In such a case, you might want the convenience of regenerating your ORM definition just before building a particular application.

You could also have a project that uses a language generator such as YACC or ANTLR.  The language generator would be called before build, then the resulting C# source could be copied into your project and then the build could proceed to build your program.

Troubleshooting BeforeBuild and AfterBuild

 Create a new console project and edit the project file.  Change the AfterBuild to this:

<Target Name=”AfterBuild”>
<Copy SourceFiles=”no.exe” DestinationFolder=”.” ContinueOnError=”true” />
</Target>

Don’t forget to uncomment this section.  Now open your project and select Build -> Rebuild Solution.  You should see a warning:

As you can see, there is an error that the file was not found, then it tells the file that the error was in, the line number and column.  If you remove the “ContinueOnError” section, you’ll get an error message instead of a warning.  Your build will stop at that point, though the normal build has completed because this occurs after your build.  If you get an error in the BeforeBuild section, your build will not occur.

List of all Macros Used by BeforeBuild and AfterBuild

You can go to Micorosofts site to get a list of all the macros that are available:

Macros for Build Commands and Properties 

 

Removing the NuGet Package Manager Files

Summary

The NuGet package manager is handy for finding DLLs and supporting modules when you want to get something up and running fast.  I like the search capability and the fact that the package knows what to install to make it work.  However, I don’t like the fact that the package manager downloads every .Net version of the package plus every conceivable support file.  I understand why it operates the way it operates, and I’ve seen the NuGet manager update packages when I change the .Net version of projects, etc. etc.  In this post, I’m going to show how to unload the NuGet baggage and strip your application to what is needed.  This will reduce the size of your installation and/or deployment package.


The NuGet Package Manager

You can add DLLs to your project by going to the Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution (or you can use the console).  Then select a package and hit the “Install” button.  Some projects have packages already installed.  One such project is the MVC4 project.  If you open Visual Studio (I’m currently using VS 2012) and select “New Project”, then inside the “Web” projects, select “ASP.Net MVC4 Web Application”, then select the “Empty” application.  Once the project is completed, you’ll see a file in your project called “packages.config”.  Open that file (it’s an XML file, just double-click on it).  Listed in this file are all the DLLs in the NuGet package.  This will be your key to untangling the needed components.

In my sample, I have this in my packages.config file:

<?xml version=”1.0encoding=”utf-8“?>
<packages>
  <package id=”Microsoft.AspNet.Mvcversion=”4.0.20710.0targetFramework=”net45” />
  <package id=”Microsoft.AspNet.Mvc.FixedDisplayModesversion=”1.0.0targetFramework=”net45” />
  <package id=”Microsoft.AspNet.Razorversion=”2.0.20715.0targetFramework=”net45” />
  <package id=”Microsoft.AspNet.WebApiversion=”4.0.20710.0targetFramework=”net45” />
  <package id=”Microsoft.AspNet.WebApi.Clientversion=”4.0.20710.0targetFramework=”net45” />
  <package id=”Microsoft.AspNet.WebApi.Coreversion=”4.0.20710.0targetFramework=”net45” />
  <package id=”Microsoft.AspNet.WebApi.WebHostversion=”4.0.20710.0targetFramework=”net45” />
  <package id=”Microsoft.AspNet.WebPagesversion=”2.0.20710.0targetFramework=”net45” />
  <package id=”Microsoft.Net.Httpversion=”2.0.20710.0targetFramework=”net45” />
  <package id=”Microsoft.Web.Infrastructureversion=”1.0.0.0targetFramework=”net45” />
  <package id=”Newtonsoft.Jsonversion=”4.5.11targetFramework=”net45” />
</packages>

First create a directory in your project, or you can create a directory in your solution to contain the DLLs that you’ll be using.  I usually name it “3rdPartyDLLs”.  If you have a lot of projects that use the same DLLs, you can create a shared directory.  I prefer to keep the DLLs with the project, so I know the versions match the project when it was designed.  Next, you’ll need to open the “References” directory of your project.  Look at the first DLL that is listed in the xml file and match the name with the DLL listed in the References.  If the DLL is in the References, then navigate to the solution folder and find the “packages” folder.  Open that folder, drill down to find the matching DLL.  If there are two or more .Net folders, then check the version in the XML file (most of the above are .Net 4, but some are 2).  Drill into the .Net folder and copy the dll and xml (if it exists) files into your “3rdPartyDLLs” folder (just drag the files into your project folder of visual studio, a copy will be made).

Next, delete the reference in your “References” folder.  Then “add reference” by right-clicking on the “References” folder and selecting “add reference”.  Use the browse button to navigate to your project’s “3rdPartyDLLs” folder and select the DLL file that you just removed from the “References” folder.

Last, delete the entry from the packages.config file.  Rebuild your project to make sure it still builds.  If it does not build, you might need to make the reference DLL copy local (click on the DLL in the “References” folder and you’ll see in the properties window a “Copy Local” flag.  Change that to “Yes”).

Now repeat this process until you have an empty packages.config file.


Final Cleanup

The final cleanup involves deleting the packages.config file in your project.  Then delete the entire “packages” folder in your solution folder (you may have difficulty deleting the whole thing at once because Windows thinks that those files are opened someplace.  I usually drill down into sub directories and delete the stubborn dlls first.  Then back-out and delete the whole thing).  

Now make sure you rebuild your project and fix any errors.

You can verify that you removed all NuGet package components when your packages.config file doesn’t re-appear and you can click on each DLL in your “References” folder and make sure the Path to each file doesn’t point to a package folder.

 

Embedded Resource

One of the clever features of Visual Studio and technically, the assembly model itself, is that you can embed your data files right inside the assembly dll.  The advantage of doing this is so you can hide your data and prevent someone from altering it with a text editor (assuming you are using text data).  Of course, the end user can still hack the assembly itself, but it takes a bit more effort.  Plus, there is one less file that you need to worry about deploying to the end desktop.  Deploying files is a pain and you have to keep track of the directory and permissions of the file in order to read from it.  Also, you can use this technique to embed test data that can be used in your unit test project without worrying about the location of the file.

Here’s how it’s done and a few tricks that you’ll need to keep in mind when you do this for your own projects.  First, I’m going to just create a console application called “EmbeddedResourceDemo”.

Next, create a blank text file named “MyFile.txt” and put some text in it.  I added the word “test” to my text file just to demonstrate the mechanics of this.  Drag the text file into your project.  The entire project solution should resemble this.


Next, you’ll need to click on “MyFile.txt” and modify the properties.  Change the “Build Options” to “Embedded Resource”:

Now you’ll need to add a couple of usings to your main project:

using System.IO;
using System.Reflection;

Now add this code to your project:

namespace EmbeddedResourceDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var resourceName = “EmbeddedResourceDemo.MyFile.txt“;

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            using (StreamReader reader = new StreamReader(stream))
            {
                string result = reader.ReadToEnd();
                Console.WriteLine(result);
                Console.ReadKey();
            }
        }
    }
}

Full Credit where it’s due

I obtained my basic code from a stack overflow answer here: How to read embedded resource text file.  This site is very useful for figuring out complex problems quickly. 


Run the Code

One of the “gotchas” that you’re likely to encounter is the name of the file (the resouceName).  You must include the assembly name in this text otherwise the GetManifestResourceStream will not be able to find your file and it will return null.

The second gotcha you’re likely to run into is the fact that you need to change the “Build Action” to “Embedded Resource”.  The same result will occur, the variable “stream” will be null.

If you run the above program, you’ll see your test message on the console window.