Service to get a change in the bank

0

I need the following. How do I make a service auto start whenever the bank flag changes from 0 to 1? I have a field in a table in the DB (Sql Server), that every time the seller requests a discount, the flag (FlagLiberacao byte) changes from 0 to 1 and at that time my service should send a message to the App. Well that, I do. I just do not know how the service will automatically do that.

    
asked by anonymous 28.09.2017 / 13:31

2 answers

0

What you want is to do a Job. Job is a task that will be performed every x value range and you can implement (do not recommend) or use a third solution.

I know some like HangFire , Quartz , RabbitMQ or even Azure has solutions for registering a service. In my case I will explain HangFire because it is the only one I know.

You need to create a Recurring Job, where the server will call every x time your method:

RecurringJob.AddOrUpdate(() => MeuMetodoAValidarOBanco(), Cron.Daily);

Notice that it does not use DateTime, but for Job the Cron concept is used. Cron is a string expression that lets you work better with time intervals. HangFire itself has some simpler options, but there is a website where you can generate your expressions.

As a service, you can upload it as a Windows service or even upload it to your API. The only problem with the latter is that IIS cleans up the pool when no one accesses the API. Here's the link for a related question here in the Stack.

    
28.09.2017 / 14:41
0

You can create a Windows Service with a SqlDependency

protected override void OnStart(string[] args)
{
    SqlDependency.Stop(this.ConnectionString);
    SqlDependency.Start(this.ConnectionString);
    Task.Run(Monitorar);
}

protected override void OnStop()
{   
    SqlDependency.Stop(this.ConnectionString);
}

private async Task Monitorar()
{
    await SqlDependencyOnChange(null, null);
}

private async Task SqlDependencyOnChange(object sender, SqlNotificationEventArgs e)
{
    var flag = false;
    using (var conexao = new SqlConnection(this.ConnectionString))
    {
        await conexao.OpenAsync();
        using (var comando = new SqlCommand("SELECT Flag FROM Tabela", conexao))
        {
            var depedency = new SqlDependency(comando);
            depedency.OnChange += new OnChangeEventHandler(async (_sender, _e) => {
                await SqlDependencyOnChange(_sender, _e);
            });

            var result = comando.ExecuteScalar();
            if (result != null || result != DBNull.Value)
                flag = (bool)result;
        }
    }

    if (flag)
    {
        await Processar();
    }
}

private async Task Processar()
{
    //Envie a notificação para o seu App.
}

Remembering that BROKER should be active in its Sql Server .:

ALTER DATABASE [Database] SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE
    
28.09.2017 / 20:07