06 May 2011

Upload files to Share point from ASP.NET

We will see some of the code samples to upload files to a SharePoint or a mapped drive using HTTP PUT methods.
ASP.NET UI code is going to look something like
UI code

<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" Width = "500px" />
<br />
<br />
<asp:Button ID="UploadButton" runat="server" OnClick="Button1_Click"
Text="Upload File" />
<br />
<br />
<asp:Label ID="Label1" runat="server">asp:Label>
div>
form>
Upload Code
protected void UploadFileToSharePoint(string UploadedFilePath,
    string SharePointPath)
{
    WebResponse response = null;
    lnkUpload.Disabled = false;
    try
    {
        // Create a PUT Web request to upload the file.
        WebRequest request = WebRequest.Create(SharePointPath);

        request.Credentials = CredentialCache.DefaultCredentials;
        request.Method = "PUT";
        byte[] buffer = new byte[1024];
        using (Stream stream = request.GetRequestStream())
        using (FileStream fsWorkbook = File.Open(UploadedFilePath,
            FileMode.Open, FileAccess.Read))
        {
            int i = fsWorkbook.Read(buffer, 0, buffer.Length);

            while (i > 0)
            {
                stream.Write(buffer, 0, i);
                i = fsWorkbook.Read(buffer, 0, buffer.Length);
            }
        }

        response = request.GetResponse();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        response.Close();
    }
}
private void UploadFile()
{
    try
    {
        if (FileUpload1.HasFile)
            try
            {
                string uploadedFilePath = FileUpload1.PostedFile.FileName;
                Label1.Text = "File name: " +
                     FileUpload1.PostedFile.FileName + "
"
+
                     FileUpload1.PostedFile.ContentLength + " bytes
"
+
                     "Content type: " +
                     FileUpload1.PostedFile.ContentType;

                UploadFileToSharePoint(
                    uploadedFilePath ,
                    sharePointListPath + FileUpload1.FileName);
            }
            catch (Exception ex)
            {
                Label1.Text = "ERROR: " + ex.Message.ToString();
            }
        else
        {
            Label1.Text = "You have not specified a file.";
        }
    }
    catch (Exception)
    {
        throw;
    }
}
Delete file
    private void DeleteFile()
    {
    //bool isExists = false;
    System.IO.StreamReader reader = null;
    Stream dataStream = null;
    HttpWebResponse response = null;
    try
    {
        WebRequest request = WebRequest.Create(deleteFile);
        request.Credentials = new System.Net.NetworkCredential(USERNAME , PWD, DOMAIN);
        request.Method = "DELETE";
        response = (HttpWebResponse)request.GetResponse();
        dataStream = response.GetResponseStream();
        reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        // isExists = true;
    }
    catch (WebException)
    {
        throw;
    }
View Code 
private void OpenDoc()
{
    string loginUri = FILENAME   ;
    WebClient Client = new WebClient();
    Client.Credentials = new NetworkCredential(USERNAME , PWD, DOMAIN );
    byte[] b = Client.DownloadData(loginUri);
    HttpContext.Current.Response.AddHeader("content-disposition", "Attachment; filename=" + "Doc1.doc");
    HttpContext.Current.Response.BinaryWrite(b);
}
Check for File Exists
private bool CheckIfFileExists()
{
    bool isExists =false;
    System.IO.StreamReader  reader = null;
    Stream dataStream = null;
    HttpWebResponse response = null ;
    try
    {
        WebRequest request = WebRequest.Create(FILENAME);
        request.Credentials = new System.Net.NetworkCredential(USERNAME , PWD , DOMAIN );
        request.Method = "HEAD";
        response = (HttpWebResponse)request.GetResponse();
        dataStream = response.GetResponseStream();
        reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        isExists = true;
    }
    catch (WebException)
    {
        throw;
    }
    return isExists;
} 

Storing Uploaded Files in a Database or in the File System

There was a requirement in one of our project where we need to upload document from .NET web application. The options were less either to Sql Server Database or File System. Share point option was ruled out because of internal issues. Sharing one of the comparison study we made that time, might be helpful to someone who is looking for the same. 

It requires less work - Storing and retrieving binary data stored within the database involves more code than when working with the data through the file system. It's also easier to update the binary data - no need for talking to the database, just overwrite the file!
Performance - Since the files are stored on the file system rather than on the database, the application is accessing less data from the database, reducing the demand on the database and lessening the network congestion between the web and database server. Database operations are more costly than file system.
Storage Limit: Storing files in the DB is great for small files and if we are sure that the size will not grow out of expectations.  In SQL Server we have limited options when you exceed the physical storage capacity of the box. The bulky database makes may creates problems in backing up the data, moving the data from one database server to another, replicating the database, and so on, is much easier because there's no worry about copying over or backing up the binary content stored in the file system. Taking backup and recovery will be more time consuming with Database storing.
Security: File system storage is great, but keep in mind that you're going to have to keep file permissions or security in mind than you would if you stored them in the DB.
Advantages of storing Binary Data in the Database...
1.    Enforcing referential integrity
2.    Tighter security as you doesn’t have to grant the web user account write access to a folder it is serving content from. Also you get the security of the sql server
3.    All files are backed up when the db is backed up
I would recommend having a shared drive where we can upload files and can store the file path in DB. That will be more simple and best solution. If we are having any issues of getting shared rive, storing in DB is definitely a solution. But we should be able to estimate the volume of the file to be stored. 

26 April 2011

File Upload Filter in JavaScript

The ASP.Net FileUpload control does not have any property to provide the functionality to filter the valid/invalid file types in the file-navigation dialog box that opens when user clicks the browse button of fileupload control. You can implement the File Type filter for FileUpload control using JavaScript client side code. This type filter validation enables you to validate the FileUpload control for disallowing the users to upload the files with invalid file type extensions.
For example there was a requirment  option to upload the User avatar that requires the file type filter validation to disable the user from uploading the files that have file extensions other than the allowed file types. Here is the sample:

<asp:FileUpload ID="dlgFileUpload" runat="server" />
<asp:LinkButton id="lnkAdd" runat="server" Text="Add" onclick="lnkAdd_Click" >asp:LinkButton>

C#code

protected void Page_Load(object sender, EventArgs e)
{
   dlgFileUpload.Attributes.Add("onchange", "return validateFileUpload(this);");
     lnkAdd.Attributes.Add("onclick", "return validateFileUpload(document.getElementById('" + dlgFileUpload.ClientID + "'));");
}

JavaScript Code:

function validateFileUpload(obj) {
    var fileName = new String();
    var fileExtension = new String();
     // store the file name into the variable   
    fileName = obj.value;
    // extract and store the file extension into another variable       
    fileExtension = fileName.substr(fileName.length - 3, 3);
    // array of allowed file type extensions       
    var validFileExtensions = new Array("rtf", "pdf", "doc","docx","msg","xlsx","txt");
    var flag = false;
    // loop over the valid file extensions to compare them with uploaded file       
    for (var index = 0; index < validFileExtensions.length; index++) {
      if (fileExtension.toLowerCase() == validFileExtensions[index].toString().toLowerCase()) {
              flag = true;
       }
     }
     // display the alert message box according to the flag value       
     if (flag == false) {
         alert('Invalid file extension.Only the following extensions are allowed:\n.rtf\n.pdf\n.doc\n.docx\n.msg\n.xls\n.xlsx\n.txt\n');
          return false;
      }
      else {
          alert('File has valid extension.');
          return true;
      }
  }

26 January 2011

Access SharePoint from an application



SharePoint is a recognized technology standard for company infrastructure organizations. It has wide functionality, and allows storing different information in one single place. Many a times, we may want to upload documents in a SharePoint server and place these documents in a document library. Sometimes this information needs to be accessed from an application. We also had a requirement where we need to talk to SharePoint from our .NET application. This is not something new, but I would like to share my experience when there was a requirement to communicate SharePoint server from web application.
There are different ways where you can operate with share point.
·       Reference and use the classes the Microsoft.Sharepoint library (SPS)
·       Make a web reference to the SharePoint services. (WSS)
·       Using windows explorer. ( Classic way)
Microsoft.SharePoint library is the easier coding method of the two, but it requires that you run the program on the same server as SharePoint. In real time this is not the case, Production server and share pint server will be always different. In this case we need to add the reference of the SharePoint library and started accessing the functionalities. This is also called object model method.
Coming back to second method, add a reference to the SharePoint Lists service (/_vti_bin/Lists.asmx) and name it ‘ListsService’. The code was written against MOSS 2007. In SharePoint, the web services are located in http:///_vti_bin/lists.asmx. For example, if the SharePoint site that you are trying to access is http://Server name/SomeSite, the URL to the web service is http://Server name/Some Site/_vti_bin/lists.asmx · In the URL field, enter the URL to access the web services.
1.   Add a reference to the System.Net library. You will need this
library to perform authentication to the SharePoint site.
using System.Net;
2.  In the Main function, add a reference to your web reference
with the following statement:
SharePointSvce.Lists listService = new SharePointSvce.Lists();
This statement indicates that you will be using the Lists web service.
    3. In the next line,    
you will be setting up the authentication credentials to the   SharePoint site.
a. To use the logged in user’s credentials, add the following line:
listService.Credentials =
System.Net.CredentialCache.DefaultCredentials;
        b. To use another set of credentials, add the following line:
listService.Credentials = new NetworkCredential(“userID”,
“password”, “domain”);
4.   Replace “userID” with the user ID to log in. 
Windows SharePoint Service has exposed 14 or more web services (please search for the names ) where applications can consume those and do all the operations where we can perform through SharePoint portal server. We have to create proxy as given above for each service that we are going to use from them.
The last method was to access share point server as windows explorer. This is the classic method and the server should be in same network to access SharePoint library folder. All the files which are uploaded like this can be accessed through SharePoint portal server also. We can follow this logic if we are in same network, if we have security issues to access web services in SharePoint server.