Entries Tagged 'ASP.NET' ↓

AJAX Activity Images

I found a pretty nice set of AJAX Activity Indicators here: http://www.napyfab.com/ajax-indicators/

One example would be this here:
AJAX Progress Bar

Saves some time in AJAX Development 😉

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: Access Controls after using PostBackUrl

Whenever you execute a Cross Page Post-Back from one site to another by using

<asp:button PostBackUrl=“anotherpage.aspx" runat=“server"/>

be sure to set this on anotherpage.aspx to gain full access to the controls of the previous page:

<%@ PreviousPage VirtualPath=“previouspage.aspx" %>

Afer that, you can access the controls by using the Page.PreviousPage Property.

Example:

Textbox MyNewTextBox = PreviousPage.FindControl("PreviousPageTextBox");
Label1.Text = MyNewTextBox.Text;

Cheers!

.NET beats Java

Microsoft is leaving Java in the dust, but the company still has room to grow in the developer arena, a key executive said. Speaking at the Microsoft FAM (Financial Analyst Meeting) on July 27 in Redmond, Wash., Bob Muglia, Microsoft’s senior vice president of Server and Tools business, said Microsoft’s .Net platform has outpaced Java, particularly the Java Enterprise Edition, over the past five years to become the development platform of choice for enterprise development.

“Five years ago we had problems with J2EE [Java 2 Platform, Enterprise Edition],” Muglia said. However, “We’ve grown from having a quarter of the market to, now, 60 percent,” he said. Microsoft displayed the FAM presentations via Webcast. “J2EE has run its course,” Muglia said.

.. as expected! Along with the .NET Framework 3.0, Java will be far behind.

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

MySQL and Microsoft Visual Studio Integration

For all you MySQL lovers out there, your dream has come true! Expect the possibility to integrate MySQL directly into your Visual Studio environment very soon. According to MySQL it will be released as plugin in the near future.

The company has paid $3,000 to become a member of Microsoft’s Visual Studio Industry Partner (VSIP) program in a move that will help cement the database’s use on Windows. MySQL joins more than 240 other ISVs also working with Microsoft. MySQL says 40 per cent of its downloads are for Windows, and VSIP membership will provide greater integration between the database and Microsoft’s development environment.

Following the statistics, 40 per cent of the MySQL downloads are for Windows. The new partnership improves the integration of the database in existing Microsoft products.

I’m still using MySQL for some of my projects so these are great news!


Source: The Register

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!

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.

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

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

Why ASP.NET 2.0 ?

ASP.NET 2.0 is Microsoft’s latest technology set for building dynamic, interactive web content. Compared to its previous versions, ASP.NET 2.0 includes many new features aimed at increasing the web developer’s productivity in building web applications.

ASP.NET is not the only server-side technology around for creating professional web sites. Among its most popular competitors are PHP (Hypertext Preprocessor), JSP (JavaServer Pages), ColdFusion, and even the outdated ASP 3.0 and CGI (Common Gateway Interface). Among these technologies are many differences, but also some fundamental similarities. For example, pages written with any of these technologies are composed of basic HTML, which draws the static part of the page (the template), and code that generates the dynamic part.

However, PHP for example is just a script language and regarding to functionality it can’t compete with ASP.NET.

ASP.NET 2.0 serves you with high productivity, professionality and a powerful IDE. Honestly, I wouldn’t want to miss all those comforts anymore..

New Atlas Build Available for Download with ASP.NET 2.0

The January CTP build of Atlas was made available today and can be downloaded from http://atlas.asp.net.  This is a pretty big release of Atlas that has a number of new and improved goodies.

The beauty of the <atlas:updatepanel> control is that it enables you to take an existing ASP.NET page with controls and Ajax enable it in under 5 minutes or less (including error handling + progress message UI, etc), without having to write a single line of javascript (note: Atlas also provides a very, very rich client
javascript library if you want to use that as well — but you don’t need to write to it at all unless you want to).

Nikhil posted a great blog entry today that summarizes all of the additional features and enhancements to the <atlas:updatepanel> scenarios that were added as part of this new Atlas CTP drop.  As you can see, there is now much richer support for
error handling and updateprogress UI you can take advantage of as well.

ASP.NET Deployment Tool v1.7 released

The updates are flying..
Get it here: ASP.NET Deployment Tool

I’ve rewritten the complete config section and added Profile Support! Check out the readme for more details.
GotDotNet has been rewritten for ASP.NET v2.0 and seems to have various problems at the moment, in fact you can access the project page only through manually navigating to it. However, you can still get the latest bits from sunlab.de.

Kind Regards, Andreas Kraus

ASP.NET Deployment Tool v1.6 released

Compiled with the RTM v2.0 Framework and greatly improved FTP Support.
Get it here: ASP.NET Deployment Tool

I also setup a Project Page at GotDotNet: ASP.NET Deployment Tool on GotDotNet

Further Plans are:

  • A Profile Management System so you are able to manage all of your Websites by choosing the appropriate Profile.
  • A few Output Tweaks here and there.
  • For the very future: App_offline.htm Support.

I’m still not satisfied with the built-in VS2005 Publishing Tools so I will definitely go on developing it.

Regards, Andreas Kraus