示例#1
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            Log = log4net.LogManager.GetLogger(typeof(Program));
            Root = ConfigurationManager.AppSettings["serviceRoot"];
            Apploader = ConfigurationManager.AppSettings["apploader"];
            Apps = new Dictionary<string, Process>();

            Log.Info("==== AppServer && Apploader ====");
            Log.InfoFormat("从目录{0}下开始启动各应用", Root);

            //TODO:支持指定pid,可通过读取对应目录下的xxxconfig来完成
            Directory.GetDirectories(Root)
                .Where(o => Filter(o)).ToList().ForEach(o => Start(o));

            //激活AppAgent
            Log.Info("启用AppAgent");
            new DefaultAgent(new Log4NetLogger(Log)
                , ConfigurationManager.AppSettings["appAgent_master"]
                , ConfigurationManager.AppSettings["appAgent_name"]
                , ConfigurationManager.AppSettings["appAgent_description"]
                , new CommandHandle())
                .Run();

            Log.Info("==== 启动完成 ====\n\n");

            RenderOutput();

            System.Console.ReadKey();
        }
示例#2
0
      protected override void OnStart(string[] args)
      {
         string baseDir = AppDomain.CurrentDomain.BaseDirectory;
         log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(baseDir + "log4net.xml"));
         log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
         try
         {
            // Pick one
            //RemotingConfiguration.CustomErrorsEnabled(false);
            RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;
            //RemotingConfiguration.Configure(baseDir + "RrdbFileService.exe.config");

            log.Info("RrdDb file server started");

            var nameValueCollection = (NameValueCollection)ConfigurationManager.GetSection("rrdbfileserver");
            log.InfoFormat("Database file base path:{0}", nameValueCollection["databasepath"]);
            string port = nameValueCollection["port"];
            int portNumber = int.Parse(port);

            channel = new TcpChannel(portNumber);
            ChannelServices.RegisterChannel(channel, false);
            log.InfoFormat("Server object registerd on port {0}", portNumber);
            RemotingConfiguration.RegisterWellKnownServiceType(
               typeof(RrdDbAdapter),
               "GetRrdDbAdapter",
               WellKnownObjectMode.Singleton);
            log.Info("Service up and running");
         }
         catch (Exception ex)
         {
            log.Error(ex);
            throw;
         }
      }
示例#3
0
        public AudioManager(bool hardware = true)
        {
            _log = Logging.LogManager.GetLogger(this);
            _log.Info("Initializing AudioManager...");
            _log.Info("Creating FMOD system...");
            uint version = 0;

            RESULT result = Factory.System_Create(ref _system);
            ErrCheck(result);

            _log.Debug("Checking FMOD version...");
            result = _system.getVersion(ref version);
            ErrCheck(result);

            if (version < VERSION.number)
            {
                var msg = string.Format("Error! You are using an old version of FMOD: {0}. This program requires: {1}.",
                                        version.ToString("X"), VERSION.number.ToString("X"));
                _log.Fatal(msg);
                throw new FMODException(msg);
            }

            result = _system.init(MaxChannels, INITFLAGS.NORMAL, (IntPtr) null);
            ErrCheck(result);

            _soundManager = new SoundManager(_system, hardware);
            _songManager = new SongManager(_system, hardware);

            _log.Info("AudioManager initialized!");
        }
示例#4
0
        public TextManager(Map map)
        {
            _log = Logging.LogManager.GetLogger(this);
            _log.Info("TextManager is loading map text entries...");
            _texts = new List<Text>();
            _activeText = null;

            if (!map.HasLayer("text"))
            {
                _log.Info("No text layer detected on map, aborting...");
                return;
            }

            foreach (var obj in map.FindObjects((l, o) => l.Name == "text"))
            {
                string title = obj.Properties.ContainsKey("title") ? obj.Properties["title"] : "<No Title>";

                string subtitle = obj.Properties.ContainsKey("subtitle") ? obj.Properties["subtitle"] : null;

                _log.DebugFormat("Adding new text {0} of type {1}", obj.Name, obj.Type);
                _texts.Add(new Text(obj.Bounds, obj.Name, obj.Type, title, subtitle));
            }

            _log.Debug("TextManager initialized!");
        }
示例#5
0
        static void Main(string[] args)
        {
            if (string.IsNullOrEmpty(Thread.CurrentThread.Name))
                Thread.CurrentThread.Name = "Main";

            #if WINDOWS && DEBUG
            if (!System.Diagnostics.Debugger.IsAttached)
            {
                AllocConsole();
                var stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
                var safeFileHandle = new SafeFileHandle(stdHandle, true);
                var fileStream = new FileStream(safeFileHandle, FileAccess.Write);
                var encoding = Encoding.GetEncoding(CODE_PAGE);
                var stdOut = new StreamWriter(fileStream, encoding) { AutoFlush = true };
                Console.SetOut(stdOut);
            }
            #endif

            _log = LogManager.GetLogger(typeof(Program));

            _log.Info("### !!! APPLICATION LOAD !!! ###");

            _log.Info("Deleting old log files (>7 days)...");

            // Delete log files older than 7 days
            if (Directory.Exists("logs"))
            {
                var now = DateTime.Now;
                var max = new TimeSpan(7, 0, 0, 0); // 7 days
                foreach (var file in from file in Directory.GetFiles("logs")
                                        let modTime = File.GetLastAccessTime(file)
                                        let age = now.Subtract(modTime)
                                        where age > max
                                        select file)
                {
                    try
                    {
                        File.Delete(file);
                        _log.Info("Deleted old log file: " + file);
                    }
                    catch (IOException ex)
                    {
                        _log.Warn("Failed to delete log file: " + file + "(" + ex.Message + ")");
                    }
                }
            }

            _log.Info("Old log files deleted!");

            _log.Info("Starting game...");
            using (var game = new MainGame())
                game.Run();

            #if WINDOWS && DEBUG
            _log.Debug("Unloading console...");
            FreeConsole();
            _log.Debug("Console unloaded!");
            #endif
            _log.Info("### !!! APPLICATION EXIT !!! ###");
        }
        /// <summary>
        /// Log写入
        /// </summary>
        /// <param name="logBean"></param>
        public void WriteLog(MsgLevel level, string message)
        {
            switch (level)
            {
            case MsgLevel.Debug:
                basicLog?.Debug(message);
                break;

            case MsgLevel.Info:
                basicLog?.Info(message);
                break;

            case MsgLevel.Warn:
                basicLog?.Warn(message);
                break;

            case MsgLevel.Error:
                errLog?.Error(message);
                break;

            case MsgLevel.Fatal:
                errLog?.Fatal(message);
                break;
            }
        }
示例#7
0
        public void WriteLog(LogEnum name, LogLevel level, string logContent)
        {
            log = log4net.LogManager.GetLogger(name.ToString());
            //log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            switch (level)
            {
                case LogLevel.DEBUG:
                    log.Debug(logContent);
                    break;
                case LogLevel.ERROR:
                    log.Error(logContent);
                    break;
                case LogLevel.FATAL:
                    log.Fatal(logContent);
                    break;
                case LogLevel.INFO:
                    log.Info(logContent);
                    break;
                case LogLevel.WARN:
                    log.Warn(logContent);
                    break;
                default:
                    log.Debug(logContent);
                    break;
            }
        }
 public void Info(string str,
                  [CallerLineNumber] int lineNumber = 0,
                  [CallerMemberName] string caller  = null,
                  [CallerFilePath] string filepath  = null)
 {
     logger?.Info(Bake(str, lineNumber, caller, filepath));
 }
示例#9
0
 protected DriverManager()
 {
     _loadedDrivers = new Dictionary<string, IDriver>();
     _driverDefinition = new Dictionary<string, KaiTrade.Interfaces.IDriverDef>();
     AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
     _wireLog = log4net.LogManager.GetLogger("KaiTradeWireLog");
     _wireLog.Info("DriverManager Created");
 }
示例#10
0
 /// <summary>
 /// Initialize a new <c>SteamFriendList</c>.
 /// </summary>
 internal SteamFriendList()
 {
     _log = LogManager.GetLogger(this);
     _list = new List<SteamFriend>();
     _updateTimer = new Timer(Update, null, 0, 60000);
     SteamManager.OnSteamClose += SteamClose;
     _log.Info("SteamFriendList loaded!");
 }
示例#11
0
 internal SoundManager(FMOD.System system, bool hardware = true)
 {
     _log = Logging.LogManager.GetLogger(this);
     _log.Info("Initializing SoundManager...");
     _system = system;
     _sounds = new List<Sound>();
     _soundMode = hardware ? MODE.HARDWARE : MODE.SOFTWARE;
     _log.DebugFormat("Sound Mode == {0}", _soundMode);
     _log.Debug("SoundManager initialized!");
 }
示例#12
0
 protected ProductManager()
 {
     //m_Products = new Dictionary<string, KaiTrade.Interfaces.IProduct>();
     //m_MnemonicProduct = new Dictionary<string, KaiTrade.Interfaces.IProduct>();
     m_Products = new System.Collections.Hashtable();
     m_MnemonicProduct = new System.Collections.Hashtable();
     m_Name = "KTAProductManager";
     m_Log = log4net.LogManager.GetLogger("Kaitrade");
     m_Log.Info("ProductManager Created");
 }
示例#13
0
 public PacketListener(Protocol protocol)
 {
     _log = LogManager.GetLogger(this);
     _log.Debug("Setting protocol...");
     _protocol = protocol;
     _log.Debug("Creating packet listen thread...");
     _listenThread = new Thread(ReadPackets) {Name = "PacketListen", IsBackground = true};
     _log.Debug("Starting packet listen thread...");
     _running = true;
     _listenThread.Start();
     _log.Info("Packet listen thread started!");
 }
示例#14
0
        internal SongManager(FMOD.System system, bool hardware = true)
        {
            _log = Logging.LogManager.GetLogger(this);
            _log.Info("Initializing SongManager...");
            _system = system;
            _songs = new List<Song>();

            // ReSharper disable BitwiseOperatorOnEnumWihtoutFlags
            if (hardware)
                _soundMode = MODE._2D | MODE.HARDWARE | MODE.CREATESTREAM;
            else
                _soundMode = MODE._2D | MODE.SOFTWARE | MODE.CREATESTREAM;
            // ReSharper restore BitwiseOperatorOnEnumWihtoutFlags

            _log.DebugFormat("Sound Mode == {0}", _soundMode);
            _log.Debug("SongManager initialized!");
        }
示例#15
0
        internal ControlsManager(string file)
        {
            _log = LogManager.GetLogger(this);

            if (File.Exists(file))
            {
                _log.Info("Loading controls from " + file + "...");
                Controls = Serializer.JsonDeserialize<Controls>(file);
                _log.Debug("Controls loaded!");
            }
            else
            {
                Controls = new Controls();
                SetDefaultControls();
                _log.Debug("Saving controls to " + SettingsFile + "...");
                Serializer.JsonSerialize(Controls, SettingsFile);
            }

            CheckControls();
        }
示例#16
0
        /// <summary>
        /// Initializes a new Steam GUI.
        /// </summary>
        public SteamGUI()
        {
            InitializeComponent();
            _log = LogManager.GetLogger(this);
            _log.Info("SteamGUI is initializing...");
            _steamClosed = false;
            sendButton.Enabled = false;
            nameLabel.Text = SteamManager.GetName();
            statusLabel.Text = SteamManager.GetStatus(true);
            friendsLabel.Text = string.Format(FriendFormat, SteamManager.FriendList.GetFriendCount(true),
                                              SteamManager.FriendList.GetFriendCount());

            foreach (var friend in SteamManager.FriendList.GetFriends())
            {
                var item = new ListViewItem(new[] { friend.GetName(), friend.GetStatus(true) }) { Tag = friend.SteamID };
                friendList.Items.Add(item);
            }
            SteamManager.FriendList.OnFriendsUpdate += UpdateData;
            _log.Debug("SteamGUI is registering to OnSteamClose event...");
            SteamManager.OnSteamClose += SteamClose;
            _log.Debug("SteamGUI is registering to OnMinecraftData event...");
            SteamManager.OnMinecraftData += UpdateMinecraftdata;
            _log.Info("SteamGUI loaded!");
        }
示例#17
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            //读取BH客户端地址
            s_bhClientAppDir = Helper.GetBhClientDir();
            if (string.IsNullOrEmpty(s_bhClientAppDir))
                ChangeBhClientAppLocation();
            if (string.IsNullOrEmpty(s_bhClientAppDir))
            {
                MessageBox.Show("未找到有效的ZLBH客户端程序目录");
            }
            else
            {
                List<ClientServerSetting> serverList = Helper.GetAllServerSetting(s_bhClientAppDir);
                using (LoginForm loginForm = LoginForm.New())
                {
                    if (loginForm.ShowDialog() == DialogResult.OK)
                    {
                        s_communicateProxy = loginForm.CommunicateProxy;
                        s_sessionID = loginForm.SessionID;
                        s_currentServer = loginForm.CurrentServer;
                    }
                    else
                    {
                        return;
                    }
                }

                if (s_communicateProxy != null)
                {
                    if (s_bhClientAppDir != AppDomain.CurrentDomain.BaseDirectory)
                    {
                        File.Copy(
                            Path.Combine(s_bhClientAppDir, "ZLSoft.BusinessHome.DynamicServiceProxy.dll"),
                            Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ZLSoft.BusinessHome.DynamicServiceProxy.dll"),
                            true);
                    }
                    Environment.CurrentDirectory = s_bhClientAppDir;

                    //日志组件
                    string logCfgFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "XToolLog.config");
                    log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(logCfgFile));
                    s_log = log4net.LogManager.GetLogger(typeof(Program));
                    ClientEventDispatcher.Log = s_log;
                    CommunicateProxy.Logger = s_log;
                    ClientLogger.logger = s_log;

                    s_log.Info(string.Format("****** 以[{0}]登陆[{1}:{2}] ******",
                        s_communicateProxy.UserName, s_currentServer.HOST, s_currentServer.Port));

                    //远程服务
                    RemoteServiceRegister register = new RemoteServiceRegister();
                    register.RegisterRemoteServices(ServiceRepository.Instance);

                    #region 客户端初始化
                    try
                    {
                        s_isNewVer = File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ZLSoft.BusinessHome.Plugin.DataLayer.Interface.dll"));
                        try
                        {
                            Helper.InitOnStartup(s_isNewVer);
                        }
                        catch (TypeLoadException)
                        {
                            if (s_isNewVer)
                            {
                                Helper.InitOnStartup(false);
                                s_isNewVer = false;
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("客户端初始化发生异常", ex);
                    }
                    #endregion

                    s_mainForm = new MainForm();
                    ClientPluginManager.EventToServer(s_mainForm, true);
                    s_communicateProxy.StartPing();
                    Application.Run(s_mainForm);
                    try
                    {
                        ClientPluginManager.RemovePlugin(s_mainForm);
                    }
                    catch { }
                    finally
                    {
                        s_mainForm.Dispose();
                        s_mainForm = null;
                    }
                    s_log.Info("****** 正常关闭 ******");
                }
            }
        }
示例#18
0
 /// <summary>
 /// Initializes a new instance of Sharpcraft.
 /// </summary>
 public Sharpcraft(User user)
 {
     _log = LogManager.GetLogger(this);
     _settings = new GameSettings(Constants.GameSettings);
     _user = user;
     if (File.Exists(Constants.GameSettings))
     {
         _log.Info("Loading game settings from file...");
         var reader = new StreamReader(Constants.GameSettings);
         _settings = new JsonSerializer().Deserialize<GameSettings>(new JsonTextReader(reader));
         _log.Info("Game settings loaded successfully!");
         reader.Close();
     }
     else
     {
         _settings = new GameSettings(Constants.GameSettings) {Size = new Point(1280, 720)};
     }
     _log.Debug("Initializing graphics device.");
     _graphics = new GraphicsDeviceManager(this);
     if (_settings.Fullscreen)
     {
         _graphics.IsFullScreen = true;
         _settings.Size = new Point(SystemInformation.PrimaryMonitorSize.Width, SystemInformation.PrimaryMonitorSize.Height);
     }
     _graphics.PreferredBackBufferWidth = _settings.Size.X;
     _graphics.PreferredBackBufferHeight = _settings.Size.Y;
     _log.Debug("Setting content directory.");
     Content.RootDirectory = Constants.ContentDirectory;
     _log.Debug("Creating DebugDisplay...");
     Components.Add(new DebugDisplay(this, _graphics));
     #if DEBUG
     _gameMenuOpen = true;
     #endif
 }
示例#19
0
        public static List <AppShortDescription> CollectAppsShortInformationFromCategories(string category)
        {
            List <AppShortDescription> parsedApps_list = new List <AppShortDescription>();


            log.Info("Crawling Category : [ " + category + " ]");

            int numberOfCyclesCompleted = 0;

            while (numberOfCyclesCompleted < Consts.CATEGORY_NUMBER_OF_CYCLES)
            {
                string crawlUrl = String.Format(Consts.CRAWL_URL_CATEGORY, category, "Russia");
                string postData = String.Format(Consts.POST_DATA_CATEGORY, Consts.CATEGORY_NUMBER_OF_APPS_PER_CYCLE * numberOfCyclesCompleted);
                numberOfCyclesCompleted++;
                //Console.WriteLine(postDataTest);


                // HTML Response
                string response = string.Empty;

                // Executing Web Requests
                using (WebRequests server = new WebRequests())
                {
                    // Creating Request Object
                    server.Host = Consts.HOST;

                    //  this is how we actually connect to all this shit
                    //  the only thing left - we need to randomize it and check if 200
                    //WebProxy proxyObject = new WebProxy("http://" + ProxyLoader.ReturnRandomProxy(), true);
                    //server.Proxy = proxyObject;

                    int insertedAppCount = 0;
                    int skippedAppCount  = 0;
                    int errorsCount      = 0;

                    // Executing Request
                    response = server.Post(crawlUrl, postData);

                    // Checking Server Status
                    if (server.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        log.Error("Http Error - Status Code: " + server.StatusCode);

                        errorsCount++;

                        if (errorsCount > Consts.MAX_REQUEST_ERRORS)
                        {
                            log.Info("Crawl Stopped: MAX_REQUEST_ERRORS reached");
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }


                    //var kek1 = parser.ParseAppUrls(response);


                    // Parsing Links out of Html Page
                    foreach (AppShortDescription asd in parser.ParseAppUrls(response))
                    {
                        if (!parsedApps_list.Contains(asd))
                        {
                            parsedApps_list.Add(asd);

                            log.Info("Inserted App: " + asd);

                            ++insertedAppCount;
                        }
                        else
                        {
                            ++skippedAppCount;
                            log.Info("Duplicated App. Skipped: " + asd);
                        }
                    }

exit:
                    log.Info("Inserted App Count: " + insertedAppCount);
                    log.Info("Skipped App Count: " + skippedAppCount);
                    log.Info("Error Count: " + errorsCount + "\n");
                }
            }

            return(parsedApps_list);
        }
示例#20
0
        public string ScheduleNewRequest(EventoDTO even, PrestazioneDTO pres, RichiestaLISDTO esam, List <AnalisiDTO> anals, ref string errorString)
        {
            Stopwatch tw = new Stopwatch();

            tw.Start();

            log.Info(string.Format("Starting ..."));

            string hl7_stato = IBLL.HL7StatesRichiestaLIS.Idle;
            string evenIdStr = null;
            string esamIdStr = null;
            string presIdStr = null;

            EventoDTO         evenInserted  = null;
            PrestazioneDTO    presInserted  = null;
            RichiestaLISDTO   esamInserted  = null;
            List <AnalisiDTO> analsInserted = null;

            if (errorString == null)
            {
                errorString = "";
            }

            try
            {
                if (even == null || esam == null || anals == null || (anals != null && anals.Count == 0))
                {
                    throw new Exception("Error! Request a null or void insertion of EVEN and/or ESAM and/or ANAL.");
                }

                // Validation Even!!!!
                if (!bll.ValidateEven(even, ref errorString))
                {
                    string msg = "Validation Even Failure! Check the error string for figuring out the issue!";
                    log.Info(msg + "\r\n" + errorString);
                    log.Error(msg + "\r\n" + errorString);
                    throw new Exception(msg);
                }

                // Check if Epis exists!!!!
                log.Info(string.Format("Checking EPIS '{0}' exists ...", even.evenepis));
                EpisodioDTO epis = bll.GetEpisodioById(even.evenepis.ToString());
                if (epis == null)
                {
                    string msg = string.Format("EPIS Checking Failure! EPIS '{0}' not Found!", even.evenepis);
                    log.Info(msg);
                    log.Error(msg);
                    throw new Exception(msg);
                }
                epis = null;
                log.Info(string.Format("Checking EPIS '{0}' succeded!", even.evenepis));

                // Create Even
                log.Info(string.Format("EVEN Insertion ..."));
                even.evenidid = null;
                evenInserted  = bll.AddEvento(even);
                if (evenInserted == null)
                {
                    throw new Exception("Error during EVEN writing into the DB.");
                }
                log.Info(string.Format("EVEN Inserted. Got {0} EVENIDID!", evenInserted.evenidid));

                evenIdStr = evenInserted.evenidid.ToString();

                pres.preseven = evenInserted.evenidid;
                log.Info(string.Format("PRES foreign key PRESEVEN updated!"));
                // Validation Pres!!!!
                if (!bll.ValidatePres(pres, ref errorString))
                {
                    string msg = "Validation Pres Failure! Check the error string for figuring out the issue!";
                    log.Info(msg + "\r\n" + errorString);
                    log.Error(msg + "\r\n" + errorString);
                    throw new Exception(msg);
                }

                pres.hl7_stato = hl7_stato;

                // Create Pres
                log.Info(string.Format("PRES Insertion ..."));
                presInserted = bll.AddPrestazione(pres);
                if (presInserted == null)
                {
                    throw new Exception("Error during PRES writing into the DB.");
                }
                log.Info(string.Format("PRES Inserted. Got {0} PRESIDID!", presInserted.presidid));

                presIdStr = presInserted.presidid.ToString();

                esam.esameven = evenInserted.evenidid;
                // Validation Esam!!!!
                if (!bll.ValidateEsam(esam, ref errorString))
                {
                    string msg = "Validation Esam Failure! Check the error string for figuring out the issue!";
                    log.Info(msg + "\r\n" + errorString);
                    log.Error(msg + "\r\n" + errorString);
                    throw new Exception(msg);
                }

                log.Info(string.Format("ESAM foreign key ESAMEVEN updated!"));
                esam.hl7_stato = hl7_stato;

                // Create Esam
                log.Info(string.Format("ESAM Insertion ..."));
                esamInserted = bll.AddRichiestaLIS(esam);
                if (esamInserted == null)
                {
                    throw new Exception("Error during ESAM writing into the DB.");
                }
                log.Info(string.Format("ESAM Inserted. Got {0} ESAMIDID!", esamInserted.esamidid));

                esamIdStr = esamInserted.esamidid.ToString();

                anals.ForEach(p => { p.analesam = int.Parse(esamIdStr); p.hl7_stato = hl7_stato; });

                // Validation Anals!!!!
                if (!bll.ValidateAnals(anals, ref errorString))
                {
                    string msg = "Validation Anals Failure! Check the error string for figuring out the issue!";
                    log.Info(msg + "\r\n" + errorString);
                    log.Error(msg + "\r\n" + errorString);
                    throw new Exception(msg);
                }

                // Create Anals
                log.Info(string.Format("Insertion of {0} ANAL requested. Processing ...", anals.Count));
                analsInserted = bll.AddAnalisis(anals);
                if ((analsInserted == null) || (analsInserted != null && analsInserted.Count != anals.Count))
                {
                    throw new Exception("Error during ANALs writing into the DB.");
                }
                log.Info(string.Format("Inserted {0} ANAL successfully!", analsInserted.Count));

                // Log Total Number Of Records Inserted! 1 for Esam, 1 for PRES and n for ANAL(s)
                log.Info(string.Format("Inserted {0} records successfully!", analsInserted.Count + 1 + 1));
            }
            catch (Exception ex)
            {
                string msg = "An Error occured! Exception detected!";
                log.Info(msg);
                log.Error(msg + "\n" + ex.Message);

                if (errorString == "")
                {
                    errorString = msg + "\r\n" + ex.Message;
                }
                else
                {
                    errorString += "\r\n" + msg + "\r\n" + ex.Message;
                }

                int evenRB  = 0;
                int presRB  = 0;
                int esamRB  = 0;
                int analsRB = 0;

                log.Info(string.Format("Rolling Back of the Insertions due an error occured ..."));
                // Rolling Back
                if (evenIdStr != null)
                {
                    evenRB = bll.DeleteEventoById(evenIdStr);
                    log.Info(string.Format("Rolled Back {0} EVEN record. EVENIDID was {1}!", evenRB, evenIdStr));
                }
                if (presIdStr != null)
                {
                    presRB = bll.DeletePrestazioneById(presIdStr);
                    log.Info(string.Format("Rolled Back {0} PRES record. PRESIDID was {1}!", presRB, presIdStr));
                }
                if (esamIdStr != null)
                {
                    esamRB = bll.DeleteRichiestaLISById(esamIdStr);
                    log.Info(string.Format("Rolled Back {0} ESAM record. ESAMIDID was {1}!", esamRB, esamIdStr));
                    analsRB = bll.DeleteAnalisiByRichiesta(esamIdStr);
                    log.Info(string.Format("Rolled Back {0} ANAL records. ANALESAM was {1}!", analsRB, esamIdStr));
                }

                log.Info(string.Format("Rolled Back {0} records of {1} requested!", evenRB + presRB + esamRB + analsRB, anals.Count + 1 + 1 + 1));
                esamIdStr = null;
            }

            tw.Stop();
            log.Info(string.Format("Completed! Elapsed time {0}", LibString.TimeSpanToTimeHmsms(tw.Elapsed)));

            if (errorString == "")
            {
                errorString = null;
            }

            return(esamIdStr);
        }
示例#21
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
            #if DEBUG
            bool debug = true;
            #else
            bool debug = false;
            #endif
            if (args.Length > 0)
                if (args[0].ToLower() == "debug")
                    debug = true;

            if (string.IsNullOrEmpty(Thread.CurrentThread.Name))
                Thread.CurrentThread.Name = "Main";

            if (debug && !System.Diagnostics.Debugger.IsAttached)
            {
                AllocConsole();
                IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
                var safeFileHandle = new SafeFileHandle(stdHandle, true);
                var fileStream = new FileStream(safeFileHandle, FileAccess.Write);
                var encoding = System.Text.Encoding.GetEncoding(CODE_PAGE);
                var stdOut = new StreamWriter(fileStream, encoding) {AutoFlush = true};
                Console.SetOut(stdOut);
            }

            LogManager.LoadConfig(debug);
            _log = LogManager.GetLogger(typeof (Program));
            _log.Info("!!! APPLICATION LOAD !!!");
            _log.Info("Detecting components...");
            foreach (var file in Directory.GetFiles(Directory.GetCurrentDirectory()))
            {
                string ext = Path.GetExtension(file);
                if (string.IsNullOrEmpty(ext))
                    continue;
                ext = ext.Substring(1);
                if (ext == "dll" || ext == "exe")
                {
                    string version = AssemblyName.GetAssemblyName(file).Version.ToString();
                    string name = Path.GetFileNameWithoutExtension(file);
                    _log.Info(name + " v" + version);
                }
            }

            _log.Info("Components detected!");
            _log.Info("Sharpcraft is loading...");

            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                if (!Directory.Exists(Constants.SettingsDirectory))
                    Directory.CreateDirectory(Constants.SettingsDirectory);

            #if SC_DIRECT
                new Sharpcraft(null).Run();
            #else
                _log.Debug("Starting launcher...");
                _launcher = new Launcher();
                _launcher.Show();
                _context = new ApplicationContext(_launcher);
                Application.Run(_context);
                _log.Info("Launcher has returned execution to main thread.");
            #endif
            }
            catch(FileNotFoundException ex)
            {
                _log.Fatal("Required file \"" + ex.FileName + "\" not found! Application is exiting...");
            }
            catch(IOException ex)
            {
                _log.Fatal("IO Operation failed: " + ex.Message);
                _log.Fatal("Application is exiting...");
            }
            catch(Exception ex)
            {
                UnhandledExceptionHandler(null, new UnhandledExceptionEventArgs(ex, false));
            #if DEBUG
                throw;
            #endif
            }
            finally
            {
                if (_launcher != null)
                {
                    _log.Debug("Closing launcher.");
                    _launcher.Close();
                    _launcher.Dispose();
                    _launcher = null;
                    _log.Info("Launcher closed.");
                }
                if (debug)
                {
                    _log.Debug("Closing debug console.");
                    FreeConsole();
                }
                _log.Info("!!! APPLICATION EXIT !!!");
            }
        }
示例#22
0
        /// <summary>
        /// 発行コントロール
        /// </summary>
        /// <param name="publishModel">publishMode to join.</param>
        /// <param name="guid">guid</param>
        /// <param name="productDivision">商材区分</param>
        /// <param name="backupDivision">バックアップ区分(バックアップ管理画面用)</param>
        /// <returns>publishMode</returns>
        private PublishModel PublishControl(PublishModel publishModel, string guid, string productDivision, string backupDivision)
        {
            // 多重起動を禁止する。
            string mutexName = "publish";

            System.Threading.Mutex mutex = null;
            // 商材詳細
            EnvDetail envDetail = null;
            // メッセージ
            string message = string.Empty;

            try
            {
                // 固有のmutexNameを持つmutexを呼び出す。
                mutex = System.Threading.Mutex.OpenExisting(mutexName);
            }
            catch (System.Threading.WaitHandleCannotBeOpenedException ex)
            {
                // 現在起動しているものがない場合、Exception発生するのが当たり前なので、このまま流す。
            }

            // mutexがnullか確認する。
            if ((mutex == null))
            {
                // mutexを生成する。
                mutex = new System.Threading.Mutex(true, mutexName);
            }
            else
            {
                // mutexがnullではない場合、現在起動中のものがあるという意味なのでエラーを返す。
                Logger.Info("多重起動エラー:ただいま発行処理を実施しているため、この処理は中止します。guid:" + guid);
                ModelState.AddModelError(string.Empty, "ただいま発行処理を実施しています。時間をおいて再度お試しください。");
                return(publishModel);
            }

            try
            {
                Logger.Info("### Start Publish ### -- guid:" + guid);

                // 入力フォームから渡された発行元と発行先の情報が正しいか確認(サーバー一覧から逆検索して確認)
                //EnvDetail serverDetail = null;
                foreach (EnvDetail server in PublishModel.ReadServerCsv())
                {
                    var serverValue = server.value.ToString().Split(',');
                    // 商材区分、発行元、発行先が一致するサーバー情報があるか確認
                    // バックアップからの発行の場合はFromPathは比較対象から外す
                    if (backupDivision == null &&
                        productDivision.Equals(serverValue[2]) &&
                        publishModel.FromPath.Equals(server.FromPath) &&
                        publishModel.ToPath.Equals(server.ToPath))
                    {
                        envDetail = server;
                        break;
                    }
                    else if (backupDivision != null &&
                             productDivision.Equals(serverValue[2]) &&
                             publishModel.ToPath.Equals(server.ToPath))
                    {
                        envDetail = server;
                        break;
                    }
                }

                // 商材の情報がある場合、発行処理を行う
                if (envDetail != null)
                {
                    // 商材区分に商材名と発行先のhttpHeadをに表示する
                    envDetail.viewName = envDetail.httpHeader + "|" + envDetail.viewName;

                    Logger.Info("発行を開始します。商材区分:" + envDetail.viewName);

                    // バックアップ区分がある場合(=バックアップからの発行の場合)
                    if (backupDivision != null)
                    {
                        // 選択したバックアップ元を発行元とする。
                        envDetail.FromPath = backupDivision;

                        // バックアップ元のディレクトリが存在する場合、エラーを返す。
                        if (!Directory.Exists(backupDivision))
                        {
                            // バックアップ元のディレクトリが存在しない場合、エラーを返す。
                            message = "選択したバックアップディレクトリが存在しません。再度お試しください。";
                            Logger.Info(message);
                            ModelState.AddModelError(string.Empty, message);
                            return(publishModel);
                        }
                    }

                    // 発行処理。PublishControlの処理結果がtrueの場合のみ、完了メッセージを返す。
                    // (PublishControlの結果がfalseの場合はエラー発生箇所で格納したエラーメッセージを表示する)

                    // 商材名
                    string productName = envDetail.viewName;
                    // 発行元(商材から選択した場合は【仮本番】になる)
                    string fromPath = envDetail.FromPath;
                    // 発行先(商材から選択した場合は【本番】になる)
                    string toPath = Common.GetDirectoryPath(envDetail.ToPath);

                    // 最新バックアップ(ロールバック時にはここでバックアップしたソースが元になる)
                    if (LatestBackup(productName, toPath))
                    {
                        // 発行
                        if (Publisher(productName, fromPath, toPath))
                        {
                            // バックアップ
                            if (Backup(productName, toPath))
                            {
                                // 発行元、発行先の情報を画面のフォームに返す
                                ModelState.SetModelValue("FromPath", new ValueProviderResult(envDetail.FromPath, envDetail.FromPath, null));
                                ModelState.SetModelValue("ToPath", new ValueProviderResult(envDetail.ToPath, envDetail.ToPath, null));

                                // 完了メッセージを返す
                                message = "発行が完了しました。商材区分:" + envDetail.viewName + "、発行元(From):" + envDetail.FromPath + "、発行先(To):" + envDetail.ToPath;
                                Logger.Info(message);
                                // メール送信
                                Common.SendMail(message, ": publish complete: " + envDetail.viewName);

                                ModelState.AddModelError(string.Empty, message);
                            }
                        }
                    }
                }
                else
                {
                    // 商材情報がない場合、エラーを返す。
                    message = "商材区分が正しくありません。";
                    Logger.Info(message);
                    ModelState.AddModelError(string.Empty, message);
                }

                Logger.Info("### End Publish ### -- guid:" + guid);
            }
            catch (Exception e)
            {
                message = "発行処理中にエラーが発生しました。";
                string subject = "";

                // 商材の情報がある場合、内容を表示する。
                if (envDetail != null)
                {
                    message += "商材区分:" + envDetail.viewName + "、発行元(From):" + envDetail.FromPath + "、発行先(To):" + envDetail.ToPath + "。";
                    subject  = envDetail.viewName;
                }

                // メール送信
                Common.SendMail(message, ": catch error: " + subject);

                Logger.Info(message + "StackTrace:" + e.StackTrace + "、message : " + e.Message);
                ModelState.AddModelError(string.Empty, message);
            }
            finally
            {
                // mutexを開放する(次の起動ok)
                mutex.Close();
            }

            return(publishModel);
        }
示例#23
0
        public void Run(System.Threading.CancellationToken token)
        {
            ProductAdapter productAdapter = new ProductAdapter(new SqlDb("Data Source=42.112.28.93;Initial Catalog=QT_2;Persist Security Info=True;User ID=wss_price;Password=HzlRt4$$axzG-*UlpuL2gYDu;connection timeout=200"));

            log.InfoFormat("Start run at {0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
            CacheProductHash       cashProductHash        = CacheProductHash.Instance();
            RedisLastUpdateProduct cacheLastUpdateProduct = RedisLastUpdateProduct.Instance();
            int countProduct = 0;

            try
            {
                var lstFn = productAdapter.GetAllCompanyIdCrawlerFindNew();
                var lstRl = productAdapter.GetAllCompanyIdCrawlerReload();
                RedisCompanyWaitCrawler redisCache = RedisCompanyWaitCrawler.Instance();
                redisCache.SyncCompanyFindNew(lstFn);
                redisCache.SyncCompanyReload(lstRl);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

            var lst           = new List <QT.Entities.CrawlerProduct.Cache.ProductHash>();
            var lstLastUpdate = new List <long>();
            var lstCompany    = productAdapter.GetAllCompanyIdCrawler();

            foreach (var companyID in lstCompany)
            {
                Company cmp = new Company(companyID);
                productAdapter.DeleteProductUnvalidOfCOmpany(companyID);
                DataTable tbl = productAdapter.GetProductResetColumnDuplicateAndChange(companyID);
                foreach (DataRow rowProduct in tbl.Rows)
                {
                    long   productId        = QT.Entities.Common.Obj2Int64(rowProduct["ID"]);
                    long   originPrice      = QT.Entities.Common.Obj2Int64(rowProduct["OriginPrice"]);
                    string name             = rowProduct["Name"].ToString();
                    long   price            = QT.Entities.Common.Obj2Int64(rowProduct["Price"]);
                    string imageUrl         = Convert.ToString(rowProduct["ImageUrls"]);
                    string detailUrl        = Convert.ToString(rowProduct["DetailUrl"]);
                    int    inStock          = QT.Entities.Common.Obj2Int(rowProduct["InStock"]);
                    bool   valid            = QT.Entities.Common.Obj2Bool(rowProduct["Valid"]);
                    string shortDescription = QT.Entities.Common.CellToString(rowProduct["ShortDescription"], "");
                    long   categoryId       = rowProduct["ClassificationID"] == DBNull.Value ? 0 : QT.Entities.Common.Obj2Int64(rowProduct["ClassificationID"]);
                    long   hashChange       = ProductEntity.GetHashChangeInfo(inStock, valid, price, name, imageUrl, categoryId, shortDescription, originPrice);
                    long   hashDuplicate    = Product.GetHashDuplicate(cmp.Domain, price, name, imageUrl);
                    long   hashImage        = Product.GetHashImageInfo(imageUrl);
                    lst.Add(new QT.Entities.CrawlerProduct.Cache.ProductHash()
                    {
                        HashChange    = hashChange,
                        HashDuplicate = hashDuplicate,
                        HashImage     = hashImage,
                        Id            = productId,
                        Price         = price,
                        url           = detailUrl
                    });
                    lstLastUpdate.Add(productId);
                }
                cashProductHash.SetCacheProductHash(companyID, lst, 100); cacheLastUpdateProduct.RemoveAllLstProduct(companyID);
                cacheLastUpdateProduct.UpdateBathLastUpdateProduct(companyID, lstLastUpdate, DateTime.Now.AddDays(-1));
                productAdapter.UpdateCountProductForCompany(companyID, lstLastUpdate.Count, lstLastUpdate.Count);
                lst.Clear();
                lstLastUpdate.Clear();
                log.Info(string.Format("Complete Company: {0} {1}/{2}", companyID, countProduct++, lstCompany.Count));
            }
            log.Info("Complete all company");
            NextRun = DateTime.Now.AddHours(MAX_HOUR_LOOP);
            log.InfoFormat("End at {0}", DateTime.Now.ToString());
        }
示例#24
0
        public void ProcesarAnalisis()
        {
            string TwitterConsumerKey    = ConfigurationManager.AppSettings.Get("TwitterConsumerKey");
            string TwitterConsumerSecret = ConfigurationManager.AppSettings.Get("TwitterConsumerSecret");
            string TwitterAccessToken    = ConfigurationManager.AppSettings.Get("TwitterAccessToken");
            string TwitterAccessSecret   = ConfigurationManager.AppSettings.Get("TwitterAccessSecret");

            Auth.SetUserCredentials(TwitterConsumerKey, TwitterConsumerSecret, TwitterAccessToken, TwitterAccessSecret);

            TweetinviConfig.CurrentThreadSettings.TweetMode = TweetMode.Extended;

            _log.Info("Iniciando proceso de recolección de datos");

            MongoAsync().Wait();
            var db = MongoAsync().Result;

            _log.Info("Obteniendo datos para Analizar de la BD");

            if (CollectionExists(db, "analysis"))
            {
                var collection = db.GetCollection <Analysis>("analysis");
                var list       = collection.AsQueryable <Analysis>().ToList();
                if (list.Count > 0)
                {
                    var analisisRegistrados = list.Where(d => d.stateAnalysis == (int)EstadoAnalisis.Registrado).ToList();

                    Stopwatch sw = new Stopwatch();

                    foreach (var analisis in analisisRegistrados)
                    {
                        _log.InfoFormat("Procesando analisis con id {0} y palabra clave {1}", analisis.id, analisis.nameKey);
                        _log.Info("Cambiando el estado del análisis a DatosRecolectados");
                        UpdateState(db, analisis.id, (int)EstadoAnalisis.DatosRecolectados);

                        sw.Start();
                        _log.Info("Procesando tweets");
                        ProcesarTweets(db, analisis.id, analisis.nameKey);

                        sw.Stop();
                        _log.InfoFormat("Milisegundos totales para los datos recolectados {0}", sw.ElapsedMilliseconds);


                        sw.Start();
                        _log.Info("Cambiando el estado del análisis a AnalisisSemantico");
                        UpdateState(db, analisis.id, (int)EstadoAnalisis.AnalisisSemantico);

                        _log.Info("Procesando el análisis semántico de los tweets");
                        ProcesarAnalisisSemantico(db, analisis.id);

                        //_log.Info("Calculando el sexo de las personas");
                        //RegistroSexoUsuarios(db, analisis.id);


                        _log.Info("Cambiando el estado del análisis a Completado");
                        UpdateState(db, analisis.id, (int)EstadoAnalisis.Completado);

                        UpdateEndDate(db, analisis.id);

                        sw.Stop();
                        Console.WriteLine(sw.ElapsedMilliseconds);
                    }
                }
            }
        }
示例#25
0
        private void FinishExport(bool exportSTL)
        {
            logger.Info("Completing URDF export");
            SaveConfigTree(ActiveSWModel, BaseNode, false);

            // Saving selected node
            LinkNode node = (LinkNode)treeViewLinkProperties.SelectedNode;

            if (node != null)
            {
                SaveLinkDataFromPropertyBoxes(node.Link);
            }

            Exporter.URDFRobot = CreateRobotFromTreeView(treeViewLinkProperties);

            // The UI should prevent these sorts of errors, but just in case
            string errors = CheckLinksForErrors(Exporter.URDFRobot.BaseLink);

            if (!string.IsNullOrWhiteSpace(errors))
            {
                logger.Info("Link errors encountered:\n " + errors);

                string message = "The following links contained errors in either their link or joint " +
                                 "properties. Please address before continuing\r\n\r\n" + errors;
                MessageBox.Show(message, "URDF Errors");
                return;
            }

            string warnings = CheckLinksForWarnings(Exporter.URDFRobot.BaseLink);

            if (!string.IsNullOrWhiteSpace(warnings))
            {
                logger.Info("Link warnings encountered:\r\n" + warnings);

                string message = "The following links contained issues that may cause problems. " +
                                 "Do you wish to proceed?\r\n\r\n" + warnings;
                DialogResult result =
                    MessageBox.Show(message, "URDF Warnings", MessageBoxButtons.YesNo);

                if (result == DialogResult.No)
                {
                    logger.Info("Export canceled for user to review warnings");
                    return;
                }
            }

            SaveFileDialog saveFileDialog1 = new SaveFileDialog
            {
                RestoreDirectory = true,
                InitialDirectory = Exporter.SavePath,
                FileName         = Exporter.PackageName
            };

            bool saveResult = DialogResult.OK == saveFileDialog1.ShowDialog();

            saveFileDialog1.Dispose();
            if (saveResult)
            {
                Exporter.SavePath    = Path.GetDirectoryName(saveFileDialog1.FileName);
                Exporter.PackageName = Path.GetFileName(saveFileDialog1.FileName);

                logger.Info("Saving URDF package to " + saveFileDialog1.FileName);
                Exporter.ExportRobot(exportSTL);
                Close();
            }
        }
示例#26
0
        public void Verify(Stream target, string filename)
        {
            log.InfoFormat("Started verifying {0} bytes in {1} after copy via iSCSI.", _bytescopied, filename);

            int  bytesRead = 0;
            long offset    = 0;
            long limit     = (long)_bytescopied;

            string updatemsg = string.Format(Messages.ISCSI_VERIFY_PROGRESS, filename);

            OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.FileStart, "SendData Start", updatemsg, 0, (ulong)limit));

            // Create a hash algorithm to compute the hash from separate blocks in the same way as Copy().
            using (var hashAlgorithm = System.Security.Cryptography.HashAlgorithm.Create(_hashAlgorithmName))
            {
                while (offset < limit)
                {
                    if (Cancel)
                    {
                        log.Info(Messages.ISCSI_VERIFY_CANCELLED);
                        throw new OperationCanceledException(Messages.ISCSI_VERIFY_CANCELLED);
                    }

                    try
                    {
                        bytesRead = target.Read(_buffer, 0, _buffer.Length);

                        if (bytesRead <= 0)
                        {
                            break;
                        }

                        if (!IsZeros(_buffer))
                        {
                            if ((offset + bytesRead) < limit)
                            {
                                // This is not the last block.
                                // Compute the partial hash.
                                hashAlgorithm.TransformBlock(_buffer, 0, bytesRead, _buffer, 0);
                            }
                        }

                        offset += bytesRead;

                        OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.FileProgress, "SendData Start", updatemsg, (ulong)offset, (ulong)limit));
                    }
                    catch (Exception ex)
                    {
                        var message = string.Format(Messages.ISCSI_VERIFY_ERROR, filename);
                        log.WarnFormat("{0} {1}", message, ex.Message);
                        throw new Exception(message, ex);
                    }
                }

                // It is necessary to call TransformBlock at least once and TransformFinalBlock only once before getting the hash.
                // If only the last buffer had content, then TransformBlock would not have been called at least once.
                // So, split the last buffer and hash it even if it is empty.
                // Note: TransformBlock will accept an "inputCount" that is zero.
                hashAlgorithm.TransformBlock(_buffer, 0, bytesRead / 2, _buffer, 0);

                // Compute the final hash.
                hashAlgorithm.TransformFinalBlock(_buffer, bytesRead / 2, bytesRead / 2 + bytesRead % 2);

                // Compare targetHash with copyHash.
                if (!System.Linq.Enumerable.SequenceEqual(_copyHash, hashAlgorithm.Hash))
                {
                    log.Error(Messages.ISCSI_VERIFY_INVALID);
                    throw new Exception(Messages.ISCSI_VERIFY_INVALID);
                }
            }

            OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.FileComplete, "SendData Completed", updatemsg, (ulong)offset, (ulong)limit));

            log.InfoFormat("Finished verifying {0} bytes in {1} after copy via iSCSI.", target.Length, filename);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            log4net.ILog log = log4net.LogManager.GetLogger(this.GetType());

            // **************演示后台接收银联返回报文交易结果展示***********************
            if (Request.HttpMethod == "POST")
            {
                // 使用Dictionary保存参数
                Dictionary <string, string> resData = new Dictionary <string, string>();

                NameValueCollection coll = Request.Form;

                string[] requestItem = coll.AllKeys;

                for (int i = 0; i < requestItem.Length; i++)
                {
                    resData.Add(requestItem[i], Request.Form[requestItem[i]]);
                }

                //商户端根据返回报文内容处理自己的业务逻辑 ,DEMO此处只输出报文结果
                StringBuilder builder = new StringBuilder();
                log.Info("receive back notify: " + SDKUtil.CreateLinkString(resData, false, true, System.Text.Encoding.UTF8));

                builder.Append("<tr><td align=\"center\" colspan=\"2\"><b>商户端接收银联返回报文并按照表格形式输出结果</b></td></tr>");

                for (int i = 0; i < requestItem.Length; i++)
                {
                    builder.Append("<tr><td width=\"30%\" align=\"right\">" + requestItem[i] + "</td><td style='word-break:break-all'>" + Request.Form[requestItem[i]] + "</td></tr>");
                }

                if (AcpService.Validate(resData, System.Text.Encoding.UTF8))
                {
                    builder.Append("<tr><td width=\"30%\" align=\"right\">商户端验证银联返回报文结果</td><td>验证签名成功.</td></tr>");

                    string respcode = resData["respCode"]; //00、A6为成功,其余为失败。其他字段也可按此方式获取。

                    //如果卡号我们业务配了会返回且配了需要加密的话,请按此方法解密
                    //if(resData.ContainsKey("accNo"))
                    //{
                    //    string accNo = SecurityUtil.DecryptData(resData["accNo"], System.Text.Encoding.UTF8);
                    //}

                    //customerInfo子域的获取
                    if (resData.ContainsKey("customerInfo"))
                    {
                        Dictionary <string, string> customerInfo = AcpService.ParseCustomerInfo(resData["customerInfo"], System.Text.Encoding.UTF8);
                        if (customerInfo.ContainsKey("phoneNo"))
                        {
                            string phoneNo = customerInfo["phoneNo"]; //customerInfo其他子域均可参考此方式获取
                        }
                        foreach (KeyValuePair <string, string> pair in customerInfo)
                        {
                            builder.Append(pair.Key + "=" + pair.Value + "<br>\n");
                        }
                    }
                }
                else
                {
                    builder.Append("<tr><td width=\"30%\" align=\"right\">商户端验证银联返回报文结果</td><td>验证签名失败.</td></tr>");
                }
                html = builder.ToString();
            }
        }
示例#28
0
        public static void InoCallProcess(_AcDb.ResultBuffer rb)
        {
            try
            {
                if (rb == null)
                {
                    return;
                }
                _AcDb.TypedValue[] values = rb.AsArray();
                if (values == null || values.Length < 1)
                {
                    return;
                }
                if (values[0].Value == null)
                {
                    return;
                }
                string fileName = values[0].Value.ToString();
                if (string.IsNullOrEmpty(fileName))
                {
                    return;
                }

                string args = string.Empty;
                if (values.Length > 1)
                {
                    args = values[1].Value.ToString();
                }

                // Simple variante
                //if (string.IsNullOrEmpty(args))
                //{
                //    System.Diagnostics.Process.Start(fileName);
                //}
                //else
                //{
                //    System.Diagnostics.Process.Start(fileName, args);
                //}

                _AcEd.Editor ed = _AcAp.Application.DocumentManager.MdiActiveDocument.Editor;

                // Variante with output
                int exitCode = -1;
                // -> async writings to editor are ignored
                //ExecuteCommandAsyncOut(fileName, args, ref exitCode, ed);
                string error  = string.Empty;
                string output = string.Empty;

                log.InfoFormat(CultureInfo.InvariantCulture, "InoCallProcess: args='{0}', filename='{1}'.", args, fileName);

                ExecuteCommandSyncOut(fileName, args, ref error, ref output, ref exitCode);
                if (!string.IsNullOrEmpty(output))
                {
                    ed.WriteMessage("\n" + output);
                    log.Info(output);
                }
                if (!string.IsNullOrEmpty(error))
                {
                    ed.WriteMessage("\nError>>" + error);
                    log.Warn("\nError>>" + error);
                }
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(string.Format(CultureInfo.CurrentCulture, "Fehler in CallProcess: {0}", ex.Message), "CallProcess");
            }
        }
        /// <summary>
        /// Loads the DropTemplateXItemTemplate
        /// </summary>
        /// <returns></returns>
        protected static bool PreloadLootTemplates()
        {
            if (m_lootTemplates == null)
            {
                m_lootTemplates = new Dictionary <string, Dictionary <string, DropTemplateXItemTemplate> >();

                lock (m_lootTemplates)
                {
                    IList <DropTemplateXItemTemplate> dbLootTemplates;

                    try
                    {
                        // TemplateName (typically the mob name), ItemTemplateID, Chance
                        dbLootTemplates = GameServer.Database.SelectAllObjects <DropTemplateXItemTemplate>();
                    }
                    catch (Exception e)
                    {
                        if (log.IsErrorEnabled)
                        {
                            log.Error("LootGeneratorMobTemplate: DropTemplateXItemTemplate could not be loaded:", e);
                        }
                        return(false);
                    }

                    if (dbLootTemplates != null)
                    {
                        Dictionary <string, DropTemplateXItemTemplate> loot;

                        foreach (DropTemplateXItemTemplate dbTemplate in dbLootTemplates)
                        {
                            if (!m_lootTemplates.TryGetValue(dbTemplate.TemplateName.ToLower(), out loot))
                            {
                                loot = new Dictionary <string, DropTemplateXItemTemplate>();
                                m_lootTemplates[dbTemplate.TemplateName.ToLower()] = loot;
                            }

                            ItemTemplate drop = GameServer.Database.FindObjectByKey <ItemTemplate>(dbTemplate.ItemTemplateID);

                            if (drop == null)
                            {
                                if (log.IsErrorEnabled)
                                {
                                    log.Error("ItemTemplate: " + dbTemplate.ItemTemplateID + " is not found, it is referenced from DropTemplateXItemTemplate: " + dbTemplate.TemplateName);
                                }
                            }
                            else
                            {
                                if (!loot.ContainsKey(dbTemplate.ItemTemplateID.ToLower()))
                                {
                                    loot.Add(dbTemplate.ItemTemplateID.ToLower(), dbTemplate);
                                }
                            }
                        }
                    }
                }

                log.Info("DropTemplateXItemTemplates pre-loaded.");
            }

            if (m_mobXLootTemplates == null)
            {
                m_mobXLootTemplates = new Dictionary <string, List <MobDropTemplate> >();

                lock (m_mobXLootTemplates)
                {
                    IList <MobDropTemplate> dbMobXLootTemplates;

                    try
                    {
                        // MobName, LootTemplateName, DropCount
                        dbMobXLootTemplates = GameServer.Database.SelectAllObjects <MobDropTemplate>();
                    }
                    catch (Exception e)
                    {
                        if (log.IsErrorEnabled)
                        {
                            log.Error("LootGeneratorMobTemplate: MobDropTemplate could not be loaded", e);
                        }
                        return(false);
                    }

                    if (dbMobXLootTemplates != null)
                    {
                        foreach (MobDropTemplate dbMobXTemplate in dbMobXLootTemplates)
                        {
                            // There can be multiple MobDropTemplate for a mob, each pointing to a different loot template
                            List <MobDropTemplate> mobxLootTemplates;
                            if (!m_mobXLootTemplates.TryGetValue(dbMobXTemplate.MobName.ToLower(), out mobxLootTemplates))
                            {
                                mobxLootTemplates = new List <MobDropTemplate>();
                                m_mobXLootTemplates[dbMobXTemplate.MobName.ToLower()] = mobxLootTemplates;
                            }
                            mobxLootTemplates.Add(dbMobXTemplate);
                        }
                    }
                }

                log.Info("MobDropTemplates pre-loaded.");
            }

            return(true);
        }
示例#30
0
        public static void Start(string[] args)
        {
            bool isAlreadyRunning = false;
            List<string> filesToOpen = new List<string>();

            // Init Log4NET
            LogFileLocation = LogHelper.InitializeLog4NET();
            // Get logger
            LOG = log4net.LogManager.GetLogger(typeof(MainForm));

            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            // Log the startup
            LOG.Info("Starting: " + EnvironmentInfo.EnvironmentToString(false));

            IniConfig.Init();
            AppConfig.UpgradeToIni();
            // Read configuration
            conf = IniConfig.GetIniSection<CoreConfiguration>();
            try
            {
                // Fix for Bug 2495900, Multi-user Environment
                // check whether there's an local instance running already

                try
                {
                    // Added Mutex Security, hopefully this prevents the UnauthorizedAccessException more gracefully
                    // See an example in Bug #3131534
                    SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    MutexSecurity mutexsecurity = new MutexSecurity();
                    mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow));
                    mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny));
                    mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny));

                    bool created = false;
                    // 1) Create Mutex
                    applicationMutex = new Mutex(false, @"Local\F48E86D3-E34C-4DB7-8F8F-9A0EA55F0D08", out created, mutexsecurity);
                    // 2) Get the right to it, this returns false if it's already locked
                    if (!applicationMutex.WaitOne(0, false))
                    {
                        LOG.Debug("Greenshot seems already to be running!");
                        isAlreadyRunning = true;
                        // Clean up
                        applicationMutex.Close();
                        applicationMutex = null;
                    }
                }
                catch (AbandonedMutexException e)
                {
                    // Another Greenshot instance didn't cleanup correctly!
                    // we can ignore the exception, it happend on the "waitone" but still the mutex belongs to us
                    LOG.Warn("Greenshot didn't cleanup correctly!", e);
                }
                catch (UnauthorizedAccessException e)
                {
                    LOG.Warn("Greenshot is most likely already running for a different user in the same session, can't create mutex due to error: ", e);
                    isAlreadyRunning = true;
                }
                catch (Exception e)
                {
                    LOG.Warn("Problem obtaining the Mutex, assuming it was already taken!", e);
                    isAlreadyRunning = true;
                }

                if (args.Length > 0 && LOG.IsDebugEnabled)
                {
                    StringBuilder argumentString = new StringBuilder();
                    for (int argumentNr = 0; argumentNr < args.Length; argumentNr++)
                    {
                        argumentString.Append("[").Append(args[argumentNr]).Append("] ");
                    }
                    LOG.Debug("Greenshot arguments: " + argumentString.ToString());
                }

                for (int argumentNr = 0; argumentNr < args.Length; argumentNr++)
                {
                    string argument = args[argumentNr];
                    // Help
                    if (argument.ToLower().Equals("/help"))
                    {
                        // Try to attach to the console
                        bool attachedToConsole = Kernel32.AttachConsole(Kernel32.ATTACHCONSOLE_ATTACHPARENTPROCESS);
                        // If attach didn't work, open a console
                        if (!attachedToConsole)
                        {
                            Kernel32.AllocConsole();
                        }
                        StringBuilder helpOutput = new StringBuilder();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("Greenshot commandline options:");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t/help");
                        helpOutput.AppendLine("\t\tThis help.");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t/exit");
                        helpOutput.AppendLine("\t\tTries to close all running instances.");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t/reload");
                        helpOutput.AppendLine("\t\tReload the configuration of Greenshot.");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t/language [language code]");
                        helpOutput.AppendLine("\t\tSet the language of Greenshot, e.g. greenshot /language en-US.");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t[filename]");
                        helpOutput.AppendLine("\t\tOpen the bitmap files in the running Greenshot instance or start a new instance");
                        Console.WriteLine(helpOutput.ToString());

                        // If attach didn't work, wait for key otherwise the console will close to quickly
                        if (!attachedToConsole)
                        {
                            Console.ReadKey();
                        }
                        FreeMutex();
                        return;
                    }

                    if (argument.ToLower().Equals("/exit"))
                    {
                        // unregister application on uninstall (allow uninstall)
                        try
                        {
                            LOG.Info("Sending all instances the exit command.");
                            // Pass Exit to running instance, if any
                            SendData(new CopyDataTransport(CommandEnum.Exit));
                        }
                        catch (Exception e)
                        {
                            LOG.Warn("Exception by exit.", e);
                        }
                        FreeMutex();
                        return;
                    }

                    // Reload the configuration
                    if (argument.ToLower().Equals("/reload"))
                    {
                        // Modify configuration
                        LOG.Info("Reloading configuration!");
                        // Update running instances
                        SendData(new CopyDataTransport(CommandEnum.ReloadConfig));
                        FreeMutex();
                        return;
                    }

                    // Stop running
                    if (argument.ToLower().Equals("/norun"))
                    {
                        // Make an exit possible
                        FreeMutex();
                        return;
                    }

                    // Language
                    if (argument.ToLower().Equals("/language"))
                    {
                        conf.Language = args[++argumentNr];
                        IniConfig.Save();
                        continue;
                    }

                    // Files to open
                    filesToOpen.Add(argument);
                }

                // Finished parsing the command line arguments, see if we need to do anything
                CopyDataTransport transport = new CopyDataTransport();
                if (filesToOpen.Count > 0)
                {
                    foreach (string fileToOpen in filesToOpen)
                    {
                        transport.AddCommand(CommandEnum.OpenFile, fileToOpen);
                    }
                }

                if (MainForm.instance == null)
                    MainForm.instance = new MainForm(transport);

                // if language is not set, show language dialog
                if (string.IsNullOrEmpty(conf.Language))
                {
                    LanguageDialog languageDialog = LanguageDialog.GetInstance();
                    languageDialog.ShowDialog();
                    conf.Language = languageDialog.SelectedLanguage;
                    IniConfig.Save();
                }

                // Check if it's the first time launch?
                if (conf.IsFirstLaunch)
                {
                    conf.IsFirstLaunch = false;
                    IniConfig.Save();
                    transport.AddCommand(CommandEnum.FirstLaunch);
                }
            }
            catch (Exception ex)
            {
                LOG.Error("Exception in startup.", ex);
                Application_ThreadException(MainForm.ActiveForm, new ThreadExceptionEventArgs(ex));
            }
        }
示例#31
0
 void Application_EndRequest(Object Sender, EventArgs e)
 {
     log4net.ILog log = log4net.LogManager.GetLogger(typeof(MvcApplication));
     log.Info(Request.HttpMethod + ": " + Request.Path);
 }
示例#32
0
 private void Window_Closing(object sender, CancelEventArgs e)
 {
     log.Info("WinHue Closing.");
     Application.Current.Shutdown();
 }
示例#33
0
 public override void Write(string message)
 {
     _log?.Info(message);
 }
示例#34
0
        /// <summary>
        /// Method called asynchronously on User entities collection changed.
        /// </summary>
        /// <param name="newItems">Thee list of items to add.</param>
        public static void DbInsert(List <UserEntity> newItems)
        {
            MessageBoxs.IsBusy = true;
            log.Info("Adding User(s). Please wait...");

            try
            {
                log.Info("Adding User(s). Please wait...");

                if (newItems != null && newItems.Count > 0)
                {
                    foreach (UserEntity entity in newItems)
                    {
                        Db.Users.Add(entity);

                        log.Info(string.Format("User [{0}:{1}] added.", entity.PrimaryKey, entity.Name));
                    }
                }

                AppNavigatorBase.Clear();
                log.Info("Adding User(s). Done !");
            }
            catch (Exception e)
            {
                log.Error(e);
                MessageBoxs.Fatal(e, "Adding User(s) failed !");
            }
            finally
            {
                MessageBoxs.IsBusy = false;
            }
        }
示例#35
0
        /// <summary>
        /// Initializes a new instance of the Sharpcraft Launcher.
        /// </summary>
        public Launcher()
        {
            InitializeComponent();
            _log = LogManager.GetLogger(this);
            PassBox.PasswordChar = (char) 0x25CF;
            _auth = new Authenticator(McVersion);
            _auth.OnLoginEvent += LoginEvent;
            if (File.Exists(Constants.GitInfoFile))
            {
                using (var reader = new StreamReader(Constants.GitInfoFile))
                {
                    string content = reader.ReadLine();
                    if (!string.IsNullOrEmpty(content))
                    {
                        string[] gitInfo = content.Split(':');
                        if (gitInfo.Length >= 4)
                        {
                            _hash = gitInfo[0];
                            _shortHash = gitInfo[1];
                            _author = gitInfo[2];
                            if (_author.Contains(" "))
                                _author = _author.Split(' ')[0];
                            _time = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(double.Parse(gitInfo[3])).ToLocalTime();
                        }
                    }
                }
            }

            VersionLabel.Text = VersionString;

            if (File.Exists(Constants.LauncherSettings))
            {
                _log.Info("Loading launcher settings from file...");
                var reader = new StreamReader(Constants.LauncherSettings);
                _settings = new JsonSerializer().Deserialize<LauncherSettings>(new JsonTextReader(reader));
                _log.Info("Launcher settings loaded successfully!");
                reader.Close();
            }
            else
            {
                _settings = new LauncherSettings(Constants.LauncherSettings);
            }
            if (!string.IsNullOrEmpty(_settings.Username))
            {
                _userBoxInactive = false;
                UserBox.Text = _settings.Username;
                UserBox.ForeColor = Color.Black;
            }
            RememberCheckbox.Checked = _settings.Remember;
            if (_settings.Remember && !string.IsNullOrEmpty(_settings.GetPassword()))
            {
                _passBoxInactive = false;
                PassBox.Text = _settings.GetPassword();
                PassBox.ForeColor = Color.Black;
            }
            UpdateForm();
            _log.Info("Launcher initialized.");
        }
示例#36
0
 /// <summary>
 /// Log information to the HTML Report and the Log file.
 /// </summary>
 /// <param name="info">The information being stored.</param>
 public static void Log(string info)
 {
     test.Info(info);
     log.Info(info);
 }
示例#37
0
        public MainForm()
        {
            Log = Logger.Get(this);
            Log.Info("TQVaultAE Initialization !");

            this.Enabled       = false;
            this.ShowInTaskbar = false;
            this.Opacity       = 0;
            this.Hide();

            this.InitializeComponent();

            this.SetupFormSize();

            #region Apply custom font & scaling

            this.exitButton.Font = FontHelper.GetFontAlbertusMTLight(12F, UIService.UI.Scale);
            ScaleControl(this.exitButton);
            this.characterComboBox.Font = FontHelper.GetFontAlbertusMTLight(13F, UIService.UI.Scale);
            ScaleControl(this.characterComboBox);
            this.characterLabel.Font = FontHelper.GetFontAlbertusMTLight(11F, UIService.UI.Scale);
            ScaleControl(this.characterLabel);
            ScaleControl(this.itemTextPanel);

            ScaleControl(this.itemText);
            this.vaultListComboBox.Font = FontHelper.GetFontAlbertusMTLight(13F, UIService.UI.Scale);
            ScaleControl(this.vaultListComboBox);
            this.vaultLabel.Font = FontHelper.GetFontAlbertusMTLight(11F, UIService.UI.Scale);
            ScaleControl(this.vaultLabel);
            this.configureButton.Font = FontHelper.GetFontAlbertusMTLight(12F, UIService.UI.Scale);
            ScaleControl(this.configureButton);
            this.customMapText.Font = FontHelper.GetFontAlbertusMT(11.25F, UIService.UI.Scale);
            ScaleControl(this.customMapText);
            this.panelSelectButton.Font = FontHelper.GetFontAlbertusMTLight(12F, UIService.UI.Scale);
            ScaleControl(this.panelSelectButton);
            this.secondaryVaultListComboBox.Font = FontHelper.GetFontAlbertusMTLight(11F, UIService.UI.Scale);
            ScaleControl(this.secondaryVaultListComboBox);
            this.aboutButton.Font = FontHelper.GetFontAlbertusMTLight(8.25F, UIService.UI.Scale);
            ScaleControl(this.aboutButton);
            this.titleLabel.Font = FontHelper.GetFontAlbertusMTLight(24F, UIService.UI.Scale);
            ScaleControl(this.titleLabel);
            this.searchButton.Font = FontHelper.GetFontAlbertusMTLight(12F, UIService.UI.Scale);
            ScaleControl(this.searchButton);

            #endregion

            // Changed to a global for versions in tqdebug
            AssemblyName aname = Assembly.GetExecutingAssembly().GetName();
            this.currentVersion = aname.Version.ToString();
            this.Text           = string.Format(CultureInfo.CurrentCulture, "{0} {1}", aname.Name, this.currentVersion);

            if (TQDebug.DebugEnabled)
            {
                // Write this version into the debug file.
                Log.DebugFormat(CultureInfo.InvariantCulture, "Current TQVault Version: {0}", this.currentVersion);
                Log.Debug(string.Empty);
                Log.Debug("Debug Levels");
                Log.DebugFormat(CultureInfo.InvariantCulture, "ARCFileDebugLevel: {0}", TQDebug.ArcFileDebugLevel);
                Log.DebugFormat(CultureInfo.InvariantCulture, "DatabaseDebugLevel: {0}", TQDebug.DatabaseDebugLevel);
                Log.DebugFormat(CultureInfo.InvariantCulture, "ItemAttributesDebugLevel: {0}", TQDebug.ItemAttributesDebugLevel);
                Log.DebugFormat(CultureInfo.InvariantCulture, "ItemDebugLevel: {0}", TQDebug.ItemDebugLevel);
                Log.Debug(string.Empty);
            }


            // Setup localized strings.
            this.characterLabel.Text    = Resources.MainFormLabel1;
            this.vaultLabel.Text        = Resources.MainFormLabel2;
            this.configureButton.Text   = Resources.MainFormBtnConfigure;
            this.exitButton.Text        = Resources.GlobalExit;
            this.panelSelectButton.Text = Resources.MainFormBtnPanelSelect;
            this.Icon = Resources.TQVIcon;
            this.searchButton.Text = Resources.MainFormSearchButtonText;

            // Set up Item strings
            Item.ItemWith           = Resources.ItemWith;
            Item.ItemRelicBonus     = Resources.ItemRelicBonus;
            Item.ItemRelicCompleted = Resources.ItemRelicCompleted;
            Item.ItemQuest          = Resources.ItemQuest;
            Item.ItemSeed           = Resources.ItemSeed;
            Item.ItemIT             = Resources.ItemIT;
            Item.ItemRagnarok       = Resources.ItemRagnarok;
            Item.ItemAtlantis       = Resources.ItemAtlantis;
            Item.ShowSkillLevel     = Config.Settings.Default.ShowSkillLevel;

            this.lastDragPoint.X = -1;
            this.DragInfo        = new ItemDragInfo();

            this.CreatePanels();

            // Process the mouse scroll wheel to cycle through the vaults.
            this.MouseWheel += new MouseEventHandler(this.MainFormMouseWheel);

            this.splashScreen = new SplashScreenForm();
            this.splashScreen.MaximumValue = 1;
            this.splashScreen.FormClosed  += new FormClosedEventHandler(this.SplashScreenClosed);

            if (Config.Settings.Default.LoadAllFiles)
            {
                this.splashScreen.MaximumValue += LoadAllFilesTotal();
            }

            this.splashScreen.Show();
            this.splashScreen.Update();
        }
示例#38
0
        static void Main()
        {
            bool ok;

            // Only allow one instance of the switcher to start
            exclusiveAppMtx = new System.Threading.Mutex(true, "{D39FAB11-ED23-478d-AF57-C638F79A7BA8}", out ok);
            if (!ok)
            {
                return;
            }

            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Assembly.GetExecutingAssembly().Location + ".config"));
            log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            log.Info("Application Started");

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ThreadException += Application_ThreadException;
            Application.ApplicationExit += Application_ApplicationExit;
            monitor.RegChanged += new EventHandler(OnRegChanged);
            monitor.Error += new System.IO.ErrorEventHandler(OnRegMonError);

            try
            {
                log.Info("Starting plugin...");

                //Populate notifications from XML file
                _assembly = Assembly.GetExecutingAssembly();
                alertReader = new StreamReader(_assembly.GetManifestResourceStream(Resources.ResourceManager.GetString("strings.xml")));
                XmlSerializer deserializer = new XmlSerializer(typeof(List<Alert>));
                TextReader textReader = alertReader;
                alertList = (List<Alert>)deserializer.Deserialize(textReader);
                textReader.Close();
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
                MessageBox.Show(Resources.ResourceManager.GetString("Error loading"));
            }

            if (SetupPlugin())
            {
                OnRegChanged(null, EventArgs.Empty);
                _systray = new TrayIcon();
                Application.Run();
            }
        }
 public static void WriteLog(string msg)
 {
     log4net.ILog log = log4net.LogManager.GetLogger("loginfo");
     log.Info(msg);
 }
        /// <summary>
        /// Read the options from the XML
        ///  can get only the 3 ones for Move Pitch, Yaw, Roll right now
        /// </summary>
        /// <param name="reader">A prepared XML reader</param>
        /// <param name="instance">the Joystick instance number</param>
        /// <returns></returns>
        public bool Options_fromXML(XElement option, string deviceClass, int instance)
        {
            /*
             *            <flight_move_pitch exponent="1.00" >
             *                    <nonlinearity_curve>
             *                            <point in="0.182"  out="0.028"/>
             *                            <point in="0.629"  out="0.235"/>
             *                            <point in="0.895"  out="0.629"/>
             *                    </nonlinearity_curve>
             *            </flight_move_pitch>
             */
            m_devClass      = deviceClass;
            m_devInstanceNo = instance;
            m_option        = option.Name.LocalName;

            // derive from flight_move_pitch || flight_move_yaw || flight_move_roll (nothing bad should arrive here)
            string[] e = m_option.ToLowerInvariant( ).Split(new char[] { '_' });
            if (e.Length > 2)
            {
                m_cmdCtrl = e[2];           // TODO - see if m_cmdCtrl is needed to be derived here
            }
            string invert = (string)option.Attribute("invert");

            if (!string.IsNullOrEmpty(invert))
            {
                InvertUsed = false;
                if (invert == "1")
                {
                    InvertUsed = true;
                }
            }

            string exponent = (string)option.Attribute("exponent");

            if (!string.IsNullOrEmpty(exponent))
            {
                Exponent     = RoundString(exponent);
                ExponentUsed = true;
            }

            // we may have a nonlin curve...
            XElement nlc = option.Element("nonlinearity_curve");

            if (nlc != null)
            {
                m_PtsIn.Clear( ); m_PtsOut.Clear( ); // reset pts
                IEnumerable <XElement> points = from x in nlc.Elements( )
                                                where (x.Name == "point")
                                                select x;
                foreach (XElement point in points)
                {
                    string ptIn  = RoundString((string)point.Attribute("in"));
                    string ptOut = RoundString((string)point.Attribute("out"));
                    m_PtsIn.Add(ptIn); m_PtsOut.Add(ptOut); m_ptsEnabled = true;
                }
                ExponentUsed = false; // despite having the Expo=1.00 in the options - it is not used with nonlin curve
                Exponent     = RoundString("1.00");
            }
            // sanity check - we've have to have 3 pts  here - else we subst
            // add 2nd
            if (m_PtsIn.Count < 2)
            {
                m_PtsIn.Add("0.500"); m_PtsOut.Add("0.500");
                log.Info("Options_fromXML: got only one nonlin point, added (0.5|0.5)");
            }
            // add 3rd
            if (m_PtsIn.Count < 3)
            {
                m_PtsIn.Add("0.750"); m_PtsOut.Add("0.750");
                log.Info("Options_fromXML: got only two nonlin points, added (0.75|0.75)");
            }

            return(true);
        }
示例#41
0
        public MainGame()
        {
            _log = LogManager.GetLogger(this);

            Activated += GameActivated;
            Deactivated += GameDeactivated;

            _log.Debug("Setting initial FPS value");
            FPS = 0.0f;

            _log.Info("Setting graphics settings...");

            _graphics = new GraphicsDeviceManager(this)
            {
                PreferredBackBufferWidth = ScreenWidth,
                PreferredBackBufferHeight = ScreenHeight
            };

            _log.Info(string.Format("Screen size set to: [W]{0} x [H]{1}", ScreenWidth, ScreenHeight));

            _graphics.SynchronizeWithVerticalRetrace = false;
            //IsFixedTimeStep = false;

            _graphics.ApplyChanges();

            ScreenRectangle = new Rectangle(0, 0, ScreenWidth, ScreenHeight);

            _log.Debug("Setting content root directory...");

            Content.RootDirectory = "Content";

            // Create necessary folders if they don't exist
            try
            {
                if (!Directory.Exists(Paths.SettingsFolder))
                    Directory.CreateDirectory(Paths.SettingsFolder);
            }
            catch (IOException ex)
            {
                _log.Error("Failed to create necessary game folders. Exception details as follows...");
                _log.Fatal("IOException: " + ex.Message + Environment.NewLine + "Details:", ex);
                _log.Fatal("Game will now exit...");
                Exit();
            }

            _log.Info("Loading controls...");
            ControlsManager = new ControlsManager();
            _log.Debug("Controls loaded!");

            _log.Info("Creating components...");

            AudioManager = new AudioManager();

            _stateManager = new GameStateManager(this);
            TitleScreen = new TitleScreen(this, _stateManager);
            StartMenuScreen = new StartMenuScreen(this, _stateManager);
            CharacterGeneratorScreen = new CharacterGeneratorScreen(this, _stateManager);
            SkillScreen = new SkillScreen(this, _stateManager);
            LoadGameScreen = new LoadGameScreen(this, _stateManager);
            GamePlayScreen = new GamePlayScreen(this, _stateManager);

            Components.Add(new InputHandler(this));
            Components.Add(_stateManager);

            _log.Info("Components created!");

            LoadMusic();

            var menuSong = AudioManager.Song.GetSong("MenuTheme");
            menuSong.SetStartFade(new FadeInfo(0.0f, 1.0f, 0.01f, TimeSpan.FromMilliseconds(20)));
            menuSong.SetEndFade(new FadeInfo(1.0f, 0.0f, 0.01f, TimeSpan.FromMilliseconds(15)));

            _log.Debug("Changing to TitleScreen...");
            _stateManager.ChangeState(TitleScreen);
        }
示例#42
0
        public IceManager(string adapterName, string host, int port, bool catchSignals = true)
        {
            IceGridHost = host;
            IceGridPort = port;
            Name = adapterName;

            logger = log4net.LogManager.GetLogger(this.GetType().Name + "::" + Name);

            _ServantIds = new List<Ice.Identity>(); //keep track of servants for emergency cleanup
            string myIP = findLocalIPAddress();
            logger.Info("My IPAddress is: " + myIP);

            //initialize Ice
            Ice.Properties prop = Ice.Util.createProperties();
            prop.setProperty("hms.AdapterId", adapterName);
            prop.setProperty("hms.Endpoints", "tcp -h " + myIP + ":udp -h " + myIP);
            prop.setProperty("Ice.Default.Locator", "IceGrid/Locator:tcp -p " + IceGridPort + " -h " + IceGridHost);
            prop.setProperty("Ice.ThreadPool.Server.Size", "5");
            prop.setProperty("Ice.ThreadPool.Server.SizeMax", "100000");
            prop.setProperty("Ice.ThreadPool.Client.Size", "5");
            prop.setProperty("Ice.ThreadPool.Client.SizeMax", "100000");

            Ice.InitializationData iceidata = new Ice.InitializationData();
            iceidata.properties = prop;
            Communicator = Ice.Util.initialize(iceidata); // could add sys.argv
            try
            {
                _Adapter = Communicator.createObjectAdapter("hms");
                _Adapter.activate();
            }
            catch (Exception ex)
            {
                logger.Fatal("Network error, check configuration: " + ex.Message);
                logger.Fatal("Endpoint(should be local machine): " + prop.getProperty("hms.Endpoints"));
                logger.Fatal("Locator (should be IceGrid Server): " + prop.getProperty("Ice.Default.Locator"));
                throw (ex); // we are dead anyway
            }
            //Now are we ready to communicate with others
            //getting usefull proxies

            try
            {
                // proxy to icegrid to register our vc devices
                Query = IceGrid.QueryPrxHelper.checkedCast(Communicator.stringToProxy("IceGrid/Query"));
                if (Query == null)
                {
                    logger.Error("invalid ICeGrid proxy");
                }
                // proxy to icestorm to publish events
                EventMgr = IceStorm.TopicManagerPrxHelper.checkedCast(Communicator.stringToProxy("EventServer/TopicManager"));
                if (EventMgr == null)
                {
                    logger.Error("invalid IceStorm proxy");
                }
                //these 2 objects are only needed to get the IceGrid admin object in order to register
                _Registry = IceGrid.RegistryPrxHelper.uncheckedCast(Communicator.stringToProxy("IceGrid/Registry"));
                updateIceGridAdmin();

            }
            catch (Ice.NotRegisteredException e)
            {
                logger.Fatal("If we fail here it is probably because the Icebox objects are not registered: " + e.Message);
            }
            catch (Exception e)
            {
                logger.Fatal("IceGrid Server not found!!!!!: " + e.Message);
                throw (e);//without yellow page system, there is no need to start
            }
            if (catchSignals)
            {
                setupSignals();
            }
        }
示例#43
0
 public ActionResult Index()
 {
     log.Info("Action Index has been fired.");
     return(View());
 }
示例#44
0
        static void Main(string[] args)
        {
            try
            {
                basePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                addresses = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName());

                string url = "/Btnm/LocalPlatform";
                string addr = "tcp://127.0.0.1:7070";


                foreach (string ss in args)
                {
                    if (ss.StartsWith("--Url=", StringComparison.InvariantCultureIgnoreCase))
                    {
                        url = ss.Substring("--Url=".Length);
                    }
                    else if (ss.StartsWith("--Address=", StringComparison.InvariantCultureIgnoreCase))
                    {
                        addr = ss.Substring(10);
                    }
                    else if (ss.StartsWith("--MaxSize=", StringComparison.InvariantCultureIgnoreCase))
                    {
                        maxSize = int.Parse(ss.Substring(10));
                    }
                }


                XmlSetting xmlSetting = new XmlSetting(new StreamReader(Path.Combine(basePath, "nanrui.modul.config")));
                defaultSetting = XmlSetting.ReadFromFile(Path.Combine(basePath, "../nanrui.default.config"));

                log4net.Config.XmlConfigurator.Configure(xmlSetting.SelectOne("/configuration/log4net").AsXmlNode() as System.Xml.XmlElement);
                logger = log4net.LogManager.GetLogger("Betanetworks");

                try
                {
                    cachePath = Path.Combine(basePath, "cache");
                    profix = defaultSetting.ReadSetting("/configuration/Locale/PrefixId/@value", profix);
                    corporation = defaultSetting.ReadSetting("/configuration/Locale/Corporation/@value", corporation);
                    uploadForPCAgent = "true" == xmlSetting.ReadSetting("/configuration/Locale/UploadForPCAgent/@value", "false");
                    uploadForBadLink = "true" == xmlSetting.ReadSetting("/configuration/Locale/UploadForBadLink/@value", "false");
                    supportMultCPU = "true" == xmlSetting.ReadSetting("/configuration/Locale/SupportMultCPU/@value", "false");
                    logger.InfoFormat("配置发送程序启动,缺省前缀 '{0}',缺省公司 '{1}'", profix, corporation);

                    logger.Info("载入设备指标映射!");
                    DispatchImpl.ReadDispatch(xmlSetting.SelectOne("/configuration/Maps/Device"), _deviceDispatcher, logger);
                    
                    logger.Logger.Log(typeof(Dispatcher), log4net.Core.Level.Trace, "载入要发送的设备备注列表!", null);
                    ReadMap(_deviceFields, xmlSetting.Select("/configuration/Locale/DeviceFields/*"));
                    
                    logger.Logger.Log(typeof(Dispatcher), log4net.Core.Level.Trace, "载入設備的公司列表!", null);
                    ReadIni(_corporationIPSeg, xmlSetting.Select("/configuration/Locale/Corporations/*"));
                    
    //<Corporations>
    //  <IPAddress from="" to="" value="" />
    //</Corporations>

                    

                    Dictionary<string, XmlContainer> dict = new Dictionary<string, XmlContainer>();

                    logger.Info("开始读设备表!");

                        IList<Device> devices = Device.FindBy<Device>(null);

                        logger.Info("读设备表完成,开始处理!");


                        foreach (Device dev in devices)
                        {
                            XmlContainer xmlContainer = null;
                            switch (dev.Catalog)
                            {
                                case 1: //交换机
                                    logger.InfoFormat("开始处理交换机{0}:{1}:{2}!", dev.Id, dev.Address, dev);
                                    xmlContainer = processSW(dev, dict);
                                    break;
                                case 2://路由器
                                    logger.InfoFormat("开始处理路由器{0}:{1}:{2}!", dev.Id, dev.Address, dev);
                                    xmlContainer = processRT(dev, dict);
                                    break;
                                case 3://交换路由器
                                    logger.InfoFormat("开始处理交换路由器{0}:{1}:{2}!", dev.Id, dev.Address, dev);
                                    xmlContainer = processSW(dev, dict);
                                    break;
                                default:
                                    logger.InfoFormat("跳过未知设备{0}:{1}:{2}!", dev.Id, dev.Address, dev);
                                    break;
                            }

                            if (null != xmlContainer)
                            {
                                _deviceByIds[dev.Id] = dev;
                                clearXml(xmlContainer, dict);
                            }

                        }

                        logger.Info("处理设备表完成,开始读线路表!");

                        using (linkLogger = new StreamWriter(Path.Combine(basePath, string.Concat("nanrui.modul.link.txt"))))
                        {
                            IList<Link> links = Link.FindBy<Link>(null);
                            logger.Info("读线路表完成,开始处理!");

                            foreach (Link link in links)
                            {
                                logger.InfoFormat("开始处理线路{0}:{1}!", link.Id, link);

                                XmlContainer xmlContainer = processLink(link, dict);

                                clearXml(xmlContainer, dict);


                                if (null != xmlContainer)
                                {
                                    _linkByIds[link.Id] = link;
                                    clearXml(xmlContainer, dict);
                                }
                            }
                        }
                        linkLogger = null;

                        logger.Info("处理线路表完成, 开始发送数据!");

                        foreach (XmlContainer xmlContainer in dict.Values)
                        {

                            XmlNode node = xmlContainer.Doc.SelectSingleNode("/IMSDATA/datas[@classname=\"RelationShip\"]");
                            if (null != node)
                            {
                                XmlNode parentNode = node.ParentNode;
                                parentNode.RemoveChild(node);
                                parentNode.AppendChild(node);
                            }

                            Send(xmlContainer.Doc, xmlContainer.Doc.OuterXml);
                        }
                    
                        logger.Info("数据处理完成,配置发送程序退出!");
                }
                catch (Exception e)
                {
                    logger.Fatal("发生异常!", e);
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
示例#45
0
 private void WhereUsed_FormClosed(object sender, FormClosedEventArgs e)
 {
     log.Info("Closed Where Used " + itemnumber + " by " + System.Environment.UserName);
     this.Dispose();
 }
        public string Post([FromBody] grocitem obj)
        {
            _log4net.Info(" Http POST Request done");

            return(_context.Post(obj));
        }
        static public void Plan2ReplaceInLayoutNamesBulk()
        {
            try
            {
                log.Info("----------------------------------------------------------------------------------");
                log.Info("Plan2ReplaceInLayoutNamesBulk");

                string dirName = null;
                _NrOfReplacedTexts = 0;
                _OldText           = "";
                _NewText           = "";
                List <string> saveNotPossible = new List <string>();

                _AcEd.Editor ed = _AcAp.Application.DocumentManager.MdiActiveDocument.Editor;

                if (!GetOldText(ed))
                {
                    return;
                }
                if (!GetNewText(ed))
                {
                    return;
                }

                using (var folderBrowser = new System.Windows.Forms.FolderBrowserDialog())
                {
                    folderBrowser.Description = "Verzeichnis mit Zeichnungen für die Umbenennung der Layouts";
                    folderBrowser.RootFolder  = Environment.SpecialFolder.MyComputer;
                    if (folderBrowser.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                    {
                        return;
                    }
                    dirName = folderBrowser.SelectedPath;
                }

                log.Info(string.Format(CultureInfo.CurrentCulture, "Ersetzung: '{0}' -> '{1}'.", _OldText, _NewText));

                var files = System.IO.Directory.GetFiles(dirName, "*.dwg", System.IO.SearchOption.AllDirectories);

                foreach (var fileName in files)
                {
                    SetReadOnlyAttribute(fileName, false);

                    bool ok = false;

                    log.Info("----------------------------------------------------------------------------------");
                    log.Info(string.Format(CultureInfo.CurrentCulture, "Öffne Zeichnung {0}", fileName));

                    _AcAp.Application.DocumentManager.Open(fileName, false);
                    _AcAp.Document doc = _AcAp.Application.DocumentManager.MdiActiveDocument;
                    _AcDb.Database db  = doc.Database;

                    //Lock the new document
                    using (DocumentLock acLckDoc = doc.LockDocument())
                    {
                        // main part
                        var layoutNames = Plan2Ext.Layouts.GetLayoutNames();
                        layoutNames = layoutNames.Where(x => string.Compare(x, "Model", StringComparison.OrdinalIgnoreCase) != 0).ToList();

                        _Tr = db.TransactionManager.StartTransaction();
                        using (_Tr)
                        {
                            _AcDb.LayoutManager layoutMgr = _AcDb.LayoutManager.Current;

                            foreach (var name in layoutNames)
                            {
                                bool changed;
                                var  newT = ReplaceTexts(name, out changed);
                                if (changed)
                                {
                                    layoutMgr.RenameLayout(name, newT);
                                    _NrOfReplacedTexts++;
                                    ok = true;
                                }
                            }

                            _Tr.Commit();
                        }
                    }

                    if (ok)
                    {
                        log.Info(string.Format(CultureInfo.CurrentCulture, "Zeichnung speichern und schließen: {0}", fileName));
                        try
                        {
                            doc.CloseAndSave(fileName);
                        }
                        catch (System.Exception ex)
                        {
                            log.Warn(string.Format(CultureInfo.CurrentCulture, "Zeichnung konnte nicht gespeichert werden! {0}. {1}", fileName, ex.Message));
                            saveNotPossible.Add(fileName);
                            doc.CloseAndDiscard();
                        }
                    }
                    else
                    {
                        log.Info(string.Format(CultureInfo.CurrentCulture, "Zeichnung schließen ohne zu speichern da keine Layouts geändert wurden: {0}", fileName));
                        doc.CloseAndDiscard();
                    }
                }

                if (saveNotPossible.Count > 0)
                {
                    var names    = saveNotPossible.Select(x => System.IO.Path.GetFileName(x)).ToArray();
                    var allNames = string.Join(", ", names);

                    System.Windows.Forms.MessageBox.Show(string.Format("Folgende Zeichnungen konnen nicht gespeichert werden: {0}", allNames), "Plan2ReplaceInLayoutNamesBulk");
                }

                ShowResultMessage(dirName.ToUpperInvariant());
            }
            catch (System.Exception ex)
            {
                string msg = string.Format(CultureInfo.CurrentCulture, "{0}", ex.Message);
                System.Windows.Forms.MessageBox.Show(msg, "Plan2ReplaceInLayoutNamesBulk");
            }
        }
示例#48
0
 /// <summary>
 /// 将指定的字符串信息写入日志。
 /// </summary>
 /// <param name="message">需要写入日志的字符串信息。</param>
 public static void Log(string message)
 {
     log.Info(message);
 }
        protected void LoginButton_Click(object sender, EventArgs e)
        {
            logger = log4net.LogManager.GetLogger("LogInFile");

            HttpCookie cookie = new HttpCookie("blocoMorador");
            cookie.Value = drpBloco.SelectedItem.Text;
            cookie.Expires = DateTime.Now.AddDays(365); this.Page.Response.AppendCookie(cookie);
            Response.Cookies.Add(cookie);

            Session.Clear();

            oAPmodel.apartamento = Convert.ToInt32(txtAP.Text);
            oAPmodel.bloco = Convert.ToInt32(drpBloco.Text);
            oProprietarioModel.senha = Password.Text;

            Session["AP"] = Convert.ToInt32(txtAP.Text);
            Session["Bloco"] = Convert.ToInt32(drpBloco.Text);

            int valida = oProprietario.autenticaMorador(oAPmodel, oProprietarioModel);

            if (valida != 0)
            {

                foreach (var item in oProprietario.populaProprietario(oAPmodel, oProprietarioModel))
                {
                    Session["AP"] = item.ap.apartamento;
                    Session["Bloco"] = item.ap.bloco;
                    Session["Proprie1"] = item.proprietario1.ToString();
                    Session["Proprie2"] = item.proprietario2.ToString();
                    if (item.email != null)
                        Session["email"] = item.email.ToString();

                    //  Session["senha"] = item.senha.ToString();
                }

                if (Session["AP"].ToString() == "0" && Session["Bloco"].ToString() == "0")
                {
                    Response.Redirect("WelcomeAdmin.aspx");
                }
                else
                {

                    if (Session["AP"].ToString() != "301" && Session["Bloco"].ToString() != "6")
                    {
                        Util.SendMail oEmail = new SendMail();
                        oEmail.enviaSenha("Acesso feito com sucesso para o apartamento/bloco " + Session["AP"].ToString() + " - " + Session["Bloco"].ToString(), "Acessos", "*****@*****.**", 0);
                        logger.Info("Acesso feito com sucesso para o apartamento/bloco " + Session["AP"].ToString() + " - " + Session["Bloco"].ToString());
                        Response.Redirect("~/paginaInicialMoradores.aspx");
                    }
                    else
                    {
                        Response.Redirect("~/paginaInicialMoradores.aspx");
                        logger.Warn("Acesso negado!");
                    }

                }
            }
            else
            {
                FailureText.Text = "Número do Apartamento ou senha inválida";
                Session.Clear();
            }
        }
示例#50
0
        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.GetObjectsByName <GameNPC>("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");
            }
        }
        public Pension GetPensioner(PensionerInput pensionerInput)
        {
            _log4net.Info("PensionDetail post method is invoked for aadhaar" + pensionerInput.AadhaarNo);

            return(repo.GetPension(pensionerInput));
        }
示例#52
0
        public DriverBase()
        {
            // Set up logging - will participate in the standard toolkit log
            log = log4net.LogManager.GetLogger("KaiTrade");

            wireLog = log4net.LogManager.GetLogger("KaiTradeWireLog");
            driverLog = log4net.LogManager.GetLogger("KaiDriverLog");

            _state = new DriverState();
            _facade = AppFacade.Instance();

            _clOrdIDOrderMap = new Dictionary<string, OrderContext>();
            _apiIDOrderMap = new Dictionary<string, OrderContext>();
            _pXContexts = new Dictionary<string, PXUpdateContext>();

            _clients = new List<KaiTrade.Interfaces.IClient>();
            _publisherRegister = new Dictionary<string, KaiTrade.Interfaces.IPublisher>();
            _productGenericNameRegister = new Dictionary<string, string>();
            _productRegister = new Dictionary<string, KaiTrade.Interfaces.IProduct>();
            _externalProduct = new Dictionary<string, object>();
            _sessions = new Dictionary<string, IDriverSession>();
            _priceAgregators = new Dictionary<string, List<IPriceAgregator>>();
            _identity = System.Guid.NewGuid().ToString();

            // setup the components info - used on status messages
            SetComponentInfo(out _module, this, this.m_ID, "DriverManager", 0, "");

            // creat a last status object - used to report status when requested
            _lastStatus = new K2DataObjects.Message();

            _lastStatus.Label = "Status";
            _lastStatus.Data = "Loaded";
            _lastStatus.AppState = (int)KaiTrade.Interfaces.Status.loaded;
            _activeContextMap = new Dictionary<string, OrderContext>();
            _runningState = new DriverStatus();


            log.Info("MainMessageHandler Created");

            pxUpdates = new BlockingCollection<KaiTrade.Interfaces.IPXUpdate>();
            _pxUpdateProcessor = new PxUpdateProcessor(this, pxUpdates);
            _pXUpdateThread = new Thread(_pxUpdateProcessor.ThreadRun);
            _pXUpdateThread.Start();

            replaceRequests = new BlockingCollection<RequestData>();
            _replaceProcessor = new OrderReplaceProcessor(this, replaceRequests);
            _replaceUpdateThread = new Thread(_replaceProcessor.ThreadRun);
            _replaceUpdateThread.Start();

            //private BlockingCollection<List<KaiTrade.Interfaces.IDOMSlot>> slotUpdates;
            inboundMessages = new BlockingCollection<KaiTrade.Interfaces.IMessage>();      
            _inboundProcessor = new MessageProcessorThread(this, inboundMessages);
            _inboundProcessorThread = new Thread(_inboundProcessor.ThreadRun);
            _inboundProcessorThread.Start();

            outboundMessages = new BlockingCollection<KaiTrade.Interfaces.IMessage>();
            _outboundProcessor = new MessageProcessorThread(ref _clients, outboundMessages);
            _outboundProcessorThread = new Thread(_outboundProcessor.ThreadRun);
            _outboundProcessorThread.Start();

        }
 public ActionResult InsertarRegla(InsertReglasParams parametersIR)
 {
     try
     {
         parametersIR.CREATED_BY = HttpContext.User.Identity.Name;
         logger.Info(new { parametersIR });
         var rpt = Bll.InsertarRegla(parametersIR);
         logger.Info(new { rpt });
         return(Json(new { data = rpt }, JsonRequestBehavior.AllowGet));
     }
     catch (Exception ex)
     {
         logger.Error(new { ex });
         throw;
     }
 }
示例#54
0
 /// <summary>
 /// Initialize a new Minecraft client.
 /// </summary>
 /// <param name="server">The server to connect to.</param>
 /// <param name="player">The player who logged in with the client.</param>
 public Client(Server server, Player player)
 {
     _log = LogManager.GetLogger(this);
     _log.Debug("Minecraft Client created!");
     _server = server;
     _log.Debug("Loading Items from file...");
     try
     {
         using (var reader = new StreamReader(Constants.MinecraftItemFile))
             Items = new JsonSerializer().Deserialize<List<Item>>(new JsonTextReader(reader));
     }
     catch(IOException ex)
     {
         _log.Error("Failed to read item list from file!");
         _log.Error(ex.GetType() + ": " + ex.Message);
         _log.Error("Stack Trace:\n" + ex.StackTrace);
         throw new Exception("Sharpcraft.Library.Minecraft.Client failed to initialize! Could not read item list file!", ex);
     }
     _log.Debug("Creating communication protocol...");
     _protocol = new Protocol(_server.Address, _server.Port);
     _log.Info("Client initiated on " + _server.Address + ":" + _server.Port + "!");
     _player = player;
     _world = new World();
 }
示例#55
0
        /// <summary>
        /// Initializes the <c>SteamManager</c>.
        /// This MUST be called before other Steam operations are executed.
        /// </summary>
        /// <returns><c>true</c> if everything initialized properly, <c>false</c> otherwise.</returns>
        public static bool Init()
        {
            if (Enabled)
            {
                _log.Warn("Tried to call Init method when SteamManager has already been initialized! Aborting...");
                return false;
            }
            _log = LogManager.GetLogger(typeof(SteamManager));
            try
            {
                if (!Steamworks.Load())
                {
                    _log.Error("Steamworks failed to load, throwing exception!");
                    throw new SteamException("Steamworks failed to load.", SteamExceptionType.SteamworksLoadFail);
                }

                Client = Steamworks.CreateInterface<ISteamClient010>("SteamClient010");
                if (Client == null)
                {
                    _log.Error("Steamclient is NULL!! Throwing exception!");
                    throw new SteamException("Steamclient failed to load! Is the client running? (Sharpcraft.Steam.SteamManager.Client == null!)",
                                             SteamExceptionType.SteamLoadFail);
                }

                Pipe = Client.CreateSteamPipe();
                User = Client.ConnectToGlobalUser(Pipe);

                Friends = Steamworks.CastInterface<ISteamFriends002>(Client.GetISteamFriends(User, Pipe, "SteamFriends002"));

                if (Friends == null)
                    return false;

                FriendList = new SteamFriendList();

                _steamWatcher = new Timer(SteamCheck, null, 0, 1000);
            }
            catch (SteamException ex)
            {
                _log.Warn("Warning! SteamManager caught a SteamException exception, returning FALSE. Steam components will NOT LOAD!");
                _log.Warn("The SteamException type was: " + System.Enum.GetName(typeof(SteamExceptionType), ex.Type));
                return false;
            }
            _log.Info("SteamManager has been initialized!");
            SteamLoaded = true;
            Enabled = true;
            return true;
        }
示例#56
0
 /// <summary>
 /// 提示信息
 /// </summary>
 /// <param name="info">错误信息</param>
 public static void LogInfo(string info)
 {
     logger.Info(info);
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                log.Info("Page load Started");
                if (!IsPostBack && HiddenField1.Value != "loaded")
                {
                    log.Info("Page load 3");
                    string param     = Request.QueryString["rp"];
                    string export    = Request.QueryString["export"];
                    Guid   requestID = new Guid(Request.QueryString["r"]);

                    /*var data = getResponse(requestID.ToString());
                     * log.Info("Page load 4" + data);
                     * if (data == "") return;
                     * JObject jsonObj = JObject.Parse(data);
                     * string fileName = jsonObj["FileName"].Value<string>();*/

                    string fileName = getResponseSQL(requestID.ToString());
                    if (fileName == null || fileName == "")
                    {
                        fileName = "";
                    }
                    string userid = Request.QueryString["userid"];
                    if (userid == null || userid == "")
                    {
                        userid = "0";
                    }
                    log.Info("Page load 5" + userid);
                    string reportServerUser     = ConfigurationManager.AppSettings["ReportServerUser"];
                    string reportServerPassword = ConfigurationManager.AppSettings["ReportServerPassword"];
                    string reportServerDomain   = ConfigurationManager.AppSettings["ReportServerDomain"];
                    string reportPath           = ConfigurationManager.AppSettings["ReportServerPath"];
                    log.Info("Page load 6" + reportPath);

                    IReportServerCredentials irsc = new CustomReportCredentials(reportServerUser, reportServerPassword, reportServerDomain);
                    log.Info("Page load 7" + irsc.ToString());
                    mainReportViewer.ServerReport.ReportServerCredentials = irsc;
                    mainReportViewer.ServerReport.ReportServerUrl         =
                        new Uri(ConfigurationManager.AppSettings["ReportServerUrl"]);
                    mainReportViewer.ServerReport.ReportPath =
                        string.Format(ConfigurationManager.AppSettings["ReportPath"], reportPath.Substring(1) + "/" + fileName);
                    mainReportViewer.ProcessingMode = ProcessingMode.Remote;
                    log.Info("Page load 8" + mainReportViewer.ServerReport.ReportPath.ToString());

                    // Set the report parameters for the report
                    if (param != null)
                    {
                        Dictionary <string, string> reportParams = JsonConvert.DeserializeObject <Dictionary <string, string> >(param);
                        if (reportParams.Count > 0)
                        {
                            ReportParameter[] reportParameter = new ReportParameter[reportParams.Count];

                            int iLoop = 0;
                            foreach (var para in reportParams)
                            {
                                reportParameter[iLoop] = new ReportParameter(para.Key.ToString(), para.Value.ToString());
                                iLoop++;
                            }

                            if (iLoop > 0)
                            {
                                mainReportViewer.ServerReport.SetParameters(reportParameter);
                            }
                            log.Info("Page load 9" + iLoop);
                        }
                    }

                    try
                    {
                        mainReportViewer.ServerReport.SetParameters(new ReportParameter("path", reportPath));
                        mainReportViewer.ServerReport.SetParameters(new ReportParameter("pam_UserId", userid));
                    }
                    catch (Exception exc)
                    {
                        log.Error(exc.Message, exc);
                    }

                    mainReportViewer.ServerReport.Refresh();
                    HiddenField1.Value = "loaded";
                    if (export == "true")
                    {
                        string title = Request.QueryString["title"];
                        CreateWord(mainReportViewer, title);
                    }
                }
            }
            catch (Exception exc)
            {
                log.Error(exc.Message, exc);
            }
        }