More on ASP.NET webforms MVC hybrid

Here’s another great article by Scott Hanselman about using different .NET front-end technologies in the same project.


Add MVC capabilites to ASP.NET webform application

Because they both are built on the same framework, it’s pretty simple to get the two to play nice together. I used this as a guide:,guid,4f5a8ea1-1f90-4b32-a635-1d73d906aeca.aspx. It’s an old article but it worked for me. I’m using Visual Studio 2010, .NET 4.0 and MVC 3 with Razor.

The steps are as follows:

Add the following 3 references to your project:
System.Web.Mvc (be aware of what DLL version you’re adding)

Modify the project’s web.config. The easiest way is to create a new MVC project and copy over the value from there. You need to copy over the following sections, but don’t overwrite the existing values:
HttpHandlers (this didn’t apply for me because it wasn’t in the MVC web.config. Might be a .NET 4.0 or MVC 3 thing.)

Next modify Global.asax Application_Start method to perform the same functions as your temp MVC functions.

Then copy the web.config in the View folder of the MVC project and paste it in the View folder of your webform project. Also don’t forget to copy any scaffolding files such as _Layout.cshtml and _ViewStart.cshtml.

Finally, you need to let Visual Studio know that your project now handles MVC pages as well. This will allow you to use the IDE to create Controller, Views, and other MVC goodies. Open the temp MVC project file in notepad and look for the <ProjectTypeGuids> section. Copy that guid and add it to your webform project folder. The guid in my project is {E53F8FEA-EAE0-44A6-8774-FFD645390401}.

That’s it. Now you should be able to create MVC files just was if the webform project was an MVC project itself.

iTextSharp – Removing Fields from PDF templates

Sometimes the iTextSharp RemoveField() method won’t work. This is likely because the PDF template was created in Adobe LiveCycle. LiveCycle saves the file in XFA format. iTextSharp functionality against XfA files are limited to get and set. RemoveField(), at least for now, only works on AcroForm templates created in Adobe Acrobat.

BTW, here’s the code to read from a template, edit a field and save to a new file…or output to the browser.

string templateFile = Server.MapPath(“pdf/FSSTemplate.pdf”);
string newFile = Server.MapPath(“pdf/FSS.pdf”);

PdfReader reader = new PdfReader(templateFile);
PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));

//Use the two lines below to write the pdf to the browser
//MemoryStream ms = new System.IO.MemoryStream();
//PdfStamper stamper = new PdfStamper(reader, ms);

AcroFields fields = stamper.AcroFields;
fields.SetField(“field1”, “Hello World!”);

//Flatten and close
stamper.FormFlattening = true;

//If you’re writing to a file, you’re done here. If you want to write to the browser, use the code below.

Byte[] byteArray = ms.ToArray();
Response.BufferOutput = true;
string timestamp = DateTime.Now.ToString(“MMddyyyy_HHmmss”);
Response.AddHeader(“Content-Disposition”, “attachment; filename=PDF_” + timestamp + “.pdf”);
Response.ContentType = “application/pdf”;

.NET 3.5, Entity Framework, Add Function Import…

Gahhh!…? If your project is built on .NET 3.5 and you try to create an Entity Framework function using the “Add Function Import…” tool for a stored procedure that doesn’t return an EF object (instead return a scalar or nothing), the code for the function is not generated. Basically, all your spocs have to return an equivalent of one of your data objects. It all works fine if I use .NET 4.0 but I don’t think our servers have the framework installed yet. What to do…what to do…

SQL Named Instance Port Number

Heads up, you probably know the default port for SQL is 1433 but did you know the port is different for a named instance? And this port is dynamically set when you install the server. You can see what it is by looking in the registry. The below registry path is for SQL2008.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.(InstanceName)\MSSQLServer\SuperSocketNetLib\TCP\IPAll

There are more details in this article

And if you are using a named instance SQL server, don’t forget to adjust your connection string.

<add name=”MyConnString” connectionString=”Data Source=MyServerName, 51601; Initial Catalog=Northwind;user id=MyUserName;password=SecretPassword” providerName=”System.Data.SqlClient” />

Notice 51601 is the port number.

Dividing by zero

Don’t forget people, dividing by zero does NOT always throw an exception. Sometimes the result is Infinity. It seems to only throw a DivideByZeroException when the zero is an integer or decimal. Here are my test results for C#.

z = 10 / y;

int y = 0; //throws exception
decimal y = 0; //throws exception
decimal y = 0m; //throws exception
double y = 0; //Infinity
double y = 0d; //Infinity
float y = 0; //Infinity
float y = 0F; //Infinity


Ensuring image quality when resizing in .NET

I needed to create a web page where users can upload photos. In turn, these photos will be resized into three different dimensions (small, medium, and large) and displayed on the site. The original code I was using to resize the images was pretty much hit or miss. Often times the resulting image was blurry and/or pixelated. The original code took the file from the file upload control and saved it as a bitmap. Then it used the GetThumbnailImage method to resize the image. Here is a sample.

System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallBack);
System.Drawing.Bitmap bitmap = new Bitmap(fileUpload.InputStream);
System.Drawing.Image newImage = bitmap.GetThumbnailImage(600, 800, myCallBack, IntPtr.Zero);

private static bool ThumbnailCallback()
return false;

The callback method is called if the resize fails but I’m not sure what the IntPtr.Zero does. VS’s intellisense states “Must be System.IntPtr.Zero”, so who am I to argue. The code is very simple but not very effective. Today I found a better method. This time using an Image object instead and resizing it with the Graphics class. Finally, I use the Bitmap object to save the image.

System.Drawing.Image image = Bitmap.FromStream(file.InputStream);
System.Drawing.Imaging.ImageFormat imageFormat = image.RawFormat;
Size size = new Size(600, 800);
bitmap = new Bitmap(image, size.Width, size.Height);

Graphics resizer;
resizer = Graphics.FromImage(bitmap);
resizer.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
resizer.DrawImage(image, 0, 0, size.Width, size.Height);

bitmap.Save(“c:\resizedImage.jpg”, imageFormat);

There are a few important key elements here. First is the InterpolationMode. HighQualityBicubic gives you the best quality but I find HighQualityBilinear decreases the size by at least a few KB and I couldn’t tell the difference between the two just by looking at it. Also, when using bitmap.Save(), the image format parameter is not required but it makes all the difference. For example, I resized a 2112 x 2816 pixel to 600 x 800. If I didn’t specify the image format the size was reduced from 2.2 MB to 1.1 MB. When I did specify the image format, the resulting file size was 58 KB! Again, I could barely tell the difference between the two resulting images. And finally, always clean up after yourself. Dispose of objects you no longer need, especially if they deal with streams.