Extract the first N words from a string with C#

This code will return the first 5 words, change the number in the regular expression as needed: Continue reading

Posted in RegEx | Tagged | Leave a comment

Streaming Files for more Secure Downloads in ASP.NET

If you just have a link to a file on your web site then you maybe leaving yourself open to other sites linking to the same files thereby giving their users the benefit of content without any hit on their bandwidth. It will also give clues to your site structure that can only be of benefit to anyone wishing to compromise your site’s security.

One workaround to this is to stream the files to your users using a FileStream and the Response object. Here is some C# code that will do that job for you:

/// <summary>
/// Write a secure file out to the response stream. Writes piece-meal in 4K chunks to
/// help prevent problems with large files.
/// <example>
/// <code>WriteFileToResponse(@"secureFolder/mysecurefile.pdf", @"test.pdf",
/// @"application/pdf");</code>
/// </example>
/// <example>
/// <code>WriteFileToResponse(@"secureFolder/mysecurefile helpful hints.pdf", @"test.pdf");</code>
/// </example>
/// </summary>
/// <param name="secureFilePath">Relative path to the file to download from our 
/// secure folder</param>
/// <param name="userFilename">Name of file the user will see</param>
/// <param name="contentType">MIME type of the file for Response.ContentType, 
/// "application/octet-stream" is a good catch all. A list of other possible values 
/// can be found at http://msdn.microsoft.com/en-us/library/ms775147.aspx </param>

public void WriteFileToResponse(string secureFilePath, string userFilename, 
    string contentType = @"application/octet-stream")
{
    // Process the file in 4K blocks
    byte[] dataBlock = new byte[0x1000];
    long fileSize;
    int bytesRead;
    long totalBytesRead = 0;

    using (var fs = new FileStream(Server.MapPath(secureFilePath), 
        FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        fileSize = fs.Length;

        Response.Clear();
        Response.ContentType = contentType;
        Response.AddHeader("Content-Disposition", 
            "attachment; filename=" + userFilename);

        while (totalBytesRead < fileSize)
        {
            if (!Response.IsClientConnected)
                break;

            bytesRead = fs.Read(dataBlock, 0, dataBlock.Length);
            Response.OutputStream.Write(dataBlock, 0, bytesRead);
            Response.Flush();
            totalBytesRead += bytesRead;
        }

        Response.Close();
    }
}
Posted in Security | Tagged | Leave a comment

Using the Entity Framework and the ObjectDataSource: Custom Paging

Readers maybe familiar with the Entity Framework (EF) tutorials on the asp.net web site (http://www.asp.net/entity-framework/tutorials). The latest addition to the series “Continuing with the Entity Framework” is an excellent tutorial on using version 4 of the Entity Framework in a web forms application with the ObjectDataSource control. However, at present there is one omission that prevents it from effective use on a web site where you need to list a large amount of data on a web page, and that is custom paging. With the author’s permission of the original tutorial I have posted this article on implementing custom paging based on his original code. Continue reading

Posted in Entity Framework | Tagged | Leave a comment

Using data from Entity Framework 2 to fill a 2010 local SSRS report in ASP.NET

When you design a local SSRS report you are forced to use a Dataset as part of the design process, however, this does not mean that you have to keep the dependancy on a dataset or even retain the dataset in your project once you have completed the design.

Simply use code similar to the C# example that follows to clear the dataset the report is expecting to use and specify the new collection of data it is to use instead:

var context = new AWEntities();

var vendors = from v in context.Vendors
                    where v.CreditRating != 1
                    select v;

ReportViewer1.LocalReport.DataSources.Clear();
ReportDataSource datasource = new ReportDataSource("VendorList", vendors);
ReportViewer1.LocalReport.DataSources.Add(datasource);
ReportViewer1.LocalReport.Refresh();

You can use the same method to substitute data from Linq to SQL or ADO.NET if they are your DAL technology of choice.

Posted in Entity Framework | Tagged , | Leave a comment