public static void Init() { _log = LogManager.GetLogger("AppDomain"); var _fa = new FileAppender() { Layout = new log4net.Layout.PatternLayout("%timestamp [%thread] %-5level %logger - %message%newline"), File = Path.Combine(Environment.CurrentDirectory, "update.log"), AppendToFile = false }; _fa.ActivateOptions(); BasicConfigurator.Configure( _fa, new ConsoleAppender() ); AppDomain.CurrentDomain.AssemblyLoad += (sender, e) => { _log.DebugFormat("Assembly load: {0}", e.LoadedAssembly.FullName); }; AppDomain.CurrentDomain.ProcessExit += (sender, e) => { _log.Info("Process exiting."); }; AppDomain.CurrentDomain.UnhandledException += (sender, e) => { _log.ErrorFormat("Unhandled exception: {0}", e.ExceptionObject.ToString()); }; }
public QueueProcessor(string QueuePath) { //访问本地电脑上的消息队列时Path的格式可以有如下几种: //MessageQueue mq = new MessageQueue(); //mq.Path = @".\Private$\test"; //mq.Path = @"sf00902395d34\Private$\test"; //sf00902395d34是主机名 //mq.Path = @"FormatName:DIRECT=OS:sf00902395d34\Private$\test"; //mq.Path = @"FormatName:DIRECT=OS:localhost\Private$\test"; //访问远程电脑上的消息队列时Path的格式 //mq.Path = @"FormatName:DIRECT=OS:server\Private$\test"; reset = new ManualResetEvent(true); logger = LogManager.GetLogger("logger"); _path = QueuePath; //判断指定的消息队列是否存在 if (MessageQueue.Exists(QueuePath)) { queue = new MessageQueue(QueuePath); logger.Info(string.Format("Init : {0} successfully!", QueuePath)); } else { //不存在,创建 queue = MessageQueue.Create(QueuePath); //赋予权限 queue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl, AccessControlEntryType.Set); logger.Info(string.Format("Create message queue : {0} successfully!", QueuePath)); } }
public void Init(string[] args) { ParseArgs(args); mLogger = LogManager.GetLogger(GetType().Name); mLogger.Info(string.Format("Initializing Emulator Manager processor with args: [{0}]",string.Join(",",args))); if (configPath == null) { ConfigComponent.Instance.Initialize(); } else { ConfigComponent.Instance.Initialize(configPath); } if (serverUrl == null) { RomDataComponent.Instance.Initialize(); } else { RomDataComponent.Instance.Initialize(serverUrl); } mLogger.Info("Done Initializing Emulator Manager processor"); }
protected void Application_Start() { AppDomain.CurrentDomain.UnhandledException += Application_Error; try { XmlConfigurator.Configure(); AppLogger = LogManager.GetLogger(GetType()); AppLogger.Info("Application_Start..."); AppLogger.Info("Bootstrapping the container..."); Container = ContainerConfig.Config(AppLogger); AppLogger.Info("Setting the Controller Factory..."); var controllerFactory = new WindsorControllerFactory(Container.Kernel); ControllerBuilder.Current.SetControllerFactory(controllerFactory); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); } catch (Exception ex) { AppLogger.Fatal("Application_Start FAILED", ex); throw; } }
protected void WaitForResultOfRequest(ILog logger, string workerTypeName, IOperation operation, Guid subscriptionId, string certificateThumbprint, string requestId) { OperationResult operationResult = new OperationResult(); operationResult.Status = OperationStatus.InProgress; bool done = false; while (!done) { operationResult = operation.StatusCheck(subscriptionId, certificateThumbprint, requestId); if (operationResult.Status == OperationStatus.InProgress) { string logMessage = string.Format(CultureInfo.CurrentCulture, "{0} '{1}' submitted a deployment request with ID '{2}', the operation was found to be in process, waiting for '{3}' seconds.", workerTypeName, this.Id, requestId, FiveSecondsInMilliseconds / 1000); logger.Info(logMessage); Thread.Sleep(FiveSecondsInMilliseconds); } else { done = true; } } if (operationResult.Status == OperationStatus.Failed) { string logMessage = string.Format(CultureInfo.CurrentCulture, "{0} '{1}' submitted a deployment request with ID '{2}' and it failed. The code was '{3}' and message '{4}'.", workerTypeName, this.Id, requestId, operationResult.Code, operationResult.Message); logger.Error(logMessage); } else if (operationResult.Status == OperationStatus.Succeeded) { string logMessage = string.Format(CultureInfo.CurrentCulture, "{0} '{1}' submitted a deployment request with ID '{2}' and it succeeded. The code was '{3}' and message '{4}'.", workerTypeName, this.Id, requestId, operationResult.Code, operationResult.Message); logger.Info(logMessage); } }
public ControllerService() { logger = LogManager.GetLogger("ControllerService"); logger.Info("ControllerService initializing..."); // Read port value int port; if (ConfigurationManager.AppSettings["ControllerPort"] != null) { if (!int.TryParse(ConfigurationManager.AppSettings["ControllerPort"], out port)) { port = DefaultPort; } } else { port = DefaultPort; } // Create server this.server = new ControllerServer(port, logger); this.server.OnClientConnected += this.ServerOnClientConnected; logger.Info("ControllerService initialized."); }
public OrgDataGenerator(ProvisionerConfig config,IDocumentStore orgStore,IDocumentStore masterStore,ILog logger,bool newOrg=true ) { _logger = logger; var orgUrl = "unknown"; var masterUrl = "unknown"; if (orgStore.Url != null) orgUrl = orgStore.Url; if (masterStore.Url != null) masterUrl = masterStore.Url; _logger.Info(string.Format("Data generator - OrgDataGenerator for org store {0}, master store {1}, new org is {2}", orgUrl, masterUrl, newOrg)); _logger = logger; _config = config; _orgStore = orgStore; _masterStore = masterStore; if(newOrg) GenerateLookupData(); if(_config.Users!=null) StoreInOrg(_config.Users); if (_config.AuthUsers != null) { _logger.Info(string.Format("Data generator - about to generate {0} auth users",_config.AuthUsers.Count())); StoreInMaster(_config.AuthUsers); foreach (var authUser in _config.AuthUsers) { var matchingUser = _config.Users.First(u => u.Id == authUser.Id); var password = MembershipRebootHelper.GenerateRandomPassword(); MembershipRebootHelper.CreateLocalAccount(IlluminateDatabase.GetMasterFromConfig(), matchingUser.EmailAddress, password); Email.EmailActivation(matchingUser, authUser, _orgStore,password); } _logger.Info(string.Format("Data generator - generated {0} auth users", _config.AuthUsers.Count())); } }
public static void Main(string[] args) { Console.WriteLine("Hello World!"); //if (log4net.LogManager.GetCurrentLoggers().Length == 0) { log4net.Config.XmlConfigurator.Configure(new FileInfo("log4net.config")); } logger = log4net.LogManager.GetLogger(typeof(Program)); logger.Info("LogzAppender working!!"); logger.Info("This is another message!!"); try { var a = 0; a += 0; var b = 5 / a; } catch (Exception ex) { logger.Error(new Dictionary<String, String>() { { "message", "test message" }, { "gilly", "barr" } }, ex); } Console.ReadKey(true); }
public static WeiChatReceivedContentMessage ParseWeichatXML(string xml,ILog logger=null) { WeiChatReceivedContentMessage message = new WeiChatReceivedContentMessage(); try { logger.Info("ParseWeichatXML"); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); XmlNode contentNode = xmlDoc.SelectSingleNode("/xml/Content"); if(contentNode!=null && !string.IsNullOrEmpty(contentNode.InnerText)) { message.Content = contentNode.InnerText.Trim(); } XmlNode toUserNode = xmlDoc.SelectSingleNode("/xml/ToUserName"); if (toUserNode != null && !string.IsNullOrEmpty(toUserNode.InnerText)) { message.ToUserName = toUserNode.InnerText.Trim(); } XmlNode msgType = xmlDoc.SelectSingleNode("/xml/MsgType"); if (msgType != null && !string.IsNullOrEmpty(msgType.InnerText)) { message.MsgType = msgType.InnerText.Trim(); } XmlNode fromUserNode = xmlDoc.SelectSingleNode("/xml/FromUserName"); if (fromUserNode != null && !string.IsNullOrEmpty(fromUserNode.InnerText)) { message.FromUserName = fromUserNode.InnerText.Trim(); } XmlNode msgIdNode = xmlDoc.SelectSingleNode("/xml/MsgId"); if (msgIdNode != null && !string.IsNullOrEmpty(msgIdNode.InnerText)) { message.MsgId = msgIdNode.InnerText.Trim(); } XmlNode createTimeNode = xmlDoc.SelectSingleNode("/xml/CreateTime"); if (createTimeNode != null && !string.IsNullOrEmpty(createTimeNode.InnerText)) { long time = 0; long.TryParse( createTimeNode.InnerText, out time); message.CreateTime = time; } xmlDoc = null; } catch(Exception ex) { if(logger!=null) { logger.Error(ex); } }finally { logger.Info("Finished ParseWeichatXML"); } return message; }
/// <summary> /// Reads and processes any decision files in the configured folder /// </summary> /// <param name="fileReaderStrategy"></param> /// <param name="log"></param> public static void ReadDecisionFile(DecisionManager.DecisionFileReader fileReaderStrategy, ILog log) { if (fileReaderStrategy == null) throw new ArgumentNullException("fileReaderStrategy"); if (log == null) throw new ArgumentNullException("log"); try { // Get folder and file pattern from web.config so they're easy to update string folder = ConfigurationManager.AppSettings["DecisionsFolder"]; if (String.IsNullOrEmpty(folder)) throw new ConfigurationErrorsException("DecisionsFolder setting is missing from appSettings in app.config"); string filePattern = ConfigurationManager.AppSettings["DecisionFiles"]; if (String.IsNullOrEmpty(filePattern)) throw new ConfigurationErrorsException("DecisionFiles setting is missing from appSettings in app.config"); // Look in the folder, deal with and then delete each file var filenames = Directory.GetFiles(folder, filePattern, SearchOption.TopDirectoryOnly); foreach (string filename in filenames) { // Log that we're working on this file Console.WriteLine(String.Format(CultureInfo.CurrentCulture, Properties.Resources.LogReadingFile, filename)); log.Info(String.Format(CultureInfo.CurrentCulture, Properties.Resources.LogReadingFile, filename)); if (File.Exists(filename)) { fileReaderStrategy(filename, log); var delete = String.IsNullOrEmpty(ConfigurationManager.AppSettings["DeleteProcessedFiles"]); try { if (!delete) delete = Boolean.Parse(ConfigurationManager.AppSettings["DeleteProcessedFiles"]); } catch (FormatException ex) { throw new ConfigurationErrorsException("DeleteProcessedFiles setting in app.config appSettings must be a boolean", ex); } if (delete) { Console.WriteLine(String.Format(CultureInfo.CurrentCulture, Properties.Resources.LogDeletingFile, filename)); log.Info(String.Format(CultureInfo.CurrentCulture, Properties.Resources.LogDeletingFile, filename)); File.Delete(filename); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); log.Error(ex.Message, ex); ex.ToExceptionless().Submit(); return; } }
public AgentService() { logger = LogManager.GetLogger("AgentService"); logger.Info("AgentService initializing..."); // TODO: Extract class ConfigurationManager // Read controller address if (ConfigurationManager.AppSettings["ControllerAddress"] == null) { logger.Fatal("ControllerAddress setting not found in App.config file!"); throw new Exception("ControllerAddress setting not found in App.config file!"); } var controllerAddress = ConfigurationManager.AppSettings["ControllerAddress"]; // Read controller port if (ConfigurationManager.AppSettings["ControllerPort"] == null) { logger.Fatal("ControllerPort setting not found in App.config file!"); throw new Exception("ControllerPort setting not found in App.config file!"); } int controllerPort; if (!int.TryParse(ConfigurationManager.AppSettings["ControllerPort"], out controllerPort)) { logger.Fatal("ControllerPort setting is not an integer!"); throw new Exception("ControllerPort setting is not an integer!"); } // Read threads count value int threadsCount; if (ConfigurationManager.AppSettings["ThreadsCount"] != null) { if (!int.TryParse(ConfigurationManager.AppSettings["ThreadsCount"], out threadsCount)) { threadsCount = DefaultThreadsCount; } } else { threadsCount = DefaultThreadsCount; } // Create clients this.clients = new List<AgentClient>(); for (var i = 1; i <= threadsCount; i++) { var client = new AgentClient(controllerAddress, controllerPort, logger); this.clients.Add(client); } logger.Info("AgentService initialized."); }
/// <summary> /// Initializes a new instance of the LoggerFacade class that implements the log4net logger. /// </summary> public LoggerFacade() { // Log4net requires a call to configure the logger from // the App.config file prior to calling GetLogger(). log4net.Config.XmlConfigurator.Configure(); logger = LogManager.GetLogger(typeof(LoggerFacade)); logger.Info("*********************************************"); logger.Info("*********************************************"); logger.Info("AuthorisationManager.WCFServiceHost"); logger.Info("Copyright © Development In Progress Ltd 2016"); logger.Info("Start Service"); }
/// <summary> /// Initializes a new instance of the LoggerFacade class that implements the log4net logger. /// </summary> public LoggerFacade() { // Log4net requires a call to configure the logger from // the App.config file prior to calling GetLogger(). log4net.Config.XmlConfigurator.Configure(); logger = LogManager.GetLogger(typeof(LoggerFacade)); logger.Info("*********************************************"); logger.Info("*********************************************"); logger.Info("Origin"); logger.Info("Copyright © Development In Progress Ltd 2012"); logger.Info("Start Application"); }
internal static void Test2(ILog logger) { logger.Info("first message " + DateTime.Now.ToString()); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int x = 0; x < 1000000; x++) { logger.Info("Logging message: " + x); } stopwatch.Stop(); Console.WriteLine("Last message: " + DateTime.Now); Console.WriteLine("time taken: " + stopwatch.ElapsedMilliseconds); }
protected void Application_Start() { log4net.Config.XmlConfigurator.Configure(); log = LogManager.GetLogger("nhibernatedemo"); log.Info("Starting up"); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); CreateContainer(); log.Info("Startup complete"); }
protected void Application_Start() { // create empty config database if it not exists ConfigureMEF(); DatabasesConfigure.ConfigureDB(); // set the anti CSRF for name (that's a unqiue claim in our system) AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name; AreaRegistration.RegisterAllAreas(); _logger = ServiceLocator.Current.GetInstance<ILog>(); _logger.Info("Application_Start started"); GlobalConfig.CustomizeConfig(GlobalConfiguration.Configuration); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters, ServiceLocator.Current.GetInstance<IConfigurationRepository>()); ProtocolConfig.RegisterProtocols(GlobalConfiguration.Configuration, RouteTable.Routes, ServiceLocator.Current.GetInstance<IConfigurationRepository>(), ServiceLocator.Current.GetInstance<IUserRepository>(), ServiceLocator.Current.GetInstance<IRelyingPartyRepository>()); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //WebApiApplication.DataManager = ServiceLocator.Current.GetInstance<IDataManager>(); //Start processing integration tasks //IntegrationTasksManager.Start(); }
public override void Execute(DataModel context, ILog log) { var scannedLearners = context.ScannedInLearners.ToList().Where(s => DateTime.Now - s.TimeIn > TimeSpan.FromHours(5)); var scans = scannedLearners.Select(scannedLearner => new LearnerScan() { CreatedAt = DateTime.Now, Activity = "Scanned Out", Details = "Out (Automatic Midnight)", ScanType = "Attendance", Division = scannedLearner.Division, LearnerNumber = scannedLearner.LearnerNumber, Username = "******", Session = scannedLearner.Session, PartnerID = scannedLearner.LinkID } ).ToList(); context.LearnerScans.AddRange(scans); context.SaveChanges(); foreach (var scan in scans) { log.Info($"Scanning out learner: {scan.LearnerNumber} from {scan.Division}"); if (scan.PartnerID == null) continue; var partner = context.LearnerScans.FirstOrDefault(s => s.ID == scan.PartnerID); if (partner != null) { partner.PartnerID = scan.ID; } } context.ScannedInLearners.RemoveRange(scannedLearners); context.SaveChanges(); }
/// <summary> /// The info. /// </summary> /// <param name="log"> /// The log. /// </param> /// <param name="message"> /// The message. /// </param> public static void Info(ILog log, string message) { if (log != null && log.IsInfoEnabled) { log.Info(message); } }
private void notifyCompletedLearners(DataModel context, ILog log) { var learnersByDivision = Enrollment.CompletedToday(context) .Include(e => e.Learner) .Select(e => e.Learner) .Include(l => l.Division).ToList() .GroupBy(l => l.Division); foreach (var grouping in learnersByDivision) { var division = grouping.Key; var mail = new MailMessage("*****@*****.**", division.Email); var builder = new StringBuilder(); builder.AppendLine("The following learners have completed their enrollments today:"); foreach (var learner in grouping) { log.Info($"Notified {learner.DivisionAbreviation} that learner {learner.LearnerNumber} completed their enrollment."); builder.AppendLine($"{learner.DivisionAbreviation}{learner.LearnerNumber}\t{learner.Surname}, {learner.Name}"); } mail.Subject = "Learners that have completed their enrollments"; mail.Body = builder.ToString(); var outbox = new Outbox(); outbox.Send(mail); } }
public LoginBase() { Logger = LoggerHelper.GetLogger(GetType()); Lpage = new LoginPage(ObjectRepository.Driver); HPage = Lpage.LoginApplication(ObjectRepository.Config.GetUsername(), ObjectRepository.Config.GetPassword()); Logger.Info("Test Execution Started"); }
public static void Info(string message, ILog log) { if (log.IsInfoEnabled) { log.Info(message); } }
public GroundControlCore(IntPtr handle) { XmlConfigurator.Configure(); logger = LogManager.GetLogger(""); logger.Info(new UAVCommons.Logging.ParameterLogEvent()); currentUAV = new UAV(); try { stick = new FlightControlCommons.UAVJoystick("Joystickunmapped", "", handle); stick.ConnectHardware(); currentUAV.uavData.Add(stick); mapping = new UAVCommons.UAVDataMapping("Joystick", "", stick); foreach (string key in stick.values.Keys) { if (!mapping.Mapping.ContainsKey(key)) { mapping.Mapping.Add(key, key); } } currentUAV.uavData.Add(mapping); } catch (Exception ex) { // currentUAV.WriteToLog("GroundLog","Error on Adding Joystick"); } // currentUAV.uavData.Add("Joystick", new FlightControlCommons.UAVJoystick("Joystick",0)); // currentUAV.uavData.Add("Keyboard", new FlightControlCommons.UAVKeyboard("Keyboard", 0)); }
/** * <summary> * Constructor with port name and open the port. * Also initializes servo channels to center * </summary> * * <param name="portName">Name of the serial port</param> * <param name="channels">Channels to center on construction</param> */ protected MiniSSCIIServoController(string portName, ICollection<uint> channels) { log = LogManager.GetLogger(this.GetType()); log.Debug(this.ToString() + " constructed."); activeChannels = channels; try { port = new SerialPort(portName); port.Open(); port.BaudRate = 9600; port.NewLine = string.Empty + Convert.ToChar(13); port.Handshake = System.IO.Ports.Handshake.None; port.BaseStream.Flush(); port.ReadTimeout = 1000; inactive = false; foreach (uint ch in channels) { ServoMovementCommand smc = new ServoMovementCommand(ch, 128); sendCommand(smc); } log.Info("Initiating all servos to center."); } catch (IOException ex) { log.Error("Could not open Servo Controller Port on " + portName, ex); inactive = true; } }
public static void Write(string msg, LogLevel lv = LogLevel.INFO) { log4net.GlobalContext.Properties["LogName"] = string.Format("{0}.{1}.log", DateTime.Now.ToString("yyyy-MM-dd"), lv.ToString().ToLower()); _Log = LogManager.GetLogger(typeof(LogHelper)); switch (lv) { case LogLevel.ALL: _Log.Info(msg); break; case LogLevel.DEBUG: _Log.Debug(msg); break; case LogLevel.ERROR: _Log.Error(msg); break; case LogLevel.FATAL: _Log.Fatal(msg); break; case LogLevel.INFO: _Log.Info(msg); break; case LogLevel.WARN: _Log.Warn(msg); break; default: _Log.Info(msg); break; } }
public NorthwindController() { logger = log4net.LogManager.GetLogger("NorthwindController"); logger.Info("NorthwindController ctor"); var session = NorthwindConfig.OpenSession(); context = new NorthwindContext(session, NorthwindConfig.Configuration); }
public void Configure(string collectorName, XElement configElement, ISystemMetricsService systemMetrics) { _log = SuperCheapIOC.Resolve<ILog>(); _systemMetrics = systemMetrics; var config = new SqlServerConfiguration(configElement.Attribute("connectionString").Value, configElement.ToInt("writeBatchSize")); _connectionString = config.ConnectionString; _collectorName = collectorName; _retries = config.Retries; InitialiseRetryHandling(); _batchBlock = new BatchBlock<GraphiteLine>(config.WriteBatchSize); _actionBlock = new ActionBlock<GraphiteLine[]>(p => SendToDB(p), new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = 1 }); _batchBlock.LinkTo(_actionBlock); _batchBlock.Completion.ContinueWith(p => _actionBlock.Complete()); _actionBlock.Completion.ContinueWith(p => { _isActive = false; }); _completionTask = new Task(() => { _log.Info("SqlServerBackend - Completion has been signaled. Waiting for action block to complete."); _batchBlock.Complete(); _actionBlock.Completion.Wait(); }); }
public override void Execute(DataModel context, ILog log) { var today = DateTime.Today; var scannedEmployees = context.ScannedInEmployees .Include(e => e.InScan) .Where(s => DbFunctions.TruncateTime(s.InScan.CreatedAt) < today) .ToList(); foreach (var scannedEmployee in scannedEmployees) { var scanIn = context.EmployeeScans.Find(scannedEmployee.ScanID); var scan = new EmployeeScan() { CreatedAt = scanIn.CreatedAt, EmployeeNumber = scannedEmployee.EmployeeNumber, Division = scanIn.Division, Details = "Out (System)", ScanType = "Type", PartnerID = scanIn.ID, Username = "******" }; log.Info($"Scanning out Employee: {scan.EmployeeNumber} from {scan.Division}"); context.EmployeeScans.Add(scan); } context.ScannedInEmployees.RemoveRange(scannedEmployees); context.SaveChanges(); }
internal static void Test1(ILog logger) { IList<string> myList = new List<string>(); myList.Add("item1"); myList.Add("item2"); IDictionary<string, string> myDictionary = new Dictionary<string, string>(); myDictionary["k1"] = "v1"; myDictionary["k2"] = "v2"; HttpField.HttpInstance.Set(HttpFieldName.ResponseHeaders, myList); HttpField.HttpInstance.Set(HttpFieldName.RequestHeaders, myDictionary); logger.Error("there's been an error"); // log4net doesn't give exceptions any special treatment... // also dotnet won't generate a stacktrace for an exception til we throw it... logger.Error(new ArgumentException("Fake Error Thrown")); try { string dodgy = null; Console.WriteLine(dodgy.Equals("that", StringComparison.InvariantCulture)); } catch (NullReferenceException e) { logger.Error(e); } HttpField.HttpInstance.Clear(); logger.Info("non exception"); }
public App() { log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); log.Info("程序启动"); try { log.Info("启动初始化启动窗口"); SplashScreen splashScreen = new SplashScreen("icons/SplashScreen.png"); splashScreen.Show(true); } catch (Exception ex) { log.Fatal("初始化启动窗口出错", ex); } }
public QueryResultsContainer(QuestionType questionType) { _questionType = questionType; _results = new List<QueryResult>(); _logger = ServiceLocator.Current.GetInstance<ILog>(); _logger.Info("Create query result container with question type '" + _questionType); }
public void Info(string message, Exception ex = null) { _logger.Info(ex == null ? message : String.Format(_messageFormat, message, ex)); }
public void StartWork() { LOG.Info(string.Format("设备{0}监控启动.", ResourceName)); }
public void Log(string message) { _log.Info(message); }
public void Add(Persona persona) { log.Info("Accediendo al metodo Add."); CreateJsonPersona(persona); }
public static void ScriptLoaded(DOLEvent e, object sender, EventArgs args) { if (!ServerProperties.Properties.LOAD_QUESTS) { return; } if (log.IsInfoEnabled) { log.Info("Quest \"" + questTitle + "\" initializing ..."); } GameNPC[] npcs = WorldMgr.GetNPCsByName("Sir Strain", eRealm.Albion); if (npcs == null || npcs.Length == 0) { sirStrain = new GameNPC(); sirStrain.Model = 28; sirStrain.Name = "Sir Strain"; if (log.IsWarnEnabled) { log.Warn("Could not find " + sirStrain.Name + ", creating him ..."); } sirStrain.GuildName = "Part of " + questTitle + " Quest"; sirStrain.Realm = eRealm.Albion; sirStrain.CurrentRegionID = 27; GameNpcInventoryTemplate template = new GameNpcInventoryTemplate(); template.AddNPCEquipment(eInventorySlot.HandsArmor, 696); template.AddNPCEquipment(eInventorySlot.FeetArmor, 697); template.AddNPCEquipment(eInventorySlot.TorsoArmor, 693); template.AddNPCEquipment(eInventorySlot.Cloak, 676); template.AddNPCEquipment(eInventorySlot.LegsArmor, 694); template.AddNPCEquipment(eInventorySlot.ArmsArmor, 695); sirStrain.Inventory = template.CloseTemplate(); sirStrain.SwitchWeapon(GameLiving.eActiveWeaponSlot.TwoHanded); sirStrain.Size = 50; sirStrain.Level = 50; sirStrain.X = 98507; sirStrain.Y = 90637; sirStrain.Z = 5716; sirStrain.Heading = 147; //You don't have to store the created mob in the db if you don't want, //it will be recreated each time it is not found, just comment the following //line if you rather not modify your database if (SAVE_INTO_DATABASE) { sirStrain.SaveIntoDatabase(); } sirStrain.AddToWorld(); } else { sirStrain = npcs[0]; } GameEventMgr.AddHandler(GamePlayerEvent.AcceptQuest, new DOLEventHandler(SubscribeQuest)); GameEventMgr.AddHandler(GamePlayerEvent.DeclineQuest, new DOLEventHandler(SubscribeQuest)); GameEventMgr.AddHandler(sirStrain, GameLivingEvent.Interact, new DOLEventHandler(TalkToSirStrain)); GameEventMgr.AddHandler(sirStrain, GameLivingEvent.WhisperReceive, new DOLEventHandler(TalkToSirStrain)); sirStrain.AddQuestToGive(typeof(GreetingsPaladin)); if (log.IsInfoEnabled) { log.Info("Quest \"" + questTitle + "\" initialized"); } }
private static bool Patch(string updateUrl, string patcherUrl, string[] extraArgs, bool forceScan, bool exit_after_patch) { string localVersion = string.Empty; try { localVersion = GetClientVersion(File.Open("../" + VersionFile, FileMode.Open, FileAccess.Read)); } catch (Exception e) { LogUtil.ExceptionLog.ErrorFormat("Unable to determine local version: {0}", e); } string remoteVersion = string.Empty; // Pull the remote version WebClient webClient = new WebClient(); webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache); string localUpdateUrl = (updateUrl == null) ? UpdateUrl : updateUrl; Stream webStream; // It is extremely common for people to not have the right update url. // Assume they left off the trailing slash and try again if we do not // find the file. log.Info("Checking for client updates at URL '" + localUpdateUrl + VersionFile + "'"); try { webStream = webClient.OpenRead(localUpdateUrl + VersionFile); } catch (WebException ex) { if (ex.Response is HttpWebResponse && ((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound) { webStream = webClient.OpenRead(localUpdateUrl + "/" + VersionFile); log.Warn("Incorrect Update URL Specification: Update URL should have a trailing slash."); localUpdateUrl = localUpdateUrl + "/"; } else { throw; } } try { remoteVersion = GetClientVersion(webStream); } catch (Exception e) { LogUtil.ExceptionLog.ErrorFormat("Failed to retrieve remote version: {0}", e); } finally { webStream.Close(); } if (localVersion == remoteVersion) { log.InfoFormat("Client version up to date: {0}", localVersion); // we are up to date.. if (!forceScan) { return(false); } log.InfoFormat("Forcing patch from {0} to {1}", localVersion, remoteVersion); } else { log.InfoFormat("Patching from {0} to {1}", localVersion, remoteVersion); } // Pull the updated patcher, and spawn it log.Info("Downloading patcher..."); string currentDir = Directory.GetCurrentDirectory(); string parentDir = Directory.GetParent(currentDir).FullName; if ((parentDir + "\\bin") != currentDir) { Debug.Assert(false, "Client must be run from the bin folder.\nIf you are running a development build, you should use the --noupdate command line option. Current folder is: " + currentDir); return(true); } try { webClient.DownloadFile(localUpdateUrl + Patcher, Path.Combine(Path.GetTempPath(), Patcher)); } catch (Exception e) { log.Error("Failed to download patcher" + e.ToString()); } Process clientProcess = Process.GetCurrentProcess(); string cmdArgs = "--parent_id " + clientProcess.Id.ToString(); if (updateUrl != null) { cmdArgs += " --update_url " + updateUrl; } if (patcherUrl != null) { cmdArgs += " --patcher_url " + patcherUrl; } if (exit_after_patch) { cmdArgs += " --exit"; } foreach (string extraArg in extraArgs) { cmdArgs += " \"" + extraArg + "\""; } log.DebugFormat("Patcher arguments: {0}", cmdArgs); ProcessStartInfo psi = new ProcessStartInfo(Path.Combine(Path.GetTempPath(), Patcher), cmdArgs); psi.WorkingDirectory = parentDir; try { Process p = Process.Start(psi); log.Info("Launched patcher..." + p.ToString()); } catch (Exception) { // Probably didn't have permission on Vista log.Error("Failed to launch patcher..."); } return(true); }
protected virtual void info(string str, LoggerSource source = LoggerSource.none) { try { logger.Info(createMessage(str, source)); } catch { } Console.WriteLine(createMessage(str, source)); }
public static void info(string str, LoggerSource source = LoggerSource.server) { logger.Info(createMessage(str, source)); }
public void DownloadHtmlFormat() { log4net.ILog logger = log4net.LogManager.GetLogger("File"); try { Int32 intcellCount = gvKeySearch.Columns.Count; string strContent = ""; string strHeaderText = ""; string strHtmlFile = "TxnHtmlFile"; Response.ClearHeaders(); Response.ClearContent(); string datetime = string.Empty; datetime = Convert.ToString(System.DateTime.Now); string str = string.Empty; if (txtkeyno1.Text != "") { str = (" Key No. : " + txtkeyno1.Text); } if (txtKeyName.Text != "") { str = (" Name : " + txtKeyName.Text); } if (txtdatefrom.Text != "" && txtdateto.Text != "") { str = (" Date From : " + txtdatefrom.Text + " To :" + txtdateto.Text); } Response.AddHeader("content-disposition", string.Format("attachment;filename=testhtml.html")); Response.Charset = ""; Response.ContentType = "text/html"; StringWriter sw = new StringWriter(); sw.Write("<table border =1>"); sw.Write("<CAPTION><b>Key Report</b></CAPTION>"); sw.Write("Generated On : "); sw.Write(datetime); sw.Write("<CAPTION><br/></CAPTION>"); sw.Write("Searching Parameter : "); sw.Write(str); sw.Write("<tr>"); for (int i = 0; i < intcellCount; i++) { strHeaderText = gvKeySearch.Columns[i].HeaderText.ToString(); sw.Write("<th>"); sw.Write(strHeaderText); sw.Write("</th>"); sw.Write("<td>"); sw.Write(" "); sw.Write("</td>"); } sw.Write("</tr>"); foreach (GridViewRow grvRow in gvKeySearch.Rows) { sw.Write("<tr>"); for (Int32 i = 0; i < intcellCount; i++) { strContent = grvRow.Cells[i].Text.ToString(); sw.Write("<td>"); sw.Write(strContent); sw.Write("</td>"); sw.Write("<td>"); sw.Write(" "); sw.Write("</td>"); } sw.Write("</tr>"); } sw.Write("</table>"); Response.Write(sw.ToString()); Response.End(); } catch (Exception ex) { logger.Info(ex.Message); } }
private void SendEmail() { log.Info("BatchJobmailSender : Inside SendEmail function"); string toaddress = ""; string cc = ""; string bcc = ""; string subject = ""; string id = ""; SendMailObject obj = new SendMailObject(); DataSet ds = new DataSet(); ds = obj.SelectEMailQueueDetails(); try { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { try { MailMessage Msg = new MailMessage(); System.Net.Mail.SmtpClient spcl = new System.Net.Mail.SmtpClient(); string password = ConfigurationManager.AppSettings["MailPassword"].ToString(); string from = ConfigurationManager.AppSettings["FromAddress"].ToString(); string footertext = ConfigurationManager.AppSettings["FooterText"].ToString(); subject = ds.Tables[0].Rows[i]["Subject"].ToString(); string to = ds.Tables[0].Rows[i]["ToEmail"].ToString(); cc = ds.Tables[0].Rows[i]["CC"].ToString(); bcc = ds.Tables[0].Rows[i]["BCC"].ToString(); string body = ds.Tables[0].Rows[i]["MsgBody"].ToString(); id = ds.Tables[0].Rows[i]["Id"].ToString(); Session["Module"] = ds.Tables[0].Rows[i]["Module"].ToString(); Msg.Subject = subject; if (cc != "") { string[] ccemaillist = cc.Split(','); for (int j = 0; j <= ccemaillist.GetUpperBound(0); j++) { Msg.CC.Add(ccemaillist[j]); } } if (bcc != "") { string[] bccemaillist = bcc.Split(','); for (int j = 0; j <= bccemaillist.GetUpperBound(0); j++) { Msg.Bcc.Add(bccemaillist[j]); } } Msg.Priority = MailPriority.Normal; Msg.IsBodyHtml = true; Msg.From = new MailAddress(from); Msg.Body = body; toaddress = ds.Tables[0].Rows[i]["ToEmail"].ToString(); if (toaddress != null) { string[] toaddress_value = toaddress.Split(','); for (int j = 0; j <= toaddress_value.GetUpperBound(0); j++) { Msg.To.Add(toaddress_value[j]); } } spcl.Host = ConfigurationManager.AppSettings["MailHost"].ToString(); spcl.Port = Convert.ToInt16(ConfigurationManager.AppSettings["SMTPPort"]); spcl.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSSL"]); spcl.Credentials = new System.Net.NetworkCredential(from, password); spcl.Send(Msg); bool result = obj.UpdateEmailSendFlag(id, Session["Module"], subject); if (result == true) { log.Info("BatchJobmailSender:Email is sent to sucessfully for the user (To adress) :" + toaddress + " subject: " + subject + " Module: " + Session["Module"] + " Id: " + id); if (cc != "") { log.Info("BatchJobmailSender:Email is sent to sucessfully for the user (CC) : '" + cc + "' "); } if (bcc != "") { log.Info(" BatchJobmailSender:Email is sent to sucessfully for the user (BCC) : '" + bcc + "' "); } ClientScript.RegisterStartupScript(Page.GetType(), "validation1", "<script language='javascript'>alert('Email is sent sucessfully')</script>"); } } catch (Exception ex) { //ClientScript.RegisterStartupScript(Page.GetType(), "validation1", "<script language='javascript'>alert('Problem in sending email')</script>"); log.Error(ex.StackTrace); log.Error(ex.Message); log.Error("BatchJobmailSender:Email Send Failed : '" + ex + "' "); log.Error("BatchJobmailSender:Email Failed for the user :"******" subject: " + subject + " Module: " + Session["Module"] + " Id: " + id); log.Error("BatchJobmailSender:Email Failed for the user :"******" subject: " + subject + " Module: " + Session["Module"] + " Id: " + id); log.Error("BatchJobmailSender:Email Failed for the user :"******" subject: " + subject + " Module: " + Session["Module"] + " Id: " + id); if (cc != "") { log.Info("BatchJobmailSender:Email Failed for the user (CC) : '" + cc + "' "); } if (bcc != "") { log.Info("BatchJobmailSender:Email Failed for the user (BCC) : '" + bcc + "' "); } } } } catch (Exception e1) { log.Error(e1.StackTrace); log.Error(e1.Message); log.Error("BatchJobmailSender:Email Send Failed : '" + e1 + "' "); ClientScript.RegisterStartupScript(Page.GetType(), "validation1", "<script language='javascript'>alert('Problem in sending email')</script>"); } Response.Write("<script language='javascript'> {window.open('', '_self', ''); window.close();}</script>"); }
public void Info <T>(object message) { //log.LogInformation(message.ToString()); log4.Info(message); }
// public bool EnviarOrdemCross(OrdemCrossInfo info) { return false; } public bool EnviarOrdem(OrdemInfo ordem, long ini = 0, long fim = 0, int delay = 0, string mnemonic = "", string senderSubID = "", string extraTags = "") { //Cria a mensagem FIX de NewOrderSingle QuickFix.FIX42.NewOrderSingle ordersingle = new QuickFix.FIX42.NewOrderSingle(); ordersingle.Set(new Account(ordem.Account.ToString())); if (!string.IsNullOrEmpty(mnemonic)) { ordersingle.SetField(new Account(mnemonic), true); } if (!string.IsNullOrEmpty(senderSubID)) { ordersingle.Header.SetField(new SenderSubID(senderSubID)); } ordersingle.Set(new Symbol(ordem.Symbol)); ordersingle.Set(new ClOrdID(ordem.ClOrdID)); // Armazena ClOrdID em Memo (5149) para posterior referência nos tratamentos de retornos QuickFix.Fields.StringField field5149 = new QuickFix.Fields.StringField(5149, ordem.ClOrdID); ordersingle.SetField(field5149); //ordersingle.Set(new IDSource()); if (ordem.Side == OrdemDirecaoEnum.Venda) { ordersingle.Set(new Side(Side.SELL)); } else { ordersingle.Set(new Side(Side.BUY)); } TimeInForce tif = FixMessageUtilities.deOrdemValidadeParaTimeInForce(ordem.TimeInForce); if (tif != null) { ordersingle.Set(tif); } ordersingle.Set(new OrderQty(ordem.OrderQty)); if (ordem.TimeInForce == OrdemValidadeEnum.ValidoAteDeterminadaData) { DateTime expiredate = Convert.ToDateTime(ordem.ExpireDate); ordersingle.Set(new ExpireDate(expiredate.ToString("yyyyMMdd"))); } OrdType ordType = FixMessageUtilities.deOrdemTipoParaOrdType(ordem.OrdType); if (ordType != null) { ordersingle.Set(ordType); } // Para versao 4.2, os novos tipos de OrdType a serem enviados (5, A ou B); if (!string.IsNullOrEmpty(ordem.Memo5149)) { ordersingle.SetField(new OrdType(Convert.ToChar(ordem.Memo5149)), true); } // Verifica envio do preco switch (ordem.OrdType) { case OrdemTipoEnum.Limitada: case OrdemTipoEnum.MarketWithLeftOverLimit: ordersingle.Set(new Price(Convert.ToDecimal(ordem.Price))); break; case OrdemTipoEnum.StopLimitada: case OrdemTipoEnum.StopStart: ordersingle.Set(new Price(Convert.ToDecimal(ordem.Price))); ordersingle.Set(new StopPx(Convert.ToDecimal(ordem.StopPrice))); break; case OrdemTipoEnum.Mercado: case OrdemTipoEnum.OnClose: ordersingle.Set(new Price(Convert.ToDecimal(ordem.Price))); break; default: ordersingle.Set(new Price(Convert.ToDecimal(ordem.Price))); break; } ordersingle.Set(new TransactTime(DateTime.Now)); ordersingle.Set(new HandlInst('1')); ordersingle.Set(new ExecBroker("227")); if (ordem.MaxFloor > 0) { ordersingle.Set(new MaxFloor(Convert.ToDecimal(ordem.MaxFloor))); } if (ordem.MinQty > 0) { ordersingle.Set(new MinQty(Convert.ToDecimal(ordem.MinQty))); } // Tags Customizadas Bloomberg if (!string.IsNullOrEmpty(extraTags)) { string[] arr = extraTags.Split(';'); for (int i = 0; i < arr.Length; i++) { if (!string.IsNullOrEmpty(arr[i])) { string [] valor = arr[i].Split('='); StringField fld = new StringField(Convert.ToInt32(valor[0]), valor[1]); ordersingle.SetField(fld); } } } QuickFix.FIX42.NewOrderSingle.NoAllocsGroup noAllocsGrp = new QuickFix.FIX42.NewOrderSingle.NoAllocsGroup(); noAllocsGrp.Set(new AllocAccount("67")); ordersingle.AddGroup(noAllocsGrp); bool bRet = false; if (ini == 0) { bRet = Session.SendToTarget(ordersingle, _session.SessionID); } else { long times = fim - ini; logger.Info("=====================================> INICIO ========> Qtd: " + times); for (long i = 0; i < times; i++) { ClOrdID xx = new ClOrdID(ini.ToString()); ordersingle.ClOrdID = xx; bRet = Session.SendToTarget(ordersingle, _session.SessionID); if (!bRet) { logger.Info("erro"); break; } if (0 != delay) { Thread.Sleep(delay); } ini++; } logger.Info("=====================================> FIM ========> Qtd: " + times); } return(bRet); }
private void BUT_geinjection_Click(object sender, EventArgs e) { var MainMap = new GMapControl(); MainMap.MapProvider = GoogleSatelliteMapProvider.Instance; MainMap.CacheLocation = Path.GetDirectoryName(Application.ExecutablePath) + "/gmapcache/"; var fbd = new FolderBrowserDialog(); try { fbd.SelectedPath = @"C:\Users\hog\Documents\albany 2011\New folder"; } catch { } if (fbd.ShowDialog() != DialogResult.OK) { return; } if (fbd.SelectedPath != "") { var files = Directory.GetFiles(fbd.SelectedPath, "*.jpg", SearchOption.AllDirectories); var files1 = Directory.GetFiles(fbd.SelectedPath, "*.png", SearchOption.AllDirectories); var origlength = files.Length; Array.Resize(ref files, origlength + files1.Length); Array.Copy(files1, 0, files, origlength, files1.Length); foreach (var file in files) { log.Info(DateTime.Now.Millisecond + " Doing " + file); var reg = new Regex(@"Z([0-9]+)\\([0-9]+)\\([0-9]+)"); var mat = reg.Match(file); if (mat.Success == false) { continue; } var temp = 1 << int.Parse(mat.Groups[1].Value); var pnt = new GPoint(int.Parse(mat.Groups[3].Value), int.Parse(mat.Groups[2].Value)); BUT_geinjection.Text = file; BUT_geinjection.Refresh(); //MainMap.Projection. var tile = new MemoryStream(); var Img = Image.FromFile(file); Img.Save(tile, ImageFormat.Jpeg); tile.Seek(0, SeekOrigin.Begin); log.Info(pnt.X + " " + pnt.Y); Application.DoEvents(); GMaps.Instance.PrimaryCache.PutImageToCache(tile.ToArray(), Custom.Instance.DbId, pnt, int.Parse(mat.Groups[1].Value)); // Application.DoEvents(); } } }
static void Main(string[] args) { try { System.IO.FileInfo fi = new System.IO.FileInfo(@"myLog4Net.xml"); //Enklare lösning på kopieringsproblemet fås genom filens Property-fönstro if (fi.Exists) { log4net.Config.XmlConfigurator.Configure(fi); logger.Info("File myLog4Net.xml exists"); } else { log4net.Config.BasicConfigurator.Configure(); // Den enklaste konfiguratorn kräver ej att du specar en konfigureringsfil logger.Error("Missing file myLog4Net.xml"); } } catch (Exception e) { log4net.Config.BasicConfigurator.Configure(); // Den enklaste konfiguratorn kräver ej att du specar en konfigureringsfil logger.Error("Missing file myLog4Net.xml", e); } if (logger.IsDebugEnabled) { logger.Debug("Test av DEBUG-logg"); } if (logger.IsInfoEnabled) { logger.Info("Test av INFO-logg"); } if (logger.IsWarnEnabled) { logger.Warn("Test av WARN-logg"); } if (logger.IsErrorEnabled) { logger.Error("Test av ERROR-logg"); } if (logger.IsFatalEnabled) { logger.Fatal("Test av FATAL-logg"); } while (i != 0) { Console.WriteLine("Enter a number"); str = Console.ReadLine(); Int32.TryParse(str, out i); if (i == 1) { Console.WriteLine("Full in"); logger.Debug("Number 1 pressed"); } else if (i == 2) { Console.WriteLine("Half in"); logger.Debug("Number 2 pressed"); } else { Console.WriteLine("Not in"); logger.Debug("Other pressed"); } } }
private string ReturnWhere() { string str = string.Empty; string makeWhereClause = string.Empty; log4net.ILog logger = log4net.LogManager.GetLogger("File"); try { List <String> arr = new List <String>(); arr.Add("test"); if (txtItemName.Text.Trim() != "") { if (arr.Count == 1) { makeWhereClause = " where "; str += " and Item_Name='" + txtItemName.Text + "'"; //str += " where Item_Name='" + txtItemName.Text + "'"; //arr.Add("1"); } else { //str += " and Item_Name='" + txtItemName.Text + "'"; str += " where Item_Name='" + txtItemName.Text + "'"; arr.Add("1"); } } if (txtModel.Text.Trim() != "") { if (arr.Count == 1) { str += " and Model_No = '" + txtModel.Text + "'"; //str += " where Model_No = '" + txtModel.Text + "'"; //arr.Add("2"); } else { //str += " and Model_No = '" + txtModel.Text + "'"; str += " where Model_No = '" + txtModel.Text + "'"; arr.Add("2"); } } if (txtIssuedTo.Text.Trim() != "") { if (arr.Count == 1) { makeWhereClause = " where "; str += " and IssuedTo_Name='" + txtIssuedTo.Text + "'"; //str += " where IssuedTo_Name='" + txtIssuedTo.Text + "'"; //arr.Add("3"); } else { str += " where IssuedTo_Name='" + txtIssuedTo.Text + "'"; arr.Add("3"); //str += " and IssuedTo_Name='" + txtIssuedTo.Text + "'"; } } if (txtIssuedBy.Text.Trim() != "") { if (arr.Count == 1) { str += " and IssuedBy_Name = '" + txtIssuedBy.Text + "'"; //str += " where IssuedBy_Name = '" + txtIssuedBy.Text + "'"; //arr.Add("4"); } else { str += " where IssuedBy_Name = '" + txtIssuedBy.Text + "'"; arr.Add("4"); //str += " and IssuedBy_Name = '" + txtIssuedBy.Text + "'"; } } if (txtdateto.Text != "" && txtdatefrom.Text != "") { if (arr.Count == 1) { str += " and IssuedBy_Time BETWEEN '" + txtdatefrom.Text + "' AND '" + txtdateto.Text + "'"; // str += " where IssuedBy_Time BETWEEN '" + txtdatefrom.Text + "' AND '" + txtdateto.Text + "'"; //arr.Add("5"); } else { str += " where IssuedBy_Time BETWEEN '" + txtdatefrom.Text + "' AND '" + txtdateto.Text + "'"; arr.Add("5"); //str += " and IssuedBy_Time BETWEEN '" + txtdatefrom.Text + "' AND '" + txtdateto.Text + "'"; } } if (txtdatefrom.Text != "" && txtdateto.Text == "") { if (arr.Count == 1) { str += " and IssuedBy_Time ='" + txtdatefrom.Text + "'"; //str += " where IssuedBy_Time ='" + txtdatefrom.Text + "'"; //arr.Add("6"); } else { str += " where IssuedBy_Time ='" + txtdatefrom.Text + "'"; arr.Add("6"); //str += " and IssuedBy_Time ='" + txtdatefrom.Text + "'"; } } } catch (Exception ex) { logger.Info(ex.Message); } return(str); }
public void DownloadPDFFormat() { log4net.ILog logger = log4net.LogManager.GetLogger("File"); try { Document pdfReport = new Document(PageSize.A4, 25, 25, 40, 25); System.IO.MemoryStream msReport = new System.IO.MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(pdfReport, msReport); pdfReport.Open(); string datetime = string.Empty; datetime = Convert.ToString(System.DateTime.Now); string str = string.Empty; if (txtkeyno1.Text != "") { str = (" Key No. : " + txtkeyno1.Text); } if (txtKeyName.Text != "") { str = (" Name : " + txtKeyName.Text); } if (txtdatefrom.Text != "" && txtdateto.Text != "") { str = (" Date From : " + txtdatefrom.Text + " To :" + txtdateto.Text); } Phrase headerPhrase = new Phrase("Key Report ", FontFactory.GetFont("Garamond", 14)); headerPhrase.Add(" Generated On : "); headerPhrase.Add(datetime); headerPhrase.Add(" Searching Parameter : "); headerPhrase.Add(str); HeaderFooter header = new HeaderFooter(headerPhrase, false); header.Border = Rectangle.NO_BORDER; header.Alignment = Element.ALIGN_CENTER; header.Alignment = Element.ALIGN_BOTTOM; pdfReport.Header = header; pdfReport.Add(headerPhrase); // Creates the Table PdfPTable ptData = new PdfPTable(gvKeySearch.Columns.Count); ptData.SpacingBefore = 8; ptData.DefaultCell.Padding = 1; float[] headerwidths = new float[gvKeySearch.Columns.Count]; // percentage headerwidths[0] = 3.2F; headerwidths[1] = 3.2F; headerwidths[2] = 3.2F; headerwidths[3] = 3.2F; headerwidths[4] = 3.2F; headerwidths[5] = 3.2F; headerwidths[6] = 3.2F; headerwidths[7] = 3.2F; headerwidths[8] = 4.5F; ptData.SetWidths(headerwidths); ptData.WidthPercentage = 100; ptData.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED; ptData.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE; //Insert the Table Headers for (int intK = 0; intK < gvKeySearch.Columns.Count; intK++) { PdfPCell cell = new PdfPCell(); cell.BorderWidth = 0.001f; cell.BackgroundColor = new Color(200, 200, 200); cell.BorderColor = new Color(100, 100, 100); cell.Phrase = new Phrase(gvKeySearch.Columns[intK].HeaderText.ToString(), FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7, Font.BOLD)); ptData.AddCell(cell); } ptData.HeaderRows = 1; // this is the end of the table header //Insert the Table Data for (int intJ = 0; intJ < gvKeySearch.Rows.Count; intJ++) { for (int intK = 0; intK < gvKeySearch.Columns.Count; intK++) { PdfPCell cell = new PdfPCell(); cell.BorderWidth = 0.001f; cell.BorderColor = new Color(100, 100, 100); cell.BackgroundColor = new Color(250, 250, 250); if (gvKeySearch.Rows[intJ].Cells[intK].Text.ToString() != " ") { cell.Phrase = new Phrase(gvKeySearch.Rows[intJ].Cells[intK].Text.ToString(), FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 6)); } else { cell.Phrase = new Phrase("", FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 6)); } ptData.AddCell(cell); } } //Insert the Table pdfReport.Add(ptData); //Closes the Report and writes to Memory Stream pdfReport.Close(); //Writes the Memory Stream Data to Response Object Response.Clear(); Response.AddHeader("content-disposition", string.Format("attachment;filename=testpfd.pdf")); Response.Charset = ""; Response.ContentType = "application/pdf"; Response.BinaryWrite(msReport.ToArray()); Response.End(); } catch (Exception ex) { logger.Info(ex.Message); } }
public static void logInfo(string className, string msg) { logger = log4net.LogManager.GetLogger(className); logger.Info(string.Format("{0}: {1}", className, msg)); }
private string ReturnWhere() { string str = string.Empty; string makeWhereClause = string.Empty; log4net.ILog logger = log4net.LogManager.GetLogger("File"); try { List <String> arr = new List <String>(); arr.Add("test"); if (txtkeyno1.Text != "") { if (arr.Count == 1) { makeWhereClause = " where "; str += " where Key_no='" + txtkeyno1.Text + "'"; arr.Add("1"); } else { str += " and Key_no='" + txtkeyno1.Text + "'"; } } if (txtKeyName.Text != "") { if (arr.Count == 1) { str += " where name='" + txtKeyName.Text + "'"; arr.Add("3"); } else { str += " and name='" + txtKeyName.Text + "'"; } } if (ddlstatus.Text != "") { if (arr.Count == 1) { str += " where status='" + ddlstatus.Text + "'"; arr.Add("3"); } else { str += " and status='" + ddlstatus.Text + "'"; } } if (txtdatefrom.Text != "" && txtdateto.Text != "") { if (arr.Count == 1) { str += " where Date_From BETWEEN '" + txtdatefrom.Text + "' AND '" + txtdateto.Text + "'"; arr.Add("6"); } else { str += " and Date_From BETWEEN'" + txtdatefrom.Text + "' AND '" + txtdateto.Text + "'"; } } if (txtdatefrom.Text != "" && txtdateto.Text == "") { if (arr.Count == 1) { str += " where Date_From='" + txtdatefrom.Text + "'"; arr.Add("7"); } else { str += " and Date_From='" + txtdatefrom.Text + "'"; } } } catch (Exception ex) { logger.Info(ex.Message); } return(str); }
protected void txtItemNo_TextChanged(object sender, EventArgs e) { log4net.ILog logger = log4net.LogManager.GetLogger("File"); try { if (chksingout.Checked == true) { String ZipRegex = "^[0-9]+$"; if (Regex.IsMatch(txtItemNo.Text, ZipRegex)) { cn = a.getconnection(); SqlCommand command = new SqlCommand("select Top 1 Item_no,Item_Description,Item_quantity,loged_Nric,loged_Name,loged_CompName,loged_Time,Found_Nric,Status from Item_Manager where Item_no='" + txtItemNo.Text + "' ", cn); SqlDataReader rd = command.ExecuteReader(); if (rd.HasRows) { if (rd.Read()) { txtItemNo.Text = rd.GetValue(0).ToString(); txtItemdescription.Text = rd.GetValue(1).ToString(); txtItemquantity.Text = rd.GetValue(2).ToString(); txtlogednric.Text = rd.GetValue(3).ToString(); txtlogedname.Text = rd.GetValue(4).ToString(); txtlogedcompname.Text = rd.GetValue(5).ToString(); lbllogedtime.Text = rd.GetValue(6).ToString(); txtfoundnric.Text = rd.GetValue(7).ToString(); cmbstatus.Text = rd.GetValue(8).ToString(); } rd.Close(); //===============================// rd.Dispose(); //==================================// } else { lblerror.Visible = true; lblerror.Text = "Invalid Item No. ..!"; lblerr2.Visible = true; } } else { lblerror.Visible = true; lblerror.Text = "Invalid Item No. ..!"; lblerr2.Visible = true; } } if (chklost.Checked == true) { String ZipRegex = "^[0-9]+$"; if (Regex.IsMatch(txtItemNo.Text, ZipRegex)) { cn = a.getconnection(); SqlCommand command = new SqlCommand("select Top 1 Item_no,Item_Description,Item_quantity,loged_Time from Item_Manager where Item_no='" + txtItemNo.Text + "' ", cn); SqlDataReader rd = command.ExecuteReader(); if (rd.HasRows) { if (rd.Read()) { txtItemNo.Text = rd.GetValue(0).ToString(); txtItemdescription.Text = rd.GetValue(1).ToString(); txtItemquantity.Text = rd.GetValue(2).ToString(); lbllogedtime.Text = rd.GetValue(3).ToString(); } rd.Close(); //======================// rd.Dispose(); //========================// } else { lblerror.Visible = true; lblerror.Text = "Invalid Item No. ..!"; lblerr2.Visible = true; } } else { lblerror.Visible = true; lblerror.Text = "Invalid Item No. ..!"; lblerr2.Visible = true; } } } catch (Exception ex) { logger.Info(ex.Message); } }
private void BindGridWithFilter() { log4net.ILog logger = log4net.LogManager.GetLogger("File"); try { AdminBLL ws = new AdminBLL(); GetNewKey objReq = new GetNewKey(); string WhereClause = ReturnWhere(); if (!string.IsNullOrEmpty(txtkeyno1.Text)) { objReq.key_no = txtkeyno1.Text; } if (!string.IsNullOrEmpty(txtKeyName.Text)) { objReq.name = txtKeyName.Text; } if (!string.IsNullOrEmpty(ddlstatus.Text)) { objReq.status = ddlstatus.Text; } if (!string.IsNullOrEmpty(txtKeyName.Text)) { objReq.name = txtKeyName.Text; } if (!string.IsNullOrEmpty(WhereClause)) { objReq.WhereClause = WhereClause; } if (!string.IsNullOrEmpty(txtdateto.Text)) { if (!string.IsNullOrEmpty(txtdatefrom.Text)) { objReq.Date_From = txtdatefrom.Text; objReq.Date_From = txtdatefrom.Text; } } if (!string.IsNullOrEmpty(txtdatefrom.Text)) { if (string.IsNullOrEmpty(txtdateto.Text)) { objReq.Date_From = txtdatefrom.Text; } } GetNewKeyRequest ret = ws.GetNewKey(objReq); int pageSize = ContextKeys.GRID_PAGE_SIZE; gvKeySearch.PageSize = pageSize; gvKeySearch.DataSource = ret.Key; if (ret.Key.Count == 0) { key2.Visible = false; } gvKeySearch.DataBind(); key2.Text = ret.Key.Count.ToString(); } catch (Exception ex) { logger.Info(ex.Message); } }
public override void Information(string message) { _log.Info(message); }
private void Validate() { if (string.IsNullOrWhiteSpace(Context.HotFolderPath)) { throw new ExpectedException($"You must specify a /{nameof(Context.HotFolderPath)} option."); } Context.HotFolderPath = ResolvePath(FileHelper.ExeDirectory, Context.HotFolderPath); SourceFolder = Context.HotFolderPath; ThrowIfFolderIsMissing(SourceFolder); StatusIndicator.Activate(SourceFolder); ProcessingFolder = ResolveSourceFolderPath(Context.ProcessingFolder); PartialFolder = ResolveSourceFolderPath(Context.PartialFolder); ArchivedFolder = ResolveSourceFolderPath(Context.ArchivedFolder); UploadedFolder = ResolveSourceFolderPath(Context.UploadedFolder); FailedFolder = ResolveSourceFolderPath(Context.FailedFolder); FileMasks = (Context.FileMask ?? "*.*") .Split(FileMaskDelimiters, StringSplitOptions.RemoveEmptyEntries) .Where(mask => !string.IsNullOrWhiteSpace(mask)) .Select(CreateRegexFromDosWildcard) .ToList(); LoadLocalPlugins(); Log.Info($"{LoadedPlugins.Count} local plugins ready for parsing field data files."); foreach (var loadedPlugin in LoadedPlugins) { Log.Info($"{PluginLoader.GetPluginNameAndVersion(loadedPlugin.Plugin)}"); } }
protected void Page_Load(object sender, EventArgs e) { log4net.ILog logger = log4net.LogManager.GetLogger("File"); try { //--------------image display--------------------------- DBConnectionHandler1 bd = new DBConnectionHandler1(); SqlConnection cn = bd.getconnection(); cn.Open(); SqlCommand cmd = new SqlCommand("select * from UploadLogo", cn); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { if (dr.GetString(0) != "") { image1.ImageUrl = dr.GetString(0); cn.Close(); dr.Close(); } } if (!IsPostBack) { // BindGridWithFilter(); } string ctrlname = Page.Request.Params.Get("__EVENTTARGET"); string ctrlname1 = Page.Request.Params.Get("__eventargument"); if (ctrlname != null) { string controlname = ctrlname;//.Split('$')[ctrlname.Split('$').Length - 1].ToString(); if (!controlname.Contains("imgView") && !controlname.Contains("imgDelete") && !controlname.Contains("imglock256") && !controlname.Contains("CheckBox1")) { if (controlname.ToUpper().Contains("gvItemTable".ToUpper())) { if (ctrlname1 != null) { if (ctrlname1.Contains("RowClick")) { } else if (ctrlname1.ToUpper().Contains("FIRECOMMAND") || ctrlname1 == "") { BindGridWithFilter(); } else { } } } } } else { BindGridWithFilter(); } } catch (Exception ex) { logger.Info(ex.Message); } }
public static void Info(object message, Exception exception) { Log.Info(message, exception); }
/// <summary> /// Specifies the custom attribute by converting this to a string and passing to GetCustomAttribute() /// </summary> // public enum CustomAttribute { D3DDEVICE, D3DZBUFFER, D3DBACKBUFFER } public void CreateD3DResources() { // access device via driver Device device = driver.Device; if (isSwapChain && device == null) { throw new Exception("Secondary window has not been given the device from the primary!"); } DeviceType devType = DeviceType.Hardware; presentParams = new PresentParameters(); presentParams.Windowed = !isFullScreen; presentParams.SwapEffect = SwapEffect.Discard; // triple buffer if VSync is on presentParams.BackBufferCount = isVSync ? 2 : 1; presentParams.EnableAutoDepthStencil = isDepthBuffered; presentParams.DeviceWindow = windowHandle; presentParams.BackBufferWidth = width; presentParams.BackBufferHeight = height; presentParams.FullScreenRefreshRateInHz = isFullScreen ? displayFrequency : 0; if (isVSync) { presentParams.PresentationInterval = PresentInterval.One; } else { // NB not using vsync in windowed mode in D3D9 can cause jerking at low // frame rates no matter what buffering modes are used (odd - perhaps a // timer issue in D3D9 since GL doesn't suffer from this) // low is < 200fps in this context if (!isFullScreen) { log.Debug("Disabling VSync in windowed mode can cause timing issues at lower " + "frame rates, turn VSync on if you observe this problem."); } presentParams.PresentationInterval = PresentInterval.Immediate; } presentParams.BackBufferFormat = Format.R5G6B5; if (colorDepth > 16) { presentParams.BackBufferFormat = Format.X8R8G8B8; } if (colorDepth > 16) { // Try to create a 32-bit depth, 8-bit stencil if (!D3D.Manager.CheckDeviceFormat(driver.AdapterNumber, devType, presentParams.BackBufferFormat, Usage.DepthStencil, ResourceType.Surface, DepthFormat.D24S8)) { // Bugger, no 8-bit hardware stencil, just try 32-bit zbuffer if (!D3D.Manager.CheckDeviceFormat(driver.AdapterNumber, devType, presentParams.BackBufferFormat, Usage.DepthStencil, ResourceType.Surface, DepthFormat.D32)) { // Jeez, what a naff card. Fall back on 16-bit depth buffering presentParams.AutoDepthStencilFormat = DepthFormat.D16; } else { presentParams.AutoDepthStencilFormat = DepthFormat.D32; } } else { // Woohoo! if (D3D.Manager.CheckDepthStencilMatch(driver.AdapterNumber, devType, presentParams.BackBufferFormat, presentParams.BackBufferFormat, DepthFormat.D24S8)) { presentParams.AutoDepthStencilFormat = DepthFormat.D24S8; } else { presentParams.AutoDepthStencilFormat = DepthFormat.D24X8; } } } else { // 16-bit depth, software stencil presentParams.AutoDepthStencilFormat = DepthFormat.D16; } presentParams.MultiSample = fsaaType; presentParams.MultiSampleQuality = fsaaQuality; if (isSwapChain) { swapChain = new SwapChain(device, presentParams); if (swapChain == null) { // Try a second time, may fail the first time due to back buffer count, // which will be corrected by the runtime swapChain = new SwapChain(device, presentParams); } // Store references to buffers for convenience renderSurface = swapChain.GetBackBuffer(0, BackBufferType.Mono); // Additional swap chains need their own depth buffer // to support resizing them if (isDepthBuffered) { renderZBuffer = device.CreateDepthStencilSurface(width, height, presentParams.AutoDepthStencilFormat, presentParams.MultiSample, presentParams.MultiSampleQuality, false); } else { renderZBuffer = null; } // Ogre releases the mpRenderSurface here (but not the mpRenderZBuffer) // release immediately so we don't hog them // mpRenderSurface->Release(); // We'll need the depth buffer for rendering the swap chain // //mpRenderZBuffer->Release(); } else { if (device == null) { #if !USE_D3D_EVENTS // Turn off default event handlers, since Managed DirectX seems confused. Device.IsUsingEventHandlers = false; #endif // We haven't created the device yet, this must be the first time // Do we want to preserve the FPU mode? Might be useful for scientific apps CreateFlags extraFlags = 0; if (multiThreaded) { extraFlags |= CreateFlags.MultiThreaded; } // TODO: query and preserve the fpu mode // Set default settings (use the one Ogre discovered as a default) int adapterToUse = driver.AdapterNumber; if (useNVPerfHUD) { // Look for 'NVIDIA NVPerfHUD' adapter // If it is present, override default settings foreach (AdapterInformation identifier in D3D.Manager.Adapters) { log.Info("Device found: " + identifier.Information.Description); if (identifier.Information.Description.Contains("PerfHUD")) { log.Info("Attempting to use PerfHUD"); adapterToUse = identifier.Adapter; devType = DeviceType.Reference; break; } } } try { device = new D3D.Device(adapterToUse, devType, windowHandle, CreateFlags.HardwareVertexProcessing | extraFlags, presentParams); } catch (Exception) { log.Info("First device creation failed"); try { // Try a second time, may fail the first time due to back buffer count, // which will be corrected down to 1 by the runtime device = new D3D.Device(adapterToUse, devType, windowHandle, CreateFlags.HardwareVertexProcessing | extraFlags, presentParams); } catch (Exception) { try { // Looks like we can't use HardwareVertexProcessing, so try Mixed device = new D3D.Device(adapterToUse, devType, windowHandle, CreateFlags.MixedVertexProcessing | extraFlags, presentParams); } catch (Exception) { // Ok, one last try. Try software. If this fails, just throw up. device = new D3D.Device(adapterToUse, devType, windowHandle, CreateFlags.SoftwareVertexProcessing | extraFlags, presentParams); } } } // TODO: For a full screen app, I'm supposed to do this to prevent alt-tab // from messing things up. //device.DeviceResizing += new // System.ComponentModel.CancelEventHandler(this.CancelResize); } log.InfoFormat("Device constructed with presentation parameters: {0}", presentParams.ToString()); // update device in driver driver.Device = device; // Store references to buffers for convenience renderSurface = device.GetRenderTarget(0); renderZBuffer = device.DepthStencilSurface; // Ogre releases these here // release immediately so we don't hog them // mpRenderSurface->Release(); // mpRenderZBuffer->Release(); } }
protected unsafe void SplitGeometry(VertexData vd, IndexData id, SubMeshLodGeometryLink targetGeomLink) { log.Info("StaticGeometry.SplitGeometry called"); // Firstly we need to scan to see how many vertices are being used // and while we're at it, build the remap we can use later bool use32bitIndexes = id.indexBuffer.Type == IndexType.Size32; Dictionary <int, int> indexRemap = new Dictionary <int, int>(); IntPtr src = id.indexBuffer.Lock(BufferLocking.ReadOnly); indexRemap.Clear(); if (use32bitIndexes) { int *p32 = (int *)src.ToPointer(); for (int i = 0; i < id.indexCount; ++i) { indexRemap[*p32++] = indexRemap.Count; } } else { short *p16 = (short *)src.ToPointer(); for (int i = 0; i < id.indexCount; ++i) { indexRemap[*p16++] = indexRemap.Count; } } id.indexBuffer.Unlock(); if (indexRemap.Count == vd.vertexCount) { // ha, complete usage after all targetGeomLink.vertexData = vd; targetGeomLink.indexData = id; return; } // Create the new vertex data records targetGeomLink.vertexData = vd.Clone(false); // Convenience VertexData newvd = targetGeomLink.vertexData; //IndexData newid = targetGeomLink.IndexData; // Update the vertex count newvd.vertexCount = indexRemap.Count; int numvbufs = vd.vertexBufferBinding.BindingCount; // Copy buffers from old to new for (ushort b = 0; b < numvbufs; ++b) { // Lock old buffer HardwareVertexBuffer oldBuf = vd.vertexBufferBinding.GetBuffer(b); // Create new buffer HardwareVertexBuffer newBuf = HardwareBufferManager.Instance.CreateVertexBuffer(oldBuf.VertexSize, indexRemap.Count, BufferUsage.Static); // rebind newvd.vertexBufferBinding.SetBinding(b, newBuf); // Copy all the elements of the buffer across, by iterating over // the IndexRemap which describes how to move the old vertices // to the new ones. By nature of the map the remap is in order of // indexes in the old buffer, but note that we're not guaranteed to // address every vertex (which is kinda why we're here) IntPtr vdSrc = oldBuf.Lock(BufferLocking.ReadOnly); byte * pSrcBase = (byte *)vdSrc.ToPointer(); IntPtr vdDest = newBuf.Lock(BufferLocking.Discard); byte * pDstBase = (byte *)vdDest.ToPointer(); int vertexSize = oldBuf.VertexSize; // Buffers should be the same size Debug.Assert(vertexSize == newBuf.VertexSize); foreach (KeyValuePair <int, int> pair in indexRemap) { Debug.Assert(pair.Key < oldBuf.VertexCount); Debug.Assert(pair.Value < newBuf.VertexCount); byte *pSrc = pSrcBase + pair.Key * vertexSize; byte *pDst = pDstBase + pair.Value * vertexSize; for (int i = 0; i < vertexSize; i++) { *pDst++ = *pSrc++; } } // unlock oldBuf.Unlock(); newBuf.Unlock(); } // Now create a new index buffer HardwareIndexBuffer ibuf = HardwareBufferManager.Instance.CreateIndexBuffer(id.indexBuffer.Type, id.indexCount, BufferUsage.Static); IntPtr idSrc = id.indexBuffer.Lock(BufferLocking.ReadOnly); IntPtr idDest = ibuf.Lock(BufferLocking.Discard); if (use32bitIndexes) { int *pSrc32 = (int *)idSrc.ToPointer(); int *pDst32 = (int *)idDest.ToPointer(); for (int i = 0; i < id.indexCount; ++i) { *pDst32++ = (int)indexRemap[*pSrc32++]; } } else { ushort *pSrc16 = (ushort *)idSrc.ToPointer(); ushort *pDst16 = (ushort *)idDest.ToPointer(); for (int i = 0; i < id.indexCount; ++i) { *pDst16++ = (ushort)indexRemap[*pSrc16++]; } } id.indexBuffer.Unlock(); ibuf.Unlock(); targetGeomLink.indexData = new IndexData(); targetGeomLink.indexData.indexStart = 0; targetGeomLink.indexData.indexCount = id.indexCount; targetGeomLink.indexData.indexBuffer = ibuf; // Store optimised geometry for deallocation later OptimisedSubMeshGeometry optGeom = new OptimisedSubMeshGeometry(); optGeom.indexData = targetGeomLink.indexData; optGeom.vertexData = targetGeomLink.vertexData; optimisedSubMeshGeometryList.Add(optGeom); }
/// <summary> /// Método para migrar los servicios diarios /// </summary> /// <param name="IntentosRestantes"></param> /// <returns></returns> static bool MigrarServiciosDiario(int IntentosRestantes, bool vezInicial, int implementacion) { // CODIGO MODIFICADO PARA QUE SE ACTUALICE CADA 10 minutos //DsServiciosTransporteMigracion ds = (DsServiciosTransporteMigracion)pp.ServiciosPorDia( System.DateTime.Today.ToString("yyyyMMdd"),"777","sispack", "sisenco"); //DataSet ds = pp.ServiciosPorDia( System.DateTime.Today.ToString("yyyyMMdd"),"777","sispack", "sisenco"); //20050824 --fecha: entrega 9 //SISPACKSERVICE.WSenco ws = new SISPACKSERVICE.WSenco(); SispackWS.WSenco ws = new SispackWS.WSenco(); string dirWS = System.Configuration.ConfigurationSettings.AppSettings["dirWS"]; ws.Url = dirWS; string sPath = System.Configuration.ConfigurationSettings.AppSettings["FilePath"] == null ? "" : System.Configuration.ConfigurationSettings.AppSettings["FilePath"]; string sConnectionString = ""; //Recuperar los parametros de invocacion de WS string sAgenciaWS = System.Configuration.ConfigurationSettings.AppSettings["AgenciaWS"] == null ? "" : System.Configuration.ConfigurationSettings.AppSettings["AgenciaWS"]; string sUsuarioWS = System.Configuration.ConfigurationSettings.AppSettings["UsuarioWS"] == null ? "" : System.Configuration.ConfigurationSettings.AppSettings["UsuarioWS"]; string sPasswordWS = System.Configuration.ConfigurationSettings.AppSettings["PasswordWS"] == null ? "" : System.Configuration.ConfigurationSettings.AppSettings["PasswordWS"]; string sEmpresas = ""; if (implementacion == (int)SisPack.Implementaciones.Andesmar) { sConnectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"] == null ? "" : System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]; sEmpresas = System.Configuration.ConfigurationSettings.AppSettings["EmpresasAndesmar"] == null ? "" : System.Configuration.ConfigurationSettings.AppSettings["EmpresasAndesmar"]; } else if (implementacion == (int)SisPack.Implementaciones.ElRapido) { sConnectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionStringERI"] == null ? "" : System.Configuration.ConfigurationSettings.AppSettings["ConnectionStringERI"]; sEmpresas = System.Configuration.ConfigurationSettings.AppSettings["EmpresasERI"] == null ? "" : System.Configuration.ConfigurationSettings.AppSettings["EmpresasERI"]; } //DateTime fch = new DateTime(2005,08,30); string fecha = System.DateTime.Today.ToString("yyyyMMdd"); //string fecha1 = fch.AddDays(2).ToString("yyyyMMdd"); //string fecha1 = System.DateTime.Today.AddDays(1).ToString("yyyyMMdd"); // creo una coleccion con todas las empresas ArrayList empresas = new ArrayList(); string[] emp = sEmpresas.Split(','); for (int i = 0; i < emp.Length; i++) { empresas.Add(emp[i]); } try { //*************************************// // MIGRACION DE UNIDADES DE TRANSPORTE // //*************************************// if (vezInicial) { // inicio la transaccion SqlTransaction transaccion = null; SqlConnection conexion = new SqlConnection(); conexion.ConnectionString = sConnectionString; try { conexion.Open(); transaccion = conexion.BeginTransaction(); /*empresas.Add("AND"); * empresas.Add("ATM"); * empresas.Add("PTB"); * empresas.Add("PTA");*/ // Eliminacion masiva IUnidadTransporte unidadTransporte = UnidadTransporteFactory.GetUnidadTransporte(); unidadTransporte.EliminarMasivo(transaccion); IChofer chofer = ChoferFactory.GetChofer(); chofer.EliminarMasivo(transaccion); ILineaTransporte lineaTransporte = LineaTransporteFactory.GetLineaTransporte(); lineaTransporte.EliminarMasivo(transaccion); Logger.Info("Iniciando migración de Unidades de Transporte " + ((SisPack.Implementaciones)implementacion).ToString()); Logger.Info("Empresas a migrar: " + sEmpresas); ws.Proxy = WebRequest.DefaultWebProxy; ws.Credentials = new NetworkCredential("sfernandez", "Omnitronic37", "omnitronic"); ws.Proxy.Credentials = new NetworkCredential("sfernandez", "Omnitronic37", "omnitronic"); DataSet dsUT = new DataSet(); DataSet dsChoferes = new DataSet(); DataSet dsLineas = new DataSet(); if ((sAgenciaWS != "") && (sUsuarioWS != "") && (sPasswordWS != "")) { foreach (string empresa in empresas) { // migro las unidades de transporte dsUT = ws.UnidadesMostrar(empresa, sAgenciaWS, sUsuarioWS, sPasswordWS); string sPath1 = sPath; sPath1 += "//UnidadesMostrar_" + empresa + "_" + System.DateTime.Today.ToString("yyyyMMdd") + ".xml"; dsUT.WriteXml(sPath1); CargaUnidadTransporte(dsUT.Tables[0], empresa, transaccion); // migro los choferes dsChoferes = ws.ConductoresMostrar(empresa, sAgenciaWS, sUsuarioWS, sPasswordWS); sPath1 = sPath; sPath1 += "//ConductoresMostrar_" + empresa + "_" + System.DateTime.Today.ToString("yyyyMMdd") + ".xml"; dsChoferes.WriteXml(sPath1); CargaChoferes(dsChoferes.Tables[0], empresa, transaccion); // migro las lineas de transporte dsLineas = ws.LineasMostrar(empresa, sAgenciaWS, sUsuarioWS, sPasswordWS); sPath1 = sPath; sPath1 += "//LineasMostrar_" + empresa + "_" + System.DateTime.Today.ToString("yyyyMMdd") + ".xml"; dsLineas.WriteXml(sPath1); CargaLineasTransporte(dsLineas.Tables[0], empresa, transaccion); } } transaccion.Commit(); Logger.Info("Fin migración de Unidades de Transporte " + ((SisPack.Implementaciones)implementacion).ToString()); } catch (Exception ex) { transaccion.Rollback(); Logger.Error("Error el migrar unidades de transporte - " + ((SisPack.Implementaciones)implementacion).ToString() + " - " + ex); } //***********************// // MIGRACION DE AGENCIAS // //***********************// try { if ((sAgenciaWS != "") && (sUsuarioWS != "") && (sPasswordWS != "")) { //DataSet dsAgencia = ws.AgenciasGrilla(sAgenciaWS, sUsuarioWS, sPasswordWS); DataSet dsAgencia = ws.ObtenerParadasHomologadas(); string sPath1 = sPath; sPath1 += "//AgenciasGrilla_" + sAgenciaWS + "_" + System.DateTime.Today.ToString("yyyyMMdd") + ".xml"; dsAgencia.WriteXml(sPath1); Logger.Info("Iniciando migración de Agencias Paradas"); string errores = CargaAgenciasGrilla(dsAgencia.Tables[0]); if (errores != "") { // guardo en el log las agencias que no se pudieron migrar, porque no // vienen todos los datos necesarios Logger.Error(errores); } Logger.Info("Fin migración de Agencias Paradas " + ((SisPack.Implementaciones)implementacion).ToString()); } } catch (Exception ex) { Logger.Error("Error el migrar agencias paradas - " + ((SisPack.Implementaciones)implementacion).ToString() + " - " + ex); } } //************************// // MIGRACION DE SERVICIOS // //************************// //DataSet ds = ws.ServiciosPorDia(fecha1,"777","sispack", "sisenco"); Logger.Info("Iniciando migración de Servicios"); //DateTime fechaTmp = System.DateTime.Today; //Utiles.Fechas.FormatFechaDDMMYYYY(fechaActual); IServicioTransporte oServTransp = ServicioTransporteFactory.GetServicioTransporte(); //for (int ie=0; ie<empresas.Count; ie++) //{ //string a = empresas[ie].ToString(); for (int ie = 0; ie < empresas.Count; ie++) { DateTime fechaTmp = System.DateTime.Today; //Utiles.Fechas.FormatFechaDDMMYYYY(fechaActual); //string a = empresas[ie].ToString(); Logger.Info("Empresa= " + empresas[ie].ToString()); for (int dia = 0; dia <= 6; dia++) { if (dia > 0) { fechaTmp = fechaTmp.AddDays(1); } fecha = fechaTmp.ToString("yyyyMMdd"); DataSet ds = new DataSet(); if ((sAgenciaWS != "") && (sUsuarioWS != "") && (sPasswordWS != "")) { ds = ws.ServiciosPorDiaEmp(empresas[ie].ToString(), fecha, sAgenciaWS, sUsuarioWS, sPasswordWS); //ds = ws.ServiciosPorDia(fecha, sAgenciaWS, sUsuarioWS, sPasswordWS); } if (ds.Tables[0].Rows.Count == 0) { //return false; // si no devolvio filas, que termine el metodo continue; } /*DataSet ds = new DataSet(); * if((sAgenciaWS != "") && (sUsuarioWS != "") && (sPasswordWS != "")) * { * ds = ws.ServiciosPorDia(fecha, sAgenciaWS, sUsuarioWS, sPasswordWS); * } * if(ds.Tables[0].Rows.Count == 0) * return false; // si no devolvio filas, que termine el metodo*/ //En el dataset se agrega la columna donde se va seteando el dato de si el servicio se ha guardado ds.Tables[0].Columns.Add("Guardado", typeof(bool), "0"); //string sPath1 = sPath + "//ServiciosPorDia_"+System.DateTime.Today.ToString("yyyyMMdd")+".xml"; //Sólo si hay una ruta donde escribir el xml, tratar de hacerlo if (sPath != "") { string sPath1 = sPath + "//ServiciosPorDia_" + System.DateTime.Today.ToString("yyyyMMdd") + ".xml"; ds.WriteXml(sPath1); } //IServicioTransporte oServTransp = ServicioTransporteFactory.GetServicioTransporte(); DsServiciosTransporteMigracion dsServ = oServTransp.MigrarServiciosPorDia(ds.Tables[0], 1, vezInicial, dia, empresas[ie].ToString());//Siempre se trata de la Unidad de negocios de Andesmar if (dsServ.Datos.Rows.Count > 0) { DataSet dsRecorrido = new DataSet(); IServicioTransporte oServNuevo = ServicioTransporteFactory.GetServicioTransporte(); //Si tiene al menos una fila, se debe migrar para cada IDserv el que recupera el recorrido del servicio foreach (DsServiciosTransporteMigracion.DatosRow dr in dsServ.Datos.Rows) { int nroIntentos = System.Configuration.ConfigurationSettings.AppSettings["IntentosMigracionDiaria"] == null ? 4 : Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["IntentosMigracionDiaria"]); if (nroIntentos > 0) { dsRecorrido = XMLServiciosRecorrido(dr.ServicioId, nroIntentos); } else { dsRecorrido = XMLServiciosRecorrido(dr.ServicioId, 1); } if (dsRecorrido != null && dsRecorrido.Tables.Count > 0 && dsRecorrido.Tables[0] != null) { oServNuevo.MigrarServiciosRecorrido(dr, dsRecorrido.Tables[0], 1, vezInicial); } } } } } //} //descomentar esta linea 05/11/2007 oServTransp.SincronizarTablas(); Logger.Info("Fin migración de Servicios " + ((SisPack.Implementaciones)implementacion).ToString()); return(true); } catch (System.Net.WebException)//Este es el tipo de error cuando la conexion esta cerrada. { //throw ex.Message; int intFaltantes = IntentosRestantes - 1; if (intFaltantes > 0) { Logger.Info("Intentando migrar nuevamente. Intentos restantes: " + intFaltantes.ToString()); return(MigrarServiciosDiario(intFaltantes, vezInicial, implementacion)); } else { return(false); } } catch (Exception ex) { Logger.Error("Error!!! " + ex); } return(true); //string sPath1 = sPath + "//ServiciosPorDia_"+System.DateTime.Today.ToString("yyyyMMdd")+".xml"; //ds.WriteXml(sPath1); // CODIGO ORIGINAL NATI /*SisPackWS.WSenco ws = new ServMigracionAutotransportes.SisPackWS.WSenco(); * string sPath = System.Configuration.ConfigurationSettings.AppSettings["FilePath"] == null ? "" : System.Configuration.ConfigurationSettings.AppSettings["FilePath"]; * * //Recuperar los parametros de invocacion de WS * string sAgenciaWS = System.Configuration.ConfigurationSettings.AppSettings["AgenciaWS"] == null ? "" : System.Configuration.ConfigurationSettings.AppSettings["AgenciaWS"]; * string sUsuarioWS = System.Configuration.ConfigurationSettings.AppSettings["UsuarioWS"] == null ? "" : System.Configuration.ConfigurationSettings.AppSettings["UsuarioWS"]; * string sPasswordWS = System.Configuration.ConfigurationSettings.AppSettings["PasswordWS"] == null ? "" : System.Configuration.ConfigurationSettings.AppSettings["PasswordWS"]; * * //DateTime fch = new DateTime(2005,08,30); * string fecha = System.DateTime.Today.ToString("yyyyMMdd"); * //string fecha1 = fch.AddDays(2).ToString("yyyyMMdd"); * //string fecha1 = System.DateTime.Today.AddDays(1).ToString("yyyyMMdd"); * * try * { * //DataSet ds = ws.ServiciosPorDia(fecha1,"777","sispack", "sisenco"); * DataSet ds = new DataSet(); * if((sAgenciaWS != "") && (sUsuarioWS != "") && (sPasswordWS != "")) * { * ds = ws.ServiciosPorDia(fecha, sAgenciaWS, sUsuarioWS, sPasswordWS); * } * if(ds.Tables[0].Rows.Count == 0) * return false; // si no devolvio filas, que termine el metodo * * * //En el dataset se agrega la columna donde se va seteando el dato de si el servicio se ha guardado * ds.Tables[0].Columns.Add("Guardado", typeof(bool),"0"); * * //string sPath1 = sPath + "//ServiciosPorDia_"+System.DateTime.Today.ToString("yyyyMMdd")+".xml"; * * //Sólo si hay una ruta donde escribir el xml, tratar de hacerlo * if(sPath != "") * { * string sPath1 = sPath + "//ServiciosPorDia_"+System.DateTime.Today.ToString("yyyyMMdd")+".xml"; * ds.WriteXml(sPath1); * } * * IServicioTransporte oServTransp = ServicioTransporteFactory.GetServicioTransporte(); * DsServiciosTransporteMigracion dsServ = oServTransp.MigrarServiciosPorDia(ds.Tables[0], 1, vezInicial);//Siempre se trata de la Unidad de negocios de Andesmar * if(dsServ.Datos.Rows.Count > 0) * { * DataSet dsRecorrido = new DataSet(); * IServicioTransporte oServNuevo = ServicioTransporteFactory.GetServicioTransporte(); * //Si tiene al menos una fila, se debe migrar para cada IDserv el que recupera el recorrido del servicio * foreach(DsServiciosTransporteMigracion.DatosRow dr in dsServ.Datos.Rows) * { * int nroIntentos = System.Configuration.ConfigurationSettings.AppSettings["IntentosMigracionDiaria"] == null ? 4: Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["IntentosMigracionDiaria"]); * if(nroIntentos > 0) * dsRecorrido = XMLServiciosRecorrido(dr.ServicioId, nroIntentos); * else * dsRecorrido = XMLServiciosRecorrido(dr.ServicioId, 1); * * if(dsRecorrido != null) * { * oServNuevo.MigrarServiciosRecorrido(dr,dsRecorrido.Tables[0],1,vezInicial); * } * } * * } * return true; * } * catch(System.Net.WebException)//Este es el tipo de error cuando la conexion esta cerrada. * { * //throw ex.Message; * int intFaltantes = IntentosRestantes - 1; * if(intFaltantes > 0 ) * { * return MigrarServiciosDiario(intFaltantes, vezInicial); * } * else * return false; * } * * //string sPath1 = sPath + "//ServiciosPorDia_"+System.DateTime.Today.ToString("yyyyMMdd")+".xml"; * //ds.WriteXml(sPath1); */ }
/// <summary> /// 导出基本信息 /// </summary> /// <param name="message">消息文本</param> public static void Info(string message) { logInfo.Info(message); }
public void i(object msg) { logger.Info(msg); }
/// <summary> /// Append asynchronous /// </summary> /// <param name="loggingEvent">The logging event.</param> public static void AsyncAppend(object loggingEvent) { LoggingEvent Event = (LoggingEvent)loggingEvent; try { if (loggingEvent != null) { //scrivo il messaggio nella coda configurata System.Messaging.MessageQueue mq = new System.Messaging.MessageQueue(); System.Messaging.Message mqMessage = new Message(); //System.Messaging.Message mqMessage = new System.Messaging.Message(((BaseLogInfo)Event.MessageObject).Serialize().InnerXml); { mqMessage.AttachSenderId = false; mqMessage.Recoverable = true; mqMessage.Label = appName + "-" + Event.Level.DisplayName; mqMessage.TimeToReachQueue = System.Messaging.Message.InfiniteTimeout; mqMessage.TimeToBeReceived = System.Messaging.Message.InfiniteTimeout; mqMessage.Body = ((BaseLogInfo)Event.MessageObject).Serialize().DocumentElement; } try { mq.Path = "FormatName:" + m_queueName; mq.Formatter = new XmlMessageFormatter(); mq.Send(mqMessage, MessageQueueTransactionType.None); } catch (Exception) { if ((backupQueueName != null && !backupQueueName.Equals(""))) { try { mq.Path = "FormatName:" + backupQueueName; mq.Send(mqMessage, MessageQueueTransactionType.None); } catch (Exception e1) { ErrorLog error = new ErrorLog(); error.freeTextDetails = e1.Message; error.logCode = "ERR003"; error.loggingAppCode = "LOG"; error.loggingTime = System.DateTime.Now; error.uniqueLogID = System.DateTime.Now.Ticks.ToString(); log.Error(error); throw e1; } } } } } catch (Exception e2) { //log di 2° backup// string error = e2.Message; log4net.ILog log = log4net.LogManager.GetLogger(typeof(Com.Delta.Logging.MsmqAppender)); log.Info(Event.MessageObject); //notifico il sistema del problema if (notify) { if (System.Diagnostics.EventLog.SourceExists(eventLog)) { System.Diagnostics.EventLog myEventLog = null; try { string msg = "Errore durante la scrittura nella coda:" + m_queueName + "\\r\\n Dettaglio:\\r\\n+" + Event.MessageObject.ToString() + "\\r\\n Errore:\\r\\n" + e2.Message + "\\r\\n\\r\\n Dettaglio Errore:\\r\\n" + e2.StackTrace; myEventLog = new System.Diagnostics.EventLog(); myEventLog.Source = eventLog; myEventLog.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error); myEventLog.Close(); } finally { if (myEventLog != null) { myEventLog.Dispose(); } } } } } }