Digital Colony!

Add META keywords and Description in ASP.NET

Here is the syntax for programmatically adding META tags to an ASP.NET 2.0 page.
HtmlMeta metaDesc = new HtmlMeta();
metaDesc.Name = "description";
metaDesc.Content = "Tips on roasting coffee at home";
Page.Header.Controls.Add(metaDesc);

HtmlMeta metaKey = new HtmlMeta();
metaKey.Name = "keywords";
metaKey.Content = "roast, coffee, home, tips";
Page.Header.Controls.Add(metaKey);
ASP.NET will render the above code to valid XHTML META tags.
<meta name="description" content="Tips on roasting coffee at home" />
<meta name="keywords" content="roast, coffee, home, tips" />

Labels: , ,

 

Date Scrubbing Function for SQL Server

When creating a report often the date column provides more detail than we need to see. Here is a handy little UDF that rounds a DATETIME column to either the MINUTE, HOUR, DAY, WEEK or MONTH.

DateFirst UDF

IF OBJECT_ID('dbo.udfDateFirst') IS NOT NULL
    DROP FUNCTION dbo.udfDateFirst
GO
CREATE FUNCTION dbo.udfDateFirst
(
    @interval    VARCHAR(10),
    @rawDate    DATETIME
)
RETURNS DATETIME
AS
BEGIN    
    -- Remove seconds for allintervals
    SET @rawDate = CAST(@rawDate AS SMALLDATETIME)

    IF @interval = 'MINUTE'        
        RETURN @rawDate
    ELSE -- strip off minutes
        SET @rawDate = DATEADD(minute,-1 * DATEPART(minute,@rawDate),@rawDate)

    IF @interval = 'HOUR'        
        RETURN @rawDate
    ELSE -- strip off hours
        SET @rawDate = DATEADD(hour, -1 * DATEPART(hour,@rawDate),@rawDate)

    IF @interval = 'DAY'
        RETURN @rawDate

    IF @interval = 'WEEK'
        RETURN DATEADD(day, -1 * DATEPART(weekday,@rawDate),@rawDate)

    -- move date to first of month
    SET @rawDate = DATEADD(day, -1 * DATEPART(day,@rawDate) + 1,@rawDate)

    IF @interval = 'MONTH'
        RETURN @rawDate
    
    -- move Date to first of year
    SET @rawDate = DATEADD(month, -1 * DATEPART(month,@rawDate)+1 , @rawDate)

    RETURN @rawDate
    
END

Test Query

DECLARE @now AS DATETIME
SET @now = getDate()

SELECT dbo.udfDateFirst('MINUTE',@now)
SELECT dbo.udfDateFirst('HOUR',@now)
SELECT dbo.udfDateFirst('DAY',@now)
SELECT dbo.udfDateFirst('WEEK',@now)
SELECT dbo.udfDateFirst('MONTH',@now)
SELECT dbo.udfDateFirst('YEAR',@now)

Labels: , ,

 

File Uploading with ASP Components

This article was written in 2001.

Every now and then there comes a time when a web application requires more from a user. It's not enough that the application receives data in the form of user text boxes and drop-down selections. Sometimes, we need the user to upload a file onto the server. But can we trust the user to setup an FTP program, connect to our server, and place the right file into the right folder without touching anything else? Of course not. What we need to a chimp-simple way to allow users to upload a specific type of file into a specific folder.

Requirements

For this scenario I have 3 requirements:

1 - Restrict the user to uploading to a specified directory on my server.

2 - Restrict file size to prevent huge files from filling up my disk space.

3 - Restrict file types. In this example I only will want image files. Any other file type must be rejected.

Using an ASP Component to Handle File Uploads

There are many file upload components that one can purchase or, if you are so inclined, you can roll your own. The 2 most popular ASP file upload components are Software Artisans FileUp and Persists AspUpload. Both handle uploads slightly different. Let's code each of these components to handle the above requirements.

The FORM

The FORM, where the client uploads a file, is identical.
<form name="form" action="upload.asp" enctype="MULTIPART/FORM-DATA" method="POST">
 <input type="file" name="file1"> <input type="submit" value="Upload Files"> 
</form>

Shared Code

Before you pick which component you will be using, here is some common code that both can use. isFileSizeOK handles the file size restrictions. isValidFile is where you'll define what file extensions the client can upload.

intMaxFileSize = 8000 
strUploadFolder = "c:\uploadFolder" 

Function isFileSizeOK(bytes)    
 ' restrict file byte size    
 byteMAX = intMaxFileSize    
 If bytes > byteMAX Then        
   isFileSizeOK = FALSE    
 Else        
   isFileSizeOK = TRUE    
 End If 
End Function 

Function isValidFile(filename)    
 ' define what file types you will permit to upload    
 fileExtension = lcase(right(filename,4))    
 select case fileExtension        
   case ".gif",".jpg",".png","jpeg"            
     isValidFile = TRUE        
   case else            
     isValidFile = FALSE    
 end select 
End Function

Software Artisans FileUp

Sub uploadSA    
 Set up = Server.CreateObject("SoftArtisans.FileUp")    
 up.Path = uploadFolder    
 If NOT up.IsEmpty Then       
   filename = Mid(up.UserFilename, InstrRev(up.UserFilename, "\") + 1)       
   ' restrict file types to upload       
   If isValidFile(filename) Then          
   ' restrict file by size          
       If isFileSizeOK(up.TotalBytes) Then             
         up.Save             
         strUploadStatus1 = "File [" & filename & "] Uploaded Successfully! " & up.TotalBytes            
       Else             
         strUploadStatus1 = "ERROR: File Too Large: " & filename & " (" & up.TotalBytes & " bytes)"          
       End If       
   Else          
      strUploadStatus1 = "ERROR: This File Type is restricted from uploading: " & filename       
   End If    
 End If    
 Set up = Nothing 
End Sub

Persists AspUpload

With AspUpload, you save the file first, then perform checks. If the file fails the checks, then the code deletes it from the server. This component also has a "SaveToMemory" option, which bypasses the write to the disk until instructed. ASPUpload has built-in image size handling and can detect if a file is an image with the .ImageType property, but for this example we'll use the isValidFile function.
Sub uploadPersists    
  Set up = Server.CreateObject("Persits.Upload.1")    
  up.OverwriteFiles = TRUE    
  up.SetMaxSize intMaxFileSize    
  up.Save uploadFolder    
  For Each File in up.Files       
     fileName = File.ExtractFileName       
     If isValidFile(fileName) Then          
        If isFileSizeOK(File.OriginalSize) Then             
           strUploadStatus2 = "File [" & filename & "] Uploaded Successfully! "          
        Else             
           strUploadStatus2 = "ERROR: File Too Large: " & fileName & " (" & File.OriginalSize & " bytes)"             
           File.Delete          
        End If       
     Else          
        File.Delete          
        strUploadStatus2 = "ERROR: This File Type is restricted from uploading: " & fileName       
     End If    
  Next 
End Sub

Last Words

Both components can do a lot more than what I've demonstrated above. For a more complete list of features, check out the online manuals for Persists AspUpload and Software Artisans FileUp.

This tutorial was expanded for DevGuru.com as A Simple ASP File Upload Application

Labels: , , ,

 

Search Engine Friendly Redirects in ASP.NET

Recently I learned a tough lesson. There are two ways to handle page redirects: the brute force way and the search engine friendly way. When redesigning this site and my fitness site, I used the brute force way. I didn't know any better. Only after seeing it take weeks (Google), months (Yahoo!) or I'm still waiting (Ask) before the site was reindexed did it dawn on me that there had to be a better way. Fortunately there is a better way.

Brute Force Redirect (Server Side)

Response.Redirect("/my-new-page.aspx");

Brute Force Redirect (Client Side)

Once I realized that Yahoo! wasn't comprehending my server-side redirects, I went client-side on them. Maybe this was the trick? It wasn't.
<meta http-equiv="refresh" content="2; URL=http://digitalcolony.com"/>

Search Engine Friendly Redirect

Inside the Page Load add the following code.
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://digitalcolony.com");
Learn from my mistake and perform your search engine redirects without jeopardizing your relationship with the search engines.

Labels: ,

 

Intellisense Not Displaying Controls Inside Wizard Control

I've noticed on many occasions that when adding a new control inside an asp:Wizard control using Visual Studio .NET 2005 that the Intellisense can't find the new control. There is nothing wrong with your code if this happens. It is a bug with Visual Studio. The solution I'm using to fix this is to add my new controls inside the asp:Wizard control first. Then I close and relaunch Visual Studio. At that point the code behind detects the new controls and Intellisense works again. If anyone is aware of a better solution, post your thoughts in the comments.

Labels: , , ,

 

Digital Colony Copyright © 1999-2008 XHTML   508
This site uses Blogger, which is not 100% XHTML compliant.
Try...Catch Disclaimer: For brevity many examples do not include error handling. That is your responsibility.