Inheritance: MonoBehaviour
示例#1
2
    public static bool Execute(ProjectProperties properties, Log log)
    {
        Console.WriteLine("compiling");
        var processSettings = new ProcessStartInfo();
        processSettings.FileName = properties.CscPath;
        processSettings.Arguments = properties.FormatCscArguments();

        log.WriteLine("Executing {0}", processSettings.FileName);
        log.WriteLine("Csc Arguments: {0}", processSettings.Arguments);

        processSettings.CreateNoWindow = true;
        processSettings.RedirectStandardOutput = true;
        processSettings.UseShellExecute = false;

        Process cscProcess = null;
        try
        {
            cscProcess = Process.Start(processSettings);
        }
        catch (Win32Exception)
        {
            Console.WriteLine("ERROR: csc.exe needs to be on the path.");
            return false;
        }

        var output = cscProcess.StandardOutput.ReadToEnd();
        log.WriteLine(output);

        cscProcess.WaitForExit();

        if (output.Contains("error CS")) return false;
        return true;
    }
示例#2
0
        public void CanCreateAlarmTypeAndLog()
        {
            IRepository<AlarmType> repoA = new AlarmTypeRepository();
            AlarmType alarm = new AlarmType();
            alarm.NameAlarmType = "PruebaAlarma";
            alarm.Description = "Prueba descriptiva alarma";

            repoA.Save(alarm);

            IRepository<User> repoB = new UserRepository();
            User user = new User();
            user = repoB.GetById(1);
            IRepository<Event> repoC = new EventRepository();
            Event eventt = new Event();
            eventt = repoC.GetById(2);

            IRepository<Log> repoD = new LogRepository();
            Log log = new Log();
            log.DateTime = DateTime.Now;
            log.Text = "Prueba descriptiva log";
            log.Event = eventt;
            log.User = user;

            repoD.Save(log);
        }
示例#3
0
文件: LogDAO.cs 项目: RazenRyne/eSAR
 public Boolean AddLog(LogBDO log)
 {
     //string message = "Log Added Successfully";
     bool ret = true;
     try
     {
         Log l = new Log();
         ConvertLogBDOToLog(log, l);
         using (var DCEnt = new DCFIEntities())
         {
             DCEnt.Logs.Add(l);
             DCEnt.Entry(l).State = System.Data.Entity.EntityState.Added;
             int num = DCEnt.SaveChanges();
              if (num < 1)
             {
                 ret = false;
                
             }
         }
     }
     catch (DbEntityValidationException dbEx)
     {
         foreach (var validationErrors in dbEx.EntityValidationErrors)
         {
             foreach (var validationError in validationErrors.ValidationErrors)
             {
                 Trace.TraceInformation("Property: {0} Error: {1}",
                                         validationError.PropertyName,
                                         validationError.ErrorMessage);
             }
         }
     }
     return ret;
 }
        public void ExecuteAppendLog(Log log)
        {
            string path = string.Format("../../{0}", this.LogFile);

            try
            {
                if (!File.Exists(path))
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(path))
                    {
                        file.WriteLine(layout.Format(log));
                    }
                }
                else if (File.Exists(path))
                {
                    using (TextWriter textWriter = new StreamWriter(path, true))
                    {
                        textWriter.WriteLine(layout.Format(log));
                        textWriter.Close();
                    }
                }
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
示例#5
0
文件: Program.cs 项目: Yulli/SteamBot
 public static void Main(string[] args)
 {
     Configuration config = Configuration.LoadConfiguration("settings.json");
     Log mainLog = new Log (config.MainLog, null);
     //byte counter = 0;
     foreach (Configuration.BotInfo info in config.Bots)
     {
         //Console.WriteLine("--Launching bot " + info.DisplayName +"--");
         mainLog.Info ("Launching Bot " + info.DisplayName + "...");
         new Thread(() =>
         {
             int crashes = 0;
             while (crashes < 1000)
             {
                 try
                 {
                     new Bot(info, config.ApiKey);
                 }
                 catch (Exception e)
                 {
                     mainLog.Error ("Error With Bot: "+e);
                     crashes++;
                 }
             }
         }).Start();
         Thread.Sleep(5000);
     }
 }
示例#6
0
        private DataTable dataTable;     // загруженная таблица


        /// <summary>
        /// Конструктор
        /// </summary>
        private FrmBaseTableView()
        {
            InitializeComponent();
            errLog = null;
            baseAdapter = null;
            dataTable = null;
        }
示例#7
0
        /// <summary>
        /// Create a table 
        /// e.g. DDL.CreateTable( "Sample", "col1,int,col2,int,col3,varchar(10),col4,int,col5,int");
        /// </summary>
        /// <param name="sTableName"></param> - Name of the new table
        /// <param name="sColumns_i"></param> - A string containing list of colums in the format Column1,datatype,
        ///                                     Column2,datatype...etc
        public static void CreateTable(string sTableName, string sColumns_i)
        {
            using (Log log = new Log(".::()"))
            {
                try
                {

                    string sQuerry = "CREATE TABLE " + sTableName + "(";
                    string[] sColums = Strings.Split(sColumns_i, ",", -1, CompareMethod.Text);

                    sQuerry = sQuerry + sColums[0] + " " + sColums[1];

                    for (int nIndex = 2; nIndex < sColums.Length; nIndex += 2)
                        sQuerry = sQuerry + "," + sColums[nIndex] + " " + sColums[nIndex + 1];

                    sQuerry += ")";

                    DBWrapper.ExecuteNonQueryEx(sQuerry);
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }
        }
示例#8
0
        /// <summary>
        /// Insert data into table
        /// e.g. DDL.InsertInto("Sample", "col1,col2", "10,20");
        /// </summary>
        /// <param name="sTableName"></param>
        /// <param name="sColumns_i"></param>
        /// <param name="sValues_i"></param>
        public static void InsertInto(string sTableName, string sColumns_i, string sValues_i )
        {
            using( Log log = new Log( "Glx.DB.DDL.InsertInto()" ) )
            {
                try
                {
                    string sQuerry = "INSERT INTO " + sTableName + "(";
                    string[] sColums = Strings.Split(sColumns_i, ",", -1, CompareMethod.Text);

                    sQuerry = sQuerry + sColums[0];

                    for (int nIndex = 1; nIndex < sColums.Length; nIndex++)
                        sQuerry = sQuerry + "," + sColums[nIndex];

                    sQuerry += ") VALUES(";

                    string[] sValues = Strings.Split(sValues_i, ",", -1, CompareMethod.Text);

                    sQuerry = sQuerry + sValues[0];

                    for (int nIndex = 1; nIndex < sValues.Length; nIndex++)
                        sQuerry = sQuerry + "," + sValues[nIndex];

                    sQuerry += ")";

                    log.PutQuerry( sQuerry);
                    DBWrapper.ExecuteNonQueryEx(sQuerry);
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }
        }
示例#9
0
 static void Main(string[] args)
 {
     Log Logger =  new Log();
     for (int i = 1; i <= 100; i++)
     {
         //Check 15 first otherwise it will never hit.
         if (i % 15  == 0)
         {
             Logger.write("FizzBuzz");
         }
         else if (i % 3 == 0)
         {
             Logger.write("Fizz");
         }
         else if (i % 5 == 0)
         {
             Logger.write("Buzz");
         }
         else
         {
             Logger.write(i.ToString());
         }
         Logger.write(Environment.NewLine);
     }
     Logger.close();
     Console.ReadKey();
 }
示例#10
0
		/// <summary>
		/// Writes a single message to the output.
		/// </summary>
		/// <param name="source">The <see cref="Log"/> from which the message originates.</param>
		/// <param name="type">The type of the log message.</param>
		/// <param name="msg">The message to write.</param>
		/// <param name="context">The context in which this log was written. Usually the primary object the log entry is associated with.</param>
		public virtual void Write(Log source, LogMessageType type, string msg, object context)
		{
			int indent = source.Indent;
			string prefix = source.Prefix ?? "";
			string[] lines = msg.Split(new[] { '\n', '\r', '\0' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < lines.Length; i++)
			{
				if (i == 0)
				{
					switch (type)
					{
						case LogMessageType.Message:
							lines[i] = prefix + "Msg: " + new string(' ', indent * 2) + lines[i];
							break;
						case LogMessageType.Warning:
							lines[i] = prefix + "Wrn: " + new string(' ', indent * 2) + lines[i];
							break;
						case LogMessageType.Error:
							lines[i] = prefix + "ERR: " + new string(' ', indent * 2) + lines[i];
							break;
					}
				}
				else
				{
					lines[i] = new string(' ', prefix.Length + 5 + indent * 2) + lines[i];
				}

				this.WriteLine(source, type, lines[i], context);
			}
		}
示例#11
0
文件: Logger.cs 项目: TokleMahesh/BG
 public static void LogFailedMessage(object messageObj)
 {
     if (LogConfig.IsLoggingEnabled)
     {
         try
         {
             //log.SessionId = ApplicationContext.GetSessionId();
             var dataProvider = new LoggingDataProvider();
             var settings = new JsonSerializerSettings()
             {
                 TypeNameHandling = TypeNameHandling.Objects,
             };
             var log = new Log()
             {
                 Name = "FailedMessageItem",
                 ServiceName = messageObj.GetType().Name,
                 Request = JsonConvert.SerializeObject(messageObj, settings),
             };
             if (LogConfig.IsLogAsyncEnabled)
             {
                 Task.Factory.StartNew(() => dataProvider.SaveLog(log));
             }
             else
             {
                 dataProvider.SaveLog(log);
             }
         }
         catch (Exception ex)
         {
             File.AppendAllText("Logs.txt", "LogMessage method failed" + ex.ToString());
         }
     }
 }
示例#12
0
        public override void PostScheduleMessage(dynamic data)
        {
            try
            {

                oAuthTwitter OAuthTwt = new oAuthTwitter();
                TwitterAccountRepository fbaccrepo = new TwitterAccountRepository();
                TwitterAccount twtaccount = fbaccrepo.getUserInformation(data.UserId, data.ProfileId);


                OAuthTwt.CallBackUrl = System.Configuration.ConfigurationSettings.AppSettings["callbackurl"];
                OAuthTwt.ConsumerKey = System.Configuration.ConfigurationSettings.AppSettings["consumerKey"];
                OAuthTwt.ConsumerKeySecret = System.Configuration.ConfigurationSettings.AppSettings["consumerSecret"];
                OAuthTwt.AccessToken = twtaccount.OAuthToken;
                OAuthTwt.AccessTokenSecret = twtaccount.OAuthSecret;
                OAuthTwt.TwitterScreenName = twtaccount.TwitterScreenName;
                OAuthTwt.TwitterUserId = twtaccount.TwitterUserId;


                #region For Testing
                // For Testing 

                //OAuthTwt.ConsumerKey = "udiFfPxtCcwXWl05wTgx6w";
                //OAuthTwt.ConsumerKeySecret = "jutnq6N32Rb7cgbDSgfsrUVgRQKMbUB34yuvAfCqTI";
                //OAuthTwt.AccessToken = "1904022338-Ao9chvPouIU8ejE1HMG4yJsP3hOgEoXJoNRYUF7";
                //OAuthTwt.AccessTokenSecret = "Wj93a8csVFfaFS1MnHjbmbPD3V6DJbhEIf4lgSAefORZ5";
                //OAuthTwt.TwitterScreenName = "";
                //OAuthTwt.TwitterUserId = ""; 
                #endregion

                TwitterUser twtuser = new TwitterUser();

                if (string.IsNullOrEmpty(data.ShareMessage))
                {
                    data.ShareMessage = "There is no data in Share Message !";
                }

                JArray post = twtuser.Post_Status_Update(OAuthTwt, data.ShareMessage);

                
             
                Console.WriteLine("Message post on twitter for Id :" + twtaccount.TwitterUserId + " and Message: " + data.ShareMessage);
                ScheduledMessageRepository schrepo = new ScheduledMessageRepository();
                schrepo.updateMessage(data.Id);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                Log log = new Log();
                log.CreatedDate = DateTime.Now;
                log.Exception = ex.Message;
                log.Id = Guid.NewGuid();
                log.ModuleName = "TwitterScheduler";
                log.ProfileId = data.ProfileId;
                log.Status = false;
                LogRepository logRepo = new LogRepository();
                logRepo.AddLog(log);
            }

        }
示例#13
0
        public static void Send(string mailFrom,
                                                    string[] mailTo,
                                                    string[] mailCC,
                                                    string mailSubject,
                                                    string mailBody,
                                                    string mailServer,
                                                     Log log)
        {
            try
            {
                MailMessage mailMsg = new MailMessage();

                if (string.IsNullOrEmpty(mailSubject) || mailTo.Length == 0)
                    return;

                mailMsg.From = new MailAddress(mailFrom);

                if (mailTo.Length > 0)
                {
                    for (int i = 0; i < mailTo.Length; ++i)
                    {
                        if (mailTo[i].Trim().Length > 0)
                        {
                            mailMsg.To.Add(new MailAddress(mailTo[i]));
                        }
                    }
                }


                if (mailCC.Length > 0)
                {
                    for (int i = 0; i < mailCC.Length; ++i)
                    {
                        if (mailCC[i].Trim().Length > 0)
                        {
                            mailMsg.CC.Add(new MailAddress(mailCC[i]));
                        }
                    }
                }



                mailMsg.Subject = mailSubject;
                mailMsg.Body = mailBody;
                mailMsg.IsBodyHtml = true;

                SmtpClient client = new SmtpClient(mailServer, 25);
                if (mailMsg.To.Count > 0)
                {
                    client.Send(mailMsg);
                }

            }
            catch (Exception e)
            {
                log.write(LogType.error, 0, "sendMail", "->", e.StackTrace);
                log.write(LogType.error, 0, "sendMail", "->", e.Message);

            }
        }
示例#14
0
文件: Log.cs 项目: moto2002/UExtend
	public static Log getInstance() {
		if (Log.s_instance == null) {
			Log.s_instance = new Log();
			Log.s_instance.Initialize();
		}
		return Log.s_instance;
	}
 /// <summary>
 /// Initializes a new instance of the <see cref="LoggerService"/> class.
 /// </summary>
 public LoggerService()
 {
     InitializeComponent();
     Server = new TcpLoggerServer(4000);
     ConnectedClients = new Dictionary<string, LogMessageHandler>();
     LogWriter = new Log();
 }
示例#16
0
        private void fmMain_Load(object sender, EventArgs e)
        {
            bool r;
            AppMutex = new Mutex(true, "AndonSys.AppHelper", out r);
            if (!r)
            {
                MessageBox.Show("系统已运行!",this.Text);
                Close();
                return;
            }
            
            CONFIG.Load();

            log = new Log(Application.StartupPath, "AppHelper", Log.DEBUG_LEVEL);

            log.Debug("系统运行");
           
            gdApp.AutoGenerateColumns = false;
           
            LoadApp();
            
            tbApp.Show();

            timer.Enabled = true;
        }
示例#17
0
 public ActionResult Dangkythi()
 {
     //if (!_util.Checkdangky())
     //    return null;
     var obj = new Log();
     try
     {
         var dangKy = new Base.DangKy
         {
             Masv = Sinhvien.Username,
             KyNangDoc = false,
             KyNangNghe = false,
             DocHieu = false
         };
         UpdateModel(dangKy);
         if (Sinhvien.DiemThi < 200)
         {
             dangKy.KyNangDoc = false;
             dangKy.KyNangNghe = false;
         }
         QlsvEntities.DangKies.Add(dangKy);
         QlsvEntities.SaveChanges();
         obj.Error = false;
         obj.Message = "Đăng ký thành công";
     }
     catch (Exception)
     {
         obj.Error = true;
         obj.Message = "Xin thử lại";
     }
     return Json(obj);
 }
示例#18
0
        private bool _encodeError = false; // Any critical error

        /// <summary>
        /// General FFMPEG to convert a file
        /// </summary>
        /// <param name="Parameters">Parameters to pass to FFMPEG</param>
        /// <param name="jobStatus">Reference to JobStatus</param>
        /// <param name="jobLog">JobLog</param>
        public FFmpeg(string Parameters, JobStatus jobStatus, Log jobLog, bool ignoreSuspend = false)
            : base(Parameters, APP_PATH, jobStatus, jobLog, ignoreSuspend)
        {
            _Parameters = " -probesize 100M -analyzeduration 300M " + _Parameters; // We need to probe deeper into the files to get the correct audio / video track information else it can lead to incorrect channel information and failure
            _success = false; //ffmpeg looks for a +ve output so we have a false to begin with
            _uiAdminSessionProcess = true; // Assume we are always using ffmpeg build with hardware API's (UI Session 1 process)
        }
示例#19
0
        public static void GravarErro(Exception exception, string usuario)
        {
            Log log = new Log()
            {
                TipoLog = TipoLog.Erro,
                Observacao = exception.StackTrace,
                Usuario = usuario,
                DataHora = DateTime.Now
            };

            if (exception.InnerException != null)
            {
                log.Mensagem = exception.InnerException.ToString();
            }
            else
            {
                log.Mensagem = exception.Message;
            }

            using (Contexto db = new Contexto())
            {
                db.Logs.Add(log);
                db.SaveChanges();
            }
        }
示例#20
0
        public void DerivativeTest1()
        {
            IExpression exp = new Log(new Variable("x"), new Number(2));
            IExpression deriv = exp.Differentiate();

            Assert.AreEqual("1 / (x * ln(2))", deriv.ToString());
        }
示例#21
0
        public void DerivativeTest3()
        {
            IExpression exp = new Log(new Number(2), new Variable("x"));
            IExpression deriv = exp.Differentiate();

            Assert.AreEqual("-(ln(2) * (1 / x)) / (ln(x) ^ 2)", deriv.ToString());
        }
示例#22
0
        static public List<string> GetCNRSSNList(SqlConnection connect,
                                                                            Log log,
                                                                            int offsetDay)
        {
            List<string> SNList = new List<string>();

            SqlCommand dbCmd = connect.CreateCommand();
            dbCmd.CommandType = CommandType.Text;
            dbCmd.CommandText = @"select distinct a.SnoId
                                                            from Special_Det a
                                                            left join ProductAttr b on (a.SnoId = b.ProductID and b.AttrName='CNRSState')
                                                            where a.Tp='CNRS' 
	                                                            and a.Udt>=dateadd(dd,@day,getdate())
	                                                            and b.AttrValue is null";

            SQLHelper.createInputSqlParameter(dbCmd, "@day", offsetDay);


            log.write(LogType.Info, 0, "SQL", "GetCNRSSNList", dbCmd.CommandText);
            log.write(LogType.Info, 0, "SQL", "@day", offsetDay.ToString());



            SqlDataReader sdr = dbCmd.ExecuteReader();

            while (sdr.Read())
            {
                SNList.Add(sdr.GetString(0).Trim());
            }
            sdr.Close();
            return SNList;
        }
示例#23
0
        /// <summary>
        /// Validates a variant string, returns true if variant string is a correct HVGS nomnclature
        /// </summary>
        /// <param name="variant"></param>
        /// <returns></returns>
        public bool VariantValidate(string variant)
        {
            try
            {
                Process process = new Process();
                if (ApplicationDeployment.IsNetworkDeployed)
                    process.StartInfo.FileName = ApplicationDeployment.CurrentDeployment.DataDirectory + "\\Executables\\Validator.exe";
                else
                    process.StartInfo.FileName = Application.StartupPath + "\\Executables\\Validator.exe";
                process.StartInfo.Arguments = "-v " + "\"" + variant + "\"";
                process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.RedirectStandardOutput = true;

                process.Start();
                string output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                process.Close();

                return bool.Parse(output);
            }
            catch (Exception ex)
            {
                // something went wrong, we log it
                Log log = new Log(true);
                log.write("Error parsing variant: " + variant);
                log.write(ex.ToString());
                return false;
            }
        }
示例#24
0
        /// <summary>
        /// Log a message.
        /// </summary>
        /// <param name="message">Message to log. </param>
        /// <param name="level">Error severity level. </param>
        public void Log(Log.Level level, string message)
        {
            FileStream fileStream = null;
            StreamWriter writer = null;
            StringBuilder messageBuilder = new StringBuilder();

            try
            {
                fileStream = _logFile.Open(FileMode.OpenOrCreate,
                          FileAccess.Write, FileShare.Read);
                writer = new StreamWriter(fileStream);

                // Set the file pointer to the end of the file
                writer.BaseStream.Seek(0, SeekOrigin.End);

                // Create the message
                messageBuilder.Append(System.DateTime.Now.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss"))
                   .Append(" | ").Append(level.ToString()).Append(" | ").Append(message);

                // Force the write to the underlying file
                writer.WriteLine(messageBuilder.ToString());
                writer.Flush();
            }
            finally
            {
                if (writer != null) 
                    writer.Close();
            }
        }
示例#25
0
        static public string GetSnoPoMo(SqlConnection connect,
                                                                        Log log,
                                                                        string productId)
        {
            string ret = null;

            SqlCommand dbCmd = connect.CreateCommand();
            dbCmd.CommandType = CommandType.Text;
            dbCmd.CommandText = "select top 1 PO from dbo.SnoDet_PoMo (nolock) where SnoId=@SnoId";
            SQLHelper.createInputSqlParameter(dbCmd, "@SnoId", 10, productId);


            log.write(LogType.Info, 0, "SQL", "GetSnoPoMo", dbCmd.CommandText);
            log.write(LogType.Info, 0, "SQL", "@SnoId", productId);
           


            SqlDataReader sdr = dbCmd.ExecuteReader();
            while (sdr.Read())
            {
                ret=sdr.GetString(0).Trim();
            }
            sdr.Close();
            return ret;
        }
示例#26
0
        static public List<string> GetCDSISNList(SqlConnection connect,
                                                                                Log log,
                                                                                string snoId,
                                                                                string tp)
       {
          List<string> SNList = new List<string>();
 
          SqlCommand dbCmd = connect.CreateCommand();
          dbCmd.CommandType = CommandType.StoredProcedure;
          dbCmd.CommandText = "op_CDSIDataUpdate";
          SQLHelper.createInputSqlParameter(dbCmd, "@SnoId", 10, snoId);
          SQLHelper.createInputSqlParameter(dbCmd, "@tp", 2, tp);

          log.write(LogType.Info, 0, "SQL", "GetDNList", dbCmd.CommandText);
          log.write(LogType.Info, 0, "SQL", "@SnoId", snoId);
          log.write(LogType.Info, 0, "SQL", "@tp", tp);


         SqlDataReader sdr = dbCmd.ExecuteReader();
         while (sdr.Read())
         {
            SNList.Add(sdr.GetString(0).Trim());          
         }
         sdr.Close();
         return SNList;
       }
示例#27
0
        public void Start()
        {
            if (_running)
                throw new InvalidOperationException("Process is already running");

            if (!string.IsNullOrEmpty(LogFile))
            {
                _log = new Log(LogFile, BufferSize, ReliableLogging);
                _log.MaxNumberBackups = MaxNumberOfLogBackups;
                _log.MaxSize = MaxLogSize;
            }

            _process = new Process();
            _process.StartInfo.CreateNoWindow = true;
            _process.StartInfo.RedirectStandardError = true;
            _process.StartInfo.RedirectStandardInput = true;
            _process.StartInfo.RedirectStandardOutput = true;
            _process.StartInfo.UseShellExecute = false;
            _process.StartInfo.FileName = ImagePath;
            _process.StartInfo.Arguments = Arguments
                .Select(a => a.Replace("\"", "\\\""))
                .Select(a => a.Contains(" ") ? "\"" + a + "\"" : a)
                .Aggregate(new StringBuilder(), (sb, a) => sb.Append(a).Append(' '))
                .ToString()
                .Trim();
            _process.StartInfo.WorkingDirectory = WorkingDirectory;

            _process.ErrorDataReceived += new DataReceivedEventHandler(_process_OutputDataReceived);
            _process.OutputDataReceived += new DataReceivedEventHandler(_process_OutputDataReceived);
            _process.Exited += new EventHandler(_process_Exited);
            _process.Start();
            _process.BeginErrorReadLine();
            _process.BeginOutputReadLine();
            _running = true;
        }
示例#28
0
        /// <summary>
        /// Loads a configuration file to use when creating bots.
        /// </summary>
        /// <param name="configFile"><c>false</c> if there was problems loading the config file.</param>
        public bool LoadConfiguration(string configFile)
        {
            if (!File.Exists(configFile))
                return false;

            try
            {
                ConfigObject = Configuration.LoadConfiguration(configFile);
            }
            catch (JsonReaderException)
            {
                // handle basic json formatting screwups
                ConfigObject = null;
            }

            if (ConfigObject == null)
                return false;

            useSeparateProcesses = ConfigObject.UseSeparateProcesses;

            mainLog = new Log(ConfigObject.MainLog, null, Log.LogLevel.Debug);

            for (int i = 0; i < ConfigObject.Bots.Length; i++)
            {
                Configuration.BotInfo info = ConfigObject.Bots[i];
                mainLog.Info("Launching Bot " + info.DisplayName + "...");

                var v = new RunningBot(useSeparateProcesses, i, ConfigObject);
                botProcs.Add(v);
            }

            return true;
        }
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            // TODO: Add your acction filter's tasks here

            // Log Action Filter Call
            DatabaseContext storeDB = new DatabaseContext();
            if (filterContext.HttpContext.Session["admin"] != null)
            {
                User su = (User)filterContext.HttpContext.Session["admin"];
                var user = storeDB.Users.SingleOrDefault(u => u.Id == su.Id);
                storeDB.Entry(su).State = EntityState.Detached;
                Log log = new Log()
                {
                    Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                    Action = filterContext.ActionDescriptor.ActionName,
                    IP = filterContext.HttpContext.Request.UserHostAddress,
                    User=user,
                    Time = filterContext.HttpContext.Timestamp
                };

                storeDB.Logs.Add(log);
                storeDB.SaveChanges();
            }
            this.OnActionExecuting(filterContext);
        }
示例#30
0
文件: Login.xaml.cs 项目: KTwo/BA
        private void connect_util()
        {
            string user_name, password;
            int id_user = 0;
            user_name = user_name_txt.Text != "" ? user_name_txt.Text : "";
            password = password_txt.Text != "" ? password_txt.Text : "";

            id_user = db_util.query_user(user_name, password);

            if (id_user != 0)
            {
                log = new Log(id_user);
                log.id_log = db_util.insert_log(log);

                MainWindow main_window = new MainWindow();
                main_window.log = log;
                main_window.db_util = db_util;
                main_window.Show();
                this.Close();
            }
            else
            {
                info_lbl.Content = "Something went wrong!\nTry again";
            }
        }
示例#31
0
        public static bool TryToSelect(IToolContext context, SelectionMode mode, SelectionTargets targets, Modifier selectionModifier, Point2 point, double radius, Modifier modifier)
        {
            var shapePoint =
                mode.HasFlag(SelectionMode.Point) &&
                targets.HasFlag(SelectionTargets.Shapes) ?
                context.HitTest?.TryToGetPoint(context.CurrentContainer.Shapes, point, radius, null) : null;

            var shape =
                mode.HasFlag(SelectionMode.Shape) &&
                targets.HasFlag(SelectionTargets.Shapes) ?
                context.HitTest?.TryToGetShape(context.CurrentContainer.Shapes, point, radius) : null;

            var guidePoint =
                mode.HasFlag(SelectionMode.Point) &&
                targets.HasFlag(SelectionTargets.Guides) ?
                context.HitTest?.TryToGetPoint(context.CurrentContainer.Guides, point, radius, null) : null;

            var guide =
                mode.HasFlag(SelectionMode.Shape) &&
                targets.HasFlag(SelectionTargets.Guides) ?
                context.HitTest?.TryToGetShape(context.CurrentContainer.Guides, point, radius) : null;

            if (shapePoint != null || shape != null || guidePoint != null || guide != null)
            {
                bool haveNewSelection =
                    (shapePoint != null && !context.Renderer.Selected.Contains(shapePoint)) ||
                    (shape != null && !context.Renderer.Selected.Contains(shape)) ||
                    (guidePoint != null && !context.Renderer.Selected.Contains(guidePoint)) ||
                    (guide != null && !context.Renderer.Selected.Contains(guide));

                if (context.Renderer.Selected.Count >= 1 &&
                    !haveNewSelection &&
                    !modifier.HasFlag(selectionModifier))
                {
                    return(true);
                }
                else
                {
                    if (shapePoint != null)
                    {
                        if (modifier.HasFlag(selectionModifier))
                        {
                            if (context.Renderer.Selected.Contains(shapePoint))
                            {
                                Log.Info($"Deselected Shape Point: {shapePoint.GetType()}");
                                shapePoint.Deselect(context.Renderer);
                            }
                            else
                            {
                                Log.Info($"Selected Shape Point: {shapePoint.GetType()}");
                                shapePoint.Select(context.Renderer);
                            }
                            return(context.Renderer.Selected.Count > 0);
                        }
                        else
                        {
                            context.Renderer.Selected.Clear();
                            Log.Info($"Selected Shape Point: {shapePoint.GetType()}");
                            shapePoint.Select(context.Renderer);
                            return(true);
                        }
                    }
                    else if (shape != null)
                    {
                        if (modifier.HasFlag(selectionModifier))
                        {
                            if (context.Renderer.Selected.Contains(shape))
                            {
                                Log.Info($"Deselected Shape: {shape.GetType()}");
                                shape.Deselect(context.Renderer);
                            }
                            else
                            {
                                Log.Info($"Selected Shape: {shape.GetType()}");
                                shape.Select(context.Renderer);
                            }
                            return(context.Renderer.Selected.Count > 0);
                        }
                        else
                        {
                            context.Renderer.Selected.Clear();
                            Log.Info($"Selected Shape: {shape.GetType()}");
                            shape.Select(context.Renderer);
                            return(true);
                        }
                    }
                    else if (guidePoint != null)
                    {
                        if (modifier.HasFlag(selectionModifier))
                        {
                            if (context.Renderer.Selected.Contains(guidePoint))
                            {
                                Log.Info($"Deselected Guide Point: {guidePoint.GetType()}");
                                guidePoint.Deselect(context.Renderer);
                            }
                            else
                            {
                                Log.Info($"Selected Guide Point: {guidePoint.GetType()}");
                                guidePoint.Select(context.Renderer);
                            }
                            return(context.Renderer.Selected.Count > 0);
                        }
                        else
                        {
                            context.Renderer.Selected.Clear();
                            Log.Info($"Selected Guide Point: {guidePoint.GetType()}");
                            guidePoint.Select(context.Renderer);
                            return(true);
                        }
                    }
                    else if (guide != null)
                    {
                        if (modifier.HasFlag(selectionModifier))
                        {
                            if (context.Renderer.Selected.Contains(guide))
                            {
                                Log.Info($"Deselected Guide: {guide.GetType()}");
                                guide.Deselect(context.Renderer);
                            }
                            else
                            {
                                Log.Info($"Selected Guide: {guide.GetType()}");
                                guide.Select(context.Renderer);
                            }
                            return(context.Renderer.Selected.Count > 0);
                        }
                        else
                        {
                            context.Renderer.Selected.Clear();
                            Log.Info($"Selected Guide: {guide.GetType()}");
                            guide.Select(context.Renderer);
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
示例#32
0
 private void ReadPrimitiveArrayData <T>(XElement element, out T[] array, Func <string, T> fromString) where T : struct
 {
     string[] valueStrings = element.Value.Split(new char[] { ',' });
     array = new T[valueStrings.Length];
     try
     {
         for (int i = 0; i < array.Length; i++)
         {
             array[i] = fromString(valueStrings[i]);
         }
     }
     catch (Exception e)
     {
         this.LocalLog.WriteError("Error reading primitive value array of element type {0}: {1}", Log.Type(typeof(T)), Log.Exception(e));
     }
 }
示例#33
0
        public static bool TryToSelect(IToolContext context, SelectionMode mode, SelectionTargets targets, Modifier selectionModifier, Rect2 rect, double radius, Modifier modifier)
        {
            var shapes =
                mode.HasFlag(SelectionMode.Shape) &&
                targets.HasFlag(SelectionTargets.Shapes) ?
                context.HitTest?.TryToGetShapes(context.CurrentContainer.Shapes, rect, radius) : null;

            var guides =
                mode.HasFlag(SelectionMode.Shape) &&
                targets.HasFlag(SelectionTargets.Guides) ?
                context.HitTest?.TryToGetShapes(context.CurrentContainer.Guides, rect, radius) : null;

            if (shapes != null || guides != null)
            {
                if (shapes != null)
                {
                    if (modifier.HasFlag(selectionModifier))
                    {
                        foreach (var shape in shapes)
                        {
                            if (context.Renderer.Selected.Contains(shape))
                            {
                                Log.Info($"Deselected Shape: {shape.GetType()}");
                                shape.Deselect(context.Renderer);
                            }
                            else
                            {
                                Log.Info($"Selected Shape: {shape.GetType()}");
                                shape.Select(context.Renderer);
                            }
                        }
                        return(context.Renderer.Selected.Count > 0);
                    }
                    else
                    {
                        Log.Info($"Selected Shapes: {shapes?.Count ?? 0}");
                        context.Renderer.Selected.Clear();
                        foreach (var shape in shapes)
                        {
                            shape.Select(context.Renderer);
                        }
                        return(true);
                    }
                }
                else if (guides != null)
                {
                    if (modifier.HasFlag(selectionModifier))
                    {
                        foreach (var guide in guides)
                        {
                            if (context.Renderer.Selected.Contains(guide))
                            {
                                Log.Info($"Deselected Guide: {guide.GetType()}");
                                guide.Deselect(context.Renderer);
                            }
                            else
                            {
                                Log.Info($"Selected Guide: {guide.GetType()}");
                                guide.Select(context.Renderer);
                            }
                        }
                        return(context.Renderer.Selected.Count > 0);
                    }
                    else
                    {
                        Log.Info($"Selected Guides: {guides?.Count ?? 0}");
                        context.Renderer.Selected.Clear();
                        foreach (var guide in guides)
                        {
                            guide.Select(context.Renderer);
                        }
                        return(true);
                    }
                }
            }

            return(false);
        }
示例#34
0
        public unsafe void SetupKnife()
        {
            Directory.CreateDirectory(AtlasiSnipe.d_script + @"\Knife");

            try
            {
                byte?[] search1 = new byte?[23]
                {
                  new byte?((byte) 139),
                  new byte?(),
                  new byte?(),
                  new byte?(),
                  new byte?((byte) 131),
                  new byte?(),
                  new byte?((byte) 4),
                  new byte?(),
                  new byte?((byte) 131),
                  new byte?(),
                  new byte?((byte) 12),
                  new byte?((byte) 217),
                  new byte?(),
                  new byte?(),
                  new byte?(),
                  new byte?((byte) 139),
                  new byte?(),
                  new byte?((byte) 217),
                  new byte?(),
                  new byte?(),
                  new byte?(),
                  new byte?((byte) 217),
                  new byte?((byte) 5)
                };
                KnifeRange = (int*)(FindMem(search1, 1, 4194304, 5242880) + search1.Length);
                if ((int)KnifeRange == search1.Length)
                {
                    byte?[] search2 = new byte?[25]
                    {
                        new byte?((byte) 139),
                        new byte?(),
                        new byte?(),
                        new byte?(),
                        new byte?((byte) 131),
                        new byte?(),
                        new byte?((byte) 24),
                        new byte?(),
                        new byte?((byte) 131),
                        new byte?(),
                        new byte?((byte) 12),
                        new byte?((byte) 217),
                        new byte?(),
                        new byte?(),
                        new byte?(),
                        new byte?((byte) 141),
                        new byte?(),
                        new byte?(),
                        new byte?(),
                        new byte?((byte) 217),
                        new byte?(),
                        new byte?(),
                        new byte?(),
                        new byte?((byte) 217),
                        new byte?((byte) 5)
                    };
                    this.KnifeRange = (int*)(FindMem(search2, 1, 4194304, 5242880) + search2.Length);
                    if ((int)this.KnifeRange == search2.Length)
                        this.KnifeRange = null;
                }
                this.DefaultKnifeAddress = *this.KnifeRange;
                byte?[] search3 = new byte?[24]
                {
                  new byte?((byte) 217),
                  new byte?((byte) 92),
                  new byte?(),
                  new byte?(),
                  new byte?((byte) 216),
                  new byte?(),
                  new byte?(),
                  new byte?((byte) 216),
                  new byte?(),
                  new byte?(),
                  new byte?((byte) 217),
                  new byte?((byte) 92),
                  new byte?(),
                  new byte?(),
                  new byte?((byte) 131),
                  new byte?(),
                  new byte?((byte) 1),
                  new byte?((byte) 15),
                  new byte?((byte) 134),
                  new byte?(),
                  new byte?((byte) 0),
                  new byte?((byte) 0),
                  new byte?((byte) 0),
                  new byte?((byte) 217)
                };

                ZeroAddress = (int*)(FindMem(search3, 1, 4194304, 5242880) + search3.Length + 2);
                
                if (!((int)KnifeRange != 0 && DefaultKnifeAddress != 0 && (int)ZeroAddress != 0))
                    Log.Error("Error finding address: NoKnife Plugin will not work");
            }
            catch (Exception ex)
            {
                Log.Error("Error in NoKnife Plugin. Plugin will not work.");
                Log.Error(ex.ToString());
            }

            //looks bad, but actually the else will always be fired "first"
            if (DefaultKnifeAddress == (int)ZeroAddress)
            {
                if (!File.Exists(AtlasiSnipe.d_script + @"\Knife\addr_" + ProcessID))
                {
                    //    print("now it will be feked");
                    Log.Error("Error: NoKnife will not work.");
                    return;
                }

                // print("restoring proper knife addr");

                DefaultKnifeAddress = int.Parse(File.ReadAllText(AtlasiSnipe.d_script + @"\Knife\addr_" + ProcessID));

                //  print("done");

            }
            else
            {
                File.WriteAllText(AtlasiSnipe.d_script + @"\Knife\addr_" + ProcessID, DefaultKnifeAddress.ToString());     //save for when it's feked
            }
        }
示例#35
0
    public override void OnInspectorGUI()
    {
        if (manager == null)
        {
            manager       = (UduinoManager)target;
            baudRateIndex = System.Array.IndexOf(baudRates, manager.BaudRate.ToString());
        }
        Log.SetLogLevel(manager.debugLevel);

        SetColorAndStyles();

        DrawLogo();

        defaultPanel = DrawHeaderTitle("Uduino Settings", defaultPanel, headerColor);

        if (defaultPanel)
        {
            CheckCompatibility();

            GUILayout.Label("General", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;
            manager.debugLevel = (LogLevel)EditorGUILayout.EnumPopup("Log Level", manager.debugLevel);
            EditorGUI.indentLevel--;
            GUILayout.Label("Arduino", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;

            baudRateIndex = EditorGUILayout.Popup("Baud Rate", baudRateIndex, baudRates);
            if (prevBaudRateIndex != baudRateIndex)
            {
                int result = 9600;
                int.TryParse(baudRates[baudRateIndex], out result);
                manager.BaudRate  = result;
                prevBaudRateIndex = baudRateIndex;
            }

            manager.ReadOnThread = EditorGUILayout.Toggle("Read on threads", manager.ReadOnThread);
            EditorGUI.indentLevel--;

            GUILayout.Label("Messages", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;
            if (manager.LimitSendRate = EditorGUILayout.Toggle("Limit Send Rate", manager.LimitSendRate))
            {
                if (manager.LimitSendRate)
                {
                    manager.SendRateSpeed = EditorGUILayout.IntField("Send Rate speed", manager.SendRateSpeed);
                    EditorGUILayout.Separator();
                }
            }

            EditorGUI.indentLevel--;

            EditorGUILayout.Separator();
        }

        arduinoPanel = DrawHeaderTitle("Adruino", arduinoPanel, headerColor);
        if (arduinoPanel)
        {
            ArduinoSetings();
        }

        advancedPanel = DrawHeaderTitle("Advanced", advancedPanel, headerColor);
        if (advancedPanel)
        {
            AdvancedSettings();
        }

        // if (GUI.changed)
        EditorUtility.SetDirty(target);
    }
示例#36
0
 public override State Stop()
 {
     Log.V("Handling stop, state: '{0}'", this);
     return(Complete(new Stopped(this)));
 }
示例#37
0
        protected override bool UnPacket(byte[] recv_all)
        {
            int bLen = recv_all.Length;

            //RecvPackage = Encoding.UTF8.GetString(recv_all);
            RecvPackage = Encoding.GetEncoding("GBK").GetString(recv_all);
            Log.Info("recv packet : " + RecvPackage);

            bool ret = false;

            if (string.IsNullOrEmpty(RecvPackage))
            {
                return(ret);
            }
            try
            {
                int pos = 0;
                _entity.ReturnCode = getEveryField(pos, recv_all, 2);
                pos += 2;
                if (_entity.ReturnCode != "00")
                {
                    _entity.ReturnMsg = _entity.GetReturnMsg(_entity.ReturnCode);
                    return(ret);
                }

                _entity.CardNO       = getEveryField(pos, recv_all, 8);
                pos                 += 8;
                _entity.Addr         = getEveryField(pos, recv_all, 64);
                pos                 += 64;
                _entity.UserName     = getEveryField(pos, recv_all, 64);
                pos                 += 64;
                _entity.CompanyCode  = getEveryField(pos, recv_all, 2);
                pos                 += 2;
                _entity.PastBalance  = double.Parse(getEveryField(pos, recv_all, 11).Trim());
                pos                 += 11;
                _entity.TotalArrears = double.Parse(getEveryField(pos, recv_all, 11).Trim());
                pos                 += 11;
                int times = int.Parse(getEveryField(pos, recv_all, 2).Trim());
                pos += 2;
                if (times > 0)
                {
                    for (int i = 0; i < times; i++)
                    {
                        UserInfo u = new UserInfo();
                        u.FeeType          = getEveryField(pos, recv_all, 16);
                        pos               += 16;
                        u.HeatingPeriod    = getEveryField(pos, recv_all, 9);
                        pos               += 9;
                        u.Area             = double.Parse(getEveryField(pos, recv_all, 11));
                        pos               += 11;
                        u.Price            = double.Parse(getEveryField(pos, recv_all, 7));
                        pos               += 7;
                        u.ReceivableAmount = double.Parse(getEveryField(pos, recv_all, 11));
                        pos               += 11;
                        u.amountOwed       = double.Parse(getEveryField(pos, recv_all, 11));
                        pos               += 11;

                        _entity.userInfoList.Add(u);
                    }
                }
                ret = true;
            }
            catch (Exception ex)
            {
                Log.Error("[" + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "][" + System.Reflection.MethodBase.GetCurrentMethod().Name + "] err" + ex);
            }
            return(ret);
        }
示例#38
0
 public override void OnEnter(State prev)
 {
     Log.V("Entering state: {0}", this);
     Fsm.NotifyEnterAwaiting();
 }
示例#39
0
 public override State Start()
 {
     Log.V("Handling start, state: {0}", this);
     return(Complete(new Connecting(this)));
 }
示例#40
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static void validate(org.neo4j.kernel.configuration.Config config, org.neo4j.logging.Log log) throws org.neo4j.graphdb.config.InvalidSettingException
		 public static void Validate( Config config, Log log )
		 {
			  LoadBalancingPlugin plugin = FindPlugin( config );
			  plugin.Validate( config, log );
		 }
        internal void DebugLogChances()
        {
            var sb = new StringBuilder();

            foreach (var defEvent in DefDatabase <EventDef> .AllDefsListForReading)
            {
                var         outComeOne   = 0;
                var         outComeTwo   = 0;
                var         outComeThree = 0;
                const float pawnsToTest  = 1000;
                float       skill        = 0;

                double mean     = 0;
                double variance = 0;
                double stdDev   = 0;
                double min      = 0;
                double max      = 0;

                sb.AppendLine(defEvent.LabelCap);

                for (var i = 0; i < pawnsToTest; i++)
                {
                    var bestpawn = PawnGenerator.GeneratePawn(PawnKindDefOf.Colonist, Faction.OfPlayer);

                    while (defEvent.relevantStat.Worker.IsDisabledFor(bestpawn))
                    {
                        bestpawn = PawnGenerator.GeneratePawn(PawnKindDefOf.Colonist, Faction.OfPlayer);
                    }

                    skill += bestpawn.GetStatValue(defEvent.relevantStat);

                    var placement = DeterminePlacementFor(bestpawn, defEvent, out mean, out variance, out stdDev,
                                                          out max, out min);
                    switch (placement)
                    {
                    case Placement.First:
                        outComeOne++;
                        break;

                    case Placement.Second:
                        outComeTwo++;
                        break;

                    case Placement.Third:
                        outComeThree++;
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }

                sb.AppendLine(
                    $"Chances for {pawnsToTest} pawns with stat {defEvent.relevantStat} @ {skill / pawnsToTest}:" +
                    $" first: {(outComeOne / pawnsToTest).ToStringPercent()}, " +
                    $" second: {(outComeTwo / pawnsToTest).ToStringPercent()}, " +
                    $" third: {(outComeThree / pawnsToTest).ToStringPercent()} " +
                    $" mean: {mean}, variance: {variance}, stdDev: {stdDev}, min: {min}, max: {max}");
            }

            Log.Error(sb.ToString(), true);
        }
示例#42
0
		public void InflictDamage(Actor self, Actor attacker, Damage damage, bool ignoreModifiers)
		{
			// Overkill! Don't count extra hits as more kills!
			if (IsDead)
				return;

			var oldState = DamageState;

			// Apply any damage modifiers
			if (!ignoreModifiers && damage.Value > 0)
			{
				var modifiers = damageModifiers
					.Concat(damageModifiersPlayer)
					.Select(t => t.GetDamageModifier(attacker, damage));

				damage = new Damage(Util.ApplyPercentageModifiers(damage.Value, modifiers), damage.DamageTypes);
			}

			hp = (hp - damage.Value).Clamp(0, MaxHP);

			var ai = new AttackInfo
			{
				Attacker = attacker,
				Damage = damage,
				DamageState = DamageState,
				PreviousDamageState = oldState,
			};

			foreach (var nd in notifyDamage)
				nd.Damaged(self, ai);
			foreach (var nd in notifyDamagePlayer)
				nd.Damaged(self, ai);

			if (DamageState != oldState)
				foreach (var nd in notifyDamageStateChanged)
					nd.DamageStateChanged(self, ai);

			if (Info.NotifyAppliedDamage && attacker != null && attacker.IsInWorld && !attacker.IsDead)
			{
				foreach (var nd in attacker.TraitsImplementing<INotifyAppliedDamage>())
					nd.AppliedDamage(attacker, self, ai);
				foreach (var nd in attacker.Owner.PlayerActor.TraitsImplementing<INotifyAppliedDamage>())
					nd.AppliedDamage(attacker, self, ai);
			}

			if (hp == 0)
			{
				foreach (var nd in notifyKilled)
					nd.Killed(self, ai);
				foreach (var nd in notifyKilledPlayer)
					nd.Killed(self, ai);

				if (RemoveOnDeath)
					self.Dispose();

				if (attacker == null)
					Log.Write("debug", "{0} #{1} was killed.", self.Info.Name, self.ActorID);
				else
					Log.Write("debug", "{0} #{1} killed by {2} #{3}", self.Info.Name, self.ActorID, attacker.Info.Name, attacker.ActorID);
			}
		}
        public override bool Execute()
        {
            bool isWebassembly = InputFiles.Contains("_bin");

            string aspnetCoreComponentsPath = null;
            string outputPath = null;

            List <string> otherFiles = new List <string>();

            if (isWebassembly)
            {
                foreach (var file in Directory.GetFiles(InputFiles, "*.dll"))
                {
                    if (file.EndsWith("Microsoft.AspNetCore.Components.dll", StringComparison.InvariantCultureIgnoreCase))
                    {
                        aspnetCoreComponentsPath = file;
                        outputPath = $"{file}.patched";
                    }
                    else
                    {
                        otherFiles.Add(file);
                    }
                }
            }
            else
            {
                foreach (var file in References.Select(x => x.ItemSpec))
                {
                    if (file.EndsWith("Microsoft.AspNetCore.Components.dll", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (file.Contains("dotnet"))
                        {
                            var dotnetpath = file.Substring(0, file.LastIndexOf("dotnet") + 6);

                            var latest = Directory.GetDirectories(Path.Combine(dotnetpath, "shared", "Microsoft.AspNetCore.App")).Last();
                            aspnetCoreComponentsPath = Path.Combine(latest, Path.GetFileName(file));
                        }
                        else
                        {
                            aspnetCoreComponentsPath = file;
                        }

                        Log.LogWarning(aspnetCoreComponentsPath);
                        outputPath = Path.Combine(InputFiles, $"{Path.GetFileName(file)}.patched");
                    }
                    else
                    {
                        if (file.EndsWith("Microsoft.Extensions.DependencyInjection.Abstractions.dll", StringComparison.InvariantCultureIgnoreCase))
                        {
                            Log.LogWarning(file);
                        }
                        otherFiles.Add(file);
                    }
                }
            }

            try
            {
                using (var assemblyPatcher = new AssemblyPatcher(aspnetCoreComponentsPath, outputPath, otherFiles.ToArray(), true))
                {
                    assemblyPatcher.Run();
                }
                var targetFileName = outputPath.Replace(".patched", "");
                File.Delete(targetFileName);
                File.Move(outputPath, targetFileName);
                return(true);
            }
            catch (Exception ex)
            {
                this.Log.LogError($"There was an error patching Microsoft.AspNetCore.Components.dll. The error is: {ex.Message}");
                this.Log.LogError($"Stack trace: {ex.StackTrace}");
            }
            return(false);
        }
示例#44
0
 private void RenderLoggingSettings() {
   using (new UnityEngine.GUILayout.HorizontalScope()) {
     UnityEngine.GUILayout.Label(text : "Verbose level:");
     if (UnityEngine.GUILayout.Button(text    : "←",
                                      options : GUILayoutWidth(2))) {
       Log.SetVerboseLogging(Math.Max(verbose_logging_ - 1, 0));
       verbose_logging_ = Log.GetVerboseLogging();
     }
     UnityEngine.GUILayout.TextArea(
         text    : Log.GetVerboseLogging().ToString(),
         options : GUILayoutWidth(2));
     if (UnityEngine.GUILayout.Button(text    : "→",
                                      options : GUILayoutWidth(2))) {
       Log.SetVerboseLogging(Math.Min(verbose_logging_ + 1, 4));
       verbose_logging_ = Log.GetVerboseLogging();
     }
   }
   float column_width = Width(3);
   var gui_layout_column_width = GUILayoutWidth(3);
   using (new UnityEngine.GUILayout.HorizontalScope()) {
     UnityEngine.GUILayout.Space(column_width);
     UnityEngine.GUILayout.Label(text    : "Log",
                                 options : gui_layout_column_width);
     UnityEngine.GUILayout.Label(text    : "stderr",
                                 options : gui_layout_column_width);
     UnityEngine.GUILayout.Label(text    : "Flush",
                                 options : gui_layout_column_width);
   }
   using (new UnityEngine.GUILayout.HorizontalScope()) {
     UnityEngine.GUILayout.Space(column_width);
     if (UnityEngine.GUILayout.Button(text    : "↑",
                                      options : gui_layout_column_width)) {
       Log.SetSuppressedLogging(Math.Max(suppressed_logging_ - 1, 0));
       suppressed_logging_ = Log.GetSuppressedLogging();
     }
     if (UnityEngine.GUILayout.Button(text    : "↑",
                                      options : gui_layout_column_width)) {
       Log.SetStderrLogging(Math.Max(stderr_logging_ - 1, 0));
       stderr_logging_ = Log.GetStderrLogging();
     }
     if (UnityEngine.GUILayout.Button(text    : "↑",
                                      options : gui_layout_column_width)) {
       Log.SetBufferedLogging(Math.Max(buffered_logging_ - 1, -1));
       buffered_logging_ = Log.GetBufferedLogging();
     }
   }
   for (int severity = 0; severity <= 3; ++severity) {
     using (new UnityEngine.GUILayout.HorizontalScope()) {
       UnityEngine.GUILayout.Label(
           text    : Log.severity_names[severity],
           options : gui_layout_column_width);
       UnityEngine.GUILayout.Toggle(
           value   : severity >= Log.GetSuppressedLogging(),
           text    : "",
           options : gui_layout_column_width);
       UnityEngine.GUILayout.Toggle(
           value   : severity >= Log.GetStderrLogging(),
           text    : "",
           options : gui_layout_column_width);
       UnityEngine.GUILayout.Toggle(
           value   : severity > Log.GetBufferedLogging(),
           text    : "",
           options : gui_layout_column_width);
     }
   }
   using (new UnityEngine.GUILayout.HorizontalScope()) {
     UnityEngine.GUILayout.Space(column_width);
     if (UnityEngine.GUILayout.Button(text    : "↓",
                                      options : gui_layout_column_width)) {
       Log.SetSuppressedLogging(Math.Min(suppressed_logging_ + 1, 3));
       suppressed_logging_ = Log.GetSuppressedLogging();
     }
     if (UnityEngine.GUILayout.Button(text    : "↓",
                                      options : gui_layout_column_width)) {
       Log.SetStderrLogging(Math.Min(stderr_logging_ + 1, 3));
       stderr_logging_ = Log.GetStderrLogging();
     }
     if (UnityEngine.GUILayout.Button(text    : "↓",
                                      options : gui_layout_column_width)) {
       Log.SetBufferedLogging(Math.Min(buffered_logging_ + 1, 3));
       buffered_logging_ = Log.GetBufferedLogging();
     }
   }
   using (new UnityEngine.GUILayout.HorizontalScope()) {
     must_record_journal_ = UnityEngine.GUILayout.Toggle(
         value   : must_record_journal_,
         text    : "Record journal (starts on load)");
     UnityEngine.GUILayout.Label(
         "Journaling is " + (journaling_ ? "ON" : "OFF"),
         style : Style.Info(Style.RightAligned(UnityEngine.GUI.skin.label)));
   }
   if (journaling_ && !must_record_journal_) {
     // We can deactivate a recorder at any time, but in order for replaying to
     // work, we should only activate one before creating a plugin.
     journaling_ = false;
     Interface.ActivateRecorder(false);
   }
 }
示例#45
0
  public override void Load(ConfigNode node) {
    base.Load(node);

    string show_ksp_features_value =
        node.GetAtMostOneValue("show_ksp_features");
    if (show_ksp_features_value != null) {
      show_ksp_features_ = Convert.ToBoolean(show_ksp_features_value);
    }
    string show_logging_settings_value =
        node.GetAtMostOneValue("show_logging_settings");
    if (show_logging_settings_value != null) {
      show_logging_settings_ = Convert.ToBoolean(show_logging_settings_value);
    }
    string show_prediction_settings_value =
        node.GetAtMostOneValue("show_prediction_settings");
    if (show_prediction_settings_value != null) {
      show_prediction_settings_ =
          Convert.ToBoolean(show_prediction_settings_value);
    }

    string history_length_value =
        node.GetAtMostOneValue("history_length");
    if (history_length_value != null) {
      history_length_.value = Convert.ToDouble(history_length_value);
    }

    string buffered_logging_value =
        node.GetAtMostOneValue("buffered_logging");
    if (buffered_logging_value != null) {
      buffered_logging_ = Convert.ToInt32(buffered_logging_value);
    }
    string stderr_logging_value = node.GetAtMostOneValue("stderr_logging");
    if (stderr_logging_value != null) {
      stderr_logging_ = Convert.ToInt32(stderr_logging_value);
    }
    string suppressed_logging_value =
        node.GetAtMostOneValue("suppressed_logging");
    if (suppressed_logging_value != null) {
      suppressed_logging_ = Convert.ToInt32(suppressed_logging_value);
    }
    string verbose_logging_value = node.GetAtMostOneValue("verbose_logging");
    if (verbose_logging_value != null) {
      verbose_logging_ = Convert.ToInt32(verbose_logging_value);
    }

    string must_record_journal_value =
        node.GetAtMostOneValue("must_record_journal");
    if (must_record_journal_value != null) {
      must_record_journal_ = Convert.ToBoolean(must_record_journal_value);
    }

    Log.SetBufferedLogging(buffered_logging_);
    Log.SetSuppressedLogging(suppressed_logging_);
    Log.SetStderrLogging(stderr_logging_);
    Log.SetVerboseLogging(verbose_logging_);

    if (must_record_journal_) {
      journaling_ = true;
      Log.ActivateRecorder(true);
    }
  }
示例#46
0
        protected override void OnCreate(Bundle savedInstanceState)
        {

            string appDirectory;
            string newDirectory;
            string textFilePath;
            string text;
            IEnumerable entries;
            IEnumerable files;

            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

            Button read = FindViewById<Button>(Resource.Id.button1);
            Button write = FindViewById<Button>(Resource.Id.button2);
            Button log = FindViewById<Button>(Resource.Id.button3);
            Button readLog = FindViewById<Button>(Resource.Id.button4);
            EditText editText = FindViewById<EditText>(Resource.Id.editText1);
            EditText textArea = FindViewById<EditText>(Resource.Id.editText2);

            FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.fab);
            fab.Click += delegate
            {

                //Grab the app storage directory
                // In this case we're going to use the external files directory becasue android devices have limited storage in terms of the app storage area
                appDirectory = Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath;
                entries = Directory.EnumerateDirectories(appDirectory);
                files = Directory.EnumerateFiles(appDirectory);

                //The following method takes an absolute path and appends another item to it which can be a folder (and creates the foñder) or a file (if it ends with a ".'extension'", so it creates a file)
                newDirectory = Path.Combine(appDirectory, "myDirectory");

                Directory.CreateDirectory(newDirectory); //Creates if it doesn't exists

                textFilePath = Path.Combine(appDirectory, "myTXT.txt");
                File.CreateText(textFilePath);

                foreach(var e in entries)
                {
                    Log.Debug("DEBUG", e.ToString());
                }

                foreach (var e in files)
                {
                    Log.Debug("DEBUG", e.ToString());
                }

                //Unless you really, really, relly have to, never use the internal storage

            };

            read.Click += delegate
            {
                appDirectory = Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath;
                textFilePath = Path.Combine(appDirectory, "myTXT.txt");
                text = File.ReadAllText(textFilePath);
                textArea.Text = text;
            };

            write.Click += delegate
            {
                appDirectory = Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath;
                textFilePath = Path.Combine(appDirectory, "myTXT.txt");
                File.AppendAllText(textFilePath, editText.Text);
                editText.Text = "";
            };

            log.Click += delegate
            {
                Toast.MakeText(this, "Creating log...", ToastLength.Short).Show();
                appDirectory = Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath;
                textFilePath = Path.Combine(appDirectory, "log.txt");
                File.WriteAllText(textFilePath, "");

                Task.Factory.StartNew(() => { //Let's create a new thread

                    RunOnUiThread(() => {
                        readLog.Enabled = false; //We're trying to acces a button which lies on th UI thread and we're running our whole taks into a separate thread. Let's make this run back on the main thread
                    });
                    
                    for (int i = 0; i < 5; i++)
                    {
                        File.AppendAllText(textFilePath, DateTime.Now.ToString() + "\n");
                        Thread.Sleep(1000);
                    }

                    RunOnUiThread(() => {
                        readLog.Enabled = true;
                    });

                });
            };

            readLog.Click += delegate
            {
                appDirectory = Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath;
                textFilePath = Path.Combine(appDirectory, "log.txt");
                text = File.ReadAllText(textFilePath);
                Log.Debug("FILE", text);
                AlertDialog.Builder alert = new Android.App.AlertDialog.Builder(this);
                alert.SetTitle("Log records");
                alert.SetMessage(text);
                alert.Show();
            };
        }
示例#47
0
        /// <summary>
        /// Dies Methode hält die Kommuniktion mit dem Client aufrecht, um den Synchronisierungsfortschritt
        /// pro Foto in den Ausgabefluss zu schreiben
        /// </summary>
        /// <param name="stream">Der Stream mit dem Client</param>
        /// <param name="content">Der Inhalt des Streams. Wird nicht verwendet, ist aber für den Aufruf erfordern</param>
        /// <param name="context">Der Context der Verbindung. Wird nicht verwendet, ist aber für den Aufruf erfordern</param>
        /// <remarks>Es ist nicht sichergestellt, dass die Verbindung offen bleibt. Außerdem ist unklar wie die Browser auf den
        /// Flush reaagieren, so dass das Parsen der einzelnen Fortschirttinformatioen <see cref="SynchProgress"/> nicht klar ist</remarks>
        public void OnStreamAvailable(Stream stream, HttpContent content, TransportContext context)
        {
            try
            {
                var serializer = new JsonSerializer();
                var memberId = GetMemberId();
                bool streamIsOpen = true;
                foreach (var currentStep in _connector.RefreshFolderContent())
                {
                    try
                    {
                        NotificationHub.PushNotification(new Notification()
                        {
                            Data = currentStep,
                            Type = NotificationType.PhotoSynch,
                            Date = DateTime.Now,
                            MemberId = memberId,
                            PhotoName = currentStep.Photo == null ? string.Empty : currentStep.Photo.Name,
                            PhotoTitle  = currentStep.Photo == null ? string.Empty : currentStep.Photo.Title 
                        });

                        if (currentStep.Photo != null)
                        {
                            SavePhotosToDatabase(currentStep.Photo);
                        }

                        if (!streamIsOpen) continue;

                        using (var writer = new StreamWriter(stream))
                        {
                            if (currentStep.Photo != null)
                            {
                                dynamic currentPhoto = new
                                {
                                    currentStep.Photo.Id,
                                    currentStep.Photo.Title,
                                    currentStep.Photo.Name,
                                    currentStep.Photo.OriginalName,
                                    currentStep.Photo.MemberId,
                                    currentStep.Photo.IsPrivate,
                                    DirectLinks = currentStep.Photo.DirectLinks.Where(l => l.Size <= 400).ToList(),
                                    currentStep.Photo.Color
                                };
                                dynamic progress = new
                                {
                                    currentStep.TotalFileCount,
                                    currentStep.Index,
                                    Photo = currentPhoto
                                };
                                var returnValue = new Result<object>() { Data = progress };
                                serializer.Serialize(writer, returnValue);
                            }
                            else
                            {
                                var returnValue = new Result<SynchProgress> { Data = currentStep };
                                serializer.Serialize(writer, returnValue);
                            }
                            stream.Flush();
                        }
                    }

                    catch (HttpException ex)
                    {
                        // Die Verbindung zum Client wurde unterbrochen, die Synchronisierung läuft jedoch weiter
                        if (ex.ErrorCode == -2147023667)
                        {
                            streamIsOpen = false;
                        }
                    }
                }
                var notification = new Notification()
                {
                    Type = NotificationType.PhotoSynch,
                    MemberId = memberId,
                    UserAlias = "fotosteam"
                };
                DataRepository.Add(notification);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                var error = new Result<SynchProgress> { Data = new SynchProgress() };
                error.Status.Code = Controller.StatusCode.Failure;
                error.Status.Message = ResultMessages.UnhandledException;
                try
                {
                    using (var writer = new StreamWriter(stream))
                    {
                        var serializer = new JsonSerializer();
                        serializer.Serialize(writer, error);

                    }
                }
                catch (Exception ex1)
                {
                    //Da können wir jetzt auch nicht mehr machen.
                    Log.Error(ex1);
                }

            }
            finally
            {
                // Close output stream as we are done
                stream.Close();
            }
        }
示例#48
0
 public static void CloseAndFlush()
 {
     Log.CloseAndFlush();
 }
 private void Client_Ready(object sender, EventArgs e)
 {
     Log.Information("Discord Connected!");
 }