Monday, March 31, 2008

[Design Patterns] Butchering Design Patterns Part 1 - Open Door Pattern

Hi all,

this is the first post of the Butchering Design Patterns series. What we do here is try to highlight Design Patterns very common between butchers. Just like everyone, they often don't know they're using these patterns, they just go ahead with their unplanned coding and these patterns just emerge. Some of them make sense, some others do not, but after seeing them a number of times you may need to classify them.

Open Door - the Open Door Pattern is not particularly exciting but is very common between coding butchers.

Definition: define an abstract class declaring all your variable members as public, then implement a getter and setter for each of them. Define a concrete child class for your abstract class; when you need to set/get the variable member value, just use the first way that comes to your mind (access directly or through the getter/setter), or toss a coin if in doubt.

Frequency of use: very high

UML Diagram:
















Partecipants:
AbstractOpenDoor: declares an interface common to all concrete open doors.
ConcreteOpenDoor: inherits from abstract open door.

Code Sample:

// Open Door Pattern -- Structural example

using System;

namespace DotNetButchering.ButcheringPatterns.OpenDoor.Structural
{

// MainApp test application

class MainApp
{
const string scuffia = "Dirty Sanchez Lover";

static void Main()
{
ConcreteOpenDoor myOpenDoor = new ConcreteOpenDoor(0);

//It's good practice to use getter/setter
if (myOpenDoor.GetGenericMember() == 0)
myOpenDoor.SetGenericMember(1);

//...

//Now I am in a bit of a rush, I'll access directly
myOpenDoor.m_genericMember = 2;

//..

//I am not the butcher who developed this, and I'll probably never notice
//that m_genericMember is public
if(scuffia == "Dirty Sanchez Lover")
myOpenDoor.SetGenericMember(3);

//..

// Wait for user
Console.Read();
}
}

// "Abstract Open Door"

abstract class AbstractOpenDoor
{
public T m_genericMember;

public virtual T GetGenericMember()
{
return m_genericMember;
}

public virtual void SetGenericMember(T genericValue)
{
m_genericMember = genericValue;
}
}

//"Concrete Open Door"
class ConcreteOpenDoor: AbstractOpenDoor
{
public ConcreteOpenDoor(T initValue)
{
m_genericMember = initValue;
}

//whatever
}


That's all about the open door pattern. Keep in mind it is common to find it used without any abstract base.

Thursday, March 27, 2008

Missing Sql Server 2005 Management Studio

Problem: after the installation of Microsoft SQL Server 2005 there is no trace of the Management Studio.

Asked Johnny Idol about the solution, he answered "Google it"...what a great tip!


The main problem seems related to a previous installation of MS Visual Studio (2008), which comes with a SQL Server Express Edition, that interferes for some reason.

Below are two solutions for the problem:

Solution 1: check this link for an elegant solution, found just when I had already used solution 2.

Solution 2: just because this is a butchering blog, I'll show you a very powerful solution.



  1. open Control Panel

  2. select Add or Remove Programs

  3. uninstall ALL voices related to MS SQL Server

  4. Reinstall Microsoft SQL Server 2005

  5. Now the Management Studio is right into your program menu.


Simple and brutal, but it works both in Windows XP and Vista.
Stay tuned!

Wednesday, March 26, 2008

[VC++, MFC] How to set ComboBox DropDown Height

This is a good example of how messy working with MFC can be. Something apparently so easy could take a lot of time to figure out, so here you can find two easy ways out:

1) Designer - through the designer by default you can just resize the ComboBox width. If you want to resize the Drop Down List height you need to click on the dropdown arrow on the right, then you'll be able to resize the dropped control height. This seems so easy but if no-one tells you it's anything but intuitive. If you just need to statically fix height this'll save you a lot of bitchin'.

2) Programmatically - use the following function to programmatically resize you dropped control height. The function takes as input the number of items you want to display, but if you wanna modify it to take pixels or whatever as parameter it shouldn't be too hard (unless you're brain damaged as Scuffia is).


void SetDropDownHeight(CComboBox* pMyComboBox, int itemsToShow)
{
  //Get rectangles
  CRect rctComboBox, rctDropDown;
  //Combo rect
  pMyComboBox->GetClientRect(&rctComboBox); 
  //DropDownList rect
  pMyComboBox->GetDroppedControlRect(&rctDropDown); 

  //Get Item height
  int itemHeight = pMyComboBox->GetItemHeight(-1); 
  //Converts coordinates
  pMyComboBox->GetParent()->ScreenToClient(&rctDropDown); 
  //Set height
  rctDropDown.bottom = rctDropDown.top + rctComboBox.Height() + itemHeight*itemsToShow; 
  //apply changes
  pMyComboBox->MoveWindow(&rctDropDown); 
}

Keep the butchering up.

Tuesday, March 25, 2008

[Poll] Favourite Web Technology - Result

Hi there,
the first .NET Butchering poll - What's is your favourite web technology - is closed.
We had 78 votes in 10 days, which is not a lot but is something considering we've been around just for a few months.

To cut a long story short, PHP (40 votes - 51%) kicked ASP.NET's ass (36 votes - 46%). Just a few votes Ruby ( 11 - 14%) and JSP (9 - 11%), which might be considered as a good result for ruby but a very poor result for JSP (understandable, as working with Java Server Pages is a real pain in the ass). For the Others section (19%) we had a number of comments about Django, indicating the guy is kicking and screaming right now.

I'd say the result confirms PHP as the nicest web technology around, and ASP.NET as the hottest for the industry. Bye bye JSP, welcome Django.

Wednesday, March 19, 2008

[CSS, Javascript] How to make your <DIV> disappear


This is a quick how to for beginners.
I'll show you how to make a DIV element disapper using a button, like in this way:

This div will disapper!!!

This is done changing the class attribute of the selected DIV, as is done in the following javascript function.

<script type="text/javascript">

function hideDiv()

{

var isIE = (window.ActiveXObject)?true:false;

var attributeClass = (isIE)?"className":"class";

var element = document.getElementById("hiddenDiv");

if(element==null)

return;

if(element.getAttribute(attributeClass)=="hidden")

element.setAttribute(attributeClass, "visible");

else

element.setAttribute(attributeClass, "hidden");

}

</script>


This won't work without the definitions of the CSS classes used and the button that send the event onClick:

<STYLE>

.hidden{ display:none; }

.visible{}

</STYLE>



<input type="button" onClick="javascript:hideDiv();" value="hide"/>



<div id="hiddenDiv" >This div will disapper!!!</div>


Actually the .visible class is empty, because by default an element will be visible, so there is no need to specify that it should be visible: this is needed just to override the .hidden class.
You can use the hideDiv method with each control you wish to use that can launch an event (an hyperlink, an image, ...).

Besides, you can use also another CSS attribute, the visibility attribute; this simply makes the entity invisible/visibile, but it still occupies its space: that's why you need to insert manually a zero width and height, like in this way:
.hidden{ visibility:none; width:0px; height:0px;}
.visible{visibility:visible; }


And that's all!
See ya!

Tuesday, March 18, 2008

[C++] How to retrieve Application Path

Hi There,
welcome back to "the Best Resource on the web for Application Path retrieval" (Jack Jones - Collective Development); after .NET Application Path and JAVA Application Path we present a quick reference about how to retrieve Application Path using C++ and raw WinAPIs.

There are two common ways to retrieve App Path in C++ in a windows environment:

1) GetCurrentDirectory - this is probably the most common way to do it but it has a Drawback: the current directory path is not always the directory from where your assembly is being executed; You can alway change your current directory with a call to SetCurrentDirectory Indeed. This function fills a buffer with the current directory path (without filename), and returns the path size (termination character excluded); in case of errors it returns 0, In case the buffer is too short it returns the buffer required size:

#define PATH_LENGTH 1023

char buffer[PATH_LENGTH];
CString AppPathNoFileName;
int rv = GetCurrentDirectory(PATH_LENGTH,buffer);

if((!rv) || (rv > PATH_LENGTH))
{
//something wrong!
}
else
{
AppPathNoFileName = buffer;
}


Ref: GetCurrentDirectory

2) GetModuleFileName - this is safer if you wanna be sure to get the directory from which the current assembly is being executed. With this method you get not only the path but the file name as well, so you might wanna parse the resulting string in order to cut the filename if you don't need it. If the buffer is too short the path gets trucated. The function returns the size of path (number of characters- excluding end of string character) or 0 if an error occurs:


HINSTANCE hInst = AfxGetInstanceHandle();
char _buffer[PATH_LENGTH];
CString AppPath, AppPathNoName;

if(!GetModuleFileName(hInst, _buffer, PATH_LENGTH))
{
//Troubles!
}
else
{
AppPath = _buffer;
AppPathNoName = AppPath.Left(ApplicationPath_.Find("\\[appname].[appext]", 0));
}


Ref: GetModuleFileName

That's all; Stay out of troubles.

Friday, March 14, 2008

How to set up your own CVS server (and make it work)

Few words on how to set up a CVS server in Windows 2000/XP.
For those who don't know what a CVS server is, see wikipedia: it is a way to share code between developers, that keeps track of every change made and thus create several version of your application.

The first thing we do is downloading a CVS server for Windows, from here (when prompted I used a standard installation...I'm one of "the most users").

You can avoid restarting your machine: it will work anyway.

Open the "CVSNT Control Panel", click on the "Repository configuration" tab and set a local directory in which the code will be stored, as in picture:

The go to the "Server Settings" tab and change the temporary directory (it is not mandatory but I prefer taking this directory outside windows directory).

In the "About" tab you can stop the services required for handling a CVS server.

Now the problem is: how do I create new users?
They shold have created a GUI for this purpose, but for this task you have to write some DOS commands.
All users will be linked to local windows accounts, that are listed in this menu:

Load a console ("Execute..." + cmd) and write those lines of code:

where "d:\temp" is the directory set in the previous step.
Then you will be prompted to set the user's password, and the work is done!
As surely you'll be using this server with other developers and maybe you don't have static IP address at home (I suppose you are using this tutorial just for private proposals), you need a way to reach it remotly. I currently use a quick and reliable service, No-IP; there are a lot of this kind of services online, but this one works well.

And that's all.
Stay tuned!!

Thursday, March 13, 2008

[C++] How to disable Alt+Tab (and other key combinations)

You might need at some stage to disable some key combinations. There are -as always- different ways to do it; the one that I find -arguably- the easiest is showed in the following snippet, which traps the ALT+TAB combo:


#define MY_HOTKEYID 100 //unique in your window
//...
//Lock ALT+TAB - might wanna do it in your form constructor
bool isMyKeyComboTrapped = RegisterHotKey(GetSafeHwnd(), MY_HOTKEYID, MOD_ALT, VK_TAB);
ASSERT(isMyKeyComboTrapped!= FALSE); // just in case
//...
//...
//Unlock ALT+TAB - might wanna do it in your form destructor
isMyKeyComboTrapped = UnregisterHotKey(GetSafeHwnd(), MY_HOTKEYID);
ASSERT(isMyKeyComboTrapped!= TRUE); // just in case


What you're doing here is basically register a key combo without providing any handler for the WM_HOTKEY message fired when the Alt+Tab combination is pressed. You can use this trick to lock other key combos; use this msdn link as reference: RegisterHotKey reference. This method can't be used to trap the infamous Ctrl+Alt+Del combination in order to disable Task Manager; for this you can use the method described in this other post: How to Disable Task Manager.

Have a nice Patrick's Day!

Wednesday, March 12, 2008

[C++] How to disable Windows Task Manager

Here's a kick-ass function snippet you can use to lock/unlock Task Manager.
It works setting the appropriate windows registry key. You might wanna do this when you're looking for a way to disable the Ctrl+Alt+Del combination; trapping this particular combination is not as straightforward as trapping the Alt+Tab one or similar, so you can't use the Register/UnregisterHotKey trick (that's gonna be another post).

You'll usually call this function within class contructor/destructor in order to make sure after your object is destroyed you enable back Task Manager (if that's what you want):


void LockTaskManager(bool Lock)
{
HKEY hkey;
DWORD dwDisposition;
DWORD dwType, dwSize;
DWORD value;

if (Lock)
value = 1;
else
value = 0;
if(RegCreateKeyEx(HKEY_CURRENT_USER,
TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\system"),
0,
NULL,
0,
KEY_SET_VALUE,
NULL,
&hkey,
&dwDisposition)== ERROR_SUCCESS)
{
dwType = REG_DWORD;
dwSize = sizeof(DWORD);
RegSetValueEx(hkey, TEXT("DisableTaskMgr"), 0, dwType, (PBYTE)&value, dwSize);
RegCloseKey(hkey);
}
}
RegCreateKeyEx will open the key if existing otherwise it'll create it. The KEY_SET_VALUE parameter on the RegCreateKeyEx is necessary, otherwise you wouldn't be able to set the DisableTaskMgr DWORD value on the reg. This is tested on Win2000 and WinXP SP2.

Enough registry butchering for today.

Tuesday, March 11, 2008

[Poll] Which web technology do you prefer?

Hi butchers,

this is .NET Butchering first poll, and we're asking you about your fave web-technology: your favourite, not the one you are using (if they're the same then you're lucky bastards). It is a multiple choice poll so you're not forced to let anything out. If you go with none of the above you can leave a comment to let other people know what you meant. The poll will last for 10 days.

All the bets are on.

Monday, March 10, 2008

Regular Expression Validator

This is a simple application of the Javascript Regular Expression matcher.
Digg it!


RegExp
String



Try some regular expressions:

Here you find the code. If you need an explanation, comment below!

<script language="javascript">
function regexMatch()
{
var isIE = (window.ActiveXObject)?true:false;
var attributeClass = (isIE)?"className":"class";

var t1 = document.getElementById("regexField");
var t2 = document.getElementById("string");
var strPattern = "^"+t1.value+"$";
var oTest = t2.value;

var oREGEXP = new RegExp(strPattern);
if (oREGEXP.test(oTest))
{
t2.setAttribute(attributeClass,"right");
}
else
{
t2.setAttribute(attributeClass,"wrong");
}
}
</script>

<style>
.right{background-color:#33FF33;}
.wrong{background-color:#FF5555;}
</style>


<form name="formRegEx" onSubmit="javascript:regexMatch(); return false;">
<input type="text" id="regexField"/>
<input type="text" id="string" />
<input type="button" onClick="javascript:regexMatch();" value="check"/>
</form>


Friday, March 7, 2008

Why SEO is not a job

Let's face it: SEO is a joke, not a job.

Anybody today can achieve excellent search engine ranking for his own blog or website in his sparetime, working on the strength of contents or services offered. A little bit of social bookmarking, alittle bit of fuss on major social or professional networks, a little bit of impression exchange, a little bit of back-links here and there: it doesn't seem to me as a big deal.

Wether you're using white or black hats or not I don't really care: the point is getting noticed on the web is extremely easy, just with a little reading and even less intelligence. I'd rather throw money out of the window than hire a SEO consultant, or I'd rather pay someone who doesn't call himself Search Engine Optimizer. Why? Because SEO is not a job, and will never be.

I see SEO people as prodigal sons of the new economy trying to make a living out of big and small companies ignorance.

Let's look at a Search Engine Optimizer profile: they're usually wannabe-techies who don't have a clue about what's behind what they're optimizing. We're talking about people who like the thrill of a tech-chat based on total vacuum. The most sophisticated SEO strategy I've ever heard about is "remember to provide a back link whenever you put a link on you website". What's this, if not a joke.

People who claim to be SEOs are most likely to fall in one of the categories below:
  1. Web Designers gone BAD
  2. Web Designers who overrate themselves
  3. Web Designers who were dancers
  4. Web Designers with a tiny backpack
  5. Web Designers who suck at web design
Before closing I'd like to point out this link: SEO is bullshit, it's quite hilarious (and there's no backlink).

And that's about it, at least for today.

Thursday, March 6, 2008

Silverlight vs. Flash and .NET integration


Two words about this new Technology by Microsoft.
I saw it for the first time near the end of 2007, but I gave it no importance: yeah, cool graphics but, as I'm not a graphic designer and having so little taste in graphics :), I had no interest in learning the fundamentals.
This is the same thing in Flash: in fact in the field I develop, Flash could help me only in the presentation step of my applications, because in the development step server techologies with javascript are enough.

Some weeks ago I came across the 1.1 alpha version of SilverLight, a complete version of the plugin, that can run on all main platforms (Win, MacOS, and a developing version for Linux) and on all main browsers (with only one plugin!!).

The main problem using FLASH with other technologies, such as .NET, is that you need a completely different environment to develop your applet (Flex) and have to use another language for your script (Action Script): moreover it's pretty difficult to generate both ASP.NET code and Flash code server-side, as they are in complete different domains. This can be done using third party solutions (such as SWFSource.NET, from this link) that allow you to generate SWF files server side, but at a too low level and of course without a complete intergration with the .NET technology.

At Microsoft Labs they wrote a scaled down version of the .NET platform to make Silverlight working: this allow you to write your client application in the same way you write your server pages, thus using the same data structures, objects and languages (C#, VB.NET, managed C++, ...), coming in help to the poor butcher programmer.

The framework, fully included in Visual Studio with few operations, comes with a completetly 2D rich model for drawing and responding to events (mouse click and this kind of stuff), some interesting streaming object for the mainly used video/audio standards (and Microsoft offers a 4Giga service of media storage and streaming server functionality in this link for free) fully customizable, a complete animation model and really interesting a full support for web services: this is what you will find in the 1.1 version, as the 1.0 is still something mostly related to graphical and animation manipolations.

No doubt that beeing an alpha release, I bet, there are still a lot of bugs and all the framework is missing some usefull objects not yet implemented, anyway this alpha is paving the way for a great new and useful technology.

Stay tuned for further readings, from your preferred butcher's shop!

Wednesday, March 5, 2008

[.NET] VB - C# Type Conversion Differences

There are some basic differences between VB.NET and C# when it comes to type conversion.

In both VB and C# widening conversions are implicit. Widening means that the destination type can represent all the possible values of the source type:


' VB sample
Dim myInteger As Integer = 1
Dim d As
myDouble = 1.007
myDouble = myInteger

'Helluva Implicit conversion allowed

// C# sample
int myInteger = 1;
double myDouble = 1.0001;
myDouble = myInteger;

//Implicit Conversion
//allowed


For narrowing conversion - let's say assigning a double to an int, when the destination type cannot represent all possible values of the source type - things change: you need to explicitly cast in C# while in VB the conversion keeps being implicit (don't come asking for an example plz... ).
If you want VB to behave as C# in case of narrowing conversions you have two options: either write at the very top of the code Option Strict On to enable the option at page level, or set the same Options Strict from the project properties to enable it at project level.

This difference reflects VB's wannabe-user-friendly attitude that often ends up messing-up things for people who's learning; but since every .NET developer is called once in a while to do some quick and dirty job using VB (there's a whole lot of frightening VB code out there) we certainly gotta deal with it.

That's all - Kick ass.

Monday, March 3, 2008

[Flash] Flow Player and video random access


Problem: handle random access to a FLV (Flash Video) file using FlowPlayer flash player.

Solution: this article is a sort of How To about how to make random access working using this particular flash palyer (that is open source and well working).

What is random access?
Essentially random access can be seen in most of YouTube videos: you don't have to buffer the entire video, because it's possible to select a specific instant to play that has not been buffered yet!

Simply, but of course it didn't mean to work...

I had to work with already coded FLV files, using ffmpeg (if I'm not wrong they came from a MPEG4 video and MP3 audio). Anyway I haven't never worked with FLV files, but I found them very very interesting; in fact it's possibile to write MetaData just inside the file.
Anyway FlowPlayer, from its site, grants the possibility of random access, so it was not a player's fault if my videos didn't work with random access.

After a full day of searching, finally a flash of knwoledge: there is a free tool, called FLVTool2 that puts inside the file constant metadata to mark up each instant (I suppose it is done each half second or more or less), so random access depends on those markups (and so it is not continous).
To make it possibile this is one of the possibile usage of the tool (inserts meta data in an output file and after the process visualizes metadata content of the file):
flvtool2 -UP inputVideo.flv outputVIdeo.flv

Of course output file is not needed.

This is not all: random access wasn't still working!

After some reading (one inside the FlowPlayer site I haven't seen at first sight) I found the problem: if you want random access you must use a streaming server.
Just this?? What's the problem, sure you can find billions of free streaming server...

Well , yes, there are a lot of them but all in beta or even alpha release, so in my opinion they were not worth for business applications.

Fortunately a google (I love you) result came to save me: Flash Streaming to FlowPlayer using only PHP!!
In few words, using a script linked in that page, you set up a PHP Streaming Server (it simply sends via HTTP the video from the point selected with FlowPlayer) that works very well: I don't know how it is scalable, but in my tests the streaming was fluid and in time.

So if you have my same problem and don't want to spend hundreds of euros to buy a professional streaming server, this is your solution!

And remember, you are never alone: google is always next to you with a confortable word!