Entries Tagged 'Development' ↓

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.

Editing large files

Just a quick note because I’m dealing with that kind of files at the moment. Whenever you have a large SQL file which is bigger than 1GB most editors need plenty of time to load such files and we didn’t talk about editing those files yet. UltraEdit for example lags a lot when opening 1gb+ files.

To be able to open, edit and save those files quickly I highly recommend WinHex. It’s not as easy as a usual Text Editor but it’s ultra fast because files are being edited just in time. Check it out, you’ll love it!

JustCode! v1.1 RC released!

Wanted to share this with you because it is really a great tool!

JustCode! is a new productivity add-in for Visual Studio. JustCode! enhances Visual Studio with solution-wide on-the-fly error checking, smart code navigation features, refactoring and other powerful coding tools for C#, J# and Visual Basic.NET.

It’s available for Visual Studio 2003 and 2005.

The new v1.1 RC build got the following new features:

  • ASP.Net support: Full support for C# and VB code in script or <% %> regions as well as analysis of asp: tags (usage search, renaming, error checking). Example: it is now possible to rename the value of the id attribute of an asp: tag. JustCode! will automatically find references in the Codebehind files and rename them too.
  • HTML support: Code formatting, syntax checking of HTML in ASP pages and HTML pages
  • JavaScript support: Usage search and Rename Refactoring using global analysis, code formatting, smart templates, syntax checking of JavaScript in script regions as well as .js files
  • All features are now accessible via configurable keybindings
  • Configurable code templates
  • Code formatter with “Learn Code Style” feature
  • Other enhancements and bug fixes

Check it out here: JustCode! v1.1

New IIS7 coded Admin Features

There will be several new ways of administrating IIS7 by using .NET with the upcoming IIS7 which is being delivered with Windows Vista.

The power and simplicity of the new API is just stunning at the moment. To use the new APIs in Windows Vista you just have to add a new Reference in Visual Studio Microsoft.Web.Administration.dll that can be found at IIS directory (%WinDir%\System32\InetSrv).

Creating a Site

ServerManager iisManager = new ServerManager();
iisManager.Sites.Add("NewSite", "http", "*:8080:", "d:\\MySite");
iisManager.Update();

This basically creates an instance of the ServerManager class and uses the Add method in the Sites collection to create a new site named “NewSite” listening at port 8080 using http protocol and content files are at d:\MySite.
One thing to note is that calling Update is a requirement since that is the moment when we persist the changes to the configuration store.
After running this code you have now a site that you can browse using http://localhost:8080

That’s just one little example of the cool new Admin Features in IIS7. That will make administration Softwares like PLESK a piece of cake.

You can get more example right here, at CarlosAg’s Blog.

SQL Server 2005 Service Pack 1


Service Pack 1 for Microsoft SQL Server 2005 is now available. You can use these packages to upgrade any of the following SQL Server 2005 editions: Enterprise, Enterprise Evaluation, Developer, Standard, Workgroup.

Get it here.

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!

ASP.NET “Atlas” April Community Technology Preview

This new Web development technology from Microsoft integrates client script libraries with the ASP.NET 2.0 server-based development framework. In addition, ‘Atlas’ offers you the same type of development platform for client-based Web pages that ASP.NET offers for server-based pages. And because ‘Atlas’ is an extension of ASP.NET, it is fully integrated with server-based services.

I’m following the Atlas Development since the beginning and it’s really worth it to test it out. It’s pretty easy and even cross-browser compatible.

Go and check it out here.

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.

Visual Studio 2005 Web Application Project RC released!

Great Tool for your Web Applications!

What’s new?

  • Event handler generation and wire-up from the WYSIWYG designer
  • F7/Shift-F7 Navigation Support (switch between page views)
  • Add New Item Wizard to add pages based on Master Pages (easily pick master)
  • Richer Publishing Support
  • Connection String and Settings Support in Web.Config
  • Resources and .Resx Resource Editor Support
  • Support for building multi-project applications and sub-web projects
  • .ASPX files no longer locked when debugging
  • Support for root-path based image and stylesheets (/images/foo.jpg)
  • Control Registrations within Web.Config files
  • Web Service Cross-Project Reference Support
  • Section 508 and WCAG Accessibility Checker Support
  • Ability to create an IIS Vroot/Application setting within Project Dialog
  • SQL DataSource Control Support
  • ASP.NET Custom Folder Templates
  • Component Designer Support
  • Support to Drag/Drop User Controls, StyleSheets, Images from Solution Explorer to designer
  • New Web Service Project Template
  • SQL Express Support

If you have installed and used the previous two preview releases of the VS 2005 Web Application Project, you can simply uninstall the previous installs and install this new one. The project file format and code is the same, so your apps will keep working (but now with more features to use).

ScottGu wrote a nice Walk-Through, check it out here.

Download here.

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..

Virtual Server 2005 R2 – Enterprise Edition released!

Great News for all Developers and it’s even free!

Microsoft Virtual Server 2005 R2 is an ideal, production-quality tool for consolidating multiple workloads onto a physical server, allowing organizations to make more efficient use of their hardware resources. Built upon Microsoft Virtual Server 2005 SP1 and bolstered with new functionality, Virtual Server 2005 R2 enables IT organizations to enhance their administrative productivity and rapidly deploy new servers to address changing business needs through automated deployment and configuration of connected virtual machines that are easily administered with standard server management tools. Virtual Server 2005 R2 is an extensively tested and well supported virtualization solution that is supported both by the broader ISV community and by Microsoft in conjunction with its server operating systems and applications.

Because it is part of the Microsoft Windows Server System, Virtual Server 2005 R2 is designed to integrate seamlessly with your other server infrastructure investments. For more information about Virtual Server 2005 R2, see the Virtual Server Product Overview page.

In addition to the license terms of this downloaded software, you are also granted rights to use the software to provide hosted services. End customers receiving this software service are not required to obtain their own Microsoft software licenses. End customers receive the right to interact with functionalities of Microsoft software through the services of the provider’s hosted environment.

Download here

PayPal Development Kit v4 released

It’s available for Java & Coldfusion, ASP.NET, Classic ASP and PHP.

Supported Platforms: Windows Server 2000, 2003, XP; Red Hat Linux 9.0; Sun Solaris 9.0; .NET 1.1, Service Pack 1; JDK 1.4.2 or later; PHP 4.3 or later; Tomcat 5.0 or later; ColdFusion MX 7.

I just downloaded and installed it. Unfortunately the ASP.NET implementation is still written in v1.1 which is truly annoying. After having a short E-Mail Conversation with PayPal they have no plans about an ASP.NET v2 Kit so far – sad but true.

You can get it here.

Handling 1.5 Billion Page Views Per Day Using ASP.NET 2.0

One of the highlights for me at the MIX conference earlier this week was being able to chat with customers about the success they’ve had with sites they’ve built on top of ASP.NET 2.0 and IIS 6.

MySpace.com was definitely the biggest highlight. For those that aren’t familiar with MySpace.com, it is the fastest growing site on the Internet right now. They have 65 million registered subscribers, and are registering 260,000 new users each day. According to the Media Metrix report (an independent analyst firm) MySpace.com had more page views in February than all of the MSN and Google sites combined. That is some serious load.

They re-built and re-deployed their site on ASP.NET 2.0 shortly after Microsoft shipped last year. Some of the pretty amazing statistics Aber and Allen (the MySpace CTP and VP of Engineering who were both in BillG’s keynote session) shared at MIX about the MySpace.com site:

  • MySpace.com is now processing 1.5 Billion page views per day
  • MySpace.com handles 2.3 million concurrent users during the day
  • MySpace.com’s average server CPU utilization went from 85% to 27% after moving (from another technology) to ASP.NET 2.0

Atlas to Go-Live this week!

Microsoft’s Mix conference this week in Las Vegas will be the venue for news surrounding its Web 2.0 strategy. A key part of that strategy is “Atlas,” the company’s AJAX development tool, for which Microsoft will release a new preview at the show.

Microsoft will announce a March CTP (Community Technology Preview) of the Asynchronous JavaScript and XML tool with a Go-Live license, officials said. The Atlas March CTP with Go-Live license enables developers to begin building and deploying new Atlas applications and to extend applications that they can redistribute commercially.

I did some experiments with Atlas in the past and so far it’s pretty impressing. A key factor is that it works on almost every browser so you don’t have to take care of cross browser support. It’ll boost up your Ajax Developing process.