European Windows 2019 Hosting BLOG

BLOG about Windows 2019 Hosting and SQL 2019 Hosting - Dedicated to European Windows Hosting Customer

European FREE ASP.NET 4.5 Hosting UK - HostForLIFE.eu :: Sending additional form data in multipart uploads with ASP.NET Web API

clock March 20, 2014 06:10 by author Peter

If you've used ASP.NET MVC you'll be used to being able to easily process multipart form data on the server by virtue of the ASP.NET MVC model binder. Unfortunately things are not quite so simple in ASP.NET Web API. Most of the examples I have seen demonstrate how to upload a file but do not cover how to send additional form data with the request. The example below (taken from the Fabrik API Client) demonstrates how to upload a file using HttpClient:

public async Task<IEnumerable<MediaUploadResult>> UploadMedia(int siteId, params UploadMediaCommand[] commands)

{

    Ensure.Argument.NotNull(commands, "commands");

    Ensure.Argument.Is(commands.Length > 0, "You must provide at least one file to upload.");

    var formData = new MultipartFormDataContent();

    foreach (var command in commands)

    {

        formData.Add(new StreamContent(command.FileStream), command.FileName, command.FileName);

    }

    var request = api.CreateRequest(HttpMethod.Post, api.CreateRequestUri(GetMediaPath(siteId)));

    request.Content = formData;

    var response = await api.HttpClient.SendAsync(request).ConfigureAwait(false);

    return await response.Content.ReadAsAsync<IEnumerable<MediaUploadResult>>().ConfigureAwait(false);

}

The UploadMediaCommand passed to this method contain a Stream object that we've obtained from an uploaded file in ASP.NET MVC. As you can see, we loop through each command (file) and add it to the MultipartFormDataContent. This effectively allows us to perform multiple file uploads at once. When making some changes to our API recently I realized we needed a way to correlate the files we uploaded with the MediaUploadResult objects sent back in the response. We therefore needed to send a unique identifier for each file included in the multipart form.

Since the framework doesn't really offer a nice way of adding additional form data to MultiPartFormDataContent, I've created a few extension methods below that you can use to easily send additional data with your file uploads.

/// <summary>

/// Extensions for <see cref="System.Net.Http.MultipartFormDataContent"/>.

/// </summary>

public static class MultiPartFormDataContentExtensions

{      

    public static void Add(this MultipartFormDataContent form, HttpContent content, object formValues)

    {       

        Add(form, content, formValues);

    }

    public static void Add(this MultipartFormDataContent form, HttpContent content, string name, object formValues)

    {

        Add(form, content, formValues, name: name);

    }

     public static void Add(this MultipartFormDataContent form, HttpContent content, string name, string fileName, object formValues)

    {

        Add(form, content, formValues, name: name, fileName: fileName);

    }

    private static void Add(this MultipartFormDataContent form, HttpContent content, object formValues, string name = null, string fileName = null)

    {        

        var header = new ContentDispositionHeaderValue("form-data");

        header.Name = name;

        header.FileName = fileName;

        header.FileNameStar = fileName;

        var headerParameters = new HttpRouteValueDictionary(formValues);

        foreach (var parameter in headerParameters)

       {

            header.Parameters.Add(new NameValueHeaderValue(parameter.Key, parameter.Value.ToString()));

        }

         content.Headers.ContentDisposition = header;

        form.Add(content);

    }

}

With these extensions in place I can now update our API client to do the following:foreach (var command in commands)

{

    formData.Add(

        new StreamContent(command.FileStream),

        command.FileName, command.FileName,

        new {

            CorrelationId = command.CorrelationId,

            PreserveFileName = command.PreserveFileName

        }

    );

}

This sets the content disposition header like so:

Content-Disposition: form-data;

    name=CS_touch_icon.png;

    filename=CS_touch_icon.png;

    filename*=utf-8''CS_touch_icon.png;

    CorrelationId=d4ddd5fb-dc14-4e93-9d87-babfaca42353;

    PreserveFileName=False

On the API, to read we can loop through each file in the upload and access the additional data like so:

foreach (var file in FileData) {

    var contentDisposition = file.Headers.ContentDisposition;

    var correlationId = GetNameHeaderValue(contentDisposition.Parameters, "CorrelationId");

}

Using the following helper method:

private static string GetNameHeaderValue(ICollection<NameValueHeaderValue> headerValues, string name)

{          

    if (headerValues == null)

        return null;

    var nameValueHeader = headerValues.FirstOrDefault(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));

    return nameValueHeader != null ? nameValueHeader.Value : null;

}

In case you were interested below is the updated code we are using to process the uploaded files within ASP.NET MVC:

[HttpPost]

public async Task<ActionResult> Settings(SiteSettingsModel model)

{

    await HandleFiles(new[] {

        Tuple.Create<HttpPostedFileBase, Action<string>>(model.LogoFile, uri => model.LogoUri = uri),

        Tuple.Create<HttpPostedFileBase, Action<string>>(model.IconFile, uri => model.IconUri = uri ),

        Tuple.Create<HttpPostedFileBase, Action<string>>(model.FaviconFile, uri => model.FaviconUri = uri)

    });

    await siteClient.UpdateSiteSettings(Customer.CurrentSite, model);

    return RedirectToAction("settings")

        .AndAlert(AlertType.Success, "Success!", "Your site settings were updated successfully.");

}

private async Task HandleFiles(Tuple<HttpPostedFileBase, Action<string>>[] files)

{

    var uploadRequests = (from file in files

                          where file.Item1.IsValid() // ensures a valid file

                          let correlationId = Guid.NewGuid().ToString()

                          select new

                          {

                              CorrelationId = correlationId,

                              Command = file.Item1.ToUploadMediaCommand(correlationId),

                              OnFileUploaded = file.Item2

                          }).ToList();

    if (uploadRequests.Any())

    {

        var results = await mediaClient.UploadMedia(Customer.CurrentSite,

            uploadRequests.Select(u => u.Command).ToArray());

         foreach (var result in results)

        {

            // find the original request using the correlation id

            var request = uploadRequests.FirstOrDefault(r => r.CorrelationId == result.CorrelationId);

            if (request != null)

            {

                request.OnFileUploaded(result.Uri);

            }

        }

   }

}



ASP.NET Spain Hosting - HostForLIFE.eu :: ASP.NET App Suspend in ASP.NET 4.5.1

clock February 10, 2014 06:11 by author Peter

Suspend is the new terminate

ASP.NET App Suspend is a new feature in the .NET Framework 4.5.1 that makes ASP.NET sites much more responsive and enables you to host more sites on a single server. It is very well suited for commercial web hosters, like Windows Azure Web Sites, and Enterprise IT web hosting. HostForLIFE.eu proudly launches the support of ASP.NET 4.5.1 on all their newest Windows Server environment. HostForLIFE.eu ASP.NET 4.5.1 Spain Hosting plan starts from just as low as €3.00/month only.

ASP.NET App Suspend is a self-tuning mechanism for web hosting, a little bit like CLR GC generations (if you squint). The addition of suspend establishes three states that a site can be in on a given machine. You can see the three states in the diagram, below.

All sites start out as inactive. As sites are requested, they are loaded into memory, become active, and respond to page requests. After sites have been idle, as determined by the timeout setting, they will be suspended. Suspended sites effectively lose access to the CPU, making CPU cycles and most of the memory they were using available for requests to other sites. However, they are kept in a state – this is the new suspended state – by which they can be resumed very quickly and respond to traffic again.

Usage scenarios

- Scenarios that can benefit from ASP.NET App Suspend.

- Shared hosting (commercial hosting or enterprise IT) Companies selling or taking advantage of shared hosting can pack many more sites on a given machine, while providing much more responsive site experience.  Shared web hosting is certainly the most popular kind of hosting you will discover. As the name indicates, the equipment (server) that your particular web site is held on will be shared together with lots of other users. Because of how prevalent this sort of hosting is, the considerably low cost of managing it, and the volume of companies providing this kind of service plan you can get yourself started out for very little cash. Even though shared hosting is ideal for compact or hobby web sites, it’s not at all without it’s negative aspects. These come from the very character of ‘shared’ web hosting, check out the video above to find out more.

- Switch to shared hosting Web site owners can take advantage of low-cost shared hosting while delivering the responsive experience that they want.

- Hot spare for large sites large high-traffic sites can maintain spares in suspend, ready for when one of the servers behind a load balancer goes down (planned or unplanned).

- Disaster recovery large high-traffic sites can maintain spares in suspend in a backup datacenter, ready for when the main data center goes down or otherwise becomes inaccessible.



Press Release - Premier European HostForLIFE.eu Proudly Announces FREE Trial Windows ASP.NET Hosting

clock October 8, 2013 12:31 by author Scott

European Windows and ASP.NET hosting specialist, HostForLIFE.eu, has officially launched FREE trial web hosting package. This free trial is offered for the next 14 days and at anytime, the customers can always cancel anytime. This FREE trial packages combine generous or unlimited web space, unlimited bandwith, unlimited email accounts, 1 MSSQL database, 1 MySQL database. There is also the ability to host multiple websites in this package. As the market for hosted solutions continues to grow, the new hosting range is designed to exceed the growing technical demands of businesses and IT professionals.

HostForLIFE.eu continues to invest heavily in developing powerful and resilient Business web hosting packages. The new range scales to accommodate a wide range of business needs including ecommerce and multiple websites. The range comprises of Classic Package, which is priced €3.00/month. The Budget Package is priced at €5.50/month. There is Economy package which is priced €8.00/month, this is the most favourite package and it is designed for Portal/Business site. And then Business Package is priced at €11.00/month. Furthermore, the Business Package delivers HostForLIFE’s most powerful shared hosting feature set to date, and is optimized for hosting multiple and business websites.

Every day thousands of people decide to set up a website for business or personal use. New business owners and the average consumer don't always have access to unlimited budgets. HostForLIFE.eu understand the importance of reliable hosting but are not always prepared to pay the exorbitant prices that reliable hosts charge.

“We believe that all customers should be given a free trial before buying into a service and with such approach, customers are confident that the product / service that they choose is not faulty or wrong.” Said John Curtis, VP Marketing and Business Development at HostForLIFE.eu. “With this free trial hosting, we want our customers to test drive our quality services. We believe that our web hosting platform and customer support are up there with the best and our commitment to give the best for our customers.”

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see www.microsoft.com/web/hosting/HostingProvider/Details/953). HostForLIFE.eu services is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, HostForLIFE.eu has also won several awards from reputable organizations in the hosting industry and the detail can be found on HostForLIFE.eu official website.

For more information about this FREE trial package offered by HostForLIFE.eu, please visit http://www.hostforlife.eu

About HostForLIFE.eu:

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

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 serves the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.   



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in