Exemplo n.º 1
0
        /// <summary>
        /// Builds a project.
        /// </summary>
        /// <param name="projectPath">The absolute path to the project.</param>
        /// <param name="targetsToBuild">The targets to build. If not specified, the project's default target will be invoked.</param>
        /// <param name="properties">The optional global properties to pass to the project. May come from the <see cref="MSBuild.Properties"/> static class.</param>
        /// <returns>A task whose result is the result of the build.</returns>
        public static async Task<BuildResultAndLogs> ExecuteAsync(string projectPath, string[] targetsToBuild = null, IDictionary<string, string> properties = null, ITestOutputHelper testLogger = null)
        {
            targetsToBuild = targetsToBuild ?? new string[0];

            var logger = new EventLogger();
            var logLines = new List<string>();
            var parameters = new BuildParameters
            {
                Loggers = new List<ILogger>
                {
                    new ConsoleLogger(LoggerVerbosity.Detailed, logLines.Add, null, null),
                    new ConsoleLogger(LoggerVerbosity.Minimal, v => testLogger?.WriteLine(v.TrimEnd()), null, null),
                    logger,
                },
            };

            BuildResult result;
            using (var buildManager = new BuildManager())
            {
                buildManager.BeginBuild(parameters);
                try
                {
                    var requestData = new BuildRequestData(projectPath, properties ?? Properties.Default, null, targetsToBuild, null);
                    var submission = buildManager.PendBuildRequest(requestData);
                    result = await submission.ExecuteAsync();
                }
                finally
                {
                    buildManager.EndBuild();
                }
            }

            return new BuildResultAndLogs(result, logger.LogEvents, logLines);
        }
Exemplo n.º 2
0
    public DataTable obtenerPerfiles()
    {
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter();
        SqlConnection cn = new SqlConnection(cd.getConnectionString());

        try
        {
            cn.Open();
            da = new SqlDataAdapter("SP_TABLA_PERFIL_OBTENER", cn);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.Fill(dt);
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex); //ASP.NET 2.0.50727.0
            dt = null;
        }
        finally
        {
            cn.Close();
        }

        return dt;
    }
Exemplo n.º 3
0
        /// <summary>
        /// Builds a project.
        /// </summary>
        /// <param name="projectInstance">The project to build.</param>
        /// <param name="targetsToBuild">The targets to build. If not specified, the project's default target will be invoked.</param>
        /// <returns>A task whose result is the result of the build.</returns>
        public static async Task<BuildResultAndLogs> ExecuteAsync(ProjectInstance projectInstance, params string[] targetsToBuild)
        {
            targetsToBuild = (targetsToBuild == null || targetsToBuild.Length == 0) ? projectInstance.DefaultTargets.ToArray() : targetsToBuild;

            var logger = new EventLogger();
            var logLines = new List<string>();
            var parameters = new BuildParameters
            {
                Loggers = new List<ILogger>
                {
                    new ConsoleLogger(LoggerVerbosity.Detailed, logLines.Add, null, null),
                    logger,
                },
            };

            BuildResult result;
            using (var buildManager = new BuildManager())
            {
                buildManager.BeginBuild(parameters);
                try
                {
                    var brdFlags = BuildRequestDataFlags.ProvideProjectStateAfterBuild;
                    var requestData = new BuildRequestData(projectInstance, targetsToBuild, null, brdFlags);
                    var submission = buildManager.PendBuildRequest(requestData);
                    result = await submission.ExecuteAsync();
                }
                finally
                {
                    buildManager.EndBuild();
                }
            }

            return new BuildResultAndLogs(result, logger.LogEvents, logLines);
        }
Exemplo n.º 4
0
    protected void cmdBuscar_Click(object sender, EventArgs e)
    {
        try
        {
            DataTable dtPais = new DataTable();
            dtPais = pais.obtener(txtNomenclatura.Text, txtNombre.Text, txtEdad.Text);

            if (dtPais != null)
            {
                if (dtPais.Rows.Count == 0)
                    divMensaje.InnerHtml = "<div id=\"info\">No hay resultados que coincidan con los criterios de búsqueda ingresados.</div>";
                else
                    divMensaje.InnerHtml = "";

                gvPais.DataSource = dtPais;
                gvPais.DataBind();
            }
            else
                divMensaje.InnerHtml = "<div id=\"error\">Ha ocurrido un error al cargar la lista de países.</div>";
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0 [vistaPaises - método: cmdBuscar_Click]", ex);
        }
    }
Exemplo n.º 5
0
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Detalle")
        {
            try
            {
                //int i = Convert.ToInt16(e.CommandArgument);// - (GvFormaPago.PageIndex * GvFormaPago.PageSize);
                //string reingresoid = Convert.ToString(GridView1.DataKeys[i].Value);

                string region = GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].Values[0].ToString();
                string zona = GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].Values[1].ToString();
                string _estado = GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].Values[2].ToString();

                int estado = 0;
                if (_estado.Equals("True"))
                    estado = 1;

                Response.Redirect("ReingresoDetalle.aspx?ps=" + Session["paisId"].ToString() + "&rn=" + region + "&za=" + zona +"&eo=" + estado, false);
            }
            catch (Exception ex)
            {
                EventLogger ev = new EventLogger();
                ev.Save("Reingreso, RowCommand ", ex);
            }
        }
    }
Exemplo n.º 6
0
    protected void Page_Load(object sender, EventArgs e)
    {
        String APPID, IDPAIS, PIN, IMSI;

        APPID = Request.QueryString.Get("APPID");
        IDPAIS = Request.QueryString.Get("IDPAIS");
        PIN = Request.QueryString.Get("PIN");
        IMSI = Request.QueryString.Get("IMSI");

         try
        {
            String sqlUsuario =
                "SELECT     Tablas.idTablas, Tablas.Descripcion "+
                " FROM         Tablas INNER JOIN " +
                "  TipoTabla ON Tablas.TipoTabla_idTipoTabla = TipoTabla.idTipoTabla " +
                " where Tablas.Pais_idPais = '"+ IDPAIS +"' and TipoTabla.idTipoTabla = '5' "+
                " and Tablas.estado = 'true' ";
            DataTable dtsUsuario = new DataTable();
            dtsUsuario = con.AccesoDatos(sqlUsuario);
             int size = dtsUsuario.Rows.Count ;
             //if (size != 0)
             //{
             //    lblResultado.Text = "";
             //    for (int i = 0; i < size; i++)
             //    {
             //        lblResultado.Text += Convert.ToString(dtsUsuario.Rows[i][0]);
             //        lblResultado.Text += con.separador() + dtsUsuario.Rows[i][1] + " <br/>";
             //    }
             //}
             //else
             //    lblResultado.Text = "sin datos";

             Response.Clear();
             Response.Buffer = true;
             Response.AddHeader("Content-type","text/xml");
             Response.AddHeader("charset","iso-8859-1");
             Response.Write("<?xml version=" + (char)34 + "1.0" + (char)34 + "?> ");
             //Response.Write("<XML>");
             Response.Write("<R>");
                 for (int i = 0; i < size; i++)
                 {

                    Response.Write("<A>");
                    Response.Write(Convert.ToString(dtsUsuario.Rows[i][0]));
                    Response.Write("|");
                    Response.Write(Convert.ToString(dtsUsuario.Rows[i][1]));
                    Response.Write("</A>");

                 }
                 Response.Write("</R>");
            //Response.Write("</XML>");

         }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("sw2, error tb.Tablas ", ex);

        }
    }
Exemplo n.º 7
0
        public void EventLoggerLogErrorException()
        {
            ManualResetEvent handle = new ManualResetEvent(false);

            try
            {
                EventLogger logger = new EventLogger();
                Exception ex = new Exception();

                logger.Log += (sender, args) =>
                {
                    Assert.AreEqual(EventLoggerEventType.Error, args.EventType);
                    Assert.AreEqual(string.Empty, args.Message);
                    Assert.AreEqual(ex, args.Exception);
                    handle.Set();
                };

                logger.Error(ex);
                WaitHandle.WaitAll(new WaitHandle[] { handle });
            }
            finally
            {
                handle.Close();
            }
        }
Exemplo n.º 8
0
    public String actualizar(int divisionID, bool estado, SqlCommand cmd)
    {
        String resultado = "success";
        SqlCommand cmdLocal = new SqlCommand();
        cmdLocal = cmd;
        try
        {
            cmdLocal = new SqlCommand("SP_DIVPOLITICA_ACTUALIZAR_ESTADO", cmd.Connection);
            cmdLocal.CommandType = CommandType.StoredProcedure;
            cmdLocal.Transaction = cmd.Transaction;
            //cmd.Transaction = cn.BeginTransaction();

            cmdLocal.Parameters.Add("@divisionID", SqlDbType.Int).Value = divisionID;
            cmdLocal.Parameters.Add("@estado", SqlDbType.Bit).Value = estado;

            cmdLocal.ExecuteNonQuery();
            //cmd.Transaction.Commit();
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex); //ASP.NET 2.0.50727.0
            resultado = ex.Message;
            //cmd.Transaction.Rollback();
        }
        finally
        {
            //cn.Close();
        }

        return resultado;
    }
Exemplo n.º 9
0
    public DataTable obtenerPorPaisID(int paisID)
    {
        DataTable dt = new DataTable("ListaDivisiones");
        SqlDataAdapter da = new SqlDataAdapter();
        SqlConnection cn = new SqlConnection(cd.getConnectionString());

        try
        {
            cn.Open();
            da = new SqlDataAdapter("SP_DIVPOLITICA_OBTENER_POR_PAIS", cn);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.SelectCommand.Parameters.Add("@paisID", SqlDbType.Int).Value = paisID;
            da.Fill(dt);
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex); //ASP.NET 2.0.50727.0
            dt = null;
        }
        finally
        {
            cn.Close();
        }

        return dt;
    }
Exemplo n.º 10
0
    protected void cmdBuscar_Click(object sender, EventArgs e)
    {
        try
        {
            int num = Convert.ToInt32(ddlPerfil.SelectedValue);
            DataTable dtUsuario = new DataTable();
            dtUsuario = usuario.obtener(Convert.ToInt32(Session["paisID"]), txtNombre.Text, Convert.ToInt32(ddlPerfil.SelectedValue), ddlEstado.SelectedValue);

            if (dtUsuario != null)
            {
                if (dtUsuario.Rows.Count == 0)
                    divMensaje.InnerHtml = "<div id=\"info\">No hay resultados que coincidan con los criterios de búsqueda ingresados.</div>";
                else
                    divMensaje.InnerHtml = "";

                gvUsuarios.DataSource = dtUsuario;
                gvUsuarios.DataBind();
            }
            else
                divMensaje.InnerHtml = "<div id=\"error\">Ha ocurrido un error al cargar la lista de usuarios.</div>";
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0 [vistaUsuarios - método: cmdBuscar_Click]", ex);
        }
    }
Exemplo n.º 11
0
    public DataTable cargar(int usuarioID)
    {
        DataTable dt = new DataTable("Usuario");
        SqlDataAdapter da = new SqlDataAdapter();
        SqlConnection cn = new SqlConnection(cd.getConnectionString());

        try
        {
            cn.Open();
            da = new SqlDataAdapter("SP_USUARIO_CARGAR", cn);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.SelectCommand.Parameters.Add("@usuarioID", SqlDbType.Int).Value = usuarioID;
            da.Fill(dt);
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex); //ASP.NET 2.0.50727.0
            dt = null;
        }
        finally
        {
            cn.Close();
        }

        return dt;
    }
Exemplo n.º 12
0
    protected void cmdBuscar_Click(object sender, EventArgs e)
    {
        try
        {
            DataTable dtGZ = new DataTable();
            dtGZ = gz.obtener(txtUsuario.Text, txtRegion.Text, txtZona.Text);

            if (dtGZ != null)
            {
                if (dtGZ.Rows.Count == 0)
                    divMensaje.InnerHtml = "<div id=\"info\">No hay resultados que coincidan con los criterios de búsqueda ingresados.</div>";
                else
                    divMensaje.InnerHtml = "";

                gvGerenteZona.DataSource = dtGZ;
                gvGerenteZona.DataBind();
            }
            else
                divMensaje.InnerHtml = "<div id=\"error\">Ha ocurrido un error al cargar la lista de gerentes de zona.</div>";
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0 [vistaGZ - método: cmdBuscar_Click]", ex);
        }
    }
 public static void Main(string[] args)
 {
     IReader reader = new ConsoleReader();
     IWriter writer = new ConsoleWriter();
     IEventHolder events = new EventHolder();
     IEventLogger logger = new EventLogger();
     IEventEngine eventEngine = new EventEngine(reader, writer, events, logger);
     eventEngine.Run();
 }
Exemplo n.º 14
0
    protected void Login1_Authenticate1(object sender, AuthenticateEventArgs e)
    {
        try
        {
            DropDownList ddlPais = ((DropDownList)(Login1.FindControl("ddlPais")));

            bool Autenticado = false;
            Autenticado = LoginCorrecto(Login1.UserName, Login1.Password, ddlPais.SelectedValue);
            e.Authenticated = Autenticado;
            if (Autenticado)
            {
                Response.Redirect("Inicio.aspx?ctry=" + Session["paisID"].ToString());
            }
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex);
        }
    }
Exemplo n.º 15
0
    public String actualizar(int correoID, int operacionID, String apellidoPaterno, String apellidoMaterno, String nombres, String nrodoc, String email, bool estado)
    {
        String resultado = "success";

        SqlDataAdapter da = new SqlDataAdapter();
        SqlCommand cmd = new SqlCommand();
        SqlConnection cn = new SqlConnection(cd.getConnectionString());

        try
        {
            cn.Open();
            cmd = new SqlCommand("SP_CORREO_ACTUALIZAR", cn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Transaction = cn.BeginTransaction();

            cmd.Parameters.Add("@correoID", SqlDbType.Int).Value = correoID;
            cmd.Parameters.Add("@operacionID", SqlDbType.Int).Value = operacionID;
            cmd.Parameters.Add("@apellidoPaterno", SqlDbType.VarChar, 30).Value = apellidoPaterno;
            cmd.Parameters.Add("@apellidoMaterno", SqlDbType.VarChar, 30).Value = apellidoMaterno;
            cmd.Parameters.Add("@nombres", SqlDbType.VarChar, 30).Value = nombres;
            cmd.Parameters.Add("@numeroDocumento", SqlDbType.Char, 18).Value = nrodoc;
            cmd.Parameters.Add("@email", SqlDbType.VarChar, 40).Value = email;
            cmd.Parameters.Add("@estado", SqlDbType.Bit).Value = estado;

            cmd.ExecuteNonQuery();
            cmd.Transaction.Commit();
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex); //ASP.NET 2.0.50727.0
            resultado = ex.Message;
            cmd.Transaction.Rollback();
        }
        finally
        {
            cn.Close();
        }

        return resultado;
    }
Exemplo n.º 16
0
    public String actualizar(int gerenteID, String pin, String imsi, bool estado)
    {
        String resultado = "success";

        SqlDataAdapter da = new SqlDataAdapter();
        SqlCommand cmd = new SqlCommand();
        SqlConnection cn = new SqlConnection(cd.getConnectionString());

        try
        {
            cn.Open();
            cmd = new SqlCommand("SP_GERENTEZONA_ACTUALIZAR", cn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Transaction = cn.BeginTransaction();

            cmd.Parameters.Add("@gerenteID", SqlDbType.Int).Value = gerenteID;
            cmd.Parameters.Add("@pin", SqlDbType.VarChar, 20).Value = pin;
            cmd.Parameters.Add("@imsi", SqlDbType.VarChar, 20).Value = imsi;
            cmd.Parameters.Add("@estado", SqlDbType.Bit).Value = estado;

            cmd.ExecuteNonQuery();
            cmd.Transaction.Commit();
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex); //ASP.NET 2.0.50727.0
            resultado = ex.Message;
            cmd.Transaction.Rollback();
        }
        finally
        {
            cn.Close();
        }

        return resultado;
    }
Exemplo n.º 17
0
        public void EventLoggerLogDebug()
        {
            ManualResetEvent handle = new ManualResetEvent(false);

            try
            {
                EventLogger logger = new EventLogger();

                logger.Log += (sender, args) =>
                {
                    Assert.AreEqual(EventLoggerEventType.Debug, args.EventType);
                    Assert.AreEqual("Debug", args.Message);
                    Assert.IsNull(args.Exception);
                    handle.Set();
                };

                logger.Debug("Debug");
                WaitHandle.WaitAll(new WaitHandle[] { handle });
            }
            finally
            {
                handle.Close();
            }
        }
Exemplo n.º 18
0
    public String actualizar(int usuarioID, int perfilID, String nombres, bool estado)
    {
        String resultado = "success";

        SqlCommand cmd = new SqlCommand();
        SqlConnection cn = new SqlConnection(cd.getConnectionString());

        try
        {
            cn.Open();
            cmd = new SqlCommand("SP_USUARIO_ACTUALIZAR", cn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Transaction = cn.BeginTransaction();

            cmd.Parameters.Add("@usuarioID", SqlDbType.Int).Value = usuarioID;
            cmd.Parameters.Add("@perfilID", SqlDbType.Int).Value = perfilID;
            cmd.Parameters.Add("@nombres", SqlDbType.VarChar, 99).Value = nombres;
            cmd.Parameters.Add("@estado", SqlDbType.Bit).Value = estado;

            cmd.ExecuteNonQuery();
            cmd.Transaction.Commit();
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex); //ASP.NET 2.0.50727.0
            resultado = ex.Message;
            cmd.Transaction.Rollback();
        }
        finally
        {
            cn.Close();
        }

        return resultado;
    }
Exemplo n.º 19
0
        private string rfidPrefix;                                                      // set in constructor based on paramters configured in the windows registry for this service

        #endregion

        #region INITIALISATION ---------------------------------------------------------------

        // default constructor
        public LsapdFileWriter(string outputFolder, string rfidLabelPrefix, EventLogger logger) : base(outputFolder, logger)
        {
            RfidPrefix = rfidLabelPrefix;                                               // The prefix is environment-specific, for example 'U' for UAT or 'P' for PROD, to ensure that printed tags are kept separate in each environment

            // nothing more to do here - all taken care of in base
        }
Exemplo n.º 20
0
 public string AccesoDatosIngreso(string sSQL)
 {
     try
     {
         using (SqlConnection connection = new SqlConnection(StrCx))
         {
             connection.Open();
             SqlCommand command = new SqlCommand(sSQL, connection);
             SqlDataReader reader = command.ExecuteReader();
             reader.Close();
             return "1|";
         }
     }
     catch (Exception e)
     {
         EventLogger ev = new EventLogger();
         ev.Save("error al intentar guardar la informacion ", e);
         return "0|"+e;
         //return "0|" + "error al intentar acceder a la base de datos.";
     }
 }
Exemplo n.º 21
0
 public static void LogEvent(SysEventType eventType, string eventName, string customMessage)
 {
     EventLogger.LogEvent(eventType.ToString(), eventName, customMessage, null);
 }
Exemplo n.º 22
0
        public ActionResult <List <AreaEvent> > getCameraEvents(string cameraHost)
        {
            List <AreaEvent> events = EventLogger.getCameraEvents(cameraHost);

            return(events);
        }
Exemplo n.º 23
0
        private void HandleReceive(IAsyncResult result)
        {
            int        BytesReceived;
            IPEndPoint from;
            IPEndPoint src;
            bool       Disconnect = false;

            try
            {
                if (MainSocket.SocketType == SocketType.Stream)
                {
                    from          = (IPEndPoint)MainSocket.RemoteEndPoint;
                    BytesReceived = MainSocket.EndReceive(result);
                }
                else
                {
                    BytesReceived = MainSocket.EndReceiveFrom(result, ref rEP);
                    from          = (IPEndPoint)rEP;
                }
            }
            catch (Exception ex)
            {
                // Socket Error
                bool _OK = false;
                EventLogger.Log(ex);
                lock (this)
                {
                    if (SentDisconnect == false)
                    {
                        _OK            = true;
                        SentDisconnect = true;
                    }
                }
                if (_OK)
                {
                    MainSocket = null;
                }
                if (_OK)
                {
                    OnDisconnectEvent.Fire(this);
                }
                return;
            }

            //			OpenSource.Utilities.EventLogger.Log(this,System.Diagnostics.EventLogEntryType.Information,"BytesRead: " + BytesReceived.ToString() + " BytesRequested: "+this.BufferReadLength.ToString());

            if (BytesReceived <= 0)
            {
                Disconnect = true;
            }

            if (BytesReceived != 0)
            {
                try
                {
                    src = (IPEndPoint)MainSocket.LocalEndPoint;
                }
                catch (Exception ex)
                {
                    EventLogger.Log(ex);
                    src = new IPEndPoint(IPAddress.Any, 0);
                }


                BufferEndPointer += BytesReceived;

                BufferSize       = BufferEndPointer - BufferBeginPointer;
                BufferReadLength = MainBuffer.Length - BufferEndPointer;

                if (_WriteStream == null)
                {
                    try
                    {
                        OnReceiveEvent.Fire(this, MainBuffer, BufferBeginPointer, BufferSize, BytesReceived, src, from);
                    }
                    catch (StopReadException ex)
                    {
                        EventLogger.Log(ex);
                        return;
                    }
                }
                else
                {
                    _WriteStream.Write(MainBuffer, 0, BytesReceived);
                    BufferBeginPointer = BufferEndPointer;
                    BufferReadLength   = MainBuffer.Length;
                }

                while ((BufferBeginPointer != 0) &&
                       (BufferBeginPointer != BufferEndPointer))
                {
                    Array.Copy(MainBuffer, BufferBeginPointer, MainBuffer, 0, BufferEndPointer - BufferBeginPointer);
                    BufferEndPointer   = BufferEndPointer - BufferBeginPointer;
                    BufferBeginPointer = 0;
                    BufferSize         = BufferEndPointer;
                    try
                    {
                        OnReceiveEvent.Fire(this, MainBuffer, BufferBeginPointer, BufferSize, 0, src, from);
                    }
                    catch (StopReadException ex)
                    {
                        EventLogger.Log(ex);
                        return;
                    }
                    if (StopThread != null)
                    {
                        if (Thread.CurrentThread.GetHashCode() == StopThread.GetHashCode())
                        {
                            StopThread = null;
                            return;
                        }
                    }
                }

                if (BufferBeginPointer == BufferEndPointer)
                {
                    // ResetBuffer then continue reading
                    BufferBeginPointer = 0;
                    BufferEndPointer   = 0;
                }

                if (StopThread != null)
                {
                    if (Thread.CurrentThread.GetHashCode() == StopThread.GetHashCode())
                    {
                        StopThread = null;
                        return;
                    }
                }
                try
                {
                    if (MainSocket != null && MainSocket.Connected)
                    {
                        if (MainSocket.SocketType == SocketType.Stream)
                        {
                            MainSocket.BeginReceive(MainBuffer, BufferEndPointer, BufferReadLength, SocketFlags.None, ReceiveCB, MainSocket);
                        }
                        else
                        {
                            MainSocket.BeginReceiveFrom(MainBuffer, BufferEndPointer, BufferReadLength, SocketFlags.None, ref rEP, ReceiveCB, MainSocket);
                        }
                    }
                    else
                    {
                        Disconnect = true;
                    }
                }
                catch (Exception ex)
                {
                    EventLogger.Log(ex);
                    Disconnect = true;
                }
            }

            if (Disconnect)
            {
                bool OK = false;
                lock (this)
                {
                    if (SentDisconnect == false)
                    {
                        OK             = true;
                        SentDisconnect = true;
                    }
                }
                if (OK)
                {
                    MainSocket = null;
                }
                if (Disconnect && OK)
                {
                    OnDisconnectEvent.Fire(this);
                }
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Asynchronously send a UDP payload
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="length"></param>
        /// <param name="dest"></param>
        /// <param name="Tag"></param>
        public void Send(Byte[] buffer, int offset, int length, IPEndPoint dest, object Tag)
        {
            bool Disconnect = false;

            SendInfo SI;

            lock (SendLock)
            {
                lock (CountLock)
                {
                    if (PendingBytesSent > 0)
                    {
                        SI        = new SendInfo();
                        SI.buffer = buffer;
                        SI.offset = offset;
                        SI.count  = length;
                        SI.dest   = dest;
                        SI.Tag    = Tag;
                        SendQueue.Enqueue(SI);
                    }
                    else
                    {
                        PendingBytesSent += length;
                        try
                        {
                            if (MainSocket.SocketType == SocketType.Stream)
                            {
                                MainSocket.BeginSend(buffer, offset, length, SocketFlags.None, SendCB, Tag);
                            }
                            else
                            {
                                MainSocket.BeginSendTo(buffer, offset, length, SocketFlags.None, dest, SendCB, Tag);
                            }
                        }
                        catch (Exception ex)
                        {
                            EventLogger.Log(ex);
                            EventLogger.Log(this, EventLogEntryType.Error, "Send Failure [Normal for non-pipelined connection]");
                            Disconnect = true;
                        }
                    }
                }
            }

            if (Disconnect)
            {
                bool OK = false;
                lock (this)
                {
                    if (SentDisconnect == false)
                    {
                        OK             = true;
                        SentDisconnect = true;
                    }
                }
                if (OK)
                {
                    MainSocket = null;
                    OnDisconnectEvent.Fire(this);
                }
            }
        }
Exemplo n.º 25
0
    public DataTable obtener(String nombres, String regionCodigo, String zonaCodigo)
    {
        DataTable dt = new DataTable("ListadoGerentes");
        SqlDataAdapter da = new SqlDataAdapter();
        SqlConnection cn = new SqlConnection(cd.getConnectionString());

        try
        {
            cn.Open();
            da = new SqlDataAdapter("SP_GERENTEZONA_OBTENER", cn);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;

            da.SelectCommand.Parameters.Add("@nombres", SqlDbType.VarChar, 30).Value = nombres;
            da.SelectCommand.Parameters.Add("@regionCodigo", SqlDbType.VarChar, 2).Value = regionCodigo;
            da.SelectCommand.Parameters.Add("@zonaCodgo", SqlDbType.VarChar, 6).Value = zonaCodigo;

            da.Fill(dt);
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex); //ASP.NET 2.0.50727.0
            dt = null;
        }
        finally
        {
            cn.Close();
        }

        return dt;
    }
Exemplo n.º 26
0
    //Generate new waves and spawn them on scene
    private void SpawnNewWave()
    {
        EventLogger.PrintToLog("New Wave Spawn");

        //determine if current wave formation has an empty space bigger than the size of the player ship
        const int   randRange = 100;
        const float stepSize  = (float)randRange / GameConstants.DifficultyStepCount;       //step size is currently 20

        // 10 30 50 70 90 no exit probability for difficulties 1 2 3 4 5
        float noExitProbability =
            (_difficultyManagerScript.DifficultyCoefs[DifficultyParameter.DpWaveHasNoExitCoef] - 0.5f) * stepSize;
        bool hasNoExit = Random.Range(0, randRange) < noExitProbability;

        //I. Pick a random formation type
        int       selectedFormationIndex = Random.Range(0, _formations.Count);
        Formation selectedFormation      = _formations[selectedFormationIndex];

        //determine next wave spawn interval
        float randomIntervalCoef = Random.Range(MinWaveSpawnIntervalCoef, MaxWaveSpawnIntervalCoef);

        _waveSpawnInterval = randomIntervalCoef / _difficultyManagerScript.GetDifficultyMultiplier(DifficultyParameter.DpWaveSpawnRateIncrease);

        //II. Determine Horizontal Distance Between Enemies
        float nextWaveHorizontalDistance = _waveSpawnInterval * BasicEnemy.MoveSpeed;
        float maxEnemyHorizontalDist     = nextWaveHorizontalDistance - EnemySpawnMaxHorzDist;

        if (selectedFormation.HorizontalShipSpan > 1)
        {
            maxEnemyHorizontalDist /= selectedFormation.HorizontalShipSpan;
        }

        float enemyHorizontalDist;

        if (maxEnemyHorizontalDist < _enemySpawnMinHorzDist)
        {
            enemyHorizontalDist = maxEnemyHorizontalDist;
        }
        else
        {
            maxEnemyHorizontalDist = Mathf.Clamp(maxEnemyHorizontalDist, _enemySpawnMinHorzDist, EnemySpawnMaxHorzDist);
            enemyHorizontalDist    = Random.Range(_enemySpawnMinHorzDist, maxEnemyHorizontalDist);
        }

        //III. Determine Vertical Distance Between Enemies
        float verticalMovementLength = _vertMaxShipSpawnCoord - _vertMinShipSpawnCoord;
        float minEnemyVerticalDist   = _enemySpawnMinVertDist;

        if (hasNoExit)
        {
            int maxIntervalCount = selectedFormation.WaveEntities.Count - 1;

            float minVerticalDistance = (verticalMovementLength - ShipColliderVertSize) / maxIntervalCount;
            if (minVerticalDistance > minEnemyVerticalDist)
            {
                minEnemyVerticalDist = minVerticalDistance;
            }
        }
        float enemyVerticalDist = Random.Range(minEnemyVerticalDist, EnemySpawnMaxVertDist);

        //IV. Determine Number of Enemies
        int lowerIntervalCount  = Mathf.FloorToInt((verticalMovementLength - ShipColliderVertSize) / enemyVerticalDist);
        int higherIntervalCount = Mathf.FloorToInt(verticalMovementLength / enemyVerticalDist);

        int maxPossibleVerticalIntervalCount = (lowerIntervalCount == higherIntervalCount) && !hasNoExit ? lowerIntervalCount : lowerIntervalCount + 1;

        float distBetweenFirstAndLastShip = enemyVerticalDist * maxPossibleVerticalIntervalCount;

        Assert.IsTrue(!hasNoExit || (distBetweenFirstAndLastShip >= verticalMovementLength - ShipColliderVertSize));

        int maxPossibleShipCount = maxPossibleVerticalIntervalCount + 1;
        int enemyCount;

        if (hasNoExit)
        {
            enemyCount = maxPossibleShipCount;
        }
        else
        {
            //no possible no-exits here, this is why we subtract 1 from max possible ship count, we want at least a sufficient opening
            int enemyMaxCount = Mathf.Min(maxPossibleShipCount - 1, selectedFormation.WaveEntities.Count);

            int minimumEnemyCountCoef = _difficultyManagerScript.DifficultyCoefs[DifficultyParameter.DpMinimumEnemyCountCoef];

            //diff param (1 2 3 4 5) : min count = max count - (4 3 2 1 0)
            //TODO LATER if 5 level difficulty is changed, enemy counts will break as we don't take min max difficulty difference into account
            int enemyMinCount = Mathf.Max(1, enemyMaxCount - (GameConstants.MaxDifficulty - minimumEnemyCountCoef));

            enemyCount = Random.Range(enemyMinCount, enemyMaxCount);
        }

        int   actualVerticalIntervalCount = enemyCount - 1;
        float minVerticalStartCoord       = _vertMinShipSpawnCoord;
        float maxVerticalStartCoord       = _vertMaxShipSpawnCoord - actualVerticalIntervalCount * enemyVerticalDist;

        if (maxVerticalStartCoord < minVerticalStartCoord)
        {
            //we just went off the line, this is only possible for no exit formations!
            Assert.IsTrue(hasNoExit);

            //swap these two
            maxVerticalStartCoord += minVerticalStartCoord;
            minVerticalStartCoord  = maxVerticalStartCoord - minVerticalStartCoord;
            maxVerticalStartCoord -= minVerticalStartCoord;

            if (_hugeEnemyExists)
            {
                if (!Mathf.Approximately(_vertMinShipSpawnCoord, Player.MinVerticalMovementLimit))
                {
                    minVerticalStartCoord = maxVerticalStartCoord;
                }
                else if (!Mathf.Approximately(_vertMaxShipSpawnCoord, Player.MaxVerticalMovementLimit))
                {
                    maxVerticalStartCoord = minVerticalStartCoord;
                }
                else
                {
                    Assert.IsTrue(false);                     //something is fishy, spawning a huge enemy didn't change vertical spawn coords
                }
            }
        }
        else
        {
            Assert.IsTrue(distBetweenFirstAndLastShip <= verticalMovementLength);
        }

        //V. Select Enemies From Formation List
        List <WaveEntity> selectedFormationEntities = SelectEnemiesFromFormation(selectedFormationIndex, enemyCount);

        //VI. Determine Advanced Enemy Count
        int enemyTypeCount = EnemyPrefabArray.Length;

        int[] enemyTypeSteps = new int[enemyTypeCount];
        for (int i = 0; i < enemyTypeSteps.Length; ++i)
        {
            enemyTypeSteps[i] = Mathf.RoundToInt(i * 100.0f / (enemyTypeSteps.Length - 1));
            //enemyTypeSteps = {0, 100} for 2 enemies, {0, 50, 100} for 3 enemies, {0, 33, 67, 100} for 4 enemies, and so on
        }

        float advancedEnemyPercentage = _difficultyManagerScript.DifficultyCoefs[DifficultyParameter.DpEnemyShipStrength] * stepSize - stepSize * 0.5f;

        int   advEnemyTypeIndex         = 1;
        float percentageOfStrongerEnemy = 0.0f;

        if (enemyTypeSteps.Length > 1)
        {
            int currentEnemyTypeStep = enemyTypeSteps[advEnemyTypeIndex];
            while (advancedEnemyPercentage > currentEnemyTypeStep)
            {
                ++advEnemyTypeIndex;
                Assert.IsTrue(advEnemyTypeIndex < enemyTypeSteps.Length);
                currentEnemyTypeStep = enemyTypeSteps[advEnemyTypeIndex];
            }
            // if we're here, we know which two enemies we're gonna use
            int previousEnemyTypeStep = enemyTypeSteps[advEnemyTypeIndex - 1];
            percentageOfStrongerEnemy = (advancedEnemyPercentage - previousEnemyTypeStep) / (currentEnemyTypeStep - previousEnemyTypeStep);
        }

        int minAdvancedEnemyCount = Mathf.FloorToInt(percentageOfStrongerEnemy * selectedFormationEntities.Count);
        int maxAdvancedEnemyCount = Mathf.CeilToInt(percentageOfStrongerEnemy * selectedFormationEntities.Count);
        int advancedEnemyCount    = Random.Range(minAdvancedEnemyCount, maxAdvancedEnemyCount + 1);

        //create ship types list
        int[] shipTypes = new int[selectedFormationEntities.Count];
        for (int i = 0; i < shipTypes.Length; ++i)
        {
            if (i < advancedEnemyCount)
            {
                shipTypes[i] = advEnemyTypeIndex;
            }
            else
            {
                shipTypes[i] = advEnemyTypeIndex - 1;
            }
        }

        //shuffle the list
        for (int i = 0; i < shipTypes.Length; ++i)
        {
            int temp        = shipTypes[i];
            int randomIndex = Random.Range(i, shipTypes.Length);
            shipTypes[i]           = shipTypes[randomIndex];
            shipTypes[randomIndex] = temp;
        }

        //VII. Spawn Enemies
        SpawnEnemies(selectedFormationEntities, shipTypes, minVerticalStartCoord, maxVerticalStartCoord, enemyHorizontalDist, enemyVerticalDist, maxEnemyHorizontalDist);
    }
Exemplo n.º 27
0
        /// <summary>
        /// This method is useful in getting / reading input CSV file
        /// </summary>
        /// <param name="FilePath"></param>
        /// <returns></returns>
        public InputFields GetInputFields(string FilePath)
        {
            #region Declaration

            const string MethodName = "InsuranceRenewalReminder::UIHelper::GetInputFields::  ";
            InputFields  Response   = null;
            EventLogger  EventLog   = new EventLogger();

            #endregion

            try
            {
                //Set counter on how many files to be generated at max.
                int Counter       = 0;
                int MaxInputCount = Convert.ToInt32(WebConfigurationManager.AppSettings["MaxInputFields"]);
                if (!(MaxInputCount > 0)) //Fallback for Counter if missing or invalid in Setting
                {
                    MaxInputCount = 10;
                }

                //Read Input CSV file
                if (File.Exists(FilePath))
                {
                    Response = new InputFields();

                    using (var Reader = new StreamReader(FilePath))
                    {
                        while ((!Reader.EndOfStream) && Counter < MaxInputCount)
                        {
                            var line   = Reader.ReadLine();
                            var Values = line.Split(',');

                            //Check if First row is header row then ignore and move to next row
                            if (Counter == 0 && Values != null && Values[0] == "ID")
                            {
                                continue;
                            }

                            InputField IpField = new InputField();
                            if (Int32.TryParse(Values[0], out IpField.ID) == false)
                            {
                                //Set Response + Log warning + increament counter + Go to next row
                                Response.ReturnCode    = 1;
                                Response.ReturnMessage = (string.IsNullOrWhiteSpace(Response.ReturnMessage) ? "" : Response.ReturnMessage + "</br>") + "Invalid ID, skip input for row of ID = " + Values[0];
                                EventLog.LogWarning(MethodName + "Invalid ID, skip input for row of ID = " + Values[0] + ";" + Environment.NewLine);
                                Counter++;
                                continue;
                            }
                            IpField.Title       = Values[1];
                            IpField.FirstName   = Values[2];
                            IpField.Surname     = Values[3];
                            IpField.ProductName = Values[4];
                            if (double.TryParse(Values[5], out IpField.PayoutAmount) == false)
                            {
                                //Set Response + Log warning + increament counter + Go to next row
                                Response.ReturnCode    = 1;
                                Response.ReturnMessage = (string.IsNullOrWhiteSpace(Response.ReturnMessage) ? "" : Response.ReturnMessage + "</br>") + "Invalid PayoutAmount, skip this row of ID = " + IpField.ID;
                                EventLog.LogWarning(MethodName + "Invalid PayoutAmount, Skip this row of ID = " + IpField.ID + ";" + Environment.NewLine);
                                Counter++;
                                continue;
                            }
                            if (double.TryParse(Values[6], out IpField.AnnualPremium) == false)
                            {
                                //Set Response + Log warning + increament counter + Go to next row
                                Response.ReturnCode    = 1;
                                Response.ReturnMessage = (string.IsNullOrWhiteSpace(Response.ReturnMessage) ? "" : Response.ReturnMessage + "</br>") + "Invalid AnnualPremium, skip this row of ID = " + IpField.ID;
                                EventLog.LogWarning(MethodName + "Invalid AnnualPremium, Skip this row of ID = " + IpField.ID + ";" + Environment.NewLine);
                                Counter++;
                                continue;
                            }

                            Response.InputList.Add(IpField);
                            Counter++;
                        }
                    }
                }
                else
                {
                    //Log error Show messge File not found
                    EventLog.LogError(MethodName + "Input file not found");
                }
            }
            catch (Exception ex)
            {
                //Log error
                EventLog.LogException(MethodName, ex);
            }

            return(Response);
        }
Exemplo n.º 28
0
        /// <summary>
        /// This method is is main mathod for creating output files
        /// </summary>
        /// <param name="InputFields"></param>
        /// <returns></returns>
        public ResponseBase CreateOutputFiles(InputFields InputFields)
        {
            #region Declaration

            const string MethodName = "InsuranceRenewalReminder::UIHelper::CreateOutputFiles::  ";
            ResponseBase Response   = new ResponseBase();
            EventLogger  EventLog   = new EventLogger();

            #endregion

            try
            {
                //Add Response message from InputField reading
                if (InputFields.ReturnCode > 0)
                {
                    Response.ReturnMessage = InputFields.ReturnMessage;
                }

                bool FileCreated = false;
                //Negative use case checking
                if (InputFields == null || InputFields.InputList == null || InputFields.InputList.Count == 0)
                {
                    //Console.WriteLine("No Inputs received");
                    Response.ReturnCode    = -1;
                    Response.ReturnMessage = (string.IsNullOrWhiteSpace(Response.ReturnMessage) ? "" : Response.ReturnMessage + "</br>") + "No Inputs received";
                    return(Response);
                }
                //Get input template, As template is common for all users hence implemented Singleton pattern
                TemplateReader Template        = TemplateReader.GetInstance();
                string         TemplateContent = Template.ReadTemplateFile();

                //Create output files for each input
                foreach (InputField InputData in InputFields.InputList)
                {
                    //Create customised Output file name
                    string FileName = InputData.ID + "-" + InputData.FirstName + "_" + InputData.Surname + ".txt";

                    string OutputFilePath = WebConfigurationManager.AppSettings["OutputFilePath"];

                    //Check if Output file not present previously
                    if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(OutputFilePath + "\\" + FileName)))
                    {
                        string FinalContent = FillTemplateData(TemplateContent.ToString(), InputData);
                        //string FinalContent = FormatTemplateData(TemplateContent.ToString(), InputData); // Alternate method with compromised readability.

                        FileStream   FS = new FileStream(System.Web.HttpContext.Current.Server.MapPath(OutputFilePath + "\\" + FileName), FileMode.Create, FileAccess.Write);
                        StreamWriter SW = new StreamWriter(FS);
                        SW.Write(FinalContent.ToString());
                        SW.Close();
                        FileCreated = true;
                    }
                    else
                    {
                        //Update response and log warning
                        Response.ReturnCode    = 1;
                        Response.ReturnMessage = (string.IsNullOrWhiteSpace(Response.ReturnMessage) ? "" : Response.ReturnMessage + "</br>") + "Record for " + FileName + " already Present, No updates made.";

                        EventLog.LogWarning(MethodName + "Record for " + FileName + " already Present, No updates made.");
                    }
                }

                //return success if atleast one fine created.
                if (FileCreated)
                {
                    Response.ReturnCode = 0;
                }
            }
            catch (Exception ex)
            {
                //Log error & Return response
                EventLog.LogException(MethodName, ex);

                Response.ReturnCode    = -1;
                Response.ReturnMessage = Response.ReturnMessage + Environment.NewLine + "Error while generating output file!!!";
                return(Response);
            }

            return(Response);
        }
Exemplo n.º 29
0
 static void Main()
 {
     EventLogger.WriteLog("Log this!");
 }
Exemplo n.º 30
0
 public void killKoala()
 {
     this.health = false;
     EventLogger.addLog(kName + " died");
 }
Exemplo n.º 31
0
 public void Debug(string message)
 {
     Logger.Debug(message);
     WriteToConsole(message);
     EventLogger.WriteToEventLog(message);
 }
Exemplo n.º 32
0
 public SetSKUMetadataProcess()
 {
     objEventLogger       = new EventLogger();
     objTransactionLogger = new TransactionLogger();
     objSetSKUMetadataBL  = new SetSKUMetadataBL();
 }
Exemplo n.º 33
0
        public BootstrapsPullupResult PullUp(bool forceMachine)
        {
            BootstrapsPullupResult result = null;

            if (!this.IsLoaded)
            {
                try
                {
                    // Ensure cleanup if we got partway through this before.
                    this.Pushdown(true);

                    if (Directory.Exists(this.ApplicationPath))
                    {
                        string configPath = this.ConfigPath;

                        // Default to Web.config if not specified and a Web.config file exists.
                        if (string.IsNullOrEmpty(configPath))
                        {
                            string webConfigPath = Path.Combine(this.ApplicationPath, "Web.config");

                            if (File.Exists(webConfigPath))
                            {
                                configPath = webConfigPath;
                            }
                        }

                        // Root the config path relative to the application path.
                        if (!string.IsNullOrEmpty(configPath) && !Path.IsPathRooted(configPath))
                        {
                            configPath = Path.Combine(this.ApplicationPath, configPath);
                        }

                        if (string.IsNullOrEmpty(configPath) || File.Exists(configPath))
                        {
                            // Use the bin directory if the target is a web application.
                            string binPath = Path.Combine(this.ApplicationPath, "bin");

                            bool web = Directory.Exists(binPath)
                                && (string.IsNullOrEmpty(configPath)
                                || (!string.IsNullOrEmpty(configPath)
                                && "Web.config".Equals(Path.GetFileName(configPath), StringComparison.OrdinalIgnoreCase)));

                            AppDomainSetup setup = new AppDomainSetup();
                            setup.ApplicationBase = this.ApplicationPath;
                            setup.ShadowCopyDirectories = this.ApplicationPath;
                            setup.ShadowCopyFiles = "true";

                            if (!string.IsNullOrEmpty(configPath))
                            {
                                setup.ConfigurationFile = configPath;
                            }

                            if (web)
                            {
                                setup.PrivateBinPath = binPath;
                            }
                            else
                            {
                                binPath = this.ApplicationPath;
                            }

                            this.domain = AppDomain.CreateDomain("Blue Collar Machine", AppDomain.CurrentDomain.Evidence, setup);

                            this.logger = new EventLogger();
                            this.logger.Log += new EventHandler<EventLoggerEventArgs>(this.LoggerLog);

                            object[] constructerArgs = new object[] { this.logger, binPath, forceMachine };

            #if NET35
                        this.machineProxy = (MachineProxy)this.domain.CreateInstanceAndUnwrap(
                            typeof(MachineProxy).Assembly.FullName,
                            typeof(MachineProxy).FullName,
                            false,
                            BindingFlags.Default,
                            null,
                            constructerArgs,
                            null,
                            null,
                            AppDomain.CurrentDomain.Evidence);
            #else
                            this.machineProxy = (MachineProxy)this.domain.CreateInstanceAndUnwrap(
                                typeof(MachineProxy).Assembly.FullName,
                                typeof(MachineProxy).FullName,
                                false,
                                BindingFlags.Default,
                                null,
                                constructerArgs,
                                null,
                                null);
            #endif

                            // Create the watchers based on application type.
                            if (web)
                            {
                                this.watchers.Add(this.CreateWatcher(binPath, FileSystemWatcherMode.Directory, "*.dll"));

                                if (!string.IsNullOrEmpty(configPath))
                                {
                                    this.watchers.Add(this.CreateWatcher(Path.GetDirectoryName(configPath), FileSystemWatcherMode.IndividualFiles, Path.GetFileName(configPath)));
                                }

                                string appCodePath = Path.Combine(this.ApplicationPath, "App_Code");

                                if (Directory.Exists(appCodePath))
                                {
                                    this.watchers.Add(this.CreateWatcher(appCodePath, FileSystemWatcherMode.Directory, "*.*"));
                                }
                            }
                            else
                            {
                                this.watchers.Add(this.CreateWatcher(this.ApplicationPath, FileSystemWatcherMode.Directory, "*.dll"));
                            }

                            this.IsLoaded = true;
                        }
                        else
                        {
                            result = new BootstrapsPullupResult(BootstrapsPullupResultType.ConfigurationFileNotFound);
                        }
                    }
                    else
                    {
                        result = new BootstrapsPullupResult(BootstrapsPullupResultType.ApplicationDirectoryNotFound);
                    }
                }
                catch (Exception ex)
                {
                    this.Pushdown(true);
                    result = new BootstrapsPullupResult(BootstrapsPullupResultType.Exception, ex);
                }
            }

            return result ?? new BootstrapsPullupResult(BootstrapsPullupResultType.Success);
        }
Exemplo n.º 34
0
 /// <summary>
 /// Get a reference to an instance of SPWeb
 /// </summary>
 /// <param name="webUrl"></param>
 /// <returns></returns>
 private SPWeb GetWeb(string siteUrl)
 {
     EventLogger.WriteLine("Get Web: {0}", siteUrl);
     return(NewInstance(siteUrl).spWeb);
 }
Exemplo n.º 35
0
 public void WriteConfig(string fullFilePath)
 {
     JsonFileIO.Write(fullFilePath, this);
     EventLogger.Info($"Configuration saved to {fullFilePath}");
 }
 public void LogError(string Message, EventLogEntryType LogType)
 {
     EventLogger.LogEvent(Message, LogType);
 }
Exemplo n.º 37
0
        private void HandleSend(IAsyncResult result)
        {
            int  sent       = 0;
            bool Ready      = false;
            bool Disconnect = false;

            try
            {
                SendInfo SI;
                lock (SendLock)
                {
                    try
                    {
                        if (MainSocket == null)
                        {
                            Disconnect = true;
                        }
                        else
                        {
                            if (MainSocket.SocketType == SocketType.Stream)
                            {
                                sent = MainSocket.EndSend(result);
                            }
                            else
                            {
                                sent = MainSocket.EndSendTo(result);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        EventLogger.Log(ex);
                        Disconnect = true;
                    }
                    lock (CountLock)
                    {
                        PendingBytesSent -= sent;
                        TotalBytesSent   += sent;
                    }

                    if (SendQueue.Count > 0)
                    {
                        SI = (SendInfo)SendQueue.Dequeue();
                        try
                        {
                            if (MainSocket.SocketType == SocketType.Stream)
                            {
                                MainSocket.BeginSend(SI.buffer, SI.offset, SI.count, SocketFlags.None, SendCB, SI.Tag);
                            }
                            else
                            {
                                MainSocket.BeginSendTo(SI.buffer, SI.offset, SI.count, SocketFlags.None, SI.dest, SendCB, SI.Tag);
                            }
                        }
                        catch (Exception ex)
                        {
                            EventLogger.Log(ex);
                            EventLogger.Log(this, EventLogEntryType.Error, "Send Failure [Normal for non-pipelined connection]");
                            Disconnect = true;
                        }
                    }
                    else
                    {
                        Ready = true;
                    }
                }
                if (Disconnect)
                {
                    bool OK = false;
                    lock (this)
                    {
                        if (SentDisconnect == false)
                        {
                            OK             = true;
                            SentDisconnect = true;
                        }
                    }
                    if (OK)
                    {
                        MainSocket = null;
                    }
                    if (OK)
                    {
                        OnDisconnectEvent.Fire(this);
                    }
                }
                else
                {
                    if (Ready)
                    {
                        OnSendReadyEvent.Fire(result.AsyncState);
                    }
                }
            }
            catch (Exception ex)
            {
                EventLogger.Log(ex);
            }
        }
Exemplo n.º 38
0
        private void HandleSend(IAsyncResult result)
        {
            int  num   = 0;
            bool flag  = false;
            bool flag2 = false;

            try
            {
                lock (this.SendLock)
                {
                    try
                    {
                        if (this.MainSocket.SocketType == SocketType.Stream)
                        {
                            num = this.MainSocket.EndSend(result);
                        }
                        else
                        {
                            num = this.MainSocket.EndSendTo(result);
                        }
                    }
                    catch (Exception)
                    {
                        flag2 = true;
                    }
                    lock (this.CountLock)
                    {
                        this.PendingBytesSent -= num;
                        this.TotalBytesSent   += num;
                    }
                    if (this.SendQueue.Count > 0)
                    {
                        SendInfo info = (SendInfo)this.SendQueue.Dequeue();
                        try
                        {
                            if (this.MainSocket.SocketType == SocketType.Stream)
                            {
                                this.MainSocket.BeginSend(info.buffer, info.offset, info.count, SocketFlags.None, this.SendCB, info.Tag);
                            }
                            else
                            {
                                this.MainSocket.BeginSendTo(info.buffer, info.offset, info.count, SocketFlags.None, info.dest, this.SendCB, info.Tag);
                            }
                        }
                        catch (Exception)
                        {
                            EventLogger.Log(this, EventLogEntryType.Error, "Send Failure [Normal for non-pipelined connection]");
                            flag2 = true;
                        }
                    }
                    else
                    {
                        flag = true;
                    }
                }
                if (flag2)
                {
                    bool flag3 = false;
                    lock (this)
                    {
                        if (!this.SentDisconnect)
                        {
                            flag3 = true;
                            this.SentDisconnect = true;
                        }
                    }
                    if (flag3)
                    {
                        this.MainSocket = null;
                    }
                    if (flag3)
                    {
                        this.OnDisconnectEvent.Fire(this);
                    }
                }
                else if (flag)
                {
                    this.OnSendReadyEvent.Fire(result.AsyncState);
                }
            }
            catch (Exception exception)
            {
                EventLogger.Log(exception);
            }
        }
Exemplo n.º 39
0
        // Change the state of the logger with respect to event
        // logging
        internal void ToggleLogging(ObjectEvent oe,
                                    String name,
                                    bool start)
        {
            TraceUtil.WriteLineInfo(this, "Event " + oe + " ToggleLogging start: " + start);

            if (start)
            {
                if (IsLogging(oe._object, oe._eventInfo))
                {
                    return;
                }

                // Make a separate object for each event to keep the event
                // name
                Delegate d = GetEventLoggerDelegate(oe);
                try
                {
                    oe._eventInfo.AddEventHandler(oe._object, d);
                }
                catch (Exception ex)
                {
                    TraceUtil.WriteLineWarning(this, "Exception while enabling logging: " + name + " " + ex);

                    Console.WriteLine("Inner: " + ex.InnerException);

                    Exception showException = ex;
                    // Remove the useless wrapper exception
                    if (showException is TargetInvocationException)
                    {
                        showException = ex.InnerException;
                    }

                    String moreText = "";
                    if (showException is InvalidCastException)
                    {
                        moreText = "  If this is an Excel event, this "
                                   + "exception is likely related to "
                                   + "Microsoft problem Q316653 ("
                                   + "http://support.microsoft.com/default.aspx?"
                                   + "scid=kb;en-us;Q316653)"
                                   + ".  "
                                   + "To use events in Excel, please modify "
                                   + "the assembly " +
                                   oe._object.GetType().Assembly.GetName().Name
                                   + " (in the converted assemblies directory) "
                                   + "according to the instructions for that "
                                   + "problem.  Once you have modified the assembly "
                                   + "and restarted the Inspector, event "
                                   + "tracing will work.";
                    }

                    // Undo the GetEventLoggerDelegate
                    RemoveLoggerInstance(oe);
                    throw new Exception("Error enabling logging for " + oe
                                        + moreText,
                                        showException);
                }


                ListViewItem li = new ListViewItem(name);
                li.Tag = oe;
                _eventsBeingLogged.Items.Add(li);
                if (_eventsBeingLogged.Items.Count == 1)
                {
                    _eventsBeingLoggedTabPage.Controls.Clear();
                    _eventsBeingLoggedTabPage.Controls.Add(_eventsBeingLogged);
                }
                li.SubItems.Add(oe._eventInfo.Name);
            }
            else
            {
                if (!IsLogging(oe._object, oe._eventInfo))
                {
                    return;
                }

                for (int i = 0; i < _eventsBeingLogged.Items.Count; i++)
                {
                    ListViewItem li =
                        (ListViewItem)_eventsBeingLogged.Items[i];
                    if (li.Tag.Equals(oe))
                    {
                        _eventsBeingLogged.Items.Remove(li);
                        break;
                    }
                }

                if (_eventsBeingLogged.Items.Count == 0)
                {
                    _eventsBeingLoggedTabPage.Controls.Clear();
                    _eventsBeingLoggedTabPage.Controls.Add(_eblText);
                }

                EventLogger logger = GetLoggerInstance(oe);
                Delegate    d      = Delegate.CreateDelegate(oe._eventInfo.EventHandlerType, logger, "Logger");
                oe._eventInfo.RemoveEventHandler(oe._object, d);
                RemoveLoggerInstance(oe);
            }
        }
Exemplo n.º 40
0
    public DataTable obtener(String nombres, String email, int operacionID, int paisID)
    {
        DataTable dt = new DataTable("ListadoCorreos");
        SqlDataAdapter da = new SqlDataAdapter();
        SqlConnection cn = new SqlConnection(cd.getConnectionString());

        try
        {
            cn.Open();
            da = new SqlDataAdapter("SP_CORREO_OBTENER_POR_PAIS", cn);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;

            da.SelectCommand.Parameters.Add("@nombres", SqlDbType.VarChar, 30).Value = nombres;
            da.SelectCommand.Parameters.Add("@email", SqlDbType.VarChar, 40).Value = email;
            da.SelectCommand.Parameters.Add("@operacionID", SqlDbType.Int).Value = operacionID;
            da.SelectCommand.Parameters.Add("@paisID", SqlDbType.Int).Value = paisID;

            da.Fill(dt);

        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex); //ASP.NET 2.0.50727.0
            dt = null;
        }
        finally
        {
            cn.Close();
        }

        return dt;
    }
Exemplo n.º 41
0
        public ActionResult <List <AreaEvent> > getMcuEvents(string mcuName)
        {
            List <AreaEvent> events = EventLogger.getMcuEvents(mcuName);

            return(events);
        }
Exemplo n.º 42
0
    private void cargarCombos()
    {
        try
        {
            DataTable dtTemp = new DataTable("TemporalDataTable");
            dtTemp.Columns.Add("paisID", typeof(Int32));
            dtTemp.Columns.Add("paisNombre", typeof(String));
            DataRow drTemp = dtTemp.NewRow();
            drTemp["paisID"] = (Int32)0;
            drTemp["paisNombre"] = "Seleccione un país";
            dtTemp.Rows.Add(drTemp);

            DataTable dtPais = new DataTable();
            dtPais = pais.obtenerNombres();

            if (dtPais != null)
            {
                dtTemp.Merge(dtPais);
            }

            ddlNombre.DataSource = dtTemp;
            ddlNombre.DataValueField = "paisID";
            ddlNombre.DataTextField = "paisNombre";
            ddlNombre.DataBind();
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0 [mantenimientoPais - método: cargarCombos]", ex);
            divPolitica.InnerHtml = "<div id=\"error\">Ha ocurrido un error al cargar la lista de paises.</div>";
        }
    }
Exemplo n.º 43
0
 public static void LogEvent(SysEventType eventType, string eventName, string customMessage,
                             Exception exception)
 {
     EventLogger.LogEvent(eventType.ToString(), eventName, customMessage, exception);
 }
Exemplo n.º 44
0
		internal void AddLoggerInstance(ObjectEvent oe, EventLogger logger)								
		{
			lock (this)
			{
				_loggerInstanceHash.Add(oe, logger);
				ObjectEventCountHolder h = (ObjectEventCountHolder)_loggerObjectHash[oe._object];
				if (h == null)
				{
					h = new ObjectEventCountHolder();
					_loggerObjectHash.Add(oe._object, h);
				}
				h._count++;
			}
		}
Exemplo n.º 45
0
        /// <summary>
        /// Exit a parse tree produced by <see cref="BBSCodeParser.bbsCodeElement"/>.
        /// </summary>
        /// <param name="context">The parse tree.</param>
        public override void ExitBbsCodeElement([NotNull] BBSCodeParser.BbsCodeElementContext context)
        {
            string tagName = context.children[1].GetText().Trim().ToUpper();
            Tags   tag;

            if (TagsTable.TryGetValue(tagName, out tag))
            {
                Attributes attr = AttributesTable.GetAttributes(tag);
                string     value;
                string     value1;
                switch (tag)
                {
                case Tags.CLS:
                    if (attr.TryGetValue("FORECOLOR", out value))
                    {
                        ANSI.pushForeColor(value);
                    }
                    if (attr.TryGetValue("BACKCOLOR", out value))
                    {
                        ANSI.pushBackColor(value);
                    }
                    Parsed.TextConcat(ANSI.ClearScreen());
                    Parsed.TextPop(true);
                    break;

                case Tags.BLINK:
                    ANSI.ResetMode(ANSICodes.Modes.Blink);
                    Parsed.TextConcat(ANSI.WriteMode());
                    Parsed.TextPop(true);
                    break;

                case Tags.REVERSE:
                    ANSI.ResetMode(ANSICodes.Modes.Reverse);
                    Parsed.TextConcat(ANSI.WriteMode());
                    Parsed.TextPop(true);
                    break;

                case Tags.BOLD:
                    ANSI.ResetMode(ANSICodes.Modes.Bold);
                    Parsed.TextConcat(ANSI.WriteMode());
                    Parsed.TextPop(true);
                    break;

                case Tags.UNDERLINE:
                    ANSI.ResetMode(ANSICodes.Modes.Underline);
                    Parsed.TextConcat(ANSI.WriteMode());
                    Parsed.TextPop(true);
                    break;

                case Tags.COLOR:
                    ANSI.popForeColor();
                    Parsed.TextConcat(ANSI.WriteMode());
                    Parsed.TextPop(true);
                    break;

                case Tags.BACKCOLOR:
                    ANSI.popBackColor();
                    Parsed.TextConcat(ANSI.WriteMode());
                    Parsed.TextPop(true);
                    break;

                case Tags.P:
                    Parsed.TextAssign(string.Join('\n',
                                                  TextHelper.WordWrap(Parsed.Parsed,
                                                                      Client.screenWidth).ToArray()));
                    Parsed.TextPop(true);
                    break;

                case Tags.MOVE:
                    if (!attr.TryGetValue("ROW", out value))
                    {
                        value = "0";
                    }
                    if (!attr.TryGetValue("COL", out value1))
                    {
                        value1 = "0";
                    }
                    Parsed.TextConcat(ANSI.Move(value1, value));
                    Parsed.TextPop(true);
                    break;

                case Tags.FIGGLE:
                    if (!attr.TryGetValue("FONT", out value))
                    {
                        value = "standard";
                    }
                    try
                    {
                        Parsed.TextAssign(Figgle.FiggleFonts.Lookup(value.ToLower()).Render(Parsed.Parsed));
                    }
                    catch (Exception)
                    { }
                    Parsed.TextPop(true);
                    break;

                case Tags.ACTION:
                    action = new BBSCodeResult.Action(attr);
                    if (!string.IsNullOrWhiteSpace(action.requires))
                    {
                        if (string.IsNullOrWhiteSpace(Client.username))
                        {
                            Parsed.TextPop(true);
                            return;
                        }
                        using (bbsContext bbs = new bbsContext())
                        {
                            User user    = bbs.GetUserByUsername(Client.username);
                            bool allowed = user.HasRights(action.requires);
                            Parsed.TextPop(allowed);
                            if (!allowed)
                            {
                                return;
                            }
                        }
                    }
                    else
                    {
                        Parsed.TextPop(true);
                    }
                    if (!Parsed.Actions.TryAdd(action.key, action))
                    {
                        EventLogger.Write(string.Format("Error adding action '{0}' in '{1}'", action.key, FileName), 0);
                    }
                    break;

                case Tags.BEEP:
                    Parsed.TextConcat((char)7);
                    Parsed.TextPop(true);
                    break;

                case Tags.HR:
                    Parsed.TextConcat(TextHelper.HR('-', Client.screenWidth));
                    Parsed.TextPop(true);
                    break;

                case Tags.HEADER:
                    if (attr.TryGetValue("BACKCOLOR", out value))
                    {
                        Parsed.HeaderBackground = ANSI.GetColorByName(value, true);
                    }
                    Parsed.Header = Parsed.Parsed;
                    Parsed.TextClear();
                    break;

                case Tags.FOOTER:
                    if (attr.TryGetValue("BACKCOLOR", out value))
                    {
                        Parsed.FooterBackground = ANSI.GetColorByName(value, true);
                    }
                    Parsed.Footer = Parsed.Parsed;
                    Parsed.TextClear();
                    break;

                case Tags.BODY:
                    if (attr.TryGetValue("ALTERNATECOLOR", out value))
                    {
                        Parsed.BodyAlternateBackground = ANSI.GetColorByName(value, true);
                    }
                    if (attr.TryGetValue("FOCUSEDCOLOR", out value))
                    {
                        Parsed.BodyFocusedBackground = ANSI.GetColorByName(value, true);
                    }
                    Parsed.Body = Parsed.Parsed;
                    Parsed.TextClear();
                    break;

                case Tags.HIDDEN:
                    Parsed.TextClear();
                    break;

                case Tags.H1:
                    Parsed.TextAssign(string.Join('\n',
                                                  ANSI.Header(Parsed.Parsed, 1,
                                                              Client.screenWidth).ToArray()));
                    Parsed.TextPop(true);
                    break;

                case Tags.H2:
                    Parsed.TextAssign(string.Join('\n',
                                                  ANSI.Header(Parsed.Parsed, 2,
                                                              Client.screenWidth).ToArray()));
                    Parsed.TextPop(true);
                    break;

                case Tags.H3:
                    Parsed.TextAssign(string.Join('\n',
                                                  ANSI.Header(Parsed.Parsed, 3,
                                                              Client.screenWidth).ToArray()));
                    Parsed.TextPop(true);
                    break;

                case Tags.H4:
                    Parsed.TextAssign(string.Join('\n',
                                                  ANSI.Header(Parsed.Parsed, 1,
                                                              Client.screenWidth).ToArray()));
                    Parsed.TextPop(true);
                    break;

                default:
                    break;
                }
            }
        }
Exemplo n.º 46
0
    public DataTable obtener(String nomenclatura, String nombre, String mayoriaEdad)
    {
        DataTable dt = new DataTable("ListadoPaises");
        SqlDataAdapter da = new SqlDataAdapter();
        SqlConnection cn = new SqlConnection(cd.getConnectionString());

        try
        {
            cn.Open();
            da = new SqlDataAdapter("SP_PAIS_OBTENER", cn);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;

            da.SelectCommand.Parameters.Add("@nomenclatura", SqlDbType.VarChar, 2).Value = nomenclatura;
            da.SelectCommand.Parameters.Add("@nombre", SqlDbType.VarChar, 200).Value = nombre;
            if (mayoriaEdad.Length > 0)
                da.SelectCommand.Parameters.Add("@mayoriaEdad", SqlDbType.Int).Value = Convert.ToInt32(mayoriaEdad);
            else
                da.SelectCommand.Parameters.Add("@mayoriaEdad", SqlDbType.Int).Value = DBNull.Value;

            da.Fill(dt);
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex); //ASP.NET 2.0.50727.0
            dt = null;
        }
        finally
        {
            cn.Close();
        }

        return dt;
    }
        /// <summary>
        /// Works like the CopyStream method but does a log rotation.
        /// </summary>
        private void CopyStreamWithRotation(Stream data, string ext)
        {
            byte[]     buf = new byte[1024];
            FileStream w   = new FileStream(BaseLogFileName + ext, FileMode.Append);
            long       sz  = new FileInfo(BaseLogFileName + ext).Length;

            while (true)
            {
                int len = data.Read(buf, 0, buf.Length);
                if (len == 0)
                {
                    break;              // EOF
                }
                if (sz + len < SizeTheshold)
                {// typical case. write the whole thing into the current file
                    w.Write(buf, 0, len);
                    sz += len;
                }
                else
                {
                    // rotate at the line boundary
                    int s = 0;
                    for (int i = 0; i < len; i++)
                    {
                        if (buf[i] != 0x0A)
                        {
                            continue;
                        }
                        if (sz + i < SizeTheshold)
                        {
                            continue;
                        }

                        // at the line boundary and exceeded the rotation unit.
                        // time to rotate.
                        w.Write(buf, s, i + 1);
                        w.Close();
                        s = i + 1;

                        try
                        {
                            for (int j = FilesToKeep; j >= 1; j--)
                            {
                                string dst = BaseLogFileName + "." + (j - 1) + ext;
                                string src = BaseLogFileName + "." + (j - 2) + ext;
                                if (File.Exists(dst))
                                {
                                    File.Delete(dst);
                                }
                                if (File.Exists(src))
                                {
                                    File.Move(src, dst);
                                }
                            }
                            File.Move(BaseLogFileName + ext, BaseLogFileName + ".0" + ext);
                        }
                        catch (IOException e)
                        {
                            EventLogger.LogEvent("Failed to rotate log: " + e.Message);
                        }

                        // even if the log rotation fails, create a new one, or else
                        // we'll infinitely try to rotate.
                        w  = new FileStream(BaseLogFileName + ext, FileMode.Create);
                        sz = new FileInfo(BaseLogFileName + ext).Length;
                    }
                }

                w.Flush();
            }
            data.Close();
            w.Close();
        }
Exemplo n.º 48
0
        public void ReadPrescriberRecords()
        {
            try
            {
                _prescriber.Clear();

                var tmpPhone = string.Empty;
                var tmpZip   = string.Empty;
                var tmpDea   = string.Empty;

                int counter = 0;

                /*
                 *  The field names in the database are generally not going to match the field names MOT uses, so we implment a pairwise
                 *  list to do the conversion on the fly. This will work for all items except where the contents of the field are incomplete,
                 *  require transformation, or are otherwise incorrect, we generate and exception list and handle them one at a time.
                 */
                TranslationTable.Add("Prescriber_ID", "RxSys_DocID");
                TranslationTable.Add("Last_Name", "LastName");
                TranslationTable.Add("First_Name", "FirstName");
                TranslationTable.Add("Middle_Initial", "MiddleInitial");
                TranslationTable.Add("Address_Line_1", "Address1");
                TranslationTable.Add("Address_Line_2", "Address2");
                TranslationTable.Add("City", "City");
                TranslationTable.Add("State_Code", "State");
                TranslationTable.Add("Zip_Code", "Zip");           // Stored as Integer
                TranslationTable.Add("Zip_Plus_4", "Zip");         // Stored as Integer
                TranslationTable.Add("Area_Code", "AreaCode");     // Stored as Integer
                TranslationTable.Add("Telephone_Number", "Phone"); // Stored as Integer
                TranslationTable.Add("DEA_Number", "DEA_ID");
                //TranslationTable.Add("DEA_Suffix", "DEA_SUFIX");
                TranslationTable.Add("Prescriber_Type ", "Specialty");
                TranslationTable.Add("Active_Flag", "Comments");      // 'Y' || 'N'

                Lookup.Add("DDS", "Dentist");
                Lookup.Add("DO", "Osteopath");
                Lookup.Add("DPM", "Podiatrist");
                Lookup.Add("DVM", "Veterinarian");
                Lookup.Add("IN", "Intern");
                Lookup.Add("MD", "Medical Doctor");
                Lookup.Add("NP", "Nurse Practitioner");
                Lookup.Add("OPT", "Optometrist");
                Lookup.Add("PA", "Physician Assistant");
                Lookup.Add("RN", "Registered Nurse");
                Lookup.Add("RPH", "Registered Pharmacist");

                /*
                 *  Query the database and collect a set of records where a valid set is {1..n} items.  This is not a traditional
                 *  record set as returned by access or SQL server, but a generic collection of IDataRecords and is usable accross
                 *  all database types.  If the set of records is {0} an exception will be thrown
                 */

                var tag = string.Empty;
                var val = string.Empty;
                var tmp = string.Empty;

                DataSet recordSet = Db.ExecuteQuery($"SELECT * FROM dbo.vPrescriber WHERE MSSQLTS > {LastTouch};");

                if (ValidTable(recordSet))
                {
                    foreach (DataRow record in recordSet.Tables[0].Rows)
                    {
                        LastTouch = ByteArrayToHexString((System.Byte[])record["MSSQLTS"]);

                        foreach (DataColumn column in record.Table.Columns)
                        {
                            if (TranslationTable.TryGetValue(column.ColumnName, out tmp))
                            {
                                tag = tmp;
                                val = record[column.ColumnName].ToString();

                                switch (column.ColumnName)
                                {
                                // Merge Zip Code, it's an int in the DB, so prepend a 0 to make it real
                                case "Zip_Code":
                                    tmpZip = "0" + val;
                                    continue;

                                case "Zip_Plus_4":
                                    tmpZip += val;
                                    val     = tmpZip;
                                    break;

                                // Merge Phone Number
                                case "Area_Code":
                                    tmpPhone = val;
                                    continue;

                                case "Telephone_Number":
                                    tmpPhone += val;
                                    val       = tmpPhone;
                                    break;

                                default:
                                    break;
                                }

                                _prescriber.SetField(tag, val, true);
                            }
                        }

                        try
                        {
                            // Write the record to the gateway
                            Mutex.WaitOne();

                            using (var gw = new TcpClient(GatewayIp, GatewayPort))
                            {
                                using (var stream = gw.GetStream())
                                {
                                    _prescriber.Write(stream);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            EventLogger.Error($"Error processing prescriptin record: {ex.Message}");
                            throw;
                        }
                        finally
                        {
                            Mutex.ReleaseMutex();
                        }

                        _prescriber.Clear();
                    }
                }

                return;
            }
            catch (RowNotInTableException)
            {
                return;  // No records
            }

            catch (Exception ex)
            {
                throw;
            }
        }
Exemplo n.º 49
0
    private void cargarCombos()
    {
        try
        {
            DataTable dtTemp = new DataTable("TemporalDataTable");
            dtTemp.Columns.Add("tablaID", typeof(Int32));
            dtTemp.Columns.Add("perfilDescripcion", typeof(String));
            DataRow drTemp = dtTemp.NewRow();
            drTemp["tablaID"] = (Int32)0;
            drTemp["perfilDescripcion"] = "Todos";
            dtTemp.Rows.Add(drTemp);

            dtTemp.Merge(tabla.obtenerPerfiles());

            ddlPerfil.DataSource = dtTemp;
            ddlPerfil.DataValueField = "tablaID";
            ddlPerfil.DataTextField = "perfilDescripcion";
            ddlPerfil.DataBind();

            dtTemp = new DataTable("TemporalDataTableB");
            dtTemp.Columns.Add("codigo", typeof(String));
            dtTemp.Columns.Add("descripcion", typeof(String));

            drTemp = dtTemp.NewRow();
            drTemp["codigo"] = 0;
            drTemp["descripcion"] = "Todos";
            dtTemp.Rows.Add(drTemp);

            drTemp = dtTemp.NewRow();
            drTemp["codigo"] = true;
            drTemp["descripcion"] = "Activo";
            dtTemp.Rows.Add(drTemp);

            drTemp = dtTemp.NewRow();
            drTemp["codigo"] = false;
            drTemp["descripcion"] = "Inactivo";
            dtTemp.Rows.Add(drTemp);

            ddlEstado.DataSource = dtTemp;
            ddlEstado.DataValueField = "codigo";
            ddlEstado.DataTextField = "descripcion";
            ddlEstado.DataBind();
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex); //ASP.NET 2.0.50727.0
        }
    }
        private void CopyStreamWithRotation(Stream data, string ext)
        {
            // lock required as the timer thread and the thread that will write to the stream could try and access the file stream at the same time
            var fileLock = new object();

            var buf = new byte[1024];

            var baseDirectory = Path.GetDirectoryName(BaseLogFileName);
            var baseFileName  = Path.GetFileName(BaseLogFileName);
            var logFile       = string.Format("{0}{1}", BaseLogFileName, ext);

            var w  = new FileStream(logFile, FileMode.Append);
            var sz = new FileInfo(logFile).Length;

            // We auto roll at time is configured then we need to create a timer and wait until time is elasped and roll the file over
            if (AutoRollAtTime != null)
            {
                var tickTime = SetupRollTimer();
                var timer    = new System.Timers.Timer(tickTime);
                timer.Elapsed += (s, e) =>
                {
                    try
                    {
                        timer.Stop();
                        lock (fileLock)
                        {
                            w.Close();

                            var nextFileNumber = GetNextFileNumber(ext, baseDirectory, baseFileName);
                            var nextFileName   = Path.Combine(baseDirectory, string.Format("{0}.{1}.#{2:D4}{3}", baseFileName, DateTime.UtcNow.ToString(FilePattern), nextFileNumber, ext));
                            File.Move(logFile, nextFileName);

                            w  = new FileStream(logFile, FileMode.Create);
                            sz = new FileInfo(logFile).Length;
                        }
                    }
                    catch (Exception et)
                    {
                        EventLogger.LogEvent(string.Format("Failed to to trigger auto roll at time event due to: {0}", et.Message));
                    }
                    finally
                    {
                        // Recalculate the next interval
                        timer.Interval = SetupRollTimer();
                        timer.Start();
                    }
                };
                timer.Start();
            }
            while (true)
            {
                var len = data.Read(buf, 0, buf.Length);
                if (len == 0)
                {
                    break;              // EOF
                }
                lock (fileLock)
                {
                    if (sz + len < SizeTheshold)
                    {
                        // typical case. write the whole thing into the current file
                        w.Write(buf, 0, len);
                        sz += len;
                    }
                    else
                    {
                        try
                        {
                            // rotate at the line boundary
                            int s = 0;
                            for (int i = 0; i < len; i++)
                            {
                                if (buf[i] != 0x0A)
                                {
                                    continue;
                                }
                                if (sz + i < SizeTheshold)
                                {
                                    continue;
                                }

                                // at the line boundary and exceeded the rotation unit.
                                // time to rotate.
                                w.Write(buf, s, i + 1);
                                w.Close();
                                s = i + 1;

                                // rotate file
                                var nextFileNumber = GetNextFileNumber(ext, baseDirectory, baseFileName);
                                var nextFileName   =
                                    Path.Combine(baseDirectory,
                                                 string.Format("{0}.{1}.#{2:D4}{3}", baseFileName, DateTime.UtcNow.ToString(FilePattern), nextFileNumber, ext));
                                File.Move(logFile, nextFileName);

                                // even if the log rotation fails, create a new one, or else
                                // we'll infinitely try to rotate.
                                w  = new FileStream(logFile, FileMode.Create);
                                sz = new FileInfo(logFile).Length;
                            }
                        }
                        catch (Exception e)
                        {
                            EventLogger.LogEvent(string.Format("Failed to roll size time log: {0}", e.Message));
                        }
                    }
                    w.Flush();
                }
            }
            data.Close();
            w.Close();
        }
Exemplo n.º 51
0
    public String actualizar(int paisID, String nomenclatura, int medad, bool seguimientoBB, bool reingresoBB, bool adicionalSC, bool gpsBB, bool verificadoIncorp, bool estado, DataTable dtDivPolitica, int caducidad)
    {
        String resultado = "success";

        SqlDataAdapter da = new SqlDataAdapter();
        SqlCommand cmd = new SqlCommand();
        SqlConnection cn = new SqlConnection(cd.getConnectionString());

        try
        {
            cn.Open();
            cmd = new SqlCommand("SP_PAIS_ACTUALIZAR", cn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Transaction = cn.BeginTransaction();

            cmd.Parameters.Add("@paisID", SqlDbType.Int).Value = paisID;
            cmd.Parameters.Add("@nomenclatura", SqlDbType.Char, 2).Value = nomenclatura;
            cmd.Parameters.Add("@medad", SqlDbType.Int).Value = medad;
            cmd.Parameters.Add("@seguimientoBB", SqlDbType.Bit).Value = seguimientoBB;
            cmd.Parameters.Add("@reingresoBB", SqlDbType.Bit).Value = reingresoBB;
            cmd.Parameters.Add("@adicionalSC", SqlDbType.Bit).Value = adicionalSC;
            cmd.Parameters.Add("@gpsBB", SqlDbType.Bit).Value = gpsBB;
            cmd.Parameters.Add("@verificadoIncorp", SqlDbType.Bit).Value = verificadoIncorp;
            cmd.Parameters.Add("@estado", SqlDbType.Bit).Value = estado;
            cmd.Parameters.Add("@caducidad", SqlDbType.Int).Value = caducidad;

            cmd.ExecuteNonQuery();

            if (dtDivPolitica != null)
            {
                DivisionPolitica dp = new DivisionPolitica();

                for (int i = 0; i < dtDivPolitica.Rows.Count; i++)
                {
                    int divisionID = Convert.ToInt32(dtDivPolitica.Rows[i]["divisionID"]);
                    bool estadoDP = Convert.ToBoolean(dtDivPolitica.Rows[i]["estado"]);
                    resultado = dp.actualizar(divisionID, estadoDP, cmd);

                    if (!resultado.Equals("success"))
                    {
                        cmd.Transaction.Rollback();
                        cn.Close();
                        return resultado;
                    }
                }
            }

            cmd.Transaction.Commit();
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex); //ASP.NET 2.0.50727.0
            resultado = ex.Message;
            cmd.Transaction.Rollback();
        }
        finally
        {
            cn.Close();
        }

        return resultado;
    }
Exemplo n.º 52
0
 public void EndLog()
 {
     print("5 TicketMachine sollicitationToLog : " + sollicitationToLog);
     File.AppendAllText(EventLogger.getPathEventLogger(), sollicitationToLog, Encoding.UTF8);
 }
Exemplo n.º 53
0
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="serverPKID"></param>
        /// <param name="address"></param>
        /// <param name="updateRate"></param>
        /// <param name="deviceTagParams"></param>
        /// <param name="callback"></param>
        private void Initial(Int64 serverPKID, string address, int updateRate,
                             List <DeviceTagParam> deviceTagParams, DataChangeEventHandler callback)
        {
            pkid = serverPKID;

            #region 初始化参数

            string ip         = (address == "") ? CBaseData.LocalIP : address;
            string serverName = address;

            string[] addes = address.Split('|', ';');  //分号隔开,前面是IP地址,后面是OPCServer名称
            if (addes.Length > 1)
            {
                ip = addes[0];
                if ((ip.ToLower() == "local") || (ip.ToLower() == "localhost") || (ip.ToLower() == "."))
                {
                    ip = CBaseData.LocalIP; //本机IP
                }
                serverName = addes[1];
            }
            else  //默认为本机
            {
                ip = CBaseData.LocalIP;
            }

            IPAddress remote;
            IPAddress.TryParse(ip, out remote);

            ServerIP      = remote;
            OPCServerName = serverName;
            Callback      = callback; //设置回调函数

            #endregion

            DeviceTags = deviceTagParams;  //标签

            #region 自定义协议

            CustomProtocol   = (addes.Length >= 3) ? addes[2] : ""; //自定义协议
            ProtocolVariable = (addes.Length >= 4) ? addes[3] : ""; //自定义协议

            #endregion

            #region OPC 设定

            string error = String.Empty;

            _opcServer = OpcServers.FirstOrDefault(c => c.PKID == serverPKID);

            if ((_opcServer == null) || (!_opcServer.IsConnected))
            {
                _opcServer = OPCConnector.ConnectOPCServer(serverPKID, ip, serverName, ref error);
            }
            else
            {
                EventLogger.Log($"【{serverPKID}】OPC服务器已连接");
            }

            if (_opcServer != null && _opcServer.IsConnected)
            {
                List <Guid>   subHandels = new List <Guid>();                                           //Handel
                List <string> subItemIds = new List <string>();                                         //标签地址

                List <Guid>   normalHandels = new List <Guid>();                                        //Handel
                List <string> normalItemIds = new List <string>();                                      //标签地址

                if (subHandels.Count > 0)                                                               //添加订阅
                {
                    OpcGroup subGroup = _opcServer.AddGroup("GP" + serverPKID + "S", updateRate, true); //订阅的Group

                    subGroup.AddItems(subItemIds.ToArray(), subHandels.ToArray());

                    subGroup.DataChanged -= OPCDataChanged;
                    subGroup.DataChanged += OPCDataChanged;
                }

                if (normalHandels.Count > 0)                                                                //添加正常
                {
                    OpcGroup normalGroup = _opcServer.AddGroup("GP" + serverPKID + "N", updateRate, false); //正常的Group

                    normalGroup.AddItems(normalItemIds.ToArray(), normalHandels.ToArray());
                }

                EventLogger.Log($"【{serverPKID}】OPC服务器连接成功。");
            }
            else
            {
                error = $"【{serverPKID}】OPC服务器连接失败,具体为:" + error;
                EventLogger.Log(error);
            }

            OpcServers.Add(_opcServer);  //将OPCServer添加到系统中

            #endregion
        }
Exemplo n.º 54
0
        /// <summary>
        /// Start AsyncReads
        /// </summary>
        /// <returns>Successfully started</returns>
        public void Begin()
        {
            bool       Disconnect = false;
            IPEndPoint src, from;

            if (MainSocket.SocketType == SocketType.Stream)
            {
                from = (IPEndPoint)MainSocket.RemoteEndPoint;
            }
            else
            {
                from = (IPEndPoint)rEP;
            }

            try
            {
                src = (IPEndPoint)MainSocket.LocalEndPoint;
            }
            catch (Exception ex)
            {
                EventLogger.Log(ex);
                src = new IPEndPoint(IPAddress.Any, 0);
            }

            while ((BufferBeginPointer != 0) &&
                   (BufferBeginPointer != BufferEndPointer))
            {
                Array.Copy(MainBuffer, BufferBeginPointer, MainBuffer, 0, BufferEndPointer - BufferBeginPointer);
                BufferEndPointer   = BufferEndPointer - BufferBeginPointer;
                BufferBeginPointer = 0;
                BufferSize         = BufferEndPointer;
                try
                {
                    OnReceiveEvent.Fire(this, MainBuffer, BufferBeginPointer, BufferSize, 0, src, from);
                }
                catch (StopReadException ex)
                {
                    EventLogger.Log(ex);
                    return;
                }
                if (StopThread != null)
                {
                    if (Thread.CurrentThread.GetHashCode() == StopThread.GetHashCode())
                    {
                        StopThread = null;
                        return;
                    }
                }
            }

            try
            {
                if (MainSocket.SocketType == SocketType.Stream)
                {
                    MainSocket.BeginReceive(MainBuffer, BufferEndPointer, BufferReadLength, SocketFlags.None, ReceiveCB, null);
                }
                else
                {
                    MainSocket.BeginReceiveFrom(MainBuffer, BufferEndPointer, BufferReadLength, SocketFlags.None, ref rEP, ReceiveCB, null);
                }
            }
            catch (Exception ex)
            {
                EventLogger.Log(ex);
                Disconnect = true;
            }

            if (Disconnect)
            {
                bool OK = false;
                lock (this)
                {
                    if (SentDisconnect == false)
                    {
                        OK             = true;
                        SentDisconnect = true;
                    }
                }
                if (OK)
                {
                    MainSocket = null;
                }
                if (OK)
                {
                    OnDisconnectEvent.Fire(this);
                }
            }
        }
        public static void UpdateSettingsMachineNameAndSerial(DatabaseAccessProvider <IPlatformDatabaseServices> dbAccess, Func <string> serialNumberGetter,
                                                              bool skipConnectionStringCheck)
        {
            // This code is used to solve the dangling machine name problem in amazon.
            // We'll start using the serial number to identify a machine instead of its name
            // for the node-specific settings.

            if (skipConnectionStringCheck)
            {
                string currentName = Settings.MachineName;
                if (currentSerial == null)
                {
                    currentSerial = serialNumberGetter();
                }

                using (RegistryKey subKey = SettingsRegistryKey) {
                    object previousNameValue   = subKey.GetValue(machineNameSetting);
                    string previousName        = previousNameValue == null ? null : previousNameValue.ToString();
                    object previousSerialValue = subKey.GetValue(serialSetting);
                    string previousSerial      = previousSerialValue == null ? null : previousSerialValue.ToString();

                    // the first time this code is run the ossys_parameter.host and ossys_server.name columns
                    // contain server names. Update them to the serial number.
                    // This is the 1st time if previousSerial is not set
                    if (previousSerial.IsEmpty())
                    {
                        FixRegistrySettingsPermissions();

                        currentSerial = serialNumberGetter();

                        using (var trans = dbAccess.GetCommitableTransaction()) {
                            UpgradeMachineNameToSerialNumber(trans, currentName, currentSerial);
                            trans.Commit();
                            EventLogger.WriteInfo("Setting Machine Serial to '" + currentSerial + "'.");
                        }
                    }

                    // serial changed - this happens for new instances created from  a server image.
                    // Update the serial number to the new one
                    if (!previousSerial.IsEmpty() && previousSerial != currentSerial)
                    {
                        using (var trans = dbAccess.GetCommitableTransaction()) {
                            UpdateSerialNumber(trans, previousSerial, currentSerial);
                            trans.Commit();
                            EventLogger.WriteInfo("Machine Serial changed from '" + previousSerial + "' to '" + currentSerial + "'.");
                        }
                    }

                    // name changed - this happens with amazon instances whenever they're stopped/started.
                    // Update the machine name to the new one
                    if (!previousName.IsEmpty() && previousName != currentName)
                    {
                        using (var trans = dbAccess.GetCommitableTransaction()) {
                            UpdateMachineName(trans, currentSerial, currentName);
                            trans.Commit();
                            EventLogger.WriteInfo("Machine Name changed from '" + previousName + "' to '" + currentName + "'.");
                        }
                    }

                    // update data in the registry
                    if (currentName == null)
                    {
                        throw new InvalidOperationException("currentName or currentSerial is null");
                    }

                    subKey.SetValue(machineNameSetting, currentName);

                    if (currentSerial == null)
                    {
                        throw new InvalidOperationException("currentSerial is null");
                    }

                    subKey.SetValue(serialSetting, currentSerial);
                }
            }
        }
Exemplo n.º 56
0
    private bool LoginCorrecto(string usuario, string clave, string pais)
    {
        SqlConnection cn = new SqlConnection(cd.getConnectionString());
        SqlDataAdapter da = new SqlDataAdapter();

        try
        {
            cn.Open();
            da = new SqlDataAdapter("usp_bel_usuario_autenticar", cn);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;

            da.SelectCommand.Parameters.Add("@nombreusuario", SqlDbType.VarChar, 15).Value = usuario;
            da.SelectCommand.Parameters.Add("@clave", SqlDbType.VarChar, 15).Value = clave;
            da.SelectCommand.Parameters.Add("@paisID", SqlDbType.Int).Value = int.Parse(pais);

            /*
            da.SelectCommand.Parameters.Add("@nombreusuario", SqlDbType.VarChar, 15).Value = "natsume" ;
            da.SelectCommand.Parameters.Add("@clave", SqlDbType.VarChar, 15).Value = "nat";
            da.SelectCommand.Parameters.Add("@paisID", SqlDbType.Int).Value = int.Parse("8");
            */
            //
            DataTable dt = new DataTable();
            da.Fill(dt);

            if (dt.Rows.Count == 1)
            {
                // Si encontró exactamente UN resultado
                int usuarioID = (Int32)dt.Rows[0]["usuarioID"];
                int paisID = (Int32)dt.Rows[0]["paisID"];
                String paisNombre = (String)dt.Rows[0]["paisNombre"];
                String paisRutaImagen = (String)dt.Rows[0]["paisRutaImagen"];
                String paisTipoDocumento = Convert.ToString(dt.Rows[0]["paisTipoDocumento"]);
                int perfilID = (Int32)dt.Rows[0]["perfilID"];
                String perfilDescripcion = (String)dt.Rows[0]["perfilDescripcion"];
                String usuarioNombre = (String)dt.Rows[0]["usuarioNombre"];
                bool estado = (bool)dt.Rows[0]["estado"];
                String usuarioNombres = (String)dt.Rows[0]["usuarioNombres"];

                // Se escriben los parámetros en sesión
                Session["usuarioNombre"] = usuarioNombres; // set user_names instead of username(login name)
                Session["paisNombre"] = paisNombre;
                Session["rolNombre"] = perfilDescripcion;
                Session["paisID"] = paisID;
                Session["paisRutaImagen"] = paisRutaImagen;
                Session["paisTipoDocumento"] = paisTipoDocumento;

                FormsAuthenticationTicket ticket;
                String cookie;
                HttpCookie httpCookie;
                ticket = new FormsAuthenticationTicket(1, usuarioNombres, DateTime.Now, DateTime.Now.AddMinutes(30), false, perfilDescripcion);
                cookie = FormsAuthentication.Encrypt(ticket);
                httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookie);
                Page.Response.Cookies.Add(httpCookie);
                return true;
            }

            return false;
        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex); //ASP.NET 2.0.50727.0
            return false;
        }
        finally
        {
            cn.Close();
        }
    }
Exemplo n.º 57
0
        public void ReadDrugRecords()
        {
            try
            {
                _drug.Clear();

                var itemType  = string.Empty;
                var itemColor = string.Empty;
                var itemShape = string.Empty;

                TranslationTable.Add("ITEM_ID", "RxSys_DrugID");
                TranslationTable.Add("ITEM_NAME", "DrugName");
                TranslationTable.Add("Manufacturer_Abbreviation", "ShortName");
                TranslationTable.Add("STRENGTH", "Strength");
                TranslationTable.Add("UNIT_OF_MEASURE", "Unit");
                TranslationTable.Add("NARCOTIC_CODE", "DrugSchedule");
                TranslationTable.Add("NDC_CODE", "NDCNum");
                TranslationTable.Add("COLOR_CODE", "VisualDescription");
                TranslationTable.Add("ITEM_TYPE", "VisualDescription");
                TranslationTable.Add("SHAPE_CODE", "VisualDescription");
                TranslationTable.Add("PACKAGE_CODE", "ProdCode");
                TranslationTable.Add("ROUTE_OF_ADMINISTRATION", "Route");
                TranslationTable.Add("FORM_TYPE", "DoseForm");


                var recordSet = Db.ExecuteQuery($"select * FROM dbo.vItem WHERE MSSQLTS > {LastTouch};");

                if (ValidTable(recordSet))
                {
                    foreach (DataRow record in recordSet.Tables[0].Rows)
                    {
                        LastTouch = ByteArrayToHexString((System.Byte[])record["MSSQLTS"]);

                        // Print the DataType of each column in the table.
                        foreach (DataColumn column in record.Table.Columns)
                        {
                            if (TranslationTable.TryGetValue(column.ColumnName, out var tmp))
                            {
                                var tag = tmp;
                                var val = record[column.ColumnName].ToString();

                                switch (column.ColumnName)
                                {
                                case "ITEM_TYPE":
                                    itemType = val;
                                    continue;

                                case "COLOR_CODE":
                                    itemColor = val;
                                    continue;

                                case "SHAPE_CODE":
                                    itemShape = val;
                                    continue;

                                default:
                                    break;
                                }

                                _drug.SetField(tag, val, true);
                            }
                        }

                        _drug.VisualDescription = string.Format("{0}/{1}/{2}", itemShape, itemColor, itemType);

                        try
                        {
                            Mutex.WaitOne();

                            using (var gw = new TcpClient(GatewayIp, GatewayPort))
                            {
                                using (var stream = gw.GetStream())
                                {
                                    _drug.Write(stream);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            EventLogger.Error($"Failed reading patient record: {ex.Message}");
                            throw;
                        }
                        finally
                        {
                            Mutex.ReleaseMutex();
                        }

                        _drug.Clear();
                    }
                }
            }
            catch (RowNotInTableException)
            {
                return;  // No records
            }

            catch (Exception ex)
            {
                throw;
            }
        }
Exemplo n.º 58
0
        private void CopyStreamWithRotation(StreamReader reader, string extension)
        {
            // lock required as the timer thread and the thread that will write to the stream could try and access the file stream at the same time
            var fileLock = new object();

            var baseDirectory = Path.GetDirectoryName(BaseLogFileName) !;
            var baseFileName  = Path.GetFileName(BaseLogFileName);
            var logFile       = BaseLogFileName + extension;

            var writer     = CreateWriter(new FileStream(logFile, FileMode.Append));
            var fileLength = new FileInfo(logFile).Length;

            // We auto roll at time is configured then we need to create a timer and wait until time is elasped and roll the file over
            if (AutoRollAtTime is TimeSpan autoRollAtTime)
            {
                // Run at start
                var tickTime = SetupRollTimer(autoRollAtTime);
                var timer    = new System.Timers.Timer(tickTime);
                timer.Elapsed += (s, e) =>
                {
                    try
                    {
                        timer.Stop();
                        lock (fileLock)
                        {
                            writer.Dispose();

                            var now            = DateTime.Now.AddDays(-1);
                            var nextFileNumber = GetNextFileNumber(extension, baseDirectory, baseFileName, now);
                            var nextFileName   = Path.Combine(baseDirectory, string.Format("{0}.{1}.#{2:D4}{3}", baseFileName, now.ToString(FilePattern), nextFileNumber, extension));
                            File.Move(logFile, nextFileName);

                            writer     = CreateWriter(new FileStream(logFile, FileMode.Create));
                            fileLength = new FileInfo(logFile).Length;
                        }

                        // Next day so check if file can be zipped
                        ZipFiles(baseDirectory, extension, baseFileName);
                    }
                    catch (Exception ex)
                    {
                        EventLogger.LogEvent($"Failed to to trigger auto roll at time event due to: {ex.Message}");
                    }
                    finally
                    {
                        // Recalculate the next interval
                        timer.Interval = SetupRollTimer(autoRollAtTime);
                        timer.Start();
                    }
                };
                timer.Start();
            }

            string?line;

            while ((line = reader.ReadLine()) != null)
            {
                lock (fileLock)
                {
                    int lengthToWrite = (line.Length + Environment.NewLine.Length) * sizeof(char);
                    if (fileLength + lengthToWrite > SizeTheshold)
                    {
                        try
                        {
                            // rotate file
                            var now            = DateTime.Now;
                            var nextFileNumber = GetNextFileNumber(extension, baseDirectory, baseFileName, now);
                            var nextFileName   =
                                Path.Combine(baseDirectory,
                                             string.Format("{0}.{1}.#{2:D4}{3}", baseFileName, now.ToString(FilePattern), nextFileNumber, extension));
                            File.Move(logFile, nextFileName);

                            // even if the log rotation fails, create a new one, or else
                            // we'll infinitely try to rotate.
                            writer     = CreateWriter(new FileStream(logFile, FileMode.Create));
                            fileLength = new FileInfo(logFile).Length;
                        }
                        catch (Exception e)
                        {
                            EventLogger.LogEvent($"Failed to roll size time log: {e.Message}");
                        }
                    }

                    writer.WriteLine(line);
                    fileLength += lengthToWrite;
                }
            }

            reader.Dispose();
            writer.Dispose();
        }
Exemplo n.º 59
0
    public void enviaCorreo(string idPais, string usr, string pwd, string correoGZ, string archivo)
    {
        string rutaArchivo = (@"C:\Bcaribe\" + archivo + ".pdf");
        string smtpServer = "smtp.gmail.com";
        MailMessage correo = new MailMessage();
        correo.From = new MailAddress("*****@*****.**");
        correo.To.Add(correoGZ);
        DataTable dtTaccion = tipoAccion(idPais);
        for (int i = 0; i < dtTaccion.Rows.Count; i++)
        {
            correo.Bcc.Add(dtTaccion.Rows[i][0].ToString());
        }
        // correo.Bcc.Add(); // enviar mensajes ocultos
        correo.Subject = "PDF-NUEVAS";
        correo.Body = "FYI";
        Attachment attachment = new Attachment(rutaArchivo); //create the attachment
        correo.Attachments.Add(attachment);	//add the attachment
        // correo.BodyEncoding =
        correo.Priority = MailPriority.Normal;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = smtpServer;
        smtp.Port = 587;
        smtp.UseDefaultCredentials = false;
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp.EnableSsl = true;
        smtp.Timeout = 900000;
        smtp.Credentials = new System.Net.NetworkCredential(usr, pwd);
        try
        {
            smtp.Send(correo);
            correo.Dispose();
            if (File.Exists(rutaArchivo))
            {
                File.Delete(rutaArchivo);
            }

            //LabelError.Text = "Mensaje enviado satisfactoriamente";
        }
        catch (Exception ex)
        {
            // "error : "+ ex ;
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex);
            //LabelError.Text = "ERROR: " + ex.Message;
        }
    }
Exemplo n.º 60
0
    public DataTable obtener(int paisID, String usuarioNombres, int perfilID, String estado)
    {
        DataTable dt = new DataTable("ListadoUsuarios");
        SqlDataAdapter da = new SqlDataAdapter();
        SqlConnection cn = new SqlConnection(cd.getConnectionString());

        try
        {
            cn.Open();
            da = new SqlDataAdapter("usp_bel_usuario_obtener", cn);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;

            da.SelectCommand.Parameters.Add("@paisID", SqlDbType.Int).Value = paisID;
            da.SelectCommand.Parameters.Add("@nombres", SqlDbType.VarChar, 99).Value = usuarioNombres;
            da.SelectCommand.Parameters.Add("@perfil", SqlDbType.Int).Value = perfilID;

            if (estado.Equals("0"))
                da.SelectCommand.Parameters.Add("@estado", SqlDbType.Bit).Value = DBNull.Value;
            else
                da.SelectCommand.Parameters.Add("@estado", SqlDbType.Bit).Value = estado;
            da.Fill(dt);

        }
        catch (Exception ex)
        {
            EventLogger ev = new EventLogger();
            ev.Save("ASP.NET 2.0.50727.0", ex); //ASP.NET 2.0.50727.0
            dt = null;
        }
        finally
        {
            cn.Close();
        }

        return dt;
    }