public bool IsLoginOK(string user, string password) { try { string text = "loginrequested"; StaticLogger.Write(text); // <--callLogger() } catch (LoggerException e) { string text = e.Message + Environment.MachineName; StaticWebService.Write(text); } if (m_users[user] != null && (string)m_users[user] == password) { return(true); } return(false); }
public ObservableCollection <MarketplaceData> GetMarketDataByASIN(string asin, out string upc) { upc = string.Empty; ObservableCollection <MarketplaceData> data = new ObservableCollection <MarketplaceData>(); MySqlDataReader reader = null; try { string query = "select m.Name, mp.*, p.UPC from products p, marketplace_data mp, marketplaces m where mp.SKU = p.SKU and "; query += "m.MarketPlaceID = mp.MarketPlaceID and p.ASIN=@asin;"; using (MySqlCommand cmd = new MySqlCommand(query, conn)) { cmd.Parameters.Add("@asin", MySqlDbType.VarChar); cmd.Parameters[0].Value = asin; using (reader = cmd.ExecuteReader()) { while (reader.Read()) { MarketplaceData mp = new MarketplaceData() { MarketPlaceName = reader.GetString(0), MarketPlaceID = reader.GetInt32(1), SKU = reader.GetString(2), Weight = reader.GetDouble(3), UOM = reader.GetInt32(4), Unpublish = reader.GetBoolean(5), MAP = reader.GetDouble(6) }; data.Add(mp); upc = reader.GetString(7); } } } } catch (MySql.Data.MySqlClient.MySqlException ex) { StaticLogger.LogException(ex); } return(data); }
/// <summary> /// Crea una entrada en el visor de eventos /// </summary> /// <param name="msg"></param> /// <param name="eventType"></param> public static void Log(string source, string msg, EventType eventType, bool sendWindowsEvent) { Event ev = new Event(); ev.LogType = eventType; ev.Source = source; ev.Message.Text = msg; ev.LogDate = System.DateTime.Now; try { if (sendWindowsEvent && sendWindowsEvent_ok) { StaticLogger.Log(TargetType.WindowsEvent, ev, string.Empty, string.Empty); } } catch (System.Security.SecurityException se) { sendWindowsEvent_ok = false; Event ev1 = new Event(); ev1.LogType = EventType.Warning; ev1.Source = ServiceName; ev1.Message.Text = string.Concat("problemas de seguridad no se permite loguear mas en el visor de eventos\r\n", ExceptionHelper.GetAllMessageException(se)); ev1.LogDate = System.DateTime.Now; Audit(ev1); } catch (System.ComponentModel.Win32Exception we)//Puede q se llene el log de windows { sendWindowsEvent_ok = false; Event ev1 = new Event(); ev1.LogType = EventType.Warning; ev1.Source = ServiceName; ev1.Message.Text = string.Concat("Problemas para crear logs en el visor de eventos, puede que este lleno\r\n", ExceptionHelper.GetAllMessageException(we)); ev1.LogDate = System.DateTime.Now; Audit(ev1); } Audit(ev); //SendMail(source, msg); }
public ObservableCollection <MarketplaceData> GetMarketDataByUPC(string upc) { ObservableCollection <MarketplaceData> data = new ObservableCollection <MarketplaceData>(); MySqlDataReader reader = null; try { string query = "select m.Name, mp.MarketPlaceID, mp.SKU, mp.Weight, mp.UOM, mp.Unpublish, mp.MAP, mp.Verified, mp.IsFood from products p, marketplace_data mp, marketplaces m where mp.SKU = p.SKU and "; query += "m.MarketPlaceID = mp.MarketPlaceID and p.UPC=@upc;"; using (MySqlCommand cmd = new MySqlCommand(query, conn)) { cmd.Parameters.Add("@upc", MySqlDbType.VarChar); cmd.Parameters[0].Value = upc; using (reader = cmd.ExecuteReader()) { while (reader.Read()) { MarketplaceData mp = new MarketplaceData() { MarketPlaceName = reader.GetString(0), MarketPlaceID = reader.GetInt32(1), SKU = reader.GetString(2), Weight = reader.GetDouble(3), UOM = reader.GetInt32(4), Unpublish = reader.GetBoolean(5), MAP = reader.GetDouble(6), Verified = reader.IsDBNull(7) ? false : reader.GetBoolean(7), IsFood = reader.IsDBNull(8) ? false : reader.GetBoolean(8) }; data.Add(mp); } } } } catch (MySql.Data.MySqlClient.MySqlException ex) { StaticLogger.LogException(ex); } return(data); }
/// <summary> /// Copies the configuration folder to the build if it exists. /// </summary> /// <param name="buildPath">The path of the build.</param> private static void CopyConfigFolder(string buildPath) { if (Directory.Exists(buildPath + "/Configuration")) { Utils.DeleteDirectory(buildPath + "/Configuration"); } if (Directory.Exists("Configuration")) { StaticLogger.Info("Configuration folder found, copying it to build."); } else { StaticLogger.Info("No configuration folder found, skipping config copy."); return; } Utils.CopyFilesRecursively(new DirectoryInfo("Configuration"), new DirectoryInfo(buildPath + "/Configuration")); }
public IRun Run() { var run = new Run(); try { StaticLogger.WriteLine($"Starting step: {this._name}"); run.Start(); this._run(); run.End(); StaticLogger.WriteLine($"Finished step: {this._name}"); return(run); } catch (Exception e) { StaticLogger.WriteErrorLine($"Error in step: {this._name}, error: {e.ToString()}"); run.End(); return(new FaultedRun(run)); } }
static void Main(string[] args) { ILogger logger = new StaticLogger(); using (MyStreamReader sr = new MyStreamReader("Data1.txt")) { try { logger.LogInfo("Start parsing..."); Shipment shipment = new Shipment(sr, logger); logger.LogInfo("Ended parsing..."); } catch (Exception ex) { logger.LogError(ex.Message); } Console.Out.WriteLine("Done..."); Console.ReadKey(); } }
private static void RecursiveRegisterRepository(IServiceRegister serviceRegister, Type RepositoryType) { serviceRegister.Register(RepositoryType, RepositoryType, ServiceLifetime.Transient); RegisterInterfaces(serviceRegister, RepositoryType); Type baseType = RepositoryType.BaseType; while (baseType != null) { if (!baseType.IsGenericTypeDefinition) { StaticLogger.Log($"PPDI: Registering repository for {baseType} => {RepositoryType}", StaticLogger.LoggingLevel.Call); serviceRegister.Register(baseType, RepositoryType, ServiceLifetime.Transient); } baseType = baseType.BaseType; } }
protected void CheckLoop() { while (CheckThread != null) { if (CurrentProcess == null || CurrentProcess.HasExited) { IsInjected = false; CurrentProcess = Process.GetProcessesByName(ProcessName).FirstOrDefault(); if (CurrentProcess != null) { try { Inject(); IsInjected = true; } catch (FileNotFoundException fe) { //LoLClient does not have ws2_32 yet. Lets try again in 1 second. StaticLogger.Trace(fe.Message); CurrentProcess = null; Thread.Sleep(1000); continue; } catch (WarningException we) { IsInjected = true; StaticLogger.Info(we.Message); } catch (NotSupportedException nse) { StaticLogger.Warning(nse); } catch (Exception ex) { StaticLogger.Error(new Exception(string.Format("{0} [{1}]", ex.Message, From), ex)); } } } Thread.Sleep(500); } }
private void RegionList_SelectedIndexChanged(object sender, EventArgs e) { LeagueRegion region; if (!LeagueRegion.TryParse(RegionList.SelectedItem.ToString(), out region)) { StaticLogger.Warning("Unknown enum " + RegionList.SelectedItem); return; } Settings.Region = region; var cert = Certificates.FirstOrDefault(kv => kv.Key == Settings.Region).Value; if (cert == null) { cert = Certificates.First().Value; } Connection.ChangeRemote(cert.Domain, cert.Certificate); }
public void Load(string file) { try { if (!File.Exists(file)) { return; } using (var sr = new StreamReader(File.Open(file, FileMode.Open, FileAccess.Read))) { JsonConvert.PopulateObject(sr.ReadToEnd(), this); } OnLoad(); } catch (IOException io) { StaticLogger.Debug(io); } }
/// <summary> /// Crea una entrada en el visor de eventos /// </summary> /// <param name="msg"></param> /// <param name="eventType"></param> public static void LogWinEvent(string msg, Fwk.Logging.EventType eventType) { Fwk.Logging.Event ev = new Fwk.Logging.Event(); ev.LogType = eventType; ev.Source = ""; ev.Message.Text = msg; try { if (!logOnWindowsEvent) { StaticLogger.Log(TargetType.WindowsEvent, ev, string.Empty, string.Empty); } Audit(msg); } catch (System.Security.SecurityException) { logOnWindowsEvent = false; } }
protected virtual void OnAccept(IAsyncResult ar) { ProxyClient client = null; try { if (!IsListening) { return; } client = NewClient(Listener.EndAcceptTcpClient(ar)); Listener.BeginAcceptTcpClient(OnAccept, null); lock (Clients) Clients.Add(client); client.Start(RemoteAddress, RemotePort); if (client.SourceTcp.Client != null) { StaticLogger.Info(string.Format("Client {0} connected", client.SourceTcp.Client.RemoteEndPoint)); } } catch (Exception ex) { if (client != null) { OnException(client, ex); } else { //Ignore objectdisposed, happens when stopping if (!(ex is ObjectDisposedException)) { StaticLogger.Error(ex); } } } }
/// <summary> /// Records/Commits the lobby to the database. Locking the database lock. /// </summary> /// <param name="lobby"></param> public void CommitLobby(GameDTO lobby) { bool committed = false; Stopwatch sw; lock (DatabaseLock) { sw = Stopwatch.StartNew(); committed = RecordLobby(lobby); if (committed) { Database.Commit(); } } sw.Stop(); if (committed) { StaticLogger.Debug(string.Format("Lobby committed in {0}ms", sw.ElapsedMilliseconds)); } }
public void IsLoginOK_StaticLoggerThrowsException_CallsStaticWebServiceWithCorrectText() { string textWrittenToWebService = null; Isolate.Fake.StaticMethods <StaticLogger>(); Isolate.Fake.StaticMethods <StaticWebService>(); Isolate .WhenCalled(() => StaticLogger.Write("")) .WillThrow(new LoggerException("fake exception")); Isolate .WhenCalled(() => StaticWebService.Write("")) .DoInstead(context => textWrittenToWebService = (string)context.Parameters[0]); var lm = new LoginManagerWithStatics(); lm.IsLoginOK("a", "b"); StringAssert.Contains("fake exception", textWrittenToWebService); }
/// <summary> /// Crea una entrada en log.xml /// </summary> /// <param name="msg"></param> /// <param name="eventType"></param> public static void Audit(Event ev) { if (!logOnFile) { return; } lock (lookFile)//Evita concurencia en hilos de la app { try { StaticLogger.Log(TargetType.File, ev, string.Format(logFileFullName, DateFunctions.Get_Year_Mont_Day_String(DateTime.Now, '-')) , string.Empty); } catch (System.IO.IOException)//Hilos externos a la app. EJ Notepad { //"The requested operation cannot be performed on a file with a user-mapped section open." //throw ex; } } }
void TrackingQueue_Process(object sender, ProcessQueueEventArgs <string> e) { try { var hr = (HttpWebRequest)WebRequest.Create("http://bit.ly/unCoIY"); hr.ServicePoint.Expect100Continue = false; hr.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0"; hr.Referer = string.Format("http://lolnotes-{0}-app.org/{1}", Version, e.Item); hr.AllowAutoRedirect = false; using (var resp = (HttpWebResponse)hr.GetResponse()) { } } catch (WebException we) { StaticLogger.Warning(we); } catch (Exception ex) { StaticLogger.Warning(ex); } }
/// <summary> /// Crea una entrada en log.xml /// </summary> /// <param name="msg"></param> /// <param name="eventType"></param> public static void Audit(string msg) { if (!logOnFile) { return; } Fwk.Logging.Event ev = new Fwk.Logging.Event(); ev.LogType = Fwk.Logging.EventType.Audit; ev.Message.Text = msg; //StaticLogger.Log(ev, string.Empty, DateFunctions.Get_Year_Mont_Day_String(DateTime.Now, '-')); try { StaticLogger.Log(ev); } catch (System.Security.SecurityException) { logOnFile = false; } }
/// <summary> /// Drops all non-security information from the database /// </summary> public static void TruncateDatabase(string ConnectionString) { StaticLogger.Log("Truncating database..."); using (SqlConnection connection = new SqlConnection(ConnectionString)) { connection.Open(); // Create the command and set its properties. using (SqlCommand command = new SqlCommand { Connection = connection, CommandText = ResourceHelper.ReadEmbeddedScript("TruncateDatabase.sql"), CommandType = CommandType.Text, CommandTimeout = 600000 }) { // Open the connection and execute the reader. command.ExecuteNonQuery(); } } StaticLogger.Log("Truncating Complete."); }
void SetChanges(JObject data) { if (data == null) { return; } try { ChangesText.Text = ""; foreach (var kv in data) { ChangesText.SelectionFont = new Font(ChangesText.Font.FontFamily, ChangesText.Font.SizeInPoints, FontStyle.Bold); ChangesText.AppendText(kv.Key); ChangesText.AppendText(Environment.NewLine); ChangesText.SelectionFont = new Font(ChangesText.Font.FontFamily, ChangesText.Font.SizeInPoints, ChangesText.Font.Style); if (kv.Value is JArray) { var list = kv.Value as JArray; foreach (var item in list) { ChangesText.AppendText(item.ToString()); ChangesText.AppendText(Environment.NewLine); } } else { ChangesText.AppendText(kv.Value.ToString()); ChangesText.AppendText(Environment.NewLine); } } } catch (Exception e) { StaticLogger.Error(e); } }
protected virtual void Dispose(bool disposing) { if (!this.isDisposed) { if (disposing) { StaticLogger.Instance.Info($"IT run {this.testData.Nonce} finished. Cleaning up..."); this.RemoveObjectsFromTenantAsync() .GetAwaiter().GetResult(); StaticLogger.Instance.Info($"Done cleaning up objects."); StaticLogger.Instance.Info("Caching statistics:"); StaticLogger.Instance.Info(TestClients.GetSAuthc1Client().GetCacheProvider().ToString()); var filename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "its.log"); StaticLogger.Instance.Info($"Saving log to file {filename}"); System.IO.File.WriteAllText(filename, StaticLogger.GetLog()); } this.isDisposed = true; } }
private static IEnumerable <object> Resolve(Registration match, ResolutionPackage resolutionPackage, bool optional = false) { resolutionPackage.AddStack(match); //We resolve with that registration. Or attempt to if (!resolutionPackage.ServiceProviders.TryGetValue(match.ServiceProvider, out AbstractServiceProvider thisManager)) { if (!resolutionPackage.ServiceProviders.TryGetValue(typeof(TransientServiceProvider), out thisManager)) { throw new Exception($"Type {match.ToInstantiate} could not be created because service provider of type {match.ServiceProvider} was not found in the current registrations and a transient service provider could not be found"); } else { StaticLogger.Log($"Type {match.ToInstantiate} created using transient service provider because {match.ServiceProvider} was not found in the current registrations", StaticLogger.LoggingLevel.Call); } } //If no registration was found, or there was no instance existing if (!(thisManager.GetService(match.ToInstantiate) is IList <object> toReturn) || !toReturn.Any()) { //Create an instance toReturn = new List <object>(); object o = CreateRegisteredInstance(match, resolutionPackage, optional); if (o != null) { thisManager?.Add(match.ToInstantiate, o); toReturn.Add(o); } } resolutionPackage.RemoveStack(); return(toReturn); }
public UpdaterModel(string server, string uid, string pwd, string db) { // var myConnectionString = "server=127.0.0.1;uid=user1;pwd=user123;database=valo_db;"; StaticLogger.LogInfo("Connecting"); StringBuilder sb = new StringBuilder("server="); sb.Append(server); sb.Append(";uid="); sb.Append(uid); sb.Append(";pwd="); sb.Append(pwd); sb.Append(";database="); sb.Append(db); sb.Append(";"); try { conn = new MySqlConnection(sb.ToString()); conn.Open(); } catch (MySqlException ex) { Console.WriteLine(ex.Message); switch (ex.Number) { case 0: StaticLogger.LogError("Cannot connect to server. Contact administrator"); break; case 1045: StaticLogger.LogError("Invalid username/password, please try again"); break; } } }
//public void Task<PlaylistModel> AddPlaylistTracks(String playlistUuid, String playlistETag, IEnumerable<Int32> trackIds, Int32 toIndex = 0) //{ // logger.Debug("Add playlist tracks"); //} //public void DeletePlaylistTracks(String playlistUuid, String playlistETag, IEnumerable<Int32> indices) //{ // logger.Debug("Delete Playlist tracks"); //} public async Task <JsonList <PlaylistModel> > GetUserPlaylists(Int32 limit = 9999) { StaticLogger.LogInfo(this.GetType(), "Get user playlists"); return(await session.GetUserPlaylists(limit)); }
public TidlBL(string username = "******", string password = "******") { StaticLogger.LogInfo(this.GetType(), "Gettins session from constructor"); session = this.Login(username, password); }
/// <summary> /// Helper method which sets all the properties in the class to their respected FlashObject field. /// Use InternalNameAttribute to specify a property which has a FlashObject counter-part. /// SetFields does not travel the hierarchy. So Derived types must make their own separate call to SetFields. /// </summary> /// <param name="obj">Object to change properties</param> /// <param name="flash">Flash object to get fields from</param> public static void SetFields <T>(T obj, ASObject flash) { if (flash == null) { return; } foreach (var prop in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { var intern = prop.GetAttribute <InternalNameAttribute>(); if (intern == null) { continue; } var type = prop.PropertyType; object value; if (!flash.TryGetValue(intern.Name, out value)) { StaticLogger.Warning(string.Format("{0} missing ASObject property {1}", typeof(T).FullName, intern.Name)); continue; } try { if (type == typeof(string)) { value = Convert.ToString(flash[intern.Name]); } else if (type == typeof(Int32)) { value = Convert.ToInt32(flash[intern.Name]); } else if (type == typeof(Int64)) { value = Convert.ToInt64(flash[intern.Name]); } else if (type == typeof(double)) { value = Convert.ToInt64(flash[intern.Name]); } else if (type == typeof(bool)) { value = Convert.ToBoolean(flash[intern.Name]); } else if (type == typeof(DateTime)) { value = Convert.ToDateTime(flash[intern.Name]); } else if (type == typeof(ASObject)) { value = flash[intern.Name] as ASObject; } else if (type == typeof(ArrayCollection)) { value = flash[intern.Name] as ArrayCollection; } else if (type == typeof(object)) { value = flash[intern.Name]; } else { try { value = Activator.CreateInstance(type, flash[intern.Name]); } catch (Exception e) { throw new NotSupportedException(string.Format("Type {0} not supported by flash serializer", type.FullName), e); } } prop.SetValue(obj, value, null); } catch (Exception e) { StaticLogger.Error(new Exception(string.Format("Error parsing {0}#{1}", typeof(T).FullName, prop.Name), e)); } } }
/// <summary> /// Whitelists a list of assemblies through the Reflection TypeFactory and then grabs all types and attempts to register any types that are relevant to the /// engine /// </summary> static Engine() { StaticLogger.Log($"Penguin.DependencyInjection: {Assembly.GetExecutingAssembly().GetName().Version}", StaticLogger.LoggingLevel.Call); ChildDependencies = new ConcurrentDictionary <Type, List <PropertyInfo> >(); Registrations = new ConcurrentDictionary <Type, ConcurrentList <Registration> >(); foreach (Type t in TypeFactory.GetAllTypes()) { try { if (t.IsAbstract || t.IsInterface) { continue; } foreach (DependencyRegistrationAttribute autoReg in t.GetCustomAttributes <DependencyRegistrationAttribute>()) { if (autoReg is RegisterAttribute ra) { if (ra.RegisteredTypes.Length > 0) { foreach (Type registeredType in ra.RegisteredTypes) { Register(registeredType, t, null, StaticServiceRegister.GetServiceProvider(ra.Lifetime)); } } else { Register(t, t, null, StaticServiceRegister.GetServiceProvider(ra.Lifetime)); } } else if (autoReg is RegisterThroughMostDerivedAttribute rmd) { RegisterAllBaseTypes(rmd.RequestType, TypeFactory.GetMostDerivedType(t), StaticServiceRegister.GetServiceProvider(rmd.Lifetime)); } } if (t.ImplementsInterface <IRegisterDependencies>()) { StaticLogger.Log($"DependencyInjector: Registering {nameof(IRegisterDependencies)} of type {t.FullName} from assembly {t.Assembly.FullName}", StaticLogger.LoggingLevel.Call); (Activator.CreateInstance(t) as IRegisterDependencies).RegisterDependencies(Registrar); } if (t.ImplementsInterface(typeof(IConsolidateDependencies <>))) { foreach (Type type in t.GetClosedImplementationsFor(typeof(IConsolidateDependencies <>))) { dependencyConsolidators.TryAdd(type.GetGenericArguments()[0], t); } } if (t.ImplementsInterface <ISelfRegistering>()) { Register(t, t, typeof(TransientServiceProvider)); } if (t.IsSubclassOf(typeof(StaticServiceProvider))) { StaticServiceProvider provider = Activator.CreateInstance(t) as StaticServiceProvider; StaticProviders.Add(t, provider); } } catch (Exception ex) { StaticLogger.Log("Failed to load information for type: " + t.FullName, StaticLogger.LoggingLevel.Call); StaticLogger.Log(ex.StackTrace, StaticLogger.LoggingLevel.Call); StaticLogger.Log(ex.Message, StaticLogger.LoggingLevel.Call); } } }
public T InvokeService <T>(string service, string operation, params object[] args) where T : class { var msg = new RemotingMessage(); msg.operation = operation; msg.destination = service; msg.headers["DSRequestTimeout"] = 60; msg.headers["DSId"] = RtmpUtil.RandomUidString(); msg.headers["DSEndpoint"] = "my-rtmps"; msg.body = args; msg.messageId = RtmpUtil.RandomUidString(); string endpoint = service + "." + operation; var result = Host.Call(msg); if (result == null) { StaticLogger.Warning(string.Format("Invoking {0} returned null", endpoint)); return(null); } if (RtmpUtil.IsError(result)) { var error = RtmpUtil.GetError(result); var errordetail = error != null && error.faultDetail != null?string.Format(" [{0}]", error.faultDetail) : ""; var errorstr = error != null && error.faultString != null?string.Format(", {0}", error.faultString) : ""; StaticLogger.Warning(string.Format( "{0} returned an error{1}{2}", endpoint, errorstr, errordetail )); return(null); } var body = RtmpUtil.GetBodies(result).FirstOrDefault(); if (body == null) { StaticLogger.Debug(endpoint + " RtmpUtil.GetBodies returned null"); return(null); } if (body.Item1 == null) { StaticLogger.Debug(endpoint + " Body.Item1 returned null"); return(null); } object obj = null; if (body.Item1 is ASObject) { var ao = (ASObject)body.Item1; obj = MessageTranslator.Instance.GetObject <T>(ao); if (obj == null) { StaticLogger.Debug(endpoint + " expected " + typeof(T) + ", got " + ao.TypeName); return(null); } } else if (body.Item1 is ArrayCollection) { try { obj = Activator.CreateInstance(typeof(T), (ArrayCollection)body.Item1); } catch (Exception ex) { StaticLogger.Warning(endpoint + " failed to construct " + typeof(T)); StaticLogger.Debug(ex); return(null); } } else { StaticLogger.Debug(endpoint + " unknown object " + body.Item1.GetType()); return(null); } if (obj is MessageObject) { ((MessageObject)obj).TimeStamp = body.Item2; } return((T)obj); }
protected virtual void CallLogger(string text) { StaticLogger.Write(text); }
protected virtual void CallStaticWs() { StaticLogger.Write("blah"); }