Archive for the ‘Coding’ Category

January 26th, 2011

Transparency in Web Design

How is it done? Let’s take a gander at four different ways. Each of them handling the illusion in a different way, and each completely appropriate depending on the situation at hand.

Totally Friggin Fake It


From the Spectrum Theme website

The end result of any web design is basically an illusion anyway. You can always create your transparent effects in Photoshop or whatever other graphics editor and export flat graphics. In Photoshop, transparent effects can be created by changing a layers opacity level, fill level, or blending mode, just to name a few.

Opacity


This entire button has opacity applied to it, to emphasize that it is currently “disabled”.

You can make any element transparent by using the opacity parameter of CSS.

#anything { opacity: 0.5;  /* 50% transparent */ }

If you need to support older browsers, see here.

Do note that all descendants of the element with opacity also become transparent. There is no way to “force” any descendant to be come any less transparent as the parent is.

RGBa / HSLa


From the Like Architects site

Using RGBa for a color value in CSS, you can set a transparency level on any color. This has the distinct advantage over opacity in that it doesn’t have any affect on descendants. It is also nice in that creating faded out variations of a color is as easy as changing the final alpha value. Speaking of color variations, that is even easier to do with HSLa, and is still able to handle transparency.

#anything { background: rgba(0,0,0,0.5);  /* 50% transparent */ }
#anything { background: hsla(0,0,0,0.5);  /* 50% transparent */ }

PNG


From a Dribbble

When “Saving for web” from Photoshop, you have two choices for PNG’s: PNG-8 and PNG-24. PNG-8 is like a GIF in that you can have transparency in pixels, but a pixel is either fully transparent or fully opaque, no in-between. PNG-24’s, while far bigger in file size, support full alpha-transparency.

In the example above, the shadows from the content areas are from PNG-24s so that the texture in the background can change and the shadows will still be the same.

May 31st, 2010

Tricks

Drag things, pick colors, make a nice class for your buttons… introducing the Button Maker.


Boy, that’s a nice button right there.

I’m saying “CSS3″, because these make use of gradients, shadows, and rounded corners which contribute greatly to their button-ness. In older browers that don’t support these properties, the fallback is solid-color background, no shadows, and square corners. Not a big deal.

I hope this is painfully obvious, but to use this Button Maker thing, you just adjust the settings until you have a nice looking button, then press the button and it will give you the CSS. Copy and paste at your leisure. Now you can use the class name “button” on HTML elements to make them look like buttons. The CSS isn’t formatted real pretty. If someone has an idea on how to make that better, please do let me know.

The super-awesome empowering concept…

…in regards to how the Button Maker preview works.

It’s easy to change the CSS of an element on-the-fly with JavaScript. But how can we change the :hover state? The answer is that we can’t really, at least not really easily. We could attach a mouseenter event that would apply some new CSS that would override the old, and a mouseleave event that would put it back. That’s a lot of overhead for something so relatively small. It gets even more complicated if we wanted to control the :active state as well.

This Button Maker shows you a live working version of the button you create, complete with :hover and :active states. It is done without attaching any JavaScript events to the button itself. So how is it done? I did it with a technique I ripped off from Doug Neiner who presented it (as small part of a totally different application) at jQConf.

OK OK I’ll get on with it. The idea is to append a <style> element into the <head> which overrides the existing CSS (in-document CSS automatically overrides linked CSS for selectors with the same specificity value). Then when something changes, you literally rip the whole style tag out, and replace it.

Appending a new style:

$("head").append("<style type='text/css'></style>");

Text variable where the CSS will be kept. Keep this text up to date when options change.

var cssText = "";

Use the replaceWith() function to rip out existing style element and apply a new one:

$("style").replaceWith("<style type='text/css'>" + cssText + "</style>");

The ripping-out part is important. Originally I tried putting an ID on the style element and replacing the content within it on the fly. It did replace the content, but those changes were not reflected on the page. Apparently in order to force the browser to re-render with the new CSS, you have to literally remove it and put it back.

Take it, shake it

I’ll provide the source for the thing in case you want to run it locally for whatever reason. Or even better, because you want to make it cooler. If you do, please share.

View Demo   Download Files

May 13th, 2010

ASP.NET for PHP Developers – Part II

In part one of the “ASP.NET for PHP Developers” tutorial, we learned the basics of ASP.NET and the C# language. Part
two builds on that foundation, and introduces some more advanced features and techniques to take your ASP.NET
pages to the next level.

Tutorial Details

  • Technology: ASP.NET (C#)
  • Difficulty: Advanced
  • Estimated Completion Time: 1 hour
  • Part: 2 of 2

Before you Start…

Ensure you have read and completed the examples in part 1 of the tutorial. We’ll be building on that application here.
It’s also worth stressing that you need a good grasp of object oriented programming (OOP) to continue.

And Before I Start…

I mentioned in part 1 of the tutorial that there are two flavours of ASP.NET available:

  • ASP.NET WebForms: the original framework allowing developers to create web applications using many of the same techniques used in .NET Windows desktop applications
  • ASP.NET MVC: a newer framework offering Model-View-Controller architecture and more control over client-side code

However I don’t use either of those, but rather a third approach of my own devising. That’s for several reasons:

  1. When I started writing serious ASP.NET applications I retained my high standards of HTML output learned when writing PHP. If the page didn’t validate I felt dirty. There are a lot of developers who feel the same. ASP.NET WebForms gave, at the time, awful markup for many of the standard controls, so I had to come up with another solution. Adding runat="server" to HTML elements offered many of the advantages of true ASP.NET controls, but gave me full control over the HTML that was outputted. Things improved, and are looking even better for ASP.NET 4.0.
  2. I saw lots of examples of ASP.NET code where it was obvious the developer didn’t care about the resulting HTML. Perhaps they were Windows desktop application developers making the jump to the web, maybe they had never hand-coded HTML. Whatever the reason, I determined I would not be one of them.
  3. Quite a few of the standard ASP.NET controls relied entirely on JavaScript which is, to be frank, unforgivable for public websites (in the UK web accessibility is a legal requirement). For example, the evil javascript:__doPostBack function is a perfect way to make your website impossible to use for a large proportion of the web audience – oh, and search engines as well.
  4. I wanted to use my own choice of JavaScript library (initially Prototype, but then jQuery, now officially supported by ASP.NET). If I had to use the ASP.NET framework JavaScript library it would have made that more difficult.
  5. So why not ASP.NET MVC? Well, it wasn’t around when I started writing ASP.NET applications, and even if it was it would have been another hurdle to jump to get anything to work. Learning the .Net framework and C# language was challenging enough!

So you can see why I chose this "roll-your-own" approach. As ASP.NET matured and I discovered new features, I started to integrate those into my applications, and I fully expect that over time I’ll be doing more of that.

So, let’s take our ASP.NET application to the next level.

Master Pages

My second favourite feature of ASP.NET (after turning HTML controls into server controls) is master pages. A master page is a template file you can use to encapsulate HTML you use in multiple pages. For example, your master page could contain the header, menu and footer of your pages, while your normal .aspx pages contain the actual content on that page. let’s look at an example web page:

A sample web page

You can see the parts which are used on multiple pages highlighted in green. The content which changes for each page in the site is highlighted in red. Master pages allow us to split up the code for these two sections into multiple files. If you’ve used templates in your PHP applications (for example WordPress has header.php, footer.php and sidebar.php) you’ll see how great master pages are.

Creating a master page

So let’s create a master page. In the Solution view create a new directory in your ASP.NET application called "Master_Pages". In that directory create a new master page by right-clicking on the Master_Pages folder, selecting "Add > New file" then selecting "Master Page with Code Behind" and call it "DefaultMaster". Your new master page will be created and you’ll see the "DefaultMaster.master", "DefaultMaster.master.cs" and "DefaultMaster.master.designer.cs" files in the Master_Pages folder.

A new master page in MonoDevelop

Open the "DefaultMaster.master" and "DefaultMaster.master.cs" files. The code-behind file (.cs) for the master page (.master) works exactly the same as the code-behind file for an .aspx page. The first thing to note is master pages do not inherit from System.Web.UI.Page like .aspx pages do. Instead they inherit from System.Web.UI.MasterPage. Here’s the default code for the code-behind.

using System; using System.Web; using System.Web.UI; namespace WebApplication1 { public partial class DefaultMaster : System.Web.UI.MasterPage { } }

And for the .master file itself:

<%@ Master Language="C#" Inherits="WebApplication1.DefaultMaster" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>DefaultMaster</title> </head> <body> <div id="container"> <form runat="server"> <asp:contentplaceholder id="contentPlaceHolder" runat="server" /> </form> </div> </body> </html>

Because we’re not using the WebForms model, let’s quickly remove the tags for the <form runat="server"> element.

You should be getting used to page declarations (the <%@ Page ... %> bit in .aspx pages) by now, so the <%@ Master ... %> declaration will come as no surprise. What is different in this code is a new control: <asp:contentplaceholder>.

<asp:contentplaceholder id="contentPlaceHolder" runat="server" />

This content placeholder is where the content from your .aspx pages will be inserted. You can have as many of these in a .master page as you like.

Referencing your master page

Let’s go back to our normal .aspx page and make some edits. The first thing to do is remove the <html>, <head> and <body> tags, as they will now be in the master page. That leaves:

<%@ Page Language="C#" Inherits="WebApplication1.Default" %>

<h1 id="headertext" runat="server">This is the text</h1>

Now we need to specify what content to place in the content placeholder. We do that by specifying where the master page is, and wrapping our content in an asp:Content control, like this:

<%@ Page Language="C#" MasterPageFile="~/Master_Pages/DefaultMaster.master" Inherits="WebApplication1.Default" %> <asp:Content id="Content1" ContentPlaceHolderID="contentPlaceHolder" runat="server"> <h1 id="headertext" runat="server">This is the text</h1> </asp:Content>

There’s a couple of things to note here. Firstly the Page declaration has an additional attribute of "MasterPageFile" with a value of "~/Master_Pages/DefaultMaster.master". In ASP.NET "~" means the root of the application, the rest of that path just points to our master page.

Secondly you see the new asp:Content control has an attribute of "ContentPlaceHolderID" with a value of "contentPlaceHolder", which is the "id" attribute of our <asp:contentplaceholder>. Running the application will give you:

An ASP.NET master page and content page working together

Checking the source code of the page proves that the master page (.master) and content page (.aspx) have been seamlessly integrated together. Now you see why I love master pages so much.

A more complex master page

We can push master pages a lot further than this simple example. Let’s have a go at building something that looks more like a real web application, starting with the master page. Firstly we’ll add some more content placeholders and a few server-side controls:

<%@ Master Language="C#" Inherits="WebApplication1.DefaultMaster" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title><asp:contentplaceholder id="PageTitle" runat="server" /></title>

<script src="scripts/jquery.min.js"></script> <asp:contentplaceholder id="PageJS" runat="server" />

<link rel="stylesheet" href="styles/default.css"></link> <asp:contentplaceholder id="PageCSS" runat="server" /> </head> <body> <div id="container">

<h1 id="sitename" runat="server"></h1>

<ul id="menu"> <li><a href="about.aspx">About me</a></li> <li><a href="services.aspx">My services</a></li> <li><a href="contact.aspx">Contact me</a></li> </ul>

<div id="content"> <asp:contentplaceholder id="PageContent" runat="server" /> </div>

<div id="footer"> <p id="copyright" runat="server"></p> </div>

</div> </body> </html>

And in the code-behind file for our master page we’ll put:

using System; using System.Web; using System.Web.UI; using System.Configuration;

namespace WebApplication1 { public partial class DefaultMaster : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { sitename.InnerHtml = ConfigurationSettings.AppSettings["SiteName"]; copyright.InnerHtml = ConfigurationSettings.AppSettings["CopyrightNotice"] + DateTime.Now.Year.ToString(); } } }

(I’ll leave it as an exercise for you to add the SiteName and CopyrightNotice applications settings to web.config.)

Now for our content page. We have four content placeholders we can use: PageTitle, PageJS, PageCSS and PageContent. Here’s the code for the .aspx content page:

<%@ Page Language="C#" MasterPageFile="~/Master_Pages/DefaultMaster.master" Inherits="WebApplication1.Default" %>

<asp:Content id="PageTitle" ContentPlaceHolderID="PageTitle" runat="server"> <asp:Literal id="Title" runat="server"></asp:Literal> </asp:Content>

<asp:Content id="PageCSS" ContentPlaceHolderID="PageCSS" runat="server"> <style type="text/css"> h1 { font-family: sans-serif; color: #090; } </style> </asp:Content>

<asp:Content id="PageContent" ContentPlaceHolderID="PageContent" runat="server">

<h2>Welcome, one and all</h2> <p>This is my very first ASP.NET website, working with a master page!</p>

</asp:Content>

And the code-behind for our .aspx content page:

using System; using System.Web; using System.Web.UI; using System.Configuration;

namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Title.Text = "Welcome to my first ASP.NET Website"; } } }

A couple of new things to notice here. Firstly I haven’t used the PageJS content placeholder at all – it’s quite OK to leave it out entirely (of course nothing will be rendered to the page for that area). Secondly I’ve introduced another ASP.NET control, namely <asp:Literal>, which we’ll take a quick look at now.

The Literal control

The Literal control is very useful when you want to render something to the page without any extra markup. For example, a lot of the time it’s fine to use:

<span id="message" runat="server"></span>

message.InnerHtml = "This is the message"

Gives:

<span id="message">This is the message</span>

But if you don’t want the span tags at all, for example for the page <title>, you need the Literal control. Setting the "Text" property of the Literal control renders just that text to the page:

<asp:Literal id="message" runat="server"></asp:Literal>

message.Text = "This is the message";

Gives:

This is the message

The completed master and content page

So running our application should give us this:

An ASP.NET master page and content page with multiple content placeholders

This is really just scratching the surface, as it’s possible to have multiple master pages (even nested master pages!). You can also set the master page programatically (but this needs to be done in the Page_Init event, as Page_Load is too late in the page lifecycle). There’s lots more detail about MasterPages on the MSDN site.

Custom Classes

It’s possible to create custom classes in your application, just like you would in PHP. Let’s create a security class by right-clicking the root of your application and selecting "Add > New file" then choosing "Empty class" from the "General" section and calling it "Security".

An new empty class

The code for your new class looks like this:

using System; namespace WebApplication1 { public class Security { public Security() { } } }

I’ll throw a bit more code into this file:

using System; using System.Web; namespace WebApplication1 { public class Security { public bool IsLoggedIn; public Security() { CheckSession(); } private void CheckSession() { if (HttpContext.Current.Session["loggedin"] != null && HttpContext.Current.Session["loggedin"] == "true") { IsLoggedIn = true; } else { IsLoggedIn = false; } } } }

Pretty simple so far. The only new thing is the use of HttpContext.Current.Session rather than just Session, that’s because HttpContext.Current is implicit in an .aspx web page, but not in a standalone class.

In our Default.aspx.cs code-behind file we write:

protected void Page_Load(object sender, EventArgs e) { Security security = new Security(); if (security.IsLoggedIn) { Title.Text = "Welcome back, you are logged in"; } else { Title.Text = "You are not logged in"; } }

Which instantiates a new instance of the Security class names "security". Running the application shows this:

Not logged in

As you’re familiar with OOP you can see how this can be used to build large-scale web applications. The only other thing to say about custom classes is how to make them static. Here’s the code for a static class:

using System; using System.Web; namespace WebApplication1 { public static class Security { public static bool IsLoggedIn; public static void CheckSession() { if (HttpContext.Current.Session["loggedin"] != null && HttpContext.Current.Session["loggedin"] == "true") { IsLoggedIn = true; } else { IsLoggedIn = false; } } } }

You can see there’s no default method, as this class is never instantiated. I’ve also added the "static" keyword to the property and method, and I’ve made the CheckSession() method public. To use this static class we would write:

protected void Page_Load(object sender, EventArgs e) { Security.CheckSession(); if (Security.IsLoggedIn) { Title.Text = "Welcome back, you are logged in"; } else { Title.Text = "You are not logged in"; } }

Pretty simple, really. As you’re fully aware of the advantages that OOP can give you for abstraction, encapsulation and inheritance you’ll see how powerful this is. But if we’re going to use objects, we really need some serious data to model in our objects. We need a database.

Databases, Data Sources and Data Binding

ASP.NET works really well with databases, but works the best with Microsoft SQL Server (not surprisingly). Even if your ASP.NET application is running on a Linux box, you can still connect to SQL Server on a Windows server to use as a datastore. I’ll demonstrate that below, but as I’m writing this tutorial in Linux I will also demonstrate the use of MySQL as an ASP.NET database. To use MySQL you’ll need the ADO.NET driver for MySQLthis excellent article helped me a lot.

Database configuration

The first thing to do is configure how to connect to our database server. You can do this in web.config, add this code inside the "configuration" section (the MySQL and SQL Server code should be pretty obvious). Note that these are standard connection strings.

<connectionStrings> <add name="MySQL" connectionString="Server=mysqlserver;Database=aspnetdb1;User ID=root;Password=mypassword;Pooling=false"/> <add name="SQLServer" connectionString="Server=sqlserver;Database=aspnetdb1;User ID=sa;Password=myPassword;"/> </connectionStrings>

I’ve also created a table called "users" with this code (this is for MySQL, minor edits will make it work in most other database systems):

CREATE TABLE users ( id int  NOT NULL AUTO_INCREMENT, username varchar(50)  NOT NULL, password varchar(32)  NOT NULL, email varchar(255)  NOT NULL, PRIMARY KEY (id) );

To access your connection string you can use the ConfigurationManager class which we used in part 1 of the tutorial to access global configuration settings. Here’s the code:

string conn = ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString;

Connecting and running a simple query

So we’re now ready to connect to our database and run a query. First, insert a couple of rows into the " users" table so we have something to query:

insert into users (username, password, email) values ('User 1', 'user1password', 'user1@asp.net')

We then need to ensure we reference the right assemblies. For MySQL make sure you have this at the top of your code-behind file:

using System.Data; using MySql.Data.MySqlClient;

Amd for SQL Server use this:

using System.Data; using System.Data.SqlClient;

A quick note about connecting to MySQL in Linux. I had a bit of trouble making my application compile when I first tried this. I did various searches but found no answer that worked for me. The error I got was "The type or namespace name `MySqlConnection’ could not be found." which looked like the MySQL Connector wasn’t installed properly. The fix (for me) was to manually add the reference by right-clicking the References folder in my application and going to "Edit references". I then found the MySQL.Data.dll file in the .Net Assembly tab and referenced it. I also had to then manually reference the System.Data and System.Configuration assemblies from the Packages tab.

MonoDevelop references

Hopefully you won’t need to jump through these hoops.

We now open a connection to our database like this for MySQL:

protected void Page_Load(object sender, EventArgs e) { // get the connection string string conn = ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString; // create a new MySQL connection MySqlConnection dbcon; using (dbcon = new MySqlConnection(conn)) { // open the connection dbcon.Open(); // create the query string query = "SELECT username, email FROM users"; // create a new adapter between the connection and query MySqlDataAdapter adapter = new MySqlDataAdapter(query, dbcon); // create a new dataset to store the query results DataSet ds = new DataSet(); // fill the dataset with the results from the adapter, // the name of the dataset is "result" adapter.Fill(ds, "result");

} }

And this for SQL Server:

protected void Page_Load(object sender, EventArgs e) { // get the connection string string conn = ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString; // create a new SQL Server connection SqlConnection dbcon; using (dbcon = new SqlConnection(conn)) { // open the connection dbcon.Open(); // create the query string query = "SELECT username, email FROM users"; // create a new adapter between the connection and query SqlDataAdapter adapter = new SqlDataAdapter(query, dbcon); // create a new dataset to store the query results DataSet ds = new DataSet(); // fill the dataset with the results from the adapter, // the name of the dataset is "result" adapter.Fill(ds, "result");

} }

See, pretty easy, and not a million miles away from the equivalent PHP code. There are a couple of bits in here I’ll explain in some more depth. Firstly the using statement:

using (something here) { ... }

The object you set up in the brackets is automatically destroyed when your code leaves the end curly brace "}". This is a really useful structure to know about, so read all about it here.

Secondly the DataSet. In the code above the results from the database query are fed into a DataSet, which is an object containing one or more tables, each table containing rows and columns. That means you can do useful things like:

DataSet ds = new DataSet(); // we put some data from the database in the DataSet here... // get the number of tables int tables = ds.Tables.Count; // get the first table DataTable dt = ds.Tables[0]; // get the number of rows in the first table int rows = ds.Tables[0].Rows.Count;

And there are many other goodies in the DataSet class. You can also loop rows, just like you do in PHP, like this:

for (int x = 0; x < ds.Tables[0].Rows.Count; x++) { Response.Write(ds.Tables[0].Rows[x]["fieldname"].ToString() + <br />); }

But there’s a much better way to display simple loops, and that’s using the Repeater control.

Using repeaters and databinding

First a confession. There are large ASP.NET applications I’ve written that use no ASP.NET controls except the Literal (which we looked at above) and the Repeater. The Repeater control allows you to "bind" data, for example from a DataSet, and display it in a looped manner. Firstly we need to add something to our database code above:

protected void Page_Load(object sender, EventArgs e) { // get the connection string string conn = ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString; // create a new MySQL connection MySqlConnection dbcon; using (dbcon = new MySqlConnection(conn)) { // open the connection dbcon.Open(); // create the query string query = "SELECT username, email FROM users"; // create a new adapter between the connection and query MySqlDataAdapter adapter = new MySqlDataAdapter(query, dbcon); // create a new dataset to store the query results DataSet ds = new DataSet(); // fill the dataset with the results from the adapter, // the name of the dataset is "result" adapter.Fill(ds, "result");

// below is the new code...

// set the DataSource of the repeater myRepeater.DataSource = ds; // bind the data myRepeater.DataBind();

} }

And in the .aspx page we put:

<asp:Repeater id="myRepeater" runat="server"> <HeaderTemplate> <table> <tr> <th>Username</th> <th>Email</th> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td><%# Eval("username") %></td> <td><%# Eval("email") %></td> </tr> </ItemTemplate> <AlternatingItemTemplate> <tr class="alt"> <td><%# Eval("username") %></td> <td><%# Eval("email") %></td> </tr> </AlternatingItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater>

You can see what happens here. When the data is bound to the Repeater control the HeaderTemplate section is displayed. Then each row is displayed in the ItemTemplate and AlternatingItemTemplate sections (the names should give you a clue how they are displayed). Then finally the FooterTemplate section is displayed. Using this simple control gives you an easy way to display repeating data, with complete control over the resulting HTML – just like you would do in PHP. Here’s the results (with some CSS for styling):

A simple example of a Repeater control

As a Repeater will throw an Exception if an empty DataSet is bound to it, you need to check there is data to be bound first. A simple if statement will work, checking if there are tables in the DataSet and if the first table has rows:

if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { myRepeater.DataSource = ds; myRepeater.DataBind(); }

I think you’ll agree that having a control which sets templating for repeating data as easily as that is a massive help to the developer. One thing to note with the Repeater control – if you bind a DataSet to it by default the first table is used. If you’re using stored procedures instead of inline SQL to run commands against your database you can return multiple tables, meaning you can load several sets of data for use in a page at once. In that case you’d use code like this (to bind the second table in the DataSet to the Repeater):

myRepeater.DataSource = ds.Tables[1]; myRepeater.DataBind();

Creating a data access class

Let’s pull the last couple of sections together and create a data access class that will simplify connecting to and running commands on your database. This code is for MySQL, but as you’ve seen the code for SQL Server is very similar. Create a new empty class called "DB" and paste this into the new file:

using System; using System.Configuration; using System.Data; using MySql.Data.MySqlClient;

namespace WebApplication1 { public class DB { private string ConnectionString; public DB() { // get the connection string this.ConnectionString = ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString; } public DataSet Select(string query) { MySqlConnection dbcon; using (dbcon = new MySqlConnection(this.ConnectionString)) { // open the connection dbcon.Open(); // create a new adapter between the connection and query MySqlDataAdapter adapter = new MySqlDataAdapter(query, dbcon); // create a new dataset to store the query results DataSet ds = new DataSet(); // fill the dataset with the results from the adapter, adapter.Fill(ds, "result"); // return the dataset return ds; } } public bool Execute(string query) { MySqlConnection dbcon; using (dbcon = new MySqlConnection(this.ConnectionString)) { // create a new SQL command on thie connection MySqlCommand command = new MySqlCommand(query, dbcon); // open the connection dbcon.Open(); // execute the query and return the number of affected rows int affectedrows = command.ExecuteNonQuery(); // there were no rows affected - the command failed if (affectedrows == 0) { return false; // the command affected at least one row } else { return true; } } } } } 

To use this in your code-behind file you’d put:

DB db = new DB(); DataSet ds = db.Select("SELECT username, email FROM users"); if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { myRepeater.DataSource = ds; myRepeater.DataBind(); }

This data access class introduces you to a new style of database connection syntax using the MySqlCommand class (SqlCommand for SQL Server) and the ExecuteNonQuery method. As the code says, the ExecuteNonQuery method executes a query and returns the number of affected rows. Very useful for INSERT, UPDATE and DELETE commands.

Those of you with a good knowledge of WordPress will see how this class is similar to the $wpdb global class in WP which offers methods like $wpdb->get_results("select * from table"); and $wpdb->query("delete * from table");. It would be easy for you to extend this data access class to have more useful properties and methods for your applications.

User Controls

So far we’ve used just two ASP.NET controls – Literal and Repeater – in honour of our aim to keep full control of the output HTML. But sometimes it’s useful to encapsulate functionality for your own controls. ASP.NET allows you to create user controls with properties and methods all your own. These user controls can be thought of as discrete blocks of HTML that can be used inside a .aspx page, just like you’d include a separate file in a .php file.

We’re going to create a very simple control that displays a truncated link. Firstly add a new file of type "User control with code-behind file" and call it "ShortLink".

Adding a new user control

You may notice the new file has an extension of .ascx, this is the extension for user controls. Open the .ascx file and you’ll see this:

<%@ Control Language="C#" Inherits="WebApplication1.ShortLink" %>

Open the code-behind file (MyControl.ascx.cs) and you’ll see this:

using System; using System.Web; using System.Web.UI;

namespace WebApplication1 { public partial class MyControl : System.Web.UI.UserControl { } }

Continue Learning…

May 10th, 2010

90+ Fresh Posts for Designers and Developers


Fresh Posts for Designers and Developers

This post is a collection of latest community news submitted on tripwire magazine by readers and other blog owners.  Most new posts in the web design and development community is included making this regular post a really fast and easy consumable overview of what is going on just now.  You can find more community news here

Create an Wooden Background Website Layout in Photoshop

In this post we will show you how to create a website using splatter brush and few cool techniques. You can customize it for a company or own web site.

10 Firefox Addons Every Web Designer Should Know

If you are web designer you absolutely use firefox because of Firefox has some cool add-ons which make the job of website designers much easier and fast.

31 Stunning Black And White Photographs

The world of photograhy is a world of passion which touches many hearts. This compilation consists of black and white pictures divided into categories.

50+ Free Fonts Collection for Web Designers and Logo Artists

Fonts should speak itself about the product. So in this article you can find some excellent font collection for logo and web designing.

How to Convert a WordPress Blog into WordPress MU

WordPress is one of the best and very popular blogging platforms which is not only free but also released as a open source project.

10 Tips For Becoming A More Efficient Web Designer

This article provides ten tips and techniques that you can use to become a more efficient and productive web designer.

Free Social Network Icons from IconShock

IconShock has designed Social Network icon-set exclusively for Smashing Share readers. The IconShock – icon sets are awesome and free to use for both your personal and commercial projects.

Learn how to create a clean busines layout

Learn how to create a clean business layout with this step by step tutorial.

50 Inspiring Sites Using Red As Their Main Color

I like the red colour a lot (makes me think of Dracula). And we already know that the web is full of great examples of web designs (using red or not) to get some inspiration from [..]

Design Envy : Make it Work For You!

It’s natural, it happens to the best of us. And it is certainly nothing to be ashamed of.

Whats the Best way to Promote your Latest Article?

There are several ways in which to achieve this, and I hope to discuss two of the easiest and simple in which to setup and carry out.

21 Wonderful Logos for your Daily Dose of Inspiration

The probably most important thing of a Brand is the Logo, It gives the Costumer/viewer a Images to the Brand Name. Even Business owners now how important the logo is for their Brand….

How to Find the Best Keywords and Ideas for Your Articles

Today, in this article we will show you how to find best SEO keywords the easy way. The next 5 tools are in the top of my keywords generators.

How to Create Perfect Radial Shapes in Illustrator

In this tutorial, It will walk you through the creation process on how to effectively recreate some perfect radial shapes.

How To Create A Retro Style Text Effect Using Illustrator

In this tutorial It explains how to easily create a 3d text and merge it into a retro-style scene. We will use Illustrator for the text,

Ten Dirty Secrets of Web Hosting Services

When looking for a web hosting service, you should be careful as there are a lot of things they may try to hide from you.

Proportion: Definition and Gallery

Proportion (or scale) refers to the relative size and scale of the various elements in a design. In essence, this takes design elements and contrasts their sizes greatly for emphasis.

Eight Greatest Things About Open Source

Linux Environment: This is a given, granted, but no one can exclude the brainchild of Linus Torvalds when talking about open source. What was begun as a learning experience…

What You Should NEVER do With Your Web Hosting Account

t should go without saying that one of the biggest data protection “faux-pas” is keeping your critical data backups on-site after they’ve been copied. In the event of theft, flooding..

50+ Creative Business Card Designs

Do you need the creative Business for your Business? We assembled Fresh collection stimulate your creative juices for your own beautiful business.

50+ Unique and Inspiring Blue Logo Designs

This 50+ Unique and Inspiring Blue Logo Designs are especially compiled for logo designers who are momentarily out of ideas.

The Guide To Landing A Graphic Design Job

The first question in this new series tackles the dilemma of finding a job as a Graphic Designer without much actual design experience.

35 Ultimate Useful Android Applications

Andriod (Google mobile operating system) market is growing day by day as this OS giving lot of user friendly applications, some of those listing today as our visitors and readers demand. Android on..

Golden Fish – Free Illustration

If your website is about pets or fishes, feel free to download this illustration. Not only it’s well done but also free to use.

Codeigniter shopping cart v1.1 Part 15: contact page and sending email message

Contact page allows visitors to send a message through a form. It has a reCaptcha in order to avoid spam. I will cover the contact page and sending email message to an administrator in this article.

Quote Portal for iPhone is The Epitome of Simplicity and Brilliance

Quote Portal has one of the nicest interfaces I have ever seen on an iPhone app. The concept is completely basic, yet the UI is so good, it transforms this app into a keeper. So what does the app do?

Coffee Shop Posters: 17 Creative Design Examples

Coffee shop posters can set the mood, provoke discussion, wake creativity, and express the shop’s unique identity and style.

Photography By Warwick Saint

Warwick Saint was born in South Africa in 1972. With a Creative dad and a Model mom, it was not surprising Warwick Saint was to become a photographer.

Over 500 Beautiful Frames

Here are over 500 Beautiful Frames for you. These frames can be used for making different Wish cards. All Frames are Zipped in a file, some of these are inserted directly so you can view these.

3 Best Solutions to make your own custom Linux

Linux is fun so much fun. It gives you awesome multidimensional opportunities to experiment. Its not just bunch of distros with colorful desktop environments.

15 Gothic Fonts for Designers

This is the seventh post of our awesome fonts series. Last time we posted a collection of free grunge fonts now in this post you will find 15 Gothic Fonts for Designers.

Over 800 Beautiful Backgrounds

I’ve collected a large number of Beautiful Backgrounds. You can use these backgrounds as your Website Bg. All backgrounds are present in a ZIP file, preview also available.

22 Fresh Web Design Tutorials using Photoshop for 2010

I have compiled a list of 22 of the latest web design tutorials released in 2010.

Top 3 Internal link building Tactics

Internal link building plays a crucial role in ensuring that all the relevant pages of your website gets crawled by the search engines.

Showcase Of Web Design In Ukraine

Here is a showcase of web design agencies and the latest trends in web design of Ukraine.

continue reading…

May 10th, 2010

Web Design, Web Development and Graphic Design Resources


Our sponsors Pixmac.com, are offering the chance to five of our readers to win a $199 subscription each to there marvelous microstock photo site service.

That is a huge prize fund of $995 to be shared amongst the winners!
Don’t miss this great opportunity, enter now!

Royalty free stock photos

How to Enter

For a chance to win this great prize all you have to do is state your Pixmac Nickname in the comments section below and describe how you are or are planning to use the images.

If you haven’t signed up to Pixmac as yet, and you want to enter this competition you will firstly need to signup, its free and you can do it here: Pixmac Registration.

And then come back here and submit your comment.
So, these are the simple steps to follow:

Comment + Nickname + Image Usage = Potential $199 Subscription Winner.

The winner will be chosen at random
The competition will run for the next 30 days and the eventual winners will be notified by email.

Good luck to everyone!

About Pixmac

Royalty free stock photosPixmac.com is the leader in microstock photo site services, with a monumentally huge 10 million+ stock photos and resources at there disposal, it is by far the leader in there field.

You can find almost any image you could dream of at Pixmac, from Valentine’s Day and spring photos to Easter stock photos. They also have classic royalty free pictures of business, people, animals or nature which can suit any of your advertising or professional presentation needs, as well as huge celebrity collections, Dreamstime images, Fotolia images, Corbis images and Image Source collections.

With its one stop shopping it takes less than three minutes to download an image and local payment methods are accepted.
What more could you want from a stock image service?
You can also follow them on Twitter and Facebook.

Top 20 Free Fonts for Distinctive Headlines and Titles

Posted: 24 Feb 2010 02:28 AM PST

Whether you are reading a printed magazine or a web article it is very rarely the content that draws you in at first, the hook is always the title or the headline. A well written and thought out title or headline are fundamental, it has to not only describe with very few words the articles content but also has to be formatted in a way that it draws the attention of your readers and is a seemingly must read – a difficult combination to achieve.

There are many ways of of making your headlines that little bit more distinctive, none are as important as choosing the correct font. Most fonts can be big and bold, but finding one with a little bit of character that helps emphasize and describe the title and the content can be difficult.

With that in mind, Peter Olexa from Fonts2u has put together this article of his top 20 beautiful, professional and distinctive free fonts you shouldn’t be missing from your font library.

01 Diavolo

Free Fonts for Logos
Free Fonts for Logos

02 Fertigo

Free Fonts for Logos
Free Fonts for Logos

03 Museo

Free Fonts for Logos
Free Fonts for Logos

04 Comfortaa

Free Fonts for Logos
Free Fonts for Logos

05 Raspoutine Demi Bold

Free Fonts for Logos
Free Fonts for Logos

06 Gauntlet Classic

Free Fonts for Logos
Free Fonts for Logos

07 DuePuntoZero

Free Fonts for Logos
Free Fonts for Logos

continue reading…

May 10th, 2010

Best Practices for Hints and Validation in Web Forms


Our instinctive dislike for forms originates from having to fill out seemingly endless paper forms, many of which require a Master’s degree in Form Content Filling to understand and fill out correctly the first time.

Unfortunately, in the offline world, getting some answer wrong would mean having to fill out the form in full and sending it again, usually days apart.

Best Practices for Hints and Validation in Web Forms

Online, we have the opportunity to not only resubmit forms countless times, but also as web developers, we can provide people with much more relevant feedback at various stages of using a web form.

Through hints and validation, we can create forms that are a lot more user-friendly than their offline counterparts. And in some cases, we can make forms that people might even enjoy filling out.

Hints in Web Forms

Validation is frequently used to provide users with a response on what information they should have entered when an error occurs.

By using a number of helpful hints, we can provide much of this information before they even enter their name. By showing more information before a user submits a form, we can reduce the chance of an error happening.

Information available prior to submission can come in three forms:

Labels: These should quickly describe what information should be entered into an input field—this could be their username, password, email, etc.

Required or optional information: an input field should be denoted as required or optional, usually by an asterisk (*) or any cues or text-based hints that tell the form user they can’t leave a field blank.

Help hints: Help hints function to give the user additional tips on how to format their information. For example, a help hint might tell a user what the password requirements are (as shown below).

http://bc-partners.net/contact/

Alignment of Labels

Of course, all information should be placed in such a way that it is clearly associated to a given input field, but the alignment of a label can actually affect not only a successful submission, but also the speed of completion.

The alignment of a label is typically either left, right or top; there are benefits and disadvantages to each alignment:

Top labels: Positioning a label at the top of input fields improves the association between the label and field, but does tend to give the impression of a longer form.

Right labels: Labels at the right of the input fields reduces the vertical space of the web form, and improves the association between the label and input. However, right labels can reduce the readability and scanability of web forms.

Left labels: Labels at the left of form fields can make for easier reading of the labels, and also makes the web form vertically shorter. However, it tends to affect the association of labels to inputs.

Alignment of Labels

Choosing the alignment of labels in a form can depend on the type of web form you are creating, the available space you have for your web form and which of the disadvantages are of greater concern to you in the given situation.

Labels inside Inputs

Some forms will use placeholders to indicate suitable examples of information within an input field, but in some instances, when screen real estate is at a premium, developers will use labels within the input fields.

This doesn’t pose too many issues on shorter forms, but as the form grows, this becomes an issue. By using the label within the input, it means that once a user enters any data, the label disappears and cannot be referred back to when reviewing the form either before or after submission.

Labels inside Inputs

Hints within inputs should be used only where sufficient information still exists to indicate an input’s purpose or requirements after the user has entered their information and the original hint has disappeared.

Additionally, labels inside input fields can be troublesome if done incorrectly, as they often rely on client-side scripting such as JavaScript.

One potential solution to the downsides of labels within inputs is using the sliding labels technique—proposed by CSSKarma—where the labels move to the side and remains visible when the user focuses and enters text into the fields. However, this technique still doesn’t solve space limitations.

Dynamic Hints

If space is at a premium or your form looks too cluttered with hints beside each input field, then you can make them dynamic. A hint can appear as a tooltip based on user action either when the user focuses on the input field or when the user hovers over a help icon placed near the input field.

Using dynamic hints allows for more descriptive information to be communicated as the character limit isn’t restricted by the available space around the input field.

Dynamic Hints

Data Validation in Web Forms

Given sufficient and correct use of hints, it may be possible that the majority of users will never see any validation, but this does not mean validation is not vitally important.

Validation provides a safety net for many users as well as a system to ensure the website is gathering the correct information required.

The structure on which the web is constructed allows us two methods by which we can validate a user input:

Server-side Validation

When using server-side validation, any information entered by the user is sent to the server to be checked rather than anything happening locally on an individual’s own computer. With the exception of using Ajax server-side form validation, this is a slower form of validation as it requires the user to first submit the form and then wait for the server to validate the data before reloading the page in order to provide a response.

However, what you lose in speed, you gain in security, as this process is not easily bypassed like client-side validation.

Client-side Validation

Although HTML5 will change the way we undertake client-side validation, JavaScript is commonly the language used for client-side validation today. Because users can disable JavaScript in their browser, a website cannot rely solely on JavaScript as a method of validation.

Instead, client-side validation should be seen as an extra layer on top of server-side validation.

Real-time Validation

Real-time validation is one of these server-side validation disadvantages that client-side validation allows us to solve. Although client-side validation can be activated via a submit button too, there is also the opportunity to use real-time validation as users enter data into the form.

Real-time validation is where JavaScript can be used to provide an instant response to a user action. So rather than having to fill out the entire form and pressing submit, the user gets an instant response as they are typing so that they can make immediate corrections if necessary.

One example of real-time validation would be a password strength indicator where each key stroke triggers the validation and sends a response to indicate to a user how weak or strong that website thinks the password they have chosen is.

http://gowalla.com/join

The Good, the Bad and the Ugly of Web Form Validation

Validation isn’t all bed of roses.

The Good

Just why do we use validation exactly? It’s not exactly the easiest thing to code, especially if you duplicate the work by using client-side and server-side web form validation.

For users: Of course, it’s pretty obvious that we do validation for our users. By using validation correctly, we create a user-friendly form that makes the process as easy and quick as possible.

For obtaining correct information: It might create a usable experience for users but it also ensures the website receives the correct information it requires and in the format necessary to store it in a database for future use.

For spam protection: By validating for specific information, we can cut out some of the spam that a form may otherwise receive. However, keep in mind that any validation we put in place for spam should never affect the user experience. Remember that users are unconcerned with the level of spam you may receive.

The Bad

Validation isn’t all good though, as developers and clients alike have been known to abuse forms, forgetting the original purpose of the form and creating something that isn’t all too user-friendly:

Unusual required fields: Rather than creating a form with only the information a user truly needs to continue, we enter optional fields. Sometimes these are useful for the user, such as extra address fields or additional information text areas. In other cases they might help site owners gather such information as "Where did you hear about us?"

When these traditionally optional fields are required by the validation, they create a barrier for completion and causes the user to wonder why such information is requested of them.

Restrictive formats: Where possible, we will ensure users enter information in the format we expect. But at times, validation goes too far and constricts the user to a given format that causes validation errors where they shouldn’t exist. This usually forces a user to jump through hoops to meet the specific criteria laid out to suit the system. One example would be the requirement of no spaces in a phone number. This is something that should be amended by the code, not the user. Another example of this is having too many requirements for the type of password you need (e.g. "Must have three numbers, a capital letter, and must be between 6-12 characters only").

The Ugly

As we all know, some malicious users on the Web are out to cause mischief by bringing down websites. When developers are a little lax with their validation, it allows some of these people the opportunity to abuse exploits like cross-site scripting (abbreviated as XSS) to break a website or gain access to areas or information they shouldn’t be accessing. It’s an unfortunate reality of the web, and something that can be addressed with validation techniques.

By protecting your site against such attacks you ensure the website is always live for you and your users and that your users’ information is always safe.

For more information on XSS, visit XSS (Cross Site Scripting) Cheat Sheet on ha.ckers.org.

Validation Responses

Simply outputting hints and validation isn’t enough. Design plays its part too, helping communicate and reinforce the messages any validation is outputting.

Many different factors help towards ensuring that a user, if they do get an error on their first attempt, can correct their submission and get the form sent in second time around.

Colour

Colour is a great design element to use in order to reinforce a message. Commonly, red would be used in the instance of an error, and green for success. The use of colour clearly indicates to a user even before they read any textual responses that result from form validation.

Colour can be used in multiple ways within a web form to highlight a particular error. As well as using colour for any validation response, you can reinforce what specific inputs have errors by using colour to alter the label, border or background of a given input field.

However, it’s best to get a balance as we’re only trying to clearly indicate errors to a user, not beat them over the head with them.

As much as colour is a useful tool to communicate a given message, it can never be used independently to convey a message for accessibility reasons. Blind, low-vision and colour-blind users will have issues in determining where errors have occurred if colour was the only method for indicating where errors have occurred.

Colour

Positioning

How you position any validation elements can also have an effect on how usable a form is, especially when it comes to longer forms:

Top of the page: This is a validation response placed at the top of the page, most frequently directly above the form. For server-side validation without Ajax, this is great for screen-reader users if done correctly, because it can be the first element they read when the page reloads.

Inline: Any validation placed in close proximity to the input where an error has occurred is considered "inline". This can work well for real-time validation and for longer web forms.

continue reading…

May 7th, 2010

Tricks

I’ve added two new buttons to all of the code snippets in the Snippets section of the site. Now a button to add directly to Snippets.app and a button to directly copy to the clipboard join the Coda and Textmate buttons.

Read on for some more details about them, and remember, you can help the Snippets section grow by submitting yours.

Snippets.app button


One-click adding to Snippets.app

Snippets.app supports a URL protocol thingy. That is, once the application installed, browsers on your system know that when a URL is entered that begins with “snippets:” (instead of like http://) that it should launch (or ask you to launch) Snippets.app and do something with that URL.

Their format is:

snippets:add?code=[ENCODED-CODE-HERE]&name=[SNIPPET-NAME]&relatedurl=[REFERENCE-URL]&author=[AUTHOR-NAME]

You’ll only see this once if you check the box.

Since all my code snippets are in <pre> elements, this is how I add the Snippets.app button to each code block (simplified):

$("pre").each(function() { $preblock = $(this); $codeblock = $preblock.find("code"); $snippets_link = "snippet:add?code=" + encodeURIComponent($codeblock.text()) + "&name=" + $title + "&relatedurl=" + encodeURIComponent(document.location.href); $("<a class='snippet-button'>Add to Snippets.app</a>").attr("href",$snippets_link).appendTo($preblock); });

Copy to Clipboard

This button is powered by the awesome Zero Clipboard. For a while after Flash 10 came out, copying to clipboard from the web was borked as Flash 10 had some new security restrictions that blocked the previous methods (Yeah, apparently Flash is needed to have this work correctly). Zero Clipboard stepped it up and fixed it somehow.


One-click copying to clipboard

One particular challenge here was with the rollover technique I’m using to display the “tooltip” like text for each button. On the three other buttons, I do a simple thing where I append a span to the anchor link on hover, and remove it on the hover callback:

$(".snippet-button").hover(function() { $el = $(this); $el.append("<span>" + $el.text() + "</span>"); }, function() { $(this).find("span").remove(); });

The span is styled and positioned with CSS.

The problem is, Zero Clipboard works by positioning a completely transparent flash embed over top of the button. This means there is no traditional hover even fired when the mouse goes over this area. Fortunately, Zero Clipboard provides event listeners which you can have fire callback functions for you. See the last two lines:

ZeroClipboard.setMoviePath( '/path/to/ZeroClipboard.swf' );

$(".copy-clip").each(function(i) {

clip = new ZeroClipboard.Client();

$el = $(this); $parent = $el.parent();

clip.glue($el[0], $parent[0]);

txt = $el.parent().find("code").text(); clip.setText(txt);

clip.addEventListener('complete', function(client, text) { // provide some user feedback of success });

clip.addEventListener('mouseOver', copyMouseOver); clip.addEventListener('mouseOut', copyMouseOut);

});

Those two functions, copyMouseOver and copyMouseOut are used to do the same span-applying-and-removing business the other buttons use. The one tricky-dick thing left is that these functions need to know which parent element to deal with, in the case of multiple snippets on a single page. Fortunately they automatically pass the object to the function which is loaded with info about that element, including the ID, which I use to specify which code snippet button we are talking about:

function copyMouseOver(passed) { $("#copy-" + passed.id).append("<span>Copy to Clipboard</span>"); };

I wanted to make sure there was a bit of user feedback when a clip was successfully copied to the clipboard, so you’ll notice that the clip itself quickly fades down and back up after a successful copy. Somewhat subtle but I think it’s fairly satisfying.

Coda and TextMate

Not much has changed here. I covered how to add Coda buttons in a previous tutorial. David Walsh covered the TextMate button, which requires some fancy server side action.

Seem to work OK?

Give it a test and let me know… I’ve heard some musings of FAIL on Twitter but all the buttons seem to work OK for me. If you want to do a FAIL report, please attempt to be helpful and explain which button isn’t working, the browser/version/platform, and what actually happens.

Macity Mac Mac Mac

Yeah all the integrations are Mac software. Sorry about that, that’s just how I roll. If there was a PC program that supported a URL protocol thingy, I’d check it out and see what I could do about integrating it. For now, the copy to clipboard thing should be useful still.

Media Fusion

Multiple Login Forms with Highlighting

Posted: 23 Feb 2010 05:12 AM PST

This is a little specific… but I figured what the heck maybe it will be useful for someone. I recently had occasion to make multiple different login forms on a single page. With CSS we know we can apply styling to active inputs with :active. That’s useful… and we’ve covered how to do both input and label highlighting before. But now we need go one step up and highlight the current form itself.

continue reading…

May 6th, 2010

Tricks

This is an update to original Chat Room we published here on CSS-Tricks. In some ways, the technology is the same. We are going to employ PHP to talk to the server, jQuery to keep the chat rolling, and the chats themselves will be stored in .txt files just like the first version.

What is changed is the addition of some new features:

  • Usernames are unique to users currently chatting
  • You can see a “currently chatting” user list
  • There are multiple rooms for chatting

 

A Little MySQL

While the first version of this used no database at all, we are going to employ a little MySQL for this version. There is a file in the download called Setup.sql for use in building the initial database. MySQL isn’t for the chats themselves, but for two other things:

  • Keeping track of active users
  • The rooms

When someone comes in to chat, they choose a username. Using some jQuery, it makes an AJAX request to see if that username is currently in use in the database. If it is in use, you get a warning:

Otherwise, it says it’s cool:

If it is cool, and you click to join the chats, that username will be put into the database and thus further checks for it’s name will tell others that name is unavailable. Idle users are removed from the database.

Adding/Editing/Removing Rooms

The names of the chatrooms are kept in the database. To add a new chatroom, just add a new row to the database with the name of the chatroom and the filename of the text file you intend to store the chat:

Then it’s just a matter of making sure the text file is on the server in the right place with proper server-writeable file permissions (see the download for properly location).

jQuery

I’m sure you’ve noticed by now we haven’t been looking at any actual code. This is on purpose. All the code is available in the download (see below). It is not so incredibly much that it’s overwhelming, but I think it’s too much for a standard written tutorial/overview. Instead, let’s overview what it’s responsible for:

Username checking: On the homepage of the chat, when you choose your username, jQuery is there watching that text input. When you type a character (on keyup) it asks a certain PHP file (via AJAX) if that username is in use. The PHP file responds with a yes or no, and a message is appended to the screen accordingly.

Message box: When a user types into the textarea for sending a message, the jQuery watches that box and ensures the text is under a certain number of characters (set via maxlength attribute on the textarea)

Sending message: When the return/enter key is pressed in the chat box the value of it is sent for processing. PHP writes the text to the text file.

Updating the chat: Every few seconds, jQuery asks a PHP file to poll the text file to see if there are any new lines, if there are, they are displayed.

Features it doesn’t have

  • You can’t kick people out
  • It doesn’t do special characters

You wanna add that stuff in? I’d love it and I’ll update this.

Demo and Download

View Demo   Download Files

FAIR WARNING: Anonymity on the internet brings out the absolute worst in people. I want to keep a live demo for this on the site because it’s fun to play with and so you can all check it out. But I guarantee that people are going to abuse it. There will be foul words, porn, and probably even some unbelievable racism. Believe me, I’d like to knock these people down and put out a cigar in their eyeball as much as you do, but hey, whattayagonnado?

Credits

Special thanks to Kenrick Beckett who created the original code that powered this and Jason Lengstorf for looking it over and tidying some things up security-wise.

March 17th, 2010

Create a CSS3 Button That Degrades Nicely

There was a time where creating a nice looking, scalable button required heavy use of images, the sliding doors technique and even some javascript. As it stands a lot of the modern browsers support the css we would like to use to create a nice looking button. Firefox, Safari and Opera all have support for rounder corners, box shadows and text shadows. What used to take six steps and lots of extra mark-up, images and css, now only takes three steps and some simple CSS3.

One of the great perks regarding this technique is that in the event that a user doesn't have a browser that supports the CSS that we will be using, they will still see a nice beveled button – it simply won't look quite as nice.

What We are Going To Do

To create a nice button we have a few major components:

  • A nice background gradient
  • Rounder corners
  • Some nice borders to give it a 3D effect
  • A drop shadow
  • A text shadow (for a nice touch)

In the end we will have a button that looks just like this, only with out using any images behind a few pixel background gradient (and when CSS gradients are supported we can even remove that!).

screenshot

The HTML

 <p><a href="#">Example Button</a></p> <p><a href="#">Example Button</a></p> <p><a href="#">Example Button</a></p>

As you can see the HTML is very basic, we essentially just need an anchor tag and text. The paragraph is there just to be semantic.

The CSS

 .css3button a { background: url(background.gif) bottom repeat-x #9eabb3; padding: 5px 10px 5px 10px; text-align: center; font-weight: bold; color: #fff; text-decoration: none; border: 1px inset #aaa; -webkit-border-radius: 8px; width: auto; -moz-border-radius: 8px;  -khtml-border-radius: 8px;  border-radius: 8px; -moz-box-shadow: 1px 1px 1px #666;  -webkit-box-shadow: 1px 1px 1px #666;  box-shadow: 1px 1px 1px #666; text-shadow: rgba(0,0,0, .5) 0px -1px 0px;       border-top: inset 1px #ccc; border-left: inset 1px #ccc; border-bottom: solid 1px solid #000; border-right: 1px solid #666; }

.css3button a:hover  { background: #999; text-shadow: rgba(0,0,0, .5) 0px 1px 0px; } 

The CSS is a bit more complicated, but still fairly simple. We are really just adding a repeating background image, adding some rounded corners, as well as box and text shadows. The borders add a bit more depth / shading and ensures that if the CSS properties are not supported that the element still retains a beveled appearance.

background

The background image is simple gradient to give the button some depth, in this case I used the following image:

That Simple

That is how easy it is. If you want to play around with the borders you can end up with some pretty nice effects as well.

More Examples

March 8th, 2010

30 Creative Examples of Javascript Slider & Scrollers

Some days before we are using flash for buttons, gallery etc, later now JavaScript frameworks like jQuery, Mootools , Scriptallicious and Prototype replace the flash with a light weight code and we can get the same effect like flash, that gives web designers and developers a lot a space for creative thinking

But how to use them effectively in such a way it won’t distract the users attention and it should add value to the website,

Have a look at the 30 Sample Websites below, which use JavaScript Slider and Scrollers effectively, Hope you like the collection!!

1. Charlie Gentle

2. Orman Clark

3. Best Before

4. Creative People

5. Tomáš Pojeta

6. Square Factor

7. Leg Works Studio

8. Enterro da Gata

9. Intermission Design

10. Jackson & Kent

11. Volll

12. X3 Studios

13. We Bleed Design

14. Bullet PR

15. Diego Latorre

16. Dreamer Lines

Click here to see more Examples…