Esempio n. 1
0
 void context_AuthenticateRequest(object sender, EventArgs e)
 {
     string name = HttpContext.Current.User.Identity.Name;
     EventLog log = new EventLog();
     log.Source = "Log User Module";
     log.WriteEntry(name + " was authenticated.");        
 }
Esempio n. 2
0
    private static void EscribeEnRegistro()
    {
        EventLog evento;
        string registro = "Application";
        string equipo = Environment.MachineName;
        string programa;

        // Mensajes de una primera aplicación ficticia
        programa = "Programa1";
        evento = new EventLog(registro, equipo, programa);
        evento.WriteEntry("Información relatica a la aplicación", EventLogEntryType.Information);
        evento.WriteEntry("Ocurrió un error en la aplicación", EventLogEntryType.Error);
        evento.WriteEntry("Suceso correcto", EventLogEntryType.SuccessAudit);
        evento = null;

        // Mensajes de una primera aplicación ficticia
        programa = "Programa2";
        evento = new EventLog(registro, equipo, programa);
        evento.WriteEntry("Información relatica a la aplicación", EventLogEntryType.Information);
        evento.WriteEntry("Ocurrió un error en la aplicación", EventLogEntryType.Error);
        evento.WriteEntry("Suceso correcto", EventLogEntryType.SuccessAudit);
        evento = null;

        evento.Source = programa;
        evento.WriteEntry(programa, EventLogEntryType.Information);
    }
Esempio n. 3
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            //除法运算
            decimal a, b, result;
            a = decimal.Parse(TextBox1.Text);
            b = decimal.Parse(TextBox2.Text);
            result = a / b;
        }
        catch (Exception ex)
        {
            //显示异常详细信息
            lblResult.Text = "<b>错误消息:</b>" + ex.Message + "<br/><br/>";
            lblResult.Text += "<b>错误源:</b>" + ex.Source + "<br/><br/>";
            lblResult.Text += "<b>堆栈追踪::</b>" + ex.StackTrace + "<br/><br/>";
            lblResult.ForeColor = System.Drawing.Color.Red;
            //将除法运算错误信息写入事件日志

            //该构造函数将打开指定名称的事件日志,如果不存在,则创建一个新的事件日志
            EventLog elog = new EventLog("ASPNET35BookDemo");
            //调用EventLog的静态方法SourceExists判断指定的事件源是否注册
            if (!EventLog.SourceExists("除法运算错误2"))
            {
                //如果没有注册,调用CreateEventSource方法注册事件源,并创建一个新的事件日志。
                EventLog.CreateEventSource("除法运算错误2", "ASPNET35BookDemo");
            }
            //EventLog可以指定事件日志名称,如果不指定,则为Application事件日志

            //指定日志源
            elog.Source = "除法运算错误2";
            //调用WriteEntry方法向日志中写入一个日志项
            elog.WriteEntry(ex.Message, EventLogEntryType.Error);
        }
    }
Esempio n. 4
0
    public static void Main()
    {
        if (!EventLog.SourceExists ("pipeline"))
            EventLog.CreateEventSource ("pipeline", "XSP");

        using (EventLog log = new EventLog ("XSP", ".", "pipeline")) {
            log.WriteEntry ("A test message.",
                EventLogEntryType.Information, 5);
            log.WriteEntry ("Some test message.",
                EventLogEntryType.Warning, 4);
            log.WriteEntry ("Another test message.",
                EventLogEntryType.Error, 1300);
        }

        if (!EventLog.SourceExists ("XPlatUI"))
            EventLog.CreateEventSource ("XPlatUI", "MWF");

        using (EventLog log = new EventLog ("MWF", ".", "XPlatUI")) {
            log.WriteEntry ("Bug #56093 fixed.",
                EventLogEntryType.Information);
            log.WriteEntry ("New bug reported.",
                EventLogEntryType.Warning);
            log.WriteEntry ("Build failure.",
                EventLogEntryType.Error);
        }
    }
        public void ShouldSortBasedOnBlockNumberAndTransaction()
        {
            //given
            var filterLog = new FilterLog()
            {
                BlockNumber = new HexBigInteger(1),
                TransactionIndex = new HexBigInteger(1)
            };
            var eventLog = new EventLog<MyEvent>(null, filterLog);
            var filterLog2 = new FilterLog()
            {
                BlockNumber = new HexBigInteger(2),
                TransactionIndex = new HexBigInteger(1)
            };
            var eventLog2 = new EventLog<MyEvent>(null, filterLog2);

            var filterLog3 = new FilterLog()
            {
                BlockNumber = new HexBigInteger(2),
                TransactionIndex = new HexBigInteger(2)
            };
            var eventLog3 = new EventLog<MyEvent>(null, filterLog3);

            var list = new List<object>(new[] {eventLog3, eventLog, eventLog2});
            list.Sort(new EventLogBlockNumberTransactionIndexComparer());
            Assert.Same(eventLog, list[0]);
            Assert.Same(eventLog2, list[1]);
            Assert.Same(eventLog3, list[2]);
        }
Esempio n. 6
0
    public void Execute(IJobExecutionContext context)
    {
        EventLog myLog = new EventLog();
        myLog.Source = "MYEVENTSOURCE";

        // Write an informational entry to the event log.
        myLog.WriteEntry("Job has run!");
    }
 public virtual void TestInstantiationEvents()
 {
     var instantiatedLog = new EventLog();
     EventRegistry().Instantiated += new _IEventListener4_20(this, instantiatedLog).OnEvent;
     RetrieveOnlyInstance(typeof (Item));
     Assert.IsFalse(instantiatedLog.xing);
     Assert.IsTrue(instantiatedLog.xed);
 }
Esempio n. 8
0
    public HelloWinService()
    {
        this.ServiceName = "WinService1";

        string source = "Main";
        eventLog = new EventLog();
        eventLog.Source = source;
    }
Esempio n. 9
0
 public virtual void TestActivationEvents()
 {
     var activationLog = new EventLog();
     EventRegistry().Activating += new _IEventListener4_19(this, activationLog).OnEvent;
     EventRegistry().Activated += new _IEventListener4_25(this, activationLog).OnEvent;
     RetrieveOnlyInstance(typeof (Item));
     Assert.IsTrue(activationLog.xing);
     Assert.IsTrue(activationLog.xed);
 }
Esempio n. 10
0
 public void LogError(String pageError, Exception error, String writePath)
 {
     RegisterLog();
     _log = new EventLog("ImportantLog");
     _log.Source = pageError;
     _log.WriteEntry(error.Message, EventLogEntryType.Error);
     int e = _log.Entries.Count;
     Entry = _log.Entries[e - 1];
     writeLogEntry(writePath);
 }
Esempio n. 11
0
 public void LogImportant(String fromPage,String message,EventLogEntryType type,String writePath)
 {
     RegisterLog();
     _log = new EventLog("ImportantLog");
     _log.Source = fromPage;
     _log.WriteEntry(message, type);
     int e=_log.Entries.Count;
     Entry = _log.Entries[e - 1];
     writeLogEntry(writePath);
 }
Esempio n. 12
0
	private void OnAuthentication(object sender, EventArgs a)
	{
		// Get the current user identity.
		string name = HttpContext.Current.User.Identity.Name;

		// Log the user name.
		EventLog log = new EventLog();
		log.Source = "Log User Module";
		log.WriteEntry(name + " was authenticated.");
	}
Esempio n. 13
0
    public static void AddLog(string errorMessage, string logName)
    {
        if (!EventLog.SourceExists(SourceName))
        {
            EventLog.CreateEventSource(SourceName, logName);
        }

        EventLog log = new EventLog();
        log.Source = SourceName;
        log.WriteEntry(errorMessage);
    }
Esempio n. 14
0
        private EventLog _log; // Предоставляет возможности взаимодействия с журналами событий Windows.

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Инициализирует новый экземпляр класса
        /// </summary>
        protected Journal()
        {
            bool find = EventLog.SourceExists(sourceName);
            if (!find)
            {
                EventLog.CreateEventSource(sourceName, "SGT");
            }

            _log = new EventLog();
            _log.Source = sourceName;
        }
    static void Main(string[] args)
    {
        EventLog evtLog = new EventLog("Application");
        evtLog.MachineName = ".";  // dot is local machine

        foreach (EventLogEntry evtEntry in evtLog.Entries)
        {
            Console.WriteLine(evtEntry.Message);
        }

        evtLog.Close();
    }
Esempio n. 16
0
 public NTEventLogLogger()
 {
     // Create the source, if it does not already exist.
     if (!EventLog.SourceExists(MySource))
     {
         EventLog.CreateEventSource(MySource, "Application");
         if (DEBUG)
             Console.WriteLine("CreatingEventSource");
     }
     // Create an EventLog instance and assign its source.
     EventLog myLog = new EventLog();
     myLog.Source = MySource;
 }
Esempio n. 17
0
 // ---------- CONSTRUCTORS ----------
 /// <summary>
 /// Creates a stored procedure.
 /// </summary>
 /// <param name="connectionString">The connection string for the SQL database to which the procedure belongs.</param>
 /// <param name="procedureName">The name of the procedure.</param>
 /// <param name="log">An event log to log exceptions to. May be null if no exception logging is desired.</param>
 public OracleStoredProcedure(string connectionString, string procedureName, EventLog.EventLog log)
 {
     // Check that parameters were supplied.
     if (!string.IsNullOrEmpty(connectionString) && !string.IsNullOrEmpty(procedureName))
     {
         // Initialize the connection and command.
         Name = procedureName;
         Connection = new OracleConnection(connectionString);
         Command = new OracleCommand(Name, (OracleConnection)Connection);
         Command.CommandType = CommandType.StoredProcedure;
     }
     Log = log;
 }
 private void Application_EndRequest(Object source, EventArgs e)
 {
     HttpApplication application = (HttpApplication)source;
     HttpContext context = application.Context;
     if (VirtualPathUtility.GetExtension(
     context.Request.FilePath) == ".aspx") {
         EventLog eLog = new EventLog();
         eLog.Source = "Robby1 Application";
         eLog.WriteEntry("End .aspx request :: " +
         DateTime.Now.ToLongDateString() + " :: " +
         context.Server.MachineName,
         EventLogEntryType.Information);
     }
 }
Esempio n. 19
0
		public void SaveEvent(IDomainEvent @event)
		{
			var eventLogEntry = new EventLog
			{
				EventId = @event.Id,
				EventProviderId = @event.AggregateId,
				Version = @event.Version,
				Type = @event.GetType().AssemblyQualifiedName,
				User = @event.ByUser,
				DateHappened = @event.DateHappened,
				JSonDomainEvent = @event.GetJSonSerialisation(),
			};

			entityRepository.Save(eventLogEntry);
		}
        /// <summary>
        /// Write a log request to the event log.
        /// </summary>
        /// <remarks>
        /// Actual event log write entry statements are commented out.
        /// Uncomment if you have the proper privileges.
        /// </remarks>
        /// <param name="sender">Sender of the log request.</param>
        /// <param name="e">Parameters of the log request.</param>
        public void Log(object sender, LogEventArgs e)
        {
            string message = "[" + e.Date.ToString() + "] " +
                e.SeverityString + ": " + e.Message;

            var eventLog = new EventLog();
            eventLog.Source = "Patterns In Action";

            // Map severity level to an Windows EventLog entry type
            var type = EventLogEntryType.Error; 
            if (e.Severity < LogSeverity.Warning) type = EventLogEntryType.Information;
            if (e.Severity < LogSeverity.Error) type = EventLogEntryType.Warning;

            // In try catch. You will need proper privileges to write to eventlog.
            try { eventLog.WriteEntry(message, type); }
            catch { /* do nothing */ }
        }
Esempio n. 21
0
 public virtual void TestDeletionEvents()
 {
     if (IsEmbedded())
     {
         // TODO: something wrong when embedded c/s is run as part
         // of the full test suite
         return;
     }
     var deletionLog = new EventLog();
     ServerEventRegistry().Deleting += new _IEventListener4_25(this, deletionLog).OnEvent;
     ServerEventRegistry().Deleted += new _IEventListener4_31(this, deletionLog).OnEvent;
     Db().Delete(((Item) RetrieveOnlyInstance(typeof (Item
         ))));
     Db().Commit();
     Assert.IsTrue(deletionLog.xing);
     Assert.IsTrue(deletionLog.xed);
 }
Esempio n. 22
0
        public override int run(string[] args)
        {
            if (args.Length != 0)
                throw new ApplicationException("starting: too many arguments in application call.");

            if (!EventLog.SourceExists("IGSMDesktop"))
                EventLog.CreateEventSource(new EventSourceCreationData("IGSMDesktop", "IGSMService"));
            m_logMgr = new EventLog("IGSMService", Environment.MachineName, "IGSMDesktop");
            m_logMgr.WriteEntry("Server manager started", EventLogEntryType.Information);

            try
            {
                s_sServerManagerPort = IGSMDesktopIce.Properties.Settings.Default.SERVERMGR_PORT_INPUT;

                Dictionary<string, string> dicSettings = new Dictionary<string, string>();
                foreach (SettingsPropertyValue prop in IGSMDesktopIce.Properties.Settings.Default.PropertyValues)
                    dicSettings.Add(prop.Name, (string)prop.PropertyValue);
                m_serverMgr = (IGServerManagerLocal)IGServerManager.CreateInstanceLocal(dicSettings, Convert.ToInt32(s_sServerManagerPort));
                string sIPShare = IGSMDesktopIce.Properties.Settings.Default.SERVERMGR_IPSHARE;
                int nFirstPort = Convert.ToInt32(IGSMDesktopIce.Properties.Settings.Default.SERVERMGR_PORT_INPUT) + 1;
                int nNbServers = 1; // start the application with one server
                List<IGServer> lServerPorts = new List<IGServer>();
                for (int idxPort = 0; idxPort < nNbServers; idxPort++)
                    lServerPorts.Add(new IGServerLocal(IGSMDesktopIce.Properties.Settings.Default.IP_LOCAL, nFirstPort + idxPort, IGSMDesktopIce.Properties.Settings.Default.SERVERMGR_IPWEBSERVER));
                m_serverMgr.ErrorEvent += new IGServerManager.ErrorHandler(OnError);
                m_serverMgr.Initialize(IGSMDesktopIce.Properties.Settings.Default.SERVERMGR_IPWEBSERVER, sIPShare, lServerPorts);

                Ice.ObjectAdapter adapter = communicator().createObjectAdapter("IGServerControllerIce");
                Ice.Properties properties = communicator().getProperties();
                Ice.Identity id = communicator().stringToIdentity(properties.getProperty("Identity"));
                adapter.add(new IGServerControllerIceI(m_serverMgr, properties.getProperty("Ice.ProgramName")), id);
                adapter.activate();

                m_logMgr.WriteEntry("Server manager initialized", EventLogEntryType.Information);
                communicator().waitForShutdown();
            }
            catch (Exception exc)
            {
                m_logMgr.WriteEntry(exc.ToString(), EventLogEntryType.Error);
            }

            return 0;
        }
Esempio n. 23
0
 /// <summary>
 /// Write event log to loggers
 /// </summary>
 /// <param name="log"></param>
 public void Write(EventLog log)
 {
     foreach (ILogger logger in _loggers.Values)
     {
         try
         {
             logger.Log(log);
         }
         catch (Exception err)
         {
             System.Diagnostics.Trace.TraceError("Log event to logger failed! Event: {0}; Exception: {1}", log, err.ToString());
         }
     }
     System.Diagnostics.Trace.WriteLineIf(log != null, log.ToString());
     if (_outputToConsole)
     {
         Console.WriteLine(log.ToString());
     }
 }
Esempio n. 24
0
    // Get static instance of the EVENT LOG object
    public static EventLog GetInstance() {

        // Find instance if never looked up, store it in h_Instance for future refference
        if (h_Instance == null)
        {
            RectTransform[] uiElements = RectTransform.FindObjectsOfType<RectTransform>();

            for (int i = 0; i < uiElements.Length; i++)
            {
                EventLog foundLog = uiElements[i].GetComponentInChildren<EventLog>();
                if (foundLog != null)
                {
                    h_Instance = foundLog;
                    break;
                }

            }
        }

        return h_Instance;
    }
Esempio n. 25
0
        public LogRoot(BinaryReader log, long chunkOffset, uint length, EventLog parent)
        {
            this.ParentLog = parent;
            this.Position = log.BaseStream.Position;
            this.ChunkOffset = chunkOffset;
            this.Nodes = new List<INode>();
            this.Strings = new Dictionary<long, string>();
            this.Length = length;

            while (this.Length >= 0 && !this.ReachedEOS)
            {
                INode node = LogNode.NewNode(log, this, chunkOffset, this);
                this.Nodes.Add(node);
                this.Length -= node.Length;

                if (node is _x00)
                    this.ReachedEOS = true;
            }

            this.SubstitutionArray = new SubstitutionArray(log, chunkOffset, this);
        }
Esempio n. 26
0
 /// <summary>
 /// Метод инициализации журнала событий Windows.
 /// </summary>
 public static void Init()
 {
     // Иницируем журнал событий Windows
     try
     {
         // Если не существует windows лога службы, то создаем его и назначаем по-умолчанию для записи
         if (!EventLog.SourceExists("SmartHouseService"))
             EventLog.CreateEventSource("SmartHouseService", "SmartHouseServiceLog");
         // Иницируем журнал событий Windows
         _log = new EventLog();
         _log.Source = "SmartHouseService";
         _log.Log = "SmartHouseServiceLog";
         _log.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 30);
     }
     catch (Exception)
     {
         if (_log != null)
             _log.Dispose();
         _log = null;
     }
 }
  private void Pump()
  {
    try
    {
      _listener = (HttpListenerWrapper)ApplicationHost.CreateApplicationHost(
          typeof(HttpListenerWrapper), _virtualDir, _physicalDir);
      _listener.Configure(_prefixes, _virtualDir, _physicalDir);
      _listener.Start();

      while (_listening)
        _listener.ProcessRequest();
    }
    catch (Exception ex)
    {
      EventLog myLog = new EventLog();
      myLog.Source = "HttpListenerController";
      if (null != ex.InnerException)
        myLog.WriteEntry(ex.InnerException.ToString(), EventLogEntryType.Error);
      else
        myLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
    }
  }
Esempio n. 28
0
    private ArrayList GetEventLogEntries(string slogName, int nNumEntries)
    {
        ArrayList saReturn = new ArrayList();
        EventLog eventLog = new EventLog(slogName);
        EventLogEntryCollection saEvents;
        int nCount = 0;

        saEvents = eventLog.Entries;

        if (nNumEntries > eventLog.Entries.Count)
            nCount = 0;
        else
            nCount = eventLog.Entries.Count - nNumEntries;

        for (int i = eventLog.Entries.Count - 1; i >= nCount; i--)
            saReturn.Add(saEvents[i].Source + SPLIT_VAL + saEvents[i].EntryType + SPLIT_VAL + saEvents[i].Message + SPLIT_VAL + saEvents[i].TimeGenerated.ToString());

        //----- Cleanup
        if (eventLog != null)
            eventLog = null;

        return saReturn;
    }
Esempio n. 29
0
 /// <inheritdoc />
 protected override void OnLog(LogEventArgs itm)
 {
     EventLog.Add(itm);
 }
Esempio n. 30
0
 protected override void OnStop()
 {
     EventLog.WriteEntry("teste de Serviço Interrompido", EventLogEntryType.Warning);
 }
Esempio n. 31
0
        private bool GetResponseFile(string _payroll_response_dir, string _payroll_output_dir, string _file, ISession session, out string outResult)
        {
            outResult = "";
            bool     _result = true;
            EventLog log     = new EventLog("Cash Management");

            log.Source = "Cash Management";

            ILog logs = LogManager.GetLogger(typeof(GetPayrollResponse));

            logs.Info("--get response file proses--");
            PayrollLog(session, "--get response file proses--");

            FileInfo file = new FileInfo(_payroll_response_dir + "\\" + _file);

            PayrollLog(session, "filenya adalah : " + file.FullName);

            FileInfo file2 = new FileInfo(_payroll_output_dir + "\\" + _file);

            try
            {
                //if (file.Exists(_payroll_response_dir + "\\" + _file))
                if (file.Exists)
                {
                    logs.Info(">>>>>> Ok, File exist");
                    PayrollLog(session, "file exists in : " + _payroll_response_dir + "filename : " + _file);

                    try
                    {
                        //File.Copy(_payroll_response_dir + "\\" + _file, _payroll_output_dir + "\\" + _file);
                        file.CopyTo(_payroll_output_dir + "\\" + _file, true);
                        PayrollLog(session, "Copy file : " + _file + "to :" + _payroll_output_dir);

                        try
                        {
                            //File.Delete(_payroll_response_dir + "\\" + _file);
                            file.Delete();
                            PayrollLog(session, "Delete file : " + _file + "from :" + _payroll_response_dir);
                            logs.Info(">>>>>> File exist");
                        }
                        catch (Exception e1)
                        {
                            _result   = false;
                            outResult = "[RETRY]Error when deleting payroll response file : " + _file + "," + e1.Message;
                            logs.Error("Error when deleting payroll response file : " + _file + "," + e1.Message);
                            log.WriteEntry("Error when deleting payroll response file : " + _file + "," + e1.Message, EventLogEntryType.Error);
                            PayrollLog(session, "Error when deleting payroll response file : " + _file + "," + e1.Message + e1.StackTrace);
                        }
                    }
                    catch (Exception e2)
                    {
                        _result   = false;
                        outResult = "Error when copying payroll response file : " + _file + "," + e2.Message;
                        logs.Error("Error when copying payroll response file : " + _file + "," + e2.Message);
                        log.WriteEntry("Error when copying payroll response file : " + _file + "," + e2.Message, EventLogEntryType.Error);
                        PayrollLog(session, "Error when copying payroll response file : " + _file + "," + e2.Message + e2.StackTrace);
                    }
                }
                else if (file2.Exists)
                {
                    logs.Info(">>>>>> Ok, File exist in " + _payroll_output_dir);
                    PayrollLog(session, "file exists in : " + _payroll_output_dir + "filename : " + _file);
                }
                else
                {
                    _result   = false;
                    outResult = "[RETRY]File Not Found on Directory...";
                    logs.Error("File Not Found on Directory...");
                    log.WriteEntry("File : " + _payroll_response_dir + "\\" + _file + " not exist.");
                    PayrollLog(session, "file : " + _payroll_response_dir + "\\" + _file + "not exist");
                }
            }
            catch (Exception e3)
            {
                _result   = false;
                outResult = "Error when getting payroll response file : " + _file + "," + e3.Message;
                logs.Error("Error when getting payroll response file : " + _file + "," + e3.Message);
                log.WriteEntry("Error when getting payroll response file : " + _file + "," + e3.Message, EventLogEntryType.Error);
                PayrollLog(session, "Error when getting payroll response file : " + _file + "," + e3.Message + e3.StackTrace);
            }
            logs.Info("--get response file end--");
            return(_result);
        }
Esempio n. 32
0
 public LogVoltageFixRunner(IVoltageFixRunner wrappee, EventLog eventLog)
 {
     this.wrappee  = wrappee;
     this.eventLog = eventLog;
 }
Esempio n. 33
0
        public bool SendMail(System.Net.Mail.MailMessage m, bool async)
        {
            bool result = false;

            try {
                string _server   = WebAppSettings.ApplicationMailServer;
                string _user     = WebAppSettings.ApplicationMailServerUsername;
                string _password = WebAppSettings.ApplicationMailServerPassword;
                bool   _useAuth  = true;
                string _port     = WebAppSettings.ApplicationMailServerPort;
                bool   _useSSL   = WebAppSettings.ApplicationMailServerSSL;


                if (_store.Settings.MailServer.UseCustomMailServer)
                {
                    _server   = _store.Settings.MailServer.HostAddress;
                    _user     = _store.Settings.MailServer.Username;
                    _password = _store.Settings.MailServer.Password;
                    _useAuth  = _store.Settings.MailServer.UseAuthentication;
                    _port     = _store.Settings.MailServer.Port;
                    _useSSL   = _store.Settings.MailServer.UseSsl;
                }


                SmtpClient server = new SmtpClient();
                server.Host = _server;

                NetworkCredential auth = new NetworkCredential(_user, _password);

                if (_useAuth)
                {
                    server.UseDefaultCredentials = false;
                    server.Credentials           = auth;
                }

                if (_port.Trim() != string.Empty)
                {
                    int altPort = 25;
                    if (int.TryParse(_port, out altPort))
                    {
                        server.Port = altPort;
                    }
                }

                server.EnableSsl = _useSSL;

                // Body Replacement
                if (m.IsBodyHtml)
                {
                    m.Body = m.Body.Replace("</body>", "<div style=\"margin:0.25em;border-style:solid;border-width:1px 0 1px 3px;padding:0.5em 1em;font-face:arial;font-size:11px;color:#333;background-color: #fffffd;border-color: #B3B300;\">Get a <a href=\"http://www.MerchantTribe.com\">Free Shopping Cart by joining MerchantTribe</a> today!</div>");
                }
                else
                {
                    m.Body += System.Environment.NewLine + System.Environment.NewLine + "Get a Free Shopping Cart by joining MerchantTribe.com!" + System.Environment.NewLine;
                }

                if (WebAppSettings.ApplicationMailServerAsync)
                {
                    string userState = "Mail Sent";
                    server.SendAsync(m, userState);
                }
                else
                {
                    server.Send(m);
                }

                result = true;
            }
            catch (Exception Ex) {
                result = false;
                System.Diagnostics.Trace.Write(Ex.Message);
                EventLog.LogEvent(Ex);
            }

            return(result);
        }
Esempio n. 34
0
 public EventLogger()
 {
     this.Log        = new EventLog("Application");
     this.Log.Source = ".NET Runtime";
 }
Esempio n. 35
0
        public static void OutputLog(ref StringBuilder result)
        {
            if (result == null)
            {
                result = new StringBuilder(1000);
            }

            var rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");

            if (rk != null)
            {
                result.AppendLine(rk.GetValue("ProductName") + " " + rk.GetValue("BuildLabEx"));
            }

            string version = LocalizationProvider.Instance.GetTextValue("About.Version") +
                             (Environment.Is64BitProcess ? " X64" : " x86") +
                             (AppConfig.UiAccess ? " UIAccess" : "");

            using (RegistryKey layers = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"))
            {
                string daemonPath   = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GestureSignDaemon.exe");
                var    daemonRecord = layers?.GetValue(daemonPath) as string;
                if (daemonRecord != null && daemonRecord.Contains("WIN8RTM"))
                {
                    version += " CompatibilityMode";
                }
            }
            result.AppendLine(version);

            string directoryPath = Path.GetDirectoryName(new Uri(Application.ResourceAssembly.CodeBase).LocalPath);

            if (directoryPath != null)
            {
                result.AppendLine(directoryPath);

                var components = Directory.EnumerateFiles(directoryPath).Where(s => s.EndsWith(".dll") || s.EndsWith(".exe"));
                foreach (var com in components)
                {
                    result.AppendLine($"{Path.GetFileName(com)} {FileVersionInfo.GetVersionInfo(com).FileVersion}");
                }
            }
            result.AppendLine();


            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_computersystem");

            foreach (ManagementObject mo in searcher.Get())
            {
                try
                {
                    result.AppendLine(mo["Manufacturer"].ToString().Trim());
                    result.AppendLine(mo["Model"].ToString().Trim());
                    break;
                }
                catch { }
            }
            searcher = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystemProduct");
            foreach (ManagementObject mo in searcher.Get())
            {
                try
                {
                    result.AppendLine(mo["Version"].ToString().Trim());
                }
                catch { }
            }

            result.AppendLine();
            result.AppendLine();

            if (File.Exists(Logging.LogFilePath))
            {
                using (FileStream fs = new FileStream(Logging.LogFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    using (StreamReader streamReader = new StreamReader(fs))
                        result.Append(streamReader.ReadToEnd());
                }
            }

            EventLog logs = new EventLog {
                Log = "Application"
            };

            foreach (EventLogEntry entry in logs.Entries)
            {
                if (entry.EntryType == EventLogEntryType.Error && ".NET Runtime".Equals(entry.Source))
                {
                    result.AppendLine(entry.TimeWritten.ToString(CultureInfo.InvariantCulture));
                    result.AppendLine(entry.Message.Replace("\n", "\r\n"));
                }
            }
        }
Esempio n. 36
0
    private DataSet GetDataSet(string storedProcName, string connectionStringName, List <SqlParameter> param = null, int level = 0)
    {
        if (!isOp())
        {
            throw new Exception("Неверный идентификатор сессии");
        }
        //    return null;
        if ((storedProcName.Trim() == "") || (connectionStringName.Trim() == ""))
        {
            return(null);
        }

        if (Session["ClientID"] == null)
        {
            Session["ClientID"] = "0";
        }
        if (Session["ClientDiscount"] == null)
        {
            Session["ClientDiscount"] = "0";
        }

        string parentMethod = CRMUtil.getParentMethodName(level);

        SqlConnection c;

        try
        {
            c = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString);
        }
        catch
        {
            string ErrMsg = "Ошибка соединения " + connectionStringName;
            Logger logger = LogManager.GetCurrentClassLogger();
            logger.Info("Error: {0}", ErrMsg);
            LogManager.Flush();
            EventLog.WriteEntry("CRMAutoInfo", ErrMsg, EventLogEntryType.Error);
            DataSet erds = new DataSet("ErrorData");
            erds.Tables.Add("ErrorTable");
            erds.Tables["ErrorTable"].Columns.Add("ErrorMessage", typeof(string));
            DataRow r = erds.Tables["ErrorTable"].NewRow();
            return(erds);
        }
        using (SqlDataAdapter da = new SqlDataAdapter(storedProcName, c))
            using (DataSet ds = new DataSet(parentMethod + "Data"))
            {
                da.SelectCommand.CommandTimeout = 120;
                da.SelectCommand.CommandType    = CommandType.StoredProcedure;
                if (param != null)
                {
                    foreach (SqlParameter p in param)
                    {
                        da.SelectCommand.Parameters.Add(p);
                    }
                }

                da.Fill(ds, parentMethod + "Table");
                da.SelectCommand.Parameters.Clear();

                return(ds);
            }
    }
Esempio n. 37
0
 protected virtual Task SaveAsync(EventLog eventLog)
 {
     return(Task.CompletedTask);
 }
Esempio n. 38
0
        static void Main(string[] args)
        {
            // System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;

            ServiceShortName = "dp2CapoService";

            PrintLogo();

            // 修改配置
            if (args.Length >= 1 && args[0].Equals("setting"))
            {
                ChangeSettings(args.Length > 1 ? args[1] : "");
                return;
            }

            // 注册或注销 Windows Service
            if (args.Length == 1 &&
                (args[0].Equals("install") || args[0].Equals("uninstall"))
                )
            {
                bool bInstall = true;

                if (args[0].Equals("uninstall"))
                {
                    bInstall = false;
                }

                // 注册为 Windows Service
                string strExePath = Assembly.GetExecutingAssembly().Location;
                Console.WriteLine((bInstall ? "注册" : "注销") + " Windows Service ...");

                try
                {
                    Console.WriteLine("停止服务 ...");
                    ServiceUtil.StopService("dp2CapoService", TimeSpan.FromMinutes(2));
                    Console.WriteLine("服务已停止。");
                }
                catch//(Exception ex)
                {
                    // Console.WriteLine("停止服务时发生异常: " + ExceptionUtil.GetExceptionText(ex));
                }
#if NO
                if (bInstall == true)
                {
                    // 创建事件日志目录
                    // 注: 创建事件日志目录应该在 InstallService 以前。因为 InstallService 过程中涉及到启动服务,可能要写入日志
                    if (!EventLog.SourceExists(ServiceShortName))   // "dp2Capo"
                    {
                        EventLog.CreateEventSource(ServiceShortName, "DigitalPlatform");
                    }
                }
#endif

                string strError = "";
                int    nRet     = ServiceUtil.InstallService(strExePath,
                                                             bInstall,
                                                             out strError);
                if (nRet == -1)
                {
                    Console.WriteLine("error: " + strError);
                }

                Console.WriteLine();
                Console.WriteLine("(按回车键返回)");
                Console.ReadLine();
                return;
            }

            // 以控制台方式运行
            if (args.Length == 1 && args[0].Equals("console"))
            {
                if (Initial() == false)
                {
                    return;
                }
                new Program().ConsoleRun();
                return;
            }
            else
            {
                // 这是从命令行启动的情况
                if (Environment.UserInteractive == true)
                {
                    Console.WriteLine("dp2capo 用法:");
                    Console.WriteLine("注册 Windows Service: dp2capo install");
                    Console.WriteLine("注销 Windows Service: dp2capo uninstall");
                    Console.WriteLine("以控制台方式运行: dp2capo console");
                    Console.WriteLine("修改配置参数: dp2capo setting");
                    Console.WriteLine("修改实例配置参数: dp2capo setting 1");

                    Console.WriteLine("(按回车键返回)");
                    Console.ReadLine();
                    return;
                }

                if (Initial() == false)
                {
                    return;
                }

                // 这是被当作 service 启动的情况
                ServiceBase.Run(new Program());
            }
        }
Esempio n. 39
0
        static void Main(string[] args)
        {
            EventLog eventLogService = new EventLog();

            if (!EventLog.SourceExists("ConsolaDBF"))
            {
                EventLog.CreateEventSource("ConsolaDBF", "DBFCmdLog");
            }

            eventLogService.Source = "ConsolaDBF";
            eventLogService.Log    = "DBFCmdLog";


            if (args.Length == 0)
            {
                eventLogService.WriteEntry("Console usage: NO ARGUMENTS FOUND.", EventLogEntryType.Error, 1, 1);
                return;
            }

            eventLogService.WriteEntry("CONSOLE EXECUTION BEGIN FOR [" + args[0] + "].");

            // Read configuration file
            string rutaDatos         = ConfigurationManager.AppSettings["rutaDatos"].ToString();
            var    configuredClients = ConfigurationManager.AppSettings as NameValueCollection;

            if (configuredClients == null)
            {
                eventLogService.WriteEntry("Unable to load the configuration file.", EventLogEntryType.Warning, 2, 1);
                return;
            }

            if (configuredClients.Count == 0)
            {
                eventLogService.WriteEntry("No keys detected in configuration file.", EventLogEntryType.Warning, 3, 1);
                return;
            }

            foreach (var key in configuredClients.AllKeys)
            {
                string configuredClient = configuredClients.GetValues(key).FirstOrDefault();

                if ("rutaDatos".Equals(key.ToString()))
                {
                    continue;
                }
                if ("primerContacto".Equals(key.ToString()))
                {
                    continue;
                }
                EnterpriseSection clientConfig = (EnterpriseSection)System.Configuration.ConfigurationManager.GetSection("Empresas/" + configuredClient);

                if (clientConfig == null)
                {
                    eventLogService.WriteEntry("Company configuration not found for Empresas/" + configuredClient + ".", EventLogEntryType.Warning, 4, 1);
                    continue;
                }

                Empresa empresa = Empresas.GetEmpresa(clientConfig.NombreEmpresa, rutaDatos, eventLogService);
                empresa.Ruta = @clientConfig.RutaEmpresa;
                if (empresa == null)
                {
                    eventLogService.WriteEntry("Configuration not found in AdminPaq for configured company: " +
                                               clientConfig.NombreEmpresa, EventLogEntryType.Warning, 5, 1);
                    continue;
                }
                else
                {
                    eventLogService.WriteEntry("Company configuration found in database: " + clientConfig.NombreEmpresa + "; " + @empresa.Ruta, EventLogEntryType.Information, 6, 1);

                    string[] ConceptosAbono      = clientConfig.CodigosPago.Split(',');
                    string[] ConceptosCredito    = clientConfig.CodigosFactura.Split(',');
                    string[] ConceptosDevolucion = clientConfig.CodigosDevolucion.Split(',');
                    string[] ConceptosVenta      = clientConfig.CodigosVenta.Split(',');
                    eventLogService.WriteEntry("Payment codes found for " + clientConfig.NombreEmpresa + " as [" + clientConfig.CodigosPago + "]", EventLogEntryType.Information, 7, 1);
                    eventLogService.WriteEntry("Credit codes found for " + clientConfig.NombreEmpresa + " as [" + clientConfig.CodigosFactura + "]", EventLogEntryType.Information, 8, 1);
                    eventLogService.WriteEntry("Sale codes found for " + clientConfig.NombreEmpresa + " as [" + clientConfig.CodigosVenta + "]", EventLogEntryType.Information, 9, 1);
                    eventLogService.WriteEntry("Return codes found for " + clientConfig.NombreEmpresa + " as [" + clientConfig.CodigosDevolucion + "]", EventLogEntryType.Information, 10, 1);

                    // Send configuration details as input to dataMiner.
                    empresa.ConceptosAbono      = ConceptosAbono;
                    empresa.ConceptosCredito    = ConceptosCredito;
                    empresa.ConceptosDevolucion = ConceptosDevolucion;
                    empresa.ConceptosVenta      = ConceptosVenta;

                    Documentos docosAPI = new Documentos();
                    docosAPI.Empresa = empresa;
                    docosAPI.Log     = eventLogService;
                    docosAPI.MonfollConnectionString = ConfigurationManager.ConnectionStrings[Config.Common.MONFOLL].ConnectionString;

                    // Execute dataMiner operation based on parameter
                    switch (args[0])
                    {
                    case "COBRANZA":
                        docosAPI.ExtraerCuentasPorCobrar();
                        break;

                    case "ACTUALIZAR":
                        docosAPI.ActualizarCuentasPorCobrar();
                        break;

                    case "VENCIDOS":
                        docosAPI.CalcularVencidos();
                        break;

                    case "PORVENCER":
                        docosAPI.CalcularPorVencer();
                        break;

                    /*case "COBRADO":
                     *  docosAPI.CalcularCobrado();
                     *  break;*/
                    case "VENTAS":
                        docosAPI.CalcularVentas();
                        break;

                    /*case "DETALLE":
                     *  docosAPI.CalcularDetalle();
                     *  break;
                     * case "FIX":
                     *  docosAPI.Fix();
                     *  break;*/
                    case "CLIENTES":
                        docosAPI.Clientes();
                        break;

                    default:
                        eventLogService.WriteEntry("Console usage: argument not allowed: " + args[0] + ".", EventLogEntryType.Error, 11, 1);
                        break;
                    }
                }
            }

            eventLogService.WriteEntry("CONSOLE EXECUTION END FOR " + args[0]);
        }
Esempio n. 40
0
        // </Snippet7>
        //<Snippet9>
        //<Snippet10>
        // Handle a session change notice
        protected override void OnSessionChange(SessionChangeDescription changeDescription)
        {
#if LOGEVENTS
            EventLog.WriteEntry("SimpleService.OnSessionChange", DateTime.Now.ToLongTimeString() +
                " - Session change notice received: " +
                changeDescription.Reason.ToString() + "  Session ID: " +
                changeDescription.SessionId.ToString());
#endif

            //</Snippet10>
            switch (changeDescription.Reason)
            {
                case SessionChangeReason.SessionLogon:
                    userCount += 1;
#if LOGEVENTS
                    EventLog.WriteEntry("SimpleService.OnSessionChange",
                        DateTime.Now.ToLongTimeString() +
                        " SessionLogon, total users: " +
                        userCount.ToString());
#endif
                    break;
                case SessionChangeReason.SessionLogoff:

                    userCount -= 1;
#if LOGEVENTS
                    EventLog.WriteEntry("SimpleService.OnSessionChange",
                        DateTime.Now.ToLongTimeString() +
                        " SessionLogoff, total users: " +
                        userCount.ToString());
#endif
                    break;
                case SessionChangeReason.RemoteConnect:
                    userCount += 1;
#if LOGEVENTS
                    EventLog.WriteEntry("SimpleService.OnSessionChange",
                        DateTime.Now.ToLongTimeString() +
                        " RemoteConnect, total users: " +
                        userCount.ToString());
#endif
                    break;
                case SessionChangeReason.RemoteDisconnect:
                    userCount -= 1;
#if LOGEVENTS
                    EventLog.WriteEntry("SimpleService.OnSessionChange",
                        DateTime.Now.ToLongTimeString() +
                        " RemoteDisconnect, total users: " +
                        userCount.ToString());
#endif
                    break;
                case SessionChangeReason.SessionLock:
#if LOGEVENTS
                    EventLog.WriteEntry("SimpleService.OnSessionChange",
                        DateTime.Now.ToLongTimeString() +
                        " SessionLock");
#endif
                    break;
                case SessionChangeReason.SessionUnlock:
#if LOGEVENTS
                    EventLog.WriteEntry("SimpleService.OnSessionChange",
                        DateTime.Now.ToLongTimeString() +
                        " SessionUnlock");
#endif
                    break;
                default:
                    break;
            }
        }
Esempio n. 41
0
File: test.cs Progetto: mono/gert
	void TestC ()
	{
		if (!EventLog.Exists ("monologtemp", ".")) {
			EventLog.CreateEventSource ("monotempsourceA", "monologtemp");
			EventLog.CreateEventSource ("monotempsourceB", "monologtemp");
		}

		EventLog otherEventLogA = new EventLog ("monologtemp", ".", "monotempsourceA");

		EventLog otherEventLogB = new EventLog ("monologtemp", ".", "monotempsourceB");
		otherEventLogB.EntryWritten += new EntryWrittenEventHandler (EventLog_EntryWritten);
		otherEventLogB.EnableRaisingEvents = true;

		otherEventLogA.WriteEntry ("message1", EventLogEntryType.Warning,
			111, 1, new byte [] { 1, 8 });

		Thread.Sleep (10000);

		Assert.AreEqual (1, _entriesWritten.Count, "#C1");

		EventLogEntry entry = (EventLogEntry) _entriesWritten [0];
		Assert.AreEqual ((short) 1, entry.CategoryNumber, "#C2");
		Assert.AreEqual (111, entry.EventID, "#C3");
		Assert.AreEqual ("message1", entry.Message, "#C4");
		Assert.AreEqual ("monotempsourceA", entry.Source, "#C5");

		otherEventLogA.Clear ();

		otherEventLogA.WriteEntry ("message2", EventLogEntryType.Warning,
			222, 2, new byte [] { 2, 8 });
		otherEventLogA.WriteEntry ("message3", EventLogEntryType.Warning,
			333, 3, new byte [] { 3, 8 });

		Thread.Sleep (10000);

		Assert.AreEqual (2, _entriesWritten.Count, "#C6");

		entry = (EventLogEntry) _entriesWritten [1];
		Assert.AreEqual ((short) 3, entry.CategoryNumber, "#C7");
		Assert.AreEqual (333, entry.EventID, "#C8");
		Assert.AreEqual ("message3", entry.Message, "#C9");
		Assert.AreEqual ("monotempsourceA", entry.Source, "#C10");

		otherEventLogB.WriteEntry ("message4", EventLogEntryType.Warning,
			444, 4, new byte [] { 3, 8 });

		Thread.Sleep (10000);

		Assert.AreEqual (3, _entriesWritten.Count, "#C11");

		entry = (EventLogEntry) _entriesWritten [2];
		Assert.AreEqual ((short) 4, entry.CategoryNumber, "#C12");
		Assert.AreEqual (444, entry.EventID, "#C13");
		Assert.AreEqual ("message4", entry.Message, "#C14");
		Assert.AreEqual ("monotempsourceB", entry.Source, "#C15");

		otherEventLogA.Dispose ();
		otherEventLogB.Dispose ();

		Thread.Sleep (2000);
	}
Esempio n. 42
0
        public static void SqlError(System.Data.Common.DbException ex, string TSql)
        {
            bool isLocal = false;

            using (EventLog log = new EventLog("WebException"))
            {
                string url, method;
                string extData;
                if (System.Web.HttpContext.Current != null)
                {
                    HttpRequest Request = System.Web.HttpContext.Current.Request;
                    url     = Request.Url.ToString();
                    method  = Request.HttpMethod;
                    isLocal = Request.IsLocal;
                    string rp;
                    if (Request.UrlReferrer == null)
                    {
                        rp = "none";
                    }
                    else
                    {
                        rp = Request.UrlReferrer.ToString();
                        if (rp.Length > 255)
                        {
                            rp = rp.Substring(0, 255) + "<...>";
                        }
                    }
                    extData  = "\r\nReferrer:" + rp;
                    extData += "\r\nUserAgent:" + Request.UserAgent;
                    if (extData.Length > 512)
                    {
                        extData = extData.Substring(0, 512) + "<...>";
                    }
                }
                else
                {
                    url     = string.Empty;
                    method  = "n/a";
                    extData = string.Empty;
                }
                log.Source = "Sql";

                StringBuilder msg = new StringBuilder();
                msg.AppendFormat("url:{0} {1}", method, url);
                msg.AppendLine(extData);
                if (!string.IsNullOrEmpty(TSql))
                {
                    msg.AppendLine("Sql:");
                    msg.AppendLine(TSql);
                }

                //msg.AppendLine(ex.Message);
                if (ex is SqlException)
                {
                    SqlException msEx = (SqlException)ex;
                    for (int i = 0; i < msEx.Errors.Count; i++)
                    {
                        msg.AppendLine("Message: " + msEx.Errors[i].Message);
                        msg.AppendLine("LineNumber: " + msEx.Errors[i].LineNumber);
                        msg.AppendLine("Source: " + msEx.Errors[i].Source);
                        msg.AppendLine("Procedure: " + msEx.Errors[i].Procedure);
                    }
                }
                else
                {
                    msg.AppendLine("Message:" + ex.Message);
                    msg.AppendLine("ErrorCode:" + ex.ErrorCode);
                }



                StackTrace s = new StackTrace(true);
                for (int i = 1; i < s.FrameCount; i++)
                {
                    StackFrame t  = s.GetFrame(i);
                    MethodBase mb = s.GetFrame(i).GetMethod();
                    System.Reflection.Module m = mb.Module;
                    int line = t.GetFileLineNumber();

                    if (mb.Name != "SqlError" && !m.ScopeName.StartsWith("System"))
                    {
                        msg.AppendLine(mb.Name + "() " + t.GetFileName() + "  行:" + t.GetFileLineNumber());
                    }
                }
                //msg.AppendLine(ex.ToString());

                byte[] bin = null;
                if (method == "POST")
                {
                    Stream stm = System.Web.HttpContext.Current.Request.InputStream;
                    if (stm.Length > 5120)
                    {
                        bin = System.Text.ASCIIEncoding.ASCII.GetBytes("*data length:" + stm.Length.ToString());
                    }
                    else
                    {
                        long p = stm.Position;
                        bin = new byte[stm.Length];
                        stm.Seek(0, SeekOrigin.Begin);
                        stm.Read(bin, 0, bin.Length);
                        stm.Position = p;
                    }
                }

                try
                {
                    if (bin != null)
                    {
                        log.WriteEntry(msg.ToString(), EventLogEntryType.Error, 0, 0, bin);
                    }
                    else
                    {
                        log.WriteEntry(msg.ToString(), EventLogEntryType.Error);
                    }
                }
                catch
                {
                    if (isLocal)
                    {
                        throw;
                    }
                }
                log.Close();
            }
        }
Esempio n. 43
0
        private HttpResponseMessage Core(bool isPost, string outputEncoding = null, string timeout = null)
        {
            if (string.IsNullOrWhiteSpace(outputEncoding))
            {
                outputEncoding = Encoding.UTF8.WebName;
            }

            if (string.IsNullOrWhiteSpace(timeout))
            {
                timeout = TimeSpan.Zero.ToString();
            }

            var result = new HttpResponseMessage();

            var root       = AppDomain.CurrentDomain.BaseDirectory;
            var tempFolder = Path.Combine(root, "Temporary");

            if (!Directory.Exists(tempFolder))
            {
                Directory.CreateDirectory(tempFolder);
            }

            var tempName          = Guid.NewGuid().ToString("N");
            var scriptFile        = Path.Combine(root, tempFolder, tempName + ".js");
            var resultFile        = Path.Combine(root, tempFolder, tempName + ".txt");
            var outputEncodingObj = Encoding.GetEncoding(outputEncoding);
            var timeoutObj        = TimeSpan.Parse(timeout);
            var proxyLog          = true;

            try
            {
                var scriptContent = string.Empty;
                if (Request.GetRouteData().Values.ContainsKey("file"))
                {
                    var file = (Request.GetRouteData().Values["file"] ?? string.Empty).ToString();
                    scriptContent = File.ReadAllText(Path.Combine(root, CasperScripts_FolderName, file));
                }
                else if (isPost)
                {
                    scriptContent = Request.Content.ReadAsStringAsync().Result;
                }
                File.WriteAllText(scriptFile, scriptContent);

                var dict    = Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
                var jsonArg = JsonConvert.SerializeObject(dict);

                var arguments = new List <string>();
                arguments.Add(scriptFile);
                arguments.Add(resultFile);
                arguments.Add(jsonArg);
                arguments.Add(outputEncodingObj.WebName);
                arguments.Add(timeoutObj.ToString());
                arguments.Add(proxyLog.ToString().ToLower());

                var executableName = typeof(Executable.Program).Assembly.ManifestModule.Name;
                var executableFile = Path.Combine(root, executableName);

                using (var p = new Process())
                {
                    p.StartInfo.FileName               = executableFile;
                    p.StartInfo.Arguments              = string.Join(" ", arguments.Select(x => "\"" + HttpUtility.UrlEncode(x) + "\""));
                    p.StartInfo.CreateNoWindow         = true;
                    p.StartInfo.UseShellExecute        = false;
                    p.StartInfo.RedirectStandardError  = true;
                    p.StartInfo.RedirectStandardInput  = true;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.Start();
                    p.BeginOutputReadLine();
                    p.BeginErrorReadLine();
                    p.WaitForExit();
                    p.Close();
                }

                var scrapeResult = File.ReadAllText(resultFile);

                result.StatusCode = HttpStatusCode.OK;
                result.Content    = new StringContent(scrapeResult);
                result.Content.Headers.ContentType = new MediaTypeHeaderValue(MediaTypeNames.Text.Plain);
            }
            catch (Exception ex)
            {
                var type   = typeof(CasperjsController);
                var source = type.Namespace + "." + type.Name;
                EventLog.WriteEntry(source, ex.ToString());
                LogFactory.GetLogger().Error(source, ex);

                result.StatusCode = HttpStatusCode.InternalServerError;
                result.Content    = new StringContent(ex.ToString());
                result.Content.Headers.ContentType = new MediaTypeHeaderValue(MediaTypeNames.Text.Plain);
            }
            finally
            {
                if (File.Exists(scriptFile))
                {
                    File.Delete(scriptFile);
                }

                if (File.Exists(resultFile))
                {
                    File.Delete(resultFile);
                }
            }

            return(result);
        }
Esempio n. 44
0
 public void WriteEntry(string input, EventLogEntryType entryType)
 {
     //grava o texto na fonte de logs com o nome que      definimos para a constante SOURCE.
     EventLog.WriteEntry(SOURCE, input, entryType);
 }
Esempio n. 45
0
 public EventLogger(EventLog e)
 {
     this.Log = e;
 }
Esempio n. 46
0
        private int SincronizarPagoDGI(DateTime FechaConsulta, int BufferPagos)
        {
            int resultado = 0;

            try
            {
                CultureInfo Cultura = new CultureInfo("es-NI");

                WsTramitesInstitucionLineaClient wcfClient = new WsTramitesInstitucionLineaClient();

                string userws = ConfigurationSettings.AppSettings["wcfTramiteDGIUser"];
                string passws = ConfigurationSettings.AppSettings["wcfTramiteDGIPass"];

                //List<ServivioWinTasaCambio.wsPagoDGI.Pagos> pago = wcfClient.listPagos(FechaConsulta, userws, passws).Take(BufferPagos).ToList();
                List <ServivioWinTasaCambio.wsPagoDGI.Pagos> pago = wcfClient.listPagos(FechaConsulta, userws, passws).ToList();
                foreach (var p in pago)
                {
                    //Insertar si no existe el pago en la base de dato local y si es activo en la DGI
                    if (!ExistePagoLocal(p.nodocumento) && p.activo == true)
                    {
                        try
                        {
                            TasacionEnLineaEntities DATO = new TasacionEnLineaEntities();
                            PagoDocumento           pd   = new PagoDocumento();

                            pd.IdPago          = Guid.NewGuid();
                            pd.NoDocSoporteBco = p.voucher;

                            var IdCotizacionWeb = ObtenerIdCotizacionWeb(p.nodocumento);
                            if (IdCotizacionWeb != Guid.Empty)
                            {
                                pd.IdCotizacionWeb = IdCotizacionWeb;
                            }

                            pd.MontoPago         = p.monto;
                            pd.IndPago           = "1";
                            pd.FechaPago         = p.fechapago;
                            pd.HoraPago          = p.fechapago.ToShortTimeString();
                            pd.IdEstadoPago      = ObtenerCodigoValorDominio("Pago Correcto");
                            pd.SucBco            = "N/D";
                            pd.CajaBanco         = "N/D";
                            pd.PagoConciliado    = false;
                            pd.Identificacion    = p.cedula;
                            pd.Comentario        = "Pago Sincronizado";
                            pd.siglasBanco       = p.banco;
                            pd.NoDocumentoPagado = p.nodocumento;

                            DATO.AddToPagoDocumento(pd);
                            DATO.SaveChanges();

                            resultado++;
                        }
                        catch (Exception Error)
                        {
                            if (!EventLog.SourceExists(OrigenLog))
                            {
                                EventLog.CreateEventSource(OrigenLog, Aplicacion);
                            }
                            EventLog.WriteEntry(OrigenLog, "Error al Guardar en la tabla <TasacionEnLinea.WEB.PagoDocumento>" + Error.Message, EventLogEntryType.Error);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (!EventLog.SourceExists(OrigenLog))
                {
                    EventLog.CreateEventSource(OrigenLog, Aplicacion);
                }
                EventLog.WriteEntry(OrigenLog, "Error al consumir el Servicio: <http://wstramiteslineapruebas.dgi.gob.ni/WsTramitesInstitucionLinea.svc> " + e.Message, EventLogEntryType.Error);
            }

            return(resultado);
        }
        /// <summary>Tests the given settings to verify connectivity to the repository.</summary>
        /// <param name="connection">The connection info</param>
        /// <param name="credentials">The login/password/domain for the provider</param>
        /// <param name="parameters">Any custom parameters</param>
        /// <param name="eventLog">A handle to the Windows Event Log used by Spira</param>
        /// <param name="custom01">Provider-specific parameter</param>
        /// <param name="custom02">Provider-specific parameter</param>
        /// <param name="custom03">Provider-specific parameter</param>
        /// <param name="custom04">Provider-specific parameter</param>
        /// <param name="custom05">Provider-specific parameter</param>
        /// <param name="cacheFolder">The location to the folder where any cached data can be stored</param>
        /// <remarks>True if connection was successful and good. False, or throws exception if failure.</remarks>
        public bool TestConnection(string connection, NetworkCredential credentials, Dictionary <string, string> parameters, EventLog eventLog, string cacheFolder, string custom01, string custom02, string custom03, string custom04, string custom05)
        {
            /*
             * TODO: Replace with a real implementation that is appropriate for the provider
             */

            //Just returns true
            return(true);
        }
Esempio n. 48
0
        //initialisation des listes
        /// <summary>
        /// aucun log dans ce programme, seulement des messages informels
        /// Si pas de fichier detecté   , alors on annule l'import
        /// Si pas de type detecté      , alors on annule l'import
        /// </summary>
        /// <param name="args">arg  0 : type d'import, arg 1 chemin vers le fichier d'import
        /// il n'y a pas d'obligation a envoyer le chemin car ce dernier peut etre fourni par l'application almacam
        /// </param>
        static void Main(string[] args)
        {
            IContext _clipper_Context = null;

            string TypeImport = "";
            //string fulpathname = "";
            string DbName = AF_JOHN_DEERE.Alma_RegitryInfos.GetLastDataBase();

            AF_JOHN_DEERE.Alma_Log.Create_Log();



            using (EventLog eventLog = new EventLog("Application"))
            {
                ModelsRepository clipper_modelsRepository = new ModelsRepository();
                string           csvImportPath            = null;
                _clipper_Context = clipper_modelsRepository.GetModelContext(DbName);  //nom de la base;
                int i = _clipper_Context.ModelsRepository.ModelList.Count();
                JohnDeere_Param.GetlistParam(_clipper_Context);
                if (args.Length == 0)
                {
                    /* dans ce cas on recupere les arguments de la base directement*/
                    /* on force l'import of*/
                    TypeImport = "OF";
                    /**/
                }
                else  //sinon on recupere le paramètre du type d'import
                {
                    TypeImport = args[0].ToUpper().ToString();
                }


                {
                    switch (TypeImport)
                    {
                    //fullpath name
                    case "STOCK":
                        //import stock


                        break;

                    case "STOCK_PURGE":
                        //puge de tous les elements du stock


                        break;

                    case "OF":

                        clipper_modelsRepository = new ModelsRepository();
                        //import of


                        if (args.Length == 0 || args.Length == 1)
                        {
                            csvImportPath = JohnDeere_Param.GetPath("IMPORT_CDA");
                        }
                        else
                        {
                            csvImportPath = args[1].ToUpper().ToString();
                        }

                        string of_dataModelstring = JohnDeere_Param.GetModelCA();


                        using (JohnDeere_OF CahierAffaire = new JohnDeere_OF())
                        {
                            CahierAffaire.Import(_clipper_Context, csvImportPath, of_dataModelstring);
                        }



                        break;
                    }
                }
            }
        }
Esempio n. 49
0
 /// <summary>
 /// Monitor EventLog writes to specific eventlog source/ID
 /// </summary>
 public EventLogListener(string eventLogName, params long[] instanceIDs)
 {
     _instanceIDs            = instanceIDs;
     _eventLog               = new EventLog(eventLogName);
     _eventLog.EntryWritten += eventLog_EntryWritten;
 }
Esempio n. 50
0
 public PowershellExecuter(CommandLineOptions opts)
 {
     this.opts = opts;
     EventLog.WriteEntry("preshutdownnotify", $"opt: {JsonSerializer.Serialize(opts)}", EventLogEntryType.Information, 12100, short.MaxValue);
 }
        /// <summary>
        /// Initializes the provider - connects, authenticates and returns a session token
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="credentials"></param>
        /// <param name="parameters"></param>
        /// <returns>
        /// A provider-specific object that is passed on subsequent calls. Since this is a dummy provider, we'll
        /// just pass back the connection and credentials
        /// </returns>
        /// <param name="eventLog">Handle to an event log object</param>
        /// <param name="custom01">Custom parameters that are provider-specific</param>
        /// <param name="custom02">Custom parameters that are provider-specific</param>
        /// <param name="custom03">Custom parameters that are provider-specific</param>
        /// <param name="custom04">Custom parameters that are provider-specific</param>
        /// <param name="custom05">Custom parameters that are provider-specific</param>
        /// <remarks>Throws an exception if unable to connect or authenticate</remarks>
        public object Initialize(string connection, NetworkCredential credentials, Dictionary <string, string> parameters, EventLog eventLog, string cacheFolder, string custom01, string custom02, string custom03, string custom04, string custom05)
        {
            /*
             * TODO: Replace with real logic for checking the connection information and the username/password
             */

            if (credentials.UserName != "fredbloggs" && credentials.UserName != "joesmith")
            {
                //Need to thow an exception of this type so that SpiraPlan knows to display the appropriate message to the user
                throw new VersionControlAuthenticationException("Unable to login to version control provider");
            }
            if (connection.Length < 7 || connection.Substring(0, 7) != "test://")
            {
                throw new VersionControlGeneralException("Unable to access version control provider with provided connection information");
            }
            applicationEventLog = eventLog;

            //Create and return the token
            AuthenticationToken token = new AuthenticationToken();

            token.Connection = connection;
            token.UserName   = credentials.UserName;
            token.Password   = credentials.Password;

            return(token);
        }
Esempio n. 52
0
 public void setLogger(EventLog eventLog)
 {
     this.eventLog1 = eventLog;
 }
    public static void Main()
    {
        try
        {
            EventLog myEventLog;
            string   mySource  = null;
            string   myLog     = null;
            string   myType    = null;
            string   myMessage = "A new event is created.";
            string   myEventID = null;
            int      myIntLog  = 0;
            int      myID      = 0;
            Console.Write("Enter source name for new event (eg: Print ): ");
            mySource = Console.ReadLine();
            Console.Write("Enter log name in which to write an event( eg: System ): ");
            myLog = Console.ReadLine();
            // Check whether source exist in event log.
            if (false == EventLog.SourceExists(mySource))
            {
                // Create a new source in a specified log on a system.
                // An event log source should not be created and immediately used.
                // There is a latency time to enable the source, it should be created
                // prior to executing the application that uses the source.
                // Execute this sample a second time to use the new source.
                EventLog.CreateEventSource(mySource, myLog);
                Console.WriteLine("Creating the event source, press the Enter key to exit the application, \n" +
                                  "then run the applicaton again to use the new event source.");
                Console.Read();
            }
            Console.WriteLine("");
            Console.WriteLine("     Select type of event to write:");
            Console.WriteLine("       1.     Error ");
            Console.WriteLine("       2.     Warning");
            Console.WriteLine("       3.     Information");
            Console.WriteLine("       4.     FailureAudit");
            Console.WriteLine("       5.     SuccessAudit");
            Console.Write("Enter the choice(eg. 1): ");
            myType   = Console.ReadLine();
            myIntLog = Convert.ToInt32(myType);
            Console.Write("Enter ID with which to write an event( eg: 0-65535 ): ");
            myEventID = Console.ReadLine();
            myID      = Convert.ToInt32(myEventID);
            // <Snippet2>

            // Create an event log instance.
            myEventLog = new EventLog(myLog);
            // Initialize source property of obtained instance.
            myEventLog.Source = mySource;
            switch (myIntLog)
            {
            case 1:
                // Write an 'Error' entry in specified log of event log.
                myEventLog.WriteEntry(myMessage, EventLogEntryType.Error, myID);
                break;

            case 2:
                // Write a 'Warning' entry in specified log of event log.
                myEventLog.WriteEntry(myMessage, EventLogEntryType.Warning, myID);
                break;

            case 3:
                // Write an 'Information' entry in specified log of event log.
                myEventLog.WriteEntry(myMessage, EventLogEntryType.Information, myID);
                break;

            case 4:
                // Write a 'FailureAudit' entry in specified log of event log.
                myEventLog.WriteEntry(myMessage, EventLogEntryType.FailureAudit, myID);
                break;

            case 5:
                // Write a 'SuccessAudit' entry in specified log of event log.
                myEventLog.WriteEntry(myMessage, EventLogEntryType.SuccessAudit, myID);
                break;

            default:
                Console.WriteLine("Error: Failed to create an event in event log.");
                break;
            }
            Console.WriteLine("A new event in log '{0}' with ID '{1}' "
                              + "is successfully written into event log.",
                              myEventLog.Log, myID);
            // </Snippet2>
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: {0}", e.Message);
        }
    }
 public async Task DataChangedAsync(MusicRecordingDTO work, EventLog <DataChangedEvent> dataEventLog)
 {
     await UpsertAsync(work);
 }
Esempio n. 55
0
 //*********************************************************************
 ///
 ///  <summary>
 ///  Constructor
 ///  </summary>
 ///  <param name="eLog"></param>
 ///
 //*********************************************************************
 public AzureRefreshService(EventLog eLog)
 {
     InitVals(eLog, null);
 }
Esempio n. 56
0
        //*********************************************************************
        ///
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="eLog"></param>
        /// <param name="cmpDbConnectionString"></param>
        ///
        //*********************************************************************

        public AzureRefreshService(EventLog eLog, string cmpDbConnectionString)
        {
            InitVals(eLog, cmpDbConnectionString);
        }
Esempio n. 57
0
        private Task WriteEvent(string message)
        {
            EventLog.WriteEntry(CreateEventSource.SourceName, message, EventLogEntryType.Error);

            return(Task.FromResult(0));
        }
Esempio n. 58
0
        private static async Task ExecuteAsync(string path)
        {
            if (Path.IsPathFullyQualified(path))
            {
                EventLog.WriteEntry("preshutdownnotify", $"opt.Path: {path}", EventLogEntryType.Information, 12101, short.MaxValue);
            }
            else
            {
                EventLog.WriteEntry("preshutdownnotify", $"AppContext: {AppContext.BaseDirectory}", EventLogEntryType.Information, 12102, short.MaxValue);
                path = Path.Combine(AppContext.BaseDirectory, path);
            }

            EventLog.WriteEntry("preshutdownnotify", $"Final Path: {path}", EventLogEntryType.Information, 12103, short.MaxValue);

            var initialState = InitialSessionState.CreateDefault();

            initialState.ImportPSModule(new string[] { "Hyper-V" });
            initialState.ThrowOnRunspaceOpenError = true;
            using Runspace runspace = RunspaceFactory.CreateRunspace(initialState);
            runspace.Open();

            var moduleErrors = runspace.SessionStateProxy.PSVariable.GetValue("Error") as ArrayList;

            if (moduleErrors.Count > 0)
            {
                foreach (var moduleError in moduleErrors)
                {
                    EventLog.WriteEntry("preshutdownnotify", $"Module error: {moduleError}", EventLogEntryType.Error, 12104, short.MaxValue);
                }
            }


            using var ps = PowerShell.Create();
            ps.Runspace  = runspace;

            var scriptContents = File.ReadAllText(path);

            // specify the script code to run.
            ps.AddScript(scriptContents);
            // ps.Streams.Error.ReadAll

            // specify the parameters to pass into the script.
            // ps.AddParameters(scriptParameters);

            // execute the script and await the result.
            ps.Streams.Error.DataAdded += (sender, args) =>
            {
                ErrorRecord err = ((PSDataCollection <ErrorRecord>)sender)[args.Index];
                EventLog.WriteEntry("preshutdownnotify", $"ERROR: {err}", EventLogEntryType.Error, 12105, short.MaxValue);
            };

            ps.Streams.Warning.DataAdded += (sender, args) =>
            {
                WarningRecord warning = ((PSDataCollection <WarningRecord>)sender)[args.Index];
                EventLog.WriteEntry("preshutdownnotify", $"WARNING: {warning}", EventLogEntryType.Information, 12106, short.MaxValue);
            };
            var pipelineObjects = await ps.InvokeAsync().ConfigureAwait(false);

            pipelineObjects.DataAdded += (sender, args) =>
            {
                PSObject output = ((PSDataCollection <PSObject>)sender)[args.Index];
                EventLog.WriteEntry("preshutdownnotify", $"OUTPUT: {output}", EventLogEntryType.Information, 12107, short.MaxValue);
            };


            // print the resulting pipeline objects to the console.
            foreach (var item in pipelineObjects)
            {
                EventLog.WriteEntry("preshutdownnotify", item.BaseObject.ToString(), EventLogEntryType.Information, 12108, short.MaxValue);
            }
            if (ps.Streams.Error.Count > 0)
            {
                EventLog.WriteEntry("preshutdownnotify", $"Error Count: {ps.Streams.Error.Count}", EventLogEntryType.Information, 12109, short.MaxValue);
                foreach (var error in ps.Streams.Error.ReadAll())
                {
                    EventLog.WriteEntry("preshutdownnotify", $"Error Message: {error.Exception.Message ?? error.ErrorDetails.Message}", EventLogEntryType.Information, 12110, short.MaxValue);
                }
                // error records were written to the error stream.
                // Do something with the error
            }
            EventLog.WriteEntry("preshutdownnotify", "Completed!!!", EventLogEntryType.Information, 12111, short.MaxValue);
        }
Esempio n. 59
0
File: test.cs Progetto: mono/gert
	void TestA ()
	{
		if (!EventLog.Exists ("monologtemp", "."))
			EventLog.CreateEventSource ("monotempsource", "monologtemp");
		if (!EventLog.Exists ("monologother", "."))
			EventLog.CreateEventSource ("monoothersource", "monologother");

		EventLog otherEventLogA = new EventLog ("monologother", ".", "monoothersource");

		EventLog otherEventLogB = new EventLog ("monologother", ".", "monoothersource");
		otherEventLogB.EntryWritten += new EntryWrittenEventHandler (EventLog_EntryWritten);

		EventLog tempEventLog = new EventLog ("monologtemp", ".", "monotempsource");
		tempEventLog.EnableRaisingEvents = true;
		tempEventLog.EntryWritten += new EntryWrittenEventHandler (EventLog_EntryWritten);

		otherEventLogA.WriteEntry ("message1", EventLogEntryType.Warning,
			111, 1, new byte [] { 1, 8 });

		Thread.Sleep (10000);

		Assert.AreEqual (0, _entriesWritten.Count, "#A1");

		otherEventLogB.EnableRaisingEvents = true;
		otherEventLogA.WriteEntry ("message2", EventLogEntryType.Warning,
			222, 2, new byte [] { 2, 8 });
		otherEventLogA.WriteEntry ("message3", EventLogEntryType.Warning,
			333, 3, new byte [] { 3, 8 });
		otherEventLogA.WriteEntry ("message4", EventLogEntryType.Warning,
			444, 4, new byte [] { 4, 8 });

		Thread.Sleep (10000);

		Assert.AreEqual (3, _entriesWritten.Count, "#A2");

		EventLogEntry entry = (EventLogEntry) _entriesWritten [0];
		Assert.AreEqual ((short) 2, entry.CategoryNumber, "#A3");
		Assert.AreEqual (222, entry.EventID, "#A4");
		Assert.AreEqual ("message2", entry.Message, "#A5");
		Assert.AreEqual ("monoothersource", entry.Source, "#A6");

		entry = (EventLogEntry) _entriesWritten [1];
		Assert.AreEqual ((short) 3, entry.CategoryNumber, "#A7");
		Assert.AreEqual (333, entry.EventID, "#A8");
		Assert.AreEqual ("message3", entry.Message, "#A9");
		Assert.AreEqual ("monoothersource", entry.Source, "#A10");

		entry = (EventLogEntry) _entriesWritten [2];
		Assert.AreEqual ((short) 4, entry.CategoryNumber, "#A11");
		Assert.AreEqual (444, entry.EventID, "#A12");
		Assert.AreEqual ("message4", entry.Message, "#A13");
		Assert.AreEqual ("monoothersource", entry.Source, "#A14");

		otherEventLogB.Dispose ();

		Thread.Sleep (2000);

		otherEventLogB = new EventLog ("monologother", ".", "monoothersource");
		otherEventLogB.EntryWritten += new EntryWrittenEventHandler (EventLog_EntryWritten);
		otherEventLogB.EnableRaisingEvents = true;

		otherEventLogA.WriteEntry ("message5", EventLogEntryType.Warning,
			555, 5, new byte [] { 5, 8 });

		Thread.Sleep (10000);

		Assert.AreEqual (4, _entriesWritten.Count, "#A15");

		entry = (EventLogEntry) _entriesWritten [3];
		Assert.AreEqual ((short) 5, entry.CategoryNumber, "#A16");
		Assert.AreEqual (555, entry.EventID, "#A17");
		Assert.AreEqual ("message5", entry.Message, "#A18");
		Assert.AreEqual ("monoothersource", entry.Source, "#A19");

		tempEventLog.Dispose ();
		otherEventLogA.Dispose ();
		otherEventLogB.Dispose ();

		Thread.Sleep (2000);
	}
Esempio n. 60
0
        protected void InvokeScript(string eventName, SPItemEventProperties properties)
        {
            using (SPSite site = new SPSite(properties.SiteId))
            {
                using (SPWeb web = site.OpenWeb(properties.RelativeWebUrl))
                {
                    SPList list = web.Lists[properties.ListId];
                    SPItem item = properties.ListItem;

                    SPFeature feature = web.Features[PowerEventReceiversConstants.FeatureId];

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        Runspace runspace = RunspaceFactory.CreateRunspace();

                        runspace.Open();

                        runspace.SessionStateProxy.SetVariable("httpContext", httpContext);
                        runspace.SessionStateProxy.SetVariable("spContext", spContext);
                        runspace.SessionStateProxy.SetVariable("this", this);
                        runspace.SessionStateProxy.SetVariable("properties",
                                                               properties);
                        runspace.SessionStateProxy.SetVariable("site", site);
                        runspace.SessionStateProxy.SetVariable("web", web);
                        runspace.SessionStateProxy.SetVariable("list", list);
                        runspace.SessionStateProxy.SetVariable("item", item);
                        runspace.SessionStateProxy.SetVariable("user",
                                                               web.SiteUsers.
                                                               GetByID(
                                                                   properties
                                                                   .
                                                                   CurrentUserId));

                        string script =
                            feature.Properties[
                                PowerEventReceiversConstants.
                                PowerItemEventReceiverPropNamePrefixScript +
                                list.RootFolder.Url].Value;

                        try
                        {
                            Pipeline pipe =
                                runspace.CreatePipeline(
                                    PowerEventReceiversConstants.
                                    PowerEventReceiversPredefinedFunctions);
                            pipe.Invoke();

                            pipe = runspace.CreatePipeline(script);
                            pipe.Invoke();

                            //check if the event's function is defined
                            List <string> functions =
                                PowerEventReceiversHelper.GetFunctions(runspace);
                            if (functions.Contains(eventName.ToLower()) ==
                                false)
                            {
                                return;
                            }

                            //invoke the event's function
                            pipe = runspace.CreatePipeline(eventName);
                            pipe.Invoke();
                            object objProperties =
                                runspace.SessionStateProxy.GetVariable(
                                    "properties");
                            if (objProperties != null)
                            {
                                if (objProperties is PSObject)
                                {
                                    properties =
                                        (SPItemEventProperties)
                                        ((PSObject)objProperties).BaseObject;
                                }
                                else
                                {
                                    properties =
                                        (SPItemEventProperties)objProperties;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                EventLog.WriteEntry(this.GetType().FullName,
                                                    ex.Message + "\n" +
                                                    ex.StackTrace,
                                                    EventLogEntryType.Error);
                            }
                            catch
                            {
                            }

                            properties.Cancel       = true;
                            properties.ErrorMessage = ex.Message;
                        }
                        finally
                        {
                            if (runspace != null &&
                                runspace.RunspaceStateInfo.State !=
                                RunspaceState.Closed)
                            {
                                runspace.Close();
                                runspace = null;
                            }
                        }
                    });
                }
            }
        }