Posts Tagged ‘Class’

File Uploader in ASP.NET and ASP.NET MVC

Friday, January 23rd, 2009

A class to upload files in ASP.NET and ASP.NET MVC.

Introduction

Uploading files is a common scenario and an essential part of many web applications. Here I have created a class which can be used to upload files easily. The uploader class automatically validate all the necessities i.e. validation of upload directory, file extensions etc.

Background

There are plenty of resources on uploading a file in ASP.NET. But I have felt to have a class which would be easier and customizable as well as can perform validation, add prefix and/or suffix to file, encrypt filename, allow choice to overwrite existing file or not and so on. You have to just set the necessary properties you need. You can use it in your ASP.NET as well as ASP.NET MVC application.

Using this Class

Here I am giving an example to use this class.

    Uploader uploader = new Uploader();
 
    uploader.UploadPath     = Server.MapPath("~\Content\Uploads");
    uploader.IsLowerName    = true;
    uploader.IsEncryptName  = false;
 
    uploader.Prefix = "Hello_";
    uploader.Suffix = "_Boom";
 
    uploader.AllowedExtensions.Add(".jpg");
    uploader.AllowedExtensions.Add(".jpeg");
    uploader.AllowedExtensions.Add(".gif");
    uploader.AllowedExtensions.Add(".png");
 
    bool success = uploader.DoUpload("MyFile");
 
    if (success)
    {
        //TODO: Code to handle success
    }
    else
    {
        //TODO: Code to handle failure
    }

Here MyFile is the name of file input type.

 <!-- In Html -->
<input type="file" name="MyFile" id="MyFile" />
<%--In tradition ASP.NET --%>
<asp:FileUpload ID="MyFile" runat="server" />

There is an overload of DoUpload() method. You can either pass the name of the file input as above or HttpPostedFile file object as follows.

HttpPostedFile postedFile = HttpContext.Current.Request.Files["MyFile"] as HttpPostedFile;
uploader.DoUpload(postedFile);

There is also a method by which you can get the HttpPostedFile object by supplying the name of the file input.

HttpPostedFile postedFile = uploader.GetHttpPostedFile("MyFile");
uploader.DoUpload(postedFile);

Configuration Settings

General Settings
UploadPath Full path where file should be uploaded exculding the filename. (Mandatory).
UploadName The name which should be used to save the uploaded file with extension. (Optional).
Prefix The prefix to the filename. (Optional).
Suffix The suffix to the filename. (Optional).
Conditional Settings
MinSize The minimum size of the file in bytes.
MaxSize The maximum size of the file in bytes.
IsOverwrite Whether a file is to overwrite or not.
IsEncryptName Whether a file name is to encrypt or not.
IsLowerName Whether a file name is to lower or not.
IsRemoveSpace Whether space is to be removed from a file name or not.
AllowedExtensions The allowed file extensions with period.
IsRemoveSpace The allowed mime types.
Object Properties
UploadError The object of UploadError class. This class holds error code and error message.
PostedFile The object of PostedFile class. This class holds different informations of posted file.
UploadedFile The object of UploadedFile class. This class holds different informations of uploaded file.
Properties of UploadError Class
Code The error code.
Message The error message.
Properties of PostedFile and UploadedFile Class
FileName The file name with extension.
RawName The file name excluding extension.
FileExtension The file extension with period.
MimeType The file MIME type.
FullPath The absolute path including the file name.
FilePath The absolute path to the file excluding the file name.
FileSize The size of the file in bytes.
IsImage Whether the file is image or not.

If your upload is not succeded then you can get the error code and message by UploadError property. For example:

strring erroCode    = uploader.UploadError.Code;
string errorMessage = uploader.UploadError.Message;

Remember, here error code is not actual http error number. I have used numbers from 1 to 10 so that corresponding message can be customized.

On the other hand, if your upload attempt is succeeded, then you can use information related to the posted file as well as uploaded file by PostedFile and UploadedFile. For example:

string previousFilename = uploader.PostedFile.FileName;
string previousFilePath = uploader.PostedFile.FilePath;
 
string uploadedFilename = uploader.UploadedFile.FileName;
string uploadedFilePath = uploader.UploadedFile.FilePath;

Enjoy this!

Downloads

Download Uploader class here. Uploader Class

Download Uploader Sample In ASP.NET here. Uploader Sample In ASP.NET

Download Uploader Sample In ASP.NET MVC here. Uploader Sample In ASP.NET MVC

Here is the .Net 2.0 version of Uploader class. Uploader Class For ASP.NET 2.0 Application

Pagination Class for ASP.NET MVC

Wednesday, August 13th, 2008

A class for creating different types of pagination link in Asp.Net Mvc.

Pagination For Asp.Net Mvc

Pagination For Asp.Net Mvc

Introduction

I was looking for a pagination class to use in Asp.Net Mvc. I found ASP.NET MVC: PagedList<T> and ASP.NET MVC – Pagination View User Control. But I felt for an easier and customizable pagination class. I have developed many projects using CodeIgniter framework and that time I found their pagination class is pretty better and easier. So, I have decided to prepare a pagination class like this for Asp.Net Mvc.

Using the Code

Controller

In your controller, to get your current (i.e. selected) page number put this code snippet.

string pageString = "";
 
try
{
    pageString = Request.Url.Segments[3];
}
catch (Exception)
{
    pageString = null;
}
 
int page = (String.IsNullOrEmpty(pageString)) ? 1 : Int32.Parse(pageString);

Here 3 is the segment which holds the page number. It can vary as per your URL.

Then use the pagination class as shown in the following example.

Pagination pagination = new Pagination();
 
pagination.BaseUrl      = "/Users/List/";
pagination.TotalRows    = totalRows;
pagination.CurPage      = page;
pagination.PerPage      = 10;
 
string pageLinks = pagination.GetPageLinks();
 
int start   = (page - 1) * pagination.PerPage;
int offset  = pagination.PerPage;

In BaseUrl you can write full path like "http://www.sitename.com/Controller/Action/" or relative path like "/Controller/Action/". Here "start" is the number from which row should be counted and "offset" is the number of rows should be returned. “totalRows” is the total number of rows.

Now you can use this "pageLinks" string which is the generated page link.

Next, set your data in the ViewData like the following.

ViewData["title"]       = "Pagination in Asp.Net Mvc";
ViewData["totalRows"]   = totalRows;
ViewData["result"]      = result;
ViewData["pageLinks"]   = pageLinks;

Here, "totalRows" is the total number of rows and "result" is the desired resultset.

View

In view page, you can show the page link as follows:

<% if ((string)ViewData["pageLinks"] != "")
   { %>
   <%= ViewData["pageLinks"] %>
   <br /><br />
<% } %>

Model

You can create a model and make two methods to get total rows and the data from table using LINQ, as shown in the following example.

public int GetTotalUsers()
{
    return new MyDataContext().Users.Count();
}
 
public List GetUsers(int start, int offset)
{
    var users = new MyDataContext().Users.Skip(start)
                                                 .Take(offset);
 
    return users.ToList();
}

Configuration Settings

General Properites
BaseUrl Full or relative URL to the controller/action (Mandatory).
TotalRows Total number of rows in your resultset (Mandatory).
CurPage Current page number, default 1 (Mandatory).
PerPage Number of items you want to show per page (Optional).
NumLinks Number of “digit” links before and after the current page number (Optional).
ItemType Item type enumeration value (Optional).
Link Properites
FirstLink The text to be shown in the “first” link on the left.
NextLink The text to be shown in the “next” page link.
PrevLink The text to be shown in the “previous” page link.
LastLink The text to be shown in the “last” link on the right.
Tag Properties
FullTagOpen The opening tag placed on the left side of the entire result.
FullTagClose The closing tag placed on the right side of the entire result.
FirstTagOpen The opening tag for the “first” link.
FirstTagClose The closing tag for the “first” link.
LastTagOpen The opening tag for the “last” link.
LastTagClose The closing tag for the “last” link.
CurTagOpen The opening tag for the “current” link.
CurTagClose The closing tag for the “current” link.
NextTagOpen The opening tag for the “next” link.
NextTagClose The closing tag for the “next” link.
PrevTagOpen The opening tag for the “previous” link.
PrevTagClose The closing tag for the “previous” link.
NumTagOpen The opening tag for the “digit” link.
NumTagClose The closing tag for the “digit” link.
ItemTagOpen The opening tag for the “Item”.
ItemTagClose The closing tag for the “Item”.

You can set configuration settings in three ways.

1. Set as regular property is set. Example:

objPagination.PerPage  = 10;
objPagination.PrevLink = "Prev";
objPagination.NextLink = "Next";

2. Put a Pagination.xml file in "Content" folder and create object of Pagination class as:

Pagination objPagination = new Pagination(true);

Pagination.xml file should be as following pattern as example.

<?xml version="1.0" encoding="utf-8" ?>
<Pagination>
    <NumLinks><![CDATA[5]]></NumLinks>
    <FullTagOpen><![CDATA[<p class='pagination'>]]></FullTagOpen>
    <FullTagClose><![CDATA[</p>]]></FullTagClose>
    <CurTagOpen><![CDATA[<span class='current'>]]></CurTagOpen>
    <CurTagClose><![CDATA[</span>]]></CurTagClose>
</Pagination>

3. Create a any xml file like the above Pagination.xml file and call the method LoadPaginationXml with the file full path as argument. Example:

objPagination.LoadPaginationXml("C:\MyProject\MyPagination.xml");

Different types of pagination

By this pagination class you can build different types of page link for your page. Just call the method GetPageLinks with your desired PaginationType as argument. Example:

objPagination.GetPageLinks(PaginationType.FirstPreviousNextLastItemRight);

If you want to display item set item type as follows:

objPagination.ItemType = ItemTypes.Page;

Conclusion

I think thats enough to use this pagination class easily. Bye for this time.

Download

You can download the Pagination class from here.

PaginationClass

You can download sample project from here.

PaginationInAspNetMvc

convert this post to pdf.