/// <summary> /// Log写入 /// </summary> /// <param name="logBean"></param> public void WriteLog(MsgLevel level, string message) { switch (level) { case MsgLevel.Debug: basicLog?.Debug(message); break; case MsgLevel.Info: basicLog?.Info(message); break; case MsgLevel.Warn: basicLog?.Warn(message); break; case MsgLevel.Error: errLog?.Error(message); break; case MsgLevel.Fatal: errLog?.Fatal(message); break; } }
public void WriteLog(LogEnum name, LogLevel level, string logContent) { log = log4net.LogManager.GetLogger(name.ToString()); //log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); switch (level) { case LogLevel.DEBUG: log.Debug(logContent); break; case LogLevel.ERROR: log.Error(logContent); break; case LogLevel.FATAL: log.Fatal(logContent); break; case LogLevel.INFO: log.Info(logContent); break; case LogLevel.WARN: log.Warn(logContent); break; default: log.Debug(logContent); break; } }
/// <summary> /// Initialize a new instance of <see cref="Protocol" />. /// </summary> /// <param name="server">Server address to connect to.</param> /// <param name="port">Server port.</param> public Protocol(string server, int port) { _log = LogManager.GetLogger(this); _log.Debug("Connecting to server."); _tcpClient = new TcpClient(); _tcpClient.Connect(server, port); _log.Debug("Getting stream."); _stream = _tcpClient.GetStream(); _log.Debug("Initializing tools."); _tools = new NetworkTools(_stream); }
public PacketListener(Protocol protocol) { _log = LogManager.GetLogger(this); _log.Debug("Setting protocol..."); _protocol = protocol; _log.Debug("Creating packet listen thread..."); _listenThread = new Thread(ReadPackets) {Name = "PacketListen", IsBackground = true}; _log.Debug("Starting packet listen thread..."); _running = true; _listenThread.Start(); _log.Info("Packet listen thread started!"); }
/// <summary> /// Initialize a new instance of <c>DebugDisplay</c>. /// </summary> /// <param name="game">The game instance.</param> /// <param name="graphics">The graphics device manager.</param> internal DebugDisplay(Game game, GraphicsDeviceManager graphics) : base(game) { _log = LogManager.GetLogger(this); _log.Debug("DebugDisplay created!"); _graphics = graphics; _content = new ContentManager(game.Services, Constants.ContentDirectory); _log.Debug("Creating FrameRateDisplay..."); game.Components.Add(new FrameRateDisplay(game)); _log.Debug("Creating UserInfoDisplay..."); game.Components.Add(new UserInfoDisplay(game)); game.Exiting += (s, e) => UnloadContent(); }
public void Debug(string str, [CallerLineNumber] int lineNumber = 0, [CallerMemberName] string caller = null, [CallerFilePath] string filepath = null) { logger?.Debug(Bake(str, lineNumber, caller, filepath)); }
public AudioManager(bool hardware = true) { _log = Logging.LogManager.GetLogger(this); _log.Info("Initializing AudioManager..."); _log.Info("Creating FMOD system..."); uint version = 0; RESULT result = Factory.System_Create(ref _system); ErrCheck(result); _log.Debug("Checking FMOD version..."); result = _system.getVersion(ref version); ErrCheck(result); if (version < VERSION.number) { var msg = string.Format("Error! You are using an old version of FMOD: {0}. This program requires: {1}.", version.ToString("X"), VERSION.number.ToString("X")); _log.Fatal(msg); throw new FMODException(msg); } result = _system.init(MaxChannels, INITFLAGS.NORMAL, (IntPtr) null); ErrCheck(result); _soundManager = new SoundManager(_system, hardware); _songManager = new SongManager(_system, hardware); _log.Info("AudioManager initialized!"); }
public TextManager(Map map) { _log = Logging.LogManager.GetLogger(this); _log.Info("TextManager is loading map text entries..."); _texts = new List<Text>(); _activeText = null; if (!map.HasLayer("text")) { _log.Info("No text layer detected on map, aborting..."); return; } foreach (var obj in map.FindObjects((l, o) => l.Name == "text")) { string title = obj.Properties.ContainsKey("title") ? obj.Properties["title"] : "<No Title>"; string subtitle = obj.Properties.ContainsKey("subtitle") ? obj.Properties["subtitle"] : null; _log.DebugFormat("Adding new text {0} of type {1}", obj.Name, obj.Type); _texts.Add(new Text(obj.Bounds, obj.Name, obj.Type, title, subtitle)); } _log.Debug("TextManager initialized!"); }
/* * Constructor for Google Maps API utilities */ public GoogleMapsEngineAPI(ref log4net.ILog log) { // establish the Google APIs project key this.GOOGLE_API_KEY = Properties.Settings.Default.gme_api_key; // establish the Google Maps Engine API settings this.GME_API_PROTOCOL = Properties.Settings.Default.gme_api_protocol; this.GME_API_DOMAIN = Properties.Settings.Default.gme_api_domain; this.GME_API_SERVICE = Properties.Settings.Default.gme_api_service; this.GME_API_VERSION = Properties.Settings.Default.gme_api_version; // set the log this.log = log; // retrieve a reference to the extension log.Debug("Retrieiving a reference to the extension object."); ext = GoogleMapsEngineToolsExtensionForArcGIS.GetExtension(); // create a Google Maps Engine Session Id for this set of sessions GoogleMapsEngineAPISessionId = Guid.NewGuid(); // if debug, create a debug folder to keep track of information if (log.IsDebugEnabled) { // create a temporary folder debugDirectory = System.IO.Directory.CreateDirectory( ext.getLocalWorkspaceDirectory() + "\\GME_API_TMP_" + GoogleMapsEngineAPISessionId.ToString().Replace("-","")); } }
internal FrameRateDisplay(Game game) : base(game) { _log = LogManager.GetLogger(this); _log.Debug("FrameRateDisplay created!"); _content = new ContentManager(game.Services, Constants.ContentDirectory); game.Exiting += (s, e) => UnloadContent(); }
protected BaseGameState(Game game, GameStateManager manager) : base(game, manager) { Log = LogManager.GetLogger(this); Log.Debug("Constructing GameState... (" + GetType() + ")"); Log = LogManager.GetLogger(this); GameRef = (MainGame) game; PlayerIndexInControl = PlayerIndex.One; }
internal UserInfoDisplay(Game game) : base(game) { _log = LogManager.GetLogger(this); _log.Debug("UserInfoDisplay created!"); _sc = (Sharpcraft) game; _content = new ContentManager(game.Services, Constants.ContentDirectory); game.Exiting += (s, e) => UnloadContent(); }
internal SoundManager(FMOD.System system, bool hardware = true) { _log = Logging.LogManager.GetLogger(this); _log.Info("Initializing SoundManager..."); _system = system; _sounds = new List<Sound>(); _soundMode = hardware ? MODE.HARDWARE : MODE.SOFTWARE; _log.DebugFormat("Sound Mode == {0}", _soundMode); _log.Debug("SoundManager initialized!"); }
static CheckBaseData() { log = log4net.LogManager.GetLogger(typeof(CheckBaseData)); #if !DEBUG tmr = new System.Timers.Timer(1000 * 20) { AutoReset = false }; tmr.Elapsed += tmr_Elapsed; tmr.Start(); log.Debug("开始"); #endif }
/// <summary> /// Initialize a new Minecraft client. /// </summary> /// <param name="server">The server to connect to.</param> /// <param name="player">The player who logged in with the client.</param> public Client(Server server, Player player) { _log = LogManager.GetLogger(this); _log.Debug("Minecraft Client created!"); _server = server; _log.Debug("Loading Items from file..."); try { using (var reader = new StreamReader(Constants.MinecraftItemFile)) Items = new JsonSerializer().Deserialize<List<Item>>(new JsonTextReader(reader)); } catch(IOException ex) { _log.Error("Failed to read item list from file!"); _log.Error(ex.GetType() + ": " + ex.Message); _log.Error("Stack Trace:\n" + ex.StackTrace); throw new Exception("Sharpcraft.Library.Minecraft.Client failed to initialize! Could not read item list file!", ex); } _log.Debug("Creating communication protocol..."); _protocol = new Protocol(_server.Address, _server.Port); _log.Info("Client initiated on " + _server.Address + ":" + _server.Port + "!"); _player = player; _world = new World(); }
internal SongManager(FMOD.System system, bool hardware = true) { _log = Logging.LogManager.GetLogger(this); _log.Info("Initializing SongManager..."); _system = system; _songs = new List<Song>(); // ReSharper disable BitwiseOperatorOnEnumWihtoutFlags if (hardware) _soundMode = MODE._2D | MODE.HARDWARE | MODE.CREATESTREAM; else _soundMode = MODE._2D | MODE.SOFTWARE | MODE.CREATESTREAM; // ReSharper restore BitwiseOperatorOnEnumWihtoutFlags _log.DebugFormat("Sound Mode == {0}", _soundMode); _log.Debug("SongManager initialized!"); }
internal ControlsManager(string file) { _log = LogManager.GetLogger(this); if (File.Exists(file)) { _log.Info("Loading controls from " + file + "..."); Controls = Serializer.JsonDeserialize<Controls>(file); _log.Debug("Controls loaded!"); } else { Controls = new Controls(); SetDefaultControls(); _log.Debug("Saving controls to " + SettingsFile + "..."); Serializer.JsonSerialize(Controls, SettingsFile); } CheckControls(); }
private void LogMsg(String msg) { log.Debug(msg); }
/// <summary> /// Initializes a new instance of Sharpcraft. /// </summary> public Sharpcraft(User user) { _log = LogManager.GetLogger(this); _settings = new GameSettings(Constants.GameSettings); _user = user; if (File.Exists(Constants.GameSettings)) { _log.Info("Loading game settings from file..."); var reader = new StreamReader(Constants.GameSettings); _settings = new JsonSerializer().Deserialize<GameSettings>(new JsonTextReader(reader)); _log.Info("Game settings loaded successfully!"); reader.Close(); } else { _settings = new GameSettings(Constants.GameSettings) {Size = new Point(1280, 720)}; } _log.Debug("Initializing graphics device."); _graphics = new GraphicsDeviceManager(this); if (_settings.Fullscreen) { _graphics.IsFullScreen = true; _settings.Size = new Point(SystemInformation.PrimaryMonitorSize.Width, SystemInformation.PrimaryMonitorSize.Height); } _graphics.PreferredBackBufferWidth = _settings.Size.X; _graphics.PreferredBackBufferHeight = _settings.Size.Y; _log.Debug("Setting content directory."); Content.RootDirectory = Constants.ContentDirectory; _log.Debug("Creating DebugDisplay..."); Components.Add(new DebugDisplay(this, _graphics)); #if DEBUG _gameMenuOpen = true; #endif }
public int AddSupplierType(SupplierTypeDTO dto) { int id = 0; try { log.Debug(SupplierTypeDTO.FormatSupplierTypeDTO(dto)); R_SupplierType t = SupplierTypeDTO.ConvertDTOtoEntity(dto); // add id = Repository.AddSupplierType(t); dto.SupplierTypeId = id; log.Debug("result: 'success', id: " + id); } catch (System.Exception e) { // error log.Error(e.ToString()); throw; } return(id); }
/// <summary> /// Initializes a new Steam GUI. /// </summary> public SteamGUI() { InitializeComponent(); _log = LogManager.GetLogger(this); _log.Info("SteamGUI is initializing..."); _steamClosed = false; sendButton.Enabled = false; nameLabel.Text = SteamManager.GetName(); statusLabel.Text = SteamManager.GetStatus(true); friendsLabel.Text = string.Format(FriendFormat, SteamManager.FriendList.GetFriendCount(true), SteamManager.FriendList.GetFriendCount()); foreach (var friend in SteamManager.FriendList.GetFriends()) { var item = new ListViewItem(new[] { friend.GetName(), friend.GetStatus(true) }) { Tag = friend.SteamID }; friendList.Items.Add(item); } SteamManager.FriendList.OnFriendsUpdate += UpdateData; _log.Debug("SteamGUI is registering to OnSteamClose event..."); SteamManager.OnSteamClose += SteamClose; _log.Debug("SteamGUI is registering to OnMinecraftData event..."); SteamManager.OnMinecraftData += UpdateMinecraftdata; _log.Info("SteamGUI loaded!"); }
public virtual void Shutdown() { Log.Debug("Imgur Plugin shutdown."); Language.LanguageChanged -= OnLanguageChanged; }
public virtual void Shutdown() { LOG.Debug("Office Plugin shutdown."); }
/************************************************************ Student Passers **/ public Student InsertStudent(string fname, string lname) { try { log.Debug("Student_" + fname + "-" + lname + "_Inserted"); return(studentSql.InsertStudent(fname, lname)); } catch (Exception e) { log.Error("Insert Student(fname, lname) Butler Failure", e); return(studentSql.FailedStudentQuery()); } }
public async Task UserFound() { // image to load into left image BitmapImage logo = new BitmapImage(); String luisResult = ""; do { String mensajeTemp = $"Dime en que te puedo ayudar "; log.Debug("Initialize Text to Speech services"); await textToSpeech.SynthesisToSpeakerAsync(mensajeTemp); log.Debug($"Finished Text to Speech"); // Updating MessageArea Demo_ChinaTown.MainWindow.AppWindow.MessageArea.Dispatcher.Invoke((Action) delegate { Demo_ChinaTown.MainWindow.AppWindow.MessageArea.Text += $"\nWong: {mensajeTemp}"; }); log.Debug(" Initialize Speech to LUIS services"); luisResult = await speechToLuis.RecognitionWithMicrophoneUsingLanguageAsync(); log.Error(luisResult); // Verifying Ubicacion as Intent if (luisResult.Equals("Ubicacion")) { log.Debug("Intent identified as 'Ubicacion'"); mensajeTemp = $"Starbucks se encuentra en el segundo piso, a lado de Zara "; // Sets RightImage to visible from another thread by invoking the dispatcher try { // setting image and making it visible Demo_ChinaTown.MainWindow.AppWindow.RightImage.Dispatcher.Invoke((Action) delegate { Demo_ChinaTown.MainWindow.AppWindow.RightImage.Source = new BitmapImage(new Uri(uri_image + starbucksImage)); Demo_ChinaTown.MainWindow.AppWindow.RightImage.Visibility = Visibility.Visible; }); // Updating MessageArea Demo_ChinaTown.MainWindow.AppWindow.MessageArea.Dispatcher.Invoke((Action) delegate { Demo_ChinaTown.MainWindow.AppWindow.MessageArea.Text += $"\nWong: {mensajeTemp}"; }); log.Debug("Initialize Text to Speech services"); await textToSpeech.SynthesisToSpeakerAsync(mensajeTemp); log.Debug($"Finished Text to Speech"); } catch (Exception ex) { log.Error($"Exception for show map: {ex}"); throw; } } else if (luisResult.Equals("Descuento")) { log.Debug("Intent identified as 'Descuento'"); mensajeTemp = $"Hoy contamos con diversos descuentos en el área de comida. En Zara, toda la ropa de verano a 25%. " + $"Massimo Dutti camisas a 25% y Banana Republic a 25% en toda la tienda"; try { // setting image and making it visible Demo_ChinaTown.MainWindow.AppWindow.RightImage.Dispatcher.Invoke((Action) delegate { Demo_ChinaTown.MainWindow.AppWindow.RightImage.Source = new BitmapImage(new Uri(uri_image + descuentosImage)); Demo_ChinaTown.MainWindow.AppWindow.RightImage.Visibility = Visibility.Visible; }); // Updating MessageArea Demo_ChinaTown.MainWindow.AppWindow.MessageArea.Dispatcher.Invoke((Action) delegate { Demo_ChinaTown.MainWindow.AppWindow.MessageArea.Text += $"\nWong: {mensajeTemp}"; }); log.Debug("Initialize Text to Speech services"); await textToSpeech.SynthesisToSpeakerAsync(mensajeTemp); log.Debug($"Finished Text to Speech"); } catch (Exception ex) { log.Error($"Exception for show map: {ex}"); throw; } } else if (luisResult.Equals("Compras")) { log.Debug("Intent identified as 'Compras'"); mensajeTemp = $"Contamos con tres zapaterías, Aldo, Steve Madden y Loly in the sky. Ubicadas en el segundo piso"; try { // setting image and making it visible Demo_ChinaTown.MainWindow.AppWindow.RightImage.Dispatcher.Invoke((Action) delegate { Demo_ChinaTown.MainWindow.AppWindow.RightImage.Source = new BitmapImage(new Uri(uri_image + zapateriaImage)); Demo_ChinaTown.MainWindow.AppWindow.RightImage.Visibility = Visibility.Visible; }); // Updating MessageArea Demo_ChinaTown.MainWindow.AppWindow.MessageArea.Dispatcher.Invoke((Action) delegate { Demo_ChinaTown.MainWindow.AppWindow.MessageArea.Text += $"\nWong: {mensajeTemp}"; }); log.Debug("Initialize Text to Speech services"); await textToSpeech.SynthesisToSpeakerAsync(mensajeTemp); log.Debug($"Finished Text to Speech"); } catch (Exception ex) { log.Error($"Exception for show map: {ex}"); throw; } } else if (luisResult.Equals("Despedida")) { log.Debug("Intent identified as 'Despedida'"); mensajeTemp = $"Hasta pronto"; // Updating MessageArea Demo_ChinaTown.MainWindow.AppWindow.MessageArea.Dispatcher.Invoke((Action) delegate { Demo_ChinaTown.MainWindow.AppWindow.MessageArea.Text += $"\nWong: {mensajeTemp}"; }); log.Debug("Initialize Text to Speech services"); await textToSpeech.SynthesisToSpeakerAsync(mensajeTemp); log.Debug($"Finished Text to Speech"); } else { log.Debug("Intent not recognized"); mensajeTemp = $"No entendí"; // Updating MessageArea Demo_ChinaTown.MainWindow.AppWindow.MessageArea.Dispatcher.Invoke((Action) delegate { Demo_ChinaTown.MainWindow.AppWindow.MessageArea.Text += $"\nWong: {mensajeTemp}"; }); log.Debug("Initialize Text to Speech services"); await textToSpeech.SynthesisToSpeakerAsync(mensajeTemp); log.Debug($"Finished Text to Speech"); Demo_ChinaTown.MainWindow.AppWindow.RightImage.Dispatcher.Invoke((Action) delegate { Demo_ChinaTown.MainWindow.AppWindow.RightImage.Visibility = Visibility.Hidden; }); } } while (luisResult != "Despedida"); // Set image to hidden Demo_ChinaTown.MainWindow.AppWindow.RightImage.Dispatcher.Invoke((Action) delegate { Demo_ChinaTown.MainWindow.AppWindow.RightImage.Visibility = Visibility.Hidden; }); // Updating MessageArea Demo_ChinaTown.MainWindow.AppWindow.MessageArea.Dispatcher.Invoke((Action) delegate { Demo_ChinaTown.MainWindow.AppWindow.MessageArea.Text = ""; }); }
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //Helper Methods /// <summary> /// Generate Query Fields from FRBOObject Property Fields, used in GenQueryFromFRBOObject /// </summary> /// <returns>Fields used in Query</returns> public string GenQueryFieldsFromFRBOObject() { string resultFields; List <string> fieldList; //Do not use Declared Fields Flag else we skip inheited properties from Base Type (ex Oid,Disabled) //BindingFlags.DeclaredOnly PropertyInfo[] propertyInfos = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);//BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly string attributeField = null; bool attributeHide = false; string mappedFieldName = String.Empty; if (_debug) { _log.Debug(string.Format("Class Name: {0}", typeof(T))); } fieldList = new List <string>(); foreach (PropertyInfo pInfo in propertyInfos) { //If not a generic Type ex a List, add it to FieldList if (!pInfo.PropertyType.IsGenericType /*&& pInfo.PropertyType.GetGenericTypeDefinition() != typeof(List<>)*/) { //Attributes Working Block //Always Reset attributeField and attributeHide attributeField = null; attributeHide = false; //Assign Object Attributes "Field" and "Hide" into attributeField and attributeHide objects var attributes = pInfo.GetCustomAttributes(false); foreach (var attribute in attributes) { //Check if is Working on a FRBO Attribute if (attribute.GetType() == typeof(FRBOAttribute)) { attributeField = ((attribute as FRBOAttribute).Field != null) ? Convert.ToString((attribute as FRBOAttribute).Field) : null; attributeHide = ((attribute as FRBOAttribute).Hide == true) ? true : false; } } if (_debug) { _log.Debug(string.Format("Name: [{0}], PropertyType[{1}], attributeField[{2}], attributeHide[{3}]", pInfo.Name, pInfo.PropertyType, attributeField, attributeHide)); } //If not a Hidden Property, Add it to filedList if (attributeHide == false) { //Get Mapped FieldName (Field Attribute AS Property Name) ex Select "fmOid AS Oid" (QueryField AS FRBOPropertyField) //or Not Mapped Name (Object Property Name) ex "Oid" mappedFieldName = (attributeField != null) ? string.Format("{0} AS {1}", attributeField, pInfo.Name) : pInfo.Name; //Add final FieldName from Attributes or Object Property fieldList.Add(mappedFieldName); } else { //_log.Debug(string.Format("pInfo.Name[{0}].Hide = [{1}] = ", pInfo.Name, attributeHide)); } } } //Finally Convert Generated fieldList into Comma Delimited, Ready to Query Database resultFields = string.Join(",", fieldList.ToArray()); if (_debug) { _log.Debug(string.Format("fields: [{0}]", resultFields)); } return(resultFields); }
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { log.Debug("in windows closing"); }
public frmView() { InitializeComponent(); log.Debug("frmView Opened"); }
private static void OnTimerUpdateCheck(object state) { _logger.Debug("OnTimerUpdateCheck"); try { if (Settings.Default.IsUpgradeRequired) { Settings.Default.Upgrade(); Settings.Default.Reload(); Settings.Default.IsUpgradeRequired = false; Settings.Default.Save(); } // AutoUpdate disabled if (!Settings.Default.IsAutoUpdate) { return; } if (Settings.Default.LastUpdateCheck == null) { Settings.Default.LastUpdateCheck = DateTime.Now; Properties.Settings.Default.Save(); } Version a = (ApplicationDeployment.IsNetworkDeployed) ? ApplicationDeployment.CurrentDeployment.CurrentVersion : Assembly.GetExecutingAssembly().GetName().Version; Version b = a; // once a day should be enougth.... if (Settings.Default.LastUpdateCheck.AddHours(1) <= DateTime.Now) { System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(Settings.Default.VersionUrl); wr.UserAgent = "ahaenggli/OutlookAddIn_KeepAttachmentsOnReply"; WebResponse x = wr.GetResponse();; using (StreamReader reader = new System.IO.StreamReader(x.GetResponseStream())) { string json = reader.ReadToEnd(); if (json.Contains("tag_name")) { Regex pattern = new Regex("\"tag_name\":\"v\\d+(\\.\\d+){2,}\","); Match m = pattern.Match(json); b = new Version(m.Value.Replace("\"", "").Replace("tag_name:v", "").Replace("tag_name:", "").Replace(",", "")); } } if (b > a) { string ProgramData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\haenggli.NET\"; string AddInData = ProgramData + @"OutlookAddIn_KeepAttachmentsOnReply\"; string StartFile = AddInData + @"OutlookAddIn_KeepAttachmentsOnReply.vsto"; string localFile = AddInData + @"OutlookAddIn_KeepAttachmentsOnReply.zip"; string DownloadUrl = Settings.Default.UpdateUrl; if (String.IsNullOrWhiteSpace(DownloadUrl)) { Settings.Default.LastUpdateCheck = DateTime.Now; Settings.Default.Save(); return; } if (!Directory.Exists(AddInData)) { Directory.CreateDirectory(AddInData); } foreach (System.IO.FileInfo file in new DirectoryInfo(AddInData).GetFiles()) { try { file.Delete(); } catch (System.Exception Ex) { _logger.Error(Ex); } } foreach (System.IO.DirectoryInfo subDirectory in new DirectoryInfo(AddInData).GetDirectories()) { try { if (subDirectory.Name.ToLower().Equals("log")) { continue; } subDirectory.Delete(true); } catch (System.Exception Ex) { _logger.Error(Ex); } } if (DownloadUrl.StartsWith("http")) { WebClient webClient = new WebClient(); webClient.DownloadFile(DownloadUrl, localFile); webClient.Dispose(); DownloadUrl = localFile; } ZipFile.ExtractToDirectory(DownloadUrl, AddInData); } Settings.Default.LastUpdateCheck = DateTime.Now; Properties.Settings.Default.Save(); } } catch (System.Exception Ex) { _logger.Error(Ex); } }
/// <summary> /// The main function of the program /// </summary> /// <param name="args">String array containing program arguments</param> public static void Main(string[] args) { if (args.Length > 0) { // getting all arguments from the command line var arguments = new UtilityArguments(args); if (arguments.Help) { DisplayHelp(); Environment.Exit(0); } log.Info("Application started"); string Mailbox = arguments.Mailbox; if ((Mailbox == null) || (Mailbox.Length == 0)) { if (log.IsWarnEnabled) { log.Warn("No mailbox is given. Use -help to refer to the usage."); } else { Console.WriteLine("No mailbox is given. Use -help to refer to the usage."); } DisplayHelp(); Environment.Exit(1); } // Log all arguments if DEBUG is set in xml log.Debug("Parsing arguments"); log.Debug("Arguments:"); log.Debug(string.Format("Mailbox: {0}", arguments.Mailbox)); log.Debug(string.Format("Help: {0}", arguments.Help)); log.Debug(string.Format("NoConfirmation: {0}", arguments.NoConfirmation)); log.Debug(string.Format("LogOnly: {0}", arguments.LogOnly)); log.Debug(string.Format("Impersonate: {0}", arguments.Impersonate)); log.Debug(string.Format("AllowRedirection: {0}", arguments.AllowRedirection)); log.Debug(string.Format("Archive: {0}", arguments.Archive)); if (arguments.Foldername != null) { log.Debug(string.Format("foldername: {0}", arguments.Foldername)); } else { log.Debug("foldername: not specified"); } if (arguments.User != null) { log.Debug(string.Format("User: {0}", arguments.User)); } if (arguments.Password != null) { log.Debug("Password: is set"); } log.Debug(string.Format("ignorecertificate: {0}", arguments.IgnoreCertificate)); if (arguments.URL != null) { log.Debug(string.Format("Server URL: {0}", arguments.URL)); } else { log.Debug("Server URL: using autodiscover"); } // Check if we need to ignore certificate errors // need to be set before the service is created if (arguments.IgnoreCertificate) { log.Warn("Ignoring SSL error because option -ignorecertificate is set"); ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; } WellKnownFolderName RootFolder; if (arguments.Archive) { RootFolder = WellKnownFolderName.ArchiveMsgFolderRoot; } else { RootFolder = WellKnownFolderName.MsgFolderRoot; } // create the service ExchangeService ExService; // connect to the server if (arguments.URL != null) { ExService = ConnectToExchange(Mailbox, arguments.URL, arguments.User, arguments.Password, arguments.Impersonate); } else { ExService = ConnectToExchange(Mailbox, arguments.AllowRedirection, arguments.User, arguments.Password, arguments.Impersonate); } if (log.IsInfoEnabled) { log.Info("Service created."); } // find all folders (under MsgFolderRoot) List <Folder> FolderList = Folders(ExService, new FolderId(RootFolder, Mailbox)); // check if we need to remove items from the list because we want to filter it (folderpath) string FolderName = arguments.Foldername; if (log.IsInfoEnabled) { log.Info(string.Format("Folders with minimum one item inside: {0}", FolderList.Count)); } if (FolderName != null) { if (FolderName.Length > 0) { if (log.IsInfoEnabled) { log.Info("Filter the folder list to apply filter."); } for (int i = FolderList.Count - 1; i >= 0; i--) // yes, we need to it this way... { try { string FolderPath; FolderPath = GetFolderPath(ExService, FolderList[i].Id); if (!(FolderPath.Contains(FolderName))) { log.Debug(string.Format("The folder: \"{0}\" does not match with the filter: \"{1}\"", FolderPath, FolderName)); FolderList.RemoveAt(i); } } catch { Environment.Exit(2); } } } } // now try to find all items that are marked as "private" for (int i = FolderList.Count - 1; i >= 0; i--) { if (log.IsDebugEnabled) { log.Debug(string.Format("Processing folder \"{0}\"", GetFolderPath(ExService, FolderList[i].Id))); } if (log.IsDebugEnabled) { log.Debug(string.Format("ID: {0}", FolderList[i].Id)); } List <Item> Results = PrivateItems(FolderList[i]); if (Results.Count > 0) { if (log.IsInfoEnabled) { log.Info(string.Format("Private items in folder: {0}", Results.Count)); } } foreach (var Result in Results) { if (Result is EmailMessage) { if (log.IsInfoEnabled) { if (log.IsInfoEnabled) { log.Info(string.Format("Found private element. Folder: \"{0}\" ", GetFolderPath(ExService, FolderList[i].Id))); } if (log.IsInfoEnabled) { log.Info(string.Format("Subject: \"{0}\"", Result.Subject)); } if (log.IsDebugEnabled) { log.Debug(string.Format("ID of the item: {0}", Result.Id)); } } else { Console.WriteLine("Found private element. Folder: {0}", GetFolderPath(ExService, FolderList[i].Id)); Console.WriteLine("Subject: {0}", Result.Subject); } if (!(arguments.NoConfirmation)) { if (!(arguments.LogOnly)) { Console.WriteLine(string.Format("Change to normal? (Y/N) (Folder: {0} - Subject {1})", GetFolderPath(ExService, FolderList[i].Id), Result.Subject)); string Question = Console.ReadLine(); if (Question == "y" || Question == "Y") { log.Info("Change the item? Answer: Yes."); ChangeItem(Result); } } } else { if (!(arguments.LogOnly)) { if (log.IsInfoEnabled) { log.Info("Changing item without confirmation because -NoConfirmation is true."); } else { Console.WriteLine("Changing item without confirmation because -NoConfirmation is true."); } ChangeItem(Result); } } } } } } else { DisplayHelp(); Environment.Exit(1); } }
public ActionResult Index(passwordModels model) { //string message = ""; //bool isValid = false; //object objHasil = null; var objResp = new passwordModels(); try { //TODO: validate user password, save to session, etc string vPassword = model.password.Trim().ToUpper(); string no_anggota = model.no_anggota.Trim().ToUpper(); //Log.Debug(DateTime.Now + "LOGIN CONTROLLER No Anggota : " + no_anggota + ", Password : "******"LOGIN CONTROLLER ==>> ID : " + objResp.id); if (objResp.id > 0) { var dataLogin = objResp.no_anggota + "#" + objResp.nama_anggota + "#" + objResp.sektor + "#" + objResp.as_admin; Log.Debug(DateTime.Now + " LOGIN No Anggota : " + objResp.id + "/" + no_anggota + ", nama_anggota : " + objResp.nama_anggota + ", Pass User : "******", Pass Data : " + objResp.password + ", As Admin : " + objResp.as_admin); if (vPassword != objResp.password.Trim().ToUpper()) { ModelState.AddModelError("", "Password Yang dimasukkan Salah..."); } } else { Log.Error("Login Failed, username:"******" Password : "******"", "Login Failed, Invalid Nomer Anggota..."); } if (ModelState.IsValid) { int SessionTime = 120; string strSessionTime = System.Configuration.ConfigurationManager.AppSettings["SessionTime"]; if (!String.IsNullOrEmpty(strSessionTime)) { if (!int.TryParse(strSessionTime, out SessionTime)) { SessionTime = 120; } } FormsAuthenticationTicket tkt; string cookiestr; HttpCookie ck; tkt = new FormsAuthenticationTicket(1, objResp.no_anggota, DateTime.Now, DateTime.Now.AddMinutes(SessionTime), false, objResp.no_anggota + "#" + objResp.nama_anggota + "#" + objResp.sektor + "#" + objResp.as_admin); cookiestr = FormsAuthentication.Encrypt(tkt); ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr); //if (model.RememberMe) // ck.Expires = tkt.Expiration; ck.Path = FormsAuthentication.FormsCookiePath; Response.Cookies.Add(ck); // Log Log.Info("Login Success, UserCode: " + model.no_anggota); // Redirect to requested URL, or homepage if no previous page requested string returnUrl = Request.QueryString["ReturnUrl"]; if (!String.IsNullOrEmpty(returnUrl)) { return(Redirect(returnUrl)); } return(RedirectToAction("Index", "Pelanggan")); } } catch (Exception ex) { Log.Error("Login Failed, username:"******"", "Login Failed, Please try Again or Contact Your Administrator."); } // Re-Initiate //model = InitiateLoginForm(model); return(View(model)); }
/// <summary> /// Return a table containing all of the PickLists and PickItem entries /// </summary> /// <returns></returns> public DataTable EnumeratePickLists() { if (isDebugEnabled) { logger.Debug(System.Reflection.MethodBase.GetCurrentMethod().Name + " in"); } DataTable table = new DataTable(TableNames.UDDD); if (compactDatabaseType) { try { using (SqlCeConnection conn = DatabaseConnection.CreateOpenCEConnection()) { string commandText = "SELECT _PICKLISTID, _NAME ,_PARENTID " + "FROM PICKLISTS " + "ORDER BY _PICKLISTID"; using (SqlCeCommand command = new SqlCeCommand(commandText, conn)) { new SqlCeDataAdapter(command).Fill(table); } } } catch (SqlCeException ex) { Utility.DisplayErrorMessage("A database error has occurred in AuditWizard." + Environment.NewLine + Environment.NewLine + "Please see the log file for further details."); logger.Error("Exception in " + System.Reflection.MethodBase.GetCurrentMethod().Name, ex); } catch (Exception ex) { Utility.DisplayErrorMessage("A database error has occurred in AuditWizard." + Environment.NewLine + Environment.NewLine + "Please see the log file for further details."); logger.Error("Exception in " + System.Reflection.MethodBase.GetCurrentMethod().Name, ex); } } else { AuditWizardDataAccess lAuditWizardDataAccess = new AuditWizardDataAccess(); table = lAuditWizardDataAccess.EnumeratePickLists(); } if (isDebugEnabled) { logger.Debug(System.Reflection.MethodBase.GetCurrentMethod().Name + " out"); } return(table); }
private DownloadStream GetDownloadStreamInternal(File afile, long?start = null, long?end = null) { bool isLinked = !string.IsNullOrEmpty(afile.PublicLink); Cached <ServerRequestResult> downServer = null; var pendingServers = isLinked ? ShardManager.WeblinkDownloadServersPending : ShardManager.DownloadServersPending; Stopwatch watch = new Stopwatch(); HttpWebRequest request = null; CustomDisposable <HttpWebResponse> ResponseGenerator(long instart, long inend, File file) { var resp = Retry.Do(() => { downServer = pendingServers.Next(downServer); string url = (isLinked ? $"{downServer.Value.Url}{WebDavPath.EscapeDataString(file.PublicLink)}" : $"{downServer.Value.Url}{Uri.EscapeDataString(file.FullPath.TrimStart('/'))}") + $"?client_id={HttpSettings.ClientId}&token={Authent.AccessToken}"; var uri = new Uri(url); request = (HttpWebRequest)WebRequest.Create(uri.OriginalString); request.AddRange(instart, inend); request.Proxy = HttpSettings.Proxy; request.CookieContainer = Authent.Cookies; request.Method = "GET"; request.Accept = "*/*"; request.UserAgent = HttpSettings.UserAgent; request.Host = uri.Host; request.AllowWriteStreamBuffering = false; if (isLinked) { request.Headers.Add("Accept-Ranges", "bytes"); request.ContentType = MediaTypeNames.Application.Octet; request.Referer = $"{ConstSettings.CloudDomain}/home/{Uri.EscapeDataString(file.Path)}"; request.Headers.Add("Origin", ConstSettings.CloudDomain); } request.Timeout = 15 * 1000; request.ReadWriteTimeout = 15 * 1000; watch.Start(); var response = (HttpWebResponse)request.GetResponse(); return(new CustomDisposable <HttpWebResponse> { Value = response, OnDispose = () => { pendingServers.Free(downServer); watch.Stop(); Logger.Debug($"HTTP:{request.Method}:{request.RequestUri.AbsoluteUri} ({watch.Elapsed.Milliseconds} ms)"); } }); }, exception => ((exception as WebException)?.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound, exception => { pendingServers.Free(downServer); Logger.Warn($"Retrying HTTP:{request.Method}:{request.RequestUri.AbsoluteUri} on exception {exception.Message}"); }, TimeSpan.FromSeconds(1), 2); return(resp); } var stream = new DownloadStream(ResponseGenerator, afile, start, end); return(stream); }
public override bool Track(List <AbstractTrackPoint> previousPoints, Bitmap currentImage, long position, out AbstractTrackPoint currentPoint) { //--------------------------------------------------------------------- // The input informations we have at hand are: // - The current bitmap we have to find the point into. // - The coordinates of all the previous points tracked. // - Previous tracking scores, stored in the TrackPoints tracked so far. //--------------------------------------------------------------------- TrackPointBlock lastTrackPoint = (TrackPointBlock)previousPoints[previousPoints.Count - 1]; PointF lastPoint = lastTrackPoint.Point; PointF subpixel = new PointF(lastPoint.X - (int)lastPoint.X, lastPoint.Y - (int)lastPoint.Y); bool matched = false; currentPoint = null; if (lastTrackPoint.Template != null && currentImage != null) { // Center search zone around last point. PointF searchCenter = lastPoint; Rectangle searchZone = new Rectangle((int)(searchCenter.X - (searchWindow.Width / 2)), (int)(searchCenter.Y - (searchWindow.Height / 2)), searchWindow.Width, searchWindow.Height); searchZone.Intersect(new Rectangle(0, 0, currentImage.Width, currentImage.Height)); //Image<Bgr, Byte> cvTemplate = new Image<Bgr, Byte>(lastTrackPoint.Template); //Image<Bgr, Byte> cvImage = new Image<Bgr, Byte>(_CurrentImage); Bitmap img = currentImage; Bitmap tpl = lastTrackPoint.Template; BitmapData imageData = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), ImageLockMode.ReadOnly, img.PixelFormat); BitmapData templateData = tpl.LockBits(new Rectangle(0, 0, tpl.Width, tpl.Height), ImageLockMode.ReadOnly, tpl.PixelFormat); Image <Bgra, Byte> cvImage = new Image <Bgra, Byte>(imageData.Width, imageData.Height, imageData.Stride, imageData.Scan0); Image <Bgra, Byte> cvTemplate = new Image <Bgra, Byte>(templateData.Width, templateData.Height, templateData.Stride, templateData.Scan0); cvImage.ROI = searchZone; int resWidth = searchZone.Width - lastTrackPoint.Template.Width + 1; int resHeight = searchZone.Height - lastTrackPoint.Template.Height + 1; Image <Gray, Single> similarityMap = new Image <Gray, Single>(resWidth, resHeight); //CvInvoke.cvMatchTemplate(cvImage.Ptr, cvTemplate.Ptr, similarityMap.Ptr, TM_TYPE.CV_TM_SQDIFF_NORMED); //CvInvoke.cvMatchTemplate(cvImage.Ptr, cvTemplate.Ptr, similarityMap.Ptr, TM_TYPE.CV_TM_CCORR_NORMED); CvInvoke.cvMatchTemplate(cvImage.Ptr, cvTemplate.Ptr, similarityMap.Ptr, TM_TYPE.CV_TM_CCOEFF_NORMED); img.UnlockBits(imageData); tpl.UnlockBits(templateData); // Find max double bestScore = 0; PointF bestCandidate = new PointF(-1, -1); Point minLoc = Point.Empty; Point maxLoc = Point.Empty; double min = 0; double max = 0; CvInvoke.cvMinMaxLoc(similarityMap.Ptr, ref min, ref max, ref minLoc, ref maxLoc, IntPtr.Zero); if (max > similarityTreshold) { PointF loc = RefineLocation(similarityMap.Data, maxLoc, parameters.RefinementNeighborhood); // The template matching was done on a template aligned with the integer part of the actual position. // We reinject the floating point part of the orginal positon into the result. loc = loc.Translate(subpixel.X, subpixel.Y); bestCandidate = new PointF(searchZone.Left + loc.X + tpl.Width / 2, searchZone.Top + loc.Y + tpl.Height / 2); bestScore = max; } #region Monitoring if (monitoring) { // Save the similarity map to file. Image <Gray, Byte> mapNormalized = new Image <Gray, Byte>(similarityMap.Width, similarityMap.Height); CvInvoke.cvNormalize(similarityMap.Ptr, mapNormalized.Ptr, 0, 255, NORM_TYPE.CV_MINMAX, IntPtr.Zero); Bitmap bmpMap = mapNormalized.ToBitmap(); string tplDirectory = @"C:\Users\Joan\Videos\Kinovea\Video Testing\Tracking\simimap"; bmpMap.Save(tplDirectory + String.Format(@"\simiMap-{0:000}-{1:0.00}.bmp", previousPoints.Count, bestScore)); } #endregion // Result of the matching. if (bestCandidate.X != -1 && bestCandidate.Y != -1) { currentPoint = CreateTrackPoint(false, bestCandidate, bestScore, position, img, previousPoints); ((TrackPointBlock)currentPoint).Similarity = bestScore; } else { // No match. Create the point at the center of the search window (whatever that might be). currentPoint = CreateTrackPoint(false, lastPoint, 0.0f, position, img, previousPoints); log.Debug("Track failed. No block over the similarity treshold in the search window."); } matched = true; } else { // No image. (error case ?) // Create the point at the last point location. currentPoint = CreateTrackPoint(false, lastPoint, 0.0f, position, currentImage, previousPoints); log.Debug("Track failed. No input image, or last point doesn't have any cached block image."); } return(matched); }
protected override void Run() { log.Debug("Running SR repair"); log.DebugFormat("SR='{0}'", SR.Name); foreach (Host host in Connection.Cache.Hosts) { Host stoHost = SR.GetStorageHost(); if (SR.shared || (stoHost != null && host.opaque_ref == stoHost.opaque_ref)) { _hostList.Add(host); } } if (_hostList.Count == 0) { return; } for (int i = 0; i < _hostList.Count; i++) { log.DebugFormat("_hostList[{0}]='{1}'", i, _hostList[i].Name); } int max = _hostList.Count * 2; int delta = 100 / max; foreach (Host host in _hostList) { if (!host.HasPBDTo(SR) && SR.shared && SR.PBDs.Count > 0) { PBD template = SR.Connection.Resolve(SR.PBDs[0]); if (template != null) { this.Description = string.Format(Messages.ACTION_SR_REPAIR_CREATE_PBD, Helpers.GetName(host)); log.Debug(this.Description); Proxy_PBD proxyPBD = new Proxy_PBD(); proxyPBD.currently_attached = false; proxyPBD.device_config = new Hashtable(template.device_config); proxyPBD.SR = template.SR; proxyPBD.host = new XenRef <Host>(host.opaque_ref); try { RelatedTask = XenAPI.PBD.async_create(this.Session, new PBD(proxyPBD)); if (PercentComplete + delta <= 100) { PollToCompletion(PercentComplete, PercentComplete + delta); } else { PollToCompletion(PercentComplete, 100); PercentComplete = 100; } } catch (XenAPI.Failure f) { failure = f; failureDescription = Description; } } } else { PercentComplete += delta; } PBD thePBD = host.GetPBDTo(SR); if (thePBD != null && !thePBD.currently_attached) { this.Description = string.Format(Messages.ACTION_SR_REPAIR_PLUGGING_PBD, Helpers.GetName(host)); log.Debug(this.Description); try { RelatedTask = XenAPI.PBD.async_plug(this.Session, thePBD.opaque_ref); if (PercentComplete + delta <= 100) { PollToCompletion(PercentComplete, PercentComplete + delta); } else { PollToCompletion(PercentComplete, 100); PercentComplete = 100; } } catch (XenAPI.Failure f) { failure = f; failureDescription = Description; } } else { PercentComplete += delta; } } if (failure != null && failureDescription != null) { Description = failureDescription; throw failure; } // CA-14928: Sometimes we have too many PBDs if there has just been a host // eject and the GC hasn't collected the PBD yet. // //if (SR.PBDs.Count != _hostList.Count && SR.shared && !SR.IsToolsSR) //{ // throw new Exception(Messages.ACTION_SR_REPAIR_FAILED); //} if (isSharedAction) { Description = string.Format(Messages.ACTION_SR_SHARE_SUCCESSFUL, SR.NameWithoutHost); } else { Description = string.Format(Messages.ACTION_SR_REPAIR_SUCCESSFUL, SR.NameWithoutHost); } }
public void EnsureInfrastructure() { Log.Debug("Ensuring Infrastructure is available on target"); _provider.EnsureInfrastructure(); }
/// <summary> /// Creates a new sequencer with a reference to the UIHandle and logicalLayer objects /// This object is responsible for organizing the timing of all events /// </summary> /// <param name="inUIHandler">Reference to the UIHandler</param> /// <param name="inLogicalLayer">Reference to the logical layer</param> public SequencerLayer(UIHandle_LLSL inUIHandler, LogicalLayer inLogicalLayer, SequencerConfig inSequencerConfig) { log.Debug(string.Format("Creating sequencer:{0} with logicalLayer:{1} and UIHandler:{2}", this, inLogicalLayer, inUIHandler)); _uiHandler = inUIHandler; _logicalLayer = inLogicalLayer; _shouldStop = false; _sequencerConfig = inSequencerConfig; startSequencerThreads(); }
static void Main(string[] args) { if (string.IsNullOrEmpty(Thread.CurrentThread.Name)) Thread.CurrentThread.Name = "Main"; #if WINDOWS && DEBUG if (!System.Diagnostics.Debugger.IsAttached) { AllocConsole(); var stdHandle = GetStdHandle(STD_OUTPUT_HANDLE); var safeFileHandle = new SafeFileHandle(stdHandle, true); var fileStream = new FileStream(safeFileHandle, FileAccess.Write); var encoding = Encoding.GetEncoding(CODE_PAGE); var stdOut = new StreamWriter(fileStream, encoding) { AutoFlush = true }; Console.SetOut(stdOut); } #endif _log = LogManager.GetLogger(typeof(Program)); _log.Info("### !!! APPLICATION LOAD !!! ###"); _log.Info("Deleting old log files (>7 days)..."); // Delete log files older than 7 days if (Directory.Exists("logs")) { var now = DateTime.Now; var max = new TimeSpan(7, 0, 0, 0); // 7 days foreach (var file in from file in Directory.GetFiles("logs") let modTime = File.GetLastAccessTime(file) let age = now.Subtract(modTime) where age > max select file) { try { File.Delete(file); _log.Info("Deleted old log file: " + file); } catch (IOException ex) { _log.Warn("Failed to delete log file: " + file + "(" + ex.Message + ")"); } } } _log.Info("Old log files deleted!"); _log.Info("Starting game..."); using (var game = new MainGame()) game.Run(); #if WINDOWS && DEBUG _log.Debug("Unloading console..."); FreeConsole(); _log.Debug("Console unloaded!"); #endif _log.Info("### !!! APPLICATION EXIT !!! ###"); }
public MainGame() { _log = LogManager.GetLogger(this); Activated += GameActivated; Deactivated += GameDeactivated; _log.Debug("Setting initial FPS value"); FPS = 0.0f; _log.Info("Setting graphics settings..."); _graphics = new GraphicsDeviceManager(this) { PreferredBackBufferWidth = ScreenWidth, PreferredBackBufferHeight = ScreenHeight }; _log.Info(string.Format("Screen size set to: [W]{0} x [H]{1}", ScreenWidth, ScreenHeight)); _graphics.SynchronizeWithVerticalRetrace = false; //IsFixedTimeStep = false; _graphics.ApplyChanges(); ScreenRectangle = new Rectangle(0, 0, ScreenWidth, ScreenHeight); _log.Debug("Setting content root directory..."); Content.RootDirectory = "Content"; // Create necessary folders if they don't exist try { if (!Directory.Exists(Paths.SettingsFolder)) Directory.CreateDirectory(Paths.SettingsFolder); } catch (IOException ex) { _log.Error("Failed to create necessary game folders. Exception details as follows..."); _log.Fatal("IOException: " + ex.Message + Environment.NewLine + "Details:", ex); _log.Fatal("Game will now exit..."); Exit(); } _log.Info("Loading controls..."); ControlsManager = new ControlsManager(); _log.Debug("Controls loaded!"); _log.Info("Creating components..."); AudioManager = new AudioManager(); _stateManager = new GameStateManager(this); TitleScreen = new TitleScreen(this, _stateManager); StartMenuScreen = new StartMenuScreen(this, _stateManager); CharacterGeneratorScreen = new CharacterGeneratorScreen(this, _stateManager); SkillScreen = new SkillScreen(this, _stateManager); LoadGameScreen = new LoadGameScreen(this, _stateManager); GamePlayScreen = new GamePlayScreen(this, _stateManager); Components.Add(new InputHandler(this)); Components.Add(_stateManager); _log.Info("Components created!"); LoadMusic(); var menuSong = AudioManager.Song.GetSong("MenuTheme"); menuSong.SetStartFade(new FadeInfo(0.0f, 1.0f, 0.01f, TimeSpan.FromMilliseconds(20))); menuSong.SetEndFade(new FadeInfo(1.0f, 0.0f, 0.01f, TimeSpan.FromMilliseconds(15))); _log.Debug("Changing to TitleScreen..."); _stateManager.ChangeState(TitleScreen); }
public AirlineDAOMSSQL(bool testMode = false) { this.testMode = testMode; log.Debug("setting connection string depending on test mode"); connection_string = !testMode ? AirlineProjectConfig.CONNECTION_STRING : AirlineProjectConfig.TEST_CONNECTION_STRING; log.Debug($"connection string = {connection_string}"); }
protected void Application_Start(object sender, EventArgs e) { // Code that runs on application startup logger = FTSS.Utilities.Common.InitLog4Net(); logger.Debug("InitLog4Net completed"); }
static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args) { log.Debug(String.Format("程序集[{0}]已加载到当前应用程序域", args.LoadedAssembly)); }
public override void Write(string message) => _log?.Debug(message);
public static void Start(string[] args) { bool isAlreadyRunning = false; List<string> filesToOpen = new List<string>(); // Init Log4NET LogFileLocation = LogHelper.InitializeLog4NET(); // Get logger LOG = log4net.LogManager.GetLogger(typeof(MainForm)); Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); // Log the startup LOG.Info("Starting: " + EnvironmentInfo.EnvironmentToString(false)); IniConfig.Init(); AppConfig.UpgradeToIni(); // Read configuration conf = IniConfig.GetIniSection<CoreConfiguration>(); try { // Fix for Bug 2495900, Multi-user Environment // check whether there's an local instance running already try { // Added Mutex Security, hopefully this prevents the UnauthorizedAccessException more gracefully // See an example in Bug #3131534 SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); MutexSecurity mutexsecurity = new MutexSecurity(); mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow)); mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny)); mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny)); bool created = false; // 1) Create Mutex applicationMutex = new Mutex(false, @"Local\F48E86D3-E34C-4DB7-8F8F-9A0EA55F0D08", out created, mutexsecurity); // 2) Get the right to it, this returns false if it's already locked if (!applicationMutex.WaitOne(0, false)) { LOG.Debug("Greenshot seems already to be running!"); isAlreadyRunning = true; // Clean up applicationMutex.Close(); applicationMutex = null; } } catch (AbandonedMutexException e) { // Another Greenshot instance didn't cleanup correctly! // we can ignore the exception, it happend on the "waitone" but still the mutex belongs to us LOG.Warn("Greenshot didn't cleanup correctly!", e); } catch (UnauthorizedAccessException e) { LOG.Warn("Greenshot is most likely already running for a different user in the same session, can't create mutex due to error: ", e); isAlreadyRunning = true; } catch (Exception e) { LOG.Warn("Problem obtaining the Mutex, assuming it was already taken!", e); isAlreadyRunning = true; } if (args.Length > 0 && LOG.IsDebugEnabled) { StringBuilder argumentString = new StringBuilder(); for (int argumentNr = 0; argumentNr < args.Length; argumentNr++) { argumentString.Append("[").Append(args[argumentNr]).Append("] "); } LOG.Debug("Greenshot arguments: " + argumentString.ToString()); } for (int argumentNr = 0; argumentNr < args.Length; argumentNr++) { string argument = args[argumentNr]; // Help if (argument.ToLower().Equals("/help")) { // Try to attach to the console bool attachedToConsole = Kernel32.AttachConsole(Kernel32.ATTACHCONSOLE_ATTACHPARENTPROCESS); // If attach didn't work, open a console if (!attachedToConsole) { Kernel32.AllocConsole(); } StringBuilder helpOutput = new StringBuilder(); helpOutput.AppendLine(); helpOutput.AppendLine("Greenshot commandline options:"); helpOutput.AppendLine(); helpOutput.AppendLine(); helpOutput.AppendLine("\t/help"); helpOutput.AppendLine("\t\tThis help."); helpOutput.AppendLine(); helpOutput.AppendLine(); helpOutput.AppendLine("\t/exit"); helpOutput.AppendLine("\t\tTries to close all running instances."); helpOutput.AppendLine(); helpOutput.AppendLine(); helpOutput.AppendLine("\t/reload"); helpOutput.AppendLine("\t\tReload the configuration of Greenshot."); helpOutput.AppendLine(); helpOutput.AppendLine(); helpOutput.AppendLine("\t/language [language code]"); helpOutput.AppendLine("\t\tSet the language of Greenshot, e.g. greenshot /language en-US."); helpOutput.AppendLine(); helpOutput.AppendLine(); helpOutput.AppendLine("\t[filename]"); helpOutput.AppendLine("\t\tOpen the bitmap files in the running Greenshot instance or start a new instance"); Console.WriteLine(helpOutput.ToString()); // If attach didn't work, wait for key otherwise the console will close to quickly if (!attachedToConsole) { Console.ReadKey(); } FreeMutex(); return; } if (argument.ToLower().Equals("/exit")) { // unregister application on uninstall (allow uninstall) try { LOG.Info("Sending all instances the exit command."); // Pass Exit to running instance, if any SendData(new CopyDataTransport(CommandEnum.Exit)); } catch (Exception e) { LOG.Warn("Exception by exit.", e); } FreeMutex(); return; } // Reload the configuration if (argument.ToLower().Equals("/reload")) { // Modify configuration LOG.Info("Reloading configuration!"); // Update running instances SendData(new CopyDataTransport(CommandEnum.ReloadConfig)); FreeMutex(); return; } // Stop running if (argument.ToLower().Equals("/norun")) { // Make an exit possible FreeMutex(); return; } // Language if (argument.ToLower().Equals("/language")) { conf.Language = args[++argumentNr]; IniConfig.Save(); continue; } // Files to open filesToOpen.Add(argument); } // Finished parsing the command line arguments, see if we need to do anything CopyDataTransport transport = new CopyDataTransport(); if (filesToOpen.Count > 0) { foreach (string fileToOpen in filesToOpen) { transport.AddCommand(CommandEnum.OpenFile, fileToOpen); } } if (MainForm.instance == null) MainForm.instance = new MainForm(transport); // if language is not set, show language dialog if (string.IsNullOrEmpty(conf.Language)) { LanguageDialog languageDialog = LanguageDialog.GetInstance(); languageDialog.ShowDialog(); conf.Language = languageDialog.SelectedLanguage; IniConfig.Save(); } // Check if it's the first time launch? if (conf.IsFirstLaunch) { conf.IsFirstLaunch = false; IniConfig.Save(); transport.AddCommand(CommandEnum.FirstLaunch); } } catch (Exception ex) { LOG.Error("Exception in startup.", ex); Application_ThreadException(MainForm.ActiveForm, new ThreadExceptionEventArgs(ex)); } }
public static void Debug(string message) { log.Debug(message); }
/// <summary> /// 调试信息 /// </summary> /// <param name="obj"></param> public void Debug(object obj) { _error.Debug(obj); }
public void Debug(object message) { _log.Debug(message); }
public TestLibWhipLru() : base(SERVICE_ADDRESS, SERVICE_PORT, SERVICE_PASSWORD) { LOG.Debug($"Initializing {nameof(TestLibWhipLru)}..."); #pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body try { System.IO.Directory.Delete("SpeedTestLibWhipLru", true); } catch (Exception) { } try { System.IO.File.Delete("SpeedTestLibWhipLru.wcache"); } catch (Exception) { } try { System.IO.File.Delete("SpeedTestLibWhipLru.pid"); } catch (Exception) { } #pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body var config = new Chattel.ChattelConfiguration( "SpeedTestLibWhipLru", "SpeedTestLibWhipLru.wcache", 100, (Chattel.IAssetServer)null ); _libWhipLruLocalStorage = new LibWhipLru.Cache.AssetLocalStorageLmdbPartitionedLRU( config, uint.MaxValue, TestLibWhipLruLocalStorage.DATABASE_PARTITION_INTERVAL ); _libWhipLruStorageManager = new LibWhipLru.Cache.StorageManager( _libWhipLruLocalStorage, TimeSpan.FromMinutes(2), null, null ); _libWhipLruStorageManager.StoreAsset(new InWorldz.Data.Assets.Stratus.StratusAsset { CreateTime = DateTime.UtcNow, // Close enough. Data = _knownAsset.Data, Description = _knownAsset.Description, Id = new Guid(_knownAsset.Uuid), Local = _knownAsset.Local, Name = _knownAsset.Name, Temporary = _knownAsset.Temporary, Type = (sbyte)_knownAsset.Type, }, result => {}); var pidFileManager = new LibWhipLru.Util.PIDFileManager("SpeedTestLibWhipLru.pid"); _libWhipLru = new LibWhipLru.WhipLru(SERVICE_ADDRESS, SERVICE_PORT, SERVICE_PASSWORD, pidFileManager, _libWhipLruStorageManager); _libWhipLru.Start(); Thread.Sleep(500); LOG.Debug($"Initialization of {nameof(TestLibWhipLru)} complete."); }
static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler; #if DEBUG bool debug = true; #else bool debug = false; #endif if (args.Length > 0) if (args[0].ToLower() == "debug") debug = true; if (string.IsNullOrEmpty(Thread.CurrentThread.Name)) Thread.CurrentThread.Name = "Main"; if (debug && !System.Diagnostics.Debugger.IsAttached) { AllocConsole(); IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE); var safeFileHandle = new SafeFileHandle(stdHandle, true); var fileStream = new FileStream(safeFileHandle, FileAccess.Write); var encoding = System.Text.Encoding.GetEncoding(CODE_PAGE); var stdOut = new StreamWriter(fileStream, encoding) {AutoFlush = true}; Console.SetOut(stdOut); } LogManager.LoadConfig(debug); _log = LogManager.GetLogger(typeof (Program)); _log.Info("!!! APPLICATION LOAD !!!"); _log.Info("Detecting components..."); foreach (var file in Directory.GetFiles(Directory.GetCurrentDirectory())) { string ext = Path.GetExtension(file); if (string.IsNullOrEmpty(ext)) continue; ext = ext.Substring(1); if (ext == "dll" || ext == "exe") { string version = AssemblyName.GetAssemblyName(file).Version.ToString(); string name = Path.GetFileNameWithoutExtension(file); _log.Info(name + " v" + version); } } _log.Info("Components detected!"); _log.Info("Sharpcraft is loading..."); try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (!Directory.Exists(Constants.SettingsDirectory)) Directory.CreateDirectory(Constants.SettingsDirectory); #if SC_DIRECT new Sharpcraft(null).Run(); #else _log.Debug("Starting launcher..."); _launcher = new Launcher(); _launcher.Show(); _context = new ApplicationContext(_launcher); Application.Run(_context); _log.Info("Launcher has returned execution to main thread."); #endif } catch(FileNotFoundException ex) { _log.Fatal("Required file \"" + ex.FileName + "\" not found! Application is exiting..."); } catch(IOException ex) { _log.Fatal("IO Operation failed: " + ex.Message); _log.Fatal("Application is exiting..."); } catch(Exception ex) { UnhandledExceptionHandler(null, new UnhandledExceptionEventArgs(ex, false)); #if DEBUG throw; #endif } finally { if (_launcher != null) { _log.Debug("Closing launcher."); _launcher.Close(); _launcher.Dispose(); _launcher = null; _log.Info("Launcher closed."); } if (debug) { _log.Debug("Closing debug console."); FreeConsole(); } _log.Info("!!! APPLICATION EXIT !!!"); } }
public void OnEnter(Type declaringType, object instance, MethodBase methodbase, object[] values) { this._methodName = methodbase.Name; this._typeName = declaringType.Name; logger.Debug($"OnEnter -> {declaringType.Name} {methodbase.Name} {string.Join(" ", values)}"); }
public async Task Invoke(HttpContext context) { string authoriztionHeader = context.Request.Headers["Authorization"]; string url = MyHttpContext.AppBaseUrl; string requester_url = Microsoft.AspNetCore.Http.Extensions.UriHelper.GetDisplayUrl(context.Request); log.Debug("API url = " + url + ", requerster url = " + requester_url); if (IsProduction) { #region Production Setting if (authoriztionHeader != null && authoriztionHeader.StartsWith("Bearer")) { Security sec = new Security(); string token = authoriztionHeader.Substring("Bearer ".Length).Trim(); JwtSecurityTokenHandler jwthandler = new JwtSecurityTokenHandler(); Microsoft.IdentityModel.Tokens.SecurityToken jwttoken = jwthandler.ReadToken(token); var expDate = jwttoken.ValidTo; string username = sec.ValidateToken(token); bool IsUserActive = facade.IsUserActive(username); if (IsUserActive && expDate < DateTime.UtcNow.AddMinutes(1)) { await next.Invoke(context); } else { context.Response.StatusCode = 401; } } else { context.Response.StatusCode = 401; } #endregion } else { #region Development Setting if (requester_url.ToLower().Contains(url.ToLower()) || requester_url.ToLower().Contains("swagger") || requester_url.ToLower().Contains("auth")) { log.Debug("Lolos pada if development, (requester_url.ToLower().Contains(url.ToLower()) || requester_url.ToLower().Contains('swagger') || requester_url.ToLower().Contains('auth')"); await next.Invoke(context); } else { if (authoriztionHeader != null && authoriztionHeader.StartsWith("Bearer")) { Security sec = new Security(); string token = authoriztionHeader.Substring("Bearer ".Length).Trim(); JwtSecurityTokenHandler jwthandler = new JwtSecurityTokenHandler(); Microsoft.IdentityModel.Tokens.SecurityToken jwttoken = jwthandler.ReadToken(token); var expDate = jwttoken.ValidTo; string username = sec.ValidateToken(token); bool IsUserActive = facade.IsUserActive(username); if (IsUserActive && expDate > DateTime.UtcNow.AddMinutes(1)) { await next.Invoke(context); } else { context.Response.StatusCode = 401; } } else { context.Response.StatusCode = 401; } } #endregion } }
internal void InternalLog(string text, LogLevel logLevel, params object[] parameters) { if (parameters != null && parameters.Length > 0) { if (logLevel == LogLevel.Critical) { if (parameters != null && parameters.Length > 0) { log.FatalFormat(text, parameters); } } else if (logLevel == LogLevel.Error) { log.ErrorFormat(text, parameters); } else if (logLevel == LogLevel.Warning) { log.WarnFormat(text, parameters); } else if (logLevel == LogLevel.Information) { log.InfoFormat(text, parameters); } else if (logLevel == LogLevel.Debug) { log.DebugFormat(text, parameters); } else if (logLevel == LogLevel.None) { //Do nothing } else { //LogLevel.Trace, log.DebugFormat(text, parameters); } } else { if (logLevel == LogLevel.Critical) { if (parameters != null && parameters.Length > 0) { log.Fatal(text); } } else if (logLevel == LogLevel.Error) { log.Error(text); } else if (logLevel == LogLevel.Warning) { log.Warn(text); } else if (logLevel == LogLevel.Information) { log.Info(text); } else if (logLevel == LogLevel.Debug) { log.Debug(text); } else if (logLevel == LogLevel.None) { //Do nothing } else { //LogLevel.Trace, log.Debug(text); } } }