Subsonic ordering – OrderByDescending

So the subsonic documentation sucks. If you’re new to activerecord, linq and subsonic in general; you’ll find it fairly hard to construct basic queries. However once you’ve got it under control, it’s a piece of cake.

To sort your table using activerecord, use the following examples;

To sort ascending by a column called name

var categories = category.All().OrderBy(c => c.name);

To sort descendingby a column called name

var categories = category.All().OrderByDescending(c => c.name);

You can then just bind to your gridview/dropdown list or whatever you like.

            if (categories != null)
            {
                drp.DataSource = categories ;
                drp.DataBind();
            }

How to Reset your MediaWiki Admin Password

So for some strange reason, it just took me a good 20minutes to find an article on Google to tell me how to reset the Mediawiki admin password (because yes .. I forgot it). Some articles mentioned using phpMyAdmin to edit the users table directly, however the password is stored in a TinyBLOB format – so I had no clue.

Luckily I finally found a way to reset the Admin password!

You’ll need shell/SSH access for this procedure to work.

1) Login to your media wiki installation
2) Then type the following;

cd maintenance
php changePassword.php --user=Admin --password=tada321$

This will change the “Admin” user’s password to “tada321$” ! I then highly suggest you login to MediaWiki and change the password to something more secure/familiar :D

3 of the Best CSS Tutorials

So I used to be one of those old “tables are still cool for layouts” kinda guys and proceeded to use tables for just about anything web related that I touched. But there came a moment where I decided .. you know what, everyone else is raving on about this CSS layout business, so I set out to see what could be done. Now I came across quite a few tutorials on Google; and I wanted to outline the best ones that I came across!

1) Creating a CSS layout from scratch
This is pretty much my favourite CSS tutorial .. which pretty much takes the scenario of cutting and slicing a web design into an actual functional website using CSS.

2) CSS Template Layout
This tutorial goes into a bit of detail and lacks images along the way (to break up the text), however everything just made sense whilst reading this tutorial.

3) CSS Tutorial: Layout a page using CSS
A little more detailed than the others, this tutorial aims to keep it simple; but yet goes into detail about each element and tag reference. The thing to remember, is that learning CSS is like learning to ride a bike – once you know it, it’ll stick – trust me.

SubSonic 3.0 ActiveRecord Tutorial

I wanted to demonstrate the complete and utter power of SubSonic Activerecord’s toolset. Pretty much, its an easy to use querying engine which automatically creates objects that you can use within your ASP.NET project. You can use LINQ querying if you like, or you can use the SubSonic preferred way as demonstrated below;

Want to bind a gridview?

var categories = category.All();
gvList.DataSource = categories;
gvList.DataBind();

Boom. Done.

<pre lang="csharp" line="1">
int iLineID = 1;
category delCat = category.SingleOrDefault(x => x.id == iLineID);
delCat.Delete();

Too easy right?

What about adding a new record?

category newCat = new category();
newCat.name = "Dummy category name";
newCat.Add();

How easy is that? Go grab SubSonic now!

How to Bootstrap PHP Code

So what the heck is this Bootstrap PHP thing anyway?

Bootstrap means to load a small program that eventually calls the desired program into the computer, similar to an operating system being called by a BIOS program. The word bootstrap also has different meaning in different fields like science, medical, etc.

With regards to computer technology, “bootstrap PHP code” means creating a bootstrapper that handles all the dynamic requests coming to a server and apply the true MVC (Model View Component) framework so that in future you can change the functionality for each unique component or application without changing the entire code or application.

Below you will find some steps to get the process started;

1. Go to the home directory of your website and create a “Website_Src” folder and put all your application files inside it.

2. Inside the “Website_Src” directory, create an index.php file and add the following code to it.

class index
{
	public function _construct()
	{
	}

	public function index($args)
	{
		echo 'This is default index page visible to every request that can’t be routed';
	}
}

3. Now, create a second file and name it “welcome.php” & add the following lines of code to it.

class welcome
{
	public function _construct()
	{
	}
	public function index($args)
	{
		// redirecting it to test function()
		$this->test($args);
	}

	public function test($args)
	{
		if (isset($args[0] )) echo $args[0];
		if (isset($args[1] )) echo ' '.$args[1];
	}
}

4. Now, create a “.htaccess” file (if you don’t already have one) and add the following code to it. This will allow only specific characters in URI.

Options FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9-_/ ] )$ index.php?route=$1 [L,QSA]

5. Finally, paste the following code into you “index.php” file present in the “public_html” directory and test your bootstrap php code by clicking on your website link say: http://www.mywebsite.com/welcome/testing/hello

// This bootstrap php code will work only with php5 with no template engine.
// Stops from reporting any error
error_reporting(0);

// This is the folder where all your application files are present.
define('CLASSDIR', ' Website_Src ');

// Absolute path to the source files, just one level behind public folder
define('BASEDIR', @realpath( dirname (__FILE__).'/../'.CLASSDIR).'/' );
// Automatic loading of classes by using a function so that you can get rid of all include() calls.

function _autoload($class)
{
	$file = BASEDIR.$class.'.php';
	if (!file_exists ($file) )
	{
		echo 'Requested module ''.$class.'' is missing. Execution stopped.';
		exit();
	}
	require($file);
}

// breaking requesting URI to parts & retrieving the specific arguments, methods & class
$route = '';
$class = '';
$method = '';
$args = null;
$cmd_path = BASEDIR;
$fullpath = '';
$file = '';

if (empty($_GET['route']) ) $route = 'index'; else $route = $_GET['route'];
$route = trim($route, '/\');
$parts = explode('/', $route);

foreach($parts as $part)
{
	$part = str_replace('-', '_', $part);
	$fullpath .= $cmd_path.$part;

	if (is_dir($fullpath))
	{
		$cmd_path .= $part.'/';
		array_shift($parts);
		continue;
	}

	if (is_file($fullpath.'.php') )
	{
		$class = $part;
		array_shift($parts);
		break;
	}
}

if (empty($class) ) $class = 'index';
	$action = array_shift($parts);
	$action = str_replace('-', '_', $action);

if (empty($action) ) $action = 'index';
	$file = $cmd_path.$class.'.php';
	$args = $parts;

// now that we have the parts , let's run a few more test and then execute the function in the class file
if (is_readable($file) == false)
{
	echo 'Requested module ''.$class.'' is missing. Execution stopped.';
	exit();
}

// load the requested file
$class = new $class();

if (is_callable(array($class, $action) ) == false )
{
	// function not found in controller , set it as index and send it to args
	array_unshift($args, $action);
	$action = 'index';
}

// Run Action
$class->$action($args);

}
?> 

ASP.NET & AlternatingRowStyle & IE8

If you’re a ASP.NET developer like myself, you may or may not have noticed a few changes to your sites when viewed in Internet Explorer 8.

As an example I had a gridview which had a different background for alternating rows.

<AlternatingRowStyle CssClass="odd" /></code>

And my CSS was something like

.odd { background-image: url(../graphics/tealbg.gif); }

The Solution

The easy (and maybe a little messy) way to solve this is to force the page to use IE7 compatibility. You can do this by adding the following to your tag.

<meta http-equiv="X-UA-Compatible" content="IE=7" />

Note: The above meta tag MUST appear before any link tags (stylesheet includes for example)

Installing Postgres gem on Windows

So you’re trying to install the postgres gem for ruby on rails, but you’re getting the following message;

Could not find PostgreSQL build environment (libraries & headers): Makefile not created

This is most likely due to the fact that you’re not using the mswin32 gem for Ruby.

Give this a whirl;

gem install ruby-postgres

ASP.NETs Forms Based Authentication

Websites that offer membership based services often require their important files to be secured from non-members. For this purpose, they need to implement form based authentication that ensures that only members can access the files and even if a non-member copies the exact location of the file on the server, he/she is denied access to the file and redirected back to the login page. Let’s check it out.

1. If you are using an IDE then you need to create a new project and add a LoginPage.aspx page. Switch to html view and add the following code inside the tag of you LoginPage.aspx page.

<h2> <font face="Times New Roman">Login Credentials</font> </h2>
<table> <tr>
<td>User Name :</td>
<td><input id="CUserName" type="text" runat="server" NAME="CUserName"></td>
<td><ASP:RequiredFieldValidator ControlToValidate="CUserName" Display="Static" ErrorMessage="*" runat="server" ID="VUserName" /></td></tr>
<tr>
<td>Password:</td>
<td><input id="CUserPass" type="password" runat="server" NAME="CUserPass"></td>
<td><ASP:RequiredFieldValidator ControlToValidate="CUserPass" Display="Static" ErrorMessage="*" runat="server" ID="VUserPass" /></td> </tr>
</table>
<input type="submit" Value="Login" runat="server" ID="cmdLogin" NAME="cmdLogin">
</p>
<asp:Label id="lblMsg" ForeColor="red" FontName="Times New Roman" FontSize="12" runat="server"/>

2. Now, change the authentication in your web.config file to and modify the authentication parameters as given below:

<authorization>
<allow users="*" />
<deny users="?" />
</authorization>

3. Now, browse the virtual directory in Internet Information Services (IIS), right click on it to access the properties. Move to security tab & click on edit to check Anonymous access option.

4. On your IDE change the view mode to code view for the LoginPage.aspx page and add the following code to it. Refer to Point 4 of Code Event Handler at http://support.microsoft.com/kb/308157

Provide your own coding for authenticating the username & password

if CUserName.Value = "AAAAAAA" and CUserPass.Value = "BBBBBBBB" Then
FormsAuthentication.RedirectFromLoginPage(CUserName.Value , True)
else
Response.Redirect("LoginPage.aspx" , True)
End if
End Sub

5. Create a new page and name it as DefaultPage.aspx and add the following to the html view of the page.

<table border="0">
<tr><-td>http://ServerName/FormsAuth/SecuredFolder/AnyFile.doc</td>
<td><-asp:Button id="SendFile" runat="server" Text="Send File"></asp:Button></td>
</tr>
</table>

Now, switch to code view for this page & add the following lines

Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button.Click FormsAuthentication.SignOut()
Response.Redirect("LoginPage.aspx" , True)
End Sub
Private Sub SendFile_Click( ByVal sender As System.Object , ByVal e As System.EventArgs ) Handles SendFile.Click
Response.ContentType = "application/msword"
Response.Clear()
Response.TransmitFile("SecuredFolderAnyFile.doc") ‘Create a SecuredFolder in Virtual Directory & add “AnyFile.doc” to it
Response.End()
End Sub

Why I used a button instead of a hyperlink is because in case of hyperlink the file will be cached and even if you change the contents of the file, the old file will be displayed. A button will prevent this.

6. Protect the SecuredFolder and ensure that you have granted the READ permission to the Network service or ASPNET. Run your project and try what happens when you try to paste the url of the file and then access it. You will notice a Login page instead of the file.

The GridView fired event PageIndexChanging which wasn’t handled

If you’ve set a gridviews AllowPaging attribute to “true”, you’ll notice the following error;

The GridView fired event PageIndexChanging which wasn’t handled

To setup paging with Gridviews, you also need to set the page index property to the new page that you wish to view. Funny enough, this is extremely easy to do. See below for a code example written in C#.

The ASPX page

<asp:GridView ID="gvList" runat="server" AutoGenerateColumns="true" AllowPaging="true" PageSize="10" OnPageIndexChanging="gvList_PageIndexChanging">

and the C# code

    protected void gvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        bindGrid();

        gvList.PageIndex = e.NewPageIndex;
        gvList.DataBind();
    }

Line Numbers in Eclipse

It’s 4am in the morning. You’ve been coding in Java for the past 6 hours and realise something’s missing from your Eclipse editor .. something that can confirm that the last 6 hours weren’t a WASTE of time..

and that is line numbers.

To turn on line numbering in Eclipse, simply do the following;

1) Windows -> Preferences
2) General – > Editors -> Text Editors

and click the “Show Line Numbers” checkbox.
Whola?

Now was the last 6 hours a waste?

Hiding Details view after update

I had the need to hide a detailsview after an update. Forget using visible=false, this just hides it permanently!

Try setting the datagrid selectedindex = -1

        protected void dvDetailsView_Updated(Object sender, System.Web.UI.WebControls.DetailsViewUpdatedEventArgs e)
        {
            gvGridview.SelectedIndex = -1;
        }

Weird scrolling issue with Modalpopupextender

Are you ripping your hair out over a issue with the AJAX modalpopupextender and a never-ending scrollbar?!? I had a panel with a style=absolute in the style= tag, causing the popup to show in the middle of the page. But for some reason, the page went wonky and I could scroll endlessly!

Here’s the fix;

I changed this

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"

to this

!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"

and my pain ended.

« Previous Entries Next Entries »