Entries Tagged 'HowTo’s' ↓

Enforce strong Passwords in ASP.NET

I’m finally back from vacation, expect some impressions of Gran Canaria in the near future. For now, here’s a little HowTo for enforcing strong passwords.

Regex is a good way to deal with password validation. If you want your users to choose strong passwords here’s how to do it:

This regular expression will enforce a password to be at least 8 characters and to be a mix of letters and numbers. Additionally they need to have at least one uppercase letter.

^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$
“pAssword555” will be accepted.

Serverside implementation:

public static bool IsPasswordStrong(string password)
{
  return Regex.IsMatch(password, @"^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$");
}

Clientside implementation:

<asp:TextBox runat="server" ID="PasswordBox" TextMode="password" />
<asp:RegularExpressionValidator runat="server"
ControlToValidate="PasswordBox"
ValidationExpression="(?=.{8,})[a-zA-Z]+[^a-zA-Z]+|[^a-zA-Z]+[a-zA-Z]+"
Display="Dynamic"
ErrorMessage="Password must be 8 chars long and has to contain letters and numbers." />

Simple and effective, enjoy!

ASP.NET on Apache

This is a quick and dirty HowTo ASP.NET on the popular Apache Webserver. It works with ASP.NET v1 and ASP.NET v2!


1) Download and install mod_AspDotNet

2) At the end of your httpd.conf file add the following lines:

#asp.net 
LoadModule aspdotnet_module "modules/mod_aspdotnet.so" 

AddHandler asp.net asax ascx ashx asmx aspx axd config cs csproj licx rem resources resx soap vb vbproj vsdisco webinfo 

<IfModule mod_aspdotnet.cpp> 
  # Mount the ASP.NET /asp application 
  AspNetMount /SampleASP "c:/SampleASP" 
  #/SampleASP is the alias name for asp.net to execute 
  #"c:/SampleASP" is the actual execution of files/folders  in that location 

  # Map all requests for /asp to the application files 
  Alias /SampleASP "c:/SampleASP" 
  #maps /SampleASP request to "c:/SampleASP" 
  #now to get to the /SampleASP type http://localhost/SampleASP 
  #It'll redirect http://localhost/SampleASP to "c:/SampleASP"

  # Allow asp.net scripts to be executed in the /SampleASP example 
  <Directory "c:/SampleASP"> 
    Options FollowSymlinks ExecCGI 
    Order allow,deny 
    Allow from all 
    DirectoryIndex index.htm index.aspx 
   #default the index page to .htm and .aspx 
  </Directory> 

  # For all virtual ASP.NET webs, we need the aspnet_client files 
  # to serve the client-side helper scripts. 
  AliasMatch /aspnet_client/system_web/(\d+)_(\d+)_(\d+)_(\d+)/(.*) "C:/Windows/Microsoft.NET/Framework/v$1.$2.$3/ASP.NETClientFiles/$4" 
  <Directory "C:/Windows/Microsoft.NET/Framework/v*/ASP.NETClientFiles"> 
    Options FollowSymlinks 
    Order allow,deny 
    Allow from all 
  </Directory> 
</IfModule> 
#asp.net

3) Continue with creating C:\AspNetTest.
4) Create a file “index.aspx” and add the following lines to it:

<%@ Page Language="C#" %> 
<html> 
   <head> 
      <link rel="stylesheet"href="example.css"> 
   </head> 
   <body>        
<form>
           <% for (int i=0;i<5;i++= { %> 
              <font size="<%=I%>"> Sample ASP.NET TEST</font> <br> 
           <% } %> 
       </form> 
   </body> 
</html>

5) Restart Apache and visit http://localhost/AspNetTest – it should be working!

Hope that helps..

Install PHP5 on IIS6 – Windows 2003 Server

A quick Tutorial, if you are a lazy reader, this is for you – Install PHP5 in 5 easy steps:

  • Download the PHP5 Zip Package here
  • Extract it to C:\PHP
  • Add C:\PHP to your PATH Variable
  • Open IIS Configuration Panel, WebService Extensions, add C:\PHP\PHP5ISAPI.DLL and set it to allowed
  • Click down to Web Sites. Right click the folder and select Properties. From the Home Directory tab click the Configuration button. Click Add to add an Application Extension. Enter C:\PHP\PHP5ISAPI.DLL as Executable and PHP as Extension. Leave the rest as default and click Ok.

That’s it, enjoy!

Understanding Hash Codes in C# – ASP.NET

To address the issue of integrity, it is common to make use of hash codes. In a nutshell, a hash code is a numerical value that is tied to a fixed input. One interesting aspect of hash code values is the fact that they provide a form of one-way encryption, given that the generated numeric value contains no trace of the original message data. For example, in the previous section, we examined how a strongly named assembly is assigned a digital signature based (in part) on a hash code value obtained from the assembly contents. Clearly a numerical value such as 79BB0DA9D45C6AE29F8 has no trace of the original assembly contents (types, methods, etc). To further illustrate the nature of hash codes, consider the method System.Object.GetHashCode. This virtual method may be overridden by derived types to generate a hash value based on its internal state data. The System.String class has overridden this method to return a different hash value for the current character data. Thus, if you have two identical strings (in the same case), System.String.GetHashCode will return the same value. If only one bit differs by case or content, you (usually) receive another numerical value. Please note: There IS a chance that there is a collision, although it is very unlikely if you use MD5 or SHA256. That being said, Hash strings are not 100% unique, a hashcode is a checksum! Ponder the following class definition:

class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Hash Codes *****");
Console.WriteLine("Hash of 'Hello': {0}", "Hello".GetHashCode());
Console.WriteLine("Hash of 'Hello': {0}", "Hello".GetHashCode());
Console.WriteLine("Hash of 'HellO': {0}", "HellO".GetHashCode());
Console.ReadLine();
}
}

Notice that the first two string objects have identical content and case, while the final string has a capitalized letter O. Now ponder the output.

Of course, when you’re interested in generating hash codes for large blocks of data or sensitive user information, you won’t leverage GetHashCode. Truth be told, overriding this virtual method is only useful when you’re designing types that may be placed in a Hashtable collection. Luckily, the .NET platform ships with types that provide implementations of many well known hash code algorithms. Each type is capable of operating on different input blocks and may differ based on the size of the message data and/or the size of the generated hash code.

Hashing a File

Once you have determined the hash code algorithm you wish to use, you can create an instance of the algorithm using the static HashAlgorithm.Create method. Simply pass in a string name of the algorithm you require (MD5, SHA1, SHA256, SHA384, or SHA512). Assume you wish to generate a hash code for a file on your local machine:

static void Main(string[] args)
{
// Open a local file on the C drive.
FileStream fs = new FileStream(@"C:\MyData.txt", FileMode.Open);
// Now generate a hash code for this file using MD5.
HashAlgorithm alg = HashAlgorithm.Create("MD5");
byte[] fileHashValue = alg.ComputeHash(fs);
// Print out the generated hash code.
Console.WriteLine("Hash code of MyData.txt");
foreach (byte x in fileHashValue)
Console.Write("{0:X2} ", x);
fs.Close();
Console.ReadLine();
}

Notice how hash values are represented using a simple array of bytes. Therefore, if MyData.txt contained thousands of lines of text, the entire contents might be represented as:

79 DC DA F4 5B F6 5C 0B B0 DA 9D 45 C6 AE 29 F8

If you were to change even a single character within MyData.txt, the new hash code will be usually different:

B3 E3 DD 14 96 2D D2 EB 0E C3 68 BF 08 04 D5 80

Again, using hash codes you’re able to represent sensitive data as a unique byte array that contains no trace of the original message data. In a distributed system, one of the most common uses of this technology is for the purposes of storing password information. By storing a user’s password in a hash code format, you increase the security of your system given that this numerical value has no trace of the original password. When the end user attempts to log into your system again, you simply rehash the message and perform a comparison against the persisted value.

Many hash code algorithms also enable you to specify a salt value. Simply put, salting is the process of incorporating a random value to the input of the hash algorithm, in order to further ensure a strong hash.

Feel free to post your comments or questions to this tutorial!

Development Methods: Top-Down and Bottom-Up Method

A little tutorial I wrote lately, hope it helps!

Application Development Methods

There are two methods for developing application code: top-down and bottom-up. Each method offers a different development perspective, and determining which is most appropriate is a case-by-case or application-by-application decision. It may be easier to develop a particular application one way but develop another application with a different method.

Essentially, the difference between the two methods is that the top-down method iterates development by starting with the big picture of the domain (the top) and works downward by decomposing the domain into assemblies, namespaces, and classes (the bottom). In contrast, a bottom-up method, which is also an iterative process, starts at the class level (the bottom) and works upward to the top, by composing classes, namespaces, and assemblies. Historically, object-oriented design and development theorists have advocated decomposing a complex domain into manageable units, which is a top-down method. However, many pragmatists have since recognized that there are times when starting with a vague abstraction is counterproductive and a more tangible approach (i.e., starting by developing classes) is preferred.

Top-Down Method

A top-down development method is one of two commonly used approaches to develop an application (the other is the bottom-up method).

What
An application is developed as an iterative decomposition of the domain. The process starts with a high-level abstraction (clouds) and works downward to implementation (code). Where A top-down method is used in developing domain or enterprise applications.

Why
The top-down approach is commonly used because it follows a traditional object-oriented design, which advocates that complexity is best understood by starting with an abstraction and decomposing it into smaller units. However, although that approach usually works, there are times when working with an abstraction is problematic and it is more productive to start with the basics and work upward (bottom-up method).

How
The domain is viewed from the big picture, and application development is commenced by developing an architecture, then working through assemblies and namespaces to develop classes. The architecture is prepared before code is developed, and it may be tweaked as code development progresses.

The Standard: Top-Down Method

The standard acknowledges the use of the top-down development method to develop a solution by developing an application by decomposing a domain problem.

Bottom-Up Method

A bottom-up development method is one of two commonly used approaches to developing an application (the other is the top-down method).

What
An application is developed as an iterative composition of the domain.

Where
A bottom-up method is used in developing domain or enterprise applications.

Why
The bottom-up approach is used because it starts off more tangibly by developing small units of functionality (classes) and incrementally composes the complexity from class level to assembly level.

How
The domain is viewed from a detailed picture, and application development is commenced by developing classes and working upward to develop the structure (e.g., namespaces and assemblies). The architecture is prepared as part of code development; it evolves as a consequence of assembling the solution.

The Standard: Bottom-Up Method

The standard acknowledges the use of the bottom-up development method to develop
an application by composing a domain solution.

Walkthrough: ASP.NET PasswordHasher Class


I did that lately and like to share that with you:

1. Create a new subdirectory in the App_Code directory of BalloonShop called SecurityLib.
2. Add a new class file called PasswordHasher.cs with code as follows:

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
namespace SecurityLib
{
public static class PasswordHasher
{
private static SHA1Managed hasher = new SHA1Managed();
public static string Hash(string password)
{

// convert password to byte array
byte[] passwordBytes =
System.Text.ASCIIEncoding.ASCII.GetBytes(password);
// generate hash from byte array of password
byte[] passwordHash = hasher.ComputeHash(passwordBytes);
// convert hash to string
return Convert.ToBase64String(passwordHash , 0,
passwordHash.Length);
     }
   }
}

3. Add a new web page to the root of your web site called SecurityLibTester.aspx, using
the usual options for having code in an external file and selecting the default Master Page (if you have one).
4. Add the following code to SecurityLibTester.aspx:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master"
AutoEventWireup="true" CodeFile="SecurityLibTester.aspx.cs"
Inherits="SecurityLibTester" Title="SecurityLib Test Page" %>
<asp:Content ID="Content1"
ContentPlaceHolderID="contentPlaceHolder" runat="Server">
Enter your password:<br />
<asp:TextBox ID="pwdBox1" runat="server" />
<br />
Enter your password again:<br />
<asp:TextBox ID="pwdBox2" runat="server" />
<br />
<asp:Button ID="processButton" runat="server" Text="Process"
OnClick="processButton_Click" />
<br />
<asp:Label ID="result" runat="server" />
</asp:Content>

5. Modify SecurityLibTester.aspx.cs as follows:

using System;
...
using System.Text;
using SecurityLib;
public partial class SecurityLibTester : System.Web.UI.Page
{
...
protected void processButton_Click(object sender, EventArgs e)
{
string hash1 = PasswordHasher.Hash(pwdBox1.Text);
string hash2 = PasswordHasher.Hash(pwdBox2.Text);
StringBuilder sb = new StringBuilder();
sb.Append("The hash of the first password is: ");
sb.Append(hash1);
sb.Append("<br />The hash of the second password is: ");
sb.Append(hash2);
if (hash1 == hash2)
{
sb.Append("<br />The passwords match! Welcome!");
}
else
{
sb.Append("<br />Password invalid. "
+ "Armed guards are on their way.");
}
result.Text = sb.ToString();
}
}

6. Browse to SecurityLibTester.aspx, enter two passwords, and click Process. Voila, check if it matches.

How It Works: Implementing the PasswordHasher Class

The code in the PasswordHasher class follows the steps that were discussed earlier. First, you use the utility
function System.Text.ASCIIEncoding.ASCII.GetBytes to convert the password string into a byte array:

// convert password to byte array
byte[]passwordBytes =
System.Text.ASCIIEncoding.ASCII.GetBytes(password);
Next, you use the private shared member hasher, an instance of SHA1Managed, to generate a hash byte array:
// generate hash from byte array of password
byte[] passwordHash = hasher.ComputeHash(passwordBytes);

Finally, you convert the hash back into a string by using the utility function Convert.ToBase64String and return
the result:

// convert hash to string
return Convert.ToBase64String(passwordHash , 0,
passwordHash.Length);

All the hash algorithm classes in the .NET Framework use this ComputeHash method to get a hash from an input
array of bytes. To increase the size of the hash, you can replace the hasher with another one of these, for example:

public static class PasswordHasher
{
private static SHA512Managed hasher = new SHA512Managed();
...
}

This change would result in a 512-bit hash, which is probably a bit excessive in this sort of application!
The client page, SecurityLibTest.aspx, hashes two passwords and compares the result. The code is basic
enough to ignore for now, but it’s important to note that the generated hashes vary a great deal for even simple
changes to the input data, even just changes of case—one of the defining features of good hash generation.

That’s it, hope you find it useful!

Understanding the E-Commerce Project Cycle

For most e-commerce projects, your best bet will be something with a Waterfall flavor, but with
a bit of changes here or there.

If you have some knowledge about management and a good artistic spirit for web design, the e-commerce project can be a “one man show.� First of all, you need to organize the tasks so that they take place in a logical, sequential order.

Understanding the customer needs should not be difficult. The customer wants an e-store
where a range of products can be advertised and bought. You need to know the type of products
the customer wants on the site and a little about future strategy (today the customer is only
selling balloons, but in the future the customer might want to sell candies). This is very important
because the database and the whole architecture must be designed from the start to support
future changes. You After the data tier is in place, you can continue by building the middle tier of your application.
In the middle tier, you implement the error-handling, data-manipulation strategies and
the business logic for your project.

Most of the customers require artistic and functional design, so, in most cases, the next
phase is creating a web prototype. Whether you do it yourself or hire a web designer, the prototype
should be only a web site template—only HTML code with something like “Product Name
Here� instead of an actual product—without the need of any databases. Depending on the
artistic taste of the customer, you might have to build several prototypes until you agree on a
design. Alternatively, you can create a more complex prototype that has some basic functionality
and even a simple database behind the scenes. The prototype will help you get a feel about
how the final application will work and can help you get some initial feedback from the future
users. With ASP.NET 2.0, you can very easily write simple throwaway interfaces using the new
data-bound controls and data-binding techniques. After you’ve passed the prototypes phase,
it’s time to start implementing the real application.

Designing the database is a critical phase of the project. The logical database
design is developed from the requirements-gathering phase, and is agreed on with the customer.
The logical design of a database describes what data you need to store and the relationships
between different entities of data (such as the relationship between products and departments),
but doesn’t include strict implementation details, such as the associate table used to physically
implement Many-to-Many relationships. If you’re an advanced database designer, you’ll create an
optimal physical database structure yourself.

A number of tools—such as Microsoft Visio—enable you to design the database visually.
These tools have very powerful features for designing relational database structures, and even
generate the SQL code to turn them into real databases. Regardless of the database engine
you’re using, design your tables in a visual way (even with a pen and paper) rather than writing
SQL queries.

If you don’t have resources to buy such an expensive program (yeah, the really professional
ones can be very expensive), you can use Visual Web Developer, which is free and comes
packed with some useful diagramming features.

Next, you implement the data tier objects. This is the place you start playing with your
database because you need to implement the data access logic that will support the other tiers
in your application. In the process, you’ll probably want to populate the database with some
fictive examples to have a base for testing your queries. Before writing the queries as data tier
objects, test them using a visual interface to the database engine that allows executing and
debugging SQL queries. This will make your life easier when debugging the SQL code, because
as all SQL developers know, the code doesn’t always work as you expect it to the first time.

After the data tier is in place, you can continue by building the middle tier of your application.
In the middle tier, you implement the error-handling, data-manipulation strategies and
the business logic for your project.

Building the user interface (the ASP.NET Web Forms, Web User Controls, and Master
Pages) should be the next step. You already have a prototype that is usable only for design,
because at the stage you created the prototypes, you didn’t have a functional foundation.
Usually, interface prototypes in software projects are throwaway code, but the ASP.NET forms
and controls generate the actual look of your web site (with the design the customer agreed on).
A final testing phase is very important at the end of the project. The database will be populated
with real records, and a simulation is made to test the efficiency of the ordering process.
Every process should be tested before going into production, so you must give your customer
enough time to test every functionality of the site, to make some test orders, and to evaluate the
shipping process. During this stage, any programming errors should be revealed for you to
correct.

After the code is ready and tested on your local machine, the next step is to find/provide a
hosting solution. Perhaps the best strategy is to host the project at a specialized provider, and
if the site proves to be successful, the customer can invest in its own hosting solution.

SQL Server 2005 – What is a View?

I explained that a couple of times lately so I decided to write a detailed description of a View in SQL Server 2005. Here we go:

There will be times when you want to group together data from more than one table, or perhaps only allow users to see specific information from a particular table, where some of the columns may contain sensitive or even irrelevant data. A view can take one or more columns from one or more tables and present this information to a user, without the user accessing the actual underlying tables. A view protects the data layer while allowing access to the data. All of these scenarios can be seen as the basis and reason for building a view rather than another method of data extraction. If you are familiar with MS Access, views are similar to Access queries. Because a view represents data as if it was another table, a virtual table in fact, it is also possible to create a view of a view.

Let’s take a look at how a view works. For example we have a customer table that holds information about customers such as their first name, last name, account number, and
balances. There will be times when you want your users to have access to only the first and last names, but not to the other sensitive data. This is where a view comes into play. You would create a view that returns only a customers first and last name but no other information. Creating a view can give a user enough information to satisfy a query he or she may have about data within a database without that user having to know any T-SQL commands. A view actually stores the query that creates it, and when you execute the view, the underlying query is the code that is being executed. The underlying code can be as complex as required, therefore leaving the end user with a simple SELECT * command to run with perhaps a small amount of filtering via a simple WHERE statement.

From a view, in addition to retrieving data, you can also modify the data that is being displayed, delete data, and in some situations insert new data. There are several rules and limitations for deleting, modifying, and inserting data from multitable views, some of which will be covered in the “Indexing a View” section later in the chapter.

However, a view is not a tool for processing data using T-SQL commands, like a stored procedure is. A view is only able to hold one query at a time. Therefore, a view is more like a query than a stored procedure. Just as with a stored procedure or a query within a Query Editor pane, you can include tables from databases that are running on different servers. Providing the user ID has the necessary security credentials, it is possible to include tables from several databases.

So to summarize, a view is a virtual table created by a stored SQL statement that can span multiple tables. Views can be used as a method of security within your database, and they provide a simpler front end to a user querying the data.

Hope that helps..

ASP.NET: MemberShip – get the UserID of the User

I’ve read that question on many message boards so I decided to post a quick blog entry about that. It’s actually very easy.

If you use the new comfortable Login Controls of ASP.NET v2, here is how you resolve the UserID of the currently logged in user:

 

        MembershipUser myObject = Membership.GetUser();
        string UserID = myObject.ProviderUserKey.ToString();

That’s all! Hope that helps..

Check if the Internet Connection State is active

I wrote a small application which uploads Images of new products and therefore I had to check if the Internet Connection State is active, otherwise it would crash. There are actually two ways (and probably more) of doing this, depending on your system. You could go with a direct api call:

        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

        //Creating a function that uses the API function...
        public static bool IsConnectedToInternet()
        {
            int Desc;
            return InternetGetConnectedState(out Desc, 0);
        }

The Description can be found on MSDN, depending on the Connection the proper Value has to be entered.

Another way would be resolving some host of which you are sure it is online all the time. That could be microsoft.com, your company’s website or something else. Here we go:

        public static bool IsConnected()
        {
            System.Uri Url = new System.Uri("http://www.microsoft.com");

            System.Net.WebRequest WebReq;
            System.Net.WebResponse Resp;
            WebReq = System.Net.WebRequest.Create(Url);            

            try 
            {
                Resp = WebReq.GetResponse();
                Resp.Close();
                WebReq = null;
                return true;
            }

            catch
            {                
                WebReq = null;
                return false;
            }
        }

Include one of those functions in your code and you’re set!

How to uninstall Internet Explorer 7 Beta 2

Ok, it’s actually mentioned in the licence agreement terms but I’m sure many of you don’t read them ;). That’s how to completly remove it and go back to IE6:

  1. Go to the Control Panel
  2. Click on Add/Remove Programs
  3. Click on Show Updates (Small Box in the upper Region)
  4. Scroll down and look for IE7
  5. Hit uninstall

That’s it, everything back to normal now.

Forward PageRank to your new Domain

Whenever you register a new domain and want to transfer an old PageRank from an old Website to that new address, be sure to use the 301 Code. Here are 3 methods on how to do that properly (pick one):


If you’re using IIS:

* In internet services manager, right click on the file or folder you wish to redirect
* Select the radio titled “a redirection to a URL”.
* Enter the redirection page
* Check “The exact url entered above” and the “A permanent redirection for this resource”
* Click on ‘Apply’

In ASP.NET:

<script runat=”server”>
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = “301 Moved Permanently”;
Response.AddHeader(“Location”,”http://www.newdomain.com/”);
}
</script>

In ASP:

<%@ Language=VBScript %>
<%
Response.Status=”301 Moved Permanently”
Response.AddHeader “Location”, “http://www.newdomain.com/”
%>

In PHP:

    <?
    Header( "HTTP/1.1 301 Moved Permanently" );
    Header( "Location: http://www.newdomain.com" );
    ?> 

Extending the Directory.GetFiles() Filter Pattern

I recently wrote a little application which uploads specific files on a specific FTP. I came across the System.IO.Directory.GetFiles() Method and noticed that it’s natively only possible to add one kind of pattern. Which means:

string[] files = Directory.GetFiles(path, "*");

Works without problems. But what if you like to insert multiply extensions like:

string[] files = Directory.GetFiles(path, "*.jpg *.png *.gif");

This won’t work that way! The function only accepts one filter. And that’s how to add more than one:

string strFilter = "*.jpg;*.png;*.gif";
string[] m_arExt = strFilter.Split(';');
foreach(string filter in m_arExt)
{
    string[] strFiles = Directory.GetFiles(folder, filter);
}

ak