Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

February 23, 2011

Multiple file upload using ExtJS & ASP.Net MVC

Recently I had to build an image gallery for one of my project which used ExtJS & ASP.Net MVC. The gallery consisted of many components, and I will explain the multiple image file upload functionality used in this gallery.


There are many ExtJS plugins already available for file upload that uses flash. One of my requirements was to avoid flash in my project. So, I could not use plugins like
Awesome uploader or UploadForm. So, if you need some fancy looking component & functionality, I suggest you have a look at them as well!

Here I have a simple uploader form that can be used for any server side. I will be using ASP.Net MVC. I have clean URLs as my application follows REST. Let’s have a look at the javascript first:
UploaderWindow =  Ext.extend(Ext.Window,{
    title: 'Upload Window',
 closeAction: 'close',
 id: 'upload-window',
 folderID: null,
 initComponent : function() {
  
  // Upload Form
  var uploadForm = new Ext.form.FormPanel({
   id: 'upload-form',
         fileUpload: true, 
         frame: true,  
   border: false,      
         bodyStyle: 'padding: 10px 10px 0 10px;',
   labelWidth: 50,
   defaults: {
          anchor: '100%'
         },          
   items: [{
             xtype: 'hidden',
             name: 'fieldCount',
    id: 'fieldCount',
    value: 0             
   },{
    xtype: 'hidden',
    name: 'folderID',
    id: 'folderID',
    value: 0
   },{
             xtype: 'fileuploadfield',
             emptyText: 'Select an image',
             fieldLabel: 'Image',
             name: 'file0'            
   }],
   buttons: [{
    text: 'Add File',
    iconCls: 'add_icon',
    handler: function(button,event) {
      
     var fIndex = parseInt(uploadForm.findById('fieldCount').getValue()) + 1;
     uploadForm.add(newField('file' + fIndex));
     uploadForm.findById('fieldCount').setValue(fIndex);
      
     uploadForm.doLayout();
            
    }
   },{
    text: 'Upload',
    handler: function(button, event){
     
     if (uploadForm.getForm().isValid()) {
      uploadForm.getForm().submit({
       url: '/Gallery/Upload',
       waitMsg: 'Uploading your photo...',
       success: function(form, o){        
        alert('Successfuly uploaded!');
       },
       failure: function(form, o){
        alert('Error in uploading the files');
       }
      });
     }
    }
   },{
    text: 'Cancel',
    handler: function() {
     var win = Ext.getCmp('upload-window');
     win.close();
    }
   }]
  });
  
  // Initial Configuration for the window
  var initConfig = {
   resizeable: false,
   modal: true,
   frame: true,
   width: 400,
   autoHeight: true,
   items: [uploadForm]
  };
  
  Ext.apply(this, Ext.apply(this.initialConfig, initConfig));
        UploaderWindow.superclass.initComponent.call(this);
 },
 onRender: function(){
  var fidField = this.upForm.findById('folderID');
  fidField.setValue(this.folderID); 
  UploaderWindow.superclass.onRender.apply(this, arguments);
 } 
});
I have extended Ext.Window class to create my component. The window provides all the controls necessary to upload multiple files onto the server. The upload form is basically embedded within the window. This helps in reuse of the entire component and also helps in customization. In the new component, we have some custom parameters. Once, such parameter is folderID (the default value is null). But when the upload window is created, I would pass a real value. On the server side, the uploaded images are stored according to the folderID passed.



The initComponent method is used to initialize the component. I have the form panel and its elements defined here. Note that I a hidden field to hold the number of files being uploaded (fieldCount) and is set to zero. I also have a field to hold the folder information. This hidden field is populated when the window is instantiated. The file selection functionality is provided by the well known ExtJS component: FileUploadField.

Each time the user click on “Add File” button, we create a new element of the type FileUploadField. This is done with the help of newField method:
function newField(name) {
    var rulesField = new Ext.ux.form.FileUploadField({
        name: name,
        emptyText: 'Select an image',
        fieldLabel: 'Image'
    });
    return rulesField;
}
Now, let’s have a look at the server side code. Our server side is accessed through the URL /Gallery/Upload and the method will be obviously POST. One of my requirements was to upload only images so; I added a simple check for the file extension on the server side. You could do the same on the client side as will. Here is the server side code:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Upload()
{
    string[] supportedTypes = new string[]{ "png", "gif", "jpg", "jpeg" };
    int count = int.Parse(Request.Params["fieldCount"]);
    int folderID = int.Parse(Request.Params["folderID"]);
    
    try
    {
        for (int i = 0; i <= count; i++)
        {
            HttpPostedFileBase postedFile = Request.Files["file" + i];
            if (postedFile != null)
            {
                string x = Path.GetExtension(postedFile.FileName);
                if (supportedTypes.Contains(x.TrimStart('.')))
                {
                   // Process the image
                } else {
                   // document not supported!
                }
            }
        }
        
    }
    catch (Exception e)
    {
        
    }
}
Improvements: There is always space for improvements. You can go ahead with lots of modifications to this component. By end of the day, I had lot of changes. Few improvements are:
  1. Removing added files from the form. 
  2. Client side validations.
  3. Option for entering meta data for the images being uploaded.
  4. Progress bar like other components mentioned above. .. etc 
Your comments are welcome. Enjoy coding! :)

Read other ExtJS related articles!

March 30, 2010

How To configure Apache log4net for ASP.Net

Apache log4net is a tool that helps programmer to log outputs to a variety of output targets. Its basically a port of log4j framework and can be used with all types of .Net applications. In this post, we will see how to configure and start using the logging framework in an ASP.Net web application.

You can download the framework from Apache site. Once downloaded, you need to add the reference of Log4net.dll to the project.

Configuring the logging framework to work with your web application can be done by 3 simple steps:

Step 1: Update web.config file
In the web.config file, you will need to add a new section under configSections tag. Notice that you will already have some section in sectionGroup tag. Do not place the new tag in them as this will lead to build errors. You need to add the following:


<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false" />

Step 2: Configure log4net
Next we need to provide some configurations to log4net. In our example, we are going to store all the logs in a file. You may refer the documentation for other Appenders available. Below is my log4net configuration:
<log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="D:\\Data\\logs\\log.txt" />
      <appendToFile value="true" />      
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message %newline" />
      </layout>
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="FileAppender" />
    </root>
  </log4net>
There are different ways of presenting this configuration to our framework. You can store the configuration in a separate xml file or use web.config to store it. In this example, I am storing it in web.config. just after ending the configSections tag, I have my log4net configurations. Now, we are ready to start using the logging framework.

Step 3: Start using log4net
To start using log4net, our web application should read the configurations. To do so, need to inform log4net to configure the logging environment. This is done with the help of the statement given below:
log4net.Config.XmlConfigurator.Configure();
I would recommend you add this to Application_Start method in Global.asax so that the logging environment is ready at the start of the applications. Inorder to log any infomation you need to get an instance of the Logger. This is done with the help of GetLogger method as shown below:
private static readonly ILog log = LogManager.GetLogger(typeof(MyclassName));
And finally, you just need to call log.Info, Debug etc methods to log you messages.

March 20, 2010

XML Transformation using C#

XML is now heavily used by developers for describing, transporting and storing data. XSLT is used to transform these XML files into different formats like HTML, XML, PDF and others. In my current project, my requirements are to generate XML and HTML. Here, I will explain how to transform XML file using C#.


Microsoft’s .Net framework provides us with a rich library. It supports XML document manipulation out of the box. All you need to do is use the necessary namespaces:


  • System.Xml
  • System.Xml.XPath
  • System.Xml.Xsl
I have created a simple class for my transformation activates. Below is the complete code:
public class Transformer
{
    private string xmlPath;
    public string xmlFilePath
    {
        get
        {
            return xmlPath;
        }
        set
        {
            xmlPath = value;
        }
    }

    private string xslPath;
    public string xslFilePath
    {
        get
        {
            return xslPath;
        }
        set
        {
            xslPath = value;
        }
    }

    private string htmlPath;
    public string htmlFilePath
    {
        get
        {
            return htmlPath;
        }
        set
        {
            htmlPath = value;
        }
    }


    public void xsltTransform()
    {
       XPathDocument xmlDoc = new XPathDocument(xmlPath);
       XslCompiledTransform xsltDoc = new XslCompiledTransform();

       xsltDoc.Load(xslPath);    

       XmlTextWriter writer = new XmlTextWriter(htmlPath, System.Text.Encoding.UTF8);       
       xsltDoc.Transform(xmlDoc, writer);
       writer.Close();
    }   
}
Lets staight way go to the xsltTransform method. Notice that, I need to set some of my class propeties; xmlPath, xslPath and htmlPath before I call the xsltTransform method.

First, I create a XPathDocument. This class provide a fast read only representation of the XML document. Next I need to load the stylesheet file. I create an instace of XslCompliedTrasform class to perform the transformation. The stylesheet is loaded using the Load method.

Now we are ready for the transformation. You can transform by call the Transform method. The method has over 15 overloads, so you will have to select the most appropriate for you. In my case, I am saving the output as a file to a specific location. I am using XmlTextWriter to do the task and provides the save to location and encoding type as construction parameters.

Here is the sample code:
Transformer tx = new Transformer();
tx.xmlFilePath = "D:\\Pragma\\data\\product.xml";
tx.xslFilePath = "D:\\Pragma\\xsl\\product.xsl";
tx.htmlFilePath = "D:\\Pragma\\output\\product.html";
tx.xsltTransform();
I suggest you try other overloaded methods available for Transform method. That’s all for now, you can expect few more .Net articles in the coming week.