Limit File Upload size in ASP.NET Web applications

One of the problems in file upload is to check the file size before uploading to the server. It’s been a big problem for web developers to restrict the file upload, if it exceeds the given file size .

Now, we can restrict it before uploading to the server using simple JavaScript snippet. Thanks to latest browsers – Microsoft IE 10+, Chrome 21+, Firefox 15+ for making this happen.

Here is the code to do that -

Code Snippet
  1. <form id="form1" runat="server" enctype="multipart/form-data">
  2.     <div>
  3.         <asp:FileUpload runat="server" ID="fileUpload" />
  4.         <asp:Button runat="server" Text="Submit" OnClientClick="return Validate();" OnClick="FileUpload" />
  5.         <div id="Message"></div>
  6.     </div>
  7.     </form>
  8.     <script type="text/javascript" >
  9.         function Validate() {
  10.             var msg = "";
  11.             var bIsValid = true;
  12.             var uploadedFile = document.getElementById("<%=fileUpload.ClientID %>");
  13.  
  14.             if (uploadedFile.files[0].size > 512000) // greater than 512KB
  15.             {
  16.                 msg += "File Size is limited to 512 KB!";
  17.                 bIsValid = false;
  18.             }
  19.  
  20.             var ext = uploadedFile.value.substr(uploadedFile.value.indexOf(".") + 1, uploadedFile.value.length);
  21.             if (ext != "jpg" || ext != "png") {
  22.                 msg += "You can upload only .jpg or .png images!";
  23.                 bIsValid = false;
  24.             }
  25.             if (!bIsValid) {
  26.                 document.getElementById("Message").innerHTML = msg;
  27.                 return false;
  28.             }
  29.             //On Success
  30.             return true;
  31.         }
  32.     </script>

The above code may fail in browsers which doesn’t support HTML 5 features, so it’s better to validate at server end as well for additional security!

Code Snippet
  1. protected  void FileUpload(object sender, EventArgs e)
  2.       {
  3.           if (fileUpload.PostedFile.ContentLength > 512000)
  4.           {
  5.               return;
  6.           }
  7.       }

 

NOTE: The above JavaScript snippet can be used across the technologies including JSP, PHP etc.,

Happy Web Programming!!!

Posted in ASP.NET, JavaScript | Tagged , , , , , | Leave a comment

How to setup Android emulator to test mobile web apps

The real deal with Mobile web application development is testing it on multiple devices. So every one may not be able to buy all the mobile devices to test, especially with Android. Since we have many devices from multiple OEM’s and with different screen size, it’s not a feasible option to buy all devices and test. Thanks to Google for providing emulators to make our job easy!

I have already wrote an article on testing mobile web applications in Android Emulator, but it’s initial version of Android device and it’s depreciated now. So, i thought writing extension to that with latest tools available from Google. 

In this article, i will show you how to setup Android Emulator to test your mobile web applications on Windows OS [Since, more people looking for a solution on this platform Winking smile].

  • Download the Android SDK from this URL – Android SDK.

image

NOTE: There may be change of page layout in future, but i hope Google allow to download the Android SDK.

  • It gives you option to download x86 or x64 version. It’s up to you to choose the right version for you. NO CONSTRAINTS. The SDK contains all the required tools to get started with developing Android apps, anyway it’s out of topic.
  • Once you are done downloading, unzip it. You will see two folders and  SDK Manager.exe.

image

  • Click on the SDK Manager to launch. It launches the Android SDK Manager window.

image

  • Now click on Tools –> Manage AVDs…

image

  • It launches Android Virtual Device Manager window.

image

  • Now, we need to create a new Android Virtual Device, by clicking on New… button.
  • When you click on New… button, it launches Create New Android Virtual Device (AVD) window.

image

  • Enter AVD Name, select Device  and Target. In the Device dropdown, you will get all the devices with different screen sizes including Android Tablets.
  • Target has the recent Android Version list, which you can select the required one. Now, we have Android 4.2 Jelly Bean.

image

  • You can leave the rest of the fields to their defaults, which we are not going to mess up. If you wish to play around with other fields too, you are free to do that. Again NO CONSTRAINTS.
  • On clicking on OK button, it shows message box, which summarizes the configuration of out emulator.

image

  • Click OK button. Now the newly configured Android emulator is added to the list.

image

  • Now select the newly created emulator and click on Start… button.

image

  • It will invoke Launch Options dialog.

image

  • Click on Launch button, by leaving the options to their defaults! It will launch the emulator Smile

image

  • Now we are ready to test our mobile web application.
  • Launch the web browser in the emulator and test your applications!

image

NOTE: If you are testing your mobile web apps, that are deployed to local IIS, then you have to use IP Address instead of using localhost.

Happy mobile web application programming and testing!

Thanks!

Posted in Mobile | Tagged , , , , , , , | 3 Comments

Mobile Web Applications with ASP.NET WebForms

I have seen many people asking questions in forums about Mobile web application development using ASP.NET WebForms. So i planned to write a blog post on the same.

ASP.NET is a powerful web application development platform, allows to leverage most of the features in Mobile web application development. Now a days, mobile devices are capable of rendering HTML 5 content. Websites which works in desktop browser is rendering great in mobile browsers too. Mobile web browsing is rapidly increased and every one looking for ON THE GO solution!

Now, the question is, Can we convert the existing web application to Mobile web application?

Answer is YES. You can can do that. Just by adding the Viewport meta tag to the Head section of the webpage and you are done!

Viewport Meta tag
  1. <meta name="viewport" content="width=device-width" />

 

To know more about the Viewport meta tag, check this link – Viewport. This viewport meta tag works absolutely fine in all major mobile device browsers including –

  • Apple iPhone – Mobile Safari
  • Android(GingerBread, ICS, Jelly Bean) – Native browser, Google Chrome, Opera
  • WindowsPhone – IE9 and IE 10
  • BlackBerry – Native Browser

Sample Code

Code Snippet
  1. <%@ Page    Language="C#"
  2.             AutoEventWireup="true"
  3.             CodeBehind="Index.aspx.cs"
  4.             Inherits="MobileApp_WebForms.Index" %>
  5.  
  6. <!DOCTYPE html>
  7.  
  8. <html>
  9. <head runat="server">
  10.     <title>Mobile WebForms</title>
  11.     <meta charset="urf-8" />
  12.     <meta name="viewport" content="width=device-width" />
  13.     <style type="text/css">
  14.         body
  15.         {
  16.             font-family:Verdana;
  17.         }
  18.         label
  19.         {
  20.             width:100px;
  21.             float:left;
  22.             display:block;
  23.         }
  24.         input[type=text]
  25.         {
  26.             width:200px;
  27.         }
  28.         .content
  29.         {
  30.             width:350px;
  31.             margin:0px auto;
  32.         }
  33.         header
  34.         {
  35.             width:350px;
  36.             text-align:center;
  37.             font-size:15px;
  38.             font-weight:bold;
  39.         }
  40.         .button
  41.         {
  42.             width:350px;
  43.             text-align:center;
  44.         }
  45.     </style>   
  46. </head>
  47. <body>
  48.     <form id="form1" runat="server">
  49.     <div class="content">
  50.         <header>
  51.             Contact Us
  52.         </header>
  53.         <div>
  54.             <label>Name</label>
  55.             <asp:TextBox runat="server" ID="txtbox" />
  56.         </div>
  57.         <div>
  58.             <label>Email</label>
  59.             <asp:TextBox runat="server" ID="txtEmail" />
  60.         </div>
  61.         <div>
  62.             <label>Phone</label>
  63.             <asp:TextBox runat="server" ID="txtPhone" />
  64.         </div>
  65.         <div class="button">
  66.             <asp:Button Text="Send" runat="server"  />
  67.         </div>
  68.     </div>
  69.     </form>
  70. </body>
  71. </html>

Try the above code in a mobile browser and you will find the difference!

Next question is, How do we create a separate version of Mobile web application?

We can create stunning mobile specific web application using ASP.NET WebForms and when you access the web application from desktop browser it renders the general desktop web app and when you access it from Mobile browser it renders the mobile web app.

How we need to redirect the user to the respective web app, when user access from different devices? 

I explained the same in one of my earlier blog post – Detect the device and redirect in ASP.NET. That’s one way of doing it. We have few more ways to do the same.

  • JavaScript – By sniffing the UserAgent string and redirect to the appropriate web app – DetectMobileBrowsers
  • CSS 3 Media Queries – Take advantage of CSS 3 media queries and you can redirect the users based on the requested device – MediaQueries. I feel it’s more elegant way.

It’s up to you to choose the right method, based on the devices you are going to support! 

I also suggest you to check the following JavaScript Framework, which has great API support for mobile web application development.

There are many mobile frameworks available, but the above mentioned are good and have great API’s to quickly design a mobile web application.

Now comes the final part, Testing. Testing the mobile web application is real challenge. Everyone can’t afford to buy physical devices and test the web applications. Few device manufacturers provide Emulators, so that we use to test your web application.

Check the below links, which i have blogged earlier related to testing the web application on Emulators!

Apple iPhone/ iPod/ iPad 

Windows Phone

Android, Android Emulator

BlackBerry – Ripple Emulator

So, not least, ASP.NET Mobile website – Mobile. Great repository of information related to developing mobile web applications in ASP.NET and links to some cool tutorials.

If you have any queries or doubts in developing Mobile web applications, do post your questions in Mobile and Handheld Devices Section in ASP.NET Forums. All time experts, great answers!

Happy mobile web programming!!!

Thanks!

Posted in ASP.NET, Mobile | Tagged , , , , , , , | 17 Comments

Installing/Configuring AjaxControlToolKit through NuGet

I see many questions has been asked regarding installation/configuration of latest version of AjaxControlToolKit in ASP.NET, Experts-Exchange etc., forums. So i thought of writing an blog post on this.

One of the best community tool set available for ASP.NET WebForms developers is AjaxControlToolKit. Microsoft is making sure that this Ajax control tool kit is updated frequently, to make developers task easier!

In this article, i will show you how to configure AjaxControlToolKit through NuGet. Believe me it’s pretty simple process and moreover it’s fast. It’s just avoid the downloading of the package, extracting it and copying it to the Visual Studio and configuring it etc.,

With NuGet, setting up the AjaxControlToolKit in Visual Studio development environment is never so easy.

NOTE: I’m explaining this article using Microsoft Visual Studio 2010 Professional, since most of the users are working in this IDE.

Let’s get our hands dirty….

1.  Let’s create a new ASP.NET Empty Web Site.

image

image

2.  We are done creating a empty website. Now we will configure AjaxControlToolKit through NuGet.

3.  Right click on the web site and select Manage NuGet Packages

image

4. It will invoke Manage NuGet packages dialog.

image

5.  Now search for “ajaxcontroltoolkit” keyword in the textbox on the right side top corner. It will list you the latest version of AjaxControlToolKit.

image 

6.  Click on Install button to install the AjaxControlToolKit.

image

7.  Once it’s done, close this dialog.

image 

8.  Now if you open the web.config file, you can see the AjaxControlToolKit already registered.

image

9. We are done with the setup. Add a ASP.NET web page, and we will test this by adding an control from AjaxControlToolKit.

image

 

NOTE: You should use Toolkit ScriptManager control, instead of Ajax ScriptManager controls, which you can observe in the above code!

10.  Now it’s time to test. I know, you are successful.

Through NuGet, Not only AjaxControlToolKit, there are many more community developed tools available, which i leave it for you explore.

Finally, NuGet made the developer task very easy!

Happy Web Programming…

Thanks

Posted in ASP.NET AJAX | Tagged , , , , , , , | 8 Comments

Tools and Tips for HTML 5 Videos

With introduction of HTML 5, embedding an video on a web page has become peace of cake! It has overcome the barrier of installing plug-ins(Adobe Flash, Silverlight etc.,).

When i start playing around with HTML 5 Videos, i encountered some problems and i wish to discuss the same, so that it will be helpful for people, who has similar issues.

Before diving in to the content, let me remind the browser compatibility of HTML 5. HTML 5 is supported in following browsers –

  • Microsoft IE 9 +
  • Mozilla Firefox 5 +
  • Google Chrome 10 +
  • Apple Safari 5 +
  • Opera 10 +

So, that means, HTML 5 video is supported only in the above mentioned browser list. For incompatible browser, you may have to use or <object> tags by using Fall back method. You can use Modernizer, to check whether the browser supports HTML 5 Video and provide an fall back method if doesn’t support!

Now, let looks in to the tools. Basically HTML 5 Video supports the following formats -

  • MP4 with H264 video codec and AAC audio codec
  • WebM with VP8 video codec and Vorbis audio codec
  • Ogg with Theora video codec and Vorbis audio codec

All web browsers doesn’t support all the video formats. It totally depends on the web browser.

Browser MP4 WebM Ogg
IE 9 + YES NO NO
Firefox 5 + NO YES YES
Chrome 10 + YES YES YES
Safari 5 + YES NO NO
Opera 10 + NO YES YES

Looks like Apple and Microsoft are great friends Smile because they support similar video format!!!

Now, the challenge is how to encode these videos to the required formats. If you wish to supports for all the browser, you may have to encode your video in all the three formats. After search on the web using Google and Bing, i found these below two software’s, which are pretty good in converting the videos to HTML 5 video support format!

  1. Any Video Converter
  2. Miro Video Converter

Both of the software do a good job in converting the videos in to the required format and it’s simple too!  

We are done converting the videos and we programmed it, and opened the web page…. BOOM… Oops, Video is not playing. It’s says, Video playback aborted due to a network error.

It’s because, MIME type is not set in the Web Server. I will consider, IIS 7 as my web server, and we will see, how to add the required MIME types!

  1. Launch IIS.
  2. Select the website. In the middle pane, under IIS section, select MIME Types icon.

image

3.   Now click on Add… option in the right pane. It will invoke Add MIME Type dialog box.

image

4.    Now add the following file types one by one in the respective edit boxes!

File name extension MIME type
.mp4 video/mp4
.webm video/webm
.ogg video/ogg

5.   Once, you are done adding the file types, close the IIS.

Now try again with the web page, which has video, surprise it’s working now. Yeah! it will work, because, we set the file type information.

NOTE: You can do the same for older IIS versions. For other web servers like Apache, we may have to do similar settings but in different way!

I think it’s time to kick the plug – ins and start using HTML 5 Video!

Happy Web Programming!!!

Thanks!

Posted in HTML 5 | Tagged , , , , , , , , , | 1 Comment

Windows 8–My Encounter

Windows 8. It’s a new operating system from Microsoft. It’s fast and fluid. Awesome UI and totally new design! Good news is that, Microsoft is unveiling the Windows 8 RT Tablet with own hardware called Surface.

I was bowled with the UI. It needs special mention, because it was an innovation. It totally changed the looks and feel of Windows. Thanks to Microsoft for designing this great product.

 When Windows 8 first announced in BUILD conference, i was surprised on how it’s goanna be! Not again Windows Vista. But it was totally different and was great!

When i started installing Windows 8, it was very fast. Installation was done in 20 minutes and I’m logged in to Windows 8 and started using it. It’s worth mentioning that the Installation was pretty smooth and user friendly.

Though Windows 8 is releasing on October 26th, Microsoft made Windows 8 available to developers and enterprise customers on August 15th in the form of Windows Enterprise Evaluation download – Windows 8 Enterprise Evaluation

Are you excited? Are you sure you want your hands get dirty with Windows 8, then go ahead and download the the Windows Enterprise version from the above link.

NOTE: You can install Windows 8 on VHD, check this link for more information.

Windows 8 for consumers

Microsoft Account – Now you can configure your Windows 8 with Microsoft account(previously Hotmail / Live account). With Microsoft account, you can now sync the contacts, Messaging(Facebook, Twitter, Linked In), Calendar etc.,

Mail is built in to Windows 8. Thanks to Microsoft for this amazing feature. You can now configure your mails accounts – Gmail, Hotmail etc., in Windows 8 with out any hassle.

SkyDrive is an amazing app, which allows you to store your multimedia content in the cloud. Microsoft offers approx. 25 GB of space per account.

XBOX – It’s my all time favourite. Now you can play XBOX games in your Windows 8. It’s amazing!

Bing – Microsoft powerful search engine now comes to Windows 8.  Awesome UI. Especially you got to try Image search! Believe me you will definitely love it!

IE 10  – Much advanced browser. Great support for HTML 5 and CSS 3. You will love surfing the web sites in IE 10! More protection from phishing, Tracking and fake websites!

Windows Store –  Great apps. Installing an app is pretty easy. Though it has few number, but going big.

Picture Password – Now you unlock your Windows 8 pc in a way, by connecting dots on the picture! It’s totally new way of unlocking the PC, than the traditional password or using biometric sensors!

Windows 8 for developers

Windows 8 is now touch enabled. No more keyboard and mouse, now you can operate Windows by hand. That’s awesome. May be it’s a tablet or laptop or computer(Should have touch capability). Now you can create awesome apps by using Windows 8 SDK. Create once and run it on multiple devices, yes what you read is absolutely right. App created for Windows 8 tablet can be installed on a Tablet, laptop or computer too!

Now you can leverage your existing Microsoft .NET skills, to develop Windows 8 apps. XAML, C#.NET / VB.NET should be fine to get started! One good news, with Windows 8, Web application developer can also be a Windows 8 developer – If you know HTML 5, CSS 3 and JavaScript, you are not only a web developer, you are Windows app developer too. Are you not  excited with this?

Great development environment – Visual Studio 2012, totally designed to created great apps for Windows 8. Good news is that VS 2012 Express Edition is totally free and you can download it today to get started – Download VS 2012 Express

Resources to get started -

http://msdn.microsoft.com/en-us/windows/apps/br229512.aspx

http://msdn.microsoft.com/library/windows/apps/hh779072

NOTE: In order create apps for Windows 8, you need to have developer license which can be brought from Microsoft – License

Though i have mentioned some features, there are lot many features for consumers as well as developers to explore, which i leave it to you to explore Winking smile

Finally, I wish Windows 8 great success and looking forward to write some cool articles!

Thanks!

Posted in Windows 8 | Tagged , , , , , , , | 1 Comment

Detect requesting device type and redirect in ASP.NET

Smart Phones are rapidly increasing, so web app developers are more concentrating on porting their web applications compatible to view on smart phones.

With ASP.NET, making an existing web application compatible for smart phones is pretty easy. You can just add the following META tags in the &lt;head&gt; section and you are done. ASP.NET takes care of the rest!

META Tags
  1. <meta name="HandheldFriendly" content="true" />
  2. <meta name="viewport" content="width=device-width" />

 

ASP.NET MVC 4 has got pretty more options for making the website Mobile compatible!

http://www.asp.net/mvc/tutorials/mvc-4/aspnet-mvc-4-mobile-features

In ASP.NET WebForms too, we have an option to check whether the requested device is Mobile or not – Request.IsMobileDevice, which is not appropriate in most of the scenarios! I mean, it’s failing to detect the device type correctly!

Now, we discuss about custom solution for ASP.NET WebForms – detect the device type and redirecting!

Suppose if you have two versions of your web application – Mobile & Desktop, and you may wish to redirect the user to the appropriate web app based on the requested device.

To do that, try the following code snippet!

Detect Device in ASP.NET
  1. //Redirect the user based on the requested device
  2.             bool bIsMobileDevice = false;
  3.            
  4.             string[] MobileDevices = new string[] { "iPhone", "iPad","iPod","BlackBerry",
  5.                                                      "Nokia", "Android", "WindowsPhone",
  6.                                                      "Mobile"
  7.                                                      };
  8.             foreach (string MobileDeviceName in MobileDevices)
  9.             {
  10.                 if ((Request.UserAgent.IndexOf(MobileDeviceName, StringComparison.OrdinalIgnoreCase)) > 0)
  11.                 {
  12.                     bIsMobileDevice = true;
  13.                     break;
  14.  
  15.                 }
  16.             }//end:foreach loop
  17.  
  18.             if (bIsMobileDevice)
  19.             {
  20.                 Response.Redirect("Mobile/Home.aspx");
  21.             }
  22.             else
  23.             {
  24.                 Response.Redirect("Desktop/Home.aspx");
  25.             }

Let’s examine, what the above code does – A String array holds the mobile device names, which is matched with the User Agent string. If match is successful, then the user is redirected to the Mobile website!

Cool! If you examine the above code, it  contains the device names hardcoded in string array! Suppose, in future if you wish to add another device. For that, you may have add the new device name to the string array, recompile it and upload it back to the web server!

Seems to be an inefficient solution. The above solution will be suitable for scenarios like if you are targeting particular device type like iPad etc.,

Now we will see a more generic way to achieve the solution to the problem! We create an XML file, which holds the Mobile device names -

MobileDevices.xml
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <Devices>
  3.   <Device>iPad</Device>
  4.   <Device>iPhone</Device>
  5.   <Device>iPod</Device>
  6.   <Device>WindowsPhone</Device>
  7.   <Device>Android</Device>
  8.   <Device>BlackBerry</Device>
  9.   <Device>Nokia</Device>
  10.   <Device>Samsung</Device>
  11.   <Device>Mobile</Device>
  12. </Devices>

 

The above file can be created under App_Data folder! Now you can read the device names from this file using classes in System.Xml.Linq namespace.

To do that, check the below code snippet,

Code Snippet
  1. bool bIsMobileDevice = false;
  2.  
  3.             XDocument mobileDeviceDoc = XDocument.Load(Server.MapPath("App_Data/MobileDevices.xml"));
  4.  
  5.             var mobileDevices = from devices in mobileDeviceDoc.Root.Elements()
  6.                                 select devices;
  7.  
  8.             foreach (XElement device in mobileDevices)
  9.             {
  10.                 if (!string.IsNullOrEmpty(device.Value))
  11.                 {
  12.                     if ((Request.UserAgent.IndexOf(device.Value, StringComparison.OrdinalIgnoreCase)) > 0)
  13.                     {
  14.                         bIsMobileDevice = true;
  15.                         break;
  16.  
  17.                     }
  18.                 }
  19.  
  20.             }//end:foreach loop
  21.  
  22.             if (bIsMobileDevice)
  23.             {
  24.                 Response.Redirect("Mobile/Home.aspx");
  25.             }
  26.             else
  27.             {
  28.                 Response.Redirect("Desktop/Home.aspx");
  29.             }

Now this solution was more feasible! When you want to add new device, just add an element in the MobieDevices.xml and you are done. No need to re compile you code and upload it back to the web server. It just works!!!

Happy Mobile Web Programming!!!

 

Posted in Mobile | Tagged , , , , , | 3 Comments