Пример #1
0
        public string RequstJson(string apiUrl, string tokenType, string accessToken)
        {
            var            json                 = string.Empty;
            HttpWebRequest apiRequest           = (HttpWebRequest)WebRequest.Create(apiUrl);
            const string   timelineHeaderFormat = "{0} {1}";

            apiRequest.Headers.Add("Authorization",
                                   string.Format(timelineHeaderFormat, tokenType,
                                                 accessToken));
            apiRequest.Method = "Get";
            try
            {
                WebResponse timeLineResponse = apiRequest.GetResponse();

                using (timeLineResponse)
                {
                    using (var reader = new StreamReader(timeLineResponse.GetResponseStream()))
                    {
                        json = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException e)
            {
                //Console.Write("Utility.RequstJson : WebException = " + e.Status);
                EventLogWriter logWriter = new EventLogWriter("oAuthTwitterWrapper");
                logWriter.WriteErrorToEventLog("Utility.RequstJson : WebException = " + e.Status);

                json = string.Format("Error: {0}", e.Message);
            }

            return(json);
        }
Пример #2
0
        /// <summary>
        /// Attempts to install/register the executable
        /// with the Service Control Manager (SCM).
        /// </summary>
        static void installService()
        {
            // The installer will barf if the event source
            // is already defined.  So we need to clean
            // up our house.
            EventLogWriter elv = new EventLogWriter();

            if (elv.SourceExists() == true)
            {
                elv.RemoveSource();
            }

            string executable = Assembly.GetExecutingAssembly().Location;

            ManagedInstallerClass.InstallHelper(
                new string[] { executable }
                );

            // We should now have the event source.
            // Let's make sure
            if (elv.SourceExists() != true)
            {
                elv.CreateSource();
            }
        }
Пример #3
0
            private void Run()
            {
                //bool debugging = false;
                //while (!debugging)
                //    Thread.Sleep(100);

                var wtr = new EventLogWriter(ServiceName);

                try
                {
                    wtr.WriteLine("Service initializing...");
                    _ci.Run(_arguments, wtr, wtr, new BlockingReader(_shutdown));
                }
                catch (Exception e)
                {
                    try
                    {
                        wtr.WriteLine(e.ToString());
                    }
                    catch
                    {
                    }
                }
                finally
                {
                    if (_shutdown.WaitOne(0, false) == false)
                    {
                        wtr.WriteLine("The command unexpectedly terminated.");
                        Environment.Exit(1);
                    }
                }
            }
Пример #4
0
 // This function will be called when the app pool has problem
 public void Notify(string message)
 {
     if (writer == null)
     {
         writer = new EventLogWriter();
     }
     writer.Write(message);
 }
Пример #5
0
        public TwitAuthenticateResponse AuthenticateMe(string oAuthConsumerKey, string oAuthConsumerSecret, string oAuthUrl)
        {
            //oAuthConsumerKey = "sLE6zXtRITflCiPIASkg";
            //oAuthConsumerSecret = "CZD1Pl6sRfALb2m4SFViMsbC9Hl8Lz38CGumDwgYwEM";

            EventLogWriter logWriter = new EventLogWriter("oAuthTwitterWrapper");

            TwitAuthenticateResponse twitAuthResponse;
            // Do the Authenticate
            const string authHeaderFormat = "Basic {0}";

            var authHeader = string.Format(authHeaderFormat,
                                           Convert.ToBase64String(
                                               Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" +

                                                                      Uri.EscapeDataString((oAuthConsumerSecret)))

                                               ));
            const string   postBody    = "grant_type=client_credentials";
            HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl);

            authRequest.Headers.Add("Authorization", authHeader);
            authRequest.Method                 = "POST";
            authRequest.ContentType            = "application/x-www-form-urlencoded;charset=UTF-8";
            authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            using (Stream stream = authRequest.GetRequestStream())
            {
                byte[] content = Encoding.ASCII.GetBytes(postBody);
                stream.Write(content, 0, content.Length);
            }
            authRequest.Headers.Add("Accept-Encoding", "gzip");
            try
            {
                WebResponse authResponse = authRequest.GetResponse();
                // deserialize into an object
                using (authResponse)
                {
                    using (var reader = new StreamReader(authResponse.GetResponseStream()))
                    {
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        var objectText          = reader.ReadToEnd();
                        twitAuthResponse = JsonConvert.DeserializeObject <TwitAuthenticateResponse>(objectText);
                    }
                }

                return(twitAuthResponse);
            }
            catch (WebException e)
            {
                logWriter.WriteErrorToEventLog(string.Format("Authenticate.TwitAuthenticateResponse: {0}", e.Message));
            }

            return(new TwitAuthenticateResponse());
        }
Пример #6
0
        public static Page <ApiError> Get(string messageId)
        {
            Page <ApiError> page = new Page <ApiError>()
            {
                Items = new List <ApiError>()
            };

            if (!String.IsNullOrWhiteSpace(messageId))
            {
                Guid   id       = new Guid(messageId);
                string schema   = eXtensibleConfig.Zone.Equals("production", StringComparison.OrdinalIgnoreCase) ? DateTime.Today.ToString("MMM").ToLower() : "log";
                var    settings = ConfigurationProvider.ConnectionStrings[eXtensibleWebApiConfig.SqlConnectionKey];
                if (settings != null && !String.IsNullOrWhiteSpace(settings.ConnectionString))
                {
                    try
                    {
                        List <ApiError> list = new List <ApiError>();
                        using (SqlConnection cn = new SqlConnection(settings.ConnectionString))
                        {
                            cn.Open();
                            using (SqlCommand cmd = cn.CreateCommand())
                            {
                                cmd.CommandType = CommandType.Text;
                                const string MessageIdParamName = "@messageid";
                                string       sql = "select [Id], [CreatedAt], [ApplicationKey], [Zone], [AppContextInstance], [MessageId]," +
                                                   "[Category], [Severity], [Message], [XmlData] from [log].[Error] where [MessageId] = " + MessageIdParamName;
                                cmd.Parameters.AddWithValue(MessageIdParamName, id);
                                cmd.CommandText = sql;

                                using (SqlDataReader reader = cmd.ExecuteReader())
                                {
                                    BorrowReader(reader, list);

                                    if (list.Count > 0)
                                    {
                                        page.Items.Add(list[0]);
                                        page.Total = 1;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        var          message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                        var          props   = eXtensibleConfig.GetProperties();
                        IEventWriter writer  = new EventLogWriter();
                        writer.WriteError(message, SeverityType.Error, "DataAccess", props);
                    }
                }
            }

            return(page);
        }
Пример #7
0
        public static void EventLog_custom_config___Test___Logging_context_error()
        {
            // Arrange
            var config = new EventLogConfig(new Dictionary <LogItemKind, IReadOnlyCollection <string> >(), "MySource", "MyLog", "Laptop", true);
            var logger = new EventLogWriter(config);

            // Act
            logger.Log("Subject".ToLogEntry("Comment").ToLogItem(LogItemOrigin.ItsLogInternalErrors));

            // Assert
            /* Confirm entry - by hand */
        }
Пример #8
0
        public static void EventLog_custom_config___Test___Non_logging_context()
        {
            // Arrange
            var config = new EventLogConfig(new Dictionary <LogItemKind, IReadOnlyCollection <string> >(), "MySourceLawson", "MyLogLawson", "MyMachine", true);
            var logger = new EventLogWriter(config);

            // Act
            logger.Log("Subject".ToLogEntry("Comment").ToLogItem(LogItemOrigin.ItsLogEntryPosted));

            // Assert
            /* Confirm no entry - by hand */
        }
Пример #9
0
        public Diagnostics()
        {
            if (_settings.Trace)
            {
                _traceLogger = new TraceLogger();
            }

            string sourceName = "Ogresoft"; 
            string logName = "Ogresoft";

            _eventLogWriter = new EventLogWriter(sourceName, logName); 
        }
Пример #10
0
 private void ProcessNextWorkDate()
 {
     while (true)
     {
         try
         {
             WorkRule workRule = new WorkRule();
             bool     flag     = false;
             foreach (Work_Plan current in workRule.GetCreateNextPlanDate(this._Work_Host))
             {
                 try
                 {
                     DateTime dateTime = PlanHelper.CreateNextPlanDate(current.PlanConfig, current.LastRunDate);
                     if (dateTime != DateTime.MaxValue)
                     {
                         Work_PlanRun work_PlanRun = new Work_PlanRun();
                         work_PlanRun.WorkInfoID = current.WorkInfoID;
                         work_PlanRun.PlanID     = current.PlanID;
                         work_PlanRun.RunDate    = dateTime;
                         work_PlanRun.IsRun      = false;
                         flag = true;
                         workRule.CurrentEntities.AddTowork_planrun(work_PlanRun);
                     }
                 }
                 catch (Exception ex)
                 {
                     ("循环检查创建" + current.PlanName + "下次执行时间出现异常:" + ex.Message).WriteLineRed("");
                     LogHelper.Write("WorkLog", "循环检创建" + current.PlanName + "下次执行时间出现异常", ex, "");
                 }
             }
             if (flag)
             {
                 "提交下一次计划更新".WriteLineYellow("");
                 workRule.CurrentEntities.SaveChanges();
             }
         }
         catch (Exception ex)
         {
             ("循环检查创建各作业下次执行时间出现异常:" + ex.Message).WriteLineRed("");
             try
             {
                 LogHelper.Write("WorkLog", "循环检查创建各作业下次执行时间出现异常", ex, "");
             }
             catch (Exception exception)
             {
                 EventLogWriter.WriterLog(exception);
             }
         }
         Thread.Sleep(this._NextWorkDateSleep);
     }
 }
Пример #11
0
    private static LogWriter ReadLogWriter(ConfigurationNode node)
    {
        LogWriter logWriter  = null;
        var       attributes = node.Attributes;
        var       type       = attributes["Type"].GetValue <string>();
        var       logLevel   = attributes["LogLevel"].GetValue <LogLevel>();

        switch (type)
        {
        case "ConsoleLogWriter":
            logWriter = new LogWriter(ConsoleLogWriter.Instance, logLevel);
            break;

#if FOUNDATION_4_7
        case "EventLogWriter":
        {
            var logName        = attributes["LogName"].GetValue <string>();
            var machineName    = attributes["MachineName"].GetValue <string>();
            var source         = attributes["Source"].GetValue <string>();
            var eventLogWriter = new EventLogWriter(logName, machineName, source);
            logWriter = new LogWriter(eventLogWriter, logLevel);
        }

        break;
#endif

        case "FileLogWriter":
        {
            var path = attributes["Path"].GetValue <string>();
            path = Environment.ExpandEnvironmentVariables(path);

            attributes.TryGetAttributeValue("Async", true, out var async);
            attributes.TryGetAttributeValue("BufferSize", 1048576, out var bufferSize);     // 1 MB
            attributes.TryGetAttributeValue("TimerPeriod", TimeSpan.FromSeconds(10), out var timerPeriod);
            attributes.TryGetAttributeValue("AutoFlush", true, out var autoFlush);
            attributes.TryGetAttributeValue("FileAttributes", FileAttributes.ReadOnly | FileAttributes.Hidden, out var fileAttributes);
            attributes.TryGetAttributeValue("DateTimeKind", DateTimeKind.Utc, out var dateTimeKind);

            var fileLogWriter = new FileLogWriter(path, Encoding.UTF8, async, bufferSize, timerPeriod, autoFlush, fileAttributes, dateTimeKind);
            logWriter = new LogWriter(fileLogWriter, logLevel);
        }
        break;

        default:
            break;
        }

        return(logWriter);
    }
Пример #12
0
        public static IConfigurationProvider Load()
        {
            IConfigurationProvider provider = null;
            IEventWriter           writer   = new EventLogWriter();

            List <string> list = new List <string>()
            {
                AppDomain.CurrentDomain.BaseDirectory,
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin"),
            };

            if (Directory.Exists(eXtensibleConfig.ConfigurationProviderPlugins))
            {
                list.Add(eXtensibleConfig.ConfigurationProviderPlugins);
            }
            try
            {
                ConfigurationModule module = null;
                ModuleLoader <ConfigurationModule> loader = new ModuleLoader <ConfigurationModule>()
                {
                    Folderpaths = list
                };
                if (loader.Load(out module) && module.Providers != null && module.Providers.Count > 0)
                {
                    provider = module.Providers.Find(x => !x.GetType().Equals(typeof(SystemConfigurationProvider)));
                }
            }
            catch (Exception ex)
            {
                string errorMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                writer.WriteError(errorMessage, SeverityType.Critical, "ConfigurationProvider");
            }

            if (provider == null)
            {
                provider = new SystemConfigurationProvider();
            }

            var    props   = eXtensibleConfig.GetProperties();
            string message = String.Format("{0}: {1} (loaded @ {2}", "Configuration Provider", provider.GetType().FullName, DateTime.Now.ToString("G"));

            writer.WriteError(message, SeverityType.Critical, "configuration", props);

            return(provider);
        }
Пример #13
0
 public ActionResult Connect(SFTPConnectionString sFTPConnectionString)
 {
     if (ModelState.IsValid)
     {
         try
         {
             SFTPClientConnector.SetConnectionInSession(sFTPConnectionString);
             EventLogWriter.SetEvent(LogEvents.Connecting);
             SFTPClientConnector.ConnectToRemote();
             EventLogWriter.SetEvent(LogEvents.Connected);
             return(new HttpStatusCodeResult(HttpStatusCode.OK));
         }
         catch (Exception e)
         {
             return(HttpNotFound(e.Message));
         }
     }
     return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
 }
Пример #14
0
        public static Page <ApiError> Get(string zone, int pageSize, int pageIndex)
        {
            Page <ApiError> page = new Page <ApiError>();

            string schema   = eXtensibleConfig.Zone.Equals("production", StringComparison.OrdinalIgnoreCase) ? DateTime.Today.ToString("MMM").ToLower() : "log";
            var    settings = ConfigurationProvider.ConnectionStrings[eXtensibleWebApiConfig.SqlConnectionKey];

            if (settings != null && !String.IsNullOrWhiteSpace(settings.ConnectionString))
            {
                try
                {
                    using (SqlConnection cn = new SqlConnection(settings.ConnectionString))
                    {
                        cn.Open();
                        using (SqlCommand cmd = cn.CreateCommand())
                        {
                            cmd.CommandType = CommandType.Text;

                            string sql = "select top " + pageSize + " [Id], [CreatedAt], [ApplicationKey], [Zone], [AppContextInstance], [MessageId], " +
                                         "[Category], [Severity], [Message], [XmlData] from [log].[Error]  order by [Id] desc";
                            cmd.CommandText = sql;
                            List <ApiError> list = new List <ApiError>();
                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                BorrowReader(reader, list);
                                page.Items = list;
                                page.Total = list.Count;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    var          message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                    var          props   = eXtensibleConfig.GetProperties();
                    IEventWriter writer  = new EventLogWriter();
                    writer.WriteError(message, SeverityType.Error, "DataAccess", props);
                }
            }

            return(page);
        }
Пример #15
0
        // Dependency Injection example
        static async Task Main(string[] args)
        {
            // Create an object of the concrete class
            EventLogWriter writer = new EventLogWriter();

            // Constructor Injection
            // Pass the object of the concrete class into the constructor of the dependent class.
            AppPoolWatcher watcher = new AppPoolWatcher(writer);
            await watcher.Notify("Sample message to log");

            // By virtue of using Dependency Injection, a new requirement can be extended by adding a new implementation.
            // In this case, adding implementation class EmailSender which is extended from the abstract class (Interface) INotificationAction.
            EmailSender emailSender = new EmailSender();

            watcher = new AppPoolWatcher(emailSender);
            await watcher.Notify("Sample message to email");

            Console.WriteLine("Hello Dependency Injection via Constructor!");
            Console.ReadLine();
        }
Пример #16
0
        private void getDirectoriesAndFiles()
        {
            EventLogWriter.SetEvent(LogEvents.Listing);

            foreach (SftpFile DirOrFile in allDirectoriesAndFiles)
            {
                if (DirOrFile.IsDirectory)
                {
                    if (DirOrFile.Name == ".." || DirOrFile.Name == ".")
                    {
                        continue;
                    }
                    directories.Add(DirOrFile.Name);
                }
                else
                {
                    files.Add(DirOrFile.Name);
                }
            }
        }
Пример #17
0
 public ActionResult CopyLocalToRemote(TransferFile transferFile)
 {
     try
     {
         string filename = Path.GetFileName(transferFile.SourcePath);
         EventLogWriter.SetEvent(LogEvents.StartTransferFile);
         EventLogWriter.SetEvent(LogEvents.TransferingFile);
         SftpClient client     = SFTPClientConnector.ConnectToRemote();
         var        fileStream = new FileStream(transferFile.SourcePath, FileMode.Open);
         client.UploadFile(fileStream, transferFile.DestinationPath + "/" + filename);
         fileStream.Dispose();
         client.Dispose();
         EventLogWriter.SetEvent(LogEvents.TransferCompleted);
         return(new HttpStatusCodeResult(HttpStatusCode.OK));
     }
     catch (Exception e)
     {
         return(HttpNotFound(e.Message));
     }
 }
        private static ApiRequest LocalGet(Guid id)
        {
            ApiRequest item = null;

            string sql      = "";
            var    settings = ConfigurationProvider.ConnectionStrings[eXtensibleWebApiConfig.SqlConnectionKey];

            if (settings != null && !String.IsNullOrWhiteSpace(settings.ConnectionString))
            {
                try
                {
                    using (SqlConnection cn = new SqlConnection(settings.ConnectionString))
                    {
                        cn.Open();
                        using (SqlCommand cmd = cn.CreateCommand())
                        {
                            cmd.CommandType    = CommandType.Text;
                            cmd.CommandText    = sql;
                            cmd.CommandTimeout = 0;

                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    var          message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                    var          props   = eXtensibleConfig.GetProperties();
                    IEventWriter writer  = new EventLogWriter();
                    writer.WriteError(message, SeverityType.Critical, "ApiRequest", props);
                }
            }

            return(item);
        }
Пример #19
0
                        public IAsyncResult BeginInvoke(Delegate method, object[] args)
                            {
                                lock (_LockObject)
                                    {
                                        if ((_Thread.ThreadState & ThreadState.Unstarted) != 0)
                                            {
                                                _Thread.Start();
                                                _Initialized.WaitOne();
                                            }
                                    }

                                try
                                    {
                                        return _Form.BeginInvoke(method, args);
                                    }
                                catch (InvalidOperationException e)
                                    {
                                        EventLogWriter.WriteEntry($"BeginInvoke 724 :Method: {method} Args[0]: {args[0]} - {e.Message} : {e.StackTrace}",
                                            EventLogEntryType.Error);
                    if (!_Form.IsHandleCreated)
                                            throw new ObjectDisposedException(GetType().ToString(), e);
                                        throw;
                                    }
                            }
Пример #20
0
        private void DefaultLogWriter(IList <LogItem> logItems)
        {
            try
            {
                //EventLogWriter.Log("Entering try block", EventLogEntryType.Information, 103);
                if (File.Exists(Location))
                {
                    var info = new FileInfo(Location);
                    //EventLogWriter.Log("File exists, file size is:" + info.Length, EventLogEntryType.Information, 104);
                    if (info.Length >= MaxFileSize)
                    {
                        //EventLogWriter.Log("File size is greater than max", EventLogEntryType.Information, 105);
                        //File.SetLastWriteTime(Location, DateTime.Now);
                        //var move = DateTime.Now;
                        ////EventLogWriter.Log("Attempting to move to: " + Location, EventLogEntryType.Information, 106);
                        //var loc = Location + "." + move.ToString("yyyy-dd-MM_HH-mm-ss_fffffff");
                        //info.MoveTo(loc);


                        var loc = Location + ".";
                        if (File.Exists(loc + "1"))
                        {
                            File.Delete(loc + "1");
                        }
                        info.MoveTo(loc + "1");

                        if (System.IO.File.Exists(loc + "1"))
                        {
                            int zipCount = 1;
                            while (System.IO.File.Exists(loc + zipCount + ".zip"))
                            {
                                zipCount++;
                            }

                            if (zipCount > MaxLogCount)
                            {
                                System.IO.File.Delete(loc + MaxLogCount + ".zip");
                                zipCount--;
                            }

                            if (zipCount > 1)
                            {
                                for (int i = zipCount; i > 1; i--)
                                {
                                    if (System.IO.File.Exists(loc + (i - 1) + ".zip") && !System.IO.File.Exists(loc + (i) + ".zip"))
                                    {
                                        System.IO.File.Move(loc + (i - 1) + ".zip", loc + (i) + ".zip");
                                    }
                                }
                            }

                            string fileName = Location.Substring(Location.LastIndexOf('\\') + 1);
                            CreateZip.CreateZipFile(Location + ".1", fileName);
                            System.IO.File.Delete(Location + ".1");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                EventLogWriter.Log(string.Format("Exception occurred in FileLoggerAppender -> DefaultLogWriter, {2}Message: {2}{0}{2}StackTrace: {2}{1}{2}Source: {2}{3}", e.Message, e.StackTrace, Environment.NewLine, e.Source), EventLogEntryType.Error, 4);
            }



            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(Location)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(Location));
                }
                using (var fs = new FileStream(Location, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, 1024 * 1024, FileOptions.WriteThrough))
                {
                    using (var fw = new StreamWriter(fs, new UTF8Encoding(), 1024 * 1024, true))
                        // ReSharper disable ForCanBeConvertedToForeach Reason: Optimization
                        for (var i = 0; i < logItems.Count; i++)
                        // ReSharper restore ForCanBeConvertedToForeach
                        {
                            var toWrite = string.Format("{0}", Logger.FormatLog(DefaultLogPattern, logItems[i], _formatting));
                            fw.WriteLine(toWrite);
                        }
                    fs.Flush(true);
                }
            }
            catch (IOException e)
            {
                if (!IsFileLocked(e))
                {
                    EventLogWriter.Log(string.Format("IOException occurred in FileLoggerAppender -> DefaultLogWriter, {2}Message: {2}{0}{2}StackTrace: {2}{1}{2}Source: {2}{3}", e.Message, e.StackTrace, Environment.NewLine, e.Source), EventLogEntryType.Error, 3);
                    return;
                }
                Thread.Sleep(2000);
                DefaultLogWriter(logItems);
            }
            catch (ArgumentNullException e)
            {
                EventLogWriter.Log(string.Format("ArgumentNullException occurred in FileLoggerAppender -> DefaultLogWriter, {2}Message: {2}{0}{2}StackTrace: {2}{1}{2}Source: {2}{3}", e.Message, e.StackTrace, Environment.NewLine, e.Source), EventLogEntryType.Error, 1);
                // Sometimes a 'file not found' exception is thrown, not sure why
            }
            catch (Exception e)
            {
                EventLogWriter.Log(string.Format("Exception occurred in FileLoggerAppender -> DefaultLogWriter, {2}Message: {2}{0}{2}StackTrace: {2}{1}{2}Source: {2}{3}", e.Message, e.StackTrace, Environment.NewLine, e.Source), EventLogEntryType.Error, 2);
            }
        }
        private static void LocalPost(ApiRequest model)
        {
            string schema = GetSchema();
            string sql    = "insert into [" + schema + "].[ApiRequest] ( [AppKey],[AppZone],[AppInstance],[Elapsed],[Start],[Protocol],[Host],[Path]" +
                            ",[ClientIP],[UserAgent],[HttpMethod],[ControllerName],[ControllerMethod],[MethodReturnType],[ResponseCode],[ResponseText]" +
                            ",[XmlData],[MessageId],[BasicToken],[BearerToken],[AuthSchema],[AuthValue],[MessageBody],[HasLog] ) values (" + AppKeyParamName + "," + AppZoneParamName + "," +
                            AppInstanceParamName + "," + ElapsedParamName + "," + StartParamName + "," + ProtocolParamName + "," + HostParamName + "," +
                            PathParamName + "," + ClientIPParamName + "," + UserAgentParamName + "," + HttpMethodParamName + "," + ControllerNameParamName + "," +
                            ControllerMethodParamName + "," + MethodReturnTypeParamName + "," + ResponseCodeParamName + "," + ResponseTextParamName + "," +
                            XmlDataParamName + "," + MessageIdParamName + "," + BasicTokenParamName + "," + BearerTokenParamName + "," + AuthSchemaParamName +
                            "," + AuthValueParamName + "," + MessageBodyParamName + "," + ErrorLogParamName + ")";


            var settings = ConfigurationProvider.ConnectionStrings[eXtensibleWebApiConfig.SqlConnectionKey];

            if (settings != null && !String.IsNullOrWhiteSpace(settings.ConnectionString))
            {
                try
                {
                    using (SqlConnection cn = new SqlConnection(settings.ConnectionString))
                    {
                        cn.Open();
                        using (SqlCommand cmd = cn.CreateCommand())
                        {
                            cmd.CommandType    = CommandType.Text;
                            cmd.CommandText    = sql;
                            cmd.CommandTimeout = 0;

                            cmd.Parameters.AddWithValue(AppKeyParamName, model.AppKey.Truncate(25));
                            cmd.Parameters.AddWithValue(AppZoneParamName, model.AppZone.Truncate(15));
                            cmd.Parameters.AddWithValue(AppInstanceParamName, model.AppInstance.Truncate(25));
                            cmd.Parameters.AddWithValue(ElapsedParamName, model.Elapsed);
                            cmd.Parameters.AddWithValue(StartParamName, model.Start);
                            cmd.Parameters.AddWithValue(ProtocolParamName, model.Protocol.Truncate(5));
                            cmd.Parameters.AddWithValue(HostParamName, model.Host.Truncate(50));
                            cmd.Parameters.AddWithValue(PathParamName, model.Path.Truncate(150));
                            cmd.Parameters.AddWithValue(ClientIPParamName, model.ClientIP);
                            cmd.Parameters.AddWithValue(UserAgentParamName, String.IsNullOrWhiteSpace(model.UserAgent) ? "none" : model.UserAgent.Truncate(200));
                            cmd.Parameters.AddWithValue(HttpMethodParamName, model.HttpMethod.Truncate(10));
                            cmd.Parameters.AddWithValue(ControllerNameParamName, String.IsNullOrWhiteSpace(model.ControllerName) ? "none" : model.ControllerName.Truncate(50));
                            cmd.Parameters.AddWithValue(ControllerMethodParamName, String.IsNullOrWhiteSpace(model.ControllerMethod) ? "none" : model.ControllerMethod.Truncate(50));
                            cmd.Parameters.AddWithValue(MethodReturnTypeParamName, String.IsNullOrWhiteSpace(model.MethodReturnType) ? "none" : model.MethodReturnType.Truncate(50));
                            cmd.Parameters.AddWithValue(ResponseCodeParamName, model.ResponseCode.Truncate(3));
                            cmd.Parameters.AddWithValue(ResponseTextParamName, model.ResponseText.Truncate(100));
                            cmd.Parameters.AddWithValue(XmlDataParamName, model.ToXmlString());
                            cmd.Parameters.AddWithValue(MessageIdParamName, model.MessageId);
                            cmd.Parameters.AddWithValue(BasicTokenParamName, String.IsNullOrWhiteSpace(model.BasicToken) ? "none" : model.BasicToken.Truncate(50));
                            cmd.Parameters.AddWithValue(BearerTokenParamName, String.IsNullOrWhiteSpace(model.BearerToken) ? "none" : model.BearerToken.Truncate(50));
                            cmd.Parameters.AddWithValue(AuthSchemaParamName, model.AuthSchema.Truncate(10));
                            cmd.Parameters.AddWithValue(AuthValueParamName, model.AuthValue.Truncate(50));
                            cmd.Parameters.AddWithValue(MessageBodyParamName, !String.IsNullOrWhiteSpace(model.MessageBody) ? (object)model.MessageBody : DBNull.Value);
                            cmd.Parameters.AddWithValue(ErrorLogParamName, model.HasErrorLog);

                            cmd.ExecuteNonQuery();
                        }
                    }
                }
                catch (Exception ex)
                {
                    var          message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                    var          props   = eXtensibleConfig.GetProperties();
                    IEventWriter writer  = new EventLogWriter();
                    writer.WriteError(message, SeverityType.Critical, "ApiRequest", props);
                }
            }
            else
            {
                var          message = "settings != null && !String.IsNullOrWhiteSpace(settings.ConnectionString) = FALSE";
                var          props   = eXtensibleConfig.GetProperties();
                IEventWriter writer  = new EventLogWriter();
                writer.WriteError(message, SeverityType.Critical, "ApiRequestProvider", props);
            }
        }
        private static IEnumerable <ApiRequest> LocalGet(int id)
        {
            List <ApiRequest> list   = new List <ApiRequest>();
            string            schema = GetSchema();
            var settings             = ConfigurationProvider.ConnectionStrings[eXtensibleWebApiConfig.SqlConnectionKey];

            if (settings != null && !String.IsNullOrWhiteSpace(settings.ConnectionString))
            {
                try
                {
                    using (SqlConnection cn = new SqlConnection(settings.ConnectionString))
                    {
                        cn.Open();
                        using (SqlCommand cmd = cn.CreateCommand())
                        {
                            string        sql = " [ApiRequestId],[XmlData] from [" + schema + "].[ApiRequest] ";
                            StringBuilder sb  = new StringBuilder();
                            sb.Append("select ");
                            if (id > 999)
                            {
                                sb.Append(sql);
                                sb.Append(" where [ApiRequestId] = " + ApiRequestIdParamName);
                                cmd.Parameters.AddWithValue(ApiRequestIdParamName, id);
                            }
                            else
                            {
                                sb.Append("top " + id.ToString() + " ");
                                sb.Append(sql);
                                sb.Append(" order by [ApiRequestId] desc");
                            }



                            cmd.CommandType    = CommandType.Text;
                            cmd.CommandText    = sb.ToString();
                            cmd.CommandTimeout = 0;



                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    string xml        = reader.GetString(reader.GetOrdinal("XmlData"));
                                    var    apiRequest = StringToRequest(xml);
                                    apiRequest.ApiRequestId = reader.GetInt64(reader.GetOrdinal("ApiRequestId"));
                                    list.Add(apiRequest);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    var          message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                    var          props   = eXtensibleConfig.GetProperties();
                    IEventWriter writer  = new EventLogWriter();
                    writer.WriteError(message, SeverityType.Critical, "ApiRequest", props);
                }
            }
            return(list);
        }
Пример #23
0
        protected override void ExecuteInternal(HttpContext context, IAuthenticationManager authManager)
        {
            if (!(this.logger?.LogWriter is MultiLogWriter))
            {
                this.logger?.Log(EventType.OperationError, "Unable to attach EventLogWriter (Passed logwriter is no MultiLogWriter).");

                throw new InternalServerErrorException();
            }

            this.logger?.Log(EventType.OperationInformation, "Parse filter (if exist).");

            List <Func <Log, bool> > filters = new List <Func <Log, bool> >()
            {
                (log) => (log is OperationLog) == false || !string.Equals((log as OperationLog).OperationName, this.Name)
            };

            var parameters = System.Web.HttpUtility.ParseQueryString(System.Web.HttpUtility.UrlDecode(context.Request.Url.Query));

            foreach (string parameter in parameters)
            {
                this.logger?.Log(EventType.OperationInformation, "Found filter for '{0}': '{1}'", parameter, parameters[parameter]);

                // skip empty filters
                if (string.IsNullOrEmpty(parameters[parameter]))
                {
                    continue;
                }

                switch (parameter)
                {
                case StreamLogsOperation.InputParameterClient:
                    filters.Add((log) =>
                    {
                        return(log is OperationLog && Regex.IsMatch((log as OperationLog).ClientIp, parameters[parameter], RegexOptions.IgnoreCase));
                    });
                    break;

                case StreamLogsOperation.InputParameterPort:
                    filters.Add((log) =>
                    {
                        return(log is OperationLog && Regex.IsMatch((log as OperationLog).LocalPort, parameters[parameter], RegexOptions.IgnoreCase));
                    });
                    break;

                case StreamLogsOperation.InputParameterOperation:
                    filters.Add((log) =>
                    {
                        return(log is OperationLog && Regex.IsMatch((log as OperationLog).OperationName, parameters[parameter], RegexOptions.IgnoreCase));
                    });
                    break;

                case StreamLogsOperation.InputParameterUrl:
                    filters.Add((log) =>
                    {
                        return(log is OperationLog && Regex.IsMatch((log as OperationLog).Url, parameters[parameter], RegexOptions.IgnoreCase));
                    });
                    break;

                case StreamLogsOperation.InputParameterType:
                    filters.Add((log) =>
                    {
                        return(log is OperationLog && Regex.IsMatch((log as OperationLog).EventType.ToString(), parameters[parameter], RegexOptions.IgnoreCase));
                    });
                    break;

                case StreamLogsOperation.InputParameterMessage:
                    filters.Add((log) =>
                    {
                        return(log is OperationLog && Regex.IsMatch((log as OperationLog).Message.ToString(), parameters[parameter], RegexOptions.IgnoreCase));
                    });
                    break;

                default:
                    this.logger?.Log(EventType.OperationError, "Unknown filter '{0}'.", parameter);

                    throw new BadRequestException("Unknown filter '{0}'.", parameter);
                }
            }

            this.logger?.Log(EventType.OperationInformation, "Set response headers.");

            context.Response.SetDefaultValues();
            context.Response.SendChuncked = true;
            context.Response.SetHeaderValue("Content-Type", "text/event-stream");
            context.SyncResponse();

            this.logger?.Log(EventType.OperationInformation, "Setup event writer.");

            this.failed = false;

            MultiLogWriter logWriter   = this.logger?.LogWriter as MultiLogWriter;
            EventLogWriter eventWriter = new EventLogWriter();

            eventWriter.LogWritten += (sender, log) =>
            {
                lock (context)
                {
                    try
                    {
                        if (filters.Any(filter => !filter(log)))
                        {
                            return;
                        }

                        this.lastLogTime = DateTime.Now;
                        context.Response.WriteContent(string.Format(
                                                          "[{0} | {1}] {2} {3}{4}",
                                                          log.Timestamp,
                                                          log.EventType,
                                                          log.ExtendedData.Length > 1 ? $"('{string.Join("', '", log.ExtendedData, 0, log.ExtendedData.Length - 1)}')" : "",
                                                          log.ExtendedData[log.ExtendedData.Length - 1],
                                                          Environment.NewLine));

                        context.FlushResponse();
                    }
                    catch (Exception ex)
                    {
                        this.logger?.Log(EventType.OperationError, "Failed to write log to stream, stop operation: {0}", ex.Message);
                        this.failed = true;
                    }
                }
            };


            this.logger?.Log(EventType.OperationInformation, "Add event writer to global log writer.");

            try
            {
                this.lastLogTime = DateTime.Now;
                logWriter.Add(eventWriter);
            }
            catch (Exception ex)
            {
                this.logger?.Log(EventType.OperationError, "Unable to attach EventLogWriter (Adding failed): {0}", ex.Message);
                return;
            }

            int idleTimeoutinMs = 300000;
            int idleTimeinMs    = 0;
            int sleepTimeInMs   = 1000;

            do
            {
                Thread.Sleep(sleepTimeInMs);

                idleTimeinMs = (int)(DateTime.Now - this.lastLogTime).TotalMilliseconds;
            } while (!failed && idleTimeinMs <= idleTimeoutinMs);

            // only output this information when stream didn't stop because flushing log data to stream failed.
            if (idleTimeinMs > idleTimeoutinMs)
            {
                this.logger?.Log(EventType.OperationInformation, "No log event for {0}s, stopping the log stream.", idleTimeoutinMs);
            }

            this.logger?.Log(EventType.OperationInformation, "Remove event writer to global log writer.");

            try
            {
                logWriter.Remove(eventWriter);
            }
            catch (Exception ex)
            {
                this.logger?.Log(EventType.SystemError, "Unable to remove EventLogWriter: {0}", ex.Message);
            }

            return;
        }
Пример #24
0
 private void ProcessNextWorkRun()
 {
     while (true)
     {
         try
         {
             WorkRule workRule = new WorkRule();
             List <Work_RunProcessInfo> createRunProcess = workRule.GetCreateRunProcess(this._Work_Host);
             if (createRunProcess.Count > 0)
             {
                 List <int> PlanIDList = (from s in createRunProcess
                                          select s.PlanID).Distinct <int>().ToList <int>();
                 List <Work_PlanStepInfo> source = (from s in workRule.Work_PlanStepInfo
                                                    where PlanIDList.Contains(s.PlanID)
                                                    select s).ToList <Work_PlanStepInfo>();
                 using (List <Work_RunProcessInfo> .Enumerator enumerator = createRunProcess.GetEnumerator())
                 {
                     while (enumerator.MoveNext())
                     {
                         Work_RunProcessInfo objWork_RunProcessInfo = enumerator.Current;
                         PlanInfo            planInfo = new PlanInfo
                         {
                             PlanRunID      = objWork_RunProcessInfo.PlanRunID,
                             PlanID         = objWork_RunProcessInfo.PlanID,
                             RunDateTime    = objWork_RunProcessInfo.RunDate,
                             WorkInfoID     = objWork_RunProcessInfo.WorkInfoID,
                             WorkInfoName   = objWork_RunProcessInfo.WorkInfoName,
                             PlanName       = objWork_RunProcessInfo.PlanName,
                             PlanConfigInfo = objWork_RunProcessInfo.ConfigInfo
                         };
                         planInfo.ProcessInfoList = new List <PlanStepInfo>();
                         foreach (Work_PlanStepInfo current in from s in
                                  (from s in source
                                   where s.PlanID == objWork_RunProcessInfo.PlanID
                                   select s).Distinct <Work_PlanStepInfo>()
                                  orderby s.SortIndex
                                  select s)
                         {
                             PlanStepInfo item = new PlanStepInfo
                             {
                                 WorkInfoName      = planInfo.WorkInfoName,
                                 RunDateTime       = objWork_RunProcessInfo.RunDate,
                                 WorkLogID         = planInfo.WorkLogID,
                                 ProcessConfig     = current.ProcessConfig,
                                 PlanConfigInfo    = planInfo.PlanConfigInfo,
                                 PlanID            = objWork_RunProcessInfo.PlanID,
                                 ProcessID         = current.ProcessID,
                                 ProcessName       = current.ProcessName,
                                 AssemblyName      = current.AssemblyName,
                                 SortIndex         = current.SortIndex,
                                 TypeName          = current.TypeName,
                                 FailProcessType   = current.FailProcessType,
                                 SucessProcessType = current.SucessProcessType,
                                 PlanStepID        = current.PlanStepID,
                                 RunCount          = current.RunCount,
                                 RunInterval       = current.RunInterval,
                                 StepName          = current.StepName,
                                 PlanName          = objWork_RunProcessInfo.PlanName
                             };
                             planInfo.ProcessInfoList.Add(item);
                         }
                         ThreadPool.QueueUserWorkItem(new WaitCallback(this.ProcessWorkRun), planInfo);
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             ("循环检查各作业的计划处理出现异常:" + ex.Message).WriteLineRed("");
             try
             {
                 LogHelper.Write("WorkLog", "循环检查各作业的计划处理出现异常", ex, "");
             }
             catch (Exception exception)
             {
                 EventLogWriter.WriterLog(exception);
             }
         }
         Thread.Sleep(this._NextWorkRunSleep);
     }
 }
Пример #25
0
        private static List <ApiRequest> GetRequests(string who, string path, string controller, string bearer, string basic, string code, bool hasLog, int pageSize, int pageIndex, out int totalCount)
        {
            List <ApiRequest> list = new List <ApiRequest>();

            totalCount = 0;
            string schema   = GetSchema();
            var    settings = ConfigurationProvider.ConnectionStrings[eXtensibleWebApiConfig.SqlConnectionKey];

            if (settings != null && !String.IsNullOrWhiteSpace(settings.ConnectionString))
            {
                try
                {
                    using (SqlConnection cn = new SqlConnection(settings.ConnectionString))
                    {
                        cn.Open();
                        using (SqlCommand cmd = cn.CreateCommand())
                        {
                            StringBuilder sb = new StringBuilder();

                            //sb.Append("select [ApiRequestId],[XmlData] from [" + schema + "].[ApiRequest]");
                            sb.Append("select r.ApiRequestId, r.XmlData AS XmlRequest, l.Id, l.ApplicationKey, l.Zone, l.AppContextInstance, l.Category, l.Severity, l.Message" +
                                      " from [" + schema + "].[Error] as l right outer join [" + schema + "].[ApiRequest]  as r on l.MessageId = r.MessageId");
                            StringBuilder sbWhere = new StringBuilder();

                            int whereCount = 0;
                            if (!String.IsNullOrWhiteSpace(who) ||
                                !String.IsNullOrWhiteSpace(path) ||
                                !String.IsNullOrWhiteSpace(controller) ||
                                !String.IsNullOrEmpty(bearer) ||
                                !String.IsNullOrEmpty(basic) ||
                                !String.IsNullOrEmpty(code) ||
                                hasLog)
                            {
                                sbWhere.Append(" where");

                                if (!String.IsNullOrEmpty(who))
                                {
                                    sbWhere.Append(" r.[AppInstance] = " + AppInstanceParamName);
                                    cmd.Parameters.AddWithValue(AppInstanceParamName, who);
                                    whereCount++;
                                }

                                if (!String.IsNullOrEmpty(path))
                                {
                                    if (whereCount > 0)
                                    {
                                        sbWhere.Append(" and");
                                    }
                                    sbWhere.Append(" r.[Path] like '%' + " + PathParamName + " + '%'");
                                    cmd.Parameters.AddWithValue(PathParamName, path);
                                    whereCount++;
                                }

                                if (!String.IsNullOrEmpty(controller))
                                {
                                    if (whereCount > 0)
                                    {
                                        sbWhere.Append(" and");
                                    }
                                    sbWhere.Append(" r.[ControllerName] like '%' + " + ControllerNameParamName + " + '%'");
                                    cmd.Parameters.AddWithValue(ControllerNameParamName, controller);
                                    whereCount++;
                                }

                                if (!String.IsNullOrEmpty(bearer))
                                {
                                    if (whereCount > 0)
                                    {
                                        sbWhere.Append(" and");
                                    }
                                    sbWhere.Append(" r.[BearerToken] like '%' + " + BearerTokenParamName + " + '%'");
                                    cmd.Parameters.AddWithValue(BearerTokenParamName, bearer);
                                    whereCount++;
                                }

                                if (!String.IsNullOrEmpty(basic))
                                {
                                    if (whereCount > 0)
                                    {
                                        sbWhere.Append(" and");
                                    }
                                    sbWhere.Append(" r.[BasicToken] like '%' + " + BasicTokenParamName + " + '%'");
                                    cmd.Parameters.AddWithValue(BasicTokenParamName, basic);
                                    whereCount++;
                                }
                                if (!String.IsNullOrEmpty(code))
                                {
                                    if (whereCount > 0)
                                    {
                                        sbWhere.Append(" and");
                                    }
                                    sbWhere.Append(" r.[ResponseCode] = " + ResponseCodeParamName);
                                    cmd.Parameters.AddWithValue(ResponseCodeParamName, code);
                                    whereCount++;
                                }
                                if (hasLog)
                                {
                                    if (whereCount > 0)
                                    {
                                        sbWhere.Append(" and");
                                    }
                                    sbWhere.Append(" r.[HasLog] = 1");
                                    whereCount++;
                                }

                                sb.Append(sbWhere.ToString());
                            }

                            sb.Append(" order by r.[ApiRequestId] desc");
                            sb.Append(" OFFSET " + PageSizeParamName + " * (" + PageIndexParamName + ") ROWS");
                            sb.Append(" FETCH NEXT " + PageSizeParamName + " ROWS ONLY");
                            cmd.Parameters.AddWithValue(PageSizeParamName, pageSize);
                            cmd.Parameters.AddWithValue(PageIndexParamName, pageIndex);

                            sb.Append(" select count (*) FROM [" + schema + "].[ApiRequest] as r (NOLOCK)");
                            sb.Append(sbWhere.ToString());

                            cmd.CommandType    = CommandType.Text;
                            cmd.CommandText    = sb.ToString();
                            cmd.CommandTimeout = 0;

                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    string xml        = reader.GetString(reader.GetOrdinal("XmlRequest"));
                                    var    apiRequest = StringToRequest(xml);
                                    apiRequest.ApiRequestId = reader.GetInt64(reader.GetOrdinal("ApiRequestId"));

                                    if (!reader.IsDBNull(reader.GetOrdinal("Id")))
                                    {
                                        // <Value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string">rb.global.tenant.rbdigital</Value>
                                        // <Value xsi:type="xsd:string">singleview</Value>
                                        //string xmllog = reader.GetString(reader.GetOrdinal("XmlLog"));
                                        List <TypedItem> apiLog   = new List <TypedItem>();// GenericSerializer.StringToGenericList<TypedItem>(xmllog);
                                        string           key      = reader.GetString(reader.GetOrdinal("ApplicationKey"));
                                        string           zone     = reader.GetString(reader.GetOrdinal("Zone"));
                                        string           ctx      = reader.GetString(reader.GetOrdinal("AppContextInstance"));
                                        string           category = reader.GetString(reader.GetOrdinal("Category"));
                                        string           severity = reader.GetString(reader.GetOrdinal("Severity"));
                                        string           message  = reader.GetString(reader.GetOrdinal("Message"));
                                        apiLog.Add(new TypedItem("key", key));
                                        apiLog.Add(new TypedItem("zone", zone));
                                        apiLog.Add(new TypedItem("ctx", ctx));
                                        apiLog.Add(new TypedItem("category", category));
                                        apiLog.Add(new TypedItem("severity", severity));
                                        apiLog.Add(new TypedItem("message", message));
                                        apiRequest.LogItems = apiLog;
                                    }
                                    list.Add(apiRequest);
                                }
                                if (reader.NextResult())
                                {
                                    reader.Read();
                                    totalCount = reader.GetInt32(0);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    var          message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                    IEventWriter writer  = new EventLogWriter();
                    var          props   = eXtensibleConfig.GetProperties();
                    writer.WriteError(message, SeverityType.Critical, "ApiRequestSqlAccess", props);
                }
            }
            return(list);
        }
        public ActionResult Index()
        {
            ParitalWidgetPageWidgetActionViewModel model = new ParitalWidgetPageWidgetActionViewModel();
            var widgetProperties = ComponentPropertiesRetriever.Retrieve <PartialWidgetPageWidgetModel>();

            if (widgetProperties == null || (widgetProperties.Path == null && widgetProperties.Page == null && widgetProperties.CustomUrl == null))
            {
                model.Render = false;
            }
            else
            {
                model.Render = true;
                var Properties = widgetProperties;
                if (Properties.RenderMode.Equals(PartialWidgetPageWidgetModel._RenderMode_Ajax))
                {
                    model.RenderMode = PartialWidgetPageWidgetRenderMode.Ajax;
                    // Get path
                    if (!string.IsNullOrWhiteSpace(Properties.CustomUrl))
                    {
                        model.AjaxUrl = Properties.CustomUrl;
                    }
                    else
                    {
                        TreeNode Page = GetPage(Properties, false);
                        if (Page == null)
                        {
                            model.Render = false;
                            model.Error  = "Could not locate Page, please check configuration";
                            EventLogWriter.WriteLog(new EventLogData(EventTypeEnum.Warning, "PartialWidgetPageWidget", "PAGENOTFOUND")
                            {
                                EventDescription = "Could not find Page from the configuration of the Parital Widget Page Widget, located on page: " + PageDataContextRetriever.Retrieve <TreeNode>().Page.NodeAlias
                            });
                        }
                        else
                        {
                            // get Relative Url
                            model.AjaxUrl = DocumentURLProvider.GetUrl(Page);
                        }
                    }
                }
                else if (Properties.RenderMode.Equals(PartialWidgetPageWidgetModel._RenderMode_Server))
                {
                    model.RenderMode = PartialWidgetPageWidgetRenderMode.ServerSide;
                    TreeNode Page = GetPage(Properties, false);
                    if (Page == null)
                    {
                        model.Render = false;
                        model.Error  = "Could not locate Page, please check configuration";
                        EventLogWriter.WriteLog(new EventLogData(EventTypeEnum.Warning, "PartialWidgetPageWidget", "PAGENOTFOUND")
                        {
                            EventDescription = "Could not find Page from the configuration of the Parital Widget Page Widget, located on page: " + PageDataContextRetriever.Retrieve <TreeNode>().Page.NodeAlias
                        });
                    }
                    else
                    {
                        // get DocumentID and RenderClass
                        model.Renderer   = PartialWidgetRenderingRetriever.GetRenderingControllerAction(Page.ClassName);
                        model.DocumentID = Page.DocumentID;
                    }
                }
                else
                {
                    model.Render = false;
                }
            }

            return(View(_VIEWPATH, model));
        }
Пример #27
0
        public TwitterItem(XElement tweet)
        {
            EventLogWriter logWriter = new EventLogWriter("TwitterManager");

            //Message Id
            try
            {
                MessageId = decimal.Parse(tweet.Element("id").Value);
            }
            catch (Exception ex)
            {
                logWriter.WriteErrorToEventLog(string.Format("TwitterItem: Exception = {0}", ex.Message));
            }

            //Created At
            try
            {
                string date = tweet.Element("created_at").Value;
                CreatedAt = DateTime.Parse(date.Substring(date.Length - 4, 4) + date.Substring(4, 19));
            }
            catch (Exception ex)
            {
                logWriter.WriteErrorToEventLog(string.Format("TwitterItem: Exception = {0}", ex.Message));
            }

            //User Id
            try
            {
                UserId = int.Parse(tweet.Element("user").Element("id").Value);
            }
            catch (Exception ex)
            {
                logWriter.WriteErrorToEventLog(string.Format("TwitterItem: Exception = {0}", ex.Message));
            }

            //Message
            Message = tweet.Element("text").Value;

            //Screen Name
            ScreenName = tweet.Element("user").Element("screen_name").Value;

            //Language
            Language = tweet.Element("user").Element("lang").Value;

            //InReplyToStatusId
            try
            {
                InReplyToStatusId = tweet.Element("in_reply_to_status_id").Value == "" ?0 :decimal.Parse(tweet.Element("in_reply_to_status_id").Value);
            }
            catch (Exception ex)
            {
                logWriter.WriteErrorToEventLog(string.Format("TwitterItem: Exception = {0}", ex.Message));
            }

            //InReplyToUserId
            try
            {
                InReplyToUserId = tweet.Element("in_reply_to_user_id").Value == "" ?0 :int.Parse(tweet.Element("in_reply_to_user_id").Value);
            }
            catch (Exception ex)
            {
                logWriter.WriteErrorToEventLog(string.Format("TwitterItem: Exception = {0}", ex.Message));
            }

            //InReplyToScreenName
            InReplyToScreenName = tweet.Element("in_reply_to_screen_name").Value;

            UploadedBy = Environment.MachineName;

            UploadedAt = DateTime.Now;
        }
Пример #28
0
        public void Execute( )
        {
            try
            {
                ILoggingDataAccessAgent2 loggingDataAccess;
                DicomEventLogDataSet     eventLogDS;

                if (!DataAccessServices.IsDataAccessServiceRegistered <ILoggingDataAccessAgent2> ( ))
                {
                    throw new InvalidOperationException("Logging Data Access is not registered.");
                }
                else
                {
                    loggingDataAccess = DataAccessServices.GetDataAccessService <ILoggingDataAccessAgent2> ( );
                }

                MatchingParameterCollection           matchingCollection = new MatchingParameterCollection( );
                MatchingParameterList                 matchingList       = new MatchingParameterList( );
                DICOMServerEventLogMatchingParameters eventLogMatching   = new DICOMServerEventLogMatchingParameters( );

                eventLogMatching.EventDateTime.EndDate = DateTime.Now.Subtract(new TimeSpan(0, 1, 0));

                matchingList.Add(eventLogMatching);
                matchingCollection.Add(matchingList);

                string directoryPath = Path.Combine(LoggingState.AutoSaveDirectory, DateTime.Now.ToShortDateString( ).Replace('/', '-'));
                string filePath;

                Directory.CreateDirectory(directoryPath);

                WriteLog("Begin Auto Save Log", LogType.Debug);

                int  batchSize  = 10000;
                long totalSaved = 0;

                eventLogDS = loggingDataAccess.QueryDicomEventLogDataset(matchingCollection, new OrderByParametersList( ), batchSize, true);

                if (eventLogDS.DICOMServerEventLog.Count > 0)
                {
                    string indexFile = Path.Combine(directoryPath, "index");

                    indexFile = Path.ChangeExtension(indexFile, ".xml");

                    using (FileStream indexfs = new FileStream(indexFile, FileMode.Create, FileAccess.Write))
                    {
                        XmlDocument document = new XmlDocument( );

                        XmlElement rootElement = document.CreateElement("logs");

                        document.AppendChild(rootElement);

                        while (eventLogDS.DICOMServerEventLog.Count != 0)
                        {
                            filePath = Path.Combine(directoryPath, eventLogDS.DICOMServerEventLog [0].EventID.ToString( ));

                            filePath = Path.ChangeExtension(filePath, "txt");

                            using (FileStream fleStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                            {
                                using (StreamWriter streamWriter = new StreamWriter(fleStream))
                                {
                                    EventLogWriter.WriteEventLog("", eventLogDS, streamWriter, new DICOMServerEventLogFormsFormatter( ), true, directoryPath);

                                    XmlElement   element            = document.CreateElement("logFile");
                                    XmlAttribute fileAttribute      = document.CreateAttribute("file");
                                    XmlAttribute dateStartAttribute = document.CreateAttribute("dateStart");
                                    XmlAttribute dateEndfAttribute  = document.CreateAttribute("dateEnd");

                                    fileAttribute.Value      = filePath;
                                    dateStartAttribute.Value = eventLogDS.DICOMServerEventLog [0].EventDateTime.ToString( );
                                    dateEndfAttribute.Value  = eventLogDS.DICOMServerEventLog [eventLogDS.DICOMServerEventLog.Count - 1].EventDateTime.ToString( );

                                    element.Attributes.Append(fileAttribute);
                                    element.Attributes.Append(dateStartAttribute);
                                    element.Attributes.Append(dateEndfAttribute);

                                    rootElement.AppendChild(element);

                                    totalSaved += eventLogDS.DICOMServerEventLog.Count;

                                    if (LoggingState.DeleteSavedLog)
                                    {
                                        //if failed to delete for any reason lets continue
                                        try
                                        {
                                            loggingDataAccess.DeleteDicomEventLog(matchingCollection, batchSize);
                                        }
                                        catch (Exception exception)
                                        {
                                            Logger.Global.Log(string.Empty, string.Empty, 0, string.Empty, string.Empty, 0, Leadtools.Dicom.DicomCommandType.Undefined, DateTime.Now, LogType.Error, MessageDirection.None,
                                                              "Auto Save Log failed to delete logs. " + exception.Message, null, null);
                                        }
                                    }
                                }
                            }

                            eventLogDS = loggingDataAccess.QueryDicomEventLogDataset(matchingCollection, new OrderByParametersList( ), batchSize, true);
                        }

                        document.Save(indexfs);
                    }

                    WriteLog("Exporting log to file: " + indexFile, LogType.Debug);
                }

                WriteLog("End Auto Save Log. " + totalSaved.ToString( ) + " log(s) saved.", LogType.Debug);
            }
            catch (Exception exception)
            {
                Logger.Global.Log(string.Empty, string.Empty, 0, string.Empty, string.Empty, 0, Leadtools.Dicom.DicomCommandType.Undefined, DateTime.Now, LogType.Error, MessageDirection.None,
                                  "Auto Save Log failed. " + exception.Message, null, null);
            }
        }
Пример #29
0
        static void Main(string[] args)
        {
            EventLogWriter ev = new EventLogWriter("testEventLog");

            ev.WriteToEventLog("test");
        }
Пример #30
0
        static eXtensibleWebApiConfig()
        {
            IEventWriter  writer  = new EventLogWriter();
            StringBuilder message = new StringBuilder();
            var           props   = eXtensibleConfig.GetProperties();

            try
            {
                string configfilepath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
                string configFolder   = Path.GetDirectoryName(configfilepath);

                WebApiPlugins = configFolder + "\\" + "webApiControllers";

                DateTimeSchemaOption  loggingSchema;
                LoggingModeOption     loggingMode;
                LoggingStrategyOption loggingStrategy;
                string logSchemaCandidate        = ConfigurationProvider.AppSettings[XFWebApiConstants.Config.LoggingSchema];
                string logToCandidate            = ConfigurationProvider.AppSettings[XFWebApiConstants.Config.LogToKey];
                string loggingModeCandidate      = ConfigurationProvider.AppSettings[XFWebApiConstants.Config.LoggingModeKey];
                string sqlConnectionKeyCandidate = ConfigurationProvider.AppSettings[XFWebApiConstants.Config.SqlConnectionKey];

                var configfilemap = new ExeConfigurationFileMap()
                {
                    ExeConfigFilename = configfilepath
                };
                Configuration           config  = ConfigurationManager.OpenMappedExeConfiguration(configfilemap, ConfigurationUserLevel.None);
                eXtensibleWebApiSection section = config.Sections[XFWebApiConstants.Config.SectionName] as eXtensibleWebApiSection;
                message.AppendLine(String.Format("{0}: {1}", "configFolder", configFolder));

                if (section != null)
                {
                    MessageProviderFolder = section.MessageProviderFolder;
                    var found = section.Elements.GetForLoggingMode(section.LoggingKey);
                    if (found != null)
                    {
                        message.AppendLine(String.Format("{0}: {1}", XFWebApiConstants.Config.SectionName, "found"));
                    }

                    if (Enum.TryParse <LoggingStrategyOption>(found.LoggingStrategy, true, out loggingStrategy) &&
                        Enum.TryParse <LoggingModeOption>(found.LoggingMode, true, out loggingMode))
                    {
                        if (loggingStrategy == LoggingStrategyOption.Datastore)
                        {
                            SqlConnectionKey = found.DatastoreKey;
                        }
                        LoggingMode = loggingMode;
                        LogTo       = loggingStrategy;
                        if (!String.IsNullOrEmpty(found.LoggingSchema) &&
                            Enum.TryParse <DateTimeSchemaOption>(found.LoggingSchema, true, out loggingSchema))
                        {
                            LoggingSchema = loggingSchema;
                        }

                        message.AppendLine(String.Format("{0}: {1}", "parsing", "success"));
                    }
                    else
                    {
                        loggingMode = XFWebApiConstants.Default.LoggingMode;
                        LogTo       = XFWebApiConstants.Default.LogTo;
                        message.AppendLine(String.Format("{0}: {1}", "parsing", "failure"));
                    }

                    IsEditRegistration = section.EditRegistration;
                    CatchAll           = section.CatchAllControllerId;
                    MessageIdHeaderKey = section.MessageIdHeaderKey;
                }
                else
                {
                    IsEditRegistration = false;
                    if (!String.IsNullOrWhiteSpace(loggingModeCandidate) && Enum.TryParse <LoggingModeOption>(loggingModeCandidate, true, out loggingMode))
                    {
                        LoggingMode = loggingMode;
                        message.AppendLine(String.Format("{0}: {1}", "parse LoggingMode", true));
                    }
                    else
                    {
                        LoggingMode = XFWebApiConstants.Default.LoggingMode;
                        message.AppendLine(String.Format("{0}: {1}", "parse LoggingMode", false));
                    }
                    // read from appsettings or use defaults
                    if (!String.IsNullOrWhiteSpace(logToCandidate) && Enum.TryParse <LoggingStrategyOption>(logToCandidate, true, out loggingStrategy))
                    {
                        LogTo = loggingStrategy;
                        message.AppendLine(String.Format("{0}: {1}", "parse LoggingTo", true));
                    }
                    else
                    {
                        LogTo = XFWebApiConstants.Default.LogTo;
                        message.AppendLine(String.Format("{0}: {1}", "parse LoggingTo", false));
                    }

                    if (!String.IsNullOrWhiteSpace(sqlConnectionKeyCandidate))
                    {
                        SqlConnectionKey = sqlConnectionKeyCandidate;
                        message.AppendLine(String.Format("{0}: {1}", "key", SqlConnectionKey));
                    }
                    else
                    {
                        SqlConnectionKey = XFWebApiConstants.Default.DatastoreConnectionKey;
                        message.AppendLine(String.Format("{0}: {1}", "key", "default"));
                    }

                    if (!String.IsNullOrWhiteSpace(logSchemaCandidate) &&
                        Enum.TryParse <DateTimeSchemaOption>(logSchemaCandidate, true, out loggingSchema))
                    {
                        LoggingSchema = loggingSchema;
                    }
                    else
                    {
                        LoggingSchema = DateTimeSchemaOption.None;
                    }

                    if (LogTo.Equals(LoggingStrategyOption.Datastore))
                    {
                        try
                        {
                            string cnText = ConfigurationProvider.ConnectionStrings[SqlConnectionKey].ConnectionString;
                            using (System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(cnText))
                            {
                                cn.Open();
                                message.AppendLine(String.Format("{0}: {1}", "cnState", cn.State));

                                if (cn.State == System.Data.ConnectionState.Open)
                                {
                                    IsLogToDatastore = true;
                                }
                                else
                                {
                                    LogTo = XFWebApiConstants.Default.LogTo;
                                    message.AppendLine(String.Format("{0}: {1}: {2}", "LogTo", "revert to default", LogTo));
                                }
                            }
                        }
                        catch (Exception innerEx)
                        {
                            LogTo = LoggingStrategyOption.None;
                            message.AppendLine(String.Format("{0}: {1}: {2}", "LogTo", "on error", LogTo));
                            string m = innerEx.InnerException != null ? innerEx.InnerException.Message : innerEx.Message;
                            message.AppendLine(m);
                        }
                    }
                    MessageProviderFolder = XFWebApiConstants.Default.MessageProviderFolder;
                    IsEditRegistration    = XFWebApiConstants.Default.IsEditRegistration;
                    CatchAll           = XFWebApiConstants.Default.CatchAllControllerId;
                    MessageIdHeaderKey = XFWebApiConstants.Default.MessageIdHeaderKey;
                }
            }
            catch (Exception ex)
            {
                // nows setup defaults
                MessageProviderFolder = XFWebApiConstants.Default.MessageProviderFolder;
                LoggingMode           = XFWebApiConstants.Default.LoggingMode;
                LogTo = XFWebApiConstants.Default.LogTo;
                IsEditRegistration = XFWebApiConstants.Default.IsEditRegistration;
                CatchAll           = XFWebApiConstants.Default.CatchAllControllerId;
                MessageIdHeaderKey = XFWebApiConstants.Default.MessageIdHeaderKey;
                var m = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                message.AppendLine(m);
            }
            //writer.WriteError(message.ToString(), SeverityType.Critical, "webApiconfig", props);
            //writer.WriteEvent(message.ToString(), "webApiConfig", props);
        }