Archive

Posts Tagged ‘Coding’

Creating a random password with PHP

October 31, 2008 Leave a comment

I have been working on getting my domain back up and running, when I ran into the need for new functionality to automatically create a random password for a user should he or she have forgotten theirs.

The following is a partial solution to what I came up with, along with commentary on what the rest of the functionality entailed.

First confirm that the user is indeed who he or she claims to be.  Good ways of doing this are getting a full name, email address, maybe even a birthday.  Next, for my site I give the ability for a user to create their own secret question and answer to go along with it.  This affords a little more security than having canned secret questions — not much, but a little.  The secret question is presented, and when a correct answer is given, I create an email that sends the random password to their account.

Simple enough, so here is the code for the random password part of this solution:

$chars = 'abcdefghijkmnopqrstuvwxyz023456789!@#$';

srand((double)microtime() * 1000000);

$passwd = '';
for ($i = 0; $i < 10; $i++)
    $passwd .= substr($chars, (rand() % 37), 1);

You will notice that in the $chars string I omitted the characters l and 1. I did this because these two characters could be confused with one another, which is something you do not want when sending a random string to a user.

Simple enough. Enjoy.

Categories: Programming Tags: ,

Making .NET 2.0 SQL Connections Fast and Efficient

October 14, 2007 Leave a comment

Lately, while cleaning up some legacy code at my company and upgrading it from .NET 1.1 to .NET 2.0, I have run into some interesting coding habits concerning database connections and using stored procedures. I wanted to explore these different methods and detail what is good, bad, or just plain ugly about each of these methods.

To create a connection to a database, most beginning C# developers are taught to open the connection like this:

SqlConnection conn = new SqlConnection("MyConnectionString");
conn.Open();
.
.
.
conn.Close();

There is nothing wrong with this code (it will work correctly) and the connection is closed when it is done being used. That does not mean that this is the best method available.

What is often neglected (or plain forgotten about) is the keyword using available in C# that allows you to “forget” about managing the objects created within the using-block. What this means is that once a using-block is executed, Dispose() is automatically called to clean up you objects for you. Think of it as a lazy shortcut for developers who do not want to fret over closing connections or cleaning up after other objects. Using a using-block (boy does that sound funny) on the above code becomes:

using (SqlConnection conn = new SqlConnection("MyConnectionString")) {
    conn.Open();
    .
    .
    .
}

No more explicitly closing the connection in the code; the using keyword takes care of that for you. This is not what really troubles me, though. What I have been more concerned with is programmers incorrectly utilizing the using keyword in their code. The offender is explicitly closing the connections within the code. Why do they do this? Most likely because they do not really know what is going on behind the scenes.

So, everyone is using the using keyword now, and all is right with the world, right? Unfortunately, no. The using keyword gives you ease of coding, but code optimization is more important, and more often ignored.

Consider the following code:

string connString = "MyConnectionString";

using (SqlConnection conn = new SqlConnection(connString)) {
    string SQL = "SELECT * FROM table1";

    using (SqlCommand cmd = new SqlCommand(SQL, conn)) {
        conn.Open();
        .
        .
        .
    }
}

I have one problem with the above code – it is declaring variables to hold some text that is only going to be used once in this code. There is no reason for this. The strings should be built inline within the method parameter, instead of creating a variable first and then using that variable. This may simply be a matter of taste, but these are what I would call wasted variables – wasted because it is memory that does not need to be taken up in this way. In the above code, the SQL variable may only remain in memory for the length of the execution of the first using-block, but the connString variable could be taking up memory it does not need to for a much longer period of time. A better way to implement this code is as follows:

using (SqlConnection conn = new SqlConnection("MyConnectionString")) {
    using (SqlCommand cmd = new SqlCommand("SELECT * FROM table1", conn)) {
        conn.Open();
        .
        .
        .
    }
}

This eliminates the variables and frees up memory that would have been otherwise wasted. So, now we are using the using keyword correctly, and we are no longer using wasted variables. It sounds like we are headed in the right direction to make .NET 2.0 SQL connections fast and efficient. We are, but now we have what I think shows the most variation in how programmers understand the relationship between .NET code and the SQL database – and that is passing variables to stored procedures.

There are two important steps that I have seen programmers skip that are important to the efficiency and speed of a program. The first is forgetting to let the SqlCommand know that it is dealing with a stored procedure and not a text command or a table. This can be accomplished simply by adding the following code:

cmd.CommandType = CommandType.StoredProcedure;

The other step programmers sometimes skip is with defining parameters. There is a “shorthand” way of defining a parameter, and it is a nice way of condensing code (more on this in a moment) but you should always let the SqlCommand know what the variable type is. This is how a parameter is sometimes defined:

cmd.Parameters.Add("@UserId).Value = "Some Value";

As you can see, there is no type defined in the parameter, and this wastes time because now the SQL server must figure out what type it is supposed to be before executing the statement. The verbose way of defining a parameter is like this:

SqlParameter spUserId = new SqlParameter("@UserId", SqlDbType.VarChar, 15);
spUserId.Direction = ParameterDirection.Input;
spUserId.Value = "Some Value";
cmd.Parameters.Add(spUserId);

This defines everything that needs to be defined, and the parameter is ready to go, with a value to send to the SQL server and everything. This code is kind of clunky, though. It lacks style and a sense of “I know what I am doing” that shows peers how technical you really are. To remedy that, we can condense all of that code in to one nice, slick, clean line of code that says “ask me anything about this stuff, I know it.”

cmd.Parameters.Add("@UserId", SqlDbType.VarChar, 15).Value = "Some Value";

Here is a final version of the structure that I believe is the best, most efficient, and fastest way of creating a .NET 2.0 SQL connections.

using (SqlConnection conn = new SqlConnection("MyConnectionString")) {
    using (SqlCommand cmd = new SqlCommand("Some_sp", conn)) {
        conn.Open();
        cmd.Parameters.Add("@UserId", SqlDbType.VarChar, 15).Value = "Some Value";
        .
        .
        .
    }
}

With this way of creating connections, you are correctly utilizing the using statement to take care of closing connections, etc. You also do not waste any memory that could potentially be valuable to your Web server (you never know). You also let the SQL server know everything it needs to ahead of time so that it does not have to blindly figure out things on the fly. This makes your program faster and more efficient.

I am sure there are those that will disagree, but this is a good way of setting up your code to get the job done right. Don’t waste processor time with things that will be done for you, don’t waste SQL server time with figuring out things you could have told it in the beginning, and don’t explicitly create things that can be done in a slicker and leaner way.

Good luck, and happy coding!

Categories: Programming Tags: ,

Formatting <script /> elements

August 28, 2007 Leave a comment

When I first started using JavaScript in my Web pages, I would always add the tag like this:

<script type="text/javascript" src="somefile.js"></script>

After doing more and more research to improve my skills, I came across an article that said (if I recall this correctly) there was a bug in some browser with the <script> element and to correct it, you should format your <script> elements like this:

<script type="text/javascript" src="somefile.js"> </script>

The space between the opening and closing tags of the element is the only difference between the two code examples. I do not remember if this is necessary or not, but I have been adding my <script> elements like the latter example for years now, and to this day, in fact.

Does anyone know which way is correct? Does it matter? Was there ever a need to put a space between the opening and closing tags?

Categories: Internet, Programming Tags:

Including Resources in JavaScript

August 22, 2006 Leave a comment

I have my bias towards Prototype, because I like the foundation it provides for creating other classes, and the built in classes and functions it has. But I do hear an awful lot about Dojo, especially recently. So do I go with Dojo or Prototype and its children (script.aculo.us, OpenRico, Moo.fx)?

script.aculo.us has a nifty little way of including resources so that not everything need be loaded all of the time:

_src_="script.aculo.us?include=xxxx"

xxxx is a comma delimited string of the components to load.

Now Dojo follows more of a Java methodology if I understand correctly (and I will admit, I’ve never actually used it…) Something like:

dojo.require('dojo.event.*');>

They are both pretty straight forward to use…my question is, which one is better?

Categories: Internet, Programming Tags:

.NET Development

August 2, 2006 Leave a comment

Let me preface this post with the following: I have never been a fan of .NET.

My experiences with .NET started when .NET was still in beta while I was contracting at Anheuser-Busch. Another programmer, Prerit, and I decided after much deliberation that we wanted to make the application we would be working on standards compliant. That’s not too much to ask, right? We quickly discovered that using the Web Forms within Visual Studio did not produce standards-compliant source. What were we to do? The only logical thing, we abandoned the Web Forms and wrote everything from scratch. Visual Studio became somewhat of a suped-up Notepad.

And so it went, for two years of development, I never touched Web Forms. Then I left A-B and .NET, at least for a while.

Now I work for TechPhob, and I have recently been put on a C# project for a big bell. I sat in on a workshop where they were introducing us to the client’s environment, and winced (probably visibly) when I found out they would still be using Visual Studio 2003 – I had learned by then that Visual Studio 2005’s Web Forms produced standards-compliant source.

But the real shock, and I guess the point of this post, is that as I watched this workshop, I found, to my horror, that these .NET developers (client side and those working for TechPhob in California) were putting all of the style for the components directly into them. My god! No thought to the cssClass or to setting a properid on the component. These were supposed to be professional .NET developers, and they had no thought to using CSS.

Did they not see the benefits? One of the TechPhob developers had mentioned at one point of his desire to use a MVC design pattern for all new development. So he was savvy enough to recognize the usefulness of design patterns, but not of a very simple and very important one – separate presentation from structure.

So, my general question to all those professional .NET developers out there – do none of you rely on CSS for presentation, or do you just use the easy tools that Microsoft provides?