Entitiy Framework Core

Create Windows Services with Topshelf
CPOL
A small compact tutorial for creating Windows services in .NET Core – Examples containing scheduled jobs / Entitiy Framework Core / Hosting a WebApi
This article shows you how to run a simple Windows service using a Scheduler, Entity Framework Core or hosting a WebApi with kestrel server.
Introduction
The core library for these examples is Topshelf. It provides a very simple way to get started with win services. This article contains examples for win services which should execute scheduled jobs or run a RestApi.
All examples are using Dependency Injection, if you are not familiar with it, here are some further readings for Dependency injection and the Autofac framework.
Example 2 – Scheduled service
See Github: ScheduledWinservice
Required NuGet-Packages
Topshelf
Topshelf.Autofac
Quartz
Autofac.Extras.Quartz
Microsoft.Extensions.Configuration.Json
Topshelf
Executing the EXE will run the service in a console
Windows service can be installed via cmd.exe (Run as Administrator) – Service.exe install
For uninstallation, use Service.exe uninstall
Bootstrap.cs
This class is for registering the types for the dependency Injection.
Registration of the log provider
Hide   Copy Code
LogProvider.SetCurrentLogProvider(new QuartzConsoleLogProvider());
Jobs
Job are the task which your service should run. These must implement the IJob interface. If this job needs some additional data, you can use the JobDataMap. (See «QuartzController.cs» and MyJob.cs)
Triggers
Quarzt provides several triggers for executing jobs at a certain time. Examples are provided in QuartzController.cs:
Execute job once.
Executing job with interval.
Delete a job from the queue.
Documentation of triggers
Example 3 – ScheduledEFCoreWinservice
See Github: ScheduledEFCoreWinservice
Required NuGet-Packages
Topshelf
Topshelf.Autofac
Quartz
Autofac.Extras.Quartz
Microsoft.Extensions.Configuration.Json
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Topshelf
Executing the EXE will run the service in a console
Windows service can be installed via cmd.exe (Run as Administrator) – Service.exe install
For uninstallation, use Service.exe uninstall
Bootstrap.cs
This class is for registering the types for the dependency Injection.
Registration of Servicecontrollers
Registration of IConfiguration – Provides reading the appsettings.json
Registration of Settings – Helperclass for easier access of the configuration
Registration of the QuartzModule
Registration of the Controller
Registration of the database context
EF Core with DependencyInjection
Database
The example database is an import of the free Ip2Location database. For instructions on downloading and importing to MS-SQL, check the following link: IP2Location™ LITE IP-COUNTRY Database.
Bootstrap
InstancePerLifetimeScope – the context will be created for each job and after the job is done, it will be disposed of.
builder.RegisterType<ip2locationContext>().InstancePerLifetimeScope();
builder.RegisterType<ip2locationWriteContext>().InstancePerLifetimeScope();
Context
The configuration will be automatically injected because of the constructor ip2locationContext(IConfiguration configuration). The configuration is used for reading the connection string.
public partial class ip2locationContext : DbContext
{
protected readonly IConfiguration _configuration;
    public ip2locationContext(IConfiguration configuration)
{
_configuration = configuration;
}
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(_configuration.GetConnectionString(“CTX”));
}
}
}
ip2locationContextFactory
If you want EF-Core migrations, you should implement this class. Otherwise, the EF-Core tools won´t find your connection string.
Quartz
Logging
If jobs are not executed, turn on the logging of Quartz. The QuartzConsoleLogProvider.cs implements a logger which is logging to the console.
Registration of the logprovider
Hide   Copy Code
LogProvider.SetCurrentLogProvider(new QuartzConsoleLogProvider());
Jobs
Job are the task which your service should run. These must implement the IJob interface. If this job needs some additional data, you can use the JobDataMap. (see «QuartzController.cs» and MyJob.cs)
Triggers
Quarzt provides several triggers for executing jobs at a certain time. Examples are provided in QuartzController.cs:
Execute job once.
Executing job with interval.
Delete a job from queue.
Documentation of triggers
Example 4 – WebapiWinservice
See Github: WebapiWinservice
Required NuGet-Packages
Topshelf
Topshelf.Autofac
Microsoft.Extensions.Configuration.Json
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Microsoft.AspNetCore
Microsoft.AspNetCore.Core
Microsoft.AspNetCore.Server.Kestrel.Core
Microsoft.Extensions.Hosting
Microsoft.Extensions.Logging.Configuration
Topshelf
Executing the EXE will run the service in a console
Windows service can be installed via cmd.exe (Run as Administrator) – Service.exe install
For uninstallation, use Service.exe uninstall
Project-setup
Console-App (.NET Core 3.1)
Is used for the windowsservice
Open Projectfile – Edit project Sdk to: <Project Sdk=”Microsoft.NET.Sdk.Web”>
Classlibrary (.NET STandard 2.0)
If responseobjects are desired for a C# application, create a class library. Alternatively, you can just use dynamic objects parsed from JSON.
appsettings.json
Publish Hints
AllowedHosts should be configured
If API should only be available internally, configure Windows Firewall
Debugging
!!! Do not execute with IIS-Express !!!
BuildContainer
Registration of the service controller
RegisterGlobalTypes
These types must be registered two times. Once for the ASP.NET webhost and once for your the service controller.
Registration of IConfiguration – Provides reading the appsettings.json
Registration of Settings – Helperclass for easier access of the configuration
WebApi
Initialization
Building the webhost
Define the settings for the kestrel server:
Hide   Copy Code
_webHost = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.MaxConcurrentConnections = 100;
serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
serverOptions.Limits.MaxRequestBodySize = 30 * 1024 * 1024;
serverOptions.Limits.MinRequestBodyDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Limits.MinResponseDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
serverOptions.Limits.KeepAliveTimeout =
TimeSpan.FromMinutes(2);
serverOptions.Limits.RequestHeadersTimeout =
TimeSpan.FromMinutes(1);
});
})
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.Build();
Startup.cs
ConfigureContainer
Registration of the types for Autofac
public void ConfigureContainer(ContainerBuilder builder)
{
Bootstrap.RegisterGlobalTypes(builder);
builder.RegisterType<Ip2LocationController>();
// is used for determining the client ip
builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance();
// context per request
builder.RegisterType<ip2locationContext>().InstancePerLifetimeScope();
}
Configure
If HostHttpsRedirect is set to «1», the service will redirect to HTTPS automatically.
Settings settings = app.ApplicationServices.GetAutofacRoot().Resolve<Settings>();
if (settings.GetAppSetting(“HostHttpsRedirect”) == “1”)
{
app.UseHttpsRedirection();
}
Start / Stop
// Start
_webHost.StartAsync().ConfigureAwait(false).GetAwaiter().GetResult();
// Stop
_webHost.StopAsync().ConfigureAwait(false).GetAwaiter().GetResult();
ApiController
Inherits from ControllerBase
Set the attributes Route & ApiController
Implement HttpGet / HttpPost methods
Example C# Client
Project «WebapiWinserviceClientExample».
Bootstrap
InstancePerLifetimeScope – the context will be created for each job and after the job is done, it will be disposed.
builder.RegisterType<ip2locationContext>().InstancePerLifetimeScope();
builder.RegisterType<ip2locationWriteContext>().InstancePerLifetimeScope();
Context
The configuration will be automatically injected because of the constructor ip2locationContext(IConfiguration configuration). The configuration is used for reading the connection string.
public partial class ip2locationContext : DbContext
{
protected readonly IConfiguration _configuration;
    public ip2locationContext(IConfiguration configuration)
{
_configuration = configuration;
}
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(_configuration.GetConnectionString(“CTX”));
}
}
}
ip2locationContextFactory
If you want EF-Core migrations, you should implement this class. Otherwise, the EF-Core tools won’t find your connection string.

More Articles:

T.J. Logan Arizona Cardinals NFL Pro Line Youth Team Color Player Jersey – Cardinal Review

Christian Kirk Arizona Cardinals NFL Pro Line Youth Player Jersey – Cardinal Review

DJ Humphries Arizona Cardinals NFL Pro Line Youth Team Color Jersey – Cardinal Review

Red bubble Mood Slime Mens

Adrotator Control in ASP.Net C#

September 2, 2019


ASP.Net AdRotator Control

The AdRotator is one of the rich web server control of asp.net. AdRotator control is used to display a sequence of advertisement images as per given priority of image.

Adrotator control display the sequence of images, which is specified in the external XML file. In a xml file we indicate the images to display with some other attributes, like  image impressions, NavigateUrl, ImageUrl, AlternateText.

In a Adrotator control images will be changed each time while refreshing the web page.

AdRotator Control Example in ASP.Net

Step 1 – Open the Visual Studio –> Create a new empty Web application.

Step 2 – Create a  New web page for display AdRotator control.

step 3 – Drag and drop AdRotator Control on web page from toolbox.

step 4 – go to Add New Item –> Add New XML File in project for write advertisement detail.

step 5 – Assign XML File to AdvertisementFile Property of AdRotator control.


Red bubble Mood Slime Mens

ASP: Text Boxes

asp dot net hosting
ASP: Text Boxes   Text box controls are typically used to accept input from the user. A text box control can accept one or more lines of text depending upon the settings of the TextMode attribute. One of the main features of Web pages is to offer forms that user can use to submit info. A flexible feature is the textmode control to allow a change in the text behavior for things like passwords. Label controls provide an easy way to display text which can be changed from one execution of a page to the next. If you want to display text that does not change, you use the literal text. Basic syntax of text control:
<asp:TextBox ID="txtstate" runat="server" ></asp:TextBox>
Common Properties of the Text Box and Labels:
Property Description
TextMode Specifies the type of text box. SingleLine creates a standard text box, MultiLIne creates a text box that accepts more than one line of text and the Password causes the characters that are entered to be masked. The default is SingleLine.
Text The text content of the text box.
MaxLength The maximum number of characters that can be entered into the text box.
Wrap It determines whether or not text wraps automatically for multi-line text box; default is true.
ReadOnly Determines whether the user can change the text in the box; default is false, i.e., the user can change the text.
Columns The width of the text box in characters. The actual width is determined based on the font that is used for the text entry.
Rows The height of a multi-line text box in lines. The default value is 0, means a single line text box.
The mostly used attribute for a label control is 'Text', which implies the text displayed on the label.
Red bubble Mood Slime Mens
>