Exemplo n.º 1
0
        internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source)
        {
            List <EventContextPair> eventList = null;

            lock (_eventHandlerLock)
            {
                if (_dependencyFired &&
                    SqlNotificationInfo.AlreadyChanged != info &&
                    SqlNotificationSource.Client != source)
                {
                    if (ExpirationTime >= DateTime.UtcNow)
                    {
                        Debug.Fail("Received notification twice - we should never enter this state!");
                    }
                }
                else
                {
                    // It is the invalidators responsibility to remove this dependency from the app domain static hash.
                    _dependencyFired = true;
                    eventList        = _eventList;
                    _eventList       = new List <EventContextPair>(); // Since we are firing the events, null so we do not fire again.
                }
            }

            if (eventList != null)
            {
                foreach (EventContextPair pair in eventList)
                {
                    pair.Invoke(new SqlNotificationEventArgs(type, info, source));
                }
            }
        }
Exemplo n.º 2
0
 internal SqlNotification(SqlNotificationInfo info, SqlNotificationSource source, SqlNotificationType type, string key)
 {
     _info   = info;
     _source = source;
     _type   = type;
     _key    = key;
 }
 internal SqlNotification(SqlNotificationInfo info, SqlNotificationSource source, SqlNotificationType type, string key)
 {
     this._info = info;
     this._source = source;
     this._type = type;
     this._key = key;
 }
Exemplo n.º 4
0
        private void NotifyClients(SqlNotificationInfo info)
        {
            var notificationHub = GlobalHost.ConnectionManager.GetHubContext <NotificationHub>();

            switch (info)
            {
            case SqlNotificationInfo.Insert:
            {
                notificationHub.Clients.All.notify("added");
                break;
            }

            case SqlNotificationInfo.Delete:
            {
                notificationHub.Clients.All.notify("deleted");
                break;
            }

            default:
            {
                notificationHub.Clients.All.notify("other");
                break;
            }
            }
        }
        internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source)
        {
            IntPtr ptr;

            Bid.NotificationsScopeEnter(out ptr, "<sc.SqlDependency.Invalidate|DEP> %d#", this.ObjectID);
            try
            {
                List <EventContextPair> list = null;
                lock (this._eventHandlerLock)
                {
                    if ((this._dependencyFired && (SqlNotificationInfo.AlreadyChanged != info)) && (SqlNotificationSource.Client != source))
                    {
                        Bid.NotificationsTrace("<sc.SqlDependency.Invalidate|DEP|ERR> ERROR - notification received twice - we should never enter this state!");
                    }
                    else
                    {
                        this._dependencyFired = true;
                        list            = this._eventList;
                        this._eventList = new List <EventContextPair>();
                    }
                }
                if (list != null)
                {
                    Bid.NotificationsTrace("<sc.SqlDependency.Invalidate|DEP> Firing events.\n");
                    foreach (EventContextPair pair in list)
                    {
                        pair.Invoke(new SqlNotificationEventArgs(type, info, source));
                    }
                }
            }
            finally
            {
                Bid.ScopeLeave(ref ptr);
            }
        }
Exemplo n.º 6
0
        public void Test_SingleDependency_Timeout()
        {
            Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener.");

            try
            {
                // with resolution of 15 seconds, SqlDependency should fire timeout notification only after 45 seconds, leave 5 seconds gap from both sides.
                const int SqlDependencyTimerResolution = 15; // seconds
                const int testTimeSeconds         = SqlDependencyTimerResolution * 3 - 5;
                const int minTimeoutEventInterval = testTimeSeconds - 1;
                const int maxTimeoutEventInterval = testTimeSeconds + SqlDependencyTimerResolution + 1;

                // create a new event every time to avoid mixing notification callbacks
                ManualResetEvent notificationReceived = new ManualResetEvent(false);
                DateTime         startUtcTime;

                using (SqlConnection conn = new SqlConnection(_execConnectionString))
                    using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn))
                    {
                        conn.Open();

                        // create SqlDependency with timeout
                        SqlDependency dep = new SqlDependency(cmd, null, testTimeSeconds);
                        dep.OnChange += delegate(object o, SqlNotificationEventArgs arg)
                        {
                            // notification of Timeout can arrive either from server or from client timer. Handle both situations here:
                            SqlNotificationInfo info = arg.Info;
                            if (info == SqlNotificationInfo.Unknown)
                            {
                                // server timed out before the client, replace it with Error to produce consistent output for trun
                                info = SqlNotificationInfo.Error;
                            }

                            DataTestUtility.AssertEqualsWithDescription(SqlNotificationType.Change, arg.Type, "Unexpected Type value.");
                            DataTestUtility.AssertEqualsWithDescription(SqlNotificationInfo.Error, arg.Info, "Unexpected Info value.");
                            DataTestUtility.AssertEqualsWithDescription(SqlNotificationSource.Timeout, arg.Source, "Unexpected Source value.");
                            notificationReceived.Set();
                        };

                        cmd.ExecuteReader();
                        startUtcTime = DateTime.UtcNow;
                    }

                Assert.True(
                    notificationReceived.WaitOne(TimeSpan.FromSeconds(maxTimeoutEventInterval), false),
                    string.Format("Notification not received within the maximum timeout period of {0} seconds", maxTimeoutEventInterval));

                // notification received in time, check that it is not too early
                TimeSpan notificationTime = DateTime.UtcNow - startUtcTime;
                Assert.True(
                    notificationTime >= TimeSpan.FromSeconds(minTimeoutEventInterval),
                    string.Format(
                        "Notification was not expected before {0} seconds: received after {1} seconds",
                        minTimeoutEventInterval, notificationTime.TotalSeconds));
            }
            finally
            {
                Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener.");
            }
        }
Exemplo n.º 7
0
        public void OnDatabaseChange(object sender, SqlNotificationEventArgs args)
        {
            SqlNotificationInfo info = default;

            if (args != null)
            {
                info = args.Info;
            }
            if (SqlNotificationInfo.Insert.Equals(info))
            {
                _logger.LogInformation($"Orders ServiceBroker called {info}");
                var attempts = maxAttempts;
                while (attempts-- > 0)
                {
                    try
                    {
                        using var conn = new SqlConnection(connStr);
                        conn.Open();
                        var cmd = conn.CreateCommand();
                        cmd.CommandText =
                            "select someFields " +
                            "from source ";
                        using var adapter = new SqlDataAdapter(cmd);
                        using var dataset = new DataSet();
                        adapter.Fill(dataset);

                        var incomedorders = dataset.Tables[0].AsEnumerable().Select
                                            (
                            row => new OrderInfo(row.Field <string>("transaction_id"),
                                                 row.Field <int>("amount"),
                                                 row.Field <int>("orderid")))
                                            .ToArray();

                        foreach (var order in incomedorders)
                        {
                            string postback     = $"{PostBackUrl}&some_parameters";
                            var    amountupdate = Common.SendPostBack(postback, out string result);
                            if (amountupdate == RequestResult.Success)
                            {
                                cmd.CommandText = $"update source set Processed=1 where Id={order.orderid}";
                                cmd.ExecuteNonQuery();
                            }
                            else if (amountupdate == RequestResult.BadTransactionId)
                            {
                                cmd.CommandText = $"delete from source where Id={order.orderid}";
                                cmd.ExecuteNonQuery();
                            }
                        }
                        break;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex.ToString());
                        Task.Delay(1000);
                        continue;
                    }
                }
            }
        }
    private void OnChange(object sender, SqlNotificationEventArgs e)
    {
        CurrentEvent = e.Info;
        SqlDependency dependency = sender as SqlDependency;

        dependency.OnChange -= OnChange;
        Start();
    }
Exemplo n.º 9
0
        private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            SqlNotificationInfo s          = e.Info;
            List <Scope>        listScopes = ScopeRepository.GetAllCompletedScopes();

            foreach (Scope obj in listScopes)
            {
                ScopeHub.Show(obj);
            }
        }
Exemplo n.º 10
0
        private void OnDatabaseChange(object sender, SqlNotificationEventArgs args)
        {
            SqlNotificationInfo info = args.Info;

            if (SqlNotificationInfo.Insert.Equals(info) || SqlNotificationInfo.Update.Equals(info))
            {
                dataGridView1.Rows.Clear();
                LoadData();
            }
            WatchingQuery();
        }
Exemplo n.º 11
0
        private void OnDatabaseChange(object sender, SqlNotificationEventArgs args)
        {
            SqlNotificationInfo info = args.Info;

            if (SqlNotificationInfo.Insert.Equals(info) ||
                SqlNotificationInfo.Update.Equals(info) ||
                SqlNotificationInfo.Delete.Equals(info))
            {
                this.callback();
            }
            ExecuteWatchingQuery();
        }
Exemplo n.º 12
0
        void onDependencyChange(object sender, SqlNotificationEventArgs args)
        {
            SqlNotificationInfo info = args.Info;

            if (SqlNotificationInfo.Insert.Equals(info) ||
                SqlNotificationInfo.Update.Equals(info) ||
                SqlNotificationInfo.Delete.Equals(info))
            {
                Utilits.Console.Log("[МОНИТОРИНГ] Получены новые данные с сервера.");

                Table table;
                int   i = 0;

                try{
                    sqlConnection = new SqlConnection(DataConfig.serverConnection);
                    sqlCommand    = new SqlCommand("SELECT [id], [name], [represent], [datetime], [error], [user] FROM History", sqlConnection);
                    sqlConnection.Open();
                    sqlDataReader = sqlCommand.ExecuteReader();
                    while (sqlDataReader.Read())
                    {
                        table.name      = sqlDataReader["name"].ToString();
                        table.represent = sqlDataReader["represent"].ToString();
                        table.datetime  = sqlDataReader["datetime"].ToString();
                        table.error     = sqlDataReader["error"].ToString();
                        table.user      = sqlDataReader["user"].ToString();

                        if (tables[i].datetime != table.datetime)
                        {
                            refresh(tables[i].name, tables[i].represent);
                            tables[i] = table;
                        }
                        i++;
                    }
                    sqlDataReader.Close();
                    sqlConnection.Close();
                    DataForms.FClient.indicator(true);
                }catch (Exception ex) {
                    Utilits.Console.Log("[МОНИТОРИНГ:ОШИБКА] " + ex.Message, false, true);
                    if (sqlDataReader != null)
                    {
                        sqlDataReader.Close();
                    }
                    if (sqlConnection != null)
                    {
                        sqlConnection.Close();
                    }
                    DataForms.FClient.indicator(false);
                }
            }
            monitoringProcess();
        }
Exemplo n.º 13
0
        private List <dynamic> obtemListaComMudancas(SqlNotificationInfo Info = SqlNotificationInfo.Unknown)
        {
            List <dynamic> mudancas = new List <dynamic>();

            if (token == null || !Permissoes.Autenticado(token))
            {
                return(mudancas);
            }

            semaforo.WaitOne();

            List <FilaBootICard> oldList = list != null ? list : new List <FilaBootICard>();

            initList();

            DateTime dtOut = DateTime.Now;

            if (list != null)
            {
                try
                {
                    if (Info.Equals(SqlNotificationInfo.Delete))
                    {
                        // Delete
                        mudancas.Add(new { NotificationInfo = Info.ToString().ToUpper(),
                                           objetos          = oldList.Where(e => !list.Any(l => l.id == e.id))
                                                              .ToList <FilaBootICard>() });
                    }
                    else
                    {
                        // Insert, Update
                        mudancas.Add(new { NotificationInfo = Info.ToString().ToUpper(),
                                           objetos          = list.Where(e => !oldList.Any(l => l.id == e.id && l.stProcessamento == e.stProcessamento &&
                                                                                           l.dtInsert == e.dtInsert && l.webpages_UsersInsert.id_users == e.webpages_UsersInsert.id_users &&
                                                                                           ((l.cdUser == null && e.cdUser == null) || (l.cdUser != null && e.cdUser != null && l.cdUser.Value == e.cdUser.Value)) &&//((l.webpages_Users == null && e.webpages_Users == null) || (l.webpages_Users != null && e.webpages_Users != null && l.webpages_Users.id_users == e.webpages_Users.id_users)) &&
                                                                                           ((l.dtProcessamento == null && e.dtProcessamento == null) || (l.dtProcessamento != null && e.dtProcessamento != null && l.dtProcessamento.Value.Equals(e.dtProcessamento.Value)))))
                                                              .ToList <FilaBootICard>() });
                    }
                }
                catch (Exception e)
                {
                }
            }

            semaforo.Release(1);

            return(mudancas);
        }
Exemplo n.º 14
0
        private List <dynamic> obtemListaComMudancas(SqlNotificationInfo Info = SqlNotificationInfo.Unknown)
        {
            List <dynamic> mudancas = new List <dynamic>();

            if (filtro.Token == null || !Permissoes.Autenticado(filtro.Token))
            {
                return(mudancas);
            }

            semaforo.WaitOne();

            List <MonitorCargasBoot> oldList = list != null ? list : new List <MonitorCargasBoot>();

            initList();

            DateTime dtOut = DateTime.Now;

            if (list != null)
            {
                try
                {
                    if (Info.Equals(SqlNotificationInfo.Delete))
                    {
                        // Delete
                        mudancas = getListaAgrupadaEOrdenada(oldList
                                                             .Where(e => !list.Any(l => l.idLogCargaDetalhe == e.idLogCargaDetalhe))    //l.empresa.nu_cnpj == e.empresa.nu_cnpj && l.tbAdquirente.cdAdquirente == e.tbAdquirente.cdAdquirente))
                                                             .ToList <MonitorCargasBoot>(), Info);
                    }
                    else
                    {
                        // Insert, Update
                        mudancas = getListaAgrupadaEOrdenada(list
                                                             .Where(e => !oldList.Any(l => l.idLogCargaDetalhe == e.idLogCargaDetalhe && l.flStatus.Equals(e.flStatus) &&
                                                                                      ((l.dtExecucaoFim == null && e.dtExecucaoFim == null) ||
                                                                                       (l.dtExecucaoFim != null && e.dtExecucaoFim != null && l.dtExecucaoFim.Equals(e.dtExecucaoFim)))))
                                                             .ToList <MonitorCargasBoot>(), Info);
                    }
                }
                catch (Exception e)
                {
                }
            }

            semaforo.Release(1);

            return(mudancas);
        }
Exemplo n.º 15
0
        private void OnDatabaseChange(object sender, SqlNotificationEventArgs args)
        {
            SqlNotificationInfo info = args.Info;

            if (SqlNotificationInfo.Insert.Equals(info))
            {
                pictureBox.Hide();
                labelOrder.Text = "You order is accepted";

                SqlCommand    myCommand = new SqlCommand("SELECT TOP 1 * FROM Orders ORDER BY order_id DESC", conn);
                SqlDataReader myReader  = myCommand.ExecuteReader();
                while (myReader.Read())
                {
                    labelName.Text    = (myReader["taxi_name"].ToString());
                    labelContact.Text = (myReader["taxi_contact"].ToString());
                    labelCarNum.Text  = (myReader["taxi_number"].ToString());
                }
            }
            WatchingQuery();
        }
        /// <summary>
        /// مانیتور دیتابیس
        /// </summary>
        void dep_onchange(object sender, SqlNotificationEventArgs e)
        {
            stateFactor = e.Info;
            //if (e.Info == SqlNotificationInfo.Insert)
            //    MessageBox.Show("insert");
            //if(e.Info == SqlNotificationInfo.Update)
            //    MessageBox.Show("Update");
            //if (e.Info == SqlNotificationInfo.Delete)
            //    MessageBox.Show("Delete");

            if (this.InvokeRequired)
            {
                this.BeginInvoke(new MethodInvoker(GetData));
            }
            else
            {
                GetData();
            }
            SqlDependency dep = sender as SqlDependency;

            dep.OnChange -= new OnChangeEventHandler(dep_onchange);
        }
 internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source)
 {
     IntPtr ptr;
     Bid.NotificationsScopeEnter(out ptr, "<sc.SqlDependency.Invalidate|DEP> %d#", this.ObjectID);
     try
     {
         List<EventContextPair> list = null;
         lock (this._eventHandlerLock)
         {
             if ((this._dependencyFired && (SqlNotificationInfo.AlreadyChanged != info)) && (SqlNotificationSource.Client != source))
             {
                 Bid.NotificationsTrace("<sc.SqlDependency.Invalidate|DEP|ERR> ERROR - notification received twice - we should never enter this state!");
             }
             else
             {
                 this._dependencyFired = true;
                 list = this._eventList;
                 this._eventList = new List<EventContextPair>();
             }
         }
         if (list != null)
         {
             Bid.NotificationsTrace("<sc.SqlDependency.Invalidate|DEP> Firing events.\n");
             foreach (EventContextPair pair in list)
             {
                 pair.Invoke(new SqlNotificationEventArgs(type, info, source));
             }
         }
     }
     finally
     {
         Bid.ScopeLeave(ref ptr);
     }
 }
Exemplo n.º 18
0
		public SqlNotificationEventArgs( SqlNotificationType type, SqlNotificationInfo info,						SqlNotificationSource source) {
			this.type = type;
			this.info = info;
			this.source = source;
		}
Exemplo n.º 19
0
        private List <dynamic> getListaAgrupadaEOrdenada(List <MonitorCargas> lista, SqlNotificationInfo Info = SqlNotificationInfo.Unknown)
        {
            if (lista == null)
            {
                return(null);
            }

            if (lista.Count == 0)
            {
                return(new List <dynamic>());
            }

            //semaforo.WaitOne();

            // Agrupa
            List <MonitorCargasAgrupado> newList = lista
                                                   .GroupBy(e => new { e.loginOperadora.id, e.loginOperadora.status })
                                                   .Select(e => new MonitorCargasAgrupado
            {
                id           = e.Key.id,
                status       = e.Key.status,
                logExecution = e.Select(x => new LogExecutionMonitor
                {
                    id = x.id,
                    dtaFiltroTransacoes = x.dtaFiltroTransacoes,
                    statusExecution     = x.statusExecution,
                    dtaExecucaoFim      = x.dtaExecucaoFim,
                    dtaExecucaoProxima  = x.dtaExecucaoProxima,
                }).OrderBy(x => x.dtaFiltroTransacoes).ToList <LogExecutionMonitor>(),
                ultimaDataExecucaoFim = e.OrderByDescending(x => x.dtaExecucaoFim)
                                        .Select(x => x.dtaExecucaoFim)
                                        .FirstOrDefault(),
                prioridade   = e.Where(x => x.statusExecution.Equals("0")).Count() > 0 ? 1 : 0,
                grupoempresa = e.Select(x => x.grupoempresa).FirstOrDefault(),
                empresa      = e.Select(x => x.empresa).FirstOrDefault(),
                operadora    = e.Select(x => x.operadora).FirstOrDefault(),
            })
                                                   .ToList <MonitorCargasAgrupado>();

            //semaforo.Release(1);

            // Filtro de status?
            if (!filtro.Status.Equals(""))
            {
                if (filtro.Status.Equals("-1"))
                {
                    // Não carregado!
                    newList = newList.Where(e => e.logExecution.Count() == 0)
                              .OrderByDescending(e => e.prioridade)
                              .ThenByDescending(e => e.ultimaDataExecucaoFim)
                              .ThenBy(e => e.empresa.ds_fantasia)
                              .ThenBy(e => e.empresa.filial)
                              .ThenBy(e => e.operadora.nmOperadora)
                              .ToList <MonitorCargasAgrupado>();
                }
                else
                {
                    newList = newList.Where(e => e.logExecution.Any(l => l.statusExecution.Equals(filtro.Status)))
                              .OrderByDescending(e => e.prioridade)
                              .ThenByDescending(e => e.ultimaDataExecucaoFim)
                              .ThenBy(e => e.empresa.ds_fantasia)
                              .ThenBy(e => e.empresa.filial)
                              .ThenBy(e => e.operadora.nmOperadora)
                              .ToList <MonitorCargasAgrupado>();
                }
            }
            else
            {
                // Sem filtro de status => apenas ordena
                newList = newList.OrderByDescending(e => e.prioridade)
                          .ThenByDescending(e => e.ultimaDataExecucaoFim)
                          .ThenBy(e => e.empresa.ds_fantasia)
                          .ThenBy(e => e.empresa.filial)
                          .ThenBy(e => e.operadora.nmOperadora)
                          .ToList <MonitorCargasAgrupado>();
            }

            if (Info.Equals(SqlNotificationInfo.Unknown))
            {
                return(newList.ToList <dynamic>());
            }

            return(new List <dynamic>()
            {
                new { NotificationInfo = Info.ToString().ToUpper(),
                      objetos = newList }
            });
        }
 public SqlNotificationEventArgs(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source)
 {
     _info   = info;
     _source = source;
     _type   = type;
 }
Exemplo n.º 21
0
        private List <dynamic> getListaAgrupadaEOrdenada(List <MonitorCargasBoot> lista, SqlNotificationInfo Info = SqlNotificationInfo.Unknown)
        {
            if (lista == null)
            {
                return(null);
            }

            if (lista.Count == 0)
            {
                return(new List <dynamic>());
            }

            //semaforo.WaitOne();

            // Agrupa
            List <MonitorCargasBootAgrupado> newList = lista
                                                       // Refazer agrupamento => Empresa/Adquirente -> LogCarga
                                                       .GroupBy(e => new { e.empresa.nu_cnpj, e.tbAdquirente.cdAdquirente })
                                                       .Select(e => new MonitorCargasBootAgrupado
            {
                tbLogCargas = e.GroupBy(x => x.tbLogCarga.idLogCarga)
                              .Select(x => new tbLogCargasMonitor
                {
                    idLogCarga                = x.Key,
                    dtCompetencia             = x.Select(d => d.tbLogCarga.dtCompetencia).FirstOrDefault(),
                    flStatusPagosAntecipacao  = x.Select(d => d.tbLogCarga.flStatusPagosAntecipacao).FirstOrDefault(),
                    flStatusPagosCredito      = x.Select(d => d.tbLogCarga.flStatusPagosCredito).FirstOrDefault(),
                    flStatusPagosDebito       = x.Select(d => d.tbLogCarga.flStatusPagosDebito).FirstOrDefault(),
                    flStatusReceber           = x.Select(d => d.tbLogCarga.flStatusReceber).FirstOrDefault(),
                    flStatusVendasCredito     = x.Select(d => d.tbLogCarga.flStatusVendasCredito).FirstOrDefault(),
                    flStatusVendasDebito      = x.Select(d => d.tbLogCarga.flStatusVendasDebito).FirstOrDefault(),
                    tbLogCargasDetalheMonitor = x.OrderBy(d => d.dsModalidade)
                                                .GroupBy(d => d.dsModalidade)
                                                .Select(d => new tbLogCargaDetalheMonitor
                    {
                        dsMensagem          = d.OrderByDescending(f => f.dtExecucaoIni).Select(f => f.dsMensagem).FirstOrDefault(),
                        dsModalidade        = d.Key,
                        dtExecucaoFim       = d.OrderByDescending(f => f.dtExecucaoIni).Select(f => f.dtExecucaoFim).FirstOrDefault(),
                        dtExecucaoIni       = d.OrderByDescending(f => f.dtExecucaoIni).Select(f => f.dtExecucaoIni).FirstOrDefault(),
                        flStatus            = d.OrderByDescending(f => f.dtExecucaoIni).Select(f => f.flStatus).FirstOrDefault(),
                        idLogCargaDetalhe   = d.OrderByDescending(f => f.dtExecucaoIni).Select(f => f.idLogCargaDetalhe).FirstOrDefault(),
                        qtTransacoes        = d.OrderByDescending(f => f.dtExecucaoIni).Select(f => f.qtTransacoes).FirstOrDefault(),
                        vlTotalProcessado   = d.OrderByDescending(f => f.dtExecucaoIni).Select(f => f.vlTotalProcessado).FirstOrDefault(),
                        qtTransacoesCS      = d.OrderByDescending(f => f.dtExecucaoIni).Select(f => f.qtTransacoesCS).FirstOrDefault(),
                        vlTotalProcessadoCS = d.OrderByDescending(f => f.dtExecucaoIni).Select(f => f.vlTotalProcessadoCS).FirstOrDefault(),
                        txAuditoria         = d.OrderByDescending(f => f.dtExecucaoIni).Select(f => f.txAuditoria).FirstOrDefault(),
                    }).ToList <tbLogCargaDetalheMonitor>(),
                }).OrderBy(x => x.dtCompetencia).ToList <tbLogCargasMonitor>(),
                ultimaDataExecucaoFim = e.OrderByDescending(x => x.dtExecucaoFim)
                                        .Select(x => x.dtExecucaoFim)
                                        .FirstOrDefault(),
                prioridade   = e.Where(x => x.flStatus == 0 || x.flStatus == 9).Count() > 0 ? 1 : 0,
                grupoempresa = e.Select(x => x.grupoempresa).FirstOrDefault(),
                empresa      = e.Select(x => x.empresa).FirstOrDefault(),
                tbAdquirente = e.Select(x => x.tbAdquirente).FirstOrDefault(),
            })
                                                       .OrderByDescending(e => e.prioridade)
                                                       .ThenByDescending(e => e.ultimaDataExecucaoFim)
                                                       .ThenBy(e => e.empresa.ds_fantasia)
                                                       .ThenBy(e => e.empresa.filial)
                                                       .ThenBy(e => e.tbAdquirente.nmAdquirente)
                                                       .ToList <MonitorCargasBootAgrupado>();

            if (Info.Equals(SqlNotificationInfo.Unknown))
            {
                return(newList.ToList <dynamic>());
            }

            return(new List <dynamic>()
            {
                new { NotificationInfo = Info.ToString().ToUpper(),
                      objetos = newList }
            });
        }
Exemplo n.º 22
0
        internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source) {
            IntPtr hscp;
            Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependency.Invalidate|DEP> %d#", ObjectID);
            try {
                List<EventContextPair> eventList = null;

                lock (_eventHandlerLock) {
                    if (_dependencyFired                           &&
                        SqlNotificationInfo.AlreadyChanged != info &&
                        SqlNotificationSource.Client       != source) {

                        if (ExpirationTime < DateTime.UtcNow) {
                            // There is a small window in which SqlDependencyPerAppDomainDispatcher.TimeoutTimerCallback
                            // raises Timeout event but before removing this event from the list. If notification is received from
                            // server in this case, we will hit this code path.
                            // It is safe to ignore this race condition because no event is sent to user and no leak happens.
                            Bid.NotificationsTrace("<sc.SqlDependency.Invalidate|DEP> ignore notification received after timeout!");
                        }
                        else {
                            Debug.Assert(false, "Received notification twice - we should never enter this state!");
                            Bid.NotificationsTrace("<sc.SqlDependency.Invalidate|DEP|ERR> ERROR - notification received twice - we should never enter this state!");
                        }
                    }
                    else {
                        // It is the invalidators responsibility to remove this dependency from the app domain static hash.
                        _dependencyFired = true;
                        eventList        = _eventList;
                        _eventList       = new List<EventContextPair>(); // Since we are firing the events, null so we do not fire again.
                    }
                }

                if (eventList != null) {
                    Bid.NotificationsTrace("<sc.SqlDependency.Invalidate|DEP> Firing events.\n");
                    foreach(EventContextPair pair in eventList) {
                        pair.Invoke(new SqlNotificationEventArgs(type, info, source));
                    }
                }
            }
            finally {
                Bid.ScopeLeave(ref hscp);
            }
        }            
Exemplo n.º 23
0
 public SqlNotificationEventArgs(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source)
 {
     this.type   = type;
     this.info   = info;
     this.source = source;
 }
Exemplo n.º 24
0
 public SqlNotificationEventArgs(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source) {
     _info = info;
     _source = source;
     _type = type;
 }
Exemplo n.º 25
0
        public void OnDatabaseChange(object sender, SqlNotificationEventArgs args)
        {
            SqlNotificationInfo info = default;

            if (args != null)
            {
                info = args.Info;
            }
            if (sender == null ||
                SqlNotificationInfo.Insert.Equals(info) ||
                SqlNotificationInfo.Update.Equals(info))
            {
                _logger.LogInformation($"Leads ServiceBroker called {info}");
                var attempts = maxAttempts;
                while (attempts-- > 0)
                {
                    try
                    {
                        using var conn = new SqlConnection(connStr);
                        conn.Open();
                        var cmd = conn.CreateCommand();
                        cmd.CommandText   = $"select someFields from {database}";
                        using var adapter = new SqlDataAdapter(cmd);
                        using var dataset = new DataSet();
                        adapter.Fill(dataset);

                        var incomedLeads = dataset.Tables[0].AsEnumerable().Select
                                           (
                            row => new LeadInfo(row.Field <int>("id"),
                                                row.Field <string>("clickid")))
                                           .Where(lead => lead.transaction_id != "")
                                           .ToArray();

                        foreach (var lead in incomedLeads)
                        {
                            string postback;
                            string result;
                            if (lead.prevstat == "")
                            {
                                postback = $"{PostBackUrl}&some_postback_parameters";
                                var statnew = Common.SendPostBack(postback, out result);
                                _logger.LogInformation($"Postback sent=>type:new      ,some info");
                                if (statnew == RequestResult.Success && lead.status != "pending")
                                {
                                    postback = $"{PostBackUrl}&some_postback_parameters";
                                    var statupdatenew = Common.SendPostBack(postback, out result);
                                    _logger.LogInformation($"Postback sent=>type:newupdate,some info");
                                }
                                if (statnew == RequestResult.Success)
                                {
                                    cmd.CommandText = $"update {database} set prevstat='{lead.status}' where id={lead.leadid}";
                                    cmd.ExecuteNonQuery();
                                }
                                else if (statnew == RequestResult.BadTransactionId)
                                {
                                    cmd.CommandText = $"update {database} set clickid='' where id={lead.leadid}";
                                    cmd.ExecuteNonQuery();
                                }
                            }
                            else if (lead.status != lead.prevstat)
                            {
                                postback = $"{PostBackUrl}&some_postback_parameters";
                                var statupdate = Common.SendPostBack(postback, out result);
                                _logger.LogInformation($"Postback sent=>type:   update,some info");
                                if (statupdate == RequestResult.Success)
                                {
                                    cmd.CommandText = $"update {database} set prevstat='{lead.status}' where id={lead.leadid}";
                                    cmd.ExecuteNonQuery();
                                }
                            }
                        }
                        break;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex.ToString());
                        Task.Delay(1000);
                        continue;
                    }
                }
            }
        }
Exemplo n.º 26
0
        public static void Send(string message, SqlNotificationInfo info)
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext <DataHub>();

            context.Clients.All.newMessage(message, info.ToString());
        }