Wednesday, August 31, 2011

Load user control dynamically with parameters

This method can be used to load a user control dynamically in ASP.NET and pass parameters in the user control's constructor.

/// 
/// This method loads a web user control with parameters
/// 
/// The path of the usercontrol eg: 'Popup.ascx'        /// Any parameters which the user control expects        /// Current page        /// 
public static UserControl LoadControl(string UserControlPath, Page page, params object[] constructorParameters)
{
	UserControl ctl = null;
	try
	{
		List constParamTypes = new List();
		foreach (object constParam in constructorParameters)
		{
			constParamTypes.Add(constParam.GetType());
		}

		ctl = page.LoadControl(UserControlPath) as UserControl;

		// Find the relevant constructor
		System.Reflection.ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray());

		//And then call the relevant constructor
		if (constructor == null)
		{
			throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType.ToString());
		}
		else
		{
			constructor.Invoke(ctl, constructorParameters);
		}
	}
	catch (Exception ex)
	{
		//Exception Handling
	}

	// Finally return the fully initialized UC
	return ctl;
}

For more details visit this blog entry

Friday, August 26, 2011

T-SQL: Clear transaction logs for all databases

Works only for SQL2005

EXEC sp_MSforeachdb @command1 = "BACKUP LOG ? WITH TRUNCATE_ONLY DBCC SHRINKDATABASE( ? ) "

Thursday, August 25, 2011

ASP.NET: Disable Submit Form on Enter Key

By default, ASP.NET submits a form when the enter key is pressed.  When more than one is present, the first submit button in the page is 'clicked'.  You can change the default button which is pressed when the user presses the Enter key by using the following attribute in the form

<form id="form1" runat="server" defaultbutton="btnDefaultButton" >

I used this technique in order to disable this behaviour by using a dummy button at the end of the screen and pointing the defaultbutton to this button.  The dummy button must be invisible and do nothing, so here's the code

At the top:
<form id="form1" runat="server" defaultbutton="btnDisableEnter" >

At the bottom:
<asp:Button ID="btnDisableEnter" runat="server" Text="" OnClientClick="return false;" style="display:none;"/>

It seems to do the job quite well till now.  Let me know if you have a better solution or if you found it useful

Monday, August 15, 2011

XNA Tutorial: Drawing Sprites

After looking at the basics of XNA in the last tutorial, it is time to do some coding and see something on our screen! The first thing we are going to do is to draw a sprite on our screen.  Games are made up of a bunch of moving images that interact with each other and integrate seamlessly into a background.  These images in games are called sprites.

Loading an image

Create a new project by following the steps in the first tutorial. Download the image that we are going to use as a sprite from here.  Right click on the content project and create a folder called 'images'.  I like to categorise the resources in the content project by their type to keep things tidy.  Then right click on the folder and choose Add > Existing Item.
Adding an image to the content project
Now create a global variable of type Texture2D.

Texture2D pacmanTexture;

This type is present in the XNA Framework and will hold the image that we have just added.  In order to load the image, go to the LoadContent method and add the following line of code just under the spriteBatch loading.

spriteBatch = new SpriteBatch(GraphicsDevice);
pacmanTexture = Content.Load<Texture2D>("images/pacman");

The above code loads the image in our project, now all we need to do is to draw the image to the screen using the spriteBatch variable in the Draw method.

Drawing a sprite


We want the background colour to be black as our texture's background is also black. To do this, change the first line of code in the Draw method from Color.CornflowerBlue to Color.Black.

If you run the project, you will see a black background instead of the default colour. Now all we have to do is to draw the image. Add the following lines of code under the GraphicsDevice.Clear line

GraphicsDevice.Clear(Color.Black);

//Draw pacman
spriteBatch.Begin();
spriteBatch.Draw(pacmanTexture, Vector2.Zero, Color.White);
spriteBatch.End();

What the above code does, is to first tell the spriteBatch that we are going to pass something to draw, then we tell the spriteBatch to draw the image by passing the texture variable we have created earlier in the spriteBatch's Draw method. The second parameter is the position where we are going to draw the image, Vector2.Zero is a static variable for position (x:0, y:00. Note that position in XNA is done by using x and y axis, (0,0) being the top-left point of the screen. The last parameter is used to tint the image with another colour. White is passed you do not want to tint the image.

Now run the project and you should see the following.

Drawing our sprite

Centering the sprite


In order to display the image in the middle of the screen we need to know the size of the screen.  This can be done by calling GraphicsDevice.Viewport.Width and GraphicsDevice.Viewport.Height.  Therefore we can adjust the position of the sprite to the centre of the screen by amending the position parameter we earlier set as Vector2.Zero.

spriteBatch.Draw(pacmanTexture, new Vector2(GraphicsDevice.Viewport.Width / 2 - pacmanTexture.Width / 2, GraphicsDevice.Viewport.Height / 2 - pacmanTexture.Height / 2), Color.White);

Centering an image

In the next tutorials we will cover how to draw text and animate sprites.

Please feel free to comment if you have any suggestions or queries for this tutorial, they are much appreciated :)

Friday, August 12, 2011

T-SQL Conditional Ordering: CASE ORDER BY


You can conditionally order a query depending on a variable by using the case statement in the order by.

DECLARE @sort SMALLINT
SET @sort = 1

SELECT * FROM   Person.Contact
ORDER BY
CASE WHEN @sort=1 THEN FirstName ELSE LastName END

Monday, August 8, 2011

XNA Tutorial: Getting Started

Introduction

So you want to get started in the game developing world? You have probably already heard about XNA and would like to see what it can do. XNA is a framework, an API, built by Microsoft in order to facilitate the work needed to create a games for Xbox 360, PC and Windows Phone 7.    This doesn't mean that you will be creating games in a few minutes.  In order to create a game using XNA, you will have to have a form of programming background, preferably with C#.   There are a lot of books out there and websites which can give you a thorough understanding of the language, but you will need to get your hands dirty in order to truly learn it.  Then, you will need to master a few skills with the XNA framework.  I recommend to start creating a simple 2D game like Pong, Tetris or Space Invaders.


Requirements

The good news is that everything you need to start learning with XNA is free. In order to start developing games you will need to install the following software:
  1. Microsoft XNA Game Studio 4.0.  Download
  2. Visual Studio. I recommend using Visual Studio C# Express as this is free  Download
I will be using the C# Language and Visual Studio 2010 during these tutorials.


Creating a new project

After having installed the above software, open your visual studio and create a New Project (File > New > Project). Select Windows Game (current XNA version) Visual C#

Creating a new project
This will create a new blank XNA Project.  As you can see, some of the work has already been done for us. On the right section, the solution explorer, you will find that our solution contains 2 projects; our game and the Content pipeline.  The content pipeline is where we will be storing all of our game assets, that is images, sounds, fonts, 3D models and other stuff.  The pipeline translates these resources into a language which XNA understands, something which we do not have to worry about :). The other project is where we will start creating our game.

Run the project (press F5 or Debug > Start Debugging). This will cause the project to build. The project should build successfully and the game should run (if you have any errors feel free to post a comment). Congratulations, you have just created your first (boring as hell) game! :)

Your first game

Under the hood

Lets see what your first game is made up of.  'A game?' you might ask. Yes, although there is only a blue screen (Microsoft, blue really?), the XNA framework has already built the essentials for us in order to create a game.  The game loop is the heart of every game. A game works just like an animation on a set of papers. If these papers are just left on top of each other, you will only see the top drawing but if you flip fast through the papers, you will see an animation. In this case, you are the game loop. Just like we need time in order to move from one frame to another, the game has a game loop which is used to call a set of methods every so often until the game ends (60 times per second to be exact).  The game loop is made up of 2 major methods, Update and Draw which will be described in more detail below.

Now let's check the code that has been generated for us

public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
        }

        protected override void UnloadContent()
        {

        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            base.Draw(gameTime);
        }
    }


Lets break down the above methods

Constructor
Used to initialize basic variables that are needed at the beginning of the game.  In the constructor you will find the class level variable GraphicsDeviceManager being initialised.  This variable is used to retrieve data from the GraphicsDevice which could be from an XBox, PC or Windows Phone 7

Initialize
Used to initialize the game objects (Sprites, Fonts, etc..)

LoadContent
Used to load information from the content pipeline.  Example: Retrieving image and loading in a variable of type Texture2D.  In the generated code, the LoadContent is used to initialize the class level variable spriteBatch.  This object (of type SpriteBatch), will be used in the method in order to load Sprites.

UnloadContent
Used to Dispose of any objects created in the game.  At first you can ignore this method as the .NET Framework has a function called GarbageCollector which will dispose of any unneeded objects.

Update
One of the most important methods.  This is where all the game logic will occur.  In order to have a moving sprite in our game, we first need to update its location and this is the place to do it.   The Update (together with the Draw) is part of the game loop and is an essential part of XNA game development.  When creating a new project, you will find a few lines of code that are used in order to check if the player has pressed the back button on the controller and if yes, exit the game.

Draw
Also a very important method.  As explained above, in order to have a moving sprite we will need to update its location but in order to see it move, we will then need to draw it to the screen each time the game loop is called.  This is what happens in the Draw method.  It is important for the sake of code readability and robustness to keep only drawing code in the Draw method (kind of obvious isn't it?).  In the auto-generated code, you will find a line of code which fills the screen with the color blue using the GraphicsDevice object described earlier.

That's it for the basics now.  In the next tutorial we will start drawing some stuff :)

Please let me know if you found out this tutorial helpful :)


Thursday, August 4, 2011

iTextSharp: Disable PDF Printing

It took me ages to find out how to disable printing on a PDF file. You need to encrypt the file in order set copying and printing settings.  Here's how:

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
writer.SetEncryption(null, encoding.GetBytes("12345678"), PdfWriter.ALLOW_COPY, PdfWriter.STRENGTH40BITS);

And this is how to enable printing if you still want the pdf to be encrypted.

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
writer.SetEncryption(null, encoding.GetBytes("12345678"), PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING, PdfWriter.STRENGTH40BITS);