Wednesday, 23 April 2014

MVC Tips : Play or display video in ASP.NET MVC using HTML5

Click Here to Download PlayVideoInMVC.zip

It is very easy to play or display video in ASP.NET MVC using HTML5. We can do this using custom action filter in MVC. We can play various files like MP4, Ogg, WebM, etc. format.

Here are step by step tutorial to play video in ASP.NET MVC using HTML5.

Here is example for this.

In this example we are taking .MP4 file to play in browser.

STEP : 1
Create an ASP.NET MVC Empty application in visual studio. Give project name like 'PlayVideoInMVC'.

STEP : 2
After creating empty application create new folder 'VideoDataFile' after that add video files in this folder.

STEP : 3
Now we are going to add custom action filter. Add new folder 'CustomDataResult' and add new class file 'VideoDataResult.cs'. In this class we need to inherit 'ActionResult' class and override 'ExecuteResult' method.

In method we write code like read video file and send response back to controller using "context.HttpContext.Response.BinaryWrite" method.

Below is code for 'VideoDataResult.cs' file :

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;

namespace PlayVideoInMVC.CustomDataResult
{
    public class VideoDataResult : ActionResult
    {
        /// <summary>
        /// The below method will respond with the Video file
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            
            var strVideoFilePath = HostingEnvironment.MapPath("~/VideoFiles/Test2.mp4");
            
            context.HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=Test2.mp4");

            var objFile = new FileInfo(strVideoFilePath);

            var stream = objFile.OpenRead();
            var objBytes = new byte[stream.Length];
            stream.Read(objBytes, 0, (int)objFile.Length);
            context.HttpContext.Response.BinaryWrite(objBytes);

        } 
    }
}

STEP 4 :
Now we are going to add our controller that can take care of Video data result. Now add one MVC controller and name it 'VideoDataController' in 'Controller' folder.

Below is code for 'VideoDataController' file : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PlayVideoInMVC.CustomDataResult;
using System.Web.Mvc;

namespace PlayVideoInMVC.Controllers
{
    public class VideoDataController : Controller
    {
        //
        // GET: /VideoData/

        public ActionResult Index()
        {
            return new VideoDataResult();
        }

    }
}

STEP : 5
Now add new controller to view or display video name it 'ViewVideoController', after that add 'view' and in this 'view' add HTML5 video tag to play video in video player.

In this view we also add one download video link. This link allows to download video. On clicking of this link you will see the download file dialog box.

Below is the HTML markup of 'View' :

@{
    ViewBag.Title = "Index";
}

<h2>Play Video</h2>
<h3><a href="@Url.Action("Index", "VideoData")">Download Video</a> </h3>
<video width="320" height="240" controls autoplay="autoplay">
    <source src="@Url.Action("Index", "VideoData")" type="video/mp4">
</video>

We need to set 'src' property of video tag to get video data and play that. Now run the application with this URL 'http://localhost:[your port]/ViewVideo'. I ran this in chrome. You can run on any other HTML5 enabled browser.

Here is a very useful link to check that does your browser support HTML5 video and also which video format support.

Important : One important thing to note here is that we can use our custom action filter for two purposes, first to display video on browser and Second allow to download video file.

So the same controller serves two purposes. We can centralize our code by doing this.


Output :



Below are the books that you would like :

Wednesday, 26 March 2014

.Net Tips : Fill DataTable from another DataTable using LINQ with C#.Net and VB.Net example

You can fill DataTable from another DataTable using LINQ after doing LINQ operation.

This would be useful in condition like you need to perform some operation on DataTable using LINQ and get back result into another 'DataTable'. Means, you can filter and projection on one DataTable and get result in another DataTable.

We can achieve this by using 'CopyToDataTable' method of LINQ query result variable.

Here is example for this.
In this example we are taking one DataTable which contains product information like ID, name, etc. Now we get only those products which ID is greater than one by LINQ operation on this table and get result in another table using 'CopyToDataTable' method of LINQ query result variable.

Tuesday, 4 March 2014

.Net Tips : Create XML file from another XML file with selected Elements using LINQ with C#.Net and VB.Net example

You can create XML file from another file with selected elements from source XML file using LINQ. In this, we query the source XML file using LINQ and write or create new XML file.

Here is example for this. 
In this example we take one "Book.xml" file. In this file we have element like Title, Pages, ISBN and Auther. Now we are querying the "Book.xml" file to get only Title and ISBN of book and create another XML with data that contains only Title and ISBN element.

C#. Net Example :
        XDocument objDoc = XDocument.Load((Server.MapPath("Books.xml")));
        
        var objResults = new XElement("Results",
                         from b in objDoc.Element("Books").Elements("Book")
                         from t in b.Elements("Title")
                         from a in b.Elements("ISBN")
                         select new XElement("Result", t, a));

        StringWriter objSW = new StringWriter();

        //save to XmlWriter
        System.Xml.XmlWriterSettings objSettings = new System.Xml.XmlWriterSettings();
        objSettings.Indent = true;

        XDocument objNewDoc = new XDocument();
        System.Xml.XmlWriter objXMLWriter = System.Xml.XmlWriter.Create(objSW, objSettings);

        objResults.Save(objXMLWriter);
        
        objXMLWriter.Close();
        //Console.WriteLine(objSW.ToString());

        //save to file
        objResults.Save(Server.MapPath("Results.xml"));

VB.Net Examples :
        Dim objDoc As XDocument = XDocument.Load((Server.MapPath("Books.xml")))

        Dim objResults = New XElement("Results",
                                      From b In objDoc.Element("Books").Elements("Book")
                                      From t In b.Elements("Title") From a In b.Elements("ISBN") Select New XElement("Result", t, a))

        Dim objSW As New StringWriter()

        'save to XmlWriter
        Dim objSettings As New System.Xml.XmlWriterSettings()
        objSettings.Indent = True

        Dim objNewDoc As New XDocument()
        Dim objXMLWriter As System.Xml.XmlWriter = System.Xml.XmlWriter.Create(objSW, objSettings)

        objResults.Save(objXMLWriter)

        objXMLWriter.Close()
        'Console.WriteLine(objSW.ToString());

        'save to file
        objResults.Save(Server.MapPath("Results.xml"))

Output :


Below are the books that you would like :

Wednesday, 12 February 2014

.Net Tips : Convert DataTable object to list of class object using LINQ with C#.Net and VB.Net example

You can fill List of object from DataTable using LINQ. There are many situations where you need to get data from DB into data table and after that from data table to proper class object. We can do this easily with LINQ.

Here is example for this.
In this example we take one DataTable object which contains two columns 'product_id' and 'product_name'. This DataTable has many rows. Now we want to convert DataTable object into list of class object. We have one Class 'clsProduct' which has two property 'product_id' and 'product_name'. Now we transform DataTable object data in to list of clsProduct class object using LINQ.

Friday, 24 January 2014

MVC Tips : Implement IValidatableObject Interface for custom validation in ASP.Net MVC 4

Click Here to Download ImplementIValidateObjectInterfaceInMVC.zip Example.

We can validate model itself by implementing IValidatableObject Interface. For validation you need to implement 'Validate' method of IValidatableObject Interface.

Here is some difference from the attribute validation version.
  • In this for validation method is 'Validate' instead of 'IsValid' and also return type and parameter is different.
  • The return type for Validate is an IEnumerable<ValidationResult>, because the logic inside this method is validating the entire model and might need to return more than a single validation error.
  • No parameter is passed to Validate because you  can directly access model properties because this Validate method is inside model.

Here is example for this.

Thursday, 16 January 2014

.Net Tips : Attach and Raise events on XML document object with C#.Net and VB.Net example

You can attach events like 'onChanging' and 'onChanged' events on XML document object. These events raise when you 'ADD' or 'REMOVE' XML element from XML Document object.

First 'onChanging' event raise after that 'onChanged' event raise. In this event we get 'XObjectChangeEventArgs' class object. This object give us property like 'ObjectChange'. In this property we can know that which method is performed.

When we call 'Add' method we get 'Add' value in 'ObjectChange' property and when we call 'Remove' method we get 'Remove' value in 'ObjectChange' property.

Here is example on this.

Wednesday, 1 January 2014

MVC Tips : Custom Annotation validation in ASP.Net MVC 4

Click Here to Download CustomAnnotationInMVC.zip Example.

You can write your own custom annotations in MVC 4.
Here we can do custom validation using custom annotations. Custom annotations validation derive from the ValidationAttribute base class. This base class available in 'System.ComponentModel.DataAnnotations' namespace. ValidationAttribute class is abstract class.

For custom validation you need to write your own class and inherit ValidationAttribute class. After that, you need to override IsValid Method. IsValid Method has two parameters 'Value' and 'ValidationContext'.

  • Value : Which contains your data, which is going to validate.
  • ValidationContext : This parameter is very important. This content information like model object instance, model type friendly display name and other information
In this method you write your own logic for validate data and return result. If value is validate at that time you need to return this 'ValidationResult.Success' else you return result like 'return new ValidationResult(your custom error message)'