public void Error(string str, [CallerLineNumber] int lineNumber = 0, [CallerMemberName] string caller = null, [CallerFilePath] string filepath = null) { logger?.Error(Bake(str, lineNumber, caller, filepath)); }
/// <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; } }
protected override void OnException(ExceptionContext filterContext) { //Log error logger = log4net.LogManager.GetLogger(filterContext.Controller.ToString()); logger.Error(filterContext.Exception.Message, filterContext.Exception); }
protected override void OnStart(string[] args) { string baseDir = AppDomain.CurrentDomain.BaseDirectory; log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(baseDir + "log4net.xml")); log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); try { // Pick one //RemotingConfiguration.CustomErrorsEnabled(false); RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off; //RemotingConfiguration.Configure(baseDir + "RrdbFileService.exe.config"); log.Info("RrdDb file server started"); var nameValueCollection = (NameValueCollection)ConfigurationManager.GetSection("rrdbfileserver"); log.InfoFormat("Database file base path:{0}", nameValueCollection["databasepath"]); string port = nameValueCollection["port"]; int portNumber = int.Parse(port); channel = new TcpChannel(portNumber); ChannelServices.RegisterChannel(channel, false); log.InfoFormat("Server object registerd on port {0}", portNumber); RemotingConfiguration.RegisterWellKnownServiceType( typeof(RrdDbAdapter), "GetRrdDbAdapter", WellKnownObjectMode.Singleton); log.Info("Service up and running"); } catch (Exception ex) { log.Error(ex); throw; } }
public clg_ServeurTCPSQLSever(string pServeur, int pPortEcouteServBD, CLG_AccesBD.clg_Connecteur pCnn, log4net.ILog pLoggeur) : base(pServeur, pPortEcouteServBD) { try { c_Loggeur = pLoggeur; c_Connecteur = pCnn; c_AdresseServSynchro = pServeur; c_PortServSynchro = pPortEcouteServBD; c_ConnexionsTCP = new Dictionary<string, clg_CnnServeurTCPSQLServer>(); c_Cnn = new CLG_AccesBD.clg_Connection(ref c_Connecteur); c_Cnn.Ouvre(); } catch (Exception ex) { c_Loggeur.Error("Erreur a l'instanciation de la classe ServeurTCPSQLServer : " + ex.Message); } }
internal void CheckRaumHoehen(bool ignoreFirstCancel = false) { log.Info("CheckRaumHoehen"); if (!CheckBlockAndAtt()) { return; } _NrOfErrors = 0; Plan2Ext.Globs.DeleteFehlerLines(FEHLER_LINE_LAYER); if (!SelectZuRaumIdEntities(ignoreFirstCancel)) { return; } List <RaumHoehenInfo> raumInfos = new List <RaumHoehenInfo>(); foreach (var oid in _RaumPolygons) { raumInfos.Add(new RaumHoehenInfo(oid, _RaumBlocks, _BodenPunkte, _DeckenPunkte, _TransMan)); } log.InfoFormat(CultureInfo.CurrentCulture, "Anzahl der gefundenen Räume: {0}", raumInfos.Count); using (var myTrans = _TransMan.StartTransaction()) { try { CheckRaumHoehen(raumInfos.Where(x => x.TheStatus == RaumHoehenInfo.Status.Ok), myTrans); myTrans.Commit(); } catch (Exception ex) { log.Error(ex.Message, ex); throw; } } var errors = raumInfos.SelectMany(x => x.ErrorPositions).ToList(); Plan2Ext.Globs.InsertFehlerLines(errors, FEHLER_LINE_LAYER); ShowSingleRaumBlocks(); string msg = string.Empty; if (errors.Count > 0) { msg = string.Format(CultureInfo.CurrentCulture, "Anzahl der Fehler: {0}.", errors.Count); } if (_RaumBlocks.Count > 0) { if (!string.IsNullOrEmpty(msg)) { msg += "\n"; } msg += string.Format(CultureInfo.CurrentCulture, "Alleinstehende Raumblöcke oder RH-Bezeichnungen: {0}.", _RaumBlocks.Count); } if (!string.IsNullOrEmpty(msg)) { _AcAp.Application.ShowAlertDialog(msg); log.Warn(msg); } else { msg = string.Format(CultureInfo.CurrentCulture, "Die Fußboden-Höhenprüfung wurde erfolgreich beendet."); _AcAp.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(msg); log.Info(msg); } }
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //objeto para poder registrar los movimientos que se hacen en esta ventana public AgregarProducto(Usuario user) //constructor { try { InitializeComponent(); usuario = user; //guarda la informacion del usuario que usa el sistema log.Debug($"Se inició AgregarProducto por el usuario {usuario.Nombre} {usuario.Apellidos}"); //registra que el usuario abrió la ventana agregar producto } catch (Exception error) { log.Error($"Error: {error.Message}", error); MessageBox.Show($"Error: {error.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void Connect() { var watch = Stopwatch.StartNew(); if (this.socket != null) { try { CloseConnection(); } catch (Exception e) { Logger.Error(string.Format("KafkaConnectio.Connect() exception in CloseConnection, duration={0}ms", watch.ElapsedMilliseconds), e); } } this.socket = null; IPAddress targetAddress; if (IPAddress.TryParse(server, out targetAddress)) { try { var newSocket = new Socket(targetAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true, ReceiveTimeout = this.receiveTimeoutMs, SendTimeout = this.sendTimeoutMs, SendBufferSize = bufferSize, ReceiveBufferSize = bufferSize }; var result = newSocket.BeginConnect(targetAddress, port, null, null); // use receiveTimeoutMs as connectionTimeoutMs result.AsyncWaitHandle.WaitOne(this.receiveTimeoutMs, true); result.AsyncWaitHandle.Close(); if (newSocket.Connected) { this.socket = newSocket; } else { newSocket.Close(); } } catch (Exception ex) { Logger.Error(string.Format("KafkaConnectio.Connect() failed, duration={0}ms,this={1},targetAddress={2}", watch.ElapsedMilliseconds, this, targetAddress), ex); throw new UnableToConnectToHostException(targetAddress.ToString(), port, ex); } } else { var addresses = Dns.GetHostAddresses(server) .Where( h => h.AddressFamily == AddressFamily.InterNetwork || h.AddressFamily == AddressFamily.InterNetworkV6); foreach (var address in addresses) { try { var newSocket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true, ReceiveTimeout = this.receiveTimeoutMs, SendTimeout = this.sendTimeoutMs, SendBufferSize = bufferSize, ReceiveBufferSize = bufferSize }; var result = newSocket.BeginConnect(address, port, null, null); // use receiveTimeoutMs as connectionTimeoutMs result.AsyncWaitHandle.WaitOne(this.receiveTimeoutMs, true); result.AsyncWaitHandle.Close(); if (!newSocket.Connected) { newSocket.Close(); continue; } this.socket = newSocket; break; } catch (Exception e) { Logger.Error(string.Format("ErrorConnectingToAddress, duration={0}ms,address={1},server={2},port={3}", watch.ElapsedMilliseconds, address, server, port), e); throw new UnableToConnectToHostException(server, port, e); } } } if (socket == null) { Logger.ErrorFormat("UnableToConnectToHostException, duration={0}ms,server={1},port={2}", watch.ElapsedMilliseconds, server, port); throw new UnableToConnectToHostException(server, port); } Logger.DebugFormat("KafkaConnection.Connect() succeeded, duration={0}ms,server={1},port={2}", watch.ElapsedMilliseconds, server, port); this.stream = new NetworkStream(socket, true) { ReadTimeout = this.networkStreamReadTimeoutMs, WriteTimeout = this.networkStreamWriteTimeoutMs }; this.reader = new KafkaBinaryReader(stream); Connected = true; this.lastActiveTimeMs = Environment.TickCount; }
/// <summary> /// /// </summary> /// <param name="document"></param> /// <param name="cachedDocumentFileName"></param> public async Task ExecuteAsync(Document document, string cachedDocumentFileName) { if (!string.Equals(document.Kind, "SummaryTables.RefreshDates", StringComparison.OrdinalIgnoreCase)) { Logger.Debug($"Document was not of SummaryTables.RefreshDates with Document ID {document.ID}"); return; } if (_db == null) { Logger.Error("The ExecuteAync Function was called before Initialize"); throw new Exception("DataContext is null. Please Call Initialize before ExecuteAsync"); } var dataMartID = await(from dm in _db.DataMarts.AsNoTracking() join reqDM in _db.RequestDataMarts.AsNoTracking() on dm.ID equals reqDM.DataMartID join res in _db.Responses.AsNoTracking() on reqDM.ID equals res.RequestDataMartID where res.ID == document.ItemID select dm.ID).FirstOrDefaultAsync(); if (dataMartID == null || dataMartID == Guid.Empty) { Logger.Error($"Could not find the associated DataMart to the document with Document ID of {document.ID}."); throw new Exception("Could not find the associated DataMart to this document."); } Logger.Debug("Deserializing the Response Document"); DTO.QueryComposer.QueryComposerResponseDTO deserialzedDoc; using (var stream = new FileStream(Path.Combine(_uploadDir, cachedDocumentFileName), FileMode.Open, FileAccess.Read)) using (var sr = new StreamReader(stream)) using (var jr = new Newtonsoft.Json.JsonTextReader(sr)) { var serializer = new Newtonsoft.Json.JsonSerializer(); serializer.Converters.Add(new DTO.QueryComposer.QueryComposerResponsePropertyDefinitionConverter()); deserialzedDoc = serializer.Deserialize <DTO.QueryComposer.QueryComposerResponseDTO>(jr); } Logger.Debug($"Looping over the Document {document.ID} with DataMart {dataMartID}"); foreach (var row in deserialzedDoc.Queries.First().Results.FirstOrDefault()) { var dt = row["DataTable"].ToString(); var period = row["Period"].ToString(); var hasQuarter = period.IndexOf('Q') > 0; if (hasQuarter) { await _db.Database.ExecuteSqlCommandAsync(@"IF NOT EXISTS(SELECT NULL FROM DataMartAvailabilityPeriods_v2 WHERE DataMartID = @DataMartID AND DataTable = @DataTable AND PeriodCategory = @PeriodCategory AND Period = @Period) INSERT INTO DataMartAvailabilityPeriods_v2 (DataMartID, DataTable, PeriodCategory, Period, Year, Quarter) VALUES (@DataMartID, @DataTable, @PeriodCategory, @Period, @Year, @Quarter)", new SqlParameter("DataMartID", dataMartID), new SqlParameter("DataTable", dt), new SqlParameter("PeriodCategory", "Q"), new SqlParameter("Period", period), new SqlParameter("Year", period.Substring(0, period.IndexOf('Q'))), new SqlParameter("Quarter", period.Substring(period.IndexOf('Q') + 1))); } else { await _db.Database.ExecuteSqlCommandAsync(@"IF NOT EXISTS(SELECT NULL FROM DataMartAvailabilityPeriods_v2 WHERE DataMartID = @DataMartID AND DataTable = @DataTable AND PeriodCategory = @PeriodCategory AND Period = @Period) INSERT INTO DataMartAvailabilityPeriods_v2 (DataMartID, DataTable, PeriodCategory, Period, Year) VALUES (@DataMartID, @DataTable, @PeriodCategory, @Period, @Year)", new SqlParameter("DataMartID", dataMartID), new SqlParameter("DataTable", dt), new SqlParameter("PeriodCategory", "Y"), new SqlParameter("Period", period), new SqlParameter("Year", period)); } } Logger.Debug($"Finished parsing the response doucment {document.ID}"); }
/// <summary> /// Create a new Excel topic. /// /// An Excel topic is a cell. We may have multiple Excel topics listening to the same /// NMS topic. /// /// Parse the supplied values and create a mapping so that the application can /// send data back to the correct topic/cell. /// </summary> /// <param name="topicId"></param> /// <param name="strings"> /// The first value is a string representing the topic. /// The second value is the field of interest. /// The third (optional) value is the broker. /// </param> /// <param name="getNewValues"></param> /// <returns></returns> public object ConnectData(int topicId, ref Array strings, ref bool getNewValues) { getNewValues = true; // over-write any saved values in the spreadsheet TopicDetails details = null; try { _log.Info("Creating subscriber for Excel topic " + topicId); // If we have a brokerUrl use it, otherwise use the default broker details = new TopicDetails { TopicId = topicId, Topic = ((string)strings.GetValue(0)), Field = ((string)strings.GetValue(1)), BrokerUrl = _config.MarketDataBrokerUrl }; if (strings.Length > 2) { details.BrokerUrl = (string)strings.GetValue(2); } // setup our mappings lock (_topicToDetails) { _topicToDetails.Add(topicId, details); var detailList = GetFieldDetails(details); if (!detailList.Contains(details)) { detailList.Add(details); } var broker = BrokerFactory.Broker(details.BrokerUrl); var subscriber = broker.TopicSubscriber(details.Topic, _topicHandler.OnMessageHandler); if (!_brokers.ContainsKey(details.BrokerUrl)) { _brokers.Add(details.BrokerUrl, broker); } var rt = LookupValueFor(details.BrokerUrl, details.Topic, details.Field); if (rt != null) { return(rt); } } switch (details.Field) { case "productVersion": return(_version); case "brokerUrl": return(_config.MarketDataBrokerUrl); } return("N/A"); } catch (Exception e) { _log.Error("Tried to subscribe to topic " + strings, e); if (details != null) { SetLookupValue(details.BrokerUrl, details.Topic, details.Field, "#Error"); } return("#Error"); } }
/// <summary> /// Parses the ms-tnef stream from the provided <see cref="System.IO.Stream" />. /// </summary> /// <param name="path">A <see cref="System.String" /> specifying the path on which to save the attachments found. Specify the <b>null</b> reference to save them in memory as <see cref="System.IO.MemoryStream" /> instances instead.</param> /// <returns><b>true</b> if parsing is successful. <b>false</b> otherwise.</returns> public bool Parse(System.String path) { if (this._reader == null || !this._reader.BaseStream.CanRead) { return(false); } int sig = this.ReadInt(); if (sig != TnefSignature) { #if LOG if (logger.IsErrorEnabled) { logger.Error(System.String.Concat("Tnef signature not matched [", sig, "]<>[", TnefSignature, "]")); } #endif return(false); } bool error = false; this._attachments = new System.Collections.ArrayList(); ushort key = this.ReadUInt16(); System.Text.Encoding enc = anmar.SharpMimeTools.SharpMimeHeader.EncodingDefault; anmar.SharpMimeTools.SharpAttachment attachment_cur = null; for (System.Byte cur = this.ReadByte(); cur != System.Byte.MinValue; cur = ReadByte()) { TnefLvlType lvl = (TnefLvlType)anmar.SharpMimeTools.SharpMimeTools.ParseEnum(typeof(TnefLvlType), cur, TnefLvlType.Unknown); // Type int type = this.ReadInt(); // Size int size = this.ReadInt(); // Attibute name and type TnefAttribute att_n = (TnefAttribute)anmar.SharpMimeTools.SharpMimeTools.ParseEnum(typeof(TnefAttribute), (ushort)((type << 16) >> 16), TnefAttribute.Unknown); TnefDataType att_t = (TnefDataType)anmar.SharpMimeTools.SharpMimeTools.ParseEnum(typeof(TnefDataType), (ushort)(type >> 16), TnefDataType.Unknown); if (lvl == TnefLvlType.Unknown || att_n == TnefAttribute.Unknown || att_t == TnefDataType.Unknown) { #if LOG if (logger.IsErrorEnabled) { logger.Error(System.String.Concat("Attribute data is not valid [", lvl, "] [type=", type, "->(", att_n, ",", att_t, ")] [size=", size, "]")); } #endif error = true; break; } // Read data System.Byte[] buffer = this.ReadBytes(size); // Read checkSum ushort checksum = this.ReadUInt16(); // Verify checksum if (!this.VerifyChecksum(buffer, checksum)) { #if LOG if (logger.IsErrorEnabled) { logger.Error(System.String.Concat("Checksum validation failed [", lvl, "] [type=", type, "->(", att_n, ",", att_t, ")] [size=", size, "(", (buffer != null)?buffer.Length:0, ")] [checksum=", checksum, "]")); } #endif error = true; break; } size = buffer.Length; #if LOG if (logger.IsDebugEnabled) { logger.Debug(System.String.Concat("[", lvl, "] [type=", type, "->(", att_n, ",", att_t, ")] [size=", size, "(", (buffer != null)?buffer.Length:0, ")] [checksum=", checksum, "]")); } #endif if (lvl == TnefLvlType.Message) { // Text body if (att_n == TnefAttribute.Body) { if (att_t == TnefDataType.atpString) { this._body = enc.GetString(buffer, 0, size); } // Message mapi props (html body, rtf body, ...) } else if (att_n == TnefAttribute.MapiProps) { this.ReadMapi(buffer, size); // Stream Codepage } else if (att_n == TnefAttribute.OEMCodepage) { uint codepage1 = (uint)(buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24)); if (codepage1 > 0) { try { enc = System.Text.Encoding.GetEncoding((int)codepage1); #if LOG if (logger.IsDebugEnabled) { logger.Debug(System.String.Concat("Now using [", enc.EncodingName, "] encoding to decode strings.")); } #endif } catch (System.Exception) {} } } } else if (lvl == TnefLvlType.Attachment) { // Attachment start if (att_n == TnefAttribute.AttachRendData) { System.String name = System.String.Concat("generated_", key, "_", (this._attachments.Count + 1), ".binary"); if (path == null) { attachment_cur = new anmar.SharpMimeTools.SharpAttachment(new System.IO.MemoryStream()); } else { attachment_cur = new anmar.SharpMimeTools.SharpAttachment(new System.IO.FileInfo(System.IO.Path.Combine(path, name))); } attachment_cur.Name = name; // Attachment name } else if (att_n == TnefAttribute.AttachTitle) { if (attachment_cur != null && att_t == TnefDataType.atpString && buffer != null && this._attachments.Count > 0) { // NULL terminated string if (buffer[size - 1] == '\0') { size--; } if (size > 0) { System.String name = enc.GetString(buffer, 0, size); if (name.Length > 0) { attachment_cur.Name = name; // Content already saved, so we have to rename if (attachment_cur.SavedFile != null && attachment_cur.SavedFile.Exists) { try { attachment_cur.SavedFile.MoveTo(System.IO.Path.Combine(path, attachment_cur.Name)); } catch (System.Exception) {} } } } } // Modification and creation date } else if (att_n == TnefAttribute.AttachModifyDate || att_n == TnefAttribute.AttachCreateDate) { if (attachment_cur != null && att_t == TnefDataType.atpDate && buffer != null && size == 14) { int pos = 0; System.DateTime date = new System.DateTime((buffer[pos++] + (buffer[pos++] << 8)), (buffer[pos++] + (buffer[pos++] << 8)), (buffer[pos++] + (buffer[pos++] << 8)), (buffer[pos++] + (buffer[pos++] << 8)), (buffer[pos++] + (buffer[pos++] << 8)), (buffer[pos++] + (buffer[pos++] << 8))); if (att_n == TnefAttribute.AttachModifyDate) { attachment_cur.LastWriteTime = date; } else if (att_n == TnefAttribute.AttachCreateDate) { attachment_cur.CreationTime = date; } } // Attachment data } else if (att_n == TnefAttribute.AttachData) { if (attachment_cur != null && att_t == TnefDataType.atpByte && buffer != null) { if (attachment_cur.SavedFile != null) { System.IO.FileStream stream = null; try { stream = attachment_cur.SavedFile.OpenWrite(); } catch (System.Exception e) { #if LOG if (logger.IsErrorEnabled) { logger.Error(System.String.Concat("Error writting file [", attachment_cur.SavedFile.FullName, "]"), e); } #endif error = true; break; } stream.Write(buffer, 0, size); stream.Flush(); attachment_cur.Size = stream.Length; stream.Close(); stream = null; attachment_cur.SavedFile.Refresh(); // Is name has changed, we have to rename if (attachment_cur.SavedFile.Name != attachment_cur.Name) { try { attachment_cur.SavedFile.MoveTo(System.IO.Path.Combine(path, attachment_cur.Name)); } catch (System.Exception) {} } } else { attachment_cur.Stream.Write(buffer, 0, size); attachment_cur.Stream.Flush(); attachment_cur.Size = attachment_cur.Stream.Length; } this._attachments.Add(attachment_cur); } // Attachment mapi props } else if (att_n == TnefAttribute.Attachment) { this.ReadMapi(buffer, size); } } } if (this._attachments.Count == 0) { this._attachments = null; } return(!error); }
public IceManager(string adapterName, string host, int port, bool catchSignals = true) { IceGridHost = host; IceGridPort = port; Name = adapterName; logger = log4net.LogManager.GetLogger(this.GetType().Name + "::" + Name); _ServantIds = new List<Ice.Identity>(); //keep track of servants for emergency cleanup string myIP = findLocalIPAddress(); logger.Info("My IPAddress is: " + myIP); //initialize Ice Ice.Properties prop = Ice.Util.createProperties(); prop.setProperty("hms.AdapterId", adapterName); prop.setProperty("hms.Endpoints", "tcp -h " + myIP + ":udp -h " + myIP); prop.setProperty("Ice.Default.Locator", "IceGrid/Locator:tcp -p " + IceGridPort + " -h " + IceGridHost); prop.setProperty("Ice.ThreadPool.Server.Size", "5"); prop.setProperty("Ice.ThreadPool.Server.SizeMax", "100000"); prop.setProperty("Ice.ThreadPool.Client.Size", "5"); prop.setProperty("Ice.ThreadPool.Client.SizeMax", "100000"); Ice.InitializationData iceidata = new Ice.InitializationData(); iceidata.properties = prop; Communicator = Ice.Util.initialize(iceidata); // could add sys.argv try { _Adapter = Communicator.createObjectAdapter("hms"); _Adapter.activate(); } catch (Exception ex) { logger.Fatal("Network error, check configuration: " + ex.Message); logger.Fatal("Endpoint(should be local machine): " + prop.getProperty("hms.Endpoints")); logger.Fatal("Locator (should be IceGrid Server): " + prop.getProperty("Ice.Default.Locator")); throw (ex); // we are dead anyway } //Now are we ready to communicate with others //getting usefull proxies try { // proxy to icegrid to register our vc devices Query = IceGrid.QueryPrxHelper.checkedCast(Communicator.stringToProxy("IceGrid/Query")); if (Query == null) { logger.Error("invalid ICeGrid proxy"); } // proxy to icestorm to publish events EventMgr = IceStorm.TopicManagerPrxHelper.checkedCast(Communicator.stringToProxy("EventServer/TopicManager")); if (EventMgr == null) { logger.Error("invalid IceStorm proxy"); } //these 2 objects are only needed to get the IceGrid admin object in order to register _Registry = IceGrid.RegistryPrxHelper.uncheckedCast(Communicator.stringToProxy("IceGrid/Registry")); updateIceGridAdmin(); } catch (Ice.NotRegisteredException e) { logger.Fatal("If we fail here it is probably because the Icebox objects are not registered: " + e.Message); } catch (Exception e) { logger.Fatal("IceGrid Server not found!!!!!: " + e.Message); throw (e);//without yellow page system, there is no need to start } if (catchSignals) { setupSignals(); } }
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); }
static void Main() { bool ok; // Only allow one instance of the switcher to start exclusiveAppMtx = new System.Threading.Mutex(true, "{D39FAB11-ED23-478d-AF57-C638F79A7BA8}", out ok); if (!ok) { return; } log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Assembly.GetExecutingAssembly().Location + ".config")); log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); log.Info("Application Started"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ThreadException += Application_ThreadException; Application.ApplicationExit += Application_ApplicationExit; monitor.RegChanged += new EventHandler(OnRegChanged); monitor.Error += new System.IO.ErrorEventHandler(OnRegMonError); try { log.Info("Starting plugin..."); //Populate notifications from XML file _assembly = Assembly.GetExecutingAssembly(); alertReader = new StreamReader(_assembly.GetManifestResourceStream(Resources.ResourceManager.GetString("strings.xml"))); XmlSerializer deserializer = new XmlSerializer(typeof(List<Alert>)); TextReader textReader = alertReader; alertList = (List<Alert>)deserializer.Deserialize(textReader); textReader.Close(); } catch (Exception ex) { log.Error(ex.ToString()); MessageBox.Show(Resources.ResourceManager.GetString("Error loading")); } if (SetupPlugin()) { OnRegChanged(null, EventArgs.Empty); _systray = new TrayIcon(); Application.Run(); } }
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { log4net.ILog log = log4net.LogManager.GetLogger("testApp.Logging");//获取一个日志记录器 log.Error("系统全局异常--Application_ThreadException", e.Exception); }
/// <summary> /// 输出日志到Log4Net /// </summary> /// <param name="t"></param> /// <param name="ex"></param> #region static void WriteLog(Type t, Exception ex) public static void WriteLog(Type t, Exception ex) { log4net.ILog log = log4net.LogManager.GetLogger(t); log.Error("Error", ex); }
static public void Main(string[] Args) { //Upgrade settings Assembly a = Assembly.GetExecutingAssembly(); Version appVersion = a.GetName().Version; string appVersionString = appVersion.ToString(); log.DebugFormat("Application version of new settings {0}", appVersionString); try { if (Properties.Settings.Default.ApplicationVersion != appVersion.ToString()) { log.Debug("Upgrading settings..."); Properties.Settings.Default.Upgrade(); // if program's hash has changed (e.g. by upgrading to .NET 4.0), then Upgrade() doesn't import the previous application settings // because it cannot locate a previous user.config file. In this case a new user.config file is created with the default settings. // We will try and find a config file from a previous installation and update the settings from it if (Properties.Settings.Default.ApplicationVersion == "" && Properties.Settings.Default.DoUpgrade) { SettingsUpdate.Update(); } log.DebugFormat("Settings upgraded from '{0}' to '{1}'", Properties.Settings.Default.ApplicationVersion, appVersionString); Properties.Settings.Default.ApplicationVersion = appVersionString; Settings.TrySaveSettings(); } } catch (ConfigurationErrorsException ex) { log.Error("Could not load settings.", ex); var msg = string.Format("{0}\n\n{1}", Messages.MESSAGEBOX_LOAD_CORRUPTED_TITLE, string.Format(Messages.MESSAGEBOX_LOAD_CORRUPTED, Settings.GetUserConfigPath())); using (var dlg = new ThreeButtonDialog(new ThreeButtonDialog.Details(SystemIcons.Error, msg, Messages.XENCENTER)) { StartPosition = FormStartPosition.CenterScreen, //For reasons I do not fully comprehend at the moment, the runtime //overrides the above StartPosition with WindowsDefaultPosition if //ShowInTaskbar is false. However it's a good idea anyway to show it //in the taskbar since the main form is not launcched at this point. ShowInTaskbar = true }) { dlg.ShowDialog(); } Application.Exit(); return; } // Reset statics, because XenAdminTests likes to call Main() twice. TestExceptionString = null; Exiting = false; // Clear XenConnections and History so static classes like OtherConfigAndTagsWatcher // listening to changes still work when Main is called more than once. ConnectionsManager.XenConnections.Clear(); ConnectionsManager.History.Clear(); Search.InitSearch(Branding.Search); TreeSearch.InitSearch(); ArgType argType = ArgType.None; AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ThreadException -= Application_ThreadException; Application.ThreadException += Application_ThreadException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { if (SystemInformation.FontSmoothingType == 2) // ClearType { TransparentUsually = SystemColors.Window; } } catch (NotSupportedException) { // Leave TransparentUsually == Color.Transparent. This is an old platform // without FontSmoothingType support. } switch (Environment.OSVersion.Version.Major) { case 6: // Vista, 2K8, Win7. if (Application.RenderWithVisualStyles) { // Vista, Win7 with styles. TitleBarStartColor = Color.FromArgb(242, 242, 242); TitleBarEndColor = Color.FromArgb(207, 207, 207); TitleBarBorderColor = Color.FromArgb(160, 160, 160); TitleBarForeColor = Color.FromArgb(60, 60, 60); HeaderGradientForeColor = Color.White; HeaderGradientFont = new Font(DefaultFont.FontFamily, 11.25f); TabbedDialogHeaderFont = HeaderGradientFont; TabPageRowBorder = Color.Gainsboro; TabPageRowHeader = Color.WhiteSmoke; } else { // 2K8 and Vista, Win7 without styles. TitleBarStartColor = ProfessionalColors.OverflowButtonGradientBegin; TitleBarEndColor = ProfessionalColors.OverflowButtonGradientEnd; TitleBarBorderColor = TitleBarEndColor; TitleBarForeColor = SystemColors.ControlText; HeaderGradientForeColor = SystemColors.ControlText; HeaderGradientFont = new Font(DefaultFont.FontFamily, DefaultFont.Size + 1f, FontStyle.Bold); TabbedDialogHeaderFont = HeaderGradientFont; TabPageRowBorder = Color.DarkGray; TabPageRowHeader = Color.Silver; } break; default: TitleBarStartColor = ProfessionalColors.OverflowButtonGradientBegin; TitleBarEndColor = ProfessionalColors.OverflowButtonGradientEnd; TitleBarBorderColor = TitleBarEndColor; TitleBarForeColor = SystemColors.ControlText; HeaderGradientForeColor = Application.RenderWithVisualStyles ? Color.White : SystemColors.ControlText; HeaderGradientFont = new Font(DefaultFont.FontFamily, DefaultFont.Size + 1f, FontStyle.Bold); TabbedDialogHeaderFont = new Font(DefaultFont.FontFamily, DefaultFont.Size + 1.75f, FontStyle.Bold); TabPageRowBorder = Color.DarkGray; TabPageRowHeader = Color.Silver; break; } // Force the current culture, to make the layout the same whatever the culture of the underlying OS (CA-46983). Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = new CultureInfo(InvisibleMessages.LOCALE, false); if (string.IsNullOrEmpty(Thread.CurrentThread.Name)) { Thread.CurrentThread.Name = "Main program thread"; } ServicePointManager.DefaultConnectionLimit = 20; ServicePointManager.ServerCertificateValidationCallback = SSL.ValidateServerCertificate; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; Session.UserAgent = string.Format("XenCenter/{0}", ClientVersion()); RememberProxyAuthenticationModules(); ReconfigureConnectionSettings(); log.Info("Application started"); logSystemDetails(); OptionsDialog.Log(); if (Args.Length > 0) { log.InfoFormat("Args[0]: {0}", Args[0]); } List <string> sanitizedArgs = new List <string>(Args); // Remove the '--wait' argument, which may have been passed to the splash screen sanitizedArgs.Remove("--wait"); string[] args = null; if (sanitizedArgs.Count > 1) { argType = ParseFileArgs(sanitizedArgs, out args); if (argType == ArgType.Passwords) { log.DebugFormat("Handling password request using '{0}'", args[0]); try { PasswordsRequest.HandleRequest(args[0]); } catch (Exception exn) { log.Fatal(exn, exn); } Application.Exit(); return; } } else if (sanitizedArgs.Count == 1 && sanitizedArgs[0] == "messageboxtest") { new MessageBoxTest().ShowDialog(); Application.Exit(); return; } else if (sanitizedArgs.Count > 0) { log.Warn("Unrecognised command line options"); } try { ConnectPipe(); } catch (Win32Exception exn) { log.Error("Creating named pipe failed. Continuing to launch XenCenter.", exn); } Application.ApplicationExit -= Application_ApplicationExit; Application.ApplicationExit += Application_ApplicationExit; MainWindow mainWindow = new MainWindow(argType, args); Application.Run(mainWindow); log.Info("Application main thread exited"); }
/// <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(); }
/// <summary> /// Výpočet příští revize dle sériových čísel v provozu pro umisteni která nejsou resena samostatně /// </summary> /// <param name="conn"></param> /// <returns></returns> private static List <VypocetPlanuRevizi> Calculate(string conn, int year) { string SAP_dtb = ConfigurationManager.ConnectionStrings["SAP_dtb"].ConnectionString; string RS_dtb = ConfigurationManager.ConnectionStrings["RS_dtb"].ConnectionString; List <VypocetPlanuRevizi> listplanrev = new List <VypocetPlanuRevizi>(); StringBuilder sql = new StringBuilder(); sql.Append(" select x.ZakaznikId , x.Zakaznik,x.ProvozId ,x.Provoz, "); sql.Append(" min(x.NextRevize) 'R1', Year(min(x.NextRevize)) as 'Rok_R1', case when Month(min(x.NextRevize)) <= 6 then 1 else 2 end as 'R1POL',"); sql.Append(" min(x.Next2Revize) 'R2', Year(min(x.Next2Revize)) as 'Rok_R2', case when Month(min(x.Next2Revize)) <= 6 then 1 else 2 end as 'R2POL'"); sql.Append(" from"); sql.Append(" ("); sql.Append(" select t1.Id as 'ZakaznikId', t1.NazevZakaznika as 'Zakaznik',"); sql.Append(" t2.Id as 'ProvozId', t2.NazevProvozu as 'Provoz', t3.NazevUmisteni, t6.Nazev, t5.seriovecislo,"); sql.Append(" DATEADD(month, convert(int, t6.periodarevize), coalesce(t4.datumrevize, t4.datumprirazeni)) as 'NextRevize',"); sql.Append(" DATEADD(month, convert(int, t6.periodarevize), DATEADD(month, convert(int, t6.periodarevize), coalesce(t4.datumrevize, t4.datumprirazeni))) as 'Next2Revize',"); sql.Append(" DATEADD(month, convert(int, t6.periodabaterie), coalesce(t4.datumbaterie, t4.datumprirazeni)) as 'NextBaterie',"); sql.Append(" DATEADD(month, convert(int, t6.periodapyro), coalesce(t4.datumpyro, t4.datumprirazeni)) as 'NextPyro',"); sql.Append(" DATEADD(month, convert(int, t6.periodatlakovazk), coalesce(t4.datumtlkzk, t4.datumprirazeni)) as 'NextTlkZk'"); sql.Append($" from [{RS_dtb}].[dbo].[Region] t0"); sql.Append($" left join [{RS_dtb}].[dbo].[Zakaznik] t1 on t0.id = t1.regionid"); sql.Append($" left join [{RS_dtb}].[dbo].[provoz] t2 on t2.zakaznikid = t1.id"); sql.Append($" left join [{RS_dtb}].[dbo].[umisteni] t3 on t3.provozid = t2.id and t3.SamostatnaRevize = 'false'"); sql.Append($" left join [{RS_dtb}].[dbo].[scprovozu] t4 on t4.provozid = t2.id and t4.umisteni = t3.id"); sql.Append($" left join [{RS_dtb}].[dbo].[SerioveCislo] t5 on t5.Id = t4.SerioveCisloId"); sql.Append($" left join [{RS_dtb}].[dbo].[Artikl] t6 on t5.ArtiklId = T6.Id"); sql.Append(" where t3.id is not null and t4.id is not null"); sql.Append(" ) x"); sql.Append(" group by x.ZakaznikId, x.Zakaznik,x.ProvozId, x.Provoz"); //LOGOVANI log.Debug($"Calculate pro revizi pro rok: {year}"); log.Debug(sql.ToString()); SqlConnection cnn = new SqlConnection(conn); SqlCommand cmd = new SqlCommand(); cmd.Connection = cnn; cmd.CommandText = sql.ToString(); cnn.Open(); cmd.ExecuteNonQuery(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { //MAKES IT HERE while (dr.Read()) { VypocetPlanuRevizi item = new VypocetPlanuRevizi(); try { item.ZakaznikId = dr.GetInt32(dr.GetOrdinal("ZakaznikId")); } catch (Exception ex) { log.Error("Error number: " + ex.HResult + " - " + ex.Message + " - " + ex.Data + " - " + ex.InnerException); } try { item.Zakaznik = dr.GetString(dr.GetOrdinal("Zakaznik")); } catch (Exception ex) { log.Error("Error number: " + ex.HResult + " - " + ex.Message + " - " + ex.Data + " - " + ex.InnerException); } try { item.ProvozId = dr.GetInt32(dr.GetOrdinal("ProvozId")); } catch (Exception ex) { log.Error("Error number: " + ex.HResult + " - " + ex.Message + " - " + ex.Data + " - " + ex.InnerException); } try { item.Provoz = dr.GetString(dr.GetOrdinal("Provoz")); } catch (Exception ex) { log.Error("Error number: " + ex.HResult + " - " + ex.Message + " - " + ex.Data + " - " + ex.InnerException); } try { item.R1 = dr.GetDateTime(dr.GetOrdinal("R1")); } catch (Exception ex) { log.Error("Error number: " + ex.HResult + " - " + ex.Message + " - " + ex.Data + " - " + ex.InnerException); } try { item.R1POL = dr.GetInt32(dr.GetOrdinal("R1POL")); } catch (Exception ex) { log.Error("Error number: " + ex.HResult + " - " + ex.Message + " - " + ex.Data + " - " + ex.InnerException); } try { item.Rok_R1 = dr.GetInt32(dr.GetOrdinal("Rok_R1")); } catch (Exception ex) { log.Error("Error number: " + ex.HResult + " - " + ex.Message + " - " + ex.Data + " - " + ex.InnerException); } try { item.R2 = dr.GetDateTime(dr.GetOrdinal("R2")); } catch (Exception ex) { log.Error("Error number: " + ex.HResult + " - " + ex.Message + " - " + ex.Data + " - " + ex.InnerException); } try { item.R2POL = dr.GetInt32(dr.GetOrdinal("R2POL")); } catch (Exception ex) { log.Error("Error number: " + ex.HResult + " - " + ex.Message + " - " + ex.Data + " - " + ex.InnerException); } try { item.Rok_R2 = dr.GetInt32(dr.GetOrdinal("Rok_R2")); } catch (Exception ex) { log.Error("Error number: " + ex.HResult + " - " + ex.Message + " - " + ex.Data + " - " + ex.InnerException); } listplanrev.Add(item); } } cnn.Close(); return(listplanrev); }
public static void Crawl() { log.Info("Starting Crawler..."); using (BlockingCollection <string> urlsToCrawl = new BlockingCollection <string>()) { log.Debug("Adding seed url: " + mStartUrl); urlsToCrawl.Add(mStartUrl); Parallel.ForEach(urlsToCrawl.GetConsumingEnumerable(), url =>//(string url in ) { int threadId = Interlocked.Increment(ref nextThreadId); if (!threadTracking.TryAdd(threadId, true)) { log.Error("Failed to track thread with id: " + threadId); return; } log.Debug("Started new thread(ID: " + threadId + ") to process URL: " + url); //handle adding new links to the crawling collection first so new threads can spin up. foreach (string newUrlToCrawl in ProcessNewlyFoundLinks(ExtractHttpLinks(url))) { string newUrlToCrawlStripped = StripQueryParametersFromUriString(newUrlToCrawl); lock (myLock) { if (!urlsToCrawl.Contains(newUrlToCrawlStripped)) { urlsToCrawl.Add(newUrlToCrawlStripped); } } } if (mUniqueResources.TryAdd(url, GetStatusCode(StripQueryParametersFromUriString(url)))) { log.Info("Added new unique resource: " + url); } else { log.Warn("Failed to add new unique resource. Likely already exists: " + url); } bool temp; if (!threadTracking.TryRemove(threadId, out temp)) { throw new Exception("Failed to remove thread ID: " + threadId); } if (threadTracking.IsEmpty) { log.Info("All processing threads appear to have stopped, waiting two minutes then shutting down."); Thread.Sleep(120000);//wait two more minutes to give all remaining threads ample time to get out. if (threadTracking.IsEmpty) { urlsToCrawl.CompleteAdding(); log.Info("Shutting down."); } else { log.Info("Aborting shutdown, new threads found and running."); } } }); } }
private void NeverCrash() { DispatcherUnhandledException += (sender, args) => Log.Error("Dispatcher unhandled exception", args.Exception); }
public string InsSubmitBiddings(INF_BIDDINGS data, List <INF_BIDDINGDETAILS> lItemDetail, List <INF_BIDDINGATTACHMENT> lItemAttach) { Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); IDbConnection conn = null; IDbTransaction tran = null; string ret = string.Empty; try { //SET CONNECTION conn = ConnectionFactory.GetConnection(); conn.ConnectionString = ConfigurationManager.GetConfiguration().DbConnectionString; //OPEN CONNECTION conn.Open(); tran = conn.BeginTransaction(IsolationLevel.Serializable); Inf_BiddingsBL bl = new Inf_BiddingsBL(conn, tran); string _biddingNo = string.Empty; _biddingNo = bl.InsertBiddings(data); if (!string.IsNullOrWhiteSpace(_biddingNo)) { ret = _biddingNo; bool insResut = false; foreach (INF_BIDDINGDETAILS item in lItemDetail) { INF_BIDDINGDETAILS insItem = new INF_BIDDINGDETAILS(); insItem.BiddingsNo = Int64.Parse(_biddingNo); insItem.ItemColumn1 = item.ItemColumn1; insItem.ItemColumn2 = item.ItemColumn2; insItem.ItemColumn3 = item.ItemColumn3; insItem.ItemColumn4 = item.ItemColumn4; insItem.ItemColumn5 = item.ItemColumn5; insItem.ItemColumn6 = item.ItemColumn6; insItem.ItemColumn7 = item.ItemColumn7; insItem.ItemColumn8 = item.ItemColumn8; insItem.CreatedBy = data.CreatedBy; insItem.CreatedDate = DateTime.Now; insItem.UpdatedBy = data.UpdatedBy; insItem.UpdatedDate = DateTime.Now; insResut = bl.InsertBiddingDetails(insItem); } if (insResut) { if (lItemAttach != null && lItemAttach.Count > 0) { foreach (INF_BIDDINGATTACHMENT itemAttach in lItemAttach) { INF_BIDDINGATTACHMENT insItem = new INF_BIDDINGATTACHMENT(); insItem.BiddingsNo = Int64.Parse(_biddingNo); insItem.AttachFilePath = itemAttach.AttachFilePath; insItem.Description = itemAttach.Description; insItem.FileName = itemAttach.FileName; insItem.CreatedBy = data.CreatedBy; insItem.CreatedDate = DateTime.Now; insItem.UpdatedBy = data.UpdatedBy; insItem.UpdatedDate = DateTime.Now; insResut = bl.InsertBiddingAttachment(insItem); } } } } tran.Commit(); } catch (Exception ex) { tran.Rollback(); ret = string.Empty; logger.Error(ex.Message); logger.Error(ex.StackTrace); } finally { if (tran != null) { tran.Dispose(); } if (conn != null) { if (conn.State == ConnectionState.Open) { conn.Close(); } conn.Dispose(); } } return(ret); }
public TDSListener(TDSProxyService service, ListenerElement configuration) { var insideAddresses = Dns.GetHostAddresses(configuration.ForwardToHost); if (0 == insideAddresses.Length) { log.ErrorFormat("Unable to resolve forwardToHost=\"{0}\" for listener {1}", configuration.ForwardToHost, configuration.Name); _stopped = true; return; } ForwardTo = new IPEndPoint(insideAddresses.First(), configuration.ForwardToPort); _service = service; var bindToEP = new IPEndPoint(configuration.BindToAddress ?? IPAddress.Any, configuration.ListenOnPort); try { var catalog = new AggregateCatalog(from AuthenticatorElement a in configuration.Authenticators select new AssemblyCatalog(a.Dll)); _mefContainer = new CompositionContainer(catalog); var allExports = _mefContainer.GetExports <IAuthenticator>().ToDictionary(a => a.GetType().GetGenericArguments()[0].FullName); var authenticators = new Lazy <IAuthenticator> [configuration.Authenticators.Count]; bool die = false; var used = new List <Lazy <IAuthenticator> >(); for (int i = 0; i < configuration.Authenticators.Count; i++) { var a = configuration.Authenticators[i]; if (!allExports.TryGetValue(a.Class, out var export)) { log.ErrorFormat( "For authenticator {0} found dll {1} but not class {2} (exports in catalog: {3})", a.Name, a.Dll, a.Class, string.Join("; ", allExports.Keys)); die = true; } used.Add(export); authenticators[i] = export; } if (die) { Dispose(); return; } _authenticators = authenticators; _mefContainer.ReleaseExports(allExports.Values.Except(used)); } catch (CompositionException ce) { log.Error( "Failed to find an authenticator. Composition errors:\r\n\t" + string.Join("\r\n\t", ce.Errors.Select(err => "Element: " + err.Element.DisplayName + ", Error: " + err.Description)), ce); Dispose(); return; } catch (Exception e) { log.Error("Failed to find an authenticator", e); Dispose(); return; } try { log.DebugFormat("Opening SSL certificate store {0}.{1}", configuration.SslCertStoreLocation, configuration.SslCertStoreName); var store = new X509Store(configuration.SslCertStoreName, configuration.SslCertStoreLocation); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); var matching = store.Certificates.Find(X509FindType.FindByThumbprint, configuration.SslCertSubjectThumbprint, false); if (0 == matching.Count) { log.ErrorFormat( "Failed to find SSL certification with thumbprint '{0}' in location {1}, store {2}.", configuration.SslCertSubjectThumbprint, configuration.SslCertStoreLocation, configuration.SslCertStoreName); Dispose(); return; } Certificate = matching[0]; } catch (Exception e) { log.Error("Failed to load SSL certificate", e); Dispose(); return; } _tcpListener = new TcpListener(bindToEP); _tcpListener.Start(); _tcpListener.BeginAcceptTcpClient(AcceptConnection, _tcpListener); _service.AddListener(this); log.InfoFormat( "Listening on {0} and forwarding to {1} (SSL cert DN {2}; expires {5} serial {3}; authenticators {4})", bindToEP, ForwardTo, Certificate.Subject, Certificate.GetSerialNumberString(), string.Join(", ", from a in Authenticators select a.GetType().FullName), Certificate.GetExpirationDateString()); }
public HttpResponseMessage SignIn(ThirdPartyUserLogin model) { try { //check if user exists ThirdPartyUserLogin check = _thirdPartyService.GetByEmail(model.Email); if (check == null) { //Register User int result = _thirdPartyService.Create(model); //If the registration does not work if (result == null || result <= 0) { ErrorResponse resp = new ErrorResponse("Unsuccessful Registration Attempt"); return(Request.CreateResponse(HttpStatusCode.OK, resp)); } //If succesfull, log the user in else { IUserAuthData success = _userService.LogIn(model.Email, model.Password); if (success != null) { List <int> pID = _userService.GetPerson(success.Id); LoginResponse <IUserAuthData> resp = new LoginResponse <IUserAuthData>(); resp.Item = success; resp.PersonID = pID; return(Request.CreateResponse(HttpStatusCode.OK, resp)); } else { ErrorResponse resp = new ErrorResponse("Uncessful Login Attempt"); return(Request.CreateResponse(HttpStatusCode.OK, resp)); } } } else //check for 3rd Party Type { if (check.ThirdPartyTypeId > 0) { IUserAuthData success = _userService.LogIn(model.Email, model.Password); if (success != null) { List <int> pID = _userService.GetPerson(success.Id); LoginResponse <IUserAuthData> resp = new LoginResponse <IUserAuthData>(); resp.Item = success; resp.PersonID = pID; return(Request.CreateResponse(HttpStatusCode.OK, resp)); } else { ErrorResponse resp = new ErrorResponse("Uncessful Login Attempt"); return(Request.CreateResponse(HttpStatusCode.OK, resp)); } } else { ErrorResponse resp = new ErrorResponse("Uncessful Login Attempt. User is already registered."); return(Request.CreateResponse(HttpStatusCode.OK, resp)); } } }//Mdoel State Valid catch (Exception ex) { log.Error(ex.Message, ex); return(Request.CreateResponse(HttpStatusCode.BadRequest, ex)); } }
public static void WriteErr(string msg) { log.Error(msg + "Err级别,报错"); }
protected override Problem RunCheck() { if (MetadataSession == null) { return(null); } try { if (xenObject is VM) { VM.assert_can_be_recovered(MetadataSession, xenObject.opaque_ref, Pool.Connection.Session.uuid); } if (xenObject is VM_appliance) { VM_appliance.assert_can_be_recovered(MetadataSession, xenObject.opaque_ref, Pool.Connection.Session.uuid); } } catch (Failure f) { if (f.ErrorDescription.Count > 2 && f.ErrorDescription[0] == Failure.VM_REQUIRES_SR) { List <SR> requiredSRs = GetRequiredSRs(xenObject) ?? new List <SR>(); SR sr = RetrieveSR(new XenRef <SR>(f.ErrorDescription[2])); if (!requiredSRs.Contains(sr)) { requiredSRs.Add(sr); } //search for local SRs SR localSR = requiredSRs.Find(item => !item.shared); if (localSR != null) { // there is local SR which means the VM cannot be recovered return(new MissingSRProblem(this, Pool, localSR, null)); } //search for FibreChannel SRs List <SRDeviceConfig> srDeviceConfigList = GetFCSRDeviceConfigList(requiredSRs); if (srDeviceConfigList.Count == 0) { return(new MissingSRProblem(this, Pool, requiredSRs[0], null)); } if (srDeviceConfigList.Count == 1) { return(new MissingSRProblem(this, Pool, srDeviceConfigList[0].SR, srDeviceConfigList[0].DeviceConfig)); } return(new MissingMultipleFCSRsProblem(this, Pool, srDeviceConfigList)); } } catch (Exception e) { log.ErrorFormat("There was an error calling assert_can_be_recovered for object {0}", xenObject.Name); log.Error(e, e); } return(null); }
public void ProcessRequest(HttpContext context) { try { string requestType = context.Request["reqtype"]; logger.Info(requestType); if (requestType != "AgentLogin" && requestType != "InitUserInfo" && !ValidUser(context)) { if (requestType == "FinancialUpload" || requestType == "InvitationUpload") { string redirect = string.Empty; redirect = "window.parent.location.href = '/login.html'"; context.Response.Write(string.Format("<script>{0};</script>", redirect)); } else { context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new { resCode = -1 })); } context.Response.End(); } Workbook workBook = null; string resp = RequestHandler(requestType, context.Request, out workBook); if (requestType.ToLower().StartsWith("export")) { resp = resp.Substring(1, resp.Length - 2); if (resp.Length > 0) { //失败操作 if (resp != "-1") { var bytes = Convert.FromBase64String(resp); string fileName = string.Empty; switch (requestType.ToLower()) { case "exportwithdrawapply": { fileName = HttpUtility.UrlEncode("提现记录明细_" + DateTime.Now.ToString("yyyyMMdd")); break; } case "exportreport": { fileName = HttpUtility.UrlEncode("业务报表_" + DateTime.Now.ToString("yyyyMMdd")); break; } } context.Response.Clear(); context.Response.ClearContent(); context.Response.ClearHeaders(); context.Response.ContentType = "application/octet-stream"; context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx"); context.Response.AddHeader("Content-Length", bytes.Length.ToString()); context.Response.OutputStream.Write(bytes, 0, bytes.Length); } } } else if (requestType.ToLower().EndsWith("upload")) { if (string.IsNullOrEmpty(resp)) { using (MemoryStream ms = new MemoryStream()) { workBook.Save(ms, SaveFormat.Xlsx); var bytes = ms.ToArray(); string fileName = HttpUtility.UrlEncode("导入结果反馈"); context.Response.Clear(); context.Response.ClearContent(); context.Response.ClearHeaders(); context.Response.ContentType = "application/octet-stream"; context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx"); context.Response.AddHeader("Content-Length", bytes.Length.ToString()); context.Response.OutputStream.Write(bytes, 0, bytes.Length); } } else { string redirect = string.Empty; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); string timestamp = Math.Round((DateTime.Now - startTime).TotalSeconds / 1000).ToString(); string type = requestType.ToLower().Substring(0, requestType.ToLower().LastIndexOf("upload")); redirect = string.Format("window.parent.document.getElementById('myIframe').src = 'biz.html#/{0}?v={1}'", type, timestamp); context.Response.Write(string.Format("<script>alert('{0}');{1};</script>", resp, redirect)); } } else { context.Response.Write(resp); } } catch (Exception ex) { logger.Error(ex.StackTrace); } context.Response.End(); }
private void dugmePretraga_Click(object sender, EventArgs e) { //pretraga sudenta if (!Validacija()) { MessageBox.Show(MenadzerStatusnihKodova.NEPRAVILAN_UNOS_PORUKA, MenadzerStatusnihKodova.NEPRAVILAN_UNOS, MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return; } try { panelPrikazRezultata.Visible = false; Dictionary <string, string> rezultat = Baza.daj_instancu().Daj_informacije_o_studentu(Convert.ToInt32(brojIndeksaUnos.Text)); if (rezultat.Count.Equals(0)) { MessageBox.Show(MenadzerStatusnihKodova.STUDENT_NIJE_PRONADJEN, MenadzerStatusnihKodova.ZAPIS_NIJE_PRONADJEN, MessageBoxButtons.OK, MessageBoxIcon.Information); } else { studentImePrikaz.Text = rezultat["ime"] + " " + rezultat["prezime"]; brojIndeksaPrikaz.Text = rezultat["broj_indeksa"]; this.id_studenta_za_brisanje = Convert.ToInt32(rezultat["broj_indeksa"]); prosekPrikaz.Text = rezultat["prosek"]; espbPrikaz.Text = rezultat["espb"]; fakultetPrikaz.Text = rezultat["fakultet"]; smerPrikaz.Text = rezultat["smer"]; jmbgPrikaz.Text = rezultat["jmbg"]; if (Convert.ToInt32(rezultat["diplomirao"]).Equals(MenadzerStatusnihKodova.STUDENT_NIJE_DIPLOMIRAO)) { diplomiraoPrikaz.Text = MenadzerStatusnihKodova.STUDENT_NIJE_DIPLOMIRAO_PORUKA; } else { diplomiraoPrikaz.Text = MenadzerStatusnihKodova.STUDENT_DIPLOMIRAO_PORUKA; } if (Convert.ToInt32(rezultat["status_studenta"]).Equals(MenadzerStatusnihKodova.STUDENT_STATUS_BUDZET)) { statusPrikaz.Text = MenadzerStatusnihKodova.STUDENT_BUDZET_PORUKA; } else { statusPrikaz.Text = MenadzerStatusnihKodova.STUDENT_SAMOFINANSIRANJE_PORUKA; } dugmeUkloniProfesora.Enabled = true; panelPrikazRezultata.Visible = true; } } catch (Exception exception) { loger.Error(MenadzerStatusnihKodova.GRESKA, exception); MessageBox.Show(MenadzerStatusnihKodova.GRESKA_TEKST, MenadzerStatusnihKodova.GRESKA, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { brojIndeksaUnos.Clear(); } }
public static void Main(string[] args) { Console.WriteLine( "MediaWiki Lucene search indexer - runtime search daemon.\n" + "Version 20051104, copyright 2004 Kate Turner.\n" ); int i = 0; while (i < args.Length - 1) { if (args[i].Equals("--port")) { port = Int32.Parse(args[++i]); } else if (args[i].Equals("--configfile")) { Configuration.SetConfigFile(args[++i]); } else { break; } ++i; } Configuration.SetIndexSection("Daemon"); config = Configuration.Open(); log.Info("Binding server to port " + port); try { sock = new TcpListener(port); } catch (Exception e) { log.Fatal("Error: bind error: " + e.Message); return; } sock.Start(); int maxWorkers = 10; string max = config.GetString("Daemon", "maxworkers"); if (max != null) { maxWorkers = int.Parse(max); } /* * log.Debug("Blah blah debug"); * log.Info("Blah blah info"); * log.Error("Blah blah error"); * log.Fatal("Blah blah fatal"); */ // Initialise statistics stats = new Statistics(1000, statsPeriod); if (config.GetBoolean("Ganglia", "report")) { // Run a background thread to push our runtime stats to Ganglia statsThread = new Thread(StatisticsThread); string gangliaPort = config.GetString("Ganglia", "port"); if (gangliaPort != null) { stats.GangliaPort = Int32.Parse(gangliaPort); } string gangliaInterface = config.GetString("Ganglia", "interface"); if (gangliaInterface != null) { stats.GangliaInterface = gangliaInterface; } statsThread.Start(); } // go! for (;;) { TcpClient client; try { log.Debug("Listening..."); client = sock.AcceptTcpClient(); } catch (Exception e) { log.Error("accept() error: " + e.Message); continue; } int threadCount = Worker.OpenCount; if (threadCount > maxWorkers) { stats.Add(false, 0, threadCount); log.Error("too many connections, skipping a request"); } else { Worker worker = new Worker(client.GetStream(), config); ThreadPool.QueueUserWorkItem(worker.Run); } } }
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { log4net.ILog log = log4net.LogManager.GetLogger("testApp.Logging");//获取一个日志记录器 log.Error("系统全局异常--CurrentDomain_UnhandledException", e.ExceptionObject as Exception); }
// ================================================== // Application Event handlers // ================================================== private void HandleError(string message, Exception error = null) { MessageBox.Show(message, Resources.ErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); Log.Error(message, error); }
private void DownloadFile() { int errorCount = 0; bool needToRetry = false; client = new WebClient(); //register download events client.DownloadProgressChanged += client_DownloadProgressChanged; client.DownloadFileCompleted += client_DownloadFileCompleted; // register event handler to detect changes in network connectivity NetworkChange.NetworkAvailabilityChanged += NetworkAvailabilityChanged; try { do { if (needToRetry) { Thread.Sleep(SLEEP_TIME_BEFORE_RETRY_MS); } needToRetry = false; client.Proxy = XenAdminConfigManager.Provider.GetProxyFromSettings(null, false); //start the download patchDownloadState = DownloadState.InProgress; client.DownloadFileAsync(address, outputFileName); bool patchDownloadCancelling = false; //wait for the file to be downloaded while (patchDownloadState == DownloadState.InProgress) { if (!patchDownloadCancelling && (Cancelling || Cancelled)) { Description = Messages.DOWNLOAD_AND_EXTRACT_ACTION_DOWNLOAD_CANCELLED_DESC; client.CancelAsync(); patchDownloadCancelling = true; } Thread.Sleep(SLEEP_TIME_TO_CHECK_DOWNLOAD_STATUS_MS); } if (patchDownloadState == DownloadState.Cancelled) { throw new CancelledException(); } if (patchDownloadState == DownloadState.Error) { needToRetry = true; // this many errors so far - including this one errorCount++; // logging only, it will retry again. log.ErrorFormat( "Error while downloading from '{0}'. Number of errors so far (including this): {1}. Trying maximum {2} times.", address, errorCount, MAX_NUMBER_OF_TRIES); log.Error(patchDownloadError ?? new Exception(Messages.ERROR_UNKNOWN)); } } while (errorCount < MAX_NUMBER_OF_TRIES && needToRetry); } finally { //deregister download events client.DownloadProgressChanged -= client_DownloadProgressChanged; client.DownloadFileCompleted -= client_DownloadFileCompleted; NetworkChange.NetworkAvailabilityChanged -= NetworkAvailabilityChanged; client.Dispose(); } //if this is still the case after having retried MAX_NUMBER_OF_TRIES number of times. if (patchDownloadState == DownloadState.Error) { log.ErrorFormat("Giving up - Maximum number of retries ({0}) has been reached.", MAX_NUMBER_OF_TRIES); MarkCompleted(patchDownloadError ?? new Exception(Messages.ERROR_UNKNOWN)); } }
static void Main(string[] args) { var list = new List <Produkt>(); //var s = System.IO.File.ReadAllText("..\\..\\produkt.txt"); //list = JsonConvert.DeserializeObject<List<Produkt>>(s); list.Add(new Produkt { Namn = "banan", Price = 122.2m, ProduktId = "321", Leverantorer = new List <Leverantor> { new Leverantor { Adress = "231312", Namn = "Lev1" }, new Leverantor { Adress = "231323423412", Namn = "Lev2" } } }); list.Add(new Produkt { Namn = "äpple", Price = 22.2m, ProduktId = "333" }); list.Add(new Produkt { Namn = "saft", Price = 12.3m, ProduktId = "123" }); string toSave = JsonConvert.SerializeObject(list); System.IO.File.WriteAllText("..\\..\\produkt.txt", toSave); log.Debug("Nu startar programmet"); while (true) { Console.WriteLine("mata in lösenord för att får köra spelet"); var password = ConsolePasswordReader.Read(); if (password == "hemligt") { break; } } log.Debug("Nu har lösenordet skrivits in"); var ui = new ConsoleUI(); ui.ShowWelcomeScreen(); try { int min = ui.GetIntBetween(1, 10, "Ange minsta värde i spelet"); int max = ui.GetIntBetween(100, 1000, "Ange högsta värde i spelet"); } catch (Exception ex) { log.Error(ex); } //var settings = new Game.Settings(min,max); //settings.Save(@"..\..\settings.txt"); //var gameEngine = new Game.GameEngine(settings,ui); //gameEngine.Run(); }
/// <summary> /// 输出日志到Log4Net /// </summary> /// <param name="t"></param> /// <param name="msg"></param> #region static void WriteLog(Type t, string msg) public static void WriteLog(Type t, string msg) { log4net.ILog log = log4net.LogManager.GetLogger(t); log.Error(msg); }
private void Display() { if (Running == false) { Running = true; Dispatcher.InvokeAsync(() => { castTypes.IsEnabled = countTypes.IsEnabled = minFreqList.IsEnabled = false; (Application.Current.MainWindow as MainWindow).Busy(true); }); Task.Delay(20).ContinueWith(task => { try { if (TheSpellCounts != null) { Dispatcher.InvokeAsync(() => { dataGrid.Columns.Add(new DataGridTextColumn() { Header = "", Binding = new Binding("Spell"), CellStyle = Application.Current.Resources["SpellGridNameCellStyle"] as Style }); }); Dictionary <string, Dictionary <string, uint> > filteredPlayerMap = new Dictionary <string, Dictionary <string, uint> >(); Dictionary <string, uint> totalCountMap = new Dictionary <string, uint>(); Dictionary <string, uint> uniqueSpellsMap = new Dictionary <string, uint>(); uint totalCasts = 0; PlayerList.ForEach(player => { filteredPlayerMap[player] = new Dictionary <string, uint>(); if ((CurrentCastType == 0 || CurrentCastType == 1) && TheSpellCounts.PlayerCastCounts.ContainsKey(player)) { foreach (string id in TheSpellCounts.PlayerCastCounts[player].Keys) { totalCasts = UpdateMaps(id, player, TheSpellCounts.PlayerCastCounts[player][id], TheSpellCounts.MaxCastCounts, totalCountMap, uniqueSpellsMap, filteredPlayerMap, false, totalCasts); } } if ((CurrentCastType == 0 || CurrentCastType == 2) && TheSpellCounts.PlayerReceivedCounts.ContainsKey(player)) { foreach (string id in TheSpellCounts.PlayerReceivedCounts[player].Keys) { totalCasts = UpdateMaps(id, player, TheSpellCounts.PlayerReceivedCounts[player][id], TheSpellCounts.MaxReceivedCounts, totalCountMap, uniqueSpellsMap, filteredPlayerMap, true, totalCasts); } } }); List <string> sortedPlayers = totalCountMap.Keys.OrderByDescending(key => totalCountMap[key]).ToList(); List <string> sortedSpellList = uniqueSpellsMap.Keys.OrderByDescending(key => uniqueSpellsMap[key]).ToList(); int colCount = 0; foreach (string name in sortedPlayers) { string colBinding = "Values[" + colCount + "]"; // dont use colCount directly since it will change during Dispatch double total = totalCountMap.ContainsKey(name) ? totalCountMap[name] : 0; string header = name + " = " + ((CurrentCountType == 0) ? total.ToString(CultureInfo.CurrentCulture) : Math.Round(total / totalCasts * 100, 2).ToString(CultureInfo.CurrentCulture)); Dispatcher.InvokeAsync(() => { DataGridTextColumn col = new DataGridTextColumn() { Header = header, Binding = new Binding(colBinding) }; col.CellStyle = Application.Current.Resources["SpellGridDataCellStyle"] as Style; col.HeaderStyle = Application.Current.Resources["BrightCenterGridHeaderStyle"] as Style; dataGrid.Columns.Add(col); }); Thread.Sleep(5); colCount++; } string totalHeader = CurrentCountType == 0 ? "Totals = " + totalCasts : "Totals = 100"; Dispatcher.InvokeAsync(() => { DataGridTextColumn col = new DataGridTextColumn() { Header = totalHeader, Binding = new Binding("Values[" + colCount + "]") }; col.CellStyle = Application.Current.Resources["SpellGridDataCellStyle"] as Style; col.HeaderStyle = Application.Current.Resources["BrightCenterGridHeaderStyle"] as Style; dataGrid.Columns.Add(col); }); int existingIndex = 0; foreach (var spell in sortedSpellList) { var row = (SpellRowsView.Count > existingIndex) ? SpellRowsView[existingIndex] : new SpellCountRow(); row.Spell = spell; row.IsReceived = spell.StartsWith("Received", StringComparison.Ordinal); row.IconColor = TableColors.ACTIVEICON; int i; double[] values = new double[sortedPlayers.Count + 1]; for (i = 0; i < sortedPlayers.Count; i++) { if (filteredPlayerMap.ContainsKey(sortedPlayers[i])) { if (filteredPlayerMap[sortedPlayers[i]].ContainsKey(spell)) { if (CurrentCountType == 0) { values[i] = filteredPlayerMap[sortedPlayers[i]][spell]; } else { values[i] = Math.Round((double)filteredPlayerMap[sortedPlayers[i]][spell] / totalCountMap[sortedPlayers[i]] * 100, 2); } } else { values[i] = CurrentCountType == 0 ? 0 : 0.0; } } } values[i] = CurrentCountType == 0 ? uniqueSpellsMap[spell] : Math.Round((double)uniqueSpellsMap[spell] / totalCasts * 100, 2); row.Values.Clear(); row.Values.AddRange(values); if ((SpellRowsView.Count <= existingIndex)) { Dispatcher.InvokeAsync(() => SpellRowsView.Add(row)); } existingIndex++; Thread.Sleep(5); } } } catch (Exception ex) { LOG.Error(ex); throw; } finally { Dispatcher.InvokeAsync(() => { castTypes.IsEnabled = countTypes.IsEnabled = minFreqList.IsEnabled = true; (Application.Current.MainWindow as MainWindow).Busy(false); exportClick.IsEnabled = copyOptions.IsEnabled = removeRowClick.IsEnabled = SpellRowsView.Count > 0; }); Running = false; } }, TaskScheduler.Default); } }
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)); } }
static public DataTable ExecuteQuery(string connectionString, string sql) { Stopwatch tw = new Stopwatch(); tw.Start(); log.Info(string.Format("Setting up ...")); DataTable dataTable = null; try { using (SqlConnection connection = new SqlConnection(connectionString)) using (SqlCommand cmd = new SqlCommand(sql, connection)) { log.Info(string.Format("Opening Connection on '{0}' ...", HidePwd(connectionString))); connection.Open(); log.Info(string.Format("Query: {0}", sql)); log.Info(string.Format("Query execution starting ...")); using (var reader = cmd.ExecuteReader()) { dataTable = new DataTable(); dataTable.Load(reader); } log.Info(string.Format("Query executed! Result count: {0}", LibString.ItemsNumber(dataTable))); connection.Close(); log.Info("Connection Closed!"); } } catch (Exception ex) { log.Info("Excepion detected!"); log.Error(ex.Message); throw; } finally { tw.Stop(); log.Info(string.Format("Completed! Elapsed time {0}", LibString.TimeSpanToTimeHmsms(tw.Elapsed))); } return(dataTable); }
static void Main(string[] args) { IDictionary <String, ICommand> commandDict = new Dictionary <String, ICommand>(); IList <ICommand> commandList = new List <ICommand>(); var frameworkFactory = new FrameworkFactory(); var framework = frameworkFactory.CreateFramework(); AppDomain.CurrentDomain.AssemblyLoad += CurrentDomainAssemblyLoad; framework.GetBundleContext().AddBundleListener(new ConsoleBundleListener()); framework.Init(); framework.Start(); commandList.Add(new HelpCommand(commandDict)); commandList.Add(new ListBundleCommand(framework)); commandList.Add(new ListAssembliesCommand()); commandList.Add(new StartBundleCommand(framework)); commandList.Add(new StopBundleCommand(framework)); commandList.Add(new InstallBundleCommand(framework)); commandList.Add(new UninstallBundleCommand(framework)); commandList.Add(new UpdateBundleCommand(framework)); commandList.Add(new ExitCommand(framework)); foreach (ICommand command in commandList) { commandDict.Add(command.GetCommandName(), command); } Console.WriteLine("------------------------------"); Console.WriteLine("欢迎使用,输入help以查看帮助"); Console.WriteLine("------------------------------"); Console.WriteLine(); while (true) { Console.Write("OSGi.NET>"); var readLine = Console.ReadLine(); if (readLine != null) { String commandLine = readLine.Trim(); if (String.IsNullOrEmpty(commandLine)) { continue; } String commandName = commandLine.Split(new Char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[0]; if (commandDict.ContainsKey(commandName)) { String result = null; try { result = commandDict[commandName].ExecuteCommand(commandLine); Console.WriteLine(result); } catch (Exception ex) { log.Error(String.Format("命令在执行过程中出现异常,信息:{0}", ex.Message), ex); } } else { log.Error(String.Format("未知 命令:{0}", commandName)); } } } }
/// <summary> /// Initializes the <c>SteamManager</c>. /// This MUST be called before other Steam operations are executed. /// </summary> /// <returns><c>true</c> if everything initialized properly, <c>false</c> otherwise.</returns> public static bool Init() { if (Enabled) { _log.Warn("Tried to call Init method when SteamManager has already been initialized! Aborting..."); return false; } _log = LogManager.GetLogger(typeof(SteamManager)); try { if (!Steamworks.Load()) { _log.Error("Steamworks failed to load, throwing exception!"); throw new SteamException("Steamworks failed to load.", SteamExceptionType.SteamworksLoadFail); } Client = Steamworks.CreateInterface<ISteamClient010>("SteamClient010"); if (Client == null) { _log.Error("Steamclient is NULL!! Throwing exception!"); throw new SteamException("Steamclient failed to load! Is the client running? (Sharpcraft.Steam.SteamManager.Client == null!)", SteamExceptionType.SteamLoadFail); } Pipe = Client.CreateSteamPipe(); User = Client.ConnectToGlobalUser(Pipe); Friends = Steamworks.CastInterface<ISteamFriends002>(Client.GetISteamFriends(User, Pipe, "SteamFriends002")); if (Friends == null) return false; FriendList = new SteamFriendList(); _steamWatcher = new Timer(SteamCheck, null, 0, 1000); } catch (SteamException ex) { _log.Warn("Warning! SteamManager caught a SteamException exception, returning FALSE. Steam components will NOT LOAD!"); _log.Warn("The SteamException type was: " + System.Enum.GetName(typeof(SteamExceptionType), ex.Type)); return false; } _log.Info("SteamManager has been initialized!"); SteamLoaded = true; Enabled = true; return true; }