Showing posts with label Windows Application. Show all posts
Showing posts with label Windows Application. Show all posts

Saturday, January 21, 2023

.Net Core Console Application As Windows Service - Background Activity

We can convert our .Net Core Console Application into regular Windows Service by using third party library like TopShelf, Quartz and for logging  we can utilize NLog.

Windows Service is mainly used when you want a regular running process in the background that do some activity behind the seen. 

Lets try to convert .Net Core Console Application to Windows Service. 


Open Visula Studio 2019 - > Go to New Project -> Select .Net Core(Console) template and Create project

We have to include maily two library

  • Topshelf
  • Quartz

Topshelf

Topshelf is use to initialies HostFactory Like Below

	
        var services = ServiceDependency.ConfigureServices();
        var serviceProvider = services.BuildServiceProvider();

        var rc = HostFactory.Run(x =>
        {
            x.Service(s =>
            {
                s.ConstructUsing(name => serviceProvider.GetService());
                s.WhenStarted(tc => tc.Start());
                s.WhenStopped(tc => tc.Stop());
            });
            x.RunAsLocalSystem();

            x.SetDescription("Windows Service Demo");
            x.SetDisplayName("WinServiceDemo");
            x.SetServiceName("WinServiceDemo");
        });

        var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());
        Environment.ExitCode = exitCode;

	

Quartz

Quart Library is used to Schedule services like below

	
           public JobTrigger GetCommonJob()
    {

        ReportProcessorJobKey = JobKey.Create("CommonJob", "CommonJob");

        var job = JobBuilder.Create().WithIdentity("CommonJob", "CommonJob").Build();
        int ConfigFrequency;
        int frequency = int.TryParse(ConfigurationManager.AppSettings["CommonJobFrequencyInSecond"], out ConfigFrequency) ? ConfigFrequency : 5;
        var jobTrigger = TriggerBuilder.Create()
            .WithSimpleSchedule(x => x.WithIntervalInSeconds(frequency).RepeatForever())
            .Build();

        return new JobTrigger { Job = job, Trigger = jobTrigger };
    }

	

For Source Code : You can follow the below Link

The Complete Source Code Example is availabe on below link ..

Download

Tuesday, December 27, 2022

Triggering/Calling Azure Data Factory Pipeline from Console/Windows Application (C#/.Net)

Azure data Factory has proper way of calling/triggering pipeline through different types of triggers like http, scheduled on specific time, event base trigger

message base trigger, manual trigger from Azure Portal. But in some scenario we required to call ADF pipeline as on demand basis through your application.

In that scenario Microsoft Azure has provided rich libraries in different language to achieve same activity.

Here I am presenting very easy way to trigger Azure data factory pipeline through code (C#/Net)

Prerequisite

Azure Details

.Net Supporting Library

  • Microsoft.Azure.Management.DataFactory;
  • Microsoft.Rest;
  • Microsoft.IdentityModel.Clients.ActiveDirectory;
  • System.Threading.Tasks;

AzureDataFactoryModel.cs


using System;
using System.Collections.Generic;
using System.Text;

namespace TriggerADFPipeline
{
    public class AzureDataFactoryModel
    {

        public AzureDataFactoryModel()
        {
            if (Parameters == null)
            {
                Parameters = new Dictionary();
            }
        }
        public Dictionary Parameters { get; set; }

        public string ResourceGroupName { get; set; }
        public string FactoryName { get; set; }
        public string PipeLineName { get; set; }

    }
}

ADFHelper.cs


using Microsoft.Azure.Management.DataFactory;
using Microsoft.Rest;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Threading.Tasks;

namespace TriggerADFPipeline
{
    public class ADFHelper
    {
        private TokenCredentials _tokenCredential;
        private DataFactoryManagementClient _dataFactoryClient;

        private readonly string tenantId = "xxxx";
        private readonly string clientId = "xxxx";
        private readonly string clientSecret = "xxxx";
        private readonly string subscriptionId = "xxxx";
        private readonly string windowsManagementUri = "https://management.core.windows.net/";
        private readonly string activeDirectoryEndpoint = "https://login.windows.net/";
        public ADFHelper()
        {
            AuthenticateUser();
            SetupClient();
        }

        private void AuthenticateUser()
        {
            var authority = new Uri(new Uri(activeDirectoryEndpoint), this.tenantId);
            var context = new AuthenticationContext(authority.AbsoluteUri);
            var credential = new ClientCredential(this.clientId, this.clientSecret);

            _tokenCredential = new TokenCredentials(context.AcquireTokenAsync(windowsManagementUri, credential).Result.AccessToken);
        }
        private void SetupClient()
        {
            _dataFactoryClient = new DataFactoryManagementClient(_tokenCredential) { SubscriptionId = subscriptionId };
        }

        
        public async Task TriggerAdfAsync(AzureDataFactoryModel azureDataFactoryModel)
        {
            try
            {
                
                var runResponse = await _dataFactoryClient.Pipelines.CreateRunWithHttpMessagesAsync(
                                                           azureDataFactoryModel.ResourceGroupName,
                                                           azureDataFactoryModel.FactoryName,
                                                          azureDataFactoryModel.PipeLineName,
                                                           parameters: azureDataFactoryModel.Parameters
                ).ConfigureAwait(false);
              
                return runResponse.Body.RunId;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }

    }
}

Program.cs


using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace TriggerADFPipeline
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello I am Calling ADF pipeline from C#....");
            ADFHelper _azureDataFactory = new ADFHelper();
            AzureDataFactoryModel azureDataFactoryModel = new AzureDataFactoryModel();
            azureDataFactoryModel.ResourceGroupName = "xxxx";
            azureDataFactoryModel.FactoryName = "xxxx";
            azureDataFactoryModel.PipeLineName = "xxxx";
            azureDataFactoryModel.Parameters = new Dictionary<string, object>
            {
                { "P1", "parameter 1"},
                { "P2", "parameter 2"},
                { "P3", "parameter 3"}
            };
            var runId = _azureDataFactory.TriggerAdfAsync(azureDataFactoryModel).ConfigureAwait(false);
            Console.WriteLine($"Run Id : {runId}");
        }

    }
}

Download Source Code

ADF Trigger

Popular Articles