示例#1
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;
         }
      }
示例#2
0
        /// <summary>
        /// 监听 "__InstanceCreationEvent" AND "__InstanceDeletionEvent" 事件
        /// <para>示例:$"TargetInstance ISA 'Win32_PnPEntity'"    //监听即插即用设备状态,有关 Win32_PnPEntity(WMI类) 属性参考:https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-pnpentity </para>
        /// <para>示例:$"TargetInstance ISA 'Win32_PnPEntity' AND TargetInstance.Name LIKE '%({Serial.PortName})'"    //监听即插即用设备状态,且名称为串口名称</para>
        /// <para>示例:$"TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType = 2 OR TargetInstance.DriveType = 4"  //监听移动硬盘状态 </para>
        /// <para>更多 WMI 类,请参考:https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/computer-system-hardware-classes </para>
        /// </summary>
        /// <param name="wql_condition">WQL 条件语句,关于 WQL 参考:https://docs.microsoft.com/zh-cn/windows/win32/wmisdk/wql-sql-for-wmi?redirectedfrom=MSDN </param>
        /// <param name="changedCallback"></param>
        /// <param name="Log"></param>
        public static void ListenInstanceChange(String wql_condition, Action <ManagementBaseObject> changedCallback, log4net.ILog Log = null)
        {
            if (InstanceCreationEvent != null || InstanceDeletionEvent != null)
            {
                return;
            }
            ManagementScope scope = new ManagementScope(@"\\.\Root\CIMV2", new ConnectionOptions()
            {
                //Username = "",
                //Password = "",
                EnablePrivileges = true,
            });

            TimeSpan interval = new TimeSpan(0, 0, 1);

            //__InstanceCreationEvent
            InstanceCreationEvent = new ManagementEventWatcher(scope, new WqlEventQuery("__InstanceCreationEvent", interval, wql_condition));
            InstanceCreationEvent.EventArrived += (s, e) =>
            {
                Log?.InfoFormat("Instance Creation Event :: {0}", e.NewEvent.ClassPath);
                changedCallback?.Invoke(e.NewEvent);
            };

            //__InstanceDeletionEvent
            InstanceDeletionEvent = new ManagementEventWatcher(scope, new WqlEventQuery("__InstanceDeletionEvent", interval, wql_condition));
            InstanceDeletionEvent.EventArrived += (s, e) =>
            {
                Log?.InfoFormat("Instance Deletion Event :: {0}", e.NewEvent.ClassPath);
                changedCallback?.Invoke(e.NewEvent);
            };

            InstanceCreationEvent.Start();
            InstanceDeletionEvent.Start();
        }
示例#3
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();
        }
        static void Main()
        {
            const string format = "This is a [{0}] level logging event";

            log.DebugFormat(format, "Debug");
            log.InfoFormat(format, "Info");
            log.WarnFormat(format, "Warn");
            log.ErrorFormat(format, "Error");
            log.FatalFormat(format, "Fatal");

            var logger = new OtherLogger();

            logger.LogThings();

            Console.ReadLine();
        }
示例#5
0
        private GameManager()
        {
            if (!log4net.LogManager.GetRepository().Configured)
            {
                using (var reader = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(Properties.Resources.test_logging_config)))
                    log4net.Config.XmlConfigurator.Configure(reader);

                logger.InfoFormat("{0}{0}{1}{0}BEGINS LOG ON GAME MANAGER CREATION{0}{1}{0}{0}", Environment.NewLine, new String('*', 40));
            }

            if (Properties.Settings.Default.UseDefaultTypeRegistry)
            {
                using (var mem_stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(Properties.Resources.TypeRegistry)))
                {
                    var register = TypeRegister.Load(mem_stream);
                    this.RegisterTypeRegister(register, true);
                }
                logger.Info("Initialized TypeRegister with default template");
            }

            switch (Properties.Settings.Default.ScreenToUse)
            {
            case "TextScreen":
                logger.Info("Starting Text Console as IScreen");
                this.RegisterTypeEntry <IScreen, Controls.TextScreen>(new Controls.TextScreen(), true, true);
                break;

            case "GraphicalScreen":
                logger.Info("Starting GraphicalScreen as IScreen");
                this.RegisterTypeEntry <IScreen, Controls.GraphicalScreen>(new Controls.GraphicalScreen(), true, true);
                break;

            default:
                logger.Warn("NO SCREEN SELECTED - using dummy screen");
                this.RegisterTypeEntry <IScreen, DummyScreen>(new DummyScreen(), true, true);
                break;
            }

            logger.Info("GameManager instance created");
        }
示例#6
0
        protected void NavigateTo(Stage stage)
        {
            log.InfoFormat("Navigate to {0}", stage);
            if (onStageChanged != null)
            {
                onStageChanged(this, new Navigate2Args(stage));
            }
            ListBox lstBox = GetListBox();

            if (lstBox == null)
            {
                return;
            }

            lstBox.SelectedIndex = (int)stage;
        }
示例#7
0
        /// <summary>
        /// Performs the installation in the Castle.Windsor.IWindsorContainer.
        /// </summary>
        /// <param name="container"></param>
        /// <param name="store"></param>
        void IWindsorInstaller.Install(IWindsorContainer container,
                                       IConfigurationStore store)
        {
            Logger.InfoFormat("Registering Files.Module");

            try
            {
                container.Register(Component.For <InstallModule>());
                var modul = container.Resolve <InstallModule>();
                modul.Initialize();
            }
            catch (System.Exception exp)
            {
                Logger.Error(exp);
            }
        }
示例#8
0
 private bool HasModi()
 {
     try {
         using (Process process = Process.Start(_ocrCommand, "-c")) {
             if (process != null)
             {
                 process.WaitForExit();
                 return(process.ExitCode == 0);
             }
         }
     } catch (Exception e) {
         Log.DebugFormat("Error trying to initiate MODI: {0}", e.Message);
     }
     Log.InfoFormat("No Microsoft Office Document Imaging (MODI) found, disabling OCR");
     return(false);
 }
示例#9
0
        /// <summary>
        /// Logins the specified player.
        /// </summary>
        /// <param name="player">The player.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        public void Login(Player player, string username, string password)
        {
            Account account = null;

            try
            {
                account = player.PersistenceContext.GetAccountByLoginName(username, password);
            }
            catch (Exception ex)
            {
                Log.Error("Login Failed.", ex);
            }

            if (account != null)
            {
                if (account.State == AccountState.Banned)
                {
                    player.PlayerView.ShowLoginResult(LoginResult.AccountBlocked);
                }
                else if (account.State == AccountState.TemporarilyBanned)
                {
                    player.PlayerView.ShowLoginResult(LoginResult.TemporaryBlocked);
                }
                else
                {
                    using (var context = player.PlayerState.TryBeginAdvanceTo(PlayerState.Authenticated))
                    {
                        if (context.Allowed && this.gameServerContext.LoginServer.TryLogin(username, this.gameServerContext.Id))
                        {
                            player.Account = account;
                            Log.DebugFormat("Login successful, username: [{0}]", username);
                            player.PlayerView.ShowLoginResult(LoginResult.OK);
                        }
                        else
                        {
                            context.Allowed = false;
                            player.PlayerView.ShowLoginResult(LoginResult.AccountAlreadyConnected);
                        }
                    }
                }
            }
            else
            {
                Log.InfoFormat($"Account not found or invalid password, username: [{username}]");
                player.PlayerView.ShowLoginResult(LoginResult.InvalidPassword);
            }
        }
示例#10
0
        public Track GetTrack(FileInfo audioFile)
        {
            log.InfoFormat("Read meta information from {0}", audioFile);
            var track = new Track {
                Path = audioFile.FullName
            };

            try
            {
                using (var f = TagLib.File.Create(audioFile.FullName))
                {
                    track.Duration = f.Properties.Duration;
                    if (!f.Tag.IsEmpty)
                    {
                        track.Title       = f.Tag.Title;
                        track.TrackNumber = f.Tag.Track;
                        track.Album       = f.Tag.Album;
                        track.Artists     = f.Tag.AlbumArtists.Concat(f.Tag.Performers).ToArray();
                    }
                }
            }
            catch (Exception ex)
            {
                log.Warn(String.Format("Exception ignored while reading {0}", audioFile), ex);
            }

            if (track.Artists == null)
            {
                track.Artists = new string[] { };
            }
            if (String.IsNullOrEmpty(track.Title))
            {
                track.Title = System.IO.Path.GetFileNameWithoutExtension(track.Path);
            }

            if (String.IsNullOrEmpty(track.Album))
            {
                track.Album = System.IO.Path.GetFileName(System.IO.Path.GetDirectoryName(track.Path));
            }

            if (track.TrackNumber == 0)
            {
                track.TrackNumber = GetDirectoryIndex(track.Path);
            }

            return(track);
        }
示例#11
0
        private void generateForSample(SampleInfo sampleInfo)
        {
            string sOutput = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\output\\";

            //create folders
            if (!Directory.Exists(sOutput))
            {
                Directory.CreateDirectory(sOutput);
            }


            sOutput = sOutput + "\\" + sampleInfo.ID.ToString() + "\\";
            if (!Directory.Exists(sOutput))
            {
                Directory.CreateDirectory(sOutput);
            }


            double r    = pipettingSetting.r_mm;
            double area = 3.14159265 * r * r;
            double volumeBloodPlasma = Math.Abs((sampleInfo.Z1 - sampleInfo.Z2) * area);   //ul

            Write2File(sOutput + "plasmaDstSliceCount.txt", sampleInfo.bloodPlasmaSlice.ToString());
            Write2File(sOutput + "buffyDstSliceCount.txt", sampleInfo.buffyCoatSlice.ToString());
            Write2File(sOutput + "buffyLayerCount.txt", pipettingSetting.buffyAspirateLayers.ToString());
            Write2File(sOutput + "plasmaEachVolume.txt", (volumeBloodPlasma / sampleInfo.bloodPlasmaSlice).ToString());
            Write2File(sOutput + "eachLayerPointCount.txt", pipettingSetting.pointsCount.ToString());
            Write2File(sOutput + "Z1.txt", sampleInfo.Z1.ToString());
            Write2File(sOutput + "Z2.txt", sampleInfo.Z2.ToString());
            using (StreamWriter sw = new StreamWriter(sOutput + "xyMoves.txt"))
            {
                List <POINT> pts = GenerateAspiratePts(r);
                //for each layer, move x,y then aspirate, then move z
                for (int layer = 0; layer < sampleInfo.buffyCoatSlice; layer++)
                {
                    //bool needDispense = (layer + 1) % (sampleInfo.buffyCoatSlice / 2) == 0;
                    foreach (POINT pt in pts)
                    {
                        log.InfoFormat("Pt position is:{0} , {1} ", pt.x, pt.y);
                        if (layer == 0)
                        {
                            sw.WriteLine(string.Format("{0},{1}", (int)pt.x, (int)pt.y));
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Sync a users free busy information between Google Calendar and the
        /// SchedulePlus Public Folder store
        /// </summary>
        /// <param name="user">The user to synchronize</param>
        /// <param name="googleAppsFeed">The Google Calendar events for the user</param>
        /// <param name="exchangeGateway">The Exchange Gateway to use</param>
        /// <param name="window">The DateTimeRange to synchronize for</param>
        public void SyncUser(
            ExchangeUser user,
            EventFeed googleAppsFeed,
            ExchangeService exchangeGateway,
            DateTimeRange window)
        {
            if (_log.IsInfoEnabled)
            {
                _log.InfoFormat("Creating F/B message.  [User={0}]", user.Email);
                _log.DebugFormat("The feed time zone is {0}", googleAppsFeed.TimeZone.Value);
            }

            string userFreeBusyUrl = FreeBusyUrl.GenerateUrlFromDN(_exchangeServerUrl,
                                                                   user.LegacyExchangeDN);

            List <string> busyMonthValues      = new List <string>();
            List <string> busyBase64Data       = new List <string>();
            List <string> tentativeMonthValues = new List <string>();
            List <string> tentativeBase64Data  = new List <string>();

            ConvertEventsToFreeBusy(user,
                                    googleAppsFeed.Entries,
                                    window,
                                    busyMonthValues,
                                    busyBase64Data,
                                    tentativeMonthValues,
                                    tentativeBase64Data);



            string startDate = FreeBusyConverter.ConvertToSysTime(window.Start).ToString();
            string endDate   = FreeBusyConverter.ConvertToSysTime(window.End).ToString();

            exchangeGateway.FreeBusy.CreateFreeBusyMessage(userFreeBusyUrl,
                                                           user.FreeBusyCommonName,
                                                           busyMonthValues,
                                                           busyBase64Data,
                                                           tentativeMonthValues,
                                                           tentativeBase64Data,
                                                           startDate,
                                                           endDate);

            if (_log.IsInfoEnabled)
            {
                _log.Info("Free/Busy message with the right properties created successfully.");
            }
        }
示例#13
0
        /// <summary>
        /// Upload the capture to imgur
        /// </summary>
        /// <param name="captureDetails"></param>
        /// <param name="image"></param>
        /// <param name="uploadURL">out string for the url</param>
        /// <returns>true if the upload succeeded</returns>
        public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadURL)
        {
            SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(config.UploadFormat, config.UploadJpegQuality, config.UploadReduceColors);

            try {
                string    filename  = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails));
                ImgurInfo imgurInfo = null;

                // Run upload in the background
                new PleaseWaitForm().ShowAndWait("Imgur plug-in", Language.GetString("imgur", LangKey.communication_wait),
                                                 delegate() {
                    imgurInfo = ImgurUtils.UploadToImgur(surfaceToUpload, outputSettings, captureDetails.Title, filename);
                    LOG.InfoFormat("Storing imgur upload for hash {0} and delete hash {1}", imgurInfo.Hash, imgurInfo.DeleteHash);
                    config.ImgurUploadHistory.Add(imgurInfo.Hash, imgurInfo.DeleteHash);
                    config.runtimeImgurHistory.Add(imgurInfo.Hash, imgurInfo);
                    CheckHistory();
                }
                                                 );

                // TODO: Optimize a second call for export
                using (Image tmpImage = surfaceToUpload.GetImageForExport()) {
                    imgurInfo.Image = ImageHelper.CreateThumbnail(tmpImage, 90, 90);
                }
                IniConfig.Save();
                uploadURL = null;
                try {
                    if (config.UsePageLink)
                    {
                        uploadURL = imgurInfo.Page;
                        ClipboardHelper.SetClipboardData(imgurInfo.Page);
                    }
                    else
                    {
                        uploadURL = imgurInfo.Original;
                        ClipboardHelper.SetClipboardData(imgurInfo.Original);
                    }
                } catch (Exception ex) {
                    LOG.Error("Can't write to clipboard: ", ex);
                }
                return(true);
            } catch (Exception e) {
                LOG.Error(e);
                MessageBox.Show(Language.GetString("imgur", LangKey.upload_failure) + " " + e.Message);
            }
            uploadURL = null;
            return(false);
        }
示例#14
0
        public static int OptimizeAllBuffers(Db4oMessageBufferOptimizationTypes opts)
        {
            DateTime start = DateTime.UtcNow, stop;
            var      dbPath  = Platform.GetBuffersBasePath();
            var      dbFiles = Directory.GetFiles(dbPath, "*.db4o",
                                                  SearchOption.AllDirectories);

            foreach (var dbFile in dbFiles)
            {
#if LOG4NET
                Logger.Info(String.Format(_("Optimizing: {0}..."), dbFile));
#endif
                try {
                    using (var buffer = new Db4oMessageBuffer(dbFile)) {
                        buffer.AggressiveGC = false;
                        if ((opts & Db4oMessageBufferOptimizationTypes.Defrag) != 0)
                        {
                            buffer.CloseDatabase();
                            buffer.DefragDatabase();
                            buffer.InitDatabase();
                        }
                        if ((opts & Db4oMessageBufferOptimizationTypes.Index) != 0)
                        {
                            buffer.RebuildIndex();
                        }
                    }
                } catch (Exception ex) {
#if LOG4NET
                    Logger.Debug("OptimizeAllBuffers(): Failed to optimize: " +
                                 dbFile + " Exception: ", ex);
                    Logger.InfoFormat(_("Failed to optimize: {0}. Reason: {1}"),
                                      dbFile, ex.Message);
#endif
                }
            }
            stop = DateTime.UtcNow;
#if LOG4NET
            Logger.Debug(
                String.Format(
                    "OptimizeAllBuffers(): optimizing buffers took: {0:0} second(s)",
                    (stop - start).TotalSeconds
                    )
                );
#endif
            return(dbFiles.Length);
        }
 public static void SaveChanges()
 {
     try
     {
         log.InfoFormat("save HypervisorInfo changes into xml: {0}", FilePath);
         Root.Save(FilePath);
     }
     catch (Exception e)
     {
         log.Error("error occur while save HypervisorInfo into xml", e);
         Application.Current.Dispatcher.BeginInvoke(new Action(() =>
         {
             MessageBox.Show("Please remove the Readonly property for the file" + FilePath + "And Try to re-open This App", "Error", MessageBoxButton.OK);
             Application.Current.Shutdown();
         }));
     }
 }
示例#16
0
        public ActionResult SendSmsCode(string forgetPhoneNum)
        {
            if (forgetPhoneNum != (string)Session["forgetPhoneNum"])
            {
                return(Json(new AjaxResult {
                    Status = "error", Msg = "手机号码与输入的不一致!"
                }));
            }
            int smsCode = new Random().Next(1000, 9999);

            TempData["smsCode"] = smsCode;
            log.InfoFormat("短信验证码是{0}", smsCode);
            return(Json(new AjaxResult
            {
                Status = "ok"
            }));
        }
示例#17
0
 public static BindingList <DocumentArchive> GetCustomerArchivesByUsername(string userName)
 {
     logger.InfoFormat("username {0}", userName);
     try
     {
         return(DbProvider.GetCustomerArchives(string.Empty, userName));
     }
     catch (Exception ex)
     {
         logger.Error(ex);
         throw;
     }
     finally
     {
         logger.Info("END");
     }
 }
示例#18
0
        public void ProcessStock(Connector connector, log4net.ILog log, XDocument products)
        {
            DateTime start = DateTime.Now;

            log.InfoFormat("Start process stock:{0}", start);
            AssortmentServiceSoapClient soap = new AssortmentServiceSoapClient();

            if (products == null)
            {
                products = new XDocument(soap.GetAssortment(connector.ConnectorID, null, false));
            }

            log.Info(products.Root.Elements("Product").Count());

            ImportStock(connector, products, log);       // DC10 Stock naar winkels
            ImportRetailStock(connector, products, log); // Overige winkels naar winkel
        }
示例#19
0
        protected void ComputeCostOfGetTimestamp()
        {
            long  startTime           = Stopwatch.GetTimestamp();
            float microsecondsPerTick = 1000000.0f / (float)Stopwatch.Frequency;
            int   cycles = 10000;

            for (int i = 0; i < cycles; i++)
            {
                Stopwatch.GetTimestamp();
            }
            long  ticks      = Stopwatch.GetTimestamp() - startTime;
            float totalUsecs = ((float)ticks) * microsecondsPerTick;

            costOfGetTimestamp = totalUsecs / (float)cycles;
            log.InfoFormat("MeterManager.ComputeCostOfGetTimestamp: Getting timestamp costs {0} usecs", costOfGetTimestamp);
            computedCostOfGetTimestamp = true;
        }
示例#20
0
        public static void SetVersion(string filePath, Version newVersion, bool writeToDisk)
        {
            var file     = ReadFile(filePath);
            var contents = file.Key;
            var encoding = file.Value;

            Logger.InfoFormat("File \"{0}\" has encoding {1}", filePath, encoding.EncodingName);

            contents = AssemblyRegex.Replace(contents, "${1}" + newVersion + "${3}");
            contents = InnoSetupVersionRegex.Replace(contents, "${1}" + newVersion + "${3}");
            contents = ArtifactFileNameRegex.Replace(contents, "${1}" + newVersion + "${3}");

            if (writeToDisk)
            {
                File.WriteAllText(filePath, contents, encoding);
            }
        }
示例#21
0
        public static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();

            for (int index = 0; index < 10; index++)
            {
                log.InfoFormat("Hello world \"{0}\"  \'\\\nHej", index + 1);
            }

            log.Info("Result string: ResponseStatus=SUCCESS&ResponseMessage=Success&ResponseTIBCount=1&TransactionID=&TransactionStatus=COMPLETED&TransactionResult=0&TransactionMessage=Approved&TransactionStartDate=Mon+Sep+19+17%3A35%3A13+PDT+2011&TransactionLastDate=Mon+Sep+19+17%3A35%3A13+PDT+2011&TransactionDuration=13&AccountID=1sfsdfasd3sfd1fs6sf4d7WJVDJIDL&ClientTransactionID=");
            System.Threading.Thread.Sleep(2000);

            Console.WriteLine("Closing down");

            log4net.LogManager.Shutdown();
            Console.ReadKey();
        }
        /// <summary>
        /// Loads all responders
        /// </summary>
        private void LoadResponders()
        {
            bot.Responders.Clear();

            foreach (string cls in cfg.Get("Common", "Responder", string.Empty).Split(new char[] { ';', ',' }))
            {
                try
                {
                    bot.Responders.Add((IResponder)Activator.CreateInstance(Type.GetType(cls), this));
                    logger.InfoFormat("Responder {0} loaded", cls);
                }
                catch (Exception eee)
                {
                    logger.Error("Error loading responder with name : " + cls + Environment.NewLine + eee.Message + Environment.NewLine + eee.StackTrace);
                }
            }
        }
示例#23
0
        public static void SaveAsExcel(string sCSVFile, string sExcelFile)
        {
            Workbooks excelWorkBooks = null;
            Workbook  excelWorkBook  = null;

            Application app = new Application();

            app.Visible       = false;
            app.DisplayAlerts = false;
            excelWorkBooks    = app.Workbooks;
            excelWorkBook     = ((Workbook)excelWorkBooks.Open(sCSVFile, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value));

            log.InfoFormat("excel path is :{0}", sExcelFile);
            excelWorkBook.SaveAs(sExcelFile, XlFileFormat.xlAddIn, Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            excelWorkBook.Close();
            app.Quit();
        }
示例#24
0
        /// <summary>
        /// 将应用程序设为或不设为开机启动
        /// </summary>
        /// <param name="onOff">自启开关</param>
        /// <param name="appName">应用程序名</param>
        /// <param name="appPath">应用程序完全路径</param>
        public static bool SetAutoStart(bool onOff, string appName, string appPath)
        {
            bool isOk = true;

            //如果从没有设为开机启动设置到要设为开机启动
            if (!IsExistKey(appName) && onOff)
            {
                isOk = SelfRunning(onOff, appName, @appPath);
            }
            //如果从设为开机启动设置到不要设为开机启动
            else if (IsExistKey(appName) && !onOff)
            {
                isOk = SelfRunning(onOff, appName, @appPath);
            }
            Logger.InfoFormat("设置:{0},目录:{1},状态:{2}", appName, appPath, onOff);
            return(isOk);
        }
示例#25
0
        public void REQSearchFiles(ServerInfo server, string pattern, string hashQuery)
        {
            log.InfoFormat("REQSearchFiles: {0}, {1}, {2}", server.ToString(), pattern, hashQuery);

            Connection conServer = new Connection(server.Name, new TcpClient(server.Ip, server.Port), new ReceiveEventHandler());

            /*  string[] payload = dato.Payload.Message.Split(new string[] { PIPE_SEPARATOR }, StringSplitOptions.None);
             * string login = payload[0];
             * string queryHash = payload[1];
             * string pattern = payload[2];
             *  */
            SendMessage(conServer, Command.REQ, OpCodeConstants.REQ_SEARCH_FILES,
                        new Payload()
            {
                Message = Login + "|" + hashQuery + "|" + pattern
            });
        }
示例#26
0
        static void Main(string[] args)
        {
            string url = "http://+:6666/";

            log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
            loginfo.InfoFormat("Server running on {0}", url);
            WebServer.WebApiApplication.Application_Start();
            using (WebApp.Start <Startup>(url))
            {
                Console.WriteLine("Server running on {0}", url);
                Console.ReadLine();
                while (true)
                {
                    Thread.Sleep(1440000); //a day
                }
            }
        }
示例#27
0
        protected void Handler(HttpListenerContext context)
        {
            HttpListenerRequest         request  = context.Request;
            HttpListenerResponse        response = context.Response;
            Dictionary <string, string> param    = new Dictionary <string, string>();

            try
            {
                switch (request.HttpMethod)
                {
                case "GET":
                    foreach (string key in request.QueryString.AllKeys)
                    {
                        param.Add(key, request.QueryString[key]);
                    }
                    break;

                case "POST":
                    Stream       stream  = context.Request.InputStream;
                    StreamReader reader  = new StreamReader(stream, Encoding.UTF8);
                    string       content = reader.ReadToEnd();
                    param = JsonConvert.DeserializeObject <Dictionary <string, string> >(content);
                    break;

                default:
                    throw new Exception("不支持的httpMethod=" + request.HttpMethod);
                }
                if (logger.IsInfoEnabled)
                {
                    logger.InfoFormat("HttpMethod={0},参数={1}", request.HttpMethod, JsonConvert.SerializeObject(param));
                }
                //处理逻辑
                Callback(param);

                Output(response, 100, "success!");
            }
            catch (Exception e)
            {
                Output(response, 500, e.Message);
                logger.Error("接收请求处理出错:", e);
            }
            finally
            {
                response.Close();
            }
        }
示例#28
0
        protected override bool OnSetActive()
        {
            if (!base.OnSetActive())
            {
                return(false);
            }

            string ip = "";

            ConnectManager.IPMaskGatewayDict.TryGetValue("ip", out ip);
            WinCenterLinkLabel.Text = winCenterLinkAddr = string.Format("https://{0}:8090/pc/index.jsp", ip);

            log.InfoFormat("进入【完成】页面");

            Wizard.SetWizardButtons(WizardButton.Finish);
            return(true);
        }
        private void ConfigThreadPool()
        {
            int minWorker;
            int minIO;

            System.Threading.ThreadPool.GetMinThreads(out minWorker, out minIO);

            minWorker = (int)StationRegistry.GetValue("MinWorkerThreads", minWorker);
            minIO     = (int)StationRegistry.GetValue("MinIOThreads", minIO);

            if (minWorker > 0 && minIO > 0)
            {
                System.Threading.ThreadPool.SetMinThreads(minWorker, minIO);
                logger.InfoFormat("Min worker threads {0}, min IO completion threads {1}",
                                  minWorker, minIO);
            }
        }
        /// <summary>
        /// Selects all values from the variable that is in the query by the value codes
        /// </summary>
        /// <param name="variable"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public static PCAxis.Paxiom.Selection SelectItem(Variable variable, Query query)
        {
            PCAxis.Paxiom.Selection s = new PCAxis.Paxiom.Selection(query.Code);
            s.ValueCodes.AddRange(
                variable.Values
                .Where(val => query.Selection.Values.Contains(val.Code))
                .Select(val => val.Code).ToArray());

            if (s.ValueCodes.Count != query.Selection.Values.Length)
            {
                //Error missmatch between the number of values
                _logger.InfoFormat("User requests some values that does not exist for variable {0}. Found {1} matching values of the {2} requested. Returning null.", variable.Code, s.ValueCodes.Count, query.Selection.Values.Length);
                return(null);
            }

            return(s);
        }
示例#31
0
 static void Main(string[] args)
 {
     log4net.Config.XmlConfigurator.Configure();
     log4net.ILog log = log4net.LogManager.GetLogger("test");
     while (true)
     {
         log.ErrorFormat("{0} test error!", "henryfan");
         System.Threading.Thread.Sleep(5000);
         log.InfoFormat("{0} test Info!", "henryfan");
         System.Threading.Thread.Sleep(5000);
         log.DebugFormat("{0} test Info!", "henryfan");
         System.Threading.Thread.Sleep(5000);
         log.FatalFormat("{0} test Info!", "henryfan");
         System.Threading.Thread.Sleep(5000);
     }
     Console.Read();
 }
示例#32
0
        static void Main()
        {
            log4net.Config.XmlConfigurator.Configure();
            log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));

            const string format = "This is a [{0}] level logging event";

            log.DebugFormat(format, "Debug");
            log.InfoFormat(format, "Info");
            log.WarnFormat(format, "Warn");
            log.ErrorFormat(format, "Error");
            log.FatalFormat(format, "Fatal");

            OtherLogger.LogThings();

            Console.ReadLine();
        }
示例#33
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);
            }
        }
示例#34
0
        static void Main(string[] args)
        {
            _log = log4net.LogManager.GetLogger(typeof(Program));

            //onetime stuff
            RadarHttpClient.DefaultRequestHeaders.Accept.Clear();
            RadarHttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //get directory from config
            //TODO: change this to read from config

            //NOTES:
            //file name is batch ID - use to retreive batch to assign details.
            // also use to determine company ID of sheet.

            var curDir = Directory.GetCurrentDirectory();

            _log.InfoFormat("running in {0}", curDir);

            var xlsxFiles = Directory.GetFiles(curDir, "*.xlsx");

            if (!xlsxFiles.Any())
            {
                _log.InfoFormat("No xlsx files found in {0}", curDir);
            }
            else
            {
                //go get column positions from DB.
                _prodTask = new UowPRODTask();
                _mapping = _prodTask.Template.GetAllWithInclude(t => t.TemplateMapping)
                    .Where(t => t.AuditStatusCode == Radar.Core.Common.Constants.StatusCode.Audit.ACTIVE)
                    .Select(t => t);

                foreach (var xlsxFile in xlsxFiles)
                {
                    processFile(xlsxFile);
                }
            }

            // import only supports XLSX files... right?

            Console.Write("Press <enter> key to exit");
            Console.ReadLine();
        }