Showing posts with label .Net. Show all posts
Showing posts with label .Net. 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

Tuesday, June 25, 2019

What are Microservices?-Azure

Ref: https://docs.microsoft.com/en-us/azure/architecture/microservices/

Microservices are a popular architectural style for building applications that are resilient, highly scalable, independently deployable, and able to evolve quickly. 

Microservices are a software architecture style in which applications are composed of small, independent modules that communicate with each other using well-defined API contracts. These service modules are highly decoupled building blocks that are small enough to implement a single functionality.

The purpose of microservices architectures is to make it easier to develop and scale applications. Microservice architectures foster collaboration between autonomous teams and enable them to bring new functionalities to market faster.


Why use microservices?

Build services independently

Microservices-based applications are built as a collection of highly decoupled services that handle a single action. Teams can independently build, verify, deploy and monitor each service.

Scale services autonomously

Independent services can be scaled based on their respective demands without impacting the overall performance, rather than scaling the entire app up or down.

Use the best approach

Development teams gain the flexibility to use the best deployment approach, language, platform and programming model for each service.

Isolate points of failure

By isolating potential problem areas to individual services, microservices architectures improve security and reliability. Services can be replaced or retired without affecting the overall structure.

Deliver value faster

Teams can deploy small, independent modules quickly. Several teams can work on different services at the same time and put new features into production faster.

Advantage with microservices in Azure

Simplify your application lifecycle

Boost agility and collaboration and reduce time to market by using Azure managed services and development tools.

Rely on a trusted platform

Develop secure and reliable applications on a compliance-certified platform.

Scale to your needs

Improve overall performance by enabling automated and fully managed scaling on demand.

Gain flexibility

Adapt faster to business needs by choosing the best approach and technology for each service.


Best approach for building microservices in Azure

Service Fabric

Get automatic scaling, rolling upgrades and self-healing from faults with a custom-built microservices framework.

Azure Kubernetes Service (AKS)

Use a fully managed Kubernetes service to handle provisioning, upgrading and scaling cluster resources on demand.

Azure Functions

Build apps with simple, serverless functions that scale on demand based on the number of executions—without managing infrastructure.

API Management

Expose and publish specific parts of your applications as an API no matter where the implementation is hosted.

Popular Articles