onsdag den 3. juli 2013

Linq-to-sql enums support


I don't much like it when I must specify hard-coded values into my code. It can be a debugging nightmare, furthermore it looks ghastly. Microsoft's Sql Server OR-mapper linq-to-sql, which I like very much, unfortuantely do not have built-in designer support for generating enums from lookup-tables, which has previously found me doing that hard-coding I do not like to do. Well, no more - look on.

Consider the examples database-tables:


The 'periodStatusId' field is the one that I would ideally want to fill in as ...


myObject.periodStatusId = periodStatusIdEnum.OpenedStatus


... as opposed to ...


myObject.periodStatusId = databaseContext.PeriodStatus.Single( foo => foo.Description.Equals("Opened"));


Well there's a will and a way. What we can do is pre-define an enum and alter our database-context to reflect it. So, in your database-layer, define an enum and copy its values from the database. Like this:


public enum PeriodStatusEnum
{
ClosedByUser = 1,
ClosedBySystem = 2,
ReOpenedByUser = 3
}


Above, the integer corresponds to the auto-incrementing interger id of the lookup-table, the text corresponds to the description field.

It, well, it sucks, to have to pre-define the enumeration. Much preferred would be to do this in the designer, but that's not possible with linq-to-sql. So pre-define it we do, in the know that at least this will be a few hundred percent better than going hard-code style.

Now the enum has been created, we'll refer to this instead of the database's native type in the datacontext. Change both the lookup-table's and the referencing table's field types to your enum, pre-fixed with a 'global::' value, i.e. global::yourNamespace(s).periodStatusEnum. Like so:


That's it - now you can use your enumeration as opposed to actively looking up the value. Like this:


TidsRegPeriode period = new TidsRegPeriode();

// populate field by referencing your enumeration
period.periodeStatusId = timeRegistrering.Domain.PeriodStatusEnum.ReOpenedByUser;

... other fields populated...

dbContext.TidsRegPeriodes.InsertOnSubmit(period);
dbContext.SubmitChanges();


Again, it would be tremendously better if we could specify enums in the designer. But we can't - so this is a heck of a lot better.

fredag den 14. juni 2013

Razor calendar table

If you need to build a calendar-table in Razor, look no further, here's a snippet that'll accomplish just that:



@{
System.Globalization.GregorianCalendar cal = new System.Globalization.GregorianCalendar();

var firstDayInMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
int daysInMonth = cal.GetDaysInMonth(DateTime.Now.Year, DateTime.Now.Month);

DayOfWeek firstWeekday = cal.GetDayOfWeek(firstDayInMonth);
var dayNo = (int)firstWeekday;
int daysInMonthCounter = 1;
}

<table id="timeRegCalendarTable">
<thead>
<tr>
@for (int i = 0; i <= 6; i++)
{
<td>@CultureInfo.CurrentCulture.DateTimeFormat.DayNames[i]</td>
}
</tr>
</thead>
<tbody>
@while (daysInMonthCounter <= daysInMonth)
{
<tr>
@for (int j = 0; j <= 6; j++)
{
if (j == dayNo && daysInMonthCounter == 1)
{
<td>@daysInMonthCounter</td>
daysInMonthCounter++;
}
else
{
if (daysInMonthCounter > 1 && daysInMonthCounter <= daysInMonth)
{
<td>@daysInMonthCounter</td>
daysInMonthCounter++;
}
else
{
<td> </td>
}
}
}
</tr>
}
</tbody>
</table>


Hope it'll save you a half an hour.

mandag den 27. maj 2013

Formatting problems in copying code from Kindle


I use Kindle a lot, most recently I've taken to downloading book on development. But I faced problems in trying to copy the code in the books across to my development environment; the formatting, although beautiful in the book, was lost and rendered the copied text useless. I corrected the issues in notepad, but I eventually got so fed up with it that I made the below kindle-code-converter. Maybe it'll be of use to you, too.

Note that I've only just begun to collect conversion-rules - there will be times when the code doesn't format properly because you've come across a rule I haven't implemented yet. Just comment below with the problem and I'll fix it ASAP.

Here's the link to the converter:

Link to Kindle code-converter

onsdag den 8. maj 2013

Kinect Painting demo - simple setup


I went looking for a simple Kinect demo in which the user's right hand would be tracked and used as a paint-brush. I found some example projects here and there, but they were either rather elaborate with a bunch of functionality not required for a simple demo, or using third-party dll's.

So I put together my own simple thing, which I'm making available for download here.

I must confess to being not particularly impressed with the Kinect itself. The premise of the device is extraordinary, and it does function as the product description promises, but I found it slow in updating. It cannot in its present version be used as a "live" paint-application, as there will be a too noticable delay in its registrering skeleton movement. The LeapMotion device promises more and is probably the way to go for this, until a better, faster Kinect version arrives.

mandag den 29. april 2013

Javascript "static" class - make javascript code more readable


I usually use static classes for my C# helper-functions, when there're no properties to expose, nor any need to inherit from them. So this increases code readability. Javascript, however, doesn't have that feature, so how to immitate it? I usually do the below:



// declare object - recall that 'function' is an object in javascript
var WebServiceFunctions = function() {
}

// declare method on the object
WebServiceFunctions.webServiceMethod = function (parameter1, parameter2) {
// method code here

// return value if any
return xyz;
}


With the above code, I call my helper-method in my code like this:


var resultFromCall = WebServiceFunctions.webServiceMethod("foo","bar");


This has the odour of a static class. Of course behind the scene the "var WebServiceFunctions = function() {}" declaration signifies the creation of an object ("function" is an object in javascript), but I find that given the generic name - 'WebServiceFunctions' - my mind abstracts from this.

The javascript increases in readability, which may be an issue with a multitude of referenced javascript files.

There's a slightly better way, though. If the helper-functions are so generic in nature that they're applicable to many different purposes, they may be used in many different files. As such, the above will declare the "WebServiceFunctions"-object with every import of the javascript file. Better would be to check beforehand if the object has already been created, in which case there's no need to create it again:



(function () {
   
    this.WebServiceFunctions = this.WebServiceFunctions || {};

    
    var ns = this.WebServiceFunctions;

    ns.getMobilityPeriodId = function (serviceUrl) {
             // function code here
     }

})();



The above this.WebServiceFunctions = this.WebServiceFunctions || {}; is a conditional that checks if this.WebServiceFunctions has any value, in which case the already created object is returned, or - represented by the two pipes '||' - a new object is created. var ns is merely a reference, to avoid having to write 'this.WebServiceFunctions' repeatedly.

So that's a way to reference javascript in a 'namespace' sort of way. I find the above helps me keep my references handy and maintain the readability of my code, especially as a project starts to become clotted with javascript. If you wish to go depper into the subject matter, the above is what is known as the Javascript Module Pattern.

tirsdag den 23. april 2013

Simple jquery stacked bar chart

One way of doing an easy and simple stacked bar chart is to style a DIV to a desired length, then have its left-border represent the second data range. If you need more ranges you can always stack several DIVs on top of each other.

Here's example HTML for the graph itself...:


<div id="Graphs">
<h2>How are we doing?</h2>
<h4>&nbsp;Exchanges at a Glance</h4>
<p style="clear: both; padding-top: 1em;">
The below bar charts indicate, percentage-wise, the total exchange grant as compared to the allotted application grants.
</p>
</div>


And here's the annotated javascript to add the data as stacked bar charts:



// dummy example data
var exchangeGraphData = new Object([
{ allottedGrant: 70, totalGrant: 90, exchangeName: "exchangeNo1" },
{ allottedGrant: 30, totalGrant: 40, exchangeName: "exchangeNo2" }]
);

// render it
if (exchangeGraphData != false) {

// get width of the graph container. This will ensure our stacked bar charts do not exceed the container width limitation
var widthOfMainBar = Number($('#Graphs').css("width").replace("px", "")) - 16 /* 1em */;

// iterate over the example data
$.each(exchangeGraphData, function () {

// add a stacked bar chart for each 'record'
var div = document.createElement("div");
// add a class-attribute to the bar chart, so as to enable styling it
div.setAttribute('class', 'mainGraphBarDiv');

// add the bar chart to the container
$('#Graphs').append(div);

// establish fill-percentage for 'sub-bar', i.e. the second data range
var fillPercentage = (Number(this.allottedGrant) * 100) / (Number(this.totalGrant));

// translate the fill-percentage into actual pixels
var fillPixels = widthOfMainBar * (fillPercentage / 100);

// ... and apply those pixels as a left-border to the bar chart
div.style.borderLeft = fillPixels + "px solid #00f500";

// lastly, subtract the same number of pixels from the bar chart's width, or the added border will extend the bar chart unnecessarily
div.style.width = (widthOfMainBar - fillPixels) + "px";
});
}

// apply a little animation, if so desired
$('.mainGraphBarDiv').slideToggle(1500);


Below is my CSS for the 'Graphs' contaner and the 'mainGraphBarDiv' elements:


#Graphs {
position: relative;
float: left;
width: 350px;
text-align: center;
margin-top: 5em;
border: 1px dotted white;
padding: 16px;
background-color: gray;
}

.mainGraphBarDiv {
color: #0d0d0d;
text-align: center;
display: none;
height: 3em;
margin: 1em;
background-color: #92ff92;
}


The above HTML, javascript and CSS renders like the below:



How are we doing?

ERAMOB-2012-041 Exchanges at a Glance

The below bar charts indicate, percentage-wise, the total exchange grant as compared to the allotted application grants.

tirsdag den 16. april 2013

iTextSharp - multi-line form filling

For those of us using iTextSharp to generate dynamic PDF documents, one caveat I found was in controlling line breaks. In as much as the PDF standard has supported RTF since version 6.1, I was trying to add line breaks via RTF-code - "\par", i.e. Yet it turns out the iTextSharp parser appreciates the ever reliable System.Environment.Newline.

So format your PDF form field thus...:



... and you'll be able to reference your field and add line breaks thus:


PdfReader reader = null;
AcroFields af = null;

PdfStamper ps = null;

reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath(@"~/App_Data/your_pdf_document.pdf")), null);

ps = new PdfStamper(reader, stream);

AcroFields af = ps.AcroFields;

af.SetField("Your PDF form field name", @"This line is " + System.Environment.Newline + "broken");

// make resultant PDF read-only for end-user
ps.FormFlattening = true;

// forget to close() PdfStamper, you end up with
// a corrupted file!
ps.Close();


That's all there is to it.

Hope this helps you in your further career. And good luck with it, too!

Buy me a coffeeBuy me a coffee