Archive for the ‘C#’ category

Dynamically assigning css properties within the razor syntax.

February 9th, 2013

You may already know this, but I thought I would share anyways.  When you are writing webpages and you are loading the data dynamically through the razor syntax, it isn’t enough to just wrap your logic inside a <div> that has a class applied to it, you need to assign the css class within in the razor syntax.  The snippet below is an example of how you can assign a css class within the razor syntax:

@Html.CheckBoxFor(x => data.Selected, new { @class = "checkbox" })

The thing to focus on is the end of the snippet, the “, new { @class = “checkbox” }”  in that example I am setting the class name of the checkbox to a css class I have that styles the checkbox the way I want it to.  I couldn’t really locate an extensive list of these HTMLAttributes, so if you know of anything, please send me a link and I will update this article, thanks!!


Adobe Acrobat (PDF) files not displaying correctly on iPad?

October 30th, 2012

I have been working on an adobe acrobat export routine on the web that uses ComponentOne’s Active Reports tool to generate the files and I ran into a bit of a snag when trying to display the files on the iPad. I have posted the code below:

HttpResponseMessage message = null;
var pdfExport = new PdfExport();
var m_stream = new System.IO.MemoryStream();

var rpt = new YourActiveReport();

pdfExport.Export(rpt.Document, m_stream);
m_stream.Position = 0;
message = Request.CreateResponse(HttpStatusCode.OK);
message.Content = new StreamContent(m_stream);

message.Content.Headers.Add("Content-Disposition", "attachment; filename=yourreportname.pdf");
//this is the magic line
message.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return message;

I put a comment on the line that looks like this:
message.Content.Headers.ContentType = new MediaTypeHeaderValue(“application/pdf”);
I didn’t have that line in before and it will work just fine on standard machines like your desktop in your browser but since the ipad either doesn’t allow plugins inside safari or doesn’t know how to handle attachments the pdf was coming back as garbage, basically displaying the raw postscript in the browser, that wasn’t cool. All you have to do is add that line in and all is well, I hope this helps someone.

Windows Azure ServiceBus Demo

May 18th, 2012

Recently I was put to task with doing some research on the Windows Azure ServiceBus for an upcoming project at my workplace and I was rather impressed with what I found. I have put a repo out on github for anybody that is interested. I began down the road of something like what is seen on this site: The problem with following those directions on the link I just sent is that it defaults to some custom port that is not 80 and that wouldn’t work in my situation due to the fact that our app would be out in the public and I didn’t want to burden my clients with having to open up that port on their firewalls, so I went with a REST-based implementation.

The demo has two wpf windows in which you will need to make a couple of changes to work with your azure account, I have a snippet below that shows the spots that need to be changed.

 static string serviceNamespace = "<YourNamespace>";
 static string baseAddress;
 static string token;
 const string issuer = "owner";
 const string key = "<YourKey>";
 const string sbHostName = "";
 const string acsHostName = "";

Here is the link to the GitHub repo:


How to resolve issues with embedded images in email.

May 10th, 2012

I am embedding an image into an email that the server is generating using the SmtpClient in .net and I was having an issue with it caching images in certain situations and then Internet Explorer wouldn’t display the images at all, which is probably a security feature of IE, but the images did show up in Firefox and Chrome. Anyways, here is the code below that will make all of it work correctly in IE and should always show the images correctly, it generates a new Guid to always have a unique image Id so that caching won’t happen and then also tells the client that the ContentType is a jpeg which apparently IE needs to display the image correctly.

Guid contentId = Guid.NewGuid().ToString();

AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
  "This is a sample JPG embedded image<br><img src="cid:" + contentId + "">", 
  null, "text/html");

ContentType ct = new ContentType(MediaTypeNames.Image.Jpeg);

LinkedResource EmbeddedObjects1 = new LinkedResource("PathToImage\image1.jpg", ct);
EmbeddedObjects1.ContentId = contentId;

Using jQGrid with ASP MVC controllers

April 24th, 2012

I have been toying around with making the JQuery Grid found over on this site work with a controller and I finally got it working after much trials and tribulations, all because of a couple of little gotchas I either didn’t see in the documentation or just overlooked.

Here is the javascript code that will load a jQgrid into your div on your page that uses a plain ActionResult method in a MVC controller that is tagged with the [HttpPost] attribute.

                url: '/Product/GetProducts',
                datatype: "json",
                jsonReader : { repeatitems: false },
                mtype: 'POST',
                width: 550,
                colNames: ['Name'],
                colModel: [{ name: 'Name', width: 120, align: 'left', editable: true}],
                toppager: true,
                pager: $("#jqTablePager"),
                rowNum: 10,
                rowList: [5, 10, 20, 50],
                sortorder: "desc",
                viewrecords: true,
                multiselect: true

Notice this line ‘jsonReader : { repeatitems: false }’, you seem to need that line if you don’t have an Id column in your data that you are mapping to a column, that was really killing me cause I was just trying to show a simple list of products with a Name property in there.

The other ‘gotcha’ that I had to do a lot of research to finally find out was the way that you have to wrap your JSON in order for the grid to display it correctly. I have included the code below that will return a correct set of JSON assuming you are using a List of some kind of object.

var jsonData = new
                total = products.Count(),
                page = totalPages,
                records = products.Count(),
                rows = (
                    from p in products
                    select new {

And then finally here is the HTML that will place the jQgrid and a paging mechanism right below it.

<table id="list2"></table>
<div id="jqTablePager" />

Getting image of GIS map

April 17th, 2012

Have you been racking your brain trying to get an image from your map and have just about given up?  I have went through several GIS libraries including OpenLayers, ThinkGEO and some others and finally came across SharpMap which is an open-source .net library that does geo-spatial imagery and it just so happens to have a very nice little Image export routine that does the job and does it simple, here is all the code you need to generate a map from SharpMap:

//code to create Lat and Lon points
var list = new List<KeyValuePair<double, double>>();
 samplePoints.ForEach(delegate(ScoutSample sample)
      list.Add(new KeyValuePair<double, double>(Latitude,Longitude));

var layer = new VectorLayer("Field Layer", provider);
layer.Style.Fill = new SolidBrush(Color.Green);
layer.Style.Outline = Pens.Black;
layer.Style.EnableOutline = true;
var map = new SharpMap.Map(new Size(250, 250));

//code to add the points
foreach (var pt in points)
     //Add a single Point
     var geomColl = new Collection<Geometry>();
     var vLayer = new VectorLayer("GeometryLayer");
     var point = new SharpMap.Geometries.Point(pt.Key, pt.Value);
     vLayer.DataSource = new GeometryProvider(geomColl);

map.BackColor = Color.White;
var image = map.GetMap() as Bitmap;

Of course I am not showing you my provider at the moment, I am still fine-tuning the code and I will update this code at a later time, but this is just so easy, just instantiate the map and then call GetMap(), that is how it should be done. There isn’t any methods in OpenLayers that I could see and ThinkGeo has to have a control loaded before you can run the GetMap, which is garbage.

Converting Array of Guids to a List

March 21st, 2012

I have been doing more web work these days and on a recent project I was working on I had a need to convert an incoming string of guids to a List<Guid> for usage over in our repositories.  Well, my first thought to get the string to be split up into an Array[] of strings was to just call the Split() function in .net, and that will do the job if all you are wanting is an Array[] of strings.  it would look something like this:

The problem was when I tried to get .net to cast that over to a List using Cast or ToList(), it won’t convert this although you would think it would be smart enough to convert an array of strings that are Guids to a List that is Guids, but whatever.  This is where the ConvertAll() method on the Array class comes into play, it is in the .net 4 libarary so make sure you are on the right version.  The ConvertAll() will convert an array of one type to an array of another type, so I have updated my code to look like so:

Ids = Array.ConvertAll(request.Headers[“ids”].Split(‘,’).ToArray(), Guid.Parse).ToList();

Hope this helps somebody :).

Draggable WPF Controls

March 19th, 2012

I have a project where I needed to have WPF controls placed on a canvas and those controls have the ability to be dragged or positioned around on the screen somewhere.  I was using some custom logic I had written to draw rectangles and textboxes to the canvas and just watching the mouse events but that was a hack because sometimes the text would get too big to fit in the textboxes.  I came across this blog post and Josh Smith has a nice little DragCanvas class that wraps up all this functionality very nicely, all you have to do is put the controls in the Xaml and you are set, very nice job Josh!

This is nice for me because I wanted to display data in a grid and have headers and be able to drag those grids around the screen.  It also allows you to do other things like set transparencies on those controls and hide and show them as well.

.Net Developers are a bunch of whiners!!!

March 6th, 2012

I don’t know if you have seen Visual Studio 2011 or not yet, here is a screenshot of the solution explorer compared to how it used to look:  I personally do not care about how my tools look, but apparently the entire .Net development community cares more about how their tools look than how their tools actually function.  Don’t believe me?
Look at these links:

There are lots more ranting and raving going on, with more and more coming on everyday.  I think Microsoft is simply moving towards what other desktop applications such as Photoshop and Lightroom are doing with darker themes and the same colors to keep the IDE in the background and allow you to focus more on your actual application, you know, what you are getting paid to build??  Sure some are focusing on the improvements, but to me, its pretty telling about a development community when what your IDE looks like is more important that the actual features or actual code you can write.

Save WPF/Xaml controls to Bitmaps

February 17th, 2012

I don’t know if you have ever had the need to save an image of a Xaml/Wpf control but I did recently in a project. The method I have below will do just this:

public List<Bitmap> ExportToPng(List<object> objects) {
            var images = new List<Bitmap>();
            // iterate wpf objects, saving current canvas transform
            foreach (object o in objects) {
                Transform transform = c.LayoutTransform;

                // reset current transform (in case it is scaled or rotated)
                c.LayoutTransform = null;

                // Create a render bitmap and push the surface to it
                var renderBitmap =
                new RenderTargetBitmap(

                System.Drawing.Image ImageWork;
                // Create a memory stream for using image
                using (var stm = new MemoryStream()) {
                    // Use png encoder for our data
                    var encoder = new PngBitmapEncoder();

                    // push the rendered bitmap to it

                    // save the data to the stream
                    ImageWork = System.Drawing.Image.FromStream(stm);
                    images.Add(ImageWork as Bitmap);
                // Restore previously saved layout
                c.LayoutTransform = transform;
            return images;

The method does take an array of objects, of course you could modify it to only do one at a time but I had several I needed in my example. The key thing here is that in your xaml code, make sure you have your control in just a single stackpanel, or a stackpanel per control. I found that when I had several controls in a single stackpanel, it was only grabbing the first one, the rest of the controls were not getting generated. This would be a really nice feature that Microsoft could provide to all their controls because I know I am not the only person that has wanted this functionality but had to write this hack in get it accomplished.