<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>NLog &#8211; Sibeesh Passion</title>
	<atom:link href="https://sibeeshpassion.com/tag/nlog/feed/" rel="self" type="application/rss+xml" />
	<link>https://sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Wed, 02 Jun 2021 15:18:27 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>NLog &#8211; Sibeesh Passion</title>
	<link>https://sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Asp.Net Core Windows Service Task Quartz.Net With Database</title>
		<link>https://sibeeshpassion.com/asp-net-core-windows-service-task-quartz-net-with-database/</link>
					<comments>https://sibeeshpassion.com/asp-net-core-windows-service-task-quartz-net-with-database/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 29 Aug 2019 12:46:07 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Asp.Net Core]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[Asp Net Core Windows Service]]></category>
		<category><![CDATA[Azure Blob Storage]]></category>
		<category><![CDATA[Azure Storage]]></category>
		<category><![CDATA[NLog]]></category>
		<category><![CDATA[NLog in Windows Service]]></category>
		<category><![CDATA[Quartz Scheduler]]></category>
		<category><![CDATA[Quartz Scheduler with Dependency Injection]]></category>
		<category><![CDATA[Quartz SQL Server]]></category>
		<category><![CDATA[Quartz With Database]]></category>
		<category><![CDATA[Windows Service]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=13893</guid>

					<description><![CDATA[[toc] Introduction In our previous article we have already seen that how we can use Quartz.Net scheduler in our Asp.Net core console application and then run it as a windows service. The problem with that approach is that, the scheduler information will be lost once the system restarts or something bad happens. To rectify that problem we can actually save all the scheduler information in a database, luckily the Quartz.Net scheduler supports this and we can easily implement it. I hope the introduction is clear and let&#8217;s jump on to the implementation. Source Code The source code can be found [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>[toc]</p>



<h2 class="wp-block-heading">Introduction</h2>



<p>In our previous article we have already seen that how we can <a href="https://medium.com/better-programming/asp-net-core-windows-service-task-scheduler-daily-weekly-monthly-700a569d502a"><strong><em>use Quartz.Net scheduler in our Asp.Net core console application and then run it as a windows service</em></strong></a>. The problem with that approach is that, the scheduler information will be lost once the system restarts or something bad happens. To rectify that problem we can actually save all the scheduler information in a database, luckily the Quartz.Net scheduler supports this and we can easily implement it. I hope the introduction is clear and let&#8217;s jump on to the implementation.</p>



<h2 class="wp-block-heading">Source Code</h2>



<p>The source code can be found <a href="https://github.com/SibeeshVenu/Perfect-Scheduler"><strong><em>in this GitHub repository</em></strong></a>. Please feel free to star, fork or do whatever you wish. You can also consider follow me on GitHub. LOL. </p>



<h2 class="wp-block-heading">Setting Up Database</h2>



<p>Before we start the coding, let us set up our database. You can choose any database as you wish. I am choosing SQL Server Express.</p>



<h3 class="wp-block-heading">Install SQL Server Express</h3>



<figure class="wp-block-image"><img fetchpriority="high" decoding="async" width="1024" height="812" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/Install-SQl-Express-1024x812.png" alt="" class="wp-image-13894" srcset="/wp-content/uploads/2019/08/Install-SQl-Express-1024x812.png 1024w, /wp-content/uploads/2019/08/Install-SQl-Express-300x238.png 300w, /wp-content/uploads/2019/08/Install-SQl-Express-768x609.png 768w, /wp-content/uploads/2019/08/Install-SQl-Express-425x337.png 425w, /wp-content/uploads/2019/08/Install-SQl-Express.png 1690w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption>SQL Server Express</figcaption></figure>



<h3 class="wp-block-heading">Enable sa Login</h3>



<p>We should enable the sa login which we will use in our Quartz configuration. If you try to configure the Quartz with windows authentication, you will get an error as below.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>2019-08-29 11:34:02.3570|INFO|Quartz.Core.QuartzScheduler|JobFactory set to: Backup.Service.Helpers.CustomJobFactory<br> 2019-08-29 11:34:12.6801|INFO|Quartz.Impl.AdoJobStore.JobStoreTX|ConnectionAndTransactionHolder passed to RollbackConnection was null, ignoring<br> 2019-08-29 11:34:12.6892|ERROR|Quartz.Impl.AdoJobStore.JobStoreTX|Failure occurred during job recovery: Failed to obtain DB connection from data source &#8216;default&#8217;: System.Data.SqlClient.SqlException (0x80131904): Cannot open database &#8220;BackupClientSchedules&#8221; requested by the login. The login failed.<br> Login failed for user &#8216;WORKGROUP\DESKTOP-3EF5B65$&#8217;.<br>    at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling)<br>    at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)<br>    at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)<br>    at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)<br>    at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)<br>    at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal&amp; connection)<br>    at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource<code>1 retry, DbConnectionOptions userOptions, DbConnectionInternal&amp; connection)    at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource</code>1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&amp; connection)<br>    at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<code>1 retry, DbConnectionOptions userOptions)    at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource</code>1 retry)<br>    at System.Data.SqlClient.SqlConnection.Open()<br>    at Quartz.Impl.AdoJobStore.JobStoreSupport.GetConnection() in C:\projects\quartznet\src\Quartz\Impl\AdoJobStore\JobStoreSupport.cs:line 323<br> ClientConnectionId:2efd5ab8-71aa-4598-b5ca-63c5aaa6afbe<br> Error Number:4060,State:1,Class:11</p></blockquote>



<p>Yes, that is such a log error, and we don&#8217;t want any errors right. So let us configure sa login first. I have already explained how you can do that , in one of my StackOverflow answer, you can see that <a href="https://stackoverflow.com/questions/3583605/login-failed-for-user-sa-the-user-is-not-associated-with-a-trusted-sql-server/57707682#57707682"><strong><em>here</em></strong></a>. </p>



<h3 class="wp-block-heading">Create Database and Tables Needed</h3>



<p>Now we need to create a database and some tables where we can save the scheduler and trigger information. You can always see the table schema here in <a href="https://github.com/quartznet/quartznet/blob/master/database/tables/tables_sqlServer.sql"><strong><em>this official Quartz GitHub repository</em></strong></a>. You can also find the same file in our source code.</p>



<p>Before you run that query in your SQL Server Management Studio, make sure to create a database first and the use the same.</p>



<pre class="wp-block-code"><code>CREATE database BackupClientSchedules
USE BackupClientSchedules</code></pre>



<p>Now id you see inside the database BackupClientSchedules, you should see some tables with no data inside.</p>



<figure class="wp-block-image"><img decoding="async" width="646" height="1024" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/Quartz-Net-Tables-646x1024.png" alt="" class="wp-image-13895" srcset="/wp-content/uploads/2019/08/Quartz-Net-Tables-646x1024.png 646w, /wp-content/uploads/2019/08/Quartz-Net-Tables-189x300.png 189w, /wp-content/uploads/2019/08/Quartz-Net-Tables-347x550.png 347w, /wp-content/uploads/2019/08/Quartz-Net-Tables.png 650w" sizes="(max-width: 646px) 100vw, 646px" /><figcaption>Quartz Net Tables</figcaption></figure>



<h2 class="wp-block-heading">Configure Quartz.Net to Use Database Instead of RAM</h2>



<p>As we have already set up our database, now we can start configuring the service. If you are new Quartz.Net scheduler, I strongly recommend you to read my previous <a href="https://sibeeshpassion.com/asp-net-core-windows-service-task-scheduler-daily-weekly-monthly/"><strong><em>article</em></strong></a>. </p>



<h3 class="wp-block-heading">Edit App.config</h3>



<p>Let&#8217;s change the App.config file as preceding.</p>



<script src="https://gist.github.com/SibeeshVenu/dd04457e4c476db1b448c610079ee522.js"></script>



<p>Note that we have set  quartz.dataSource.default.provider  as Sqlserver and also given the  quartz.dataSource.default.connectionString. You should change these values with your provider and connection string.</p>



<h3 class="wp-block-heading">Install the Nuget Package</h3>



<p>We should install the Nuget package Quartz.Serialization.Json in our application. </p>



<h3 class="wp-block-heading">Setup the Scheduler</h3>



<p>In our previous article, we have see how we can setup the scheduler and we were using a function called GetScheduler for the same. Now we can edit the code of that function as preceding.</p>



<script src="https://gist.github.com/SibeeshVenu/c1256a4314d393ef839c2368b4a411b3.js"></script>



<p>Please note the comments in the above code block.</p>



<h2 class="wp-block-heading">Install the Service</h2>



<p>Once we finished the above steps, we can run dotnet publish command with release configuration and install the service as preceding.</p>



<figure class="wp-block-image"><img decoding="async" width="1024" height="568" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/SC-Commands-1024x568.png" alt="" class="wp-image-13896" srcset="/wp-content/uploads/2019/08/SC-Commands-1024x568.png 1024w, /wp-content/uploads/2019/08/SC-Commands-300x166.png 300w, /wp-content/uploads/2019/08/SC-Commands-768x426.png 768w, /wp-content/uploads/2019/08/SC-Commands-425x236.png 425w, /wp-content/uploads/2019/08/SC-Commands.png 1838w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption>SC Commands</figcaption></figure>



<p>Again, read my previous article, if you need a detailed explanations about this step.</p>



<h2 class="wp-block-heading">Output</h2>



<p>Once the service started successfully, you should be able to see two log files backupclientlogfile_backupservice.txt and backupclientlogfile_helperservice.txt in our win7-x64 folder. You can see all the logs in this files.</p>



<p>You should also be able to see some scheduling information in our tables in our database. Some of the table&#8217;s screenshots are given below.</p>



<figure class="wp-block-image"><img decoding="async" width="1024" height="140" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/Quartz-Job-Details-1024x140.png" alt="" class="wp-image-13897" srcset="/wp-content/uploads/2019/08/Quartz-Job-Details-1024x140.png 1024w, /wp-content/uploads/2019/08/Quartz-Job-Details-300x41.png 300w, /wp-content/uploads/2019/08/Quartz-Job-Details-768x105.png 768w, /wp-content/uploads/2019/08/Quartz-Job-Details-425x58.png 425w, /wp-content/uploads/2019/08/Quartz-Job-Details.png 1923w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption>Quartz Job Details</figcaption></figure>



<figure class="wp-block-image"><img decoding="async" width="652" height="164" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/Quartz-Sample-Triggers.png" alt="" class="wp-image-13898" srcset="/wp-content/uploads/2019/08/Quartz-Sample-Triggers.png 652w, /wp-content/uploads/2019/08/Quartz-Sample-Triggers-300x75.png 300w, /wp-content/uploads/2019/08/Quartz-Sample-Triggers-425x107.png 425w" sizes="(max-width: 652px) 100vw, 652px" /><figcaption>Quartz Sample Triggers</figcaption></figure>



<figure class="wp-block-image"><img decoding="async" width="649" height="67" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/Quartz-Triggers.png" alt="" class="wp-image-13899" srcset="/wp-content/uploads/2019/08/Quartz-Triggers.png 649w, /wp-content/uploads/2019/08/Quartz-Triggers-300x31.png 300w, /wp-content/uploads/2019/08/Quartz-Triggers-425x44.png 425w" sizes="(max-width: 649px) 100vw, 649px" /><figcaption>Quartz Triggers</figcaption></figure>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Wow!. Now we have learned,</p>



<ul class="wp-block-list"><li>about Windows Service and Asp.Net Console Application</li><li>about How to create a Windows Service using Asp.Net Core</li><li>about How to use Quartz scheduler with database</li></ul>



<h2 class="wp-block-heading">Your turn. What do you think?</h2>



<p>Thanks a lot for reading. Did I miss anything that you may think which is needed in this article? Could you find this post as useful? Kindly do not forget to share me your feedback.</p>



<p>Kindest Regards<br>Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/asp-net-core-windows-service-task-quartz-net-with-database/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Asp.Net Core Windows Service Task Scheduler Daily, Weekly, Monthly</title>
		<link>https://sibeeshpassion.com/asp-net-core-windows-service-task-scheduler-daily-weekly-monthly/</link>
					<comments>https://sibeeshpassion.com/asp-net-core-windows-service-task-scheduler-daily-weekly-monthly/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 12 Aug 2019 19:15:45 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[Asp Net Core Windows Service]]></category>
		<category><![CDATA[Azure Blob Storage]]></category>
		<category><![CDATA[Azure Storage]]></category>
		<category><![CDATA[NLog]]></category>
		<category><![CDATA[NLog in Windows Service]]></category>
		<category><![CDATA[Quartz Scheduler]]></category>
		<category><![CDATA[Quartz Scheduler with Dependency Injection]]></category>
		<category><![CDATA[Windows Service]]></category>
		<category><![CDATA[Windows Service to Upload to Azure]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=13876</guid>

					<description><![CDATA[[toc] Introduction Windows services are a good way for reducing some manual jobs that we have to do in our system. In this article, we are going to write a windows service using Asp.Net core, the jobs of this windows service is given below. Zip the folder and save the file to a particular directory Upload the zipped folder to the Azure blob storage The above mentioned tasks will be running daily, weekly, monthly. We are using Quartz scheduler with Dependency Injection to do this amazing tasks. We are using Nlog for logging the details of our tasks. If you [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>[toc]</p>



<h2 class="wp-block-heading">Introduction</h2>



<p>Windows services are a good way for reducing some manual jobs that we have to do in our system. In this article, we are going to write a windows service using Asp.Net core, the jobs of this windows service is given below.</p>



<ol class="wp-block-list"><li> Zip the folder and save the file to a particular directory </li><li>Upload the zipped folder to the Azure blob storage</li></ol>



<p>The above mentioned tasks will be running daily, weekly, monthly. We are using Quartz scheduler with Dependency Injection to do this amazing tasks. We are using Nlog for logging the details of our tasks. If you think this is something that you are interested at, then you are at the right place, let us develop our PerfectScheduler. </p>



<h2 class="wp-block-heading">Source Code</h2>



<p>The source code of this project is been uploaded to the GitHub, please feel free to fork, star, create pull requests etc. The repository can be found <a href="https://github.com/SibeeshVenu/Perfect-Scheduler"><strong><em>here</em></strong></a>.</p>



<h2 class="wp-block-heading">Creating Perfect Scheduler</h2>



<p>As I mentioned earlier, we are creating a windows service with Asp.Net core, technically there is no straight way to do this, as the Windows Service with Asp.Net core template is not available in Visual Studio.</p>



<figure class="wp-block-image"><img decoding="async" width="649" height="311" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/No-Windows-Service-Project-Template.png" alt="" class="wp-image-13879" srcset="/wp-content/uploads/2019/08/No-Windows-Service-Project-Template.png 649w, /wp-content/uploads/2019/08/No-Windows-Service-Project-Template-300x144.png 300w, /wp-content/uploads/2019/08/No-Windows-Service-Project-Template-425x204.png 425w" sizes="(max-width: 649px) 100vw, 649px" /><figcaption>No Windows Service Project Template</figcaption></figure>



<p> so we will be creating an Asp.Net console application and then install executable file generated as a windows service. </p>



<figure class="wp-block-image"><img decoding="async" width="649" height="212" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/Net-Core-Console-Application.png" alt="" class="wp-image-13880" srcset="/wp-content/uploads/2019/08/Net-Core-Console-Application.png 649w, /wp-content/uploads/2019/08/Net-Core-Console-Application-300x98.png 300w, /wp-content/uploads/2019/08/Net-Core-Console-Application-425x139.png 425w" sizes="(max-width: 649px) 100vw, 649px" /><figcaption>.Net Core Console Application</figcaption></figure>



<h3 class="wp-block-heading">Creating an Asp.Net Console Application</h3>



<p>Open Visual Studio and search for the project template Console App(.Net Core) and name the solution as per your convenience, I am naming this project as Perfect Scheduler, as I am thinking that we, the community people can make this windows service perfect by creating many pull requests.</p>



<p> Once you had created the application, let us install all of our dependencies at once, so that we don&#8217;t need to worry about them later. </p>



<figure class="wp-block-image"><img decoding="async" width="650" height="640" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/Dependencies.png" alt="" class="wp-image-13881" srcset="/wp-content/uploads/2019/08/Dependencies.png 650w, /wp-content/uploads/2019/08/Dependencies-300x295.png 300w, /wp-content/uploads/2019/08/Dependencies-425x418.png 425w" sizes="(max-width: 650px) 100vw, 650px" /><figcaption>Asp.Net Core Windows Service Dependencies</figcaption></figure>



<h3 class="wp-block-heading">Write the Service</h3>



<p>As we have installed all of our dependencies, let us create our service now. Add a new class with the name BackupService and inherit the same from IHostedService, which is part of Microsoft.Extensions.Hosting namespace.</p>



<p>The IHostedService has two methods in it as follows, so we should implement them in our service class.</p>



<script src="https://gist.github.com/SibeeshVenu/2a9cb76d58645085c3704d533a0a6a73.js"></script>



<h4 class="wp-block-heading">StartAsync</h4>



<p>The StartAsync method can be implemented as preceding.</p>



<script src="https://gist.github.com/SibeeshVenu/1e39b9749d12aac8acc1af98a2da4469.js"></script>



<p>As you can see that in the first line of the above code, we are getting the scheduler of Quartz. Let us create a method and return a scheduler then.</p>



<script src="https://gist.github.com/SibeeshVenu/afd74a512ddb7c8bd6d35868c263bd30.js"></script>



<p>The next step is to build a service provider so that we can inject our dependencies using Constructor Dependency Injection. By default the Quartz is not doing this, so we have to build the configuration our own.</p>



<script src="https://gist.github.com/SibeeshVenu/914f9ee0934d63234f81f16c5ffb2fcc.js"></script>



<p>As you can see that we have configured the services for DailyJob, WeeklyJob, MonthlyJob and HelperService. No worries, we will be creating these Classes and Interfaces very soon. </p>



<p>Once we get the Service Provider, we can pass this to our Custom Job Factory, which we will be implementing soon. Now, we can start the scheduler and schedule our jobs, please make sure that you are using different Identity names for both Triggers and Jobs. The samples are given below.</p>



<script src="https://gist.github.com/SibeeshVenu/2b6fa57cb5edca68431f59133ada6de2.js"></script>



<h4 class="wp-block-heading">StopAsync</h4>



<p>The StopAsync method can be implemented as follows</p>



<script src="https://gist.github.com/SibeeshVenu/36a4edb6866bbd9394a2eeb4a4abba5f.js"></script>



<h3 class="wp-block-heading">Creating the JobBuilders and TriggerBuilders</h3>



<p>Now we can create the Interfaces and Classes for our Jobs, which are Daily, Weekly, Monthly. To do so, let us create a new folder called Helpers and then create a folder called Interfaces inside.  Below are the Interfaces you need to create then.</p>



<h4 class="wp-block-heading">IDailyJob</h4>



<script src="https://gist.github.com/SibeeshVenu/2a06425a40aa642c420616a9dc438ea4.js"></script>



<h4 class="wp-block-heading">IWeeklyJob</h4>



<script src="https://gist.github.com/SibeeshVenu/745be5f74479f91a24d454c4b4ee113d.js"></script>



<h4 class="wp-block-heading">IMonthlyJob</h4>



<script src="https://gist.github.com/SibeeshVenu/43de235532540cd5cd6ff136ad07e9e6.js"></script>



<p>Let us also create an Interface for our HelperService.</p>



<h4 class="wp-block-heading">IHelperService</h4>



<script src="https://gist.github.com/SibeeshVenu/4aa11ef3c39e323a40de2b06abfbccfd.js"></script>



<p>The parameter schedule is for determining which job it is, the value of this parameter can be daily, weekly, monthly.</p>



<script src="https://gist.github.com/SibeeshVenu/308a0cc4b620f6c65f3f47738863db75.js"></script>



<h3 class="wp-block-heading">Create a Custom Job Factory</h3>



<p>To implement the Dependency Injection, we need to create our own custom job factory. Create a class inside the Helper folder as preceding.</p>



<script src="https://gist.github.com/SibeeshVenu/a2e10e1228e65ace98e45397d7c9d849.js"></script>



<h3 class="wp-block-heading">Implement the Job Builder Interfaces</h3>



<p>Now it is time to implement our Daily, Weekly, Monthly job builders. </p>



<h4 class="wp-block-heading">DailyJob</h4>



<script src="https://gist.github.com/SibeeshVenu/d34af66c20232409c4bb15852c88aabf.js"></script>



<h4 class="wp-block-heading">WeeklyJob</h4>



<script src="https://gist.github.com/SibeeshVenu/d021c1dc0be1c03cff9147ac3d4d231c.js"></script>



<h4 class="wp-block-heading">MonthlyJob</h4>



<script src="https://gist.github.com/SibeeshVenu/3b72c9acb9ad0e00887ecbee532d0438.js"></script>



<p>As you can see that we have configured separate classes for our each jobs with the dependency IHelperService injected via constructor. In the future we should be able to write custom logic for each jobs here as it is in separate classes.</p>



<h3 class="wp-block-heading">Implement HelperService</h3>



<p>Before we start implementing this service let us configure the NLog now as we will be writing logs from this class. </p>



<h4 class="wp-block-heading">Configure NLog</h4>



<p>To configure, NLog, create a new configuration file NLog.config and edit the content as preceding.</p>



<script src="https://gist.github.com/SibeeshVenu/7eaab92256f71a5c660a83564635b0dd.js"></script>



<p>Now, create a method SetUpNLog() and add the codes as below.</p>



<script src="https://gist.github.com/SibeeshVenu/82dbe1dd2ea19f5eda4f6fc9342880fc.js"></script>



<p>Please make sure that you have already added a property ILogger _logger. </p>



<p>We can implement the HelperService as preceding with all the necessary private and public methods.</p>



<script src="https://gist.github.com/SibeeshVenu/bc02d3f5621826c2a085970c6e47b004.js"></script>



<p>The method PerformService(string schedule) will be called for every schedule and it will make sure that the below tasks are performed.</p>



<ol class="wp-block-list"><li>Zip the folder and save the file to a particular directory</li><li>Upload the zipped file to the Azure blob storage</li></ol>



<p>Here, the values of the the variable and the blob storage container names are same, that is, daily, weekly, monthly. If you are not sure how you can upload a blob to Azure storage account, I strongly recommend you to read my article <a href="https://sibeeshpassion.com/timertrigger-azure-function-to-upload-to-azure-blob-daily/#azure-function-and-azure-blob"><strong><em>here</em></strong></a>.</p>



<p>Remember to set the values for the FolderToZipLocation(To which location the file should be saved), FolderFromZipLocation (From where the files should be taken), StorageConnectionString in the App.config file.</p>



<script src="https://gist.github.com/SibeeshVenu/1a2a3f26bf5e7a73e3b0af8aa3824172.js"></script>



<h3 class="wp-block-heading">Setting Up The Program</h3>



<p>As you all know that Program class it the start of our console application, not it is time to call our BackupService from the Program class. Let us edit the code of the Program class as below.</p>



<script src="https://gist.github.com/SibeeshVenu/55d3dea19acdf8f3416269f7911c5916.js"></script>



<p>If we are running the application locally/debug, we are calling the extension method RunConsoleAsync() or else we call our own custom extension method RunTheServiceAsync(). The line services.AddHostedService() is very important as this is where we register our IHostedService, which is BackupService. Below is the code for our extension method.</p>



<script src="https://gist.github.com/SibeeshVenu/b4950ef1a36a91800fd9bf9f5a9f02a3.js"></script>



<p>The ServiceLifetime class is where we override the methods from ServiceBase class. You can find the implementation as follows.</p>



<script src="https://gist.github.com/SibeeshVenu/9c1e42e7f697b60375d1a5975c5b0f53.js"></script>



<h2 class="wp-block-heading">Creating the Windows Service</h2>



<p>As we have already created the Asp.Net Core console application, now it is time to create a windows service from it. Make sure that you had set the RuntimeIdentifier to win7-x64 and SelfContained to true in the properties of your project, this will make sure that all of your dependencies are being added to your executable file, so that you don&#8217;t need to worry about handling your dependencies manually. You can read more about it <a href="https://docs.microsoft.com/en-us/dotnet/core/deploying/#self-contained-deployments-scd"><strong><em>here</em></strong></a>. To do so, right click on the project and click on Edit Project File. At the end, your csproj file should be similar as preceding.</p>



<script src="https://gist.github.com/SibeeshVenu/4772a4e34662dc09e7421a12064bcc28.js"></script>



<h3 class="wp-block-heading">Create the Release Configuration</h3>



<p>You should also run the dotnet publish command with the release configuration before you try to install the service, because you need this executable file to install the service.</p>



<p>Open the command prompt with administrator privilege and go to the project root folder using the cd command. Run the command &#8220;dotnet publish &#8211;configuration=release&#8221; .</p>



<p>This will generate everything you wanted. If you run the command correctly, you should see an output as preceding.</p>



<figure class="wp-block-image"><img decoding="async" width="651" height="400" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/Dotnet-Publish-Release.png" alt="" class="wp-image-13883" srcset="/wp-content/uploads/2019/08/Dotnet-Publish-Release.png 651w, /wp-content/uploads/2019/08/Dotnet-Publish-Release-300x184.png 300w, /wp-content/uploads/2019/08/Dotnet-Publish-Release-425x261.png 425w" sizes="(max-width: 651px) 100vw, 651px" /><figcaption>Dotnet Publish Release</figcaption></figure>



<p>Now go to the bin folder and then release folder, you should see a folder with the name netcoreapp2.1, inside this folder, there will be a folder win7-x64, this is the folder where your exe file, log file and other items are residing. </p>



<h3 class="wp-block-heading">Install the Service</h3>



<p>To install our Asp.Net console application as a windows service, you can use the sc command. Open the command prompt with administrator privilege and run the preceding command.</p>



<script src="https://gist.github.com/SibeeshVenu/cb8761b926f41000658ec14b9dcf1799.js"></script>



<p>And then you can start the service by running the command as &#8220;sc start BackupService&#8221;. This should start your service.</p>



<h3 class="wp-block-heading">Giving Permission to the Folders</h3>



<p>Sometimes you may get some permission issue in your service as it doesn&#8217;t have enough permission to read the files form the C drive. To overcome this, you should give enough permission to the user. You can do this by editing the security properties of those folders.</p>



<figure class="wp-block-image"><img decoding="async" width="649" height="412" src="https://sibeeshpassion.com/wp-content/uploads/2019/08/Setting-Permission-for-the-Users.png" alt="" class="wp-image-13886" srcset="/wp-content/uploads/2019/08/Setting-Permission-for-the-Users.png 649w, /wp-content/uploads/2019/08/Setting-Permission-for-the-Users-300x190.png 300w, /wp-content/uploads/2019/08/Setting-Permission-for-the-Users-425x270.png 425w" sizes="(max-width: 649px) 100vw, 649px" /><figcaption>Setting Permission for the Users</figcaption></figure>



<p>Do the same for the BackupZip folder as well.</p>



<h2 class="wp-block-heading">Output</h2>



<p>If you have run the service correctly, you should see a log file with the name  backupclientlogfile.txt inside your  win7-x64  folder. Once the service is run,  the logs will be written as follows.</p>



<script src="https://gist.github.com/SibeeshVenu/8173f2129e1f79fa4689e7d25d761807.js"></script>



<p>You can also check your Azure Storage account to check whether the files have uploaded correctly or not.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Wow!. Now we have learned,</p>



<ul class="wp-block-list"><li>about Windows Service and Asp.Net Console Application </li><li>about How to create a Windows Service using Asp.Net Core</li><li>about How to use Quartz scheduler</li><li>about How to use NLog in Windows Service</li><li>about How to configure Quartz scheduler to use Dependency Injection</li><li>about How to Zip a folder and save the file</li><li>about How to upload a file to the Azure blob storage</li></ul>



<h2 class="wp-block-heading">Your turn. What do you think?</h2>



<p>Thanks a lot for reading. Did I miss anything that you may think which is needed in this article? Could you find this post as useful? Kindly do not forget to share me your feedback.</p>



<p>Kindest Regards<br>Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/asp-net-core-windows-service-task-scheduler-daily-weekly-monthly/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
