Thursday, December 24, 2009

Nightmare before Christmas: How to use JFace + SWT standalone

I could've as easily called this Eclipse plugins from HELL, but being Christmas and all I thought I would go for the Christmas thing, which gives me the opportunity to wish Merry Xmas to all the geeks who happen to be reading this lame-ass blog over the holidays instead of watching Star Trek as per tradition.

Being mainly a .NET guy, I am not too familiar with the eclipse platform, but I desperately needed to put together a quick UI and decided to go with JFace and SWT after @tarelli suggested so (he's the JAVA guy). Unfortunately, at the time I didn't realize he was talking about an Eclipse plugin project and not about using JFace and SWT in a standalone Java app.

So I went on and got started with some nice tutorials specific to running JFace + SWT standalone, and some more gentle introductions.

Time to get my hands dirty, so I started a new Java project, and dropped in some of the code from the tutorials. In order to get it build I needed to import JFace and SWT plugins as external jars, which I could not find anywhere in my plugins folder (I am on Galileo C:\eclipse 3.5\plugins). I needed to somehow get the damn plugins, but could not quite figure out how to get only those I needed from Help --> Install Software Updates, so I ended up pulling down anything to do with Eclipse SDK. To my delight the SWT and JFace plugins were there (in the plugins folder) after the lengthy process of downloading tons of stuff I didn't need.

After a bit of mocking about (blindly trying to import anything with jface or swt in it) I managed to understand which jars I needed to import to get the damn thing to build (org.eclipse.jface_3.5.1.M20090826-0800.jar and org.eclipse.swt.win32.win32.x86_3.5.1.v3555a.jar) I started mocking about with the code and spent a good while playing around with ContentProviders, ListViewers and so forth. Everything was building nicely, but as soon as I tried to run it as java application got the cold shower:

Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/core/runtime/IProgressMonitor
    at demo.ui.test.EntryPoint.main(EntryPoint.java:18)
Caused by: java.lang.ClassNotFoundException: org.eclipse.core.runtime.IProgressMonitor

Apparently some type was missing somewhere. I've seen a lot of sh*t working on Visual Studio and all, but errors don't get much more cryptic than this.

After a good while, after unfruitfully trying to offline troubleshoot the heck out of my project (offline troubleshooting is just madness but I was waiting the phone company to turn on my broadband in the new apt i moved to recently), I reverted to @tarelli, the eclipse guru who got me into this mess, and begged for help: he promptly told me that I was in a bit of a feckin' mess, and if I wanted to get out of it alive I would've had to create a Plugin Project "with a view" and take it from there. I tried, and he was right, but I did not want a plugin and all the overhead that comes with it, so I kept pulling my hair for several hours with no luck, then went to bed. I felt rightly and truely screwed, if you want.

Luckily the day after the phone company turned on my broadband and I could stop passively obsessing about the problem and started aggressively abusing google in search of a solution to the problem.

After a not too long research (God bless THE INTERNET), turns out that if you want to use JFace + SWT outside a plugin based project you need some other jars. Basically if you're using JFace and SWT in a plugin project runtime dependencies are managed for you through the manifest file (I seem to understand) but if you go for the rogue option of having SWT running standalone then you need to know you need that stuff.

In the specific case of the IProgressMonitor thingy, adding a reference to the org.eclipse.equinox.common jar did the trick. After that I got the same error on a different class, EventManager, and after a couple of blind trials I got it working by importing the org.eclipse.core.commands jar. Obviously, not a mention of this in the tutorials, as I seem to understand there was a bit of refactoring on those packages after those tutorials were drafted (looks like this problem is around since eclipse 3.2 --> read this bug report for further info).

What can I say? If you're coming from .NET sometimes Java == Pain.

Thursday, December 10, 2009

What a bunch of ...

... bullshit!

The developers count on the stackoverflow ad page is clearly increased at random.

The count is being increased in a recursively called function at random intervals. Here's the javascript:


$(function(){
       
        var visitors = 5373966;
        var updateVisitors = function()
            {
                visitors++;
                
                var vs = visitors.toString(), 
                     i = Math.floor(vs.length / 3),
                     l = vs.length % 3;
                while (i-->0) if (!(l==0&&i==0))
                    vs = vs.slice(0,i*3+l)
                       + ',' 
                       + vs.slice(i*3+l);
                $('#devCount').text(vs);
                setTimeout(updateVisitors, Math.random()*2000);
            };
        
        setTimeout(updateVisitors, Math.random()*2000);
        
    });

P.S. Posting this from google SideWiki - kinda cool

in reference to: http://inedomedia.com/stackoverflow.aspx (view on Google Sidewiki)

Friday, December 4, 2009

[WPF] How to programmatically add databound item to ListView

In this post I'll show how to programmatically add databound items to a WPF ListView - it's actually pretty straightforward but it's not the most intuitive task if you don't have a lot of experience with WPF.

Here's your xaml - pay attention to the bindings on the grid columns:

<ListView.View>
   <GridView>
      <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=Name}"/>
      <GridViewColumn Header="Value" DisplayMemberBinding="{Binding Path=Value}"/>
   </GridView>
</ListView.View>
We need to define a data class with Name and Value properties such as:

public class BoringData
{
    public string Name { get; set; }
    public string Value { get; set; }
}
And here comes the fun - how to programmatically add items to the ListView:

//utterly boring call to generate your data item
BoringData boredom = getBoringData(index);//<-- whatever
//add the item to the listView 
this.myListView.Items.Add(boredom);
If you're thinking I post boring stuff ... well, you're right. Posts like this I mainly post so that I won't forget how it's done (and hopefully will be helpful to some other occasional WPF hacker).

Tuesday, November 24, 2009

2 Obscure Javascript Features You Probably Don't Know About

I was going through the w3c javascript tutorial (I like the try it yourself sections ... yes - I am that kind of geek) and I spotted 2 pretty basic but obscure ECMAScript Javascript features I didn't know about.

Feature 1: the '===' operator!
That's right, that's a triple equal. What's it for? Well, you know javascript is not strongly typed, so you can cast a variable from a number to a string just assigning values to it. This triple = operator checks for equality of both value and type. Smart, uh? Also kinda horrible.

Feature 2: variable re-declaration!
Apparently you can re-declare a variable and the javascript interpreter couldn't care less. Moreover, if you re-declare a variable it will retain the same value as the previous homonymous variable had. Handy uh? Except it's plain twisted wrong.

Anyway, God bless ECMAScript Javascript, glorification of all sorts of butchers, and the genius dude who invented it.

Monday, November 16, 2009

[.NET] How to swallow warnings

Well aware this is against all best practices, here's how you suppress all warnings coming from a given region of code:

#pragma warning disable

//All the warnings in here are swallowed!

#pragma warning restore

This is way beyond cool - and might help you out when you can't change your code but you're being hovered by a frustrating policy of ZERO WARNING TOLERANCE.

Go forth and get it done.

Tuesday, November 3, 2009

Quick and Dirty WPF ListView Customization

When in need of customizing a WPF ListView without much WPF experience, chances are you'll hit the wall soon enough on pretty trivial tasks.

This is a collection of recent posts appeared on this blog on the topic. I think the list covers most of the common basic ListView customization tasks.
Hope this'll spare a good share of frustration to some of you cheap guys out there, pulling your hair trying to write xaml by hand rather than using some version of Expression Blend or the likes (as I did myself 'cause the 30-days trial expired and the boss wouldn't show the money).

kick it on DotNetKicks.com

Sunday, November 1, 2009

[.NET] How to bring window upfront

The stuff on this post can be easily integrated with a previous post:
How to Check if App is Already Running.

In order to bring a window upfront you need to mess with win32 API calls - no easy way around (if you know any please give me a shout). Here's how to import the calls we'll be using:
//Win32 API calls to raise a given processs main window
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);

private const int SW_RESTORE = 9;
Here's a static method to bring a Window upfront in a given winApp (can be easily integrated with the previous post linked above):
static class Program
{

// all the rest of the stuff ... Main other methods etc.

public static void BringOnFront()
{
Process myProcess = Process.GetCurrentProcess();

string myAsseblyName = Assembly.GetExecutingAssembly().GetName().Name;

foreach (Process processId in Process.GetProcessesByName(myAsseblyName))
{
if (myProcess.Id != processId.Id)
{
IntPtr hWnd = processId.MainWindowHandle;

if (IsIconic(hWnd))
{
ShowWindowAsync(hWnd, SW_RESTORE);
}

SetForegroundWindow(hWnd);

break;
}
}
}


}
That'd be all - knock yourself out (tested on a number of XP and Vista machines).

Sunday, October 25, 2009

[.NET] How to check if app is already running

Here's a quick and dirty snippet (and sample usage) to check if your app is already running (using a Mutex).
static class Program
{
private static Mutex mutex;

public static bool IsThisProcessAlreadyRunning()
{
bool createdNew;
mutex = new Mutex(false, Application.ProductName, out createdNew);
return !createdNew;
}


///
/// The main entry point for the application.
///

[STAThread]
static void Main()
{
if (!IsThisProcessAlreadyRunning())
{
// whatever you might be doing
// here's some default form initialization
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
else
{
// do something!
// usually smt like --> BringOnFront();
}
}

}
Bringing the app to the foreground is usually what you'll want to do next in scenarios like this. A post about that might follow soon enough.

Side note - if you're using VB.NET I believe there is a check-box you can tick under application properties somewhere that does the job. I'll avoid making jokes about VB.NET 'cause life is tough enough for the suckers who use it without me being a jerk.

EDIT: 2009-11-01 --> posted How to Bring Window Upfront

Thursday, October 15, 2009

[.NET] XmlDocument VS XmlReader

To cut a long story short I recently learned (thanks to a co-worker) that XmlDocument performance sucks.

It's very handy to manipulate XML stuff with XmlDocument because it comes with all the DOM stuff, and for example you can use XPath for node selection like this:
// load up the xml doc
XmlDocument doc = new XmlDocument();
doc.Load(filename);

// get a list of all the nodes you need with xPath
XmlNodeList nodeList = doc.SelectNodes("root/whatever/nestedWhatever");
The above is quite cool and it works just fine if you're not loading hundreds of files for a total size of hundreds of MBs, in which case you'll notice a lethal blow to performance.

If you need speed you wanna go with XmlReader, a bare bones class that will scan the old way (forward only) element after element your XML file. Bad thing is that you won't have all the nice DOM stuff, so you'll have to manually parse elements retrieving innerText and/or attribute values. An example:
XmlReader xmlReader = XmlReader.Create(fileName);

while (xmlReader.Read())
{
//keep reading until we see my element
if (xmlReader.Name.Equals("myElementName") && (xmlReader.NodeType == XmlNodeType.Element))
{
// get attributes (or innerText) from the Xml element here
string whatever = xmlReader.GetAttribute("whatever");
// do stuff
}
}
I can't be bothered benchmarking as it bores the sh*t out of me - but performance increases a whole lot with XmlReader, and if you want figures to look at you can find plenty on google (this guy here did a pretty good job for example) and here's another good overview of XML classes (from Scott Hanselman's blog).

Anyway - here comes the common sense advice - whatever you're doing go with XmlDocument, if it's too slow for you needs switch over to XmlReader and you'll be grand.

Saturday, October 3, 2009

GIT + GITHUB --> How to setup local repository

Once the code is up on Github (for example if you need to pull your buddy's code from github 'cause he's too cool for SVN), after you install any git package for windows it's quite easy to setup a local repository for git and pull your stuff from github.

Browse to your local repository from gitbash and this is how it's done in just 3 lines:
//init git local repo
git init

//register github user + repo
git remote add origin git@github.com:UsEr/repOsitOry.git

//pull the stuff
git pull origin master
In order to be able to talk to the github servers from your machine you need to setup the ssh stuff, which I am not covering because I can't be bothered and you can read all about it here.

Thursday, October 1, 2009

How to mimic SQL WHERE clause on Google Datastore queries

This puzzled me for a while as I never used JDO before crashing the app-engine party.

Assuming we have an Order class with a member variable named customer of type User:

//get current user
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();

//prepare query
PersistenceManager pm = PMF.get().getPersistenceManager();
String select_query = "select from " + Order.class.getName();
Query query = pm.newQuery(select_query);
query.setFilter("customer == paramCustomer");
query.declareParameters("com.google.appengine.api.users.User paramCustomer");

//execute query
List<OrderDTO> result= OrderUtils.getOrderDTOList((List<Order>) query.execute(user));

//feck-off --> I'll never get an MVP but I can swear on my blog!
pm.close();

Just wanted to share to spare some random googler (you) the same process.

Saturday, September 26, 2009

Google App Engine for JAVA Local Data Viewer!

I've been screaming like a sissy for a local Data Viewer since I put my hands on the Google App Engine. Turns out it has been there for a while (definitely not from the beginning) but I didn't know. It can be accessed when you're running the development server locally from the following URL (assuming you're running the default setup):

http://localhost:8080/_ah/admin/

You can browse your data and delete records but for the time being (at least on Java App Engine) edit operations are not supported, so don't bin just yet your dirty little hacks (a bunch of servlets in my case) for local development.

Friday, September 4, 2009

How to set WPF ListView or ScrollViewer Scrollbar width

A pretty common dirty hack to modify the scrollbars width is to set the OS value for scrollbars width to whatever you need in your app - this obviously sucks as not only your application will be affected.

In WPF you can override scrollbars width in both ListView and ScrollViewer controls pretty easily with the following XAML markup.

1) Include mscorlib with the sys prefix (or whatever prefix you want) in the page declaration:

<Page x:Class="AtlasPrototype.VehicleIdHistory"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="VehicleIdHistory">

2) Override vertical scrollbar width resource for the ScrollViewer (exact same for a ListView):

<ScrollViewer>
<ScrollViewer.Resources>
<sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">60</sys:Double>
</ScrollViewer.Resources>
<-- other stuff -->
</ScrollViewer>

Sounds all cool and easy but I had to beg work hard on stackoverflow to get this figured out. Show due Respect.

Thursday, September 3, 2009

How to check if WPF is using Hardware or Software Rendering?

In general, software rendering will usually kick-in if your machine doesn't support DirectX or if the drivers installed are not working correctly (for whatever reason). WPF is entirely built on Direct3D, and software rendering means your WPF app will run painfully slow.

In borderline scenarios, such as running on portable device where hardware capability is constrained, you might find yourself in a bit of a mexican standoff situation where you don't know if the bottleneck is the hardware itself or the problem is just that hardware acceleration is not working and the system falls back to software rendering. So, how do you check if software rendering is kicking in?

You can do this from code querying the RenderCapability.Tier property, as follows:
//shifting some 16 bits will do the trick
int renderCapabilityTier = (RenderCapability.Tier >> 16);
The int above can have three possible values:
  • 0 --> you're screwed - no hardware acceleration
  • 1 --> you're half screwed - you got some hardware acceleration
  • 2 --> you're good to go with full blown hardware acceleration
You might also wanna run the DirectX diagnostic tool (just run dxdiag.exe) to double check the state of your hardware acceleration (check the display tab) and, since we are at it, the new WPF profiler.

Wednesday, August 26, 2009

How to set WPF ListView alternate row color

Another common task you might have to tackle when working with WPF ListView is setting the background color for the rows in an alternate fashion (odd rows and even rows - you know what I mean).

This is how you do it.

First thing, create a style element in your ResourceDictionary or if you don't have one drop it on the page itself:

<Style x:Key="alternatingListViewItemStyle" TargetType="{x:Type ListViewItem}">
<Style.Triggers>
<!-- setting up triggers for alternate background colors -->
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="LightGray"></Setter>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="2">
<Setter Property="Background" Value="White"></Setter>
</Trigger>
</Style.Triggers>
<!-- setting row height here -->
<Setter Property="Height" Value="30" />
</Style>

Now set the ItemContanerStyle on the actual ListView and set the AlternationCount attribute):

<ListView Name="recordContainer" ItemContainerStyle="{StaticResource alternatingListViewItemStyle}" AlternationCount="2" >
<ListView.View>
<GridView>
<!-- Just a few sample columns -->
<GridViewColumn Header="aField" />
<GridViewColumn Header="anotherField" />
<GridViewColumn Header="yetAnotherField" />
</GridView>
</ListView.View>
<!-- Whatever you might have in here -->
</ListView>

And this is all there is to it!

Friday, August 14, 2009

How to set WPF ListView selected item background color

After my last post I came across another common WPF task that could result in excruciating frustration if you're not using Expression Blend (or you just don't know enough about this shit nice framework): setting the color of the selected item in a ListView.

This is how you do it:

<ListView>
<ListView.Style>
<Style TargetType="{x:Type ListView}">
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Margin" Value="0"/>
<!-- here we go -->
<Style.Resourcesgt>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Black"/>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Gray"/>
</Style.Resources>
</Style>
</ListView.Style>
<!-- other stuff -->
<ListView>

Hope it helps - if so you can express your gratitude by randomly upvoting some of my answers on stackoverflow.

Friday, August 7, 2009

How to set row height in WPF ListView

I've been checking out WPF lately for some prototyping work and came across something that's gotta be a very common show-stopper for beginners: I had a ListView element setup as a grid and no clue about how to set row height (without increasing font text - should go without saying).

This is a nice way of doing it (thanks stackoverflow):

<ListView>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Height" Value="50" />
</Style>
</ListView.ItemContainerStyle>
<!-- WHATEVER -->
</ListView>

That's what you get if you try to do some WPF magic without an Expression Blend license, which reminds me the good old days of editing html manually and feeling a God (except the God part).

Wednesday, July 22, 2009

IPN delivery failed. HTTP error code 405: Method Not Allowed

I was trying to test a servlet I wrote to process payapal IPN notifications (my servlet is very similar to the jsp in this example) and even after enabling all the IPN settings in the paypal test account the IPN was not firing at all after the payment, or at least so I thought because my servlet wasn't logging anything.

I then found out that in the sandbox you can thest IPN notifications through the IPN simulator, which also gives you handy error codes in case of failed transactions, such as:

IPN delivery failed. HTTP error code 405: Method Not Allowed

Thanks to this I then realized that in my servlet I was only implementing the doGet method but not the doPost. Without the doPost method implemented the servlet won't accept any HTML POSTs, thus the error 405. Implementing the doPost (same code as doGet) method solved the problem.

Morale of the story: Paypal integration can be a bitch.

Tuesday, June 30, 2009

Converting MSI Project from VS2005 to VS2008 - Welcome Back to (DLL) Hell

Just a few lines to outline something I've recently found out about converting msi projects from vs2005 to vs2008.

After upgrading to VS2008, we've been trying at work to convert everything to 2008. Everything built straightaway, "happy days", we thought.
Comes the first release of THE legacy product we start realizing something is not quite right - the msi is not overwriting all the dlls packaged as expected (this was the behavior on a vs2005 build, where everything was being replaced independently of the version). Also when spawning an msi installation as another process the installation fails and rolls back (which is a always a good crack).

After a bit of digging, looks like good old MS managed to sneak in and ship with vs2008 a fix to the RemoveExistingProducts sequence for msi projects whit the result that msis do not replace files on a vs2008 build unless the version number of the files is greater or has a wildcard in it (i.e x.x.x.*).

Possible solutions? there's plenty, here we go:
  1. Increase the msi project version every release to force an overwrite
  2. Increase single dlls versions (as a decent shop should do) where necessary
  3. Throw wildcards in all your dlls and go home happy

Great - but this doesn't seem to play quite right with COM interoperability where increasing version numbers or the wildcard trick doesn't seem to serve the purpose.

It's back to DLL Hell all over again, and it's time to get creative.

Good luck (any suggestion appreciated).

Tuesday, June 9, 2009

Google App-Engine Mail Service: Unauthorized Sender Error

I was messing around with the Google App-Engine mail service and I stumbled upon a little gotcha that I feel like sharing.

To cut a long story short - you can send emails though the mail service only from emails of accounts (google accounts or other Google app domains) registered as Developers from the Google app engine dashboard (Google App-Engine--> Dashboard--> Developers).

It took me a while to figure this out because:
  1. It doesn't make any sense: assume you wanna setup an admin account to send out mini-reports from your scheduled cron jobs, in this scenario you're supposed to setup your admin@yourDomain.com as a Developer!?
  2. I am linking this Google app deployed to appspot to a domain I have registered with Google, so I thought the app could send emails only from accounts registered as administrator of my given domain, which would make slightly more sense!

But then - I can only blame myself 'cause the documentation clearly says:
The sender must be either the address of a registered developer for the application, or the address of the user for the current request signed in with a Google Account.

As a matter of fact, I never read the documentation till I am desperate (who does?).

Saturday, May 23, 2009

[SQLServer2005] Select from Excel Spreadsheet for SQL-Rejects

This is DBA bread and butter - not being a DBA and having no will whatsoever to become one (I am too weak) I always forget the syntax for this procedure, so here we go.

In order to be able to query an excel spreadsheet we need to enable ad hoc distributed queries, to do so follow the procedure in this other post.

Once that's sorted - assuming you have an excel spreadsheet with column names (in the example I have Column1, Column2, Column3, Column4) in the first row - this is how you go about selecting the spreadsheet content into a temporary table:

USE myDB

-- drop temp table
DROP TABLE #tempTable

-- select spreadsheet content into #tempTable
SELECT S.[Column1], S.[Column2], S.[Column3], S.[Column4]
INTO #tempTable
FROM OPENROWSET
('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\mtSpreadsheet.xls;HDR=YES',
'select * from [Query1$]') AS S;

-- check if the stuff is there
select *
from #tempTable


That's it. Hope it helps some other fellow SQL-Reject.

Wednesday, May 20, 2009

[SQLServer2005] Enable Ad hoc distributed queries

The Ad Hoc Distrubuted Queries advanced feature is disabled by default - it needs to be enabled if you wanna run OpenRowSet or OpenDataSource operations (queries on excel spreadsheets and other stuff). 

To enable it run the following script and you should be OK:

-- allows you to see advaced options status
sp_configure 'show advanced options', 1
RECONFIGURE
GO
-- enables Ad Hoc Distributed Queries
sp_configure 'Ad Hoc Distributed Queries', 1
RECONFIGURE
GO
-- shows you the full list of features
sp_configure


The same result can be achieved by opening SQL Server Area Configuration tool for features and after picking Ad Hoc Distributed Queries ticking the "Enable ..." checkbox.

That'd be all.

Monday, May 4, 2009

[CSS] Center DIV within DIV

This is one of those that'll give you nightmares.

You have a wrapper div and an inner DIV:
<div id="wrapper">
<div id="inner">
<!-- your rubbish here -->
</div>
</div>

Css styling below will do the trick - text-align: center will work on IE but won't work on other browsers (css compliant) which require margin: 0 auto:
/* for IE */
div#wrapper {
text-align: center;
}

div#inner {
margin: 0 auto; /* this centers the DIV */
width: 30%; /* whatever */
}

alternatively you could set left and right margin separately.

Sunday, May 3, 2009

[Google App Engine] How to Clear SDK Datastore

To clear the SDK datastore you'll just have to delete the following file: "./WEB-INF/appengine-generated/local_db.bin". The file will be generated for you again next time you run the development server and you'll have a clear db.

This is one of the little gotchas that come in handy when you start playing with the Google Application Engine. You'll find yourself persisting objects into the datastore then changing the JDO object model for your persistable entities ending up with a obsolete data that'll make your app crash all over the place.

Thursday, April 30, 2009

[SQL] How to escape single quotes in the words of Pinal Dave

I will answer this SQL riddle in the words of Pinal Dave:

Jr. Developer asked me other day how to escape single quote?
User can escape single quote using two single quotes (NOT double quote).

In case you need it (I doubt it) he also provides a great example.

The man is a SQL master, and if you're a Jr.Developer (I am not but when it comes to SQL I am probably less than that) you gotta follow him on twitter.  

Another way of injecting single quotes using CHAR(39):

DECLARE @IanQuigley as varchar(MAX)
SET @IanQuigley = 'Thanks, I don' + CHAR(39) + 't know much about SQL'

I did my worst - as usual.

Thursday, April 23, 2009

[CSS] DIVs next to each other (and DIVs VS Tables all over again)

Let me guess - you need a page header/footer and you wanna use DIVs 'cause your buddy on digg or reddit says tables are soooooooo uncool? 

Here's a few CSS classes that will get you were you want to be:

.left {
width: 80%;
heigth: 10%;
position: relative;
float: left;
}

.right {
width: 20%;
heigth: 10%;
position: relative;
float: right;
}

.wrapper {
width: 100%;
position: relative;
clear: both;
}

And here's an example of the markup you might be looking for:

<div class="wrapper">
<div class="left">
<!-- Whatever - maybe a lame logo -->
</div>
<div class="right">
<!-- Whatever - maybe login stuff -->
</div>
</div>
<div class="wrapper">
<!-- Content -->
</div>

You can repeat this basic Header structure as much as you want if you need nested divs to resemble (here I say it) tables.

But - on a side note - using a table would be much more intuitive 'cause you know what a table is and how it looks like. You certainly don't need to remember loads of crazy CSS properties semantically and visually unrelated to what your trying to do.

Ok, if we're really doing this ... truth is everyone started using DIVs because the word has been spread that using nested tables is unprofessional. This is not totally untrue, but guess what - nesting hundreds of DIVs will bring you nowhere good in terms of maintainability at much lower speed.

My personal choice is a moderate one, try to stay in control finding the balance using a bit of both, DIVs within tables or tables within DIVs, to keep the built-in simplicity of tables and the advantages of DIVs.

Look at this:
If Amazon uses that many nested tables (that's 35 results for the table opening tag in the home page) no-one's gonna bug you for using a few (except those W3C pansies).

Monday, April 20, 2009

[SQL] Counting Rows with the Same Value of a Given Field

Here's a piss-easy script to count the number of rows in a table where a given field has the same value:

SELECT myField, COUNT(*) AS 'inelegantCount'
FROM myTable
GROUP BY myField

It's the classic GROUP BY statement example - which I can't manage to remember, thus the blog post.


Friday, April 10, 2009

Start Using WikiSearch Already!

When I run a search I often have a peek at other people's favourite search results for that given search (from the "see all notes for this WikiSearch" link) in the hope I won't have to spend precious seconds/minutes to find what I am looking for. Unfortunately - even if WikiSearch has been out for a while now - the usual result is the void.

It's well known that any respectable developer spends a fair share of time looking up stuff on Google. Wouldn't it be easier for everyone if we all started using WikiSearch? 

Telling the good stuff from the crap would be much faster.

Friday, April 3, 2009

Definitive Javascript RegEx Validation for Butchers

This comes back to bother me now and then - so I decided to put together a few snippets to use as base in case of client validation with RegExes.

First of all the core snippet, which takes text to validate and a regex and returns a boolean:

function regexMatch(regEx, stringToValidate)
{
var oREGEXP = new RegExp(regEx);
return oREGEXP.test(stringToValidate);
};

Often you will be validating a text field - so here's other two functions using the previous one:

function textFieldVisualRegexValidation(textElement, regEx)
{
var returnValue = false;

if (regexMatch(regEx, textElement.value))
{
textElement.style.backgroundColor = "green";
returnValue = true;
}
else
{
textElement.style.backgroundColor = "red";
}

return returnValue;
};

function textFieldRegexMatch(ctrlName, regEx)
{
var elem = document.getElementById(ctrlName);

return textFieldVisualRegexValidation(elem, regEx);
};

Some event will call textFieldRegexMatch triggering the validation. You can customize textFieldVisualRegexValidation to perform some action in case of validation succeeded or failed (I am setting the input field background to green.red but one could swap images or whatever).

You can hook up the above from (for example) the onBlur event of one of your textBoxes or any input field:

onblur="textFieldRegexMatch('yourInputFieldID', regExPattern)"

You obviously have to declare somewhere your regExPattern:

const regExPattern = "^[A-Z,a-z,0-9]{1,12}$";

I am sure there are better ways of doing the above but this is just meant as a reference to brutally Copy-Paste and tailor to your needs.

Saturday, March 28, 2009

Typing Monkeys and Genetic Algorithms

Recently I spent time playing with generic algorithms. I was looking for something easy enough to implement (read: PLAIN LAZY) and I found the Hello World! (literally) of genetic algorithms.

Gathering the algorithm itself from the C++ example (in the link above), I re-designed and re-coded the whole thing in C#.

TypingMonkey is a very simple application which uses a number (defined by the user) of random strings to evolve the user input text.

From the screen-shot below you can see how it took the algorithm 87 generations to evolve the string ".NET Butchering" from an initial population of 2500 random 15-characters strings:



Why "typing monkey"? Inspired by the Infinite Monkey Theorem, I am pretending our population of random string is generated by a typing monkey:

/// The Typing monkey generates random strings - can't be static 'cause it's a monkey.
/// If you wait long enough it will eventually produce Shakespeare.
class TypingMonkey
{
private const string legalCharacters = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.";

static Random random = new Random();

/// The Typing Monkey Generates a random string with the given length.
public string TypeAway(int size)
{
StringBuilder builder = new StringBuilder();
char ch;

for (int i = 0; i < size; i++)
{
ch = legalCharacters[random.Next(0, legalCharacters.Length)];
builder.Append(ch);
}

return builder.ToString();
}
}

You can find the source code here: http://github.com/JohnIdol/typingmonkey/tree/master

Feel free to contribute or despise.

Wednesday, March 4, 2009

How to figure out which SQL2000 edition is installled

I recently had the problem to understand which edition (standard/developer) was installed on an old machine. This sounds like a pretty straightforward thing to do - and it is indeed IF you know you need to run the following query:


SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')


You'd imagine you could figure this out looking at the 'about' information in enterprise manager (as in SQL2005 in SQL Management Studio) but that doesn't seem to be the case. I couldn't find any other solution.
Mysteries of MS faith.

Saturday, February 21, 2009

[SQLServer] Indexing and Scalability Tips

Recently I spent a lot of time messing about with indexes. Not because I like it - but because there was a little bit of a fuckup at work with scalability issues on a DB. After messing around with SQLProfiler (real life-saver in this case) I gained a bit more of understanding about indexes as I never got the chance to do before.

What I learned about indexes and scalability can be summarized in 2 points:

1)
You don't wanna have a clustered index on the primary key on a table once it gets huge (just make it nonclustered) if you plan on running loads of inserts

This is not a problem when the table is small - and since it's good for fast selects everyone's cool with it. Once the table gets populated with LOADS of records or it gets HUGE in size this WILL KILL YOU on any insert or update operation.

Just to give a few figures:
- A clustered index on a table with 45 million records was killing my SQL server - every insert from code was resulting in nasty timeouts (it was taking more than the default 30 secs for standard inserts - Increasing your timeout tolerance won't solve your scalability problems!)
- A clustered index on a HUGE table (15 gigs) with a few million records was slowing down inserts to the point it was taking 15 times as much as it was taking on an empty db (we're talking mSecs but on big batches it's gonna kill you)

2) You wanna have a non-clustered index for frequently selected fields on any table you plan on running extensive selects on (add the fields you select often to a single index)

- On a medium size table (40k records) select time on a given set of fields was doubling in time compared to the same table with a lot less data before adding a triple-index on the set of given fields.


Following the points above I was able to solve my scalability issues (the process I was running is now taking the same time on a huge db compared to an empty one). Obviosuly these rules are not applicable in every case - but understanding the points above might help people when 'scalability' hits the fan.


kick it on DotNetKicks.com

Tuesday, February 17, 2009

[VS2008] Theming STILL sucks!

This is no breaking news - but I feel like ranting.

I just noticed theming STILL sucks in Visual Studio 2008.

If you apply your theme to your webSite/webApp from web.config with:

<system.web>
<pages theme="myKickAssTheme">
</pages></system.web>

you STILL don't get to see your CSS stylesheet(s) applied in design view - also, as part of the same problem, if you set the CssClass property of your controls it doesn't always 'see' CSS classes defined in your theme (sometimes this seems to work).

Done ranting.

Sunday, February 15, 2009

[T-SQL] How to REPLACE on TEXT field

The REPLACE T-SQL function can be used only with VARCHAR - if you try to run REPLACE on a TEXT field you'll notice you're pretty much screwed (and that's probably how you ended up on this page in the first place).

There are ridiculously complicated ways to overcome this but the easieast solution I was able to find around is the following:

UPDATE myTable
SET myField = REPLACE(SUBSTRING(myField, 1, DATALENGTH(myField)), 'string2replace', 'replacementString')

SUBSTRING is returning VARCHAR so this way it works like charme.

I HATE SQL but I am getting to know more than I would like about it.

UPDATE:
as pointed out by people in the comments, the above will truncate to 8000 characters. This wasn't a concern for me at all because I knew my strings where pretty short. If you're worried about truncation you can use a CAST (check comments for more details).

kick it on DotNetKicks.com

Wednesday, February 11, 2009

[VS] Collapse all projects in a solution + How to setup Macro

This is not about increasing productivity - it's about being awesome.

How many times have you been collapsing manually all the projects in your solution ranting about the fact there's no option to do that automagically? Loadza times is the answer - unless you only work on small projects (which is not a crime btw). 

Anyway - after swearing at the screen a number of times I decided it was about time to do something about it and I googled it.

I found loads of awesome VS Macros to do what I was looking for but I hadn't a clue about how to create a VS Macro so I thought I'd share the whole thing.

First thing you need to go to Visual Studio Tools --> Macros --> Macro Explorer. Once you got that right click on MyMacros and create a new module (I called it CollapseAll).

Now edit the new module (double-click on it) erase whatever is in there and paste this stuff into it (if you want you can even try to understand what it does - but it's optional):


'Awesome Macros ripped-off
'from http://www.milkcarton.com/blog/

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics

Public Module CollapseAll

Public Sub CollapseTopLevel()
DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate()

Dim solutionWindow As EnvDTE.Window = DTE.ActiveWindow
solutionWindow.Visible = False
Dim solution As UIHierarchyItem = GetSolution()

CollapseHierarchy(solution.UIHierarchyItems, True, True)
solutionWindow.Visible = True
DTE.StatusBar.Clear()
DTE.StatusBar.Progress(False)
End Sub

Private Sub CollapseHierarchy(ByRef items As UIHierarchyItems, ByVal IsRoot As Boolean, ByVal OnlyCollapseRootLevel As Boolean)
For i As Int32 = 1 To items.Count
If IsRoot Then DTE.StatusBar.Progress(True, "Collapsing", i, items.Count)
If (items.Item(i).UIHierarchyItems.Count > 0 And Not OnlyCollapseRootLevel) Then
DTE.StatusBar.Text = "Collapsing " & items.Item(i).Name
CollapseHierarchy(items.Item(i).UIHierarchyItems, False, False)
End If
items.Item(i).UIHierarchyItems.Expanded = False
Next
End Sub

Private Function GetSolution() As UIHierarchyItem
Dim win As Window = DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer)
Dim uih As UIHierarchy = win.Object
GetSolution = uih.UIHierarchyItems.Item(1)
End Function

End Module


Now, the hard work is done - You'll see your CollapseTopLevel as a child of the CollapseAll module in you Macro Explorer and you can run it double clicking on it but we all know that sucks so the cool thing to do now is to assign an hotkey chord/combination to our kick-ass macro.

To do this you need to go to Tools-->Options-->Environment-->Keyboard. Pick your macro from the listBox with all the default VS stuff (remember it will be there like MyMacros.CollapseAll.CollapseTopLevel) and then assign a hotkey combination or chord to it (I used CTRL+K, CTRL+Y since it's not used by VS) and save. 

That's all.

P.S. I'd really like to thank Dan, who wrote the snippets I brutally ripped-off. The original article is awesome and there's plenty of nitty-gritty cut and paste potential there for developers in need.

kick it on DotNetKicks.com

Monday, February 2, 2009

[C++] What's the difference between BSTR and _bstr_t?

I stumbled upon this recently while maintaining some old code where BSTR and _bstr_t were being used interchangeably. This was generating a nasty (to say the least) bug which you can read all about here.

The main thing to understand here is that BSTR is a dumb pointer while _bstr_t is a class that wraps BSTR. The difference between the two is pretty much the same between char* and std::string.

_bstr_t also works like a smart pointer, so it will free the allocated memory when the variable is destroyed or goes out of scope. Another thing to say is _bstr_t has reference counting, increased every time you pass the _bstr_t variable by value (avoiding unnecessary copy) and decrement when it is no longer in use. Whenever all references are destroyed, the allocated memory for the string is freed up.

More about _bstr_t here, more about BSTR here.

That's it folks - lousy as ever.

Thursday, January 22, 2009

[C#, C++] Cascading Constructors

In C# you can call a constructor of your class from another constructor of the same class to do something like this:

class Cake
{
private string name;
private int price;

public Cake(int price, string cakeName)
{
this.name = cakeName;
this.price = price;
//init stuff
}

public Cake(int price):this(price, "Cheesecake")
{
//init other stuff
}
}

Unfortunately there's no way to do this in good old C++, but there are two common ways for simulating a similar behavior:

1) Combine two (or more) constructors via default/optional parameters:

class Cake
{
private:
string name;
int price;

public:
//combines Cake() and Cake("whatever")
Cake(int price, string name = "Cheesecake Giovacchia")
{
this->name = name;
this->price = price;
}
}

2) Use an Init method to share common code:

class Cake
{
private:
int price;
string name;

init(int price, string name)
{
//do crazy common stuff with price and name
}

public:
Cake(int price)
{
this->init(price, "Cheesecake Giovacchia");
}

Cake(int price, string cakeName)
{
this->init(price, cakeName);
}

}

That's about it, I prefer the first solution (the second kinda sucks) but if anyone knows better I am all ears.

I am done sucking for today.

Tuesday, January 13, 2009

Ask a Google Engineer - He Won't Answer

Recently I noticed a very promising initiative on Google Moderator: Ask a Google Engineer.

Geeks are encouraged asking questions to Guido Van Rossum & Co. with no limitation - from "Do you use Google toilet paper" to the infamous interview question "How would you sort 1 million 32-bit integers in 2MB of RAM?".

Turns out most of the question (roughly 1500 in total so far) asked by people (roughly 5000 so far) are silly complaints about how limited is this or why it's not possible to do that in gmail.
 
The rest are pretty much questions studied to impress Mr.Van Rossum with very elaborated Python blabbering or people trying to understand how to find the answers for the questions they are voting. 

But really - where are the answers? There are none (almost). Seen the amount of crap they're getting they're sitting it out to enable questions to be filtered by people votes.

Not exactly a success so far I'd say (maybe also because Google moderator kind of sucks imho)!

Thursday, January 8, 2009

Speed-up Visual Studio Startup!

Who thought getting rid of the splash screen could speed up Visual Studio this much?
Add a /nosplash to the visual studio shortcut target and see for yourself. 

Now, the question would be WHY is it so fast without splash-screen (something dodgy going on there), but this really made my day!