ALTER LOGIN fix for SQL Server logon problems

We’ve all done it. Changed our default database for our logon to a database in SQL Server other than master, then either detached or deleted the database some way down the line. Of course at this point your pretty much screwed as you can’t access much as your login no longer works.

To fix this when you open Management Studio press the Options button and change the Connect to Database option to master. Now, this doesn’t fix the problem, it merely allows you to then open up a New Query. In the query enter the following SQL, change the login name and execute it.

ALTER LOGIN TestLogin WITH DEFAULT_DATABASE = master

Change TestLogin for your own login, close Management Studio and re-open it, press the Options button and change the Connect to Database option back to <default>.

At this point you should be able to get back into SQL Server with the usual authority and you can now re-attach your database.

WinForms Screen Capture

For a recent project we’ve been working on we needed to get a screen shot of a form and it’s contents. After much checking on the net for some sample code, all of which used GDI32 and User32 calls, we gave up looking and decided to investigate ourselves.

In the end it was so simple and clean that we just can’t believe that this isn’t documented that well anywhere on the web. The code below is an extract of our code that takes the forms position on the screen, creates a bitmap of the contents of the screen from co-ordinates passed to it and then saves the resultant screen shot to a file

using (Bitmap bitmap = new Bitmap(ParentForm.Size.Width, ParentForm.Size.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(new Point(ParentForm.DesktopLocation.X, ParentForm.DesktopLocation.Y), new Point(0, 0), ParentForm.Size);
}

bitmap.Save(@”C:\test.jpg”, ImageFormat.Jpeg);
}

Enjoy đŸ™‚

Tagged

Ajax comes to EmigratingToOz.com

The goal of the EmigratingToOz.com website is to be the oracle of information about Australia for us UK poms and to help them in the emigrating process. To that end, one of the things we needed to do was also supply real-time information about Australia from the point of view of weather, money and time.

Initially, the website was set up to actively get this information from a variety of sources and simply display on the page via the master page. However, the weather information in particular, comes from a slowish website that was killing the inital load time of the site.

The solution was simply to implement Ajax calls to get the information required in an asynchronous manner. Using the generic library that we created to demostrate Ajax calls on our main website, we were able to implement the calls for all of the data in one quick afternoon. The result is a quicker and more pleasing experience.

Showing a Windows form full screen

Ok…. quite simple you might think! And yes it is, but only if you know how!

For a small project that we are working on at the moment we needed to show a Windows Form in full screen mode without the taskbar etc… It is quite simple in the end but needs a couple of Win32Api calls, but that is simple enough. The one thing that is easy to forget is that you need to set the FormBorderStyle property for the form to None, otherwise you will still have the menu bar showing.

To acheive the full screen mode create a simple class with the code below in it

[DllImport(“user32.dll”, EntryPoint = “GetSystemMetrics”)]
public static extern int GetSystemMetrics(int which);

[DllImport(“user32.dll”)]
public static extern void SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, int X, int Y, int width, int height, uint flags);

private const int SM_CXSCREEN = 0;
private const int SM_CYSCREEN = 1;
private static IntPtr HWND_TOP = IntPtr.Zero;
private const int SWP_SHOWWINDOW = 64;

public static int ScreenX
{
get { return GetSystemMetrics(SM_CXSCREEN); }
}

public static int ScreenY
{
get { return GetSystemMetrics(SM_CYSCREEN); }
}

public static void SetWindowFullScreen(IntPtr hwnd)
{
SetWindowPos(hwnd, HWND_TOP, 0, 0, ScreenX, ScreenY, SWP_SHOWWINDOW);
}

Then in your application simply create a new instance of the form and call the Show method on the form.

Form form1 = new Form();
form1 .Show(this);

Then finally create an OnLoad handler for the form and call the SetWindowFullScreen method on our helper class and that is it.

WinApi.SetWindowFullScreen(Handle);

Tagged

New CodeConsults website – Emigrating To Oz

We’ve recently started a new project website called Emigrating To Oz

Its a site centering around providing a resource of information for people wishing to emigrate to Australia, but its still in its infancy and we are targetting a Q2 2008 release with all the bells and whistles, but in the meantime the site is live so that we can begin getting it indexed and tested.

There’s plenty of work to do and content to add and we’re hoping that in time it will become an excellent resource for us Poms who are looking at possible life Down Under.

This application has failed to start because the application configuration is incorrect

C++ installations have never been easy and probably never will be. Having not done any C++ release work for a number of years I ran into a problem when releasing a C++ application that I built using Visual Studio 2005.

In the old days you had a nightmare working out which version of the C++ libraries to distribute and where to put them. Unless of course you statically link to the libraries which resolves the problem but makes the files rather larger.

But now with building the application using VS 2005, there is this new problem that arises which results in the obsure message

This application has failed to start because the application configuration is incorrect

After a bit of digging into all of this I found that there is a redistributable package from Microsoft that installs the necessary libraries for C++ that were used by VS2005 to build the application in the first place. Where it puts the libraries I don’t know, but to be honest I don’t really care as the installation was very simple and worked first time….so i’m happy for now.

Heres a link to the redistributable package from Microsoft.  This is the SP1 version of the package which is required if your VS2005 installation is all up-to-date. If it isn’t there is an older version of the package available from Microsoft, or your could do the right thing and get VS2005 up-to-date instead.

Tagged

A neater way of getting data out of a DbDataReader

Previously I have always done the following to iterate through a bDataReader

while(reader.Read())
{
int index = reader.GetOrdinal(“User_Description”);
list.Add(reader[index] as string);
}
But today I stumbled upon the following which is so much neater:

foreach (DbDataRecord dbDataRecord in reader)
{
int index = dbDataRecord.GetOrdinal(“User_Description”);
list.Add(dbDataRecord[index] as string);
}

I just think it’s a lot neater and clearer as to what’s going on.

Tagged

Reverse iterating through a List collection

Reversing through the object in a List is an operation that isn’t so uncommon, and there is a simple way of doing this using a for loop with a decrement on an index value. But it isn’t a particularly elegant way of acheiving this and the re-use of the for loop isn’t the most efficient in terms of code re-use. Thankfully with the use of the IEnumerable interface we can create a simple, clean and elegant solution to the problem.

By deriving from the IEnumerable interface we can create a new GetEnumerator method and do the meat of the work here. Below is a class that implements this interface to create a reversable enumerator dependant on a simple local property. The property is from a simple enumeration that is defined as Forwards or Reverse.

public sealed class Counts : List<long>, IEnumerable<long>
{
/// <summary>
/// The direction to iterate through our collection
/// </summary>
private IteratorDirection iteratorDirection = IteratorDirection.Forwards;

/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref=”T:System.Collections.Generic.IEnumerator`1″></see>
/// that can be used to iterate through the collection.
/// </returns>
public new IEnumerator<long> GetEnumerator()
{
if(iteratorDirection == IteratorDirection.Forwards)
{
for (int i = 0; i < Count; i++)
{
yield return this[i];
}
}
else
{
for (int i = Count – 1; i >= 0; i–)
{
yield return this[i];
}
}
}

/// <summary>
/// Sets the iterator direction.
/// </summary>
/// <value>The iterator direction.</value>
public IteratorDirection IteratorDirection
{
set { iteratorDirection = value; }
}
}
To use the class is simple… First set the direction that you want to iterate through the collection, then iterate through the collection using the ubiquitous foreach loop

OurCounts.IteratorDirection = IteratorDirection.Forwards;
foreach (long count in OurCounts)
{
}

OurCounts.IteratorDirection = IteratorDirection.Reverse;
foreach (long count in OurCounts)
{
}

Getting the application path using reflection and C#

Just recently I had a problem whereby there was a case which resulted in the current working directory changing before some of my code had run. As I hadn’t catered for this case it came up with a crash which was easily fixed by getting the current application path and then combining this with the filename which I wished to access. Heres the code that I used to acheive this in a nice clean fashion and create a path to a configuration file (configurationFilename):

Uri uri = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
string fullConfigurationFilename = Path.Combine(Path.GetDirectoryName(uri.AbsolutePath), configurationFilename);
fullConfigurationFilename = HttpUtility.UrlDecode(fullConfigurationFilename);

By using reflection to get the location of the currently executing assembly I am not relying on the actual .exe location (or website location in fact), but instead using the actual dll’s location from which the current code is running. You might wish to use the actual application’s path or the website root path, but in the scenario that I am using this in, the assembly’s path is exactly what I wanted.

Tagged

Scripting SQL Inserts from existing table data

In the past I usually hand generated a quick bit of SQL to generate my INSERT statements from existing table data like so:

select
‘insert into dbo.Links values (‘ +
cast(exceedence_set_id as varchar(100)) + ‘, ‘ +
cast(seq as varchar(100)) + ‘, ‘ +
cast(link_id as varchar(100)) + ‘, ‘ +
cast(link_offset as varchar(100)) + ‘, ‘ +
‘false,’ +
cast(band_id as varchar(100)) +
‘)’
from dbo.Links

The only problem with this was that I had to hand add in the column name, handle null data etc… So, I thought I’d have a look to see if someone with loads more SQL experience than me had had a go at handling this all automatically. After a bit of searching on Google I found a handy procedure from Narayana Vyas Kondreddi. Put simply it can automatically generate your Insert statements for any table and also comes with a host of configurable parameters to tailor the output to your own needs. For example to generate the statements for table Links but ommit the column names because the data will be inserted into an identical table on another SQL Server instance, and to also ommit the identity column, call the procedure like so:

EXEC sp_generate_inserts ‘Links’, @include_column_list = 0, @ommit_identity = 1

It’s that simple….great piece of work by Vyas. Also check out the rest of his site as there’s plenty more SQL stuff available…