European ASP.NET MVC 4 and MVC 5 Hosting

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

How to get textboxes values in MVC4 created by jQuery

clock October 30, 2013 11:22 by author Ronny

Yesterday, I was trying to get the values of TextBoxes created by jQuery. I was expecting to get the value of each Textbox created by jQuery by the Id attribute of the TextBox, but I was getting NULL. I tried to find out the reason behind this reason and finally I got the solution. Let's understand the ID and Name attribute of Html controls.
ID
Id attribute of an input html control is responsible for uniquely identified a control on the html page. We use Id for getting an input html control's value using jQuery at client side or for applying some CSS to that control.
Name
Name attribute of an input html control is responsible for posting that control values on server side.
Hence, while creating a Html TextBox or Dropdown list using jQuery also defined the Id and Name attributes of an Html TextBox or Dropdown list.
Note
When you will not defined the Name attributes of an Html TextBox or Dropdown list then form will not post the TextBox or Dropdown list values to the server. It means at controller's action result you will not find the Html TextBox or Dropdown list.
Suppose, you need to select no of customers from drop down list as shown below fig.

Also, Textboxes for entering customers full name are created by jQuery as shown below.

When you will submit the form you will get the Textboxes created by jQuery at controller side as shown below -

The View

<script src="~/Scripts/jquery-1.8.2.js"></script>
<script>
$(document).ready(function () {
$("#ddl").change(function () {
var i = $("#ddl :selected").val();
var str = "";
for (var j = 1; j <= i; j++) {
var id = "txtCustomer" + j;
//Remember to add name attribute to get values at server side
str = str + "<span>Customer " + j + " Full Name: </span><input type='text' id='" + id + "' name='" + id + "'/><br/>";
}
$("#content").html(str);
});
});
</script>
<br />
@using (Html.BeginForm())
{
<h2>Get TextBoxes Values Created by jQuery</h2>
<span>Select No. of Customers </span>
<select name="ddl">
<option>Select</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<br />
<div>
</div>
<br />
<div align="center">
<input id="btnSave" value="Save" />
</div>
}

You can get the Html TextBox or Dropdown list values created by jQuery by two method as given below -

Method 1: Get Values Using FormCollection

public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(FormCollection form, string ddl)
{
for (int i = 1; i <= Convert.ToInt32(ddl); i++)
{
string id = "txtCustomer" + i;
string customer = form[id];
}
return View();
}

Method 2: Get Values Using Request.Form

public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string ddl)
{
for (int i = 1; i <= Convert.ToInt32(ddl); i++)
{
string id = "txtCustomer" + i;
string customer = Request.Form[id];
}
return View();
}

What do you think?
I hope you will enjoy the tips while programming with MVC. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.



European ASP.NET MVC 4 Hosting - Amsterdam :: How To Build async Unit of Work with MVC 4

clock October 8, 2013 12:06 by author Ronny

In the RavenDB mailing list, How to combine the standard unit of work pattern of working with RavenDB in MVC applications with async. In particular, the problematic code was:

public class HomeController : Controller
   {
        public IAsyncDocumentSession Db { get; set; }
        public async Task<ActionResult> Index()
       {
            var person = new Person {Name = "Khalid Abuhakmeh"};
            await Db.StoreAsync(person);     

          return View(person);
       }
           protected override void OnActionExecuting(ActionExecutingContext filterContext)
       {
           Db = MvcApplication.DocumentStore.OpenAsyncSession();
           base.OnActionExecuting(filterContext);
       }

       protected override void OnActionExecuted(ActionExecutedContext filterContext)
       {
           Db.SaveChangesAsync()
               .ContinueWith(x => { });
           base.OnActionExecuted(filterContext);
       }
    lic class Person
       {
           public string Id { get; set; }
           public string Name { get; set; }
       }
   }

As you probably noticed, the problem Db.SaveChangesAsync(). We want to execute the save changes in an async manner, but we don’t want to do that in a way that would block the thread. The current code just assume the happy path, and any error would be ignored. That ain’t right. If we were using Web API, this would be trivially easy, but we aren’t. So let us see what can be done about it.

I created a new MVC 4 application and wrote the following code:

As you can see, I have a break point after the await, which means that when that break point is hit, I’ll be able to see what is responsible for handling async calls in MVC4. When the breakpoint was hit, I looked at the call stack, and saw:

 

Not very useful, right? But we can fix that:

And now we get:

This is a whole bunch of stuff that doesn’t really help, I am afraid. But then I thought about putting the breakpoint before the await, which gave me:

And this means that I can check the code here. I got the code and started digging. At first I thought that I couldn’t do it, but then I discovered that I could. See, all you have to do is to create you own async action invoker, like so:

 public class UnitOfWorkAsyncActionInvoker : AsyncControllerActionInvoker
   
{
  
     protected override IAsyncResult BeginInvokeActionMethod(
  
         ControllerContext controllerContext,
  
         ActionDescriptor actionDescriptor,
  
         IDictionary<string, object> parameters, AsyncCallback callback,
  
         object state)
  
    {
  
         return base.BeginInvokeActionMethod(controllerContext, actionDescriptor, parameters,
 
                                             result => DoSomethingAsyncAfterTask().ContinueWith(task => callback(task)),
 
                                             state);
 
     }
 
     public async Task DoSomethingAsyncAfterTask()
 
     {
 
         await Task.Delay(1000);
 
     }
  
}
And then register it :

   DependencyResolver.SetResolver(type =>
 
     {
 
         if (type == typeof (IAsyncActionInvoker))
 
             return new UnitOfWorkAsyncActionInvoker();
 
         return null;
 
     }, type => Enumerable.Empty<object>());

Note: Except for doing a minimum of F5 in the debugger, I have neither tested nor verified this code. It appears to do what I want it to, and since I am only getting to this because a customer asked about this in the mailing list, that is about as much investigation time that I can dedicate to it.

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Securely Verify and Validate Image Uploads in ASP.NET and ASP.NET MVC

clock September 17, 2013 10:01 by author Ronny

One of the more interesting things had to do as part of building XAPFest was handle bulk image uploads for screenshots for applications and user / app icons. Most of the challenges here are UI-centric ones (which resolved using jQuery File-Upload) but the one security challenge that remains outstanding is ensuring that the content uploaded to your servers is safe for your users to consume.

Fortunately this problem isn't too hard to solve and doesn't require much code in C#.

Flawed Approaches to Verifying Image Uploads

Here's what usually see when developers try to allow only web-friendly image uploads:

  1. File extension validation (i.e. only allow images with .png, .jp[e]g, and .gif to be uploaded) and
  2. MIME type validation.


So what's wrong with these techniques? The issue is that both the file extension and MIME type can be spoofed, so there's no guarantee that a determined hacker might not take a js. file, slap an extra .png extension somewhere in the mix and spoof the MIME type.

Stronger Approach to Verifying Image Uploads: GDI+ Format Checking

Every file format has to follow a particular codec / byte order convention in order to be read and executed by software. This is as true for proprietary formats like .pptx as it is for .png and .gif.

You can use these codecs to your advantage and quickly tell if a file is really what it says it is - you quickly check the contents of the file against the supported formats codecs to see if the content fits into any of those specifications.

Luckily GDI+ (System.Drawing.Imaging), the graphics engine which powers Windows, has some super-simple functions we can use to perform this validation. Here's a bit of source you can use to validate a file against PNG, JPEG, and GIF formats:

using System.Drawing.Imaging;
using System.IO;
using System.Drawing;
namespace XAPFest.Providers.Security
{
    ///
    /// Utility class used to validate the contents of uploaded files  
    ///
    public static class FileUploadValidator  
    {    
     public static bool FileIsWebFriendlyImage(Stream stream)   
     {
            try
            {
                //Read an image from the stream...
                var i = Image.FromStream(stream);
                 //Move the pointer back to the beginning of the stream
                stream.Seek(0, SeekOrigin.Begin);
                 if (ImageFormat.Jpeg.Equals(i.RawFormat))
                    return true;
                return ImageFormat.Png.Equals(i.RawFormat)|| ImageFormat.Gif.Equals(i.RawFormat);
            }
            catch
            {
                return false;
            }
        }
     }
}

All this code does is read the Stream object returned for each posted file into an Image object, and then verifies that the Image supports one of three supported codecs. This source code has not been tested by security experts, so use it at your own risk. If you have any questions about how this code works or want to learn more, please drop me a line in the comments below or on Twitter.

How Do Make Sure Files Are below [X] Filesize

Since had this source code lying around anyway, We thought we would share it: 

Super-simple, like we said, but it gets the job done. Express the maximum allowable size as a long and compare it against the length of the stream

public static bool FileIsWebFriendlyImage(Stream stream, long size)
        {
            return stream.Length <= size && FileIsWebFriendlyImage(stream);
        }
    }
The other important catch to note here is that move the Stream's pointer back to the front of the stream, so it can be read again by the caller which passed the reference to this function.



Press Release :: European HostForLIFE.eu Proudly Launches ASP.NET MVC 5 Hosting

clock August 28, 2013 11:05 by author Ronny

European Windows and ASP.NET hosting specialist, HostForLIFE.eu, has announced the availability of new hosting plans that are optimized for the latest update of the Microsoft ASP.NET Model View Controller (MVC) technology. The MVC web application framework facilitates the development of dynamic, data-driven websites.

The latest update to Microsoft’s popular MVC (Model-View-Controller) technology,  ASP.NET MVC 5 adds sophisticated features like single page applications, mobile optimization, adaptive rendering, and more. Here are some new features of ASP.NET MVC 5:

- ASP.NET Identity
- Bootstrap in the MVC template
- Authentication Filters
- Filter overrides

HostForLIFE.eu is Microsoft’s number one Recommended Windows and ASP.NET Spotlight Hosting Partner in Europe for its support of Microsoft technologies that include WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5, and Visual Studio Lightswitch.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression.

In addition to shared web hosting, shared cloud hosting, and cloud server hosting, HostForLIFE.eu offers reseller hosting packages and specialized hosting for Microsoft SharePoint 2010 and 2013. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee.

For more information about this new product, please visit http://www.HostForLIFE.eu

About HostForLIFE.eu:

HostForLIFE.eu is Microsoft No #1 Recommended Windows and ASP.NET Hosting in European Continent. HostForLIFE.eu service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and many top European countries.

HostForLIFE.eu number one goal is constant uptime. HostForLIFE.eu data center uses cutting edge technology, processes, and equipment. HostForLIFE.eu has one of the best up time reputations in the industry.

HostForLIFE.eu second goal is providing excellent customer service. HostForLIFE.eu technical management structure is headed by professionals who have been in the industry since it's inception. HostForLIFE.eu has customers from around the globe, spread across every continent. HostForLIFE.eu serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



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