Wednesday, December 7, 2011

Wrote my first jquery plugin it strips out html for an input field

I needed a way to remove up html from my input from the users.  This is my first attempt at it.
(function ($) {
    $.fn.safeVal = function () {
        var value = $(this).val();
        var ret = $('<div>').html(value).text();
        return ret;

Thursday, August 4, 2011

My Rules for Development

  1. If you think you need a region you really need a new class.
  2. If you are using a for loop in c# there is something wrong with your code.
  3. If you are using a foreach fix you code so you don't need it.
  4. If you think you want to use exceptions to control flow stop now and go to your room and think about what damage you may do.
  5. If you don't write a unit test it's not done.

Wednesday, May 18, 2011

Some Fun With Linq.

A friend of mine was asking me how I search through dictionary that contain lists of objects with Linq. After I chatted with him for a bit. I realized I don't do that.  I have one huge list that I parse out with linq.  It makes my life easier.  Here is a code example of what I would use.

        public class section
            public string Group { getset; }
            public string Order { getset; }
            public string Section { getset; }
            public string Title { getset; }
        static void Main(string[] args)
            var sec = new List<section>();
            sec.Add(new section { Group = "1", Order = "1", Section = "1.1", Title = "one one" });           
            sec.Add(new section { Group = "1", Order = "3", Section = "1.3", Title = "one three" });
            sec.Add(new section { Group = "1", Order = "2", Section = "1.2", Title = "one two" });
            sec.Add(new section { Group = "2", Order = "1", Section = "2.1", Title = "two one" });
            sec.Add(new section { Group = "2", Order = "2", Section = "2.2", Title = "two two" });
            sec.Add(new section { Group = "3", Order = "1", Section = "3.1", Title = "three one" });
            //creates a diction with all the sections in order grouped by group.
            var jmp = sec.OrderBy(j => j.Order).GroupBy(c => c.Group).ToDictionary(c => c.Key, d => d.ToList());
            //gets one section form a section
            var wantedSection = sec.FirstOrDefault(c => c.Section == "2.2");  //return null if no iteem found
            //gets one section in the order you set in order
            var sectionOne = sec.Where(c => c.Group == "1").OrderBy(c => c.Order).ToList();                        

Friday, April 22, 2011

Test Code that Doesn't

Consider the following code taken from an automated testing suite:

def group(self, group, options="", authUser=None, cmdOptions=""):
if options != "":
options = "-" + options

output, rCode = self._run(cmdOptions, "list {} group {}".format(options, group), authUser, returnOutput=True)
if rCode != 0 and output != None:
lines = output.splitlines()
if len(lines) > 1:
for line in lines:
if line.find("[debug]") == -1:
group = self._parseGroup(line)
group = self._parseGroup(output)

return group, rCode

What's especially interesting about this piece of code is that if the program being called succeeds and returns multiple lines, only the very last one is considered the actual output. If the program being called by _run fails, the return value is the text of what you asked for!

Though this is part of an automated testing suite, no real checks take place. The only thing it bothers to do is ignore debugging output. But that's handy!

Friday, March 25, 2011

Chat between frinds

It's often the case where I learn more about programming from a conversation over google talk then I do form reading a book.  This is a copy of one such conversation between two of my friends.  I thought the content was good enough to actually post for others to read.

Sqrl says:
Feels nice to perfect a 468-line data model using LINQ extremely liberally

Llama says:
how does LINQ relate to a data model?

Sqrl says:
Probably the wrong word

There are a number of properties of my data model that I'm exposing that are little but fundamental interpretations of the data

That's where the LINQ resides

Llama says:
data operations then
technically speaking your data model should be POCO's

Sqrl says:
What's that?

Llama says:
Plain Old CLR Objects

Sqrl says:

Llama says:
ask yourself this question, what is a Data Model, simple answer, a unified representation of the data in a system
not a unified representatino of the logic in the system
by using POCO's you make your system firstly portable and simply definable

Sqrl says:
I'm defining a system in which the rules can be changed dynamically by simply modifying some .csv or .xml files
For example, there is a number that defines how many slots you can put in your ship before the size in increased a level.
This size number is fundamental to the data itself, but emerges based on the rules
So, although it includes logic, I've included it in my data model
Defense and Speed are based on size and, again, fundamental
They also emerge from some logic

Llama says:
This is where i tell you, your system will never scale you've just written a very small idea
so if for example you want to do server side scaling of your game

Sqrl says:
Are you suggesting I should separate them into two different layers?

Llama says:
it won't happen and would be a nightmare
lol i'm suggesting you learn about software architecture
you can program, but the where and why needs to be taught

Sqrl says:
I try -_-

Llama says:
lol you suceed
this is something i learned only 18 months ago at best

Sqrl says:
So would the problem be that so much computation is done server-side?

Llama says:
the problem is, if you try to do server side calculations you can simply push data easily in a POCO from client to server
your having to push the entire logic base with it and deploy the same logic on client and server
do stateful server side objects which don't scale either

Sqrl says:

Llama says:
meaning when you create an instance of an object it stays alive on the server, rather that data moving through a system

Sqrl says:
This particular data and rule set would be computed and immutable when the actual "game" part begins, I'll tell you that

Llama says:
having dicipline does NOT make up for architectural mistakes

Sqrl says:
Fair enough
I'ma quote that, actually.

Llama says:
See your trying to apply a simple OOD which in truth is fundamentally flawed
by that, when you create an Object Oriented System, to be properly constructed it must implement this
Its the only way of making an OO system scale and be properly designed

Sqrl says:
I never did understand where the line is drawn with SRP

Llama says:
more is better
meaning, if you have to break up logic into multiple logic blocks because it violates the single responsibility, then do so
so take this for example
you have a Repository object that handles CRUD (create, retrieve, update, delete) operations
now a repository pattern does not a happy llama make but its an easy way to explain this
Technically speaking the object can follow SRP if it does CRUD operations
but that can lead to a ton of operations right?

Sqrl says:

Llama says:
insert, update, delete, and data queries
so one could say that doing insert, update, delete, and select by id is one responsibility because its doing autonomous operations on an entity in the model
and any queries should be seperated out to a secondary or multiple objects in order to satisfy SRP
both are valid interpretations
however breaking it down further gives greater scope to the SRP making it more real

Sqrl says:
But certainly wouldn't create one object to generate the Defense, another to generate Speed

Llama says:
why not
they're components aren't they?
or is it making too many objects?

Sqrl says:
public int Speed
                return (int)Math.Ceiling(this.AllSlots
                    .Where(i => i.SlotType == SlotType.Engine
                        || i.SlotType == SlotType.Universal)
                    .Where(i => i.SlottedSystem != null)
                    .Where(i => i.SlottedSystem is IShipEngine)
                    .Sum(i => (i.SlottedSystem as IShipEngine).Thrust)
                    / (float)this.Size);
That's it
Llama says:
ok, thats a horrible bastardization of a data layer
you did that in a getter? o.O

Sqrl says:

Llama says:
dude, ICalculateSpeed ftw

Sqrl says:
Are you serious?

Llama says:
as a heart attack
you CAN use a factory to keep a singleton of it
but thats logic hiding in the data layer
its a calculation leading from one entity to a speed value
You do want to learn proper OO systems no?

Sqrl says:
Why would I use a singleton instead of a static method?

Llama says:
Its a piece of logic, which is encapsulated into an object
therfore keeping w/ the DIP principle you have an interface to define the operation, and an object instance to operate it
keeping a singleton just manages memory overhead
but you can manage that w/ the Factory
which yields flexibility
rather than a run of the mill rigidity that using a Utility class w/ a static method gives you
make sense?

Sqrl says:
Damn good song btw

Llama says:
i'll have to check it out on pandora

Sqrl says:
I can definitely see where the flexibility comes in
It builds more of an internal protocol-based system instead know-it-all master objects

Llama says:
see: God Object
suprisingly, it builds a stronger system with fantastic segregation
you can tune and tweak various parts of the system
its bloody easy to unit test
you can create various proxy objects to plug into the system that mock actual logic, so your system can be 100% testable

Sqrl says:
And now

Llama says:
especially testing negatively

Sqrl says:
I have struggle with the decision of getting this thing done or plow through it so I can use it
It's a tool I wanted to use two weeks ago

Llama says:
Star Thugs?

Sqrl says:

Llama says:
rebuild it yo
use it as a teaching moment for yourself

Sqrl says:
Well here's the good news
I'm still using MVVM, even though my models are a bit massive
So I can finish it off and refactor the models without remaining committed to my shit

Llama says:
well i got NUnit to start running my F# unit tests
namespace Llama.Test
open NUnit.Framework

type EndpointRegistryTests() =
    member x.add_value_to_registry() : unit =
        printfn "hello testing world 2"
        Assert.AreEqual(5, 5)
not bad for unit tests
Sqrl says:

Llama says:
now i actually gotta fill in logic

Sqrl says:
Just testing the JIT
Iz coo

Llama says:
next is start testing components in my node server

Sqrl says:
How portable is the ViewModel architecture to ASP MVC?

Llama says:
depends on what you do
if its my framework Kronos
we actually had this type of layer for how data moves through layers

ViewModel -> Domain
View -> Controller -> Provider -> (Service : Optional) -> NHibernate
the domain object would live till the controller
then we'd do a transform using AutoMapper to a ViewModel to be used in the View
we use this for a very damn good reason, Domain objects are actually dynamically generated inherited objects that do lazy loading etc that are attached to a Session
So if we access a collection on an object in a view, we're literally running a db query in the view layer

Sqrl says:

Llama says:
So thats why we use ViewModels
So you know, Crystal thought my description of your getter as being a grose bastardization was rude
She says i should be nicer

Sqrl says:

Llama says:
Granted, i won't be, because we devs are the way we are

Sqrl says:

Llama says:
but its the thought that really counts
i told her it def wasn't the worst thing i've ever said

Sqrl says:
Gawd, what do you do when ignorant people call cute flash animations "programming"?

Llama says:
cuz they think it is

Wednesday, March 2, 2011

The way of Testivus

A friend of mine linked me to TheWayOfTestivus.pdf the other day.  It is a funny read that talks about unit testing and has a very pragmatic view on it.  Read it enjoy it and apply it. I think you will find that it improves your development process if you do.

Tuesday, March 1, 2011

CodeProject has some gems in it.

I friend linked me to this the other day and it changed how I program.  It's not very often that one article changes the way I handle coding but this allowed me to clean up a lot of code.  From the work in the article I have added one more function as well.

public static TResult Let(this TInput o, Func evaluator, TResult failValue)
            where TResult : class
            where TInput : class
            if (o == nullreturn failValue;
            return evaluator(o);
This one allows for the calling of functions that return a value.

Wednesday, February 16, 2011

Date Time you are doing it wrong again.

The other day I reading the greatest developer fallacy or the wisest words you'll ever hear and then today I found some code that I think illustrated his point that learning it when you need it isn't always the way to go. This code looks very much that way.  Although I think a quick Google search would have found better code then this even if you didn't know what words to look for.

System.Text.StringBuilder mxIsDt = new System.Text.StringBuilder();
string mxDate = mxIsDt.ToString();
Which converts into around 70 lines of IL and takes just 19160 milliseconds to complete.   Now my question is why wouldn't you use ToString on DateTime to do this. 

var d = DateTime.Now.ToString("yyyyMdhms");            
Which takes 8 lines or less in IL and takes 1213 milliseconds to complete. It's way less code easier to maintain and examples on how to do this can be found all over the web.  

Monday, January 3, 2011

Date Time You did it wrong.

This is a priceless gem I found today
It will even work for 10 months out of the year.
It should be 
Which works for 12 months out of the year.