Kevin Isom

Just a good ol' boy, by-God Virginia-proud and country-sophisticated -- sort of like a John Deere tractor with air conditioning and satellite radio.
Generating Images With .Net Part 1

I’ve recently had a project that required a great deal of image generation and manipulation. Not having done image manipulation in a good long while I thought it would be good to capture some of the “tricks of the trade”. One of the things I noticed in my searching for information on generating images in .Net is how bad variables were named. Hungarian notation or single letter names. This is not cool so I’m going to be trying to use descriptive names for all of my variables.

In this post I’ll cover how to display an image via the HttpResponse and then to generate an image from text.

Displaying Any Image

The following Code will write out the image to the HttpResponse in order for it to be displayed.

   1: protected void WriteImageToResponse(HttpContext context, Image imageToServe)
   2: {
   3:     context.Response.ContentType = "image/png";
   4:     using (MemoryStream memStream = new MemoryStream())
   5:     {
   6:         imageToServe.Save(memStream, ImageFormat.Png);
   7:         imageToServe.Dispose();
   8:         memStream.WriteTo(context.Response.OutputStream);
   9:         memStream.Dispose();
  10:     }
  11: }
  1. So the method takes the image and the HttpContext
  2. It sets the response type to image/png, you could also set the response type to other types of images.
  3. Next I new up a memory stream and then save the image into the memory stream with the ImageFormat set to Png
  4. Then I call dispose on the image class to make sure it doesn’t hang around eating up resources.
  5. Next the WriteTo method of the memory stream

Generating a Text Image

The following code sample will show how to generate an image from a text with an outline.

Setting the stage

   1: var fontCollection = new PrivateFontCollection();
   2: var fontSize = 72.0f;
   3: var fontLocation = "fonts/BIRDMAN_.ttf"; 
   4: fontCollection.AddFontFile(context.Server.MapPath(fontLocation));
   5: SolidBrush colorBrushForText = new SolidBrush(ColorTranslator.FromHtml("#567DB6"));
   6: StringFormat formatOfText = StringFormat.GenericTypographic;
   7: string textToDraw = "Hello World";
   8: var startingPointForText = new PointF(44, 20);
   9: var imageToRender = new Bitmap(600, 500);
  1. The code is setting up the Font from a location on the website (this is useful as you don’t need to install the font on the server)
  2. Also the size of the font, as well as the color to be used for the text.
  3. Next I specify the format of the text and set the text that will be generated
  4. Then I specify the starting point of the text
  5. Finally I create a new Bitmap with a width and height

Drawing The Text

   1: using (var masterGraphic = Graphics.FromImage(imageToRender))
   2: {
   3:     masterGraphic.Clear(Color.White);
   4:     masterGraphic.SmoothingMode = SmoothingMode.AntiAlias;
   5:     //uncomment the following line if you just want the text drawn
   6:     //masterGraphic.DrawString(textToDraw, fontToDraw, colorBrushForText, new PointF(xCoordinate, startingPointForText.Y), formatOfText);
   7:     GraphicsPath pathOfText = new GraphicsPath();
   8:     pathOfText.AddString(textToDraw, fontCollection.Families[0], (int)FontStyle.Regular, fontSize, startingPointForText, formatOfText);
   9:     Pen outlinePen = new Pen(Color.Black, 2);
  10:     masterGraphic.DrawPath(outlinePen, pathOfText);
  11:     SolidBrush solidBrushForText = new SolidBrush(ColorTranslator.FromHtml("#567DB6"));
  12:     masterGraphic.FillPath(solidBrushForText, pathOfText);
  13:     DisposeObjects(new List<IDisposable>{pathOfText,formatOfText,colorBrushForText, solidBrushForText,outlinePen});
  14:     masterGraphic.Save();
  15: }
  16: WriteImageToResponse(context, imageToRender);

  1. The code starts by taking the bitmap created earlier to be used as the “canvas” for the drawing
  2. The method call to Clear setting the background to white
  3. Next the SmoothingMode is set to AntiAlias
  4. A GraphicsPath is instantiated, this is the path of the text to be drawn.
  5. Now the Pen object is created to hold the color that will be used to draw the outline of the text.
  6. The method call to DrawPath with the path of the text passed and the pen with the outline color set.
  7. Now a new brush for the main text is created.
  8. Then the path is filled with the main color.
  9. The objects that implement IDisposable are passed to a method that disposes them.
  10. The graphic object has it’s save method called that generates the image in the bitmap that was passed
  11. Finally the graphic is written to the response.

The output

CropperCapture[10]

I hope this helps someone, and I hope it’s clear cut. In upcoming posts I’ll be explaining how to combine images, crop images and drawing shapes among other things.

kick it on DotNetKicks.com

Posted: Dec 11 2009, 04:11 PM by kevinisom | with 2 comment(s) |
Filed under: , ,
REST as Simple as Possible

I've been doing a lot of REST based services lately and for something that is as simple a concept as REST it is actually not the easiest thing to find guidance for a .Net developer. It's simple, or at least it should be. My first stop was the WCF Rest Starter Kit. I thought great, surely this would get me going with no fuss. I only wish it were so. I thought I could create a project with it and just get going. Instead what I got was a whole heap of code that didn't really start me on the way at all. I won't totally bag on the starter kit. I rather like the items around the atom publishing protocol. I briefly considered just writing an http handler for that but I knew that there had to be a better way.

Enter WCF.

It is actually incredibly easy to write REST services in .net. with WCF. 

Step 1

Create a new WCF service  in your website.

Step 2

Go to the cruft VS adds to your Web.config when creating your service and remove it and replace it with the following

   1:  <system.serviceModel>
   2:      <behaviors>
   3:          <endpointBehaviors>
   4:              <behavior name="web">
   5:                  <webHttp/>
   6:              </behavior>
   7:          </endpointBehaviors>
   8:      </behaviors>
   9:      <services>
  10:          <service name="Service">
  11:              <endpoint address=""
  12:                    binding="webHttpBinding"
  13:                    contract="IService"
  14:                    behaviorConfiguration="web"/>
  15:      </service>
  16:      <service name="WebsiteService">
  17:          <endpoint address=""
  18:                   binding="webHttpBinding"
  19:                   contract="WebsiteService"
  20:                   behaviorConfiguration="web"/>
  21:          </service>
  22:      </services>
  23:  </system.serviceModel>


And all you have to do it is add some attributes to your service contract

   1:  using System.ServiceModel;
   2:  using System.ServiceModel.Web;
   3:   
   4:  [ServiceContract]
   5:  public interface IService
   6:  {
   7:      [OperationContract]
   8:      [WebGet(UriTemplate = "/SayHello", ResponseFormat = WebMessageFormat.Xml)]
   9:      string SayHello();
  10:   
  11:      [OperationContract]
  12:      [WebGet(UriTemplate = "/SayHello/{user}", ResponseFormat = WebMessageFormat.Xml)]
  13:      string SayHelloToUser(string user);
  14:   
  15:      [OperationContract]
  16:      [WebGet(UriTemplate = "/SayHelloInJson/{user}", ResponseFormat = WebMessageFormat.Json)]
  17:      string SayHelloToUserInJson(string user);
  18:   
  19:      [OperationContract]
  20:      [WebGet(UriTemplate = "/GetPackage", ResponseFormat = WebMessageFormat.Json)]
  21:      Package GetPackage();
  22:   
  23:   
  24:      [OperationContract]
  25:      [WebInvoke(Method = "POST", UriTemplate = "/PlainPost", ResponseFormat = WebMessageFormat.Xml,
  26:          BodyStyle = WebMessageBodyStyle.Wrapped)]
  27:      int PlainPost(string username, string name, string message);
  28:   
  29:  }

Then implement the interface and you are good to go. I'll cover consuming these with both .Net and Javascript in a later post.

The attributes are where the real magic happens

The WebGet attribute tells WCF that this method is invoked via an HTTP Get Request.

The UriTemplate attribute property sets the URI of the call so on SayHello the url requested would be ~/Service.svc/SayHello

The ResponseFormat attribute property tells the service to return either XML or Json depending on the value of the WebMessageFormat enum

The WebInvoke attribute gives you to specify the type of HTTP request you make. The default method is POST.

The BodyStyle attribute property sets the body style of the messages sent to and from the service.

There you have it. Simple REST from WCF.

Cheers

Posted: Feb 21 2009, 08:07 PM by kevinisom | with 5 comment(s) |
Filed under: , ,
More Web Development with Internet Explorer

I have mentioned previously some useful tools for web development for IE, and now here are a couple more.

DOM Helper

CropperCapture[16]

This allows you to edit the css of a page much like EditCSS for Firefox

Fiddler

From the site

"Fiddler is a HTTP Debugging Proxy which logs all HTTP traffic between your computer and the Internet. Fiddler allows you to inspect all HTTP Traffic, set breakpoints, and "fiddle" with incoming or outgoing data. Fiddler includes a powerful event-based scripting subsystem, and can be extended using any .NET language."

CropperCapture[17]

A cool feature of Fiddler is the ability to write extensions for it. Definitely worthy looking into

Delicious

And not development related but damn useful (finally) is the Delicious plugin for IE. I have a tonne of bookmarks, keeping them synced between browsers and machines used to be a nightmare. Now I just use Delicious for IE and Firefox on all my machines and my problem is solved....Now if I could just cull some of my 2456 links I have saved I'd be alright.

Posted: Sep 25 2008, 12:55 PM by kevinisom | with no comments |
Filed under: ,
Preventing simple errors with the null coalescing operator

How often have you seen code like this?

   1:  string myAppSetting = ConfigurationManager.AppSetting["key"];
   2:  if(myAppSetting==null)
   3:       myAppSetting = "MyDefaultSetting"

Or worse yet not even do the check, then during the deploy process the appsetting doesn't get copied over to the instance and you get a null reference exception. That is not a good look.

That sucks. But is preventable in code. That's when the null coalescing operator(??) comes in handy.

Example:

   1:  string myAppSetting = 
   2:            ConfigurationManager.AppSetting["key"] ?? "MyDefaultSetting"
And that's it. A very easy way to prevent errors after deployment. Of course it's useful in other scenarios as well
 
Now the story in VB isn't nearly as nice
 
   1:  Dim myAppSetting As String = IIf(ConfigurationManager.AppSetting("key") Is Nothing, _
   2:  "MyDefaultSetting", ConfigurationManager.AppSetting("key"))
There is a gotcha with IIF as well because it's a function and not a language feature.
 
Anytime you can code to prevent error's  and keep the application working it's a win. Of course make note that the default value you set could cause other errors so use appropriately.
Posted: Sep 25 2008, 10:12 AM by kevinisom | with no comments |
Filed under: ,
Testing Web Services remotely

I hate it when I forget something. I had one of the guys on my team today asked me how to invoke a web service remotely as he was getting an error. Well I knew right away what the problem was. But could remember the solution so I had to look and now I'm gonna put it here so it'll be easier to find next time.

   1:  <system.web>  
   2:      <webServices>
   3:          <protocols>
   4:              <add name="HttpGet"/>
   5:              <add name="HttpPost"/>
   6:          </protocols>
   7:      </webServices>
   8:  </system.web>  

Now I don't recommend this for production, but it's pretty useful for testing.

Web Development with Internet Explorer

Firebug rocks. Nothing, I mean nothing beats it for debug web pages. But what do you do for problems specific to IE (most notably IE 6) Here are a list of tools I use to help cause telling the user to get a real browser is not a solution

Internet Explorer Developer Toolbar

This toolbar provides some of the features of firebug.
CropperCapture[2]

XRAY

Is a bookmarklet that let's you see information about elements on a page.
CropperCapture[3]

Companion.JS

An javascript debugger for IE
CropperCapture[4]

This may not be free in the future. Debug Bar from the same guy is also a very useful tool, but it's not free for professional use but probably worth the 59 euro if you do a lot of work with IE.

And finally something while not useful for debugging but damn useful in its own right is the Inline Search for IE.

CropperCapture[5]

Hope this helps somebody out.

Posted: Feb 29 2008, 04:01 PM by kevinisom | with 2 comment(s) |
Filed under: ,
Visual Basic.Net ain't half bad

There I said it.

I'm a C# guy. Now about 4 years when I started with .Net I started writing in VB.Net but I quickly decided to move C#. This, despite having spent the 3+ years prior working in ASP Classic. After a little bit of C# I quickly adopted the typical C# snobbish opinion of VB. For no good reason mind you, just cause it was different.

My how things change.

I've joined a VB team and instead of trying to make the team change to C# I figured I'd just get back to VB. Also we do a lot of work with XML so it got me looking into the VB 9.0 XML features and I found that you can do things like this:

   1:  Imports <xmlns:ns="http://contacts">
   2:   
   3:  Dim contact1 As XElement = _
   4:      <contact>
   5:        <name>Joe Bloggs</name>
   6:        <phone type="home">09-555-0144</phone>
   7:        <phone type="mobile">021-555-0145</phone>
   8:      </contact>

Okay, nifty and all, but what do you do from there...How about this?

   1:  Dim phoneTypes As XElement = _
   2:    <phoneTypes>
   3:        <%= From phone In contacts...<phone> _
   4:            Select <type><%= phone.@type %></type> _
   5:        %>
   6:    </phoneTypes>

And that will give you the following XML

<phoneTypes>
    <type>home</type>
    <type>mobile</type>
</phoneTypes>

That's rather cool and really useful with some of the stuff I'll be working on.

Check out the Overview of LINQ to XML in Visual Basic for more details

Now, I still want to say I'm a C# guy, but I think the snickering at the mention of VB stops now. 

Posted: Feb 29 2008, 01:49 PM by kevinisom | with no comments |
Filed under: , , ,
Visual Basic.Net and NUnit Gotcha

I like the NUnit 2.4 Constraint based syntax. So In my new role I am having to implement Unit Testing so I decided on going with NUnit to begin with despite my preference for MbUnit. But once I got started writing my tests, I discover Is is a keyword in VB (I'm more of a C# person, but hey I'm no language bigot). I kinda freak out a little. Did I do something wrong? Forget to add something? Google a bit and still no joy. Then I remember the code examples installed with NUnit and have a look and what do you know? Is is now Iz in VB. Not exactly as clear as Is but you gotta do what you gotta do. So now in VB a Unit Test looks like this

   1:  Imports NUnit.Framework
   2:  Imports NUnit.Framework.SyntaxHelpers
   3:  <TestFixture()> _
   4:  Public Class MyVIsualBasicSampleTests
   5:   
   6:      <Test()> _
   7:      Public Sub TestBlankForSyntax()
   8:          Assert.That(something.IsSomething(), Iz.False)
   9:      End Sub
  10:   
  11:      <Test()> _
  12:      Public Sub AnotherSampleTestForSomethingElse()
  13:          Assert.That(something.IsSomethingElse(), Iz.True)
  14:      End Sub
  15:   
  16:  End Class

And there you go.

Web Application Projects and Profiles

So, I'm working on a Web Application Project in Visual Studio 2008 and I realize I don't have a strongly typed Profile object...So I Google around and find that this a Problem in Visual Studio 2005 and that Microsoft didn't fix the problem in VS 2008. Needless to say I was a little unimpressed. But I also found the Web Profile Builder at the MSDN Code Gallery. I followed the instructions here and was away running.

Hiding a Popup Panel with JavaScript

Had a instance where I needed to close the Popup Control with JavaScript

   1:  <ajax:PopupControlExtender ID="pceShowPanel" runat="server"
   2:      TargetControlID="showPanel"
   3:      PopupControlID="popupPanel" 
   4:      BehaviorID="popupBehavior"                 
   5:      />

So with that on your page just hide it with hidePopup().

   1:  function Hide(){
   2:      $find('popupBehavior').hidePopup()
   3:  }

Of course you can show the popup as well with the showPopup() method. The real trick here is the $find shortcut method. The FindComponent method does just that and get's the component in this case the PopupExtender and allows you to call the methods associated with that control.

More Posts Next page »