Technical solutions and general life savers

Programming

Sometimes our lives as programmers get a bit easier, Microsoft has launchedlaunched C# 7.0 some time ago. Here are a few examples of the things that made our lives a lot easier.

The microsoft page has better explanations, the code below is just random code from my project. These examples are only intended to outline some of the new features.

Pattern matching

1

2

3

4

5

if(sender isToolStripMenuItemTranslate)

{

ToolStripMenuItemTranslate item=(ToolStripMenuItemTranslate)sender;

TabPageAddOrShow(item.CustomTabPage,ModifierKeys==Keys.Shift);

}

Can be rewriten as:

1

2

3

4

if(sender isToolStripMenuItemTranslate item)

{

TabPageAddOrShow(item.CustomTabPage,ModifierKeys==Keys.Shift);

}

Using the underscore we can ignore variables, which keeps the compiler (and resharper) happy: DoSomething(out String variable1, out String _)
Which brings us the pleasure of inline variable definition as well as ignoring unused ones.

It can also create funny code (introducing underscores in useless places):

1

if(sender isToolStripMenuItemTranslate_)

Tuples
While we have had basic tuples for a long time they grew up and gave us a weapon against the useless class/structs to perform returns (or way to many out variables).

1

public(Stringresults,Int32 exitCode)ExecuteCommand(Stringcommand)

Keep in mind that a tuple is a struct!

Switch statements with patterns
While switching still isn’t available on primitive types it sure improves our lives a lot:

Sometimes in the life of a programmer everything seems peachy, C#/DotNet provide relatively easy multi threading capabilities which 99.9% of the time work just fine as explained everywhere online.

However when things get a bit serious as these online explanations tend to be off by a small bit, only that small bit creates havoc….

Imagine having to debug code within a lock() statement that crashes with exceptions like “Collection was modified; enumeration operation may not execute” which seemingly bypass any locking in place.
These are not fun to deal with as everyone will for some reason stubbornly tell you that that is not possible and you are simply lacking a lock somewhere and just moving on like they have just shed divine light.

First of all lets get the common misconception cleared that it is impossible for a single thread to execute code in parallel and even worse that events will always be fired with a new thread affinity. This is just plain wrong!

Create a simple empty form with the following code in the shown event:

1

2

3

Button testButton=newButton{Dock=DockStyle.Fill};

testButton.Click+=Test_Click;

Controls.Add(testButton);

And paste the following somewhere below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

privatereadonly object_lockHelper=newobject();

privatevoidTest_Click(objectsender,EventArgse)

{

lock(_lockHelper)

{

Debug.WriteLine("A");

inti=0;

while(i++<50)

{

Application.DoEvents();

Thread.Sleep(50);

}

Debug.WriteLine("B");

}

}

If what everybody proclaims is right this code should just lock up the UI and neatly print “A”, “B” in sequence when triggered.
This is where the bad news starts, it doesn’t, simply clicking the button a few times very easily prints “A”, “A”, “B”, “B”.
So with a few lines of code we have disproved two very stubborn myths in one blow.

This properly locks up the UI as expected (it’s example code, not release code) and can even be used for some more interesting purposes when multi threading.

Please don’t be like all the other assholes online who proclaim that this doesn’t happen in normal production code (or even worse that a simple lock() should always be sufficient as events have different thread affinities).
Simply imagine a simple asynchronous communication protocol between two programs or a server and a client, having simple locks can seriously fuck up your day with some long debugging ahead.

There is one thing all programmers experience at one point or another, performance issues… One might use simple break points to get a coarse idea of the problem locations or when things get really frustrating a stopwatch with several measurement points.
But even that gets frustrating when there are lots of problem areas and it soon turns into a cumbersome practice which we all loathe.

But nothing beats some good old fashioned scripting to create a more elegant solution:

You might or might not have heard about XML and JSON. And wonder which one is better to represent data with for communication, save functionality or config.

Before I do so I will explain what JSON and XML are in depth. If you are not interested, skip to ‘One over the other’

What is JSON?
JSON stands for JavaScript Object Notation and is actual javascript code. When put in to a javascript evaluator JSON can directly be translated in to objects, array and primitive types (integer, string, float).

A basic JSON string containing a person object could look like this:

1

2

3

4

5

6

7

{

name:‘John’,

age:14,

length:1.55,

profession:‘Student’,

friends:['Suzzy','Cate','Mike','Tom']

}

Although JSON can only be parsed when well formed. Their is no default possibility to define what every value should look like. If you want to put ‘hello world’ into the length property this is valid. To do such checks code should be written to check these properties.

As noted before that JSON is actual javascript code. So parsing of these string is in general very quick.

What is XML?
XML stands for Extensible Markup Language and has been standardized by the W3C (World Wide Web Consortium). And has been created to standardize the way HTML (HyperText Markup Language) is written.

The same object shown above could look like this.

1

2

3

4

5

6

7

8

9

10

11

12

<person>

<name>John</name>

<age>14</age>

<length>1.55</length>

<profession>Student</profession>

<friends>

<friend>Suzzy</friend>

<friend>Cate</friend>

<friend>Mike</friend>

<friend>Tom</friend>

</friends>

</person>

I would like to point out that this representation automatically makes ‘objects’ from friends. Make it easier to put more properties on these. But the same can be done in JSON. So far you can represent the same complexity of data.

XML however has 2 things that make it more powerful then JSON.

First off is XSD (XML Schema Document) can be used to validate the structure and data types (not if it’s well formed, because it needs to be well formed to be able to check it against an XSD). XSD are XML’s with tight regulation on how they should be build and describe how your XML should look like. Thus using an XSD makes it very easy to pinpoint troubles in your data structure as it will give an accurate error of the problem.
For further information check: http://www.w3schools.com/schema/default.asp

Second is XSLT (EXtensible Stylesheet Language) which can be used to format a XML to more readable formats. Although only text can be produced by default, like HTML pages or txt files. This format is also tightly standardized and is being used as a base for PDF generators and other formats.
Check http://wiht.link/XSLT-intro/ for more information.

Finally I would like to point out that XML needs some getting used to when first used to write a data structure for. With JSON objects and arrays explain themselves. Defining structures comes naturally as it is clear what every part does.
With XML it might not always be clear how something should be represented at first and some research is needed. This is especially true when using XSD or XSLT documents.

One over the other
Here under I will point out the strengths and weaknesses of both formats.

Using JSON over other interchange-formatsPro:

Can be read more quickly

Little overhead

Fast writing

Easier to learn

High performance deserializing

Cons:

Needs time getting used to

If you write your own JSON parser its hard to debug

Harder to cut in to chunks

Thoughts on XMLPro:

Better error handling on syntax errors

More easily readable with deep levels

Superiour data integrity checking when XSD is used

XSLT can be used to formating for readability

Con:

To make error handling work their is need to make a XSD

Overhead with closing tags (slows down reading too)

Chance of conflicting names and functions of nodes

Necessity to create well formed XML constructions to represent your data

Harder to learn when structures become more complex

Conclusion
Although you might be dazzled or tempted to choose one over the other. I would like to point out that neither is absolutely superior and either can be used for all purposes you might have to represent data. However one is more suited for certain applications then the other.

If you have a website with lose data calls and no refresh, use JSON. It’s faster and has less overhead. In this fashion JSON is suitable for other communication and cases you need small size and high decoding speed.

If you need readability and tight error control over large sets of data that are being maintained by people. Use XML. It’s XSD data integrity checking makes it far easier to write by hand and XSLT can speed up human checking. So it’s ideal for config files, documents and dumps of large chunks of data that are complex in nature.

Tooltips provide an easy way to add useful information without cluttering the screen with enourmass chunks of data. ExtJs has fitted a couple of elements with a default tooltip. Button, Grid.Column.Header and Window are examples of that.

But sometimes you find yourself wanting to emphasize other things like a grid, rows, grid cells, an icon or blocks of text.

There is qtip, which can be placed within the HTML code directly to provide the user with a simple tooltip. But you have to encode everything to not make the first “ or ‘ break it.

So I recommend using the tooltip class.

Basic tooltip

This will set a tooltip on any element with the CSS class “tooltip-target” that is within the the panel “this.mainPanel”.

The CSS class does not have to exist for this to work. You might however want to add an empty CSS class with a comment, just to be sure it doesn’t get cleaned out by accident by someone that stumbles upon it.

1

2

3

4

5

6

7

8

9

10

vartip=newExt.ToolTip({

target:this.mainPanel.getEl(),//target to apply tooltip on (also scope of the search, MUST be an Ext.element)

delegate:'.tooltip-target',//target the tooltip will be shown on

delay:0,//how long to hover before showing

trackMouse:false,//follow the pointer while over element

renderTo:document.body,//where to draw, document.body is recommended

autoHide:false,//don’t hide after a while

anchor:"right",//where to show the arrow on the tooltip

html:"Tooltip content"//content to show

});

Grid cell

To make it work on a grid, just provide a different delegate and target. This will popup when hovering a row. If you want to make it select on just some cells, make up your mind in the renderer, by adding the previously mentioned “.tooltip-target” as delegate.

1

2

3

4

5

6

vargridTip=newExt.ToolTip({

target:this.grid.getView().mainBody,

delegate:'.x-grid3-row',

renderTo:document.body,

html:"Tooltip content"

});

Updating the content from given element

Nice, but now I got fixed content within the tooltip, making it hard to use. You first thought might be: “I could make more CSS classes to hang other tooltips from .”

Consider that every tooltip will be activated when entering the scope of its target elements. This could create a performance hit.

Instead update the content of the tooltip with the element you just hovered over. Is most cases like with a grid the data that the element you hovered over originated from is in a store. Or more precise, inside a record.

So for a grid you could use this after creating the tooltip.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

gridTip.on("beforeshow",function(tip){

//the element being hovered over

vartriggerElement=tip.triggerElement;

//get row index

varrowIndex=this.grid.getView().findRowIndex(triggerElement);

//get record

varrecord=this.grid.getStore().getAt(rowIndex);

//you could also format this

//or use another store to add even more information

varcontent=record.get(“some-column”);

//update the tooltip

tip.body.update(content);

},this);

Update tooltip with call

As long as the function is delayed, the tooltip will not be shown. So it is a good practice to add a loading message and update the tooltip as soon as data from example an AJAX call is available.

ExtJs has a whole range of useful components, but sometimes a more appealing interface object is required or one that is lighter to render. ExtJs provides you with a function that makes it easier to basically make anything you want within the limits of HTML and CSS.

Traffic light example
For this article I will use a component we use to illustrate risk within our application in the form of a traffic light. I will extend this example step by step to give you an idea how to design a control from the ground up and give you a feeling on how easy it can be.

If you are searching for more in dept information about how to create any kind of control try “Using XTemplate – Advanced” article.

Note: I will declare all variables in global space to make the example easier to read and try out. Using it like this is strongly discouraged as it will NOT provide any data layer abstraction. So when you got 1000+ variables inside your applicition, you are bound to override one that is used by another part of the application. When I got the time I will provide you with an article that explains this more in dept and provides you with solutions.

Setup XTemplate: Hello world
This example will output an Ext.Window that shows hello world as content.

1

2

3

4

5

6

7

8

trafficLight=newExt.Window({

height:100,

width:100,

template:newXTEmplate('Hello world'),

data:{}

})

trafficLight.show();

I agree, you can achieve the same with the HTML tag or by adding an element with that text. So lets make it more dynamic.
Now add message: ‘hello this world’ to the data object and replace hello world in the template with {message}

1

2

3

4

5

6

7

8

9

10

trafficLight=newExt.Window({

height:100,

width:100,

template:newXTemplate('{message}'),

data:{

message:"Hello this world"

}

})

trafficLight.show();

Now the message shown is read from the data object provided. This works because this behavior is inherited from Ext.Component. When tpl and data are provided, it will attempt to fill the given element with these 2 variables on render.

Now their are 2 ways to move forward. You can either call overwrite on the tpl, supply the target and data directly or call update on this component by providing the data needed. I will show you both. But first we need to split off the data object, because in a window the property ‘data’ it is not available after render. This while we want it to know what the previous state of the window was.

1

2

3

4

5

6

7

8

9

10

11

12

trafficLightData={

message:"Hello this world"

}

trafficLight=newExt.Window({

height:100,

width:100,

template:newXTemplate('{message}'),

data:trafficLightData

})

trafficLight.show();

Call update on component
There, now the easiest way is the following which uses the internal update function to handle the request.

1

2

trafficLightData.message="Goodbye and thank you for all the fish";

trafficLight.update(trafficLightData);

Call overwrite on the template
Although the following example is more ‘difficult’ and does not provide extra functionality in this example. I would like to show it to you because you can use it to apply one template to multiple components. Because it uses element as a target you can apply a template to Objects that are not inherited from Component.

1

2

trafficLightData.message="Goodbye and thank you for all the fish";

trafficLight.tpl.overwrite(trafficLightData.body,trafficLightData);

In short what I do is call overwrite on the Template, the same method used by update(), but provide the target myself. Which is Window.Body, the element that shows the content part of a Window.
Note that this only works when the Window is rendered as the body element is created then.

Example adaptive render
Now this does not at all look like a traffic light. So let’s change that.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

trafficLightData={

color:"red"

}

trafficLight=newExt.Window({

height:100,

width:100,

tpl:newExt.XTemplate(

'<strong>',

'<div style="color: red;">&bull;</div>',

'<div style="color: orange;">&bull;</div>',

'<div style="color: green;">&bull;</div>',

'</strong>'

)

})

trafficLight.show();

Wow, what is all this?
Well first is the template: When you keep adding string as parameters, these will be appended to the template. So this makes it a lot more readable. Then I have added 3 bullets using HTML entity &bull; • and put them in to div as the conveniently puts them on new lines.

Next, let’s make the component show the actual value, which is red as shown in trafficLightData.

Now this is one of the more interesting things of a template. When is used, you can add logical expressions, loops and functions in the template. In this example I use IF. Now inside the if attribute I have put “color==\’red\’”.
When a value is not inside ” it is seen as a variable that it will try to get from the data object. When put between ” it becomes a string you can use to compare. So this is essentially a simple if construction, that adds ‘ font-size: 20px;’ to the style attribute of the div when true.

Example click events
Now it makes the red light show up on default, but we want it to change dynamically, on click for example. So let’s do that first.

Although not very elegant this will make the traffic light switch from red -> green -> orange -> red. This is achieved by making an event click on Window.body which is created after render of the Window. Then the colorSwitch object is used to retrieve the next value. Then update() is called with the updated value.

Now to make a more useful component out of this you probably want to click the color you would like to select and be able to retrieve it.

This requires the following, you need to know which element has been clicked. You can make a listener for every rendered element, but this is heavier and in my opinion not a very nice solution. Instead we introduce our own attributes on the rendered elements. And let this same event return the element that was clicked.

Et voila. As the data object holds the actual value that can be used to identify the current state of the Component and the Component shows the correct state.

Optional improvements
To make this component more useful it needs a couple of things.

Use a Component or Panel as you base instead of Window, it’s more easily usable inside layouts. You might even want to consider using Ext.form.Field as a base is even lighter.

Give it fixed height and width, else you need to redesign the layout to scale.

You can also make it dynamic by being able to add any colors by a config option.

Expose something like an setValue and GetValue so you don’t have to fiddle with the data object and Update(). You might also want to expose an onValueChange() or similar event.

You can use background-color or border color to make the selection more visible and use a pointer on the values to make it appear clickable.Note: CSS code with Internet Explorer ‘hack’
cursor:pointer;cursor:hand

Final thoughts
Making a component like this is (arguably) easy. This is one of the things that make ExtJs stand out as it gives you tools, but also the possibility to easily extend on those tools to suit them for your needs. To actually create a new component you might want to look at our tutorials we have about extending and creating new components.

The possibilities of XTemplate are not exhausted by a long shot, see my article about advanced XTemplating to get a grip on those. But in the mean time, I hope you have been able to follow up on my rambling and have a grasp on the basic concept of the XTemplate.

This article goes more in dept on XTemplate usage, for an outline, look at “Using XTemplate – Basics”.

Feeding an object to XTemplate
Quick refresh. Anything within the root of given data object can be called in the template using {propertyName}.

1

2

3

4

5

6

7

8

9

vartpl=newExt.XTemplate(

'<p>Name: {name}</p>',

'<p>Full name: {nameObject.first} {nameObject.last}</p>'

);

vardataObj={

name:'demo text',

nameObject:{first:'thirst',last:'past'

};

tpl.overwrite(panel.body,data);

Simply using name.firstname could be using to reach deeper elements when objects are nested.

If statement
In the simple example we already showed you how to use the if statement.

1

2

3

4

5

6

7

vartpl=newExt.XTemplate(

'<p>Name: {name}<tpl if="name = \" yes\""=""> good</tpl></p>'

);

vardataObj={

name:'demo text'

};

tpl.overwrite(panel.body,data);

The if statement also supports lower then < and higher then > as well as the <= and >= variations.
Although these expressions work on string, we do not recommend using them like that because it provide tricky behavior one might only understand when you know how character encoding works.

Feeding an array of objects to XTemplate
Then more interesting things. You can loop through arrays and template objects inside them.
For example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

vartpl=newExt.XTemplate(

'<p>Name: {name}<tpl if="name=\" yes\""=""> good</tpl></p>',

'<tpl for="kids">',

'<b>Name:</b> {name}<br />',

'<b>Age:</b> {age}<br />',

'</tpl>'

);

vardataObj={

name:'demo text',

kids:[

{name:"sammie",age:10},

{name:"tom",age:13},

]

};

tpl.overwrite(panel.body,data);

Both kids will be shown with their ages. When looping an array of strings use . to point to the base of the iterated element.

Using self defined functions inside the template
Closing the parameter list of a template with an object abless you to set things to the template object, but can also be used to add self defined functions.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

vartpl=newExt.XTemplate(

'<p>Name: {name}<tpl if="name=\" yes\""=""> good</tpl></p>',

'<tpl for="kids">',

'<b>Name:</b> {name}<br />',

'<b>Age:</b> {age}<br />',

'<b>Baby:</b> ',

'<tpl if="this.isBaby(age)">Yes</tpl>',

'<tpl if="this.isBaby(age) == false">No</tpl>',

'</tpl>',

{

//xtemplate properties

compiled:true,

disableFormats:true,

//custom function

isBoy:function(name){

returnname=='Timmy';

},

isBaby:function(age){

returnage&lt;1;

}

}

);

vardataObj={

name:'demo text',

kids:[

{name:"sammie",age:10},

{name:"tom",age:13},

{name:"lillie",age:0},

]

};

tpl.overwrite(panel.body,data);

As you can see above a function is used along with the for function, to loop through the children and see if they are babies.

Basic math functions
When dealing with integers + – / and * can be used to directly alter the value before showing them inside the template.
So something like:

1

2

vartpl=newExt.XTemplate(

'<p>Birth year: {current_year - age}</p>',

Is permitted and could be useful for example to show a certain value from 3 different offsets.

Conclusion
Xtemplate is a excellent way to do layout as it makes markup readable using powerful tools to make dynamic markup functional. Also because it’s almost pure code when compiled it delivers high performance also reducing memory when reused on many elements.

Some programs are great to use but are annoying when it comes to bulk operations they are just too cumbersome, PNGCrush is one of them.
Don’t get me wrong, I really like this program (and actually use it quite often), but it needs a bit of spice to be more useful in our busy daily lives. I don’t want to figure out the syntax every usage and windows “scripting” is just to unreliable.

DotNet to the rescue!, if there is one thing this framework is useful for it’s fast and reliable programming, so a simple CLI helper is quickly formed.

Can easily be adapted for other programs/use cases

Launches one PNCrush instance per core

Displays files that will be processed

Displays neatly formatted results

Finds the best available PNGCrush executable (version and architecture)

Works with DotNet 4.5.2 and newer, older versions require some tinkering (although I don’t see valid reasons to remain on any older version)

Could be converted to .AsParallel() LinQ, but where is the fun in that?

Using the BeginInvoke function is way to much fun and something that entry level C# programmers get their hands on fairly quickly. That doesn’t mean it doesn’t have its pitfalls as most don’t bother to read the documentation.

It isn’t the cleanest of solutions, it spoils a whole thread so it might not be the best solution for very heavy situations (bulk loading invokes works way better in those cases). But it does alleviate most of the occasional BeginInvoke calls.

It sounds trivial, but have you ever found yourself clicking on a button at the bottom of an administrative panel to delete an item while nothing was selected inside a grid or list, presenting you with a ‘nice’ exception.

Why does this happen? The answer is probably: that the most forward way to make button states work, is to manually disable buttons for different actions.

Note: All code are orginall written in Javascript for ExtJs 3.4, but if you can read it are easily transferable to other programming languages.

1

2

3

4

5

6

DeleteItem:function(){

varselectedRec=this.grid.getSelectionModel().getSelected();

this.stores.items.remove(selectedRec);

this.deleteButton.disable();

this.editbutton.disabled();

}

Consider the following case.

You have a grid with items that can be deleted and edited.

You can always add something.

When you delete something, nothing is selected afterward. So edit and delete should be disabled.

Now there are multiple cases this will break when you manage button states with every action.

You add another button, move for example.You have to add the disable to the end of edit and delete function.

Items get states where they can’t be either deleted or edited.The logic of this will be scattered.

An item can be deselected by a refresh called from numerous functions.Again scattering logic and leaving room for errors.

You get the idea.

Interfaces like this have lot’s of states ending in an even larger list of actions that a possible. So what IS a good way to do this? In my personal opinion it’s best to fit all state information into ONE function.

Why?

Because you want the logic to be in one place.

You can call this function as often you want, so if you are unsure about states. Call it.

When it is done, it is guaranteed to be valid because it doesn’t care which function just got executed.

When you add a new state or button you only have to add a little logic to this function and don’t have to bother to check all the other places the state could change in a way unintended.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

DeleteItem:function(){

varselectedRec=this.grid.getSelectionModel().getSelected();

this.stores.items.remove(selectedRec);

this.ManageButtons();

},

ManageButtons:function(){

varhasSelection=this.grid.getSelectionModel().hasSelection();

if(hasSelection){

this.deleteButton.disable();

this.editbutton.disabled();

}else{

this.deleteButton.enabled();

this.editbutton.enabled();

}

}

Last consideration

Yes, it creates some overhead. It will run checks that ‘could’ be unnecessary because part of the buttons only change ‘sometimes’.

That are a lot of ifs. Furthermore checking for states is not that expensive. That is unless you need to loop a whole lot of items to find out if something is true. Which would be a good thing to cache or split off so you only check it when necessary.

You could consider making logical groups that you pass as parameters for things to check during the manageButtons call. But I have not experimented with that yet.