Printing Directly From ASP.NET

This is clearly something you wouldn’t often do, but I have a project where the server is going to be a local machine in a remote and temporary jobsite location and the client needs the server to print directly to a special label printer.

Here is some code that accomplishes this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing.Printing;
using System.Drawing;

namespace TestingPrinting.Controllers
{
public class HomeController : Controller
{
public ActionResult Print()
{
PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.Margins.Left = 30;
pd.DefaultPageSettings.Margins.Top = 10;
pd.DefaultPageSettings.Margins.Right = 10;
pd.DefaultPageSettings.Margins.Bottom = 10;
pd.OriginAtMargins = true;
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
// Set the printer name.
//pd.PrinterSettings.PrinterName = "\\NS5\hpoffice

pd.PrinterSettings.PrinterName = "HP LaserJet 200 color M251 PCL6 Class Driver";
pd.Print();

return View();
}

void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
Font printFont = new Font("3 of 9 Barcode", 18);
Font printFont1 = new Font("Times New Roman", 11, FontStyle.Bold);
SolidBrush br = new SolidBrush(Color.Black);
ev.Graphics.DrawString("hello", printFont, br, 10, 65);
ev.Graphics.DrawString("world", printFont1, br, 10, 85);
}
}
}

Problems reinstalling nuget packages when target framework changed

We saw this error when trying to reinstall nuget packages on one application:

Successfully uninstalled ‘Microsoft.AspNet.WebApi.Client 5.0.0′.
Install failed. Rolling back…
update-package : Could not install package ‘Microsoft.AspNet.WebApi.Client 5.0.0′. You are trying to
install this package into a project that targets ‘.NETFramework,Version=v4.0′, but the package does not
contain any assembly references or content files that are compatible with that framework. For more
information, contact the package author.
At line:1 char:1
+ update-package -project Walshgroup.Web.CorporateExperience.vbproj -reinstall
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Update-Package], InvalidOperationException
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.UpdatePackageCommand

 

This was caused by us installing this nuget package initially when the project was targeting .net 4.5, and then later it was changed to target .net 4.0. 

Abandoning Nuget Automatic Package Restore

I just wrote about the switch from the MSBuild based “Enable Nuget Package Restore” option to the new and recommended “Automatic Package Restore.”

http://chrismay.org/2015/01/07/nuget-switching-from-enable-package-restore-to-automatic-package-restore/

Not only did this not solve our problems, but it seems the solution involves returning to the “wrong” way at least based on pretty much everything I read on the topic:

http://docs.nuget.org/docs/workflows/migrating-to-automatic-package-restore

http://www.xavierdecoster.com/migrate-away-from-msbuild-based-nuget-package-restore

http://blog.davidebbo.com/2014/01/the-right-way-to-restore-nuget-packages.html

Our problem lies in the use of common projects in multiple solutions.  Lets say you have SolutionA that contains AppA, ProjectX, ProjectY, and ProjectZ.  SolutionB contains AppB, along with ProjectX, Y and Z as well.  If you are working in SolutionA and you add a new Nuget package to ProjectX, then that package is downloaded to SolutionA/Packages/MyNewNugetPackage1.0/…/…/x.dll and ProjectX is given a hint path to search for that DLL reference at that file path.

Now what happens when your build server tries to build SolutionB (not SolutionA)?  Nuget restore downloads all the necessary nuget packages into the SolutionB packages folder, but ProjectX fails to build because it expected to find x.DLL in the SolutionA packages folder, but that folder is empty (the SolutionB packages folder was the one that was just populated with nuget packages).  So the build fails.

Because of the nature of how we store our projects in source control, if we could control the location of the packages folder it would solve our problem because we could use a common packages folder across all solutions. 

What would this mean?

It means that all solutions in this source control repo would all end up downloading their nuget packages, and looking for their nuget references, in the same folder.  This means that when SolutionA downloads it’s nuget packages, it the same spot where SolutionB would download it’s packages, so ProjectX will find what it needs not matter if it’s in SolutionA or SolutionB.

To make this work here is what I had to do.  First I needed to return the solutions to the “wrong” way of doing package restore.  This means right clicking on the solution in VS.Net and picking “Enable Nuget Package Restore”.  This will create a .nuget folder under the solution which will contain a Nuget.config file.  In this file you need to add the <config> node shown below.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
</solution>
<config>
<add key="repositoryPath" value="..\..\..\..\..\..\CommonPackages" />
</config>
</configuration>

Any change to Nuget.config requires a VS.Net restart to take effect.  Once you restart VS.Net nuget will be looking in this new “CommonPackages” folder for it’s nuget packages.  But your projects aren’t looking for their DLLs there.  The easy way to solve this is to just run the Package Manager Console and issue the command:

update-package -reinstall

This will not only download all the nuget packages your solution references, but it will reassign those references so that they are now pointing to the new location, “CommonPackages” in this case.

 

image

I was not able to find a way to do anything equivalent using the nuget.exe program from outside visual studio.  If that WERE possible, then I think this would have been a possible solution to my original problem, because unlike running “nuget.exe restore”, this command actually DOES change where the solution’s projects look for their DLLs. 

Nuget: Switching from "Enable Package Restore" to "Automatic Package Restore"

So it seems that starting with Nuget 2.7 and Visual Studio 2013, it’s no longer advised to use the “Enable NuGet Package Restore” feature (see image below). 

image 

Why?  Well now there is “Automatic Package Restore”, which is a feature that allows VS 2013 to automatically download missing packages as part of the build.  Again, see the image below.

image

But… there are a few catches.

First, this means that any build servers that use MSBuild will no longer automatically download missing packages.  You’ll need to script that out using “nuget.exe restore”.  (The positive side of this is that in some situations, like ours, the Enable Package Restore option was causing conflicts in our build server.  I won’t go into details but it had to do with multiple solutions referencing the same projects and bad HintPath values getting set.

Second, you need to go through some pains to extricate yourself from “Enable Package Restore” before you can successfully work with “Automatic Package Restore”.

What pains you ask?

Well first in your solution you should delete the .nuget/Nuget.exe and .nuget/Nuget.targets files.

Second, your project files (vbproj, csproj etc) you should remove these lines:

<RestorePackages>true</RestorePackages>

 

AND
 
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />

<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">  
    <PropertyGroup>    
        <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>  
    </PropertyGroup>  
    <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Actually I’m not sure if the first part dealing with the RestorePackages element needs to be removed.  I had found a few people saying you should remove it, but leaving it seems to not cause any problems (for me).

If you are doing a build and you get seeing errors like this:

Error    2    This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is C:\Data\Whatever\\.nuget\NuGet.targets.   

Then it means that you have some of the stuff in the project file still and you need to remove it before you can try building.

After doing this, if you then delete your solutions Packages folder and do a rebuild you should see Visual Studio automatically downloading the missing packages:

image

There have been a couple times where it seemed after making these changes I needed to close Visual Studio and reopen it.  But after that everything worked.

Problems getting Forms Authentication to work with a child MVC asp.net application

Recently we had an issue where we were trying to create an MVC (I think MVC5) web app that was going to be a virtual application off of a parent .net webforms application. By this I mean that the root of the site was a webforms app, and the new MVC app being created was ~/Whatever.

We were having some problems getting the authentication ticket from the parent site to work in the new MVC app. Both sites were running under the same app pool. We had other apps running the same way without problem. What was the issue?

Well, I believe it turned out to be that the MVC app specified .net 4.5 in it’s web.config file, while the root application was running with .net 4.0. The problem line was:

<httpRuntime targetFramework=”4.5″ />

As soon as we removed that line from the web.config it started working.

This stackoverflow post seems to suggest the same thing (not the answer with 3 upvotes, the one with 26).

http://stackoverflow.com/questions/12021863/upgrading-to-asp-net-4-5-mvc-4-forms-authentication-fails

It says:

If your forms authentication ticket needs to be shared between applications using an older version of the .NET framework, you must explicitly configure your .NET 4.5 apps to use the earlier machine compatibility modes, or they will not be able to encrypt/decrypt the forms authentication ticket.

In your .net 4.5 application’s web.config, set the compatibility mode attribute:

<system.web>
<machineKey compatibilityMode=”Framework20SP2″ />
</system.web>

This will allow your .NET 4.5 apps to work with forms authentication tickets generated by earlier .NET versions.

Note: If any of your servers do not have .NET Framework 2.0 SP2 installed, you will need to set the compatibility mode to “Framework20SP1″ instead.

We didn’t do this exact same fix, we just removed the one line from the new webapp’s web.config, but it sounds like the same problem.

Trying to use more than 1 WD “My Book” external drives?

I ran into a problem with a client today where we were trying to add some USB external storage for added onsite backup storage. The problem was, it never seemed to show more than 1 of the 2 external drives.

I tried the 2nd drive that wouldn’t show up on other machines, and it worked fine.

Turns out the problem exists in more recent version of windows. This happened on Server 2012. If 2 devices are connected, it will only assign 1 of them a drive letter if they have identical signatures.

WD My Book hardware ID collision

This explains the fix using diskmgmt:

http://wdc.custhelp.com/app/answers/detail/a_id/6571/~/only-one-drive-is-seen-when-connecting-two-wd-external-drives-of-the-same-size