European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Hosting - Amsterdam :: Read E Mails from ASP.NET

clock May 21, 2012 08:20 by author Scott

This article Illustrate How to read mails from ASP.Net. Using POP commands you can access you email inbox from ASP.Net. Basic POP commands are USER, PASS, LIST, QUIT, RETR.
More details POP command help you can check these links

//Creating Object for POPHelper
//Parameters are Gmail,Yahoo or MSN Pop Server,
//Port number
//bool isSSL
POPHelper objPopHelper = new POPHelper("pop.gmail.com", 995, true);
objPopHelper.UserName = "Your Gmail Username eg:[email protected]";
objPopHelper.Password = "GmailPassword";
objPopHelper.Connect();
GridView1.DataSource = p.DataSource;
GridView1.DataBind();



Code Of Connect Method

public void Connect()
        {
            string response = string.Empty;
            ArrayList arrList = new ArrayList();
            try
            {
                //Connect to Host server
                #region Connect Host
                TcpClient _tcpClient = new TcpClient();
                try
                {
                    _tcpClient.Connect(_hostname, _port);
                    //if login is ssl
                    if (_isSsl)
                    {
                        _stream = new SslStream(_tcpClient.GetStream());
                        ((SslStream)_stream).AuthenticateAsClient(_hostname);
                    }
                    else
                    {
                        _stream = _tcpClient.GetStream();
                    }
                }
                catch (Exception ex)
                {
                    throw new POPCommandException("Connection to " + _hostname + " Port: " + _port + " failed. Error Details"+ex.Message);
                }
                #endregion
                // Send POP Commands (USER, PASS, LIST) to Host
                #region POP Commands
                _streamWriter = new StreamWriter(_stream, Encoding.ASCII);
                _streamReader = new StreamReader(_stream, Encoding.ASCII);

                //POP command for send Username
                _streamWriter.WriteLine(POPCommands.USER.ToString()+" "+ UserName);
                //send to server
                _streamWriter.Flush();

                //POP command for send  Password
                _streamWriter.WriteLine(POPCommands.PASS.ToString() + " " + Password);
                //send to server
                _streamWriter.Flush();

                //POP command for List mails
                _streamWriter.WriteLine(POPCommands.LIST.ToString());
                //send to server
                _streamWriter.Flush();
                #endregion
                //Read Response Stream from Host
                #region Read Response Srteam
                //Read Response Stream
                response = null;
                string resText = string.Empty;
                while ((resText = _streamReader.ReadLine()) != null)
                {
                    if (resText == ".")
                    { break; }
                    if (resText.IndexOf("-ERR") != -1)
                    { break; }
                    response += resText;
                    arrList.Add(resText);
                }
                #endregion
                //Binding Properties
                #region Bindings
                //Bind Message count
                BindMailCount(arrList);
                //mails returns List
                _mail = ReadMail(messagecount);
                //get  mails Subjects returns List
                _mailsub = FilterContent(_mail,FiltersOption.Subject);
                _from = FilterContent(_mail, FiltersOption.From);
                _to = FilterContent(_mail, FiltersOption.To);
                SetDataSource(_mailsub, _from);
                #endregion
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
            }
        }


Class Diagram of POPHelper




Reading Mails Using POP Command RETR from ASP.NET

private List ReadMail(int Count)

        {
            List lst = new List();
            try
            {
                for (int i = 1; i <= Count; i++)
                {
                    _streamWriter.WriteLine(POPCommands.RETR+" " + i.ToString());
                    _streamWriter.Flush();
                    string resText = string.Empty;
                    while ((resText = _streamReader.ReadLine()) != null)
                    {
                        if (resText == ".")
                        { break; }
                        if (resText.IndexOf("-ERR") != -1)
                        { break; }
                        lst.Add(resText);
                    }
                }               

            }
            catch(Exception ex)
            {
                errors.Add(ex.Message);
            }
            return lst;
        }

Enumerates for Filer message subject and From Address and ToAddress



Method for Filer Content

private List FilterContent(List Mails,FiltersOption filter)

        {
            List filterItems = new List();
            try
            {
                for (int i = 0; i < Mails.Count; i++)
                {
                    if (Mails[i].StartsWith(filter.ToString() + ":"))
                    {
                        string sub = Mails[i].Replace(filter.ToString() + ":", "");
                        filterItems.Add(sub);
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
            }
            return filterItems;
        }

Creating DataSource for GridView

private DataTable SetDataSource(Listsubject,Listsender)
        {
            int messageCount = messagecount;
            dataTab = new DataTable();
            DataRow drow;
            DataColumn Sender = new DataColumn("Sender", typeof(string));
            DataColumn Subject = new DataColumn("Subject", typeof(string));
            dataTab.Columns.Add(Sender);
            dataTab.Columns.Add(Subject);
            for (int i = 0; i < subject.Count; i++)
            {
                drow = dataTab.NewRow();
                dataTab.Rows.Add(drow);
                dataTab.Rows[i][Sender] = sender[i].ToString();
                dataTab.Rows[i][Subject] = subject[i].ToString();
            }
            return dataTab;
        }



European ASP.NET 4 Hosting - Amsterdam :: How to Solve Error - ASP.NET 4.0 has not been registered on the Web server

clock April 25, 2012 08:07 by author Scott



The above error message indicate that you haven’t configured your ASP.NET 4 on your IIS. To configure IIS7.0 to use ASP.NET 4, please follow this steps:


- Open command prompt under Administrative privileges.

- Navigate to this location C:\Windows\Microsoft.NET\Framework\v4.0.30319.
- Locate aspnet_regiis.exe file.
- Run the utility with –i switch to register ASP.NET 4.0 with IIS7



And you can see it will work now.



European ASP.NET 4 Hosting :: How to Redirect From domain.com to www.domain.com in ASP.NET

clock February 21, 2012 07:35 by author Scott

If you want to redirect from domain.com to www.domain.com in asp.net application, then you can do it through IIS settings, but you can do it through code file also. You can write the code in the global.asax file in the Application_BeginRequest method.

void Application_BeginRequest(object sender, EventArgs e)
    {
        string FromHomeURL = "http://yourdomain.com";
        string ToHomeURL = "http://www.yourdomain.com";


       if (HttpContext.Current.Request.Url.ToString().ToLower().Contains(FromHomeURL))
        {
            HttpContext.Current.Response.Status = "301 Moved Permanently";
            HttpContext.Current.Response.AddHeader("Location",
            Request.Url.ToString().ToLower().Replace(FromHomeURL, ToHomeURL));
        }
}



European ASP.NET 4 Hosting - Amsterdam :: Call ASP.NET Page Methods using your own AJAX

clock February 17, 2012 07:18 by author Scott

Microsoft has introduced JQuery as a primary javascript development tool for client end application. Even though there is a number of flexibility in ASP.NET AJAX applications, many developers do seek place to actually call a page using normal AJAX based application. In this post I will cover how you can invoke an ASP.NET page method directly from your own AJAX library.

What are page methods?

A Page method is a method that is written directly in a page. It is generally called when the actual page is posted back and some event is raised from the client. The pageMethod is called directly from ASP.NET engine.


What is a WebMethod?

A WebMethod is a special method attribute that exposes a method directly as XML service. To implement PageMethod we first need to annotate our method as WebMethod.

Steps to Create the application :

1. Start a new ASP.NET Project.
2. Add
JQuery to your page. I have added a special JQuery plugin myself which stringify a JSON object. The post looks like below :


(function ($) {
$.extend({
toJson: function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"' + obj + '"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof (v);
if (t == "string") v = '"' + v + '"';
else if (t == "object" && v !== null) v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
}
});
// extend plugin scope
$.fn.extend({
toJson: $.toJson.construct
});
})(jQuery);

The code actually extends JQuery to add a method called toJSON to its prototype.


3. Add the server side method to the Default.aspx page. For simplicity we actually return the message that is received from the client side with some formatting.

[WebMethod]
public static string DisplayTime(string message)
{
// Do something

return string.Format("Hello ! Your message : {0} at {1}", message,
DateTime.Now.ToShortTimeString());
}

Remember : You should make this method static, and probably should return only serializable object.

4. Add the following Html which actually puts one TextBox which takes a message and a Button to call server.

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<p>
Write Your message Here : <input type="text" id="txtMessage" />
</p>
<p>
<input type="button" onclick="javascript:callServer()" value="Call Server" />
</p>
</asp:Content>

Once you add this html to your default.aspx page, add some javascript to the page. We add the JQuery and our JSONStringify code to it.

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Scripts/JSONStringify.js" type="text/javascript"></script>

<script type="text/javascript">
function callServer() {
var objdata = {
"message" : $("#txtMessage").val()
};
$.ajax({
type: "POST",
url: "Default.aspx/DisplayTime",
data: $.toJson(objdata),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (xhr, ajaxOptions) {
alert(xhr.status);
}
});
}
</script>

The above code actually invokes a normal AJAX call to the page. You can use your own library of AJAX rather than JQuery to do the same. On success, it returns the serializable object to msg.d.



European ASP.NET 4 Hosting - Amsterdam :: Application pool identity of IIS 7.x as a SQL Server login to use

clock February 15, 2012 07:46 by author Scott

If we develop an ASP.NET (MVC) Web site using the ASP.NET Development Server and SQL Server database in use does, at first everything easily.

If, however, for the development of a "real" IIS 7.x, eg Windows 7, we obtain the database access, the following exception:



The solution is pretty simple - you have the Application Pool Identity "IIS AppPool \ mvcapp" assign to the users in the database.

Unfortunately, this does not do this with the SQL Server Management Studio.

Although you can insert the name of the Application Pool Identity



and be validated by "Check Names"



After clicking "OK", but you get the error message that the user was not found:



A solution to generate the login via script:

CREATE LOGIN [IIS AppPool \ MyPool] FROM WINDOWS WITH  DEFAULT_DATABASE = [master] USE [mydatabase] CREATE USER [IIS AppPool \ MyPool] FOR LOGIN [IIS AppPool \ MyPool]  

Then you can assign the SQL Server Management Studio, the permissions so that the website works with the Application Pool Identity.



European Ajax Hosting - Amsterdam :: 3 Mistakes to Avoid when Using jQuery with ASP.NET AJAX

clock February 7, 2012 08:16 by author Scott

In this post, I’m going to detail three of the problems that were discovered as a result of those previous two posts:

-          An extra requirement when making a read-only request to IIS6+.

-          An oddity in Internet Explorer 7′s XmlHttpRequest class.

-          A common mistake when passing JSON parameters through jQuery.

Finally, I’ll suggest what I now believe to be a best practice usage, taking all of these issues into account.

Security requirements when POSTing to IIS

This error message was the most common problem that was reported:

Length Required

The underlying issue is that most installations of IIS6+ require a content-length be provided with all POST requests, even if there is no content (POST data).

The content-length for a request with no data should be 0, but jQuery doesn’t set that header automatically unless there is a data parameter. Since ASP.NET AJAX’s JSON serialized services require a POST request, this becomes a stumbling block for read-only requests.

The easiest way I’ve found to work around this is to use an empty JSON object as a parameter on read-only requests. For example, if you were calling a page method:

$.ajax({
  type: "POST",
  url: "PageMethod.aspx/PageMethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});

This will cause jQuery to correctly set a content-length of 2, while your web service or page method will happily ignore the empty parameter and treat the request as read-only.

A problem with Internet Explorer and XmlHttpRequest

Previously, to call ASP.NET AJAX services with jQuery, I suggested this usage:

$.ajax({
  type: "POST",
  url: "WebService.asmx/WebMethodName",
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Content-type",
                         "application/json; charset=utf-8");
  },
  dataType: "json"
});

The reason for the beforeSend delegate is due a quirk in jQuery which causes it to send a specified content-type only if there is also a data parameter specified.


For security reasons, ASP.NET AJAX will not provide a JSON serialized response unless the proper content-type is provided. By using the beforeSend delegate as shown, the content-type will be manually set on the XmlHttpRequest object, before the request.

However, the new XmlHttpRequest class in Internet Explorer 7 doesn’t implement setRequestHeader very intuitively. Instead of setting the specified header, it appends the value.

This becomes a problem when you make a request that includes a data parameter. When POST data is provided, jQuery will automatically set the content-type to its default of application/x-www-form-urlencoded. In the beforeSend delegate, the required application/json; charset=utf-8 will be appended after jQuery’s default.

End result? Because this amalgamation of content-types isn’t what ASP.NET AJAX expects, the web service will not return JSON serialized content and jQuery will be unable to parse it.

Solution? If you’re sending data in your request, use jQuery’s contentType parameter to set the content-type, so that the default is never added:

$.ajax({
  type: "POST",
  url: "WebService.asmx/WebMethodName",
  data: "{'fname':'dave', 'lname':'ward'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});

JSON, objects, and strings

ASP.NET AJAX script services and page methods understand and expect input parameters to be serialized as JSON strings. These parameters are parsed out of the POST data and used as arguments to the method you’ve called.

However, if you directly provide a JSON object as the data parameter for an $.ajax call, jQuery will attempt to URL encode the object instead of passing it on to your web service.

Take this sample request, for example:

$.ajax({
  type: "POST",
  url: "WebService.asmx/WebMethodName",
  data: {'fname':'dave', 'lname':'ward'},
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});

Because that data parameter is a valid object literal, calling the web service this way won’t throw any JavaScript errors on the client-side. Unfortunately, it won’t have the desired result either. Instead of passing that object through to the web service as JSON, jQuery will automatically URL encode it and send it as:

fname=dave&lname=ward

To which, the server will respond with:

Invalid JSON primitive: fname.

This is clearly not what we want to happen. The solution is to make sure that you’re passing jQuery a string for the data parameter, like this:

$.ajax({
  type: "POST",
  url: "WebService.asmx/WebMethodName",
  data: "{'fname':'dave', 'lname':'ward'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});

It’s a small change in syntax, but makes all the difference. Now, jQuery will leave our JSON object alone and pass the entire string to ASP.NET for parsing on the server side.

Taking these three caveats into account, I think this is the best practice for calling read-only ASP.NET AJAX web services via jQuery:

$.ajax({
  type: "POST",
  url: "ServiceName.asmx/WebMethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do interesting things here.
  }
})
;

When consuming web services that require parameters, the usage is similar. Just make sure that you’re passing a JSON object in a string:

$.ajax({
  type: "POST",
  url: "ServiceName.asmx/WebMethodName",
  data: "{'fname':'dave','lname':'ward'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do magic here.
  }
});

In either of these cases, substitute PageName.aspx for ServiceName.asmx and PageMethodName for WebMethodName if you want to call a page method instead of a web service.



European ASP.NET 4 Hosting :: How to Set Authentication Rules in Web.Config

clock February 2, 2012 06:20 by author Scott

I have seen so many people asking again and again how to give allow access to particular page to a person or roles. So I thought its good to put this in one place. I will discuss how to configure web.config depending on the scenario.

We will start with a web.config without any authorization and modify it on case by case bassis.

No Authorization

We will start with the root web.config without any authorization.

<configuration>

<system.web>
<authentication mode="Forms">
</authentication> </system.web>
</configuration>

Deny Anonymous user to access entire website

This is the case when you want everybody to login before the can start browsing around your website. i.e. The first thing they will see is a login page.

<system.web>
<authentication mode="Forms">
</authentication>
<authorization>
<deny users="?"/> //will deny anonymous users </authorization>
</system.web>

The above situation is good when user don't have to register themselves but instead their user account is created by some administrator.

Allow access to everyone to a particular page

Sometimes you want to allow public access to your registeration page and want to restrict access to rest of the site only to logged / authenticated users .i.e. do not allow anonymous access. Say your registration page is called register.aspx in your site's root folder. In the web.config of your website's root folder you need to have following setup.


<configuration>
<system.web>
<
authentication mode="Forms"/>

<authorization> <deny users="?"/>  //this will restrict anonymous user access
</authorization>
</system.web>
<location path="register.aspx"> //path here is path to your register.aspx page e.g. it could be ~/publicpages/register.aspx
<system.web>
<authorization>
<allow users="*"/> // this will allow access to everyone to register.aspx
</authorization>
</system.web>
</location>
</configuration>

Till now we saw either allow users or to authenticated users only. But there could be cases where we want to allow particular user to certain pages but deny everyone else (authenticated as well as anonymous). 

To allow access to particular user only and deny everyone else

Say you want to give access to user "John" to a particular page e.g. userpersonal.aspx and deny all others the location tag above should look like below:

<location path="userpersonal.aspx">

<system.web>
<authorization>
<allow users="Scott"/> // allow Scott ..note: you can have multiple users seperated by comma e.g. Scott,Gary,etc
<deny users="*"/>  // deny others
</authorization>
</system.web>
</location>

Allow only users in particular Role

Here I am will not show how to setup roles. I assume you have roles managment setup for users. We will see now what needs to be done in web.config to configure authorization for a particular role. e.g You have two roles. Customer and Admin and two folders CustomerFolder and AdminFolder. Users in Admin role can access both folders. Users in Customers role can access only CustomerFolder and not AdminFolder. You will have to add location tags for each folder path as shown below:

<location path="AdminFolder">
<system.web>
<authorization>
<allow roles="Admin"/> //Allows users in Admin role
<deny users="*"/> // deny everyone else
</authorization>
</system.web>
</location>
<location path="CustomerFolder">
<system.web>
<authorization>
<allow roles="Admin, Customers"/> //Allow users in Admin and Customers roles
<deny users="*"/> // Deny rest of all
</authorization>
</system.web>
</location>

Alternate way - using individual web.config for each Folder

Alternative to above mentioned method of using <location../> tag, you can add web.config to each folder and configure authorization accordingly almost similar to one show above but not using location tag. Taking same eg. as above. Add web.config to both the folders - AdminFolder and CustomerFolder.

Web.config in AdminFolder should look like:

<configuration>
<system.web>
<authorization>
<allow roles="Admin"/> //Allows users in Admin role
<deny users="*"/> // deny everyone else
</authorization>
</system.web>
</configuration>
Web.config in CustomerFolder should look like: 
<configuration>
<system.web>
<authorization>
<allow roles="Admin, Customers"/> //Allow users in Admin and Customers roles
<deny users="*"/> // Deny rest of all
</authorization>
</system.web>
</configuration>

Images and CSS files

Say you have all your images and CSS in a seperate folder called images and you are denying anonymous access to your website. In that case you might see that on your login page you cannot see images(if any) and css(if any) applied to your login page controls.

In that case you can add a web.config to the images and css folder and allow access to everyone to that folder. So your web.config in images folder should look as below:

<configuration>
<system.web>
<authorization>
<allow users="*"/> //Allow everyone
</authorization>
</system.web>
</configuration>

Common Mistakes

I have seen people complaining that they have setup their roles correctly and also made entry to their web.config but still their authorization doesn't work. Even they have allowed access to their role that user cannot access particular page/folder. The common reason for that is placing <deny../> before <allow ../>.

Say the web.config from AdminFolder as we have seen before is something like this:

//This web.config will not allow access to users even they are in Admin Role 

<configuration>
<system.web>
<authorization>
<deny users="*"/> // deny everyone else
<allow roles="Admin"/> //Allows users in Admin role
</authorization>
</system.web>
</configuration>

Since the authorization is done from top to bottom, rules are checked until a match is found. Here we have <deny users="*"/> first and so it will not check for allow any more and deny access even if in Admin role.

So PUT all allows BEFORE ANY deny.

NOTE: deny works the same way as allow. You can deny particular roles or users as per your requirement. 



European ASP.NET Hosting :: How to Solve Unable to make the session state request to the session state server

clock January 6, 2012 07:23 by author Scott

In this article I will explain how to solve Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same. To describe it, please see this image below:



To solve this error I started Asp.net state service from services to start the service just follow below steps

Go to Control Panel ---> Administrative Tools ---> Computer Management ---> Services and Applications ---> Services 

Now Select Asp.Net State Service

After that Right Click on Asp.net State Service and choose “Start” option.



After start the service your problem will solve automatically. Hope it helps



European ASP.NET Hosting :: Create Membership tables in another database than the standard aspnetdb.mdf

clock January 4, 2012 07:42 by author Scott

When you start creating a new ASP.NET 2.0 site with Visual Studio 2005 or Visual Web Developer Express (VWD) and want to start using it you'll notice that a new file in the App_Data folder gets created besides your own database, namely the aspnetdb.mdf file. This extra database holds all the tables and stored procedures to let Membership, Roles, Profile etc run smoothly.

However a problem arises when you don't want to use that dedicated new database when you want to deploy to your live webserver, certainly not when you use a host that only offers one database and charges you extra for another database. Luckely you can control things more when using the dedicated aspnet_regsql tool that ships with the .NET 2.0 framework.

What I'm about to describe in this article is how to use that tool to generate a SQL script that you can use to run on your other database with a tool like SQL Server Management Studio (SSMS). In this example I'll be using the installed Northwind database on my localhost developer machine.

Just start up a new DOS box by going to Start | Run and type in cmd followed by enter. In Windows Vista you push the blue windows logo button and in the field with the text Start Search you type in cmd followed by ctrl + shift + enter. The reason for that combination is that you must run it under Admin privileges or else the to be generated file doesn't get writed to disk.
A new DOS box will appear and you just navigate to the following directory/folder:

Windows\Microsoft.NET\Framework\v2.0.50727\

If you're not used to using DOS you can navigate to it by typing this in the DOS box: cd \windows\Microsoft.net\framework\v2.0.50727 followed by enter.


Then you type in this line: aspnet_regsql.exe -E -S localhost -d Northwind -A all -sqlexportonly c:\membership.sql again followed by enter. At the location c:\ a new file gets generated: membership.sql.



The Northwind name in the parameter list is later on used to set the db name in the generated sql file: SET @dbname = N'Northwind'

Once generated you can use/tweak this file to be used in SSMS to get executed and to install everything needed in the database.

Ok, up untill now we focussed on getting everything ready on the database side but we also have to let our ASP.NET 2.0 application know that we're pointing out to another database than the default one. The solution for this is to override the default settings for the LocalSqlServer connectionstring which can be found in the machine.config file.

<add name="LocalSqlServer"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />

To override that you open the web.config file in your application which can be normally found in the root of the application. Go to the <connectionStrings> element.


<connectionStrings>
    <remove name="LocalSqlServer"/>
    <add name="LocalSqlServer" connectionString="The connection string to your
                         (new) database" providerName="System.Data.SqlClient" />
</connectionStrings>

Notice the second line where you call the remove statement. This is needed in order to be able to override the LocalSqlServer connection string!

If you're in need of a little help to get your connection string right there's a dedicated site: http://www.connectionstrings.com/.

If you need ASP.NET hosting with SQL database, please visit our site at http://www.hostforlife.eu. If you have any questions, please feel free to email us at [email protected].



European ASP.NET 4 Hosting :: How to Making HTML5 Video work with IIS Express

clock January 3, 2012 15:10 by author Scott

Happy New Year 2012!!! Hope this year will bring happiness, success, and prosperiority.

In this tutorial, I will show how to making HTML 5 video work with IIS Express. Ok, first I created a simple MVC Application with “File – New - Project – ASP.NET MVC 3 Web Application” and left the defaults to create an Application.  I added a videos folder and added a H.264 encoded mp4 video (one of the supported HTML5 Video formats) inside the folder.

Then, I added the following line of code in the “Index.cshtml” file.

<video src="@Url.Content("~/Videos/video.mp4")" id="myVideo" controls ></video>



All I got was the above.  Basically a broken link.  I verified that the path is right and the video is indeed playable on Windows Media Player etc.,

The issue was that, since by default Visual Studio uses the ASP.NET Development Server and the ASP.NET Development Server doesn’t have the flexibility to configure MIME types,  It doesn’t understand the video format and hence could not play.  When I ran the application on IE9 and checked the Network Tab of the Developer Toolbar, all I got was what you see below



I switched the Project to use IIS Express using “ProjectName” – Right Click – Properties – Web Tab



Still had the same result.  Since IIS Express also doesn’t have the MIME Type to play video, configured by default, it couldn’t recognize the video and couldn’t play it.

The simple option is to configure it to use the “Actual IIS” (in the above screen, remove the check from “Use IISExpress”) which can play the video.

But, thankfully
this blog post has steps on how to configure MIME types for IIS Express.  Only thing is, I had to change it for configuring the MIME type for playing MP4 video.

So, the steps are

1. Click on Start button
2. Type CMD
3. Right click on the CMD that is listed and choose “Run as Administrator”
4. Do a cd to navigate to the IIS Express directory CD “Program Files (x86)”\”IIS Express”
5. And then run the following command

appcmd set config /section:staticContent /+[fileExtension='.mp4',mimeType='vieo/mp4']

That’s it.  When I re-ran the application, it could play the video.



Please note, I was unable to configure or figure out how to do it for the ASP.NET Development Server.  So, if we need to play HTML5 Video from Visual Studio we either need to use IIS Express or use the full fledged IIS.  And from the performance and configuration perspective IIS Express offers a lot more than ASP.NET Development Server and hence it makes more sense to use IIS Express for local development.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in