Sunday, May 31, 2015

Combine png / jpg into pdf on windows from the command line for free.

There seems to be a hell of a lot of utilities to combine images (png's, jpgs etc) to form pdfs. But as a savvy user you've probably formed a distrust of shareware or similar.

If you're like me, you've installed a few to find you need to register to get the features you need! Frustrating!

Fortunately it's ridiculously easy with GraphicsMagick, an open source command line image manipulation power house (for free)!

  1. Install GraphicsMagick, doing so via chocolately is the easiest using cinst graphicsmagick from an admin command prompt (if you're not using chocolatey - you should!)
  2. Open a command prompt in the directory where your images are in
  3. gm convert *.png yournewpdf.pdf where *.png can be another image format or a list of images

If "gm" isn't working, try opening a new command prompt to allow the path to be refreshed.


Saturday, May 10, 2014

nDepend - the code analysis super tool

Patrick from nDepend kindly sent me over a copy of nDepend to try out.

nDepend is a code coverage tool with a hell of a lot to give. Think of it like FxCop / Visual Studio's Analysis tools but with a whole suite of tools to support the analysis.

It's a great fit if you're looking to refactor your code, it can analyse it for problem areas (similar to FxCop) but it also has the capability to define your own metrics using "Code Query over Linq" (clever stuff indeed).

One of my favourite features is the ability to get a grasp of existing architecture, as we all know that even though your team's documentation should of been written early on, it often becomes a low priority as soon as it hits production.

It's also a nice way to explore open source projects and to take a look at the architecture the big players are using.

Here is an example of examining the popular open source .net CMS DNN (previously DotNetNuke), we can see highlighted that the method 'RewriteUrl' is perhaps overly complicated. Clicking the function name opens visual studio directly with the file open in the right place (nicely polished - it even has Visual Studio integration). Reading over the RewriteUrl method it's a bit of a beast and could become a maintenance problem so could be a future task to refactor (for example).

The screenshot may look complex as it's a power user tool, but nDepend is a very friendly tool offering contextual help along the way. A short blog post can't do it justice, if you're dabbling with refactoring and want something more powerful than the built in tools, I'd recommend taking a look at the nDepend website to learn more.



Monday, October 29, 2012

Read CSV with LinqPad

This is a super simple way of reading CSV in linqpad, it won't handle every situation (I'll cover more ways in future posts), but it's pretty handy.

Lets say we have the following CSV:

ID,Name,Email
1,alex,alex@example.org
2,bob,bob@example.org
3,fred,fred@example.org

The first step is to click "my extensions" on the bottom left hand corner of linqpad.

Now copy the following c# code (sourced from: stackoverflow) in the "my extensions" class in linqpad:
The advantage of this rather than simply reading all lines is that it will load the file line by line and using the yield keyword will stop if finds what you need (rather than reading the whole file).

 public static IEnumerable ReadFrom(string file) 
 {
  string line;
  using(var reader = File.OpenText(file))
  {
   while((line = reader.ReadLine()) != null) 
   {
    yield return line;
   }
  }
 }
Remember to press F5 in the my expressions window to compile it.

You can now very easily read the CSV in linqpad using the following linq query (in expression syntax):
Hover over to see descriptions

var csvData =
from row in MyExtensions.ReadFrom(@"c:\sample.csv").Skip(1)
let columns = row.Split(',')
select new
{
 ID = int.Parse(columns[0]),
 Name = columns[1],
 Email = columns[2]
};

csvData.Dump();

Now when you press F5 in LinqPad your CSV will be displayed in a nicely formatted table:

You can then parse the CSV in with normal linq queries, for example this simple linq expression will find people whose name "alex". Please note the intellisense drop down will only in linqpad pro edition (certainly worth the money if you ask me!)

 var alexs = from csv in csvData
         where csv.Name.Contains("alex")
      select csv;

I have found this sort of technique especially useful when comparing on an adhoc basis if CSV data was successfully imported via SSIS etc. This technique won't handle quoted CSV, but let me know and I'll post a follow up with more in-depth CSV handling techniques or perhaps if you want me to cover linqpad further.

Sunday, October 28, 2012

[SOLVED] Sql restore error: database is in use.

Sometimes you are trying to restore a sql server database and you'll get the error:
"Exclusive access could not be obtained because the database is in use."

Exclusive access could not be obtained because the database is in use.

This simple one-liner will kick everyone off SQL Server (including any inadvertant connections from yourself e.g. edit table connections).

USE MASTER;
ALTER DATABASE [dbname] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

This technique works fine on Microsoft SQL Server 2005 / 2008 and Express Editions (probably works on more versions). It works very quickly and allows you to restore you database straight away afterwards.

This excellent tip was found on dba stackexchange. Please let me know if you found this tip helpful.

Saturday, September 15, 2012

Free Online SQL Editor

I came across a little gem; if you are ever stuck with some SQL and ask for some help in a forum etc, this free online sql editor called SQL Fiddle will allow you to create tables, run sql etc all online - ready to share with fellow developers.

If you are familiar with it's JavaScript cousin jsFiddle, then this is a welcome addition to your tool belt.

Sunday, July 17, 2011

Empty folders in Git / Mecurial

Git / Mecurial do not track empty directories, but there is a useful tool to help.

To track empty directories, you need to simply create place holder / dummy files in those directories e.g. a simple txt file.

If you have many folders or are importing an existing project into source control it can be a pain to create all the place holder files.

Fortunately there is an easy to use command line tool that will scan through all your directories and generate dummy files for you at the bottom depth. Even better if you directory structure changes and a folder is not longer empty it will delete them for you.

You can download the open source / free tool from the makeemptydirs website

Friday, July 08, 2011

firebug frame - tips

Here are a few tips for using firefox's firebug and frames:

An example of a frameset:

screenshot of a frameset rendered in firefox


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Frameset example</title>
</head>
<frameset rows="50%, 50%">
 <frame src="frame1.html" id="frame1" name="frame1"/>
 <frame src="frame2.html" id="frame2" name="frame2"/>
</frameset>
</html> 

By default firebug is relative to the "window", to make commands relative to a frame instead, you can use the "cd" command in the console pane, for example:


cd(window.frames["frame1"])

a command typed into firebug command line in firefox

Now when you execute command it will be relative to the window instead.

So for example if you had this code in frame1:



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>frame1</title>

<script type="text/javascript">
function hello() {
 alert("hello")
}
</script>

</head>
<body>
frame1
</body>
</html>


You can run the function in the firebug command line simply by running the function: hello()

an alert box being triggered within a frameset from the outer window via the firebug commandline

Similarly you can also use this alternative syntax to get to the frames:

cd(window.top)
Back to the default root window

cd(document.getElementById("frame1").contentWindow
To reference the frame by id

cd(document.frames[0]
To reference the frame by number

Monday, July 04, 2011

Incorrect syntax near the keyword 'OPTION'. When using CTE's inside a UDF.

It is useful to use common table expressions (CTE) to perform recursive calls.

Normally recursion is limited by default to 100 recursions, this is to stop infinite loops.

You can normally override the default using the MAXRECURSION query hint. e.g.


OPTION (MAXRECURSION 200); -- overrides with 200 recursions, but will break inside UDFs

Unfortunately if you set this inside a UDF, you will get the error: Incorrect syntax near the keyword 'OPTION'. This is a known issue mentioned in microsoft connect.

A simple solution

Fortunately if you have control of the outer SQL, it is simply a case of setting MAXREECURSION on the SQL calling the UDF e.g

SELECT X FROM YourUDF(Parameter) OPTION(MAXRECURSION 0)

Of course this solution is only applicable in some situations, some of you really need to be able to configure the recursion within the UDF. But when I came across this, it helped me.

Wednesday, June 29, 2011

Exclude folders (.hg / .git) from Visual Studio search

When doing a find in files in a source controlled project in Visual Studio, the source control folder i.e. .hg (Mecurial) / .git (git) will appear in the search results (which is not what you want!)


hg folder in visual studio




You can hide folders in Visual Studio in two different ways:

For websites i.e. "open website" style projects

Simply browse to the folder in windows explorer and mark the folder as hidden in the folder properties.


set the folder as hidden in the folder properties via windows explorer


You may need to refresh the solution explore in Visual Studio to see the change.

the folder should now be hidden


This has been tested in Visual Studio 2008 and 2010 and is useful for hiding .git and .hg folder, but can be used to hide any folder.


For other projects type in visual studio (class library, web application etc). you can simply right click on the folder in the solution explorer and click exclude.

Monday, June 27, 2011

Encrypt SQL statements

If you distribute your SQL code to third parties (perhaps in runs on other peoples servers), you may wish to help protect your intellectual property by encrypting your SQL statements.

Simply using "WITH ENCRYPTION" at the end of your normal CREATE PROCEDURE will stop the definition of your sql statements being returned. The statement will be automatically decrypted on the fly.


CREATE PROCEDURE AlexTestProcedure
WITH ENCRYPTION
AS
SET NOCOUNT ON;
SELECT Firstname, Surname, Email
FROM Users;
GO


After having a quick look around the internet on the merits of the added security;
In SQL server 2000, the de-obfuscated text is stored in the SYSCOMMENTS table before it is executed. So you may wish to consider this as a preventative measure for the casual nosey parker, but not a bullet proof solution. However the equivalent MSDN page for SQL 2008 R2 doesn't mention this.

MSDN article on CREATE PROCEDURE sql server 2008 r2

MSDN article on created procedure sql server 2000


Interesting things you learn whilst talking to DBA's (thanks Solomon!)

Thursday, January 06, 2011

NULL shortcut key in Sql Server Management Studio (SSMS)

Sometimes you are manually editing a row in the table pane in Sql Server Management Studio (SSMS) and you need to put NULL in a column. An easy shortcut key is, whilst the cursor is in the column:

CTRL + 0


Monday, December 20, 2010

Website screen resolution test in Internet Explorer

It's easy to simulate various screen resolutions (screen sizes) in Internet Explorer using the built in developer tool (built in since IE7). Allowing you to test your webpages in various screen sizes.

Simply go to the menu item as illustrated below or press the keyboard shortcut F12 to load the developer tool.


To open the developer tool in Internet Explorer 8; click the cog icon in the top right hand size, then click 'developer tool'

The built-in IE developer tool should now open, as illustrated below.

With the developer tool now open; in the menu click "Tools" > "Resize" and select the screen resolution of your choice. By default you can simulate, 800x600, 1024x768, 1280x768 and 1280x1024, which covers the most popular resolutions. However you can also provide your own custom resolutions.

Once the developer tools are open, click

Notably, this is only a simulation of screen resolutions. It does not show you exactly what a person using these screen resolutions will see. It will only change the height/width of your browser window and will not effect font sizes etc etc. But it is far faster than changing your own monitor resolution each time you wish to test.

The resolution simulation is therefore very useful for testing CSS layouts, but perhaps not as useful if your testing for accessibility compliance etc. You could use this technique for day-to-day testing, coupled with actually changing your monitor resolution (more time consuming) for more in-depth testing.

This tip has been written for Internet Explorer 8 under Vista, but it should be very similar for IE7+ under XP+.

Sunday, December 19, 2010

Simulate a slow internet connection in web browsers (Internet Explorer, Firefox, Chrome etc)

You can easily simulate a slow internet connection, by using a tool called "fiddler".

Perhaps you are trying to debug a web application that is behaving strangely on other peoples computers (but is working fine on your own?!). Perhaps you wish to simulate a slow modem or a slow corporate VPN.

The fiddler is a web debugging proxy which logs all HTTP traffic between your computer and the internet. The fiddler has a setting to temporarily throttle your internet connection, to make your connection behave like a slow modem. The great thing about the fiddler is that it "automagically" sits in between all your web browsers and the internet, so it works with firefox, internet explorer, chrome etc etc.

Firstly you need to install "fiddler", just go to http://www.fiddler2.com, download it and install it. It installs in seconds and has a getting started guide if you need it.

a screen shot of fiddler2.com

Once you have the fiddler installed, open it and once loaded you should see a window similar to below. It should automatically act as a proxy, so if you browse to a website in any browser you should see it being logged in the fiddler.

the first page of the tool: fiddler. With a few HTTP requests logged.

To switch on "simulate slow modem speeds" mode in the fiddler (as illustrated in the screen shot below):

  1. If not already opened, open the fiddler.
  2. Click "Rules" on the top menu.
  3. Then go to "performance".
  4. Click "simulate modem speeds"
a screen shot illustrating how to turn on simulate modem speeds in the application called fiddler.

Now any web browser that is using fiddler (should be all web browsers by default), will temporary be slow (until you turn it off)

This is only scratching the surface of what the fiddler is useful for. There is plenty more information and an introductory video in the fiddler help section.

Tuesday, December 14, 2010

<script> tag: type="text/javascript" vs language="javascript"

When adding JavaScript to a webpage using the <script> tags, should you use the type attribute, the language attribute or both? The answer is below...
<script type="text/javascript"></script>
OR
<script language="javascript"></script>
OR
<script language="javascript" type="text/javascript"></script>
The simple answer is you should be using the type attribute for script tags
<script type="text/javascript"></script>

You do not need to use the language attribute because the attribute has been deprecated since HTML 4.01, this can be seen in the "Designing documents for user agents that support scripting" section in the HTML 4.01 Specification.

Log to the built-in IE developer console

Rather than using JavaScript alert()'s to see the value of variables and alike, the IE developer tools allows you to output to IE's JavaScript console.
To open the IE developer tools, simply press F12

The console log command is simply:
console.log()

So for example:

<script type="text/javascript">
    for (var i = 0; i < 5; i++) {
        console.log("hello" + i);
    }
</script>

Would output something like this:

This is a rudimentary example, but s is especially useful if you want to know the value of many variables at a glance (rather than keep having to press OK for each alert()!)

Watch out for...

One gotcha is that your JavaScript will error in IE if your console is not open, because the console object will not be found, the simplest way around this is to remove your console commands after you have finished with them. I will post a workaround for this at a later date.

Of course using breakpoints and stepping through the debugging, is more often a better option (I'll do a quick post on how to do this at a later date), but in many situations outputting to the console is very useful.

The IE developer tool bar is built into Internet Explorer 7+ (I pressume it will also be in IE9+). As mentioned above you can access it by pressing F12 (or by using the menu).

More information

There are many variations of console.log, more information available on the MSDN site: Using Console for Logging Alerts and Error Messages

These posts are only here to give you quick and easy tips... however if web development is your day to day role, I'd highly recommend getting familiar with the built-in IE developer tools. More information is available on the MSDN site: IE Developer Tools tutorials

Friday, August 27, 2010

Incremental search in Visual Studio

If you have a long piece of code and your're finding that you are constantly scrolling up and down...

You can do a "search as you type" in Visual Studio 2010 to find what you need very quickly.

With a code file open press:

Ctrl + i

And then begin typing in what you are looking for (it will begin searching on the first letter).

To go to the next result, press Ctrl + i again.

To search upwards, press Ctrl + Shift + i

If you have misspelled, simply press backspace (it doesn't delete your code as you'd first think).

Great for quickly moving around a single file of code.

Thursday, August 19, 2010

Visual Studio - convert text to upper case short cut key

In visual studio you can quickly make text upper case, by selecting the text and simply press:


Ctrl + shift + u



It can also be found in the menu edit > advanced > make upper case.

Wednesday, August 18, 2010

Management Studio - invaluable add-on: SSMS Tools Pack

I'd highly reccomend anyone who uses Sql Server Management Studio day to day, to install a free add-on pack called "SSMS Tools Pack" available here www.ssmstoolspack.com

I won't go into to much detail, as the site sells itself.

Monday, August 16, 2010

Get database ID from MS Sql Server

If you need to get the database ID quickly (for example you are using SQL profiler and need to filter by database ID)

One of the quickest ways I have found is to execute the following built-in function:

select db_id('yourdatabasename')


Wednesday, August 04, 2010

Filtering tables in SQL Server Management Studio

You can filter your list of tables in SQL Server Management Studio by doing the following (below).

This is especially useful if you have lots of related tables and your only interested in a particular set of them e.g. every table with "user" in the table name.

  1. Right click on the tables folder
  2. Choose Filter > Filter settings
  3. This brings up a dialog window allowing you to choose your search criteria (only simple criteria can be user e.g. name, owner, so you cannot use OR/AND etc).
  4. After clicking enter your tables are filtered (in the example by all table names with the word "user" in them).
  5. Happy developer
This example is in Sql Server Management Studio 2008 R2 (but it should work in 2005 and perhaps lower).





Tuesday, August 03, 2010

Code snippet for class property

Typing out class property's is necessary but repetitive (and boring), as a quick shortcut you can use the property code snippet:
  1. start typing prop
  2. press tab twice
  3. you then get a template property
  4. pressing tab will allow you to quick fill in the type and property name


Monday, August 02, 2010

Visual Studio - Find a file auto-complete

In Visual Studio you can find files quickly by using a built in auto-complete feature (particularly useful to find files in large projects worked on in teams where you may not know the complete structure)
  1. press: CTRL + /
  2. type: of
  3. Then start typing in the filename (of the file you wish to open)
  4. Select the filename from the drop down box and press enter
  5. The file opens (happy developer)
This is tested to work in Visual Studio Professional 2008 / 2010 and Visual Web Developer Express 2010


Saturday, July 31, 2010

Shortcut Key for Table Details in Sql Server Management Studio

If you select a table name in the query window of Sql Server Management Studio
and press ALT + F1 it will display the details of that table.

In the background shortcut key will execute sp_help on your behalf, so in this example it executes: sp_help users, which is much quicker than typing it.

I'm running Sql Server Management Studio 2008 R2 (but i'm pretty sure it'll work with earlier versions)