ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET Hosting - ASPHostPortal.com :: Tips To Use BackgroundWorker in C#

clock July 26, 2016 19:54 by author Armend

How To Use BackgroundWorker in C#

BackgroundWorker is the class in System.ComponentModel which is used when you need to do some task on the back-end or in different thread while keeping the UI available to users (not freezing the user) and at the same time, reporting the progress of the same.

Using the Code

Backgroundworker has three event handlers which basically takes care of everything one needs to make it work.

  • DoWork - Your actual background work goes in here
  • ProgressChanged - When there is a progress in the background work
  • RunWorkerCompleted - Gets called when background worker has completed the work.

I have created a sample WPF application which demonstrates how to use the background worker in C#.

<ProgressBar x:Name="progressbar"
 HorizontalAlignment="Left" Height="14"
 Margin="191,74,0,0" VerticalAlignment="Top"
 Width="133"/>
<Button x:Name="button" Content="Button"
 HorizontalAlignment="Left"
 Margin="249,97,0,0" VerticalAlignment="Top"
 Width="75" Click="button_Click"/>

On Window initialization, I am creating a new object of BackgroundWorker and registering the event handlers for the same.

BackgroundWorker bg;
public MainWindow()
{
InitializeComponent();
bg = new BackgroundWorker();
bg.DoWork += Bg_DoWork;
bg.ProgressChanged += Bg_ProgressChanged;
bg.RunWorkerCompleted += Bg_RunWorkerCompleted;
bg.WorkerReportsProgress = true;
}

Here is the implementation of all three event handlers.

private void Bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Task completed");
}
private void Bg_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressbar.Value += 1;
//label.Content = e.ProgressPercentage;
}
private void Bg_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i &amp;lt;= 10; i++)
{
Thread.Sleep(1000); //do some task
bg.ReportProgress(0);
}
}

In order to make this stuff work, you need to trigger the DoWork event and for that, I am using button click event.

private void button_Click(object sender, RoutedEventArgs e)
   {
           progressbar.Value = 0;
           progressbar.Maximum = 10;
           bg.RunWorkerAsync();
   }

It is a very basic example of background worker, but it is good to start with. One must be wondering how it is updating the progress bar if it is working in the background.
Well, the ProgressChanged event handler runs on UI thread whereas DoWork runs on application thread pool. That's why despite running in the background on different thread, it is not freezing the UI and updating the progressbar upon making progress.

 

Best ASP.NET Core 1.0 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

 



ASP.NET Core 1.0 Hosting - ASPHostPortal.com :: How To Configure your ASP.‚ÄčNET Core 1.0 Application

clock June 14, 2016 20:26 by author Armend

The Web.Config is gone and the AppSettings are gone with ASP.NET Core 1.0. How do we configure our ASP.NET Core Application now? With the Web.Config, also the config transform feature is gone. How do we configure a ASP.NET Core Application for specific deployment environments?

Configuring

Unfortunately a newly started ASP.NET Core Application doesn't include a complete configuration as a sample. This makes the jump-start a little difficult. The new Configuration is quite better than the old one and it would make sense to add some settings by default. Anyway, lets start by creating a new Project.
Open the Startup.cs and take a look at the controller. There's already something like a configuration setup. This is exactly what the newly created application needs to run.

public Startup(IHostingEnvironment env)
{
    // Set up configuration sources.
    var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddEnvironmentVariables();
    if (env.IsDevelopment())
    {
        // This will push telemetry data through Application Insights
        // pipeline faster, allowing you to view results immediately.
        builder.AddApplicationInsightsSettings(developerMode: true);
    }
    Configuration = builder.Build();
}

But in the most cases you need much more configuration. This code creates a ConfigurationBuilder and adds a appsettigns.json and environment variables to the ConfigurationBuilder. In development mode, it also adds ApplicationInsights settings.
If you take a look into the appsettings.json, you'll only find a ApplicationInsights key and some logging specific settings (In case you chose a individual authentication you'll also

see a connection string):
{
  "ApplicationInsights": {
    "InstrumentationKey": ""
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Verbose",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

Where do we need to store our custom application settings?
We can use this appsettings.json or any other JSON file to store our settings. Let's use the existing one to add a new section called AppSettings:

{
...
    "AppSettings" : {
        "ApplicationTitle" : "My Application Title",
        "TopItemsOnStart" : 10,
        "ShowEditLink" : true
    }
}

This looks nice, but how do we read this settings?

In the Startup.cs the Configuration is already built and we could use it like this:

var configurationSection = Configuration.GetSection("AppSettings");
var title = configurationSection.Get<string>("ApplicationTitle");
var topItmes = configurationSection.Get<int>("TopItemsOnStart");
var showLink = configurationSection.Get<bool>("ShowEditLink");
We can also provide a default value in case that item doesn't exist or in case it is null
var topItmes = configurationSection.Get<int>("TopItemsOnStart", 15);

To use it everywhere we need to register the IConfigurationRoot to the dependency injection container:

services.AddInstance<IConfigurationRoot>(Configuration);

But this seems not to be a really useful way to provide the application settings to our application. And it looks almost similar as in the previous ASP.NET Versions. But the new configuration is pretty much better. In previous versions we created a settings facade to encapsulate the settings, to not access the configuration directly and to get typed settings.
No we just need to create a simple POCO to provide access to the settings globally inside the application:

public class AppSettings
{
    public string ApplicationTitle { get; set; }
    public int TopItemsOnStart { get; set; }
    public bool ShowEditLink { get; set; }
}

The properties of this class should match the keys in the configuration section. Is this done we are able to map the section to that AppSettings class:

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

This fills our AppSettings class with the values from the configuration section. This code also adds the settings to the IoC container and we are now able to use it everywhere in the application by requesting for the IOptions<AppSettings>:

public class HomeController : Controller
{
    private readonly AppSettings _settings
    public HomeController(IOptions<AppSettings> settings)
    {
        _settings = settings.Value;
    }
    public IActionResult Index()
    {
        ViewData["Message"] = _settings.ApplicationTitle;
        return View();
    }

Even directly in the view:

@inject IOptions<AppSettings> AppSettings
@{
    ViewData["Title"] = AppSettings.Value.ApplicationTitle;
}
<h2>@ViewData["Title"].</h2>
<ul>
    @for (var i = 0; i < AppSettings.Value.TopItemsOnStart; i++)
    {
        <li>
            <span>Item no. @i</span><br/>
            @if (AppSettings.Value.ShowEditLink) {
                <a asp-action="Edit" asp-controller="Home"
                   asp-route-id="@i">Edit</a>
            }
        </li>
    }
</ul>

With this approach, you are able to create as many configuration sections as you need and you are able to provide as many settings objects as you need to your application.
What do you think about it? Please let me know and drop a comment.

Environment specific configuration

Now we need to have differnt configurations per deployment environment. Let's assume we have a production, a staging and a development environment where we run our application. All this environments need another configuration, another connections string, mail settings, Azure access keys, whatever...
Let's go back to the Startup.cs to have a look into the constructor. We can use the IHostingEnvironment to load different appsettings.json files per environment. But we can do this in a pretty elegant way:

.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)

We can just load another JSON file with an environment specific name and with optional set to true. Let's say the appsettings.json contain the production and the default

  • settings and the appsettings.Staging.json contains the staging sepcific settings. It we are running in Staging mode, the second settings file will be loaded and the existing settings will be overridden by the new one. We just need to sepcify the settings we want to override.
  • Setting the flag optional to true means, the settings file doesn't need to exist. Whith this approatch you can commit some default setings to the source code repository and the top secret access keys and connections string, could be stored in an appsettings.Development.json, an appsettings.staging.json and an appsettings.Production.json on the buildserver or on the webserver directly.

Conclusion

As you can see, configuration in ASP.NET Core is pretty easy. You just need to know how to do it. Because it is not directly visible in a new project, it is a bit difficult to find the way to start.

 



ASP.NET Hosting - ASPHostPortal.com :: Tips to configure Kestrel URLs in ASP.NET Core RC2

clock June 10, 2016 19:44 by author Armend

How to configure Kestrel URLs in ASP.NET Core RC2

ASP.NET Core is completely decoupled from the web server environment that hosts the application. ASP.NET Core supports hosting in IIS and IIS Express, and self-hosting scenarios using the Kestrel and WebListener HTTP servers. Additionally, developers and third party software vendors can create custom servers to host their ASP.NET Core apps.

Prior to the release of ASP.NET Core RC2 Kestrel would be configured as part of the command bindings in project.json:

"commands": {
  "web": "Microsoft.AspNet.Server.Kestrel --server.urls=http://localhost:60000;http://localhost:60001;"
},

If no URLs were specified, a default binding of http://localhost:5000 would be used.

As of RC2 we have a new unified toolchain (the .NET Core CLI) and ASP.NET Core applications are effectively just .NET Core Console Applications. They have a single entry point where we programatically configure and run the web host:

public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();
    host.Run();
}

Here we're adding support for both Kestrel and IIS hosts via the appropriate extension methods.
When we upgraded SaasKit to RC2 we used the UseUrls extension to configure the URLs Kestrel would bind to:

var host = new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseUrls("http://localhost:60000", "http://localhost:60001")
    .UseIISIntegration()
    .UseStartup<Startup>()
    .Build();

I didn't really like this approach as we're hard-coding URLs. Fortunately it's still possible to load the Kestrel configuration from an external file.
First create a hosting.json file in the root of your application with your required bindings. Separate multiple URLs with a semi-colon:

{
  "server.urls": "http://localhost:60000;http://localhost:60001"
}

Next update Program.cs to load your hosting configuration, then use the UseConfiguration extension to pass the configuration to the WebHostBuilder:

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", optional: true)
        .Build();
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseConfiguration(config)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();
    host.Run();
}

If you're launching Kestrel with Visual Studio you may also need to update launchSettings.json with the correct launchUrl:

"RC2HostingDemo": {
  "commandName": "Project",
  "launchBrowser": true,
  "launchUrl": "http://localhost:60000/api/values",
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development"
  }
}

Now the web application will listen on the URLs configured in hosting.json:

Hosting environment: Development
Content root path: C:\Users\ben\Source\RC2HostingDemo\src\RC2HostingDemo
Now listening on: http://localhost:60000
Now listening on: http://localhost:60001
Application started. Press Ctrl+C to shut down.



ASPHostPortal.com Announces ASP.NET Core 1.0 RC2 Hosting Solution

clock June 2, 2016 21:13 by author Armend

ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for the ability to support the latest Microsoft and ASP.NET Core 1.0 RC2 Hosting.

ASPHostPortal.com is a well-known Windows hosting company and even one of the most famous, though it is one of the oldest Windows hosting companies. ASPHostPortal packages have gone through major changes recently, and all of us goes for the goodness of every customers. Today, we launch ASP.NET Core 1.0 RC2 hosting with interested hosting packages.

The ASP.NET team announce the availability of ASP.NET Core RC2.  This release succeeds the ASP.NET 5 RC1 release and features a number of updates to enhance compatibility with other .NET frameworks and an improved runtime.The release contains the RC2 of the .NET Core runtime and libraries.  These libraries are everything that ends up in your ‘bin’ folder when you deploy an application

.NET Core is a modular, streamlined subset of the .NET Framework and CLR. It is fully open-source and provides a common set of libraries that can be targeted across numerous platforms. Its factored approach allows applications to take dependencies only on those portions of the CoreFX that they use, and the smaller runtime is ideal for deployment to both small devices (though it doesn’t yet support some) as well as cloud-optimized environments that need to be able to run many small applications side-by-side. Support for targeting .NET Core is built into the ASP.NET 5 project templates that ship with Visual Studio 2015.

ASPHostPortal.com offers ASP.NET Core RC2 Hosting with an interested hosting plan. We are support this new technology with affordable price, a lot of ASP.NET features, 99.99% uptime guarantee, 24/7 support, and 30 days money back guarantee. We strive to make sure that all customers have the finest web-hosting experience as possible. To learn more about their ASP.NET Core RC2 Hosting, please visit http://asphostportal.com

About ASPHostPortal.com:

ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio, Latest ASP.NET Version, Latest ASP.NET MVC Version, Silverlight and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP, etc. Their service includes shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in