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

HostForLIFE.eu Proudly Launches Umbraco 7.5.7 Hosting

clock January 27, 2017 07:16 by author Peter

HostForLIFE.eu, a leading Windows web hosting provider with innovative technology solutions and a dedicated professional services team, today announced the support for Umbraco 7.5.7 hosting plan due to high demand of Umbraco users in Europe. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

 

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam, (NL), London, (UK), Washington, D.C. (US), Paris, (France), Frankfurt, (Germany), Chennai, (India), Milan, (Italy), Toronto, (Canada) and São Paulo, (Brazil) to guarantee 99.9% network uptime. All data centers feature redundancies in network connectivity, power, HVAC, security and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. HostForLIFE Umbraco hosting plan starts from just as low as €3.49/month only and this plan has supported ASP.NET Core 1.1, ASP.NET MVC 5/6 and SQL Server 2012/2014/2016.

Umbraco is a fully-featured open source content management system with the flexibility to run anything from small campaign or brochure sites right through to complex applications for Fortune 500's and some of the largest media sites in the world. Umbraco is strongly supported by both an active and welcoming community of users around the world, and backed up by a rock-solid commercial organization providing professional support and tools. Umbraco can be used in its free, open-source format with the additional option of professional tools and support if required.

Umbraco release that exemplifies our mission to continue to make Umbraco a bit simpler every day. The other change is that there's now a "ValidatingRequest" event you can hook into. This event allows you to "massage" any of the requests to ImageProcessor to your own liking. So if you'd want to never allow any requests to change BackgroundColor, you can cancel that from the event. Similarly if you have a predefined set of crops that are allowed, you could make sure that no other crop sizes will be processed than those ones you have defined ahead of time.

Further information and the full range of features Umbraco 7.5.7 Hosting can be viewed here: http://hostforlife.eu/European-Umbraco-757-Hosting



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: How To Drag And Upload Multiple Image Files In ASP.NET?

clock January 25, 2017 08:20 by author Peter

In this tutorial, I will show you How To Drag And Upload Multiple Image Files In ASP.NET. First, I create a blank ASP.NET WebForm Project. And then, right click on the Project ==>select NuGet Package Manager ==> Select DropZone and Download it.

Design a WebForm having a file upload control.
    <head runat="server"> 
        <title></title> 
        <script src="scripts/dropzone/dropzone.min.js"></script> 
        <link href="scripts/dropzone/basic.min.css" rel="stylesheet" /> 
        <link href="scripts/dropzone/dropzone.css" rel="stylesheet" /> 
          
        <script src="scripts/ai.0.15.0-build58334.min.js"></script> 
    </head> 
    <body> 
        <form id="form1" runat="server" class="dropzone"> 
            <div> 
                <div class="fallback"> 
                    <asp:FileUpload ID="file" runat="server" AllowMultiple="true" /> 
                </div> 
            </div> 
        </form> 
    </body> 
    </html> 


Write the following code in the code behind(.cs) file.
    protected void Page_Load(object sender, EventArgs e) 
           { 
               foreach (string s in Request.Files) 
               { 
                   HttpPostedFile file = Request.Files[s]; 
     
                   int fileSizeInBytes = file.ContentLength; 
                   string fileName = file.FileName; 
                   string fileExtension = ""; 
     
                   if (!string.IsNullOrEmpty(fileName)) 
                       fileExtension = Path.GetExtension(fileName); 
     
                   // IMPORTANT! Make sure to validate uploaded file contents, size, etc. to prevent scripts being uploaded into your web app directory 
                   // string savedFileName = Path.Combine(@"..\Files\", Guid.NewGuid().ToString() + fileExtension); 
                  string savepath = Path.Combine(Request.PhysicalApplicationPath, "Files"); 
                   string savefile = Path.Combine(savepath, file.FileName); 
                   file.SaveAs(savefile); 
               } 
           } 


Run the project and select multiple files and drag to the box.

Drag and drop all the images to the box. It will upload the images and save them to your local folder (here in Files Folder).

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



European ASP.NET Core Hosting - HostForLIFE.eu :: How to Add Localisation to ASP.NET Core Application

clock January 25, 2017 06:07 by author Scott

In this post I'll walk through the process of adding localisation to an ASP.NET Core application using the recommended approach with resx resource files.

Introduction to Localisation

Localisation in ASP.NET Core is broadly similar to the way it works in the ASP.NET 4.X. By default you would define a number of .resx resource files in your application, one for each culture you support. You then reference resources via a key, and depending on the current culture, the appropriate value is selected from the closest matching resource file.

While the concept of a .resx file per culture remains in ASP.NET Core, the way resources are used has changed quite significantly. In the previous version, when you added a .resx file to your solution, a designer file would be created, providing static strongly typed access to your resources through calls such as Resources.MyTitleString.

In ASP.NET Core, resources are accessed through two abstractions, IStringLocalizer and IStringLocalizer<T>, which are typically injected where needed via dependency injection. These interfaces have an indexer, that allows you to access resources by a string key. If no resource exists for the key (i.e. you haven't created an appropriate .resx file containing the key), then the key itself is used as the resource.

Consider the following example:

using Microsoft.AspNet.Mvc; 
using Microsoft.Extensions.Localization;

public class ExampleClass 
{
    private readonly IStringLocalizer<ExampleClass> _localizer;
    public ExampleClass(IStringLocalizer<ExampleClass> localizer)
    {
        _localizer = localizer;
    }

    public string GetLocalizedString()
    {
        return _localizer["My localized string"];
    }
}

In this example, calling GetLocalizedString() will cause the IStringLocalizer<T> to check the current culture, and see if we have an appropriate resource file for ExampleClass containing a resource with the name/key "My localized string". If it finds one, it returns the localised version, otherwise, it returns "My Localized string".

The idea behind this approach is to allow you to design your app from the beginning to use localisation, without having to do up front work to support it by creating the default/fallback .resx file. Instead, you can just write the default values, then add the resources in later.

Personally, I'm not sold on this approach - it makes me slightly twitchy to see all those magic strings around which are essentially keys into a dictionary. Any changes to the keys may have unintended consequences, as I'll show later in the post.

Adding localisation to your application

For now, I'm going to ignore that concern, and dive in using Microsoft's recommended approach. I've started from the default ASP.NET Core Web application without authentication.

The first step is to add the localisation services in your application. As we are building an MVC application, we'll also configure View localisation and DataAnnotations localisation. The localisation packages are already referenced indirectly by the Microsoft.AspNetCore.MVC package, so you should be able to add the services and middleware directly in your Startup class:

public void ConfigureServices(IServiceCollection services) 
{
    services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });

    services.AddMvc()
        .AddViewLocalization(
            LanguageViewLocationExpanderFormat.Suffix,
            opts => { opts.ResourcesPath = "Resources"; })
        .AddDataAnnotationsLocalization();
}

These services allow you to inject the IStringLocalizer service into your classes. They also allow you to have localised View files (so you can have Views with names like MyView.fr.cshtml) and inject the IViewLocalizer, to allow you to use localisation in your view files. Calling AddDataAnnotationsLocalizationconfigures the Validation attributes to retrieve resources via an IStringLocalizer.

The ResourcePath parameter on the Options object specifies the folder of our application in which resources can be found. So if the root of our application is found at ExampleProject, we have specified that our resources will be stored in the folder ExampleProject/Resources.

Configuring these classes is all that is required to allow you to use the localisation services in your application. However you will typically also need some way to select what the current culture is for a given request.

To do this, we use the RequestLocalizationMiddleware. This middleware uses a number of different providers to try and determine the current culture. To configure it with the default providers, we need to decide which cultures we support, and which is the default culture.

Note that the configuration example in the documentation didn't work for me, though the Localization.StarterWeb project they reference did, and is reproduced below.

public void ConfigureServices(IServiceCollection services) 
{
    // ... previous configuration not shown

    services.Configure<RequestLocalizationOptions>(
        opts =>
        {
            var supportedCultures = new[]
            {
                new CultureInfo("en-GB"),
                new CultureInfo("en-US"),
                new CultureInfo("en"),
                new CultureInfo("fr-FR"),
                new CultureInfo("fr"),
            };

            opts.DefaultRequestCulture = new RequestCulture("en-GB");
            // Formatting numbers, dates, etc.
            opts.SupportedCultures = supportedCultures;
            // UI strings that we have localized.
            opts.SupportedUICultures = supportedCultures;
        });
}

public void Configure(IApplicationBuilder app) 
{
    app.UseStaticFiles();
    var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();    app.UseRequestLocalization(options.Value);

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Using localisation in your classes

We now have most of the pieces in place to start adding localisation to our application. We don't yet have a way for users to select which culture they want to use, but we'll come to that shortly. For now, lets look at how we go about retrieving a localised string.

Controllers and services

Whenever you want to access a localised string in your services or controllers, you can inject an IStringLocalizer<T> and use its indexer property. For example, imagine you want to localise a string in a controller:

public class HomeController: Controller 
{
    private readonly IStringLocalizer<HomeController> _localizer;

    public HomeController(IStringLocalizer<HomeController> localizer)
    {
        _localizer = localizer;
    }

    public IActionResult Index()
    {
        ViewData["MyTitle"] = _localizer["The localised title of my app!"];
        return View(new HomeViewModel());
    }
}

Calling _localizer[] will lookup the provided string based on the current culture, and the type HomeController. Assuming we have configured our application as discussed previously, the HomeController resides in the ExampleProject.Controllers namespace, and we are currently using the fr culture, then the localizer will look for either of the following resource files:

  • Resources/Controller.HomeController.fr.resx
  • Resources/Controller/HomeController.fr.resx

If a resource exists in one of these files with the key "The localised title of my app!" then it will be used, otherwise the key itself will be used as the resource. This means you don't need to add any resource files to get started with localisation - you can just use the default language string as your key and come back to add .resx files later.

Views

There are two kinds of localisation of views. As described previously, you can localise the whole view, duplicating it and editing as appropriate, and providing a culture suffix. This is useful if the views need to differ significantly between different cultures.

You can also localise strings in a similar way to that shown for the HomeController. Instead of an IStringLocalizer<T>, you inject an IViewLocalizer into the view. This handles HTML encoding a little differently, in that it allows you to store HTML in the resource and it won't be encoded before being output. Generally you'll want to avoid that however, and only localise strings, not HTML.

The IViewLocaliser uses the name of the View file to find the associated resources, so for the HomeController's Index.cshtml view, with the fr culture, the localiser will look for:

  • Resources/Views.Home.Index.fr.resx
  • Resources/Views/Home/Index.fr.resx

The IViewLocalizer is used in a similar way to IStringLocalizer<T> - pass in the string in the default language as the key for the resource:

@using Microsoft.AspNetCore.Mvc.Localization
@model AddingLocalization.ViewModels.HomeViewModel
@inject IViewLocalizer Localizer
@{
    ViewData["Title"] = Localizer["Home Page"];
}
<h2>@ViewData["MyTitle"]</h2> 

DataAnnotations

One final common area that needs localisation is DataAnnotations. These attributes can be used to provide validation, naming and UI hints of your models to the MVC infrastructure. When used, they provide a lot of additional declarative metadata to the MVC pipeline, allowing selection of appropriate controls for editing the property etc.

Error messages for DataAnnotation validation attributes all pass through an IStringLocalizer<T> if you configure your MVC services using AddDataAnnotationsLocalization(). As before, this allows you to specify the error message for an attribute in your default language in code, and use that as the key to other resources later.

public class HomeViewModel 
{
    [Required(ErrorMessage = "Required")]
    [EmailAddress(ErrorMessage = "The Email field is not a valid e-mail address")]
    [Display(Name = "Your Email")]
    public string Email { get; set; }
}

Here you can see we have three DataAnnotation attributes, two of which are ValidationAttributes, and the DisplayAttribute, which is not. The ErrorMessage specified for each ValidationAttribute is used as a key to lookup the appropriate resource using an IStringLocalizer<HomeViewModel>. Again, the files searched for will be something like:

  • Resources/ViewModels.HomeViewModel.fr.resx
  • Resources/ViewModels/HomeViewModel.fr.resx

A key thing to be aware of is that the DisplayAttribute is not localised using the IStringLocalizer<T>. This is far from ideal, but I'll address it in my next post on localisation.

Allowing users to select a culture

With all this localisation in place, the final piece of the puzzle is to actually allow users to select their culture. The RequestLocalizationMiddleware uses an extensible provider mechanism for choosing the current culture of a request, but it comes with three providers built in

  • QueryStringRequestCultureProvider
  • AcceptLanguageHeaderRequestCultureProvider
  • CookieRequestCultureProvider

These allow you to specify a culture in the querystring (e.g ?culture=fr-FR), via the Accept-Languageheader in a request, or via a cookie. Of the three approaches, using a cookie is the least intrusive, as it will obviously seamlessly be sent with every request, and does not require the user to set the Accept-Language header in their browser, or require adding to the querystring with every request.

Again, the Localization.StarterWeb sample project provides a handy implementation that shows how you can add a select box to the footer of your project to allow the user to set the language. Their choice is stored in a cookie, which is handled by the CookieRequestCultureProvider for each request. The provider then sets the CurrentCulture and CurrentUICulture of the thread for the request to the user's selection.

To add the selector to your application, create a partial view _SelectLanguagePartial.cshtml in the Shared folder of your Views:

@using System.Threading.Tasks
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.Extensions.Options

@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions

@{
    var requestCulture = Context.Features.Get<IRequestCultureFeature>();
    var cultureItems = LocOptions.Value.SupportedUICultures
        .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
        .ToList();
}

<div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name"> 
    <form id="selectLanguage" asp-controller="Home"
          asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path"
          method="post" class="form-horizontal" role="form">
        @Localizer["Language:"] <select name="culture"
                                        asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems"></select>
        <button type="submit" class="btn btn-default btn-xs">Save</button>

    </form>
</div> 

We want to display this partial on every page, so update the footer of your _Layout.cshtml to reference it:

<footer> 
    <div class="row">
        <div class="col-sm-6">
            <p>&copy; 2016 - Adding Localization</p>
        </div>
        <div class="col-sm-6 text-right">
            @await Html.PartialAsync("_SelectLanguagePartial")
        </div>
    </div>
</footer> 

Finally, we need to add the controller code to handle the user's selection. This currently maps to the SetLanguage action in the HomeController:

[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl) 
{
    Response.Cookies.Append(
        CookieRequestCultureProvider.DefaultCookieName,
        CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
        new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
    );

    return LocalRedirect(returnUrl);
}

And that's it! If we fire up the home page of our application, you can see the culture selector in the bottom right corner. At this stage, I have not added any resource files, but if I trigger a validation error, you can see that the resource key is used for the resource itself:

My development flow is not interrupted by having to go and mess with resource files, I can just develop the application using the default language and add resx files later in development. If I later add appropriate resource files for the fr culture, and a user changes their culture via the selector, I can see the effect of localisation in the validation attributes and other localised strings:

As you can see, the validation attributes and page title are localised, but the label field 'Your Email' has not, as that is set in the DisplayAttribute.

Summary

In this post I showed how to add localisation to your ASP.NET Core application using the recommended approach of providing resources for the default language as keys, and only adding additional resources as required later.

In summary, the steps to localise your application are roughly as follows:

1. Add the required localisation services
2. Configure the localisation middleware and if necessary a culture provider

3. Inject IStringLocalizer<T> into your controllers and services to localise strings

4. Inject IViewLocalizer into your views to localise strings in views

5. Add resource files for non-default cultures

6. Add a mechanism for users to choose their culture



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: Implement .NET Core CSV WriterImplement .NET Core CSV Writer

clock January 18, 2017 07:56 by author Peter

Today, I will explain you about how to implement Generic CSV Writer which may take an input from any list and return a CSV string or write to a certain file, if specified. Although, this is a generic C# implementation and can be used in any .NET Framework supporting generics. Yet, we are going to discuss this with .NET Core. We are going to use .NET Core Console Application which is in continuation to Welcome to .NET Core Console Application.

Add new Class in DotNetCore.ConsoleApplication
We are going to add a new class CsvWriter in DotNetCore.ConsoleApplication.

  • Open existing solution in Visual Studio 2015.
  • Now, add a new class CsvWriter.cs.

        Open Add New Item Screen through DotNetCore.ConsoleApplication Context Menu of Common folder >> Add >> Class >> Installed >> .NET Core >> Class.

        Name it CsvWriter.cs.
        Click OK button.

  • Add CsvWriter implementation.


        Write<T> (IList<T> list, bool includeHeader = true).
        Creates and returns the generated CSV.
        Write<T> (IList<T> list, string fileName, bool includeHeader = true)
        Creates and returns the generated CSV and saves the generated CSV to the specified path.
        CreateCsvHeaderLine
        Creates CSV header line, if includeHeader is set true.
        CreateCsvLine<T>(T item, PropertyInfo[] properties).
        Creates a CSV line for the given type of the object.
        CreateCsvLine(IList<string> list).
        Creates a CSV line for the given list of the string by joining them, demarcated by comma.

        CreateCsvItem
        Adds the provided value item to the processed list, used to create CSV line.

        CreateCsvStringListItem
        Adds the provided string list as a single item to the processed list, which is used to create CSV line.

        CreateCsvStringArrayItem
        Adds the provided string array as a single item to the processed list, which is used to create CSV line.

        CreateCsvStringItem
        Adds the provided string value item to the processed list, used to create CSV line.

        ProcessStringEscapeSequence
        Processes the provided data to handle double quotes and comma value. If we do not apply escape sequences, they can corrupt the data.

        WriteFile
        Writes the generated CSV data to the file.

ConsoleApplication
    public class CsvWriter { 
        privateconst string DELIMITER = ","; 
     
        public string Write < T > (IList < T > list, bool includeHeader = true) { 
            StringBuildersb = new StringBuilder(); 
     
            Type type = typeof(T); 
     
            PropertyInfo[] properties = type.GetProperties(); 
     
            if (includeHeader) { 
                sb.AppendLine(this.CreateCsvHeaderLine(properties)); 
            } 
     
            foreach(var item in list) { 
                sb.AppendLine(this.CreateCsvLine(item, properties)); 
            } 
     
            returnsb.ToString(); 
        } 
     
        public string Write < T > (IList < T > list, string fileName, bool includeHeader = true) { 
            string csv = this.Write(list, includeHeader); 
     
            this.WriteFile(fileName, csv); 
     
            return csv; 
        } 
     
        private string CreateCsvHeaderLine(PropertyInfo[] properties) { 
            List < string > propertyValues = new List < string > (); 
     
            foreach(var prop in properties) { 
                stringstringformatString = string.Empty; 
                string value = prop.Name; 
     
                var attribute = prop.GetCustomAttribute(typeof(DisplayAttribute)); 
                if (attribute != null) { 
                    value = (attribute as DisplayAttribute).Name; 
                } 
     
                this.CreateCsvStringItem(propertyValues, value); 
            } 
     
            returnthis.CreateCsvLine(propertyValues); 
        } 
     
        private string CreateCsvLine < T > (T item, PropertyInfo[] properties) { 
            List < string > propertyValues = new List < string > (); 
     
            foreach(var prop in properties) { 
                stringstringformatString = string.Empty; 
                object value = prop.GetValue(item, null); 
     
                if (prop.PropertyType == typeof(string)) { 
                    this.CreateCsvStringItem(propertyValues, value); 
                } else if (prop.PropertyType == typeof(string[])) { 
                    this.CreateCsvStringArrayItem(propertyValues, value); 
                } else if (prop.PropertyType == typeof(List < string > )) { 
                    this.CreateCsvStringListItem(propertyValues, value); 
                } else { 
                    this.CreateCsvItem(propertyValues, value); 
                } 
            } 
     
            returnthis.CreateCsvLine(propertyValues); 
        } 
     
        private string CreateCsvLine(IList < string > list) { 
            returnstring.Join(CsvWriter.DELIMITER, list); 
        } 
     
        private void CreateCsvItem(List < string > propertyValues, object value) { 
            if (value != null) { 
                propertyValues.Add(value.ToString()); 
            } else { 
                propertyValues.Add(string.Empty); 
            } 
        } 
     
        private void CreateCsvStringListItem(List < string > propertyValues, object value) { 
            string formatString = "\"{0}\""; 
            if (value != null) { 
                value = this.CreateCsvLine((List < string > ) value); 
                propertyValues.Add(string.Format(formatString, this.ProcessStringEscapeSequence(value))); 
            } else { 
                propertyValues.Add(string.Empty); 
            } 
        } 
     
        private void CreateCsvStringArrayItem(List < string > propertyValues, object value) { 
            string formatString = "\"{0}\""; 
            if (value != null) { 
                value = this.CreateCsvLine(((string[]) value).ToList()); 
                propertyValues.Add(string.Format(formatString, this.ProcessStringEscapeSequence(value))); 
            } else { 
                propertyValues.Add(string.Empty); 
            } 
        } 
     
        private void CreateCsvStringItem(List < string > propertyValues, object value) { 
            string formatString = "\"{0}\""; 
            if (value != null) { 
                propertyValues.Add(string.Format(formatString, this.ProcessStringEscapeSequence(value))); 
            } else { 
                propertyValues.Add(string.Empty); 
            } 
        } 
     
        private string ProcessStringEscapeSequence(object value) { 
            returnvalue.ToString().Replace("\"", "\"\""); 
        } 
     
        public bool WriteFile(string fileName, string csv) { 
            boolfileCreated = false; 
     
            if (!string.IsNullOrWhiteSpace(fileName)) { 
                File.WriteAllText(fileName, csv); 
     
                fileCreated = true; 
            } 
     
            returnfileCreated; 
        } 
    } 


Add Test Model Class in DotNetCore.ConsoleApplication
We are going to add a new class TestVM in DotNetCore.ConsoleApplication.

  • Open the existing Solution in Visual Studio 2015
  • Now, add a new class TestVM.cs.

        Open Add New Item Screen through DotNetCore.ConsoleApplication Context Menu of Common folder >> Add >> Class >> Installed >> .NET Core >> Class.
        Name it TestVM.cs.
        Click OK button.

  • Add TestVM implementation.
  • Update Program.cs to initialize List<TestVM> with the dummy data and call CsvWriter.

    public class TestVM { 
        [Display(Name = "Test Id")] 
        publicintTestId { 
            get; 
            set; 
        } 
        [Display(Name = "Name")] 
        public string TestName { 
            get; 
            set; 
        } 
    } 
     
    public class Program { 
        public static void Main(string[] args) { 
            Console.WriteLine("Welcome to .NET Core Console Application"); 
            List < TestVM > tests = new List < TestVM > { 
                newTestVM { 
                    TestId = 1, TestName = "Bill Gates" 
                }, 
                newTestVM { 
                    TestId = 2, TestName = "Warren Buffett" 
                }, 
                newTestVM { 
                    TestId = 3, TestName = "Amancio Ortega" 
                }, 
                newTestVM { 
                    TestId = 4, TestName = "Carlos Slim Helu" 
                } 
            }; 
            stringstringfileName = string.Format("{0}\\test.csv", System.AppContext.BaseDirectory); 
            CsvWritercsvWriter = new CsvWriter(); 
            csvWriter.Write(tests, fileName, true); 
            Console.WriteLine("{0} has been created.", fileName); 
            Console.ReadKey(); 
        } 
    } 

Run Application in Debug Mode

  • Press F5 or Debug Menu >> Start Debugging or Start Console Application button on the toolbar to start the Application in the debugging mode. It will start an Application Console in the debug mode.
  • It will generate test.csv at given path. Therefore at C:\ASP.NET Core\CSV Writer\DotNetCore\ConsoleApplication.NetCore\bin\Debug\netcoreapp1.0.

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core Hosting - HostForLIFE.eu :: Dependency Injection in ASP.NET Core

clock January 16, 2017 11:12 by author Scott

One of the nice things that the new ASP.NET Core stack brings to the table, is Dependency Injection (DI) as a first-class citizen, right out of the box. DI is nothing new, even for ASP.NET, but in the earlier versions, it wasn't baked into the platform, and developers were forced to jump through hoops in order to enable it.

Let's look at the status quo and how things are changing for the better with the new DI system in ASP.NET Core...

Status quo

Because of the history of ASP.NET, the timelines and factoring of its different products, like WebForms, MVC, SignalR, Katana (OWIN) and Web API, they've each had their own way of doing DI. Some products have extensibility points that you can leverage in order to plug in an Inversion of Control (IoC) container:

  • Web API: System.Web.Http.Dependencies.IDependencyResolver and System.Web.Http.Dependencies.IDependencyScope
  • MVC: System.Web.Mvc.IDependencyResolver
  • SignalR: Microsoft.AspNet.SignalR.IDependencyResolver

While others, like WebForms and Katana, doesn't. Some will argue that the IDependencyResolver-type abstraction, which is essentially an implementation of the Service Locator pattern, is an anti-pattern and should be avoided, but that's a discussion for another day.

There are also other ways of achieving DI within some of the frameworks; MVC has IControllerFactory and IControllerActivator, Web API has IHttpControllerActivator etc. All of these are extensibility points that you can implement in order to leverage DI in your controllers.

Implementing these abstractions yourself isn't something that you typically want or should have to do. Most IoC containers have already implemented these adapters for you and ship them as NuGet packages. If we take Autofac as an example, some adapters include

  • Autofac.Mvc4
  • Autofac.Mvc5
  • Autofac.Owin
  • Autofac.WebApi
  • Autofac.WebApi2
  • Autofac.SignalR
  • Autofac.Web (WebForms)

As you can see, it quickly starts to add up - and this is just for a single container! Imagine if I'd compiled a list for the gazillion different IoC containers in the .NET space. Each of the adapters needs to be maintained, updated, versioned etc. That's a big burden on the adapter maintainers and the community in general.

On the consuming side of this, for a typical web application using MVC, SignalR and Web API, you'd end up needing three (or more) of these adapters, in order to leverage DI across the application.

The future

Even though a lot of ideas and code have been carried forward from Katana, ASP.NET Core is by all means a re-imagining, re-write, re-EVERYTHING of the entire, current ASP.NET stack. Hell, it's even triggered a re-jigging of the entire .NET (Core) platform and tooling. This means that it's a perfect time to bring DI into the platform itself, and make all components on top benefit of a single, unified way of doing DI.

Say hello to IServiceProvider! Even though the interface itself isn't new (it's been living in mscorlib under the System namespace since .NET 1.1), it's found new life in the ASP.NET Core DI system. It's also accompanied by a couple of new interfaces; IServiceCollection, which is essentially a builder for an IServiceProvider and IServiceScope, which is intended for resolving services within a specific lifetime scope, like per-request.

In order for things to Just Work™, out of the box, Microsoft have implemented a lightweight IoC container that ships with the ASP.NET Core hosting layer. It's in the Microsoft.Extensions.DependencyInjection NuGet package.

When ASP.NET Core is bootstrapped, it creates an instance of IServiceCollection and passes it to user code using the ConfigureServicesmethod of the Startup class:

public class Startup 
{
    public void ConfigureServices(IServiceCollection services)
    {
        // This method gets called by the runtime.
        // Use this method to add services to the container.

         // Adds the services MVC requires to run.
        services.AddMvc();

        // Add some custom services
        services.AddSingleton<ICache, Cache>();
        services.AddScoped<IDatabaseSession, DatabaseSession>();
    }

    // ...
}

In this method, you're free to add whatever services your application needs, and they will magically be available for constructor injection across the board. Different components in the stack also ship with extension methods to conveniently add the services the component needs to the collection, like AddMvc (shown above), AddCors, AddEntityFramework etc.

Now, it's important to note that the default implementation, living in Microsoft.Extensions.DependencyInjection is a deliberately lightweight, feature poor (is that a word?), fast, implementation of an IoC container. It has just the amount of features needed for the runtime/platform/framework to compose itself and run. A "lowest common denominator" feature set, if you will. If you want more advanced features, like many do, Microsoft actively encourages you to Bring Your Own Container (BYOC), or layer the functionality on top, which I've done with Scrutor. This brings us back to IoC container adapters.

If you want to use a third party container, you have to, like before, implement your own version of IServiceProvider (and its accompanying interfaces), or use an adapter that someone in the community has already provided. There are already several of these available, like

The difference this time is that you only need a single adapter to enable DI across the board. To plug in the adapter, you have to change the return type of the ConfigureServicesmethod to IServiceProvider and return the adapter implementation. By using StructureMap.Dnx as an example, let's look at our startup class again:

public class Startup 
{
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        // This method gets called by the runtime.
        // Use this method to add services to the container.

        // Adds the services MVC requires to run.
        services.AddMvc();

        // Add some custom services
        services.AddSingleton<ICache, Cache>();
        services.AddScoped<IDatabaseSession, DatabaseSession>();

        // Create an instance of a StructureMap container.
        var container = new Container();

        // Here we can add stuff to container, using StructureMap-specific APIs...

        // Populate the StructureMap container with
        // services from the IServiceCollection.
        container.Populate(services);

        // Resolve the StructureMap-specific IServiceProvider
        // and return it to the runtime.
        return container.GetInstance<IServiceProvider>();
    }

    // ...
}

By doing this, all components will resolve its services from the StructureMap container, and you'll be able to utilize the full feature set of StructureMap, like awesome diagnostics, property injection, convention based registrations, profiles, decoration etc.

This post turned out longer than I expected, just to show a couple of lines of code at the end, but I thought it would be interesting to put everything in perspective and hopefully you did too. As you can see the DI story has been greatly simplified in the this new world, while still allowing you, as an application, library or framework developer, to utilize DI across the board, with minimal effort.

 

 



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: How to Create Multi Step Form In ASP.NET?

clock January 11, 2017 07:18 by author Peter

In this post, I will tell you about how to create multi step form in ASP.NET. Multiview will be used to display the content on the tap of Tab. 

To show tab on the top, we will use Menu control. Thus, let's go and Add menu control from toolbox. I have given the Horizontal orientation, so that Tab will display horizontally. 
<asp:Menu 
           ID="menuTabs" 
           Orientation="Horizontal" 
           Width="100%" 
           runat="server"> 
           <Items> 
               <asp:MenuItem Text="Employee Info" Value="0" Selected="true"/> 
               <asp:MenuItem Text="Contact Info" Value="1" /> 
               <asp:MenuItem Text="Salary Info" Value="2" /> 
           </Items> 
</asp:Menu>
 

To display the content for each tab, we will use Multiview control. I have given a property Selected="true" for Employee Info, so that when a page is launched, it will display the content of Employee Info.
<asp:MultiView ID="multiviewEmployee" 
                      runat="server" ActiveViewIndex="0"> 

</asp:MultiView> 


Next step is to add view inside Multiview. As I have three menu items, I need to add three views inside Multiview.
<asp:MultiView ID="multiviewEmployee" 
                       runat="server" ActiveViewIndex="0"> 
              <asp:View runat="server"> 
                <div> 
                    <%--To do--%> 
                </div> 
              </asp:View> 
               <asp:View runat="server"> 
                <div> 
                    <%--To do--%> 
                </div> 
              </asp:View> 
               <asp:View runat="server"> 
                <div> 
                    <%--To do--%> 
                </div> 
              </asp:View> 
</asp:MultiView> 
 

ActiveViewIndex= "0" will display first view after page is launched. Now, we will open corresponding view, when it is clicked on menu items. For it, we need to handle OnMenuItemClick event of Menu control. Hence, add it in your code and it will look, as mentioned below.
<asp:Menu 
  ID="menuTabs" 
  Orientation="Horizontal" 
  Width="100%" 
  runat="server" 
  OnMenuItemClick="menuTabs_MenuItemClick"> 
  <Items> 
      <asp:MenuItem Text="Employee Info" Value="0" Selected="true"/> 
      <asp:MenuItem Text="Contact Info" Value="1" /> 
      <asp:MenuItem Text="Salary Info" Value="2" /> 
  </Items> 
</asp:Menu> 


In CS page, assign the value of menu item to multiview .
protected void menuTabs_MenuItemClick(object sender, MenuEventArgs e) 
    { 
        Menu menuTabs = sender as Menu; 
        MultiView multiTabs = this.FindControl("multiviewEmployee") as MultiView; 
        multiTabs.ActiveViewIndex = Int32.Parse(menuTabs.SelectedValue); 
         
    } 


Now, it's none. Your tab structure is ready. Full code for ASPX is mentioned below.
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title></title> 
<style> 
    .viewCSS { 
        border: solid 2px black; 
        padding: 20px; 
    } 


    #menuTabs a.static.selected { 
        border-bottom-color: red; 
        border-bottom-style: solid; 
        border-bottom-width: 3px; 
        color: red; 
    } 
</style> 
</head> 
<body> 
<form id="form1" runat="server" style="width: 100%"> 
    <div style="width: 100%; margin-left: 20px; margin-top: 50px; margin-right: 20px;"> 

        <asp:Menu 
            ID="menuTabs" 
            Orientation="Horizontal" 
            Width="100%" 
            runat="server" 
            OnMenuItemClick="menuTabs_MenuItemClick"> 
            <Items> 
                <asp:MenuItem Text="Employee Info" Value="0" Selected="true" /> 
                <asp:MenuItem Text="Contact Info" Value="1" /> 
                <asp:MenuItem Text="Salary Info" Value="2" /> 
            </Items> 
        </asp:Menu> 
        <asp:MultiView ID="multiviewEmployee" 
            runat="server" ActiveViewIndex="0"> 
            <asp:View runat="server"> 
                <div style="margin-top: 40px;"> 
                    <asp:Table runat="server" CssClass="viewCSS"> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">First Name</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">Last Name</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                    </asp:Table> 
                </div> 
            </asp:View> 
            <asp:View runat="server"> 
                <div style="margin-top: 40px;"> 
                    <asp:Table runat="server" CssClass="viewCSS"> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">Address</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">Mobile</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                    </asp:Table> 
                </div> 
            </asp:View> 
            <asp:View runat="server"> 
                <div style="margin-top: 40px;"> 
                    <asp:Table runat="server" CssClass="viewCSS"> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">Hire Date</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">Salary</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                    </asp:Table> 
                </div> 
            </asp:View> 

        </asp:MultiView> 
    </div> 
</form> 
</body> 
</html> 


I Hope it works for you!

 

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: How To Change app.config Data in ASP.NET?

clock January 4, 2017 08:20 by author Peter

In this post, I will tell you about How To Change app.config Data in ASP.NET. Please write the following code to change app.config data at runtime.
    private static void SetSetting(string key, string value) 
           { 
               Configuration configuration = 
                   ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
               configuration.AppSettings.Settings[key].Value = value; 
               configuration.Save(ConfigurationSaveMode.Full, true); 
               ConfigurationManager.RefreshSection("appSettings"); 
           } 


The code given below is used to fetch app.config data.
    private static string GetSetting(string key) 
            { 
                return ConfigurationManager.AppSettings[key]; 
            } 


App.config file

Key is lang and value is English.
 
Output

We get the "lang" value as English, this value is fetched from App.config file.

Modify App.config value at runtime.


Code
    public Form1() 
    { 
        InitializeComponent();  
        string objAppConfigValue = GetSetting("lang"); 
        SetSetting("lang", "Tamil"); 
        string objModifiedAppConfigValue = GetSetting("lang"); 
        
    } 

    private static string GetSetting(string key) 
    { 
        return ConfigurationManager.AppSettings[key]; 
    } 

    private static void SetSetting(string key, string value) 
    { 
        Configuration configuration = 
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
        configuration.AppSettings.Settings[key].Value = value; 
        configuration.Save(ConfigurationSaveMode.Full, true); 
        ConfigurationManager.RefreshSection("appSettings"); 
    } 



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