コード例 #1
0
ファイル: App.xaml.cs プロジェクト: sarandogou/boghe
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            try
            {
                String log4net = String.Format(BogheApp.Properties.Resources.log4net_xml, Win32ServiceManager.SharedManager.ApplicationDataPath);
                using (Stream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(log4net)))
                {
                    XmlConfigurator.Configure(stream);
                    LOG = LogManager.GetLogger(typeof(App));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                this.Shutdown();
            }

            LOG.Debug("====================================================");
            LOG.Debug(String.Format("======Starting Boghe - IMS/RCS Client v{0} ====", System.Reflection.Assembly.GetEntryAssembly().GetName().Version));
            LOG.Debug("====================================================");

            //CultureInfo culture = new CultureInfo("fr-FR");
               // System.Threading.Thread.CurrentThread.CurrentCulture = culture;
               // System.Threading.Thread.CurrentThread.CurrentUICulture = culture;

            FrameworkElement.LanguageProperty.OverrideMetadata(
                typeof(FrameworkElement),
                new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

            if (!Win32ServiceManager.SharedManager.Start())
            {
                MessageBox.Show("Failed to start service manager");
                this.Shutdown();
            }
        }
コード例 #2
0
ファイル: App.xaml.cs プロジェクト: xolile/boghe
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            try
            {
                String log4net = String.Format(BogheApp.Properties.Resources.log4net_xml, Win32ServiceManager.SharedManager.ApplicationDataPath);
                using (Stream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(log4net)))
                {
                    XmlConfigurator.Configure(stream);
                    LOG = LogManager.GetLogger(typeof(App));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                this.Shutdown();
            }

            LOG.Debug("====================================================");
            LOG.Debug(String.Format("======Starting Boghe - IMS/RCS Client v{0} ====", System.Reflection.Assembly.GetEntryAssembly().GetName().Version));
            LOG.Debug("====================================================");

            if (!Win32ServiceManager.SharedManager.Start())
            {
                MessageBox.Show("Failed to start service manager");
                this.Shutdown();
            }
        }
コード例 #3
0
ファイル: HandleDatabase.cs プロジェクト: alpermazlum/try_git
 /// <summary>
 /// Default constructor
 /// </summary>
 public HandleDatabase() {
     this.log = LogManager.GetLogger(this.GetType());
     if (log.IsDebugEnabled) {
         log.Debug("HandleDatabase Starts");
     }
     _conn = new SqlConnection(_connectionPath);
     if (log.IsDebugEnabled) {
         log.Debug("HandleDatabase Ends");
     }
 }
コード例 #4
0
        public void ToLog(ILog log)
        {
            log.Debug("\tVersion: " + Version);
            log.Debug("\tPollIntervalSeconds: " + PollIntervalSeconds);
            log.Debug("\tCollectOnly: " + CollectOnly);
            log.Debug("\tSqlEndpoints: " + Endpoints.Length);

            foreach (var endpoint in Endpoints)
            {
                endpoint.Trace(log);
            }
        }
コード例 #5
0
ファイル: SagaExtensions.cs プロジェクト: ngbrown/EasyNetQ
        public static IEnumerable<ISaga> LogWith(this IEnumerable<ISaga> sagas, ILog log)
        {
            var sagaCount = 0;

            foreach (var saga in sagas)
            {
                sagaCount++;
                log.Debug(string.Format("Loading Saga: {0}", saga.GetType().FullName));
                yield return saga;
            }
            log.Debug(string.Format("Loaded {0} Sagas", sagaCount));
        }
コード例 #6
0
ファイル: BeaglePlugin.cs プロジェクト: snorp/tangerine
        public BeaglePlugin()
        {
            server = Daemon.Server;
            db = Daemon.DefaultDatabase;
            log = Daemon.Log;

            query = new Query ();
            query.AddDomain (QueryDomain.Neighborhood);
            query.MaxHits = 10000;

            QueryPart_Property filePart = new QueryPart_Property ();
            filePart.Type = PropertyType.Keyword;
            filePart.Key = "beagle:HitType";
            filePart.Value = "File";
            query.AddPart (filePart);

            QueryPart_Or queryUnion = new QueryPart_Or ();

            foreach (string mt in supportedMimeTypes) {
                QueryPart_Property part = new QueryPart_Property ();
                part.Type = PropertyType.Keyword;
                part.Key = "beagle:MimeType";
                part.Value = mt;
                queryUnion.Add (part);
            }

            query.AddPart (queryUnion);
            query.HitsAddedEvent += OnHitsAdded;
            query.HitsSubtractedEvent += OnHitsSubtracted;
            query.FinishedEvent += OnFinished;

            int attempts = 0;
            while (true) {
                try {
                    query.SendAsync ();
                    break;
                } catch (Exception e) {
                    if (attempts++ >= 5) {
                        log.Warn ("Failed to initialize beagle plugin");
                        query = null;
                        break;
                    }

                    // something bad happened, wait a sec and try again
                    log.Debug ("Sending query failed: " + e.Message);
                    log.Debug ("Waiting 3 seconds...");
                    Thread.Sleep (3000);
                }
            }
        }
コード例 #7
0
        public override void Trace(ILog log)
        {
            base.Trace(log);

            foreach (var database in IncludedDatabases)
            {
                log.Debug("\t\t\tIncluding: " + database.Name);
            }

            foreach (var database in ExcludedDatabaseNames)
            {
                log.Debug("\t\t\tExcluding: " + database);
            }
        }
コード例 #8
0
ファイル: ServoController.cs プロジェクト: yanatan16/RoboNUI
        /**
         * <summary>
         * Constructor with port name and open the port.
         * Also initializes servo channels to center
         * </summary>
         *
         * <param name="portName">Name of the serial port</param>
         * <param name="channels">Channels to center on construction</param>
         */
        protected MiniSSCIIServoController(string portName, ICollection<uint> channels)
        {
            log = LogManager.GetLogger(this.GetType());
            log.Debug(this.ToString() + " constructed.");

            activeChannels = channels;
            try
            {
                port = new SerialPort(portName);
                port.Open();
                port.BaudRate = 9600;
                port.NewLine = string.Empty + Convert.ToChar(13);
                port.Handshake = System.IO.Ports.Handshake.None;
                port.BaseStream.Flush();

                port.ReadTimeout = 1000;
                inactive = false;

                foreach (uint ch in channels)
                {
                    ServoMovementCommand smc = new ServoMovementCommand(ch, 128);
                    sendCommand(smc);
                }
                log.Info("Initiating all servos to center.");
            }
            catch (IOException ex)
            {
                log.Error("Could not open Servo Controller Port on " + portName, ex);
                inactive = true;
            }
        }
コード例 #9
0
        public InDatabaseRegionRepository(PDSDatabase context)
        {
            _context = context;

            logger = LogManager.GetLogger(typeof(InDatabaseRegionRepository));
            logger.Debug("Initialisiert");
        }
コード例 #10
0
ファイル: Bot.cs プロジェクト: mar5/Dota2LobbyDump
        /// <summary>
        ///     Setup a new bot with some details.
        /// </summary>
        /// <param name="details"></param>
        /// <param name="extensions">any extensions you want on the state machine.</param>
        public LobbyBot(SteamUser.LogOnDetails details, params IExtension<States, Events>[] extensions)
        {
            reconnect = true;
            this.details = details;

            log = LogManager.GetLogger("LobbyBot " + details.Username);
            log.Debug("Initializing a new LobbyBot, username: " + details.Username);
            reconnectTimer.Elapsed += (sender, args) =>
            {
                reconnectTimer.Stop();
                fsm.Fire(Events.AttemptReconnect);
            };
            fsm = new ActiveStateMachine<States, Events>();
            foreach (var ext in extensions) fsm.AddExtension(ext);
            fsm.DefineHierarchyOn(States.Connecting)
                .WithHistoryType(HistoryType.None);
            fsm.DefineHierarchyOn(States.Connected)
                .WithHistoryType(HistoryType.None)
                .WithInitialSubState(States.Dota);
            fsm.DefineHierarchyOn(States.Dota)
                .WithHistoryType(HistoryType.None)
                .WithInitialSubState(States.DotaConnect)
                .WithSubState(States.DotaMenu)
                .WithSubState(States.DotaLobby);
            fsm.DefineHierarchyOn(States.Disconnected)
                .WithHistoryType(HistoryType.None)
                .WithInitialSubState(States.DisconnectNoRetry)
                .WithSubState(States.DisconnectRetry);
            fsm.DefineHierarchyOn(States.DotaLobby)
                .WithHistoryType(HistoryType.None);
            fsm.In(States.Connecting)
                .ExecuteOnEntry(InitAndConnect)
                .On(Events.Connected).Goto(States.Connected)
                .On(Events.Disconnected).Goto(States.DisconnectRetry)
                .On(Events.LogonFailSteamDown).Execute(SteamIsDown)
                .On(Events.LogonFailSteamGuard).Goto(States.DisconnectNoRetry) //.Execute(() => reconnect = false)
                .On(Events.LogonFailBadCreds).Goto(States.DisconnectNoRetry);
            fsm.In(States.Connected)
                .ExecuteOnExit(DisconnectAndCleanup)
                .On(Events.Disconnected).If(ShouldReconnect).Goto(States.Connecting)
                .Otherwise().Goto(States.Disconnected);
            fsm.In(States.Disconnected)
                .ExecuteOnEntry(DisconnectAndCleanup)
                .ExecuteOnExit(ClearReconnectTimer)
                .On(Events.AttemptReconnect).Goto(States.Connecting);
            fsm.In(States.DisconnectRetry)
                .ExecuteOnEntry(StartReconnectTimer);
            fsm.In(States.Dota)
                .ExecuteOnExit(DisconnectDota);
            fsm.In(States.DotaConnect)
                .ExecuteOnEntry(ConnectDota)
                .On(Events.DotaGCReady).Goto(States.DotaMenu);
            fsm.In(States.DotaMenu)
                .ExecuteOnEntry(SetOnlinePresence);
            fsm.In(States.DotaLobby)
                .ExecuteOnEntry(EnterLobbyChat)
                .ExecuteOnEntry(EnterBroadcastChannel)
                .On(Events.DotaLeftLobby).Goto(States.DotaMenu).Execute(LeaveChatChannel);
            fsm.Initialize(States.Connecting);
        }
コード例 #11
0
        /// <summary>
        /// Get a log4net instance based on the config
        /// </summary>
        /// <returns></returns>
        public static ILog GetLogger()
        {
            //If _logger hasn't yet been initialised then create it
            if (_logger == null)
            {
                //Configure log4net if not already configured
                var configuredAlready = true;
                var logRepository = LogManager.GetRepository();
                if (!logRepository.Configured)
                {
                    configuredAlready = false;
                    log4net.Config.XmlConfigurator.Configure();
                }

                //Come up with a name for our logger eg "Template.Web v1.0.4857.27024"
                var assembly = Assembly.GetExecutingAssembly();
                var folderNames = AppDomain.CurrentDomain.SetupInformation.ApplicationBase.Split('\\');
                var loggerNamePrefix = (folderNames.Length > 2)
                    ? folderNames[folderNames.Length - 2]
                    : AppDomain.CurrentDomain.SetupInformation.ApplicationBase; //If this lives is stored in the root of a drive (unlikely) then use the path for a name
                var loggerName = string.Format("{0} v{1}",
                    loggerNamePrefix, //The path of the application executing
                    assembly.GetName().Version.ToString());

                //Get our logger
                _logger = LogManager.GetLogger(loggerName);
                _logger.Debug(string.Format("Logger {0} with this name: {1}", configuredAlready ? "retrieved" : "configured and retrieved", loggerName));
            }

            //Return instance
            return _logger;
        }
コード例 #12
0
ファイル: CommandDatagram.cs プロジェクト: pfactorio/XPiPlane
 public CommandDatagram()
 {
     this.type = (int) XPiPlaneConstants.DatagramTypes.COMMAND;
     this.opcode = "CMND0";
     log = LogManager.GetLogger(opcode.Substring(0, 4));
     log.Debug("New XP Command Created");
 }
コード例 #13
0
        public DummyApiCommand(IOctopusRepositoryFactory repositoryFactory, ILog log, IOctopusFileSystem fileSystem)
            : base(repositoryFactory, log, fileSystem)
        {
            var options = Options.For("Dummy");
            options.Add("pill=", "Red or Blue. Blue, the story ends. Red, stay in Wonderland and see how deep the rabbit hole goes.", v => pill = v);
			log.Debug ("Pill: " + pill);
        }
コード例 #14
0
 /// <summary>
 /// The debug.
 /// </summary>
 /// <param name="log">
 /// The log.
 /// </param>
 /// <param name="message">
 /// The message.
 /// </param>
 public static void Debug(ILog log, string message)
 {
     if (log != null && log.IsDebugEnabled)
     {
         log.Debug(message);
     }
 }
コード例 #15
0
ファイル: Client.cs プロジェクト: sadstorm/LoadTester112
        public Client(int id, Config cfg, SynchronizationContext ctx)
        {
            ClientStatisticsGatherer = new ClientStatisticsGatherer();

              _ctx = ctx;
              _id = id;

              Data = new TestData(this);
              IsStopped = false;

              _log = LogManager.GetLogger("Client_" + _id);
              _log.Debug("Client created");

              Configure(cfg);

              if (String.IsNullOrEmpty(_login))
              {
            const string err = "Login command is not specified!!! Can't do any test.";
            _log.Error(err);

            throw new Exception(err);
              }

              _ajaxHelper = new AjaxHelper(new AjaxConn(_login, cfg.ServerIp, cfg.AjaxPort, _ctx));
              _webSock = new WebSockConn(_login, cfg.ServerIp, cfg.WsPort, ctx);

              _webSock.CcsStateChanged += WsOnCcsStateChanged;
              _webSock.InitializationFinished += () => _testMng.GetTest<LoginTest>().OnClientInitialized();
              _testMng.SetEnv(_login, _ajaxHelper.AjaxConn, _webSock);
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: Slesa/Playground
 internal static void LogMessages(ILog log)
 {
     log.Info("This is an info");
     log.InfoFormat("Base called at {0}", DateTime.Now);
     log.Debug("This is a debug");
     log.Warn("This is a warning");
     log.Error("This is an error");
 }
コード例 #17
0
ファイル: Provider.cs プロジェクト: tranphuong02/giat-ghe
 /// <summary>
 ///     Write message to log debug
 /// </summary>
 /// <param name="data"></param>
 public void LogDebug(object data)
 {
     ThreadContext.Properties["logPath"] = Enums.LogLevels.Debug;
     _logger = LogManager.GetLogger(GetCaller());
     XmlConfigurator.Configure();
     _logger.Debug(data);
     LogManager.GetRepository().Shutdown();
 }
 private static Settings GetSettingsFromAppConfig(ILog log)
 {
     log.Debug("No external configuration path given, attempting to load settings from from default configuration file");
     var section = (NewRelicConfigurationSection) ConfigurationManager.GetSection("newRelic");
     var settingsFromAppConfig = Settings.FromConfigurationSection(section,log);
     log.DebugFormat("Settings loaded successfully");
     return settingsFromAppConfig;
 }
コード例 #19
0
ファイル: CardWriter.cs プロジェクト: edjo23/shop
        public CardWriter(ILog log)
        {
            Log = log;

            Log.Debug("CardWriter constructed");

            Connect();
        }
コード例 #20
0
ファイル: SagaExtensions.cs プロジェクト: sdhjl2000/EasyNetQ
 public static IEnumerable<ISaga> LogWith(this IEnumerable<ISaga> sagas, ILog log)
 {
     foreach (var saga in sagas)
     {
         log.Debug(string.Format("Loading Saga: {0}", saga.GetType().FullName));
         yield return saga;
     }
 }
コード例 #21
0
ファイル: WiaSource.cs プロジェクト: UNIT6-open/TWAIN-Web
		public WiaSource(int index, string name, string deviceId)
		{
			_sourceIndex = index;
			_name = name;
			_deviceId = deviceId;
			_log = LogManager.GetLogger(typeof(WiaSource));
			_log.Debug(string.Format("Created WIA source, name={0}, index={1}", name, index));
		}
コード例 #22
0
 protected RavenDBConfiguration()
 {
     if (log == null)
     {
         log = LogManager.GetLogger(typeof (RavenDBConfiguration));
         log.Debug("Logger created for RavenDBConfiguration");
     }
 }
コード例 #23
0
        public BaseDataAccessor(string dataLocation)
        {
            mDataLocation = dataLocation;
            mLogger = LogManager.GetLogger(GetType().Name);
            dataCache = new Dictionary<string, GameData>();

            mLogger.Debug(String.Format("Data Accessor created with data location {0}", dataLocation));
        }
コード例 #24
0
ファイル: Logger.cs プロジェクト: yancyn/BumbleeBee
 public static void Debug(System.Type type, object message)
 {
     System.Diagnostics.Debug.WriteLine(message);
     logger = LogManager.GetLogger(type);
     if (!logger.Logger.Repository.Configured)
         XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(GetConfigFile() + ".config"));
     logger.Debug(message);
 }
コード例 #25
0
        public App()
        {
            XmlConfigurator.Configure();
            _logger = LogManager.GetLogger("LogFileAppender");

            _logger.Debug("Paramètres : " + string.Join(" ", Environment.GetCommandLineArgs()));

            // Check if user is NOT admin
            if (!IsRunningAsAdministrator())
            {
                _logger.Debug("Application non lancée entant qu'admin ...");
                // Setting up start info of the new process of the same application
                ProcessStartInfo processStartInfo = new ProcessStartInfo(Assembly.GetEntryAssembly().CodeBase);

                // Using operating shell and setting the ProcessStartInfo.Verb to “runas” will let it run as admin
                processStartInfo.UseShellExecute = true;
                processStartInfo.Verb = "runas";
                processStartInfo.Arguments = string.Join(" ", Environment.GetCommandLineArgs().Skip(1)); // pass args

                // Start the application as new process
                Process.Start(processStartInfo);

                // Shut down the current (old) process
                //System.Windows.Forms.Application.Exit();
                Environment.Exit(0); // Changement en Environment.Exit(0) parce qu'avec l'autre méthode, il me restait un process
            }

            Current.DispatcherUnhandledException += CurrentOnDispatcherUnhandledException;
            TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;

            string startup = Environment.GetFolderPath(Environment.SpecialFolder.Programs);
            string uriName = ConfigurationManager.AppSettings["uri:name"];
            string uriDescription = ConfigurationManager.AppSettings["uri:description"];
            string clickOncePublisher = ConfigurationManager.AppSettings["clickonce:publisher"];
            string clickOncePackageName = ConfigurationManager.AppSettings["clickonce:packageName"];
            string clickOnceFileName = ConfigurationManager.AppSettings["clickonce:fileName"];
            string appPath = Path.Combine(startup, clickOncePublisher, clickOncePackageName, clickOnceFileName);
            //if (!UriHelper.IsUriRegistered(uriName, appPath))
            //{
                //_logger.Info("Installation de l'URI...");
                //UriHelper.RegisterUri(uriName, appPath, uriDescription);
            //}

            _logger.Info("Lancement de WSU");
        }
コード例 #26
0
 public void record(ILog logger, string message, LogLevel logLevel)
 {
     switch (logLevel)
     {
         case LogLevel.Debug:
             logger.Debug(message, new Exception(message));
             break;
     }
 }
コード例 #27
0
ファイル: RegionImportService.cs プロジェクト: JueZ/SKS
        public RegionImportService(IRegionRepository regionrepository)
        {
            _regionrepository = regionrepository;

            _geodataserviceagent = new GeoDataServiceAgent();

            logger = LogManager.GetLogger(typeof(RegionImportService));
            logger.Debug("Initialisiert");
        }
コード例 #28
0
    public static void LogDebug(String debugMessage, ILog logger)
    {
        //set log file anme
        log4net.GlobalContext.Properties["LogName"] = getfilePathPrefix() + "_DebugLog.log";

        //configure log4net
        log4net.Config.XmlConfigurator.Configure();

        logger.Debug(debugMessage);
    }
コード例 #29
0
        static AppState()
        {
            try
            {
                try
                {
                    // Initialise logging functionality from an XML node in the app.config file.
                    Console.WriteLine("Starting logging initialisation.");
                    log4net.Config.XmlConfigurator.Configure();
                }
                catch
                {
                    // Unable to load the log4net configuration node (probably invalid XML in the config file).
                    Console.WriteLine("Unable to load logging configuration check that the app.config file exists and is well formed.");

                    try
                    {
                        //EventLog.WriteEntry(APP_LOGGING_ID, "Unable to load logging configuration check that the app.config file exists and is well formed.", EventLogEntryType.Error, 0);
                    }
                    catch (Exception evtLogExcp)
                    {
                        Console.WriteLine("Exception writing logging configuration error to event log. " + evtLogExcp.Message);
                    }

                    // Configure a basic console appender so if there is anyone watching they can still see log messages and to
                    // ensure that any classes using the logger won't get null references.
                    ConfigureConsoleLogger();
                }
                finally
                {
                    try
                    {
                        logger = log4net.LogManager.GetLogger(APP_LOGGING_ID);
                        logger.Debug("Logging initialised.");
                    }
                    catch (Exception excp)
                    {
                        StreamWriter errorLog = new StreamWriter(DEFAULT_ERRRORLOG_FILE, true);
                        errorLog.WriteLine(DateTime.Now.ToString("dd MMM yyyy HH:mm:ss") + " Exception Initialising AppState Logging. " + excp.Message);
                        errorLog.Close();
                    }
                }

                // Initialise the string dictionary to hold the application settings.
                m_appConfigSettings = new StringDictionary();

                CurrentDirectory = Regex.Replace(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase), @"^file:\\", ""); // There's undoubtedly a better way!
            }
            catch (Exception excp)
            {
                StreamWriter errorLog = new StreamWriter(DEFAULT_ERRRORLOG_FILE, true);
                errorLog.WriteLine(DateTime.Now.ToString("dd MMM yyyy HH:mm:ss") + " Exception Initialising AppState. " + excp.Message);
                errorLog.Close();
            }
        }
コード例 #30
0
ファイル: CardReader.cs プロジェクト: edjo23/shop
        public CardReader(ILog log, IEventAggregator eventAggregator)
        {
            Log = log;
            EventAggregator = eventAggregator;

            Log.Debug("CardReader constructed");

            Connect();

            KeepAliveTimer = new Timer(s => EventAggregator.Publish(new KeepAlive()), null, KeepAliveInterval, KeepAliveInterval);
        }
コード例 #31
0
 /// <summary>
 /// Logs the debug message.
 /// </summary>
 /// <param name="message">The message.</param>
 public void Debug(object message)
 {
     m_Log.Debug(message);
 }
コード例 #32
0
 public Game(List <Player> players, int bb, int sb, Boolean train)
 {
     log.Debug("Game() - Begin");
     log.Debug("New Game - Player: " + players.Count + " Stakes: " + sb + "/" + bb);
     trainMode  = train;
     boolCancel = false;
     blindLevel = 0;
     foreach (Player p in players)
     {
         log.Info("Name: " + p.name + "; Position: " + p.position + "; Stack: " + p.stack);
     }
     this.players    = players;
     this.smallBlind = sb;
     this.bigBlind   = bb;
     pot             = new Pot();
     round           = 0;
     players.Sort((x, y) => x.position.CompareTo(y.position));
     for (int i = 2; i < players.Count + 2; i++)
     {
         players.Find(x => (x.position > (i - 2)) && (x.ingamePosition == -1)).ingamePosition = i;
     }
     log.Debug("Game() - End");
 }
コード例 #33
0
        private string srid      = "4326";  // name of SRID Constraint, EPSG:4326, of tables

        /// <summary>
        /// Experimental SQL service
        /// </summary>
        /// <param name="Parameters">SQLParameter Parameters</param>
        /// <returns>Stream</returns>
        public Stream GetSQLBBox(SQLParameter Parameters)
        {
            Encoding encoding  = new UTF8Encoding();
            Stream   WKTStream = new MemoryStream();

            if (Parameters.columnnames == null || Parameters.columnnames.Length == 0)
            {
                Parameters.columnnames = "*";
            }

            string        connStr = ConfigurationManager.ConnectionStrings["DataConnectionString"].ConnectionString;
            SqlConnection conn    = new SqlConnection(connStr);
            SqlDataReader rdr     = null;

            try
            {
                StringBuilder query = new StringBuilder("SELECT " + Parameters.columnnames + "," + geomField + ".Reduce(" + Parameters.reduce + ").STAsText() as " + geomField + "wkt FROM [dbo].[" + Parameters.table + "] WITH(INDEX(geog_sidx))");
                if (Parameters.points != null || Parameters.filter != null)
                {
                    query.Append(" WHERE ");
                }
                query.Append(geomField + ".STIntersects(geography::STGeomFromText('POLYGON((" + Parameters.points + "))', " + srid + "))=1");

                if (Parameters.filter != null && Parameters.filter.Length > 0)
                {
                    if (Parameters.points != null)
                    {
                        query.Append(" AND ");
                    }
                    query.Append(Parameters.filter);
                }
                log.Info(query);

                SqlCommand cmd = new SqlCommand(query.ToString(), conn);
                conn.Open();
                rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    Shape shp = new Shape();
                    shp.Fields = new Dictionary <string, string>();
                    for (int i = 0; i < rdr.FieldCount; i++)
                    {
                        log.Debug(rdr[i].GetType() + "  " + rdr.GetName(i));
                        if (rdr[i].GetType().Equals(typeof(SqlGeography)) ||
                            rdr[i].GetType().Equals(typeof(SqlGeometry))
                            )
                        { //skip
                            log.Debug("skip " + rdr[i].GetType());
                        }
                        else
                        {
                            if (rdr.GetName(i).Equals("ID"))
                            {
                                shp.ID = rdr[i].ToString();
                                log.Debug(rdr[i].GetType() + "  " + rdr.GetName(i) + "  " + rdr[i].ToString());
                            }
                            else if (rdr.GetName(i).Equals(geomField + "wkt"))
                            {
                                log.Debug(rdr[i].GetType() + "  " + rdr.GetName(i) + "  " + rdr[i].ToString());
                                shp.WKT = rdr[i].ToString();
                            }
                            else
                            {
                                shp.Fields.Add(rdr.GetName(i), rdr[i].ToString());
                                log.Debug(rdr.GetName(i) + " : " + rdr[i].ToString());
                            }
                        }
                    }
                    log.Debug(shp.ID + "  " + shp.WKT);
                    WKTStream.Write(encoding.GetBytes(shp.WKT), 0, shp.WKT.Length);
                    WKTStream.Flush();
                }
            }
            catch (Exception e)
            {
                log.Error(e.Message);
            }
            finally
            {
                if (rdr != null)
                {
                    rdr.Close();
                }
                if (conn != null)
                {
                    conn.Close();
                }
            }
            return(WKTStream);
        }
コード例 #34
0
ファイル: BruTileLayer.cs プロジェクト: jjgas/ArcBruTile
        public void Draw(esriDrawPhase drawPhase, IDisplay display, ITrackCancel trackCancel)
        {
            switch (drawPhase)
            {
            case esriDrawPhase.esriDPGeography:
                if (Valid)
                {
                    if (Visible)
                    {
                        try
                        {
                            var clipEnvelope = display.ClipEnvelope;

                            // when loading from a file the active map doesn't exist yet
                            // so just deal with it here.
                            if (_map == null)
                            {
                                var mxdoc = (IMxDocument)_application.Document;
                                _map = mxdoc.FocusMap;
                            }

                            Debug.WriteLine("Draw event");
                            var activeView = _map as IActiveView;
                            Logger.Debug("Layer name: " + Name);

                            if (activeView != null)
                            {
                                //_envelope = activeView.Extent;
                                //_envelope = clipEnvelope;

                                Logger.Debug("Draw extent: xmin:" + clipEnvelope.XMin +
                                             ", ymin:" + clipEnvelope.YMin +
                                             ", xmax:" + clipEnvelope.XMax +
                                             ", ymax:" + clipEnvelope.YMax
                                             );
                                if (SpatialReference != null)
                                {
                                    Logger.Debug("Layer spatial reference: " + SpatialReference.FactoryCode);
                                }
                                if (_map.SpatialReference != null)
                                {
                                    Logger.Debug("Map spatial reference: " + _map.SpatialReference.FactoryCode);
                                }

                                var bruTileHelper = new BruTileHelper(_tileTimeOut);
                                _displayFilter.Transparency  = (short)(255 - ((_transparency * 255) / 100));
                                _displayFilter.BackgroundRGB = 587202560;
                                if (display.Filter == null)
                                {
                                    display.Filter = _displayFilter;
                                }

                                FileCache fileCache;

                                if (_config != null)
                                {
                                    fileCache = CacheDirectory.GetFileCache(_cacheDir, _config, _enumBruTileLayer);
                                }
                                else
                                {
                                    fileCache = CacheDirectory.GetFileCache(_cacheDir, _tileSource, _enumBruTileLayer);
                                }

                                if (_enumBruTileLayer == EnumBruTileLayer.Giscloud &&
                                    _config.CreateTileSource().Schema.Format == "jpg")
                                {
                                    // potential black borders: need to add a check for clip....
                                    bruTileHelper.ClipTilesEnvelope = _envelope;
                                }
                                bruTileHelper.Draw(_application.StatusBar.ProgressBar, activeView, fileCache, trackCancel, SpatialReference, ref _currentLevel, _tileSource, display, _auth);
                            }
                        }
                        catch (Exception ex)
                        {
                            var mbox = new ExceptionMessageBox(ex);
                            mbox.Show(null);
                        }
                    }  // isVisible
                }      // isValid
                break;

            case esriDrawPhase.esriDPAnnotation:
                break;
            }
        }
コード例 #35
0
ファイル: LogHelper.cs プロジェクト: wayshan/tljs
 public static void Debug(string msg)
 {
     log.Debug(msg);
 }
コード例 #36
0
ファイル: _Log4Net.cs プロジェクト: zeroisstart/TinyAdmin
 /// <summary>
 /// Debug信息记录
 /// </summary>
 /// <param name="message">消息内容</param>
 public static void Debug(string message)
 {
     log4net.ILog logger = log4net.LogManager.GetLogger(loggerRepository.Name, "debuginfo");
     logger.Debug(message);
 }
コード例 #37
0
 public void WriteMessage(string msg)
 {
     log.Debug(msg);
 }
コード例 #38
0
ファイル: Program.cs プロジェクト: sky-gc/AgpsServer
        static void Main(string[] args)
        {
            Console.WriteLine("Press any key to start the agps client!");

            Console.ReadKey();
            Console.WriteLine();

            //测试代码
            //byte[] rsp = { 0x30, 0x00, 0x31, 0x00, 0x1D, 0x60, 0xD1, 0x79, 0x80, 0xA0, 0xA1 };
            //byte[] rsp1 = { 0x40, 0x00, 0x41, 0x00, 0x1D, 0x60, 0xD1, 0x79, 0x80, 0xB0, 0xB1, 0xC0, 0xCF, 0xFE, 0xFF };
            //string utfString = Encoding.UTF8.GetString(rsp, 0, rsp.Length);
            //string utfString1 = Encoding.ASCII.GetString(rsp, 0, rsp.Length);
            //string str = Encoding.GetEncoding(936).GetString(rsp, 0, rsp.Length);
            //Console.WriteLine(utfString);
            //Console.WriteLine(utfString1);
            //Console.WriteLine(str);
            //byte[] rsp2 = new byte[10];
            //Console.WriteLine(rsp2.Length);
            //List< byte > ls = new List<byte>();
            //ls.AddRange(rsp);
            //ls.AddRange(rsp1);
            //rsp2 = ls.ToArray();
            //Console.WriteLine(rsp2.Length);
            //ArrayList arrLi = new ArrayList();
            //arrLi.AddRange(rsp);
            //Console.WriteLine(arrLi.ToArray().Length);
            //arrLi.AddRange(rsp1);
            //Console.WriteLine(arrLi.ToArray().Length);
            //byte[] tmpRsp = { 0x60, 0xD1 };
            //var i = arrLi.IndexOf(tmpRsp);
            //Console.WriteLine(i);
            //byte tmpRsp1 = 0x60;
            //var j = arrLi.IndexOf(tmpRsp1);
            //Console.WriteLine(j);
            //Console.WriteLine(Array.IndexOf(rsp, tmpRsp));

            //// 注意是TelnetServer
            //var appServer = new TelnetServer();
            //appServer.Setup(2012);
            //// 开始监听
            //appServer.Start();
            //while (Console.ReadKey().KeyChar != 'q')
            //{
            //    Console.WriteLine();
            //    continue;
            //}
            //// 停止服务器。
            //appServer.Stop();

            //启动客户端
            string     host   = "agps.u-blox.com";
            int        port   = 46434;
            AgpsClient client = new AgpsClient();

            client.StartClient(host, port);
            Console.WriteLine("Ublox Agps data len {0}", AgpsClient.AgpsData.Length);

            //MTK AGPS data
            MtkAgpsData mtkAgps = new MtkAgpsData();

            mtkAgps.update();
            Console.WriteLine("Mtk Agps data len {0}", MtkAgpsData.Data.Length);

            //启动定时器,定时更新AGPS数据。
            System.Timers.Timer agpsUbloxTimer = new System.Timers.Timer();
            agpsUbloxTimer.AutoReset = true;
            agpsUbloxTimer.Enabled   = true;
            agpsUbloxTimer.Interval  = 600000;
            agpsUbloxTimer.Elapsed  += new System.Timers.ElapsedEventHandler(AgpsUbloxHandle);
            agpsUbloxTimer.Start();

            Console.WriteLine("Press any key to start the agps server!");
            Console.ReadKey();
            Console.WriteLine();

            //读取配置文件
            //ConfigurationSection accounts = config.AppSettings.Settings());
            //Console.WriteLine(accounts.ToString());
            //判断App.config配置文件中是否有key
            if (ConfigurationManager.AppSettings.HasKeys())
            {
                //List<string> theKeys = new List<string>();      //保存key的集合
                //List<string> theValues = new List<string>();    //保存value的集合
                ////遍历出所有的key并添加进thekeys集合
                //foreach (string theKey in ConfigurationManager.AppSettings.Keys)
                //{
                //    theKeys.Add(theKey);
                //}
                ////根据key遍历出所有的value并添加进theValues集合
                //for (int i = 0; i < theKeys.Count; i++)
                //{
                //    foreach (string theValue in ConfigurationManager.AppSettings.GetValues(theKeys[i]))
                //    {
                //        theValues.Add(theValue);
                //    }
                //}
                ////验证key和value
                //for (int i = 0; i < theKeys.Count; i++)
                //{
                //    Console.WriteLine("Account: {0}, {1}", theKeys[i], theValues[i]);
                //}
                //遍历出所有的key并添加进thekeys集合
                //foreach (string theKey in ConfigurationManager.AppSettings.Keys)
                //{
                //    Keys.Add(theKey);
                //}
                ////根据key遍历出所有的value并添加进theValues集合
                //for (int i = 0; i < Keys.Count; i++)
                //{
                //    foreach (string theValue in ConfigurationManager.AppSettings.GetValues(Keys[i]))
                //    {
                //        Pwds.Add(theValue);
                //    }
                //}
                //for (int i = 0; i < Keys.Count; i++)
                //{
                //    Console.WriteLine("Account: {0},{1}", Keys[i], Pwds[i]);
                //}
                foreach (string key in ConfigurationManager.AppSettings.Keys)
                {
                    string value = ConfigurationManager.AppSettings.GetValue(key);
                    KeyDic.Add(key, value);
                }
                foreach (KeyValuePair <string, string> kvp in KeyDic)
                {
                    Console.WriteLine("KeyDic: {0},{1}", kvp.Key, kvp.Value);
                }
            }

            // 通过工厂创建一个加载器。
            var bootstrap = BootstrapFactory.CreateBootstrap();

            if (!bootstrap.Initialize())
            {
                Console.WriteLine("Failed to initialize!");
                Console.ReadKey();
                return;
            }

            var result = bootstrap.Start();

            Console.WriteLine("Start result : {0}!", result);
            if (log.IsDebugEnabled)
            {
                log.Debug("Start succ!");
            }
            if (result == StartResult.Failed)
            {
                Console.WriteLine("Failed to start!");
                Console.ReadKey();
                return;
            }

            while (Console.ReadKey().KeyChar != 'q')
            {
                Console.WriteLine();
                continue;
            }
            // 停止服务器
            bootstrap.Stop();

            //var appServer = new AppServer();

            ////Setup the appServer
            //if (!appServer.Setup(2012)) //Setup with listening port
            //{
            //    Console.WriteLine("Failed to setup!");
            //    Console.ReadKey();
            //    return;
            //}

            //Console.WriteLine();

            ////Try to start the appServer
            //if (!appServer.Start())
            //{
            //    Console.WriteLine("Failed to start!");
            //    Console.ReadKey();
            //    return;
            //}

            //Console.WriteLine("The server started successfully, press key 'q' to stop it!");
            //appServer.NewSessionConnected += new SessionHandler<AppSession>(appServer_NewSessionConnected);
            //appServer.NewRequestReceived += new RequestHandler<AppSession, StringRequestInfo>(appServer_NewRequestReceived);

            //while (Console.ReadKey().KeyChar != 'q')
            //{
            //    Console.WriteLine();
            //    continue;
            //}

            ////Stop the appServer
            //appServer.Stop();

            //Console.WriteLine("The server was stopped!");
            //Console.ReadKey();
        }
コード例 #39
0
        /// <summary>
        /// 调试日志
        /// </summary>
        /// <param name="throwMsg"></param>
        /// <param name="ex"></param>
        public void LogDebug(string throwMsg)
        {
            string errorMsg = string.Format("【调试信息记录】:{0} \r\n", throwMsg);

            logDebug.Debug(errorMsg);
        }
コード例 #40
0
        /// <summary>
        /// 客户端服务线程
        /// </summary>
        private void TCPClientHandler()
        {
            DateTime handshakeTime = DateTime.Now;

            while (true)
            {
                if (_socket.Connected)
                {
                    // 与客户端握手
                    if (_logon == 0)
                    {
                        log.Debug("正在与客户端 " + this.IPAddress + " 握手");

                        try
                        {
                            // 向客户端发送握手信号
                            byte[] bytes = Encoding.UTF8.GetBytes("ESTSHOPCSVC.HELLO");
                            _socket.Send(bytes);
                            Thread.Sleep(100);
                        } catch (Exception ex)
                        {
                            OnClientDisconnected(this, "客户端 " + this.IPAddress + " 套接字已断开-9:" + ex.Message);
                            Thread.Sleep(Timeout.Infinite);
                        }

                        // 记录下给客户端发送握手信号的时间,此时间经过5秒仍未
                        // 收到客户端的握手响应则踢掉客户端
                        _logon        = 1;
                        handshakeTime = DateTime.Now;
                    }

                    if (_socket.Available > 0)
                    {
                        // 接收客户端发送的数据
                        log.Debug("接收到客户端 " + this.IPAddress + " 发送的数据,正在解析请求信息");
                        byte[] reply = null;
                        try
                        {
                            reply = new byte[_socket.Available];
                            _socket.Receive(reply, reply.Length, SocketFlags.None);
                        }
                        catch (Exception ex)
                        {
                            OnClientDisconnected(this, "客户端 " + this.IPAddress + " 套接字已断开-0: " + ex.Message);
                            Thread.Sleep(Timeout.Infinite);
                        }

                        string replyString = Encoding.UTF8.GetString(reply);

                        // 处理客户端的握手信号
                        if (replyString.StartsWith("ESTSHOPCCLIENT.HELLO"))
                        {
                            // 客户端正确响应了握手信号
                            log.Debug("接收到客户端 " + this.IPAddress + " 发送的握手信号");
                            _logon = 2;
                        }
                        else
                        {
                            // 处理其他非握手请求
                            if (_logon != 2)
                            {
                                // 检查客户端是否已经握手
                                // 如果客户端还未发送握手信号就给出其他内容
                                // 则判定客户端非法并断开连接
                                OnClientDisconnected(this, "客户端 " + this.IPAddress + " 在握手前发送指令");
                                Thread.Sleep(Timeout.Infinite);
                            }

                            // 客户端已经成功握手
                            // 处理客户端的读取OPCITEM请求
                            if (replyString.StartsWith("ESTSHOPCSVC.READ:"))
                            {
                                // 解析要读取的OPCITEM名称
                                string blockName = replyString.Split(':')[1];
                                string value     = "NaN";

                                log.Debug("客户端 " + this.IPAddress + " 请求读取 " + blockName);
                                // 检查请求的数据库是否已经存在于全局结果集中
                                // (如果不存在代表配置文件中未配置此数据块)
                                if (ValuesContainer.Values.ContainsKey(blockName))
                                {
                                    value = ValuesContainer.Values[blockName].ToString();
                                }
                                else
                                {
                                    log.Debug("服务器中未配置此地址块 " + blockName);
                                    OnClientDisconnected(this, "客户端 " + this.IPAddress + " 试图读取未配置的地址块:" + blockName);
                                    Thread.Sleep(Timeout.Infinite);
                                }

                                try
                                {
                                    // 把获取到的值和连接品质发送给客户端
                                    _socket.Send(Encoding.UTF8.GetBytes("ESTSHOPCSVC.RESULT:" + value + ":" + ValuesContainer.Qualities[blockName].ToString()));
                                    log.Debug("向客户端 " + this.IPAddress + " 发送了读取响应 " + blockName + "=" + value);
                                    ValuesContainer.ReadCounts[blockName] = (int)ValuesContainer.ReadCounts[blockName] + 1;
                                    // 更新心跳时间戳
                                    this._heartbeat = DateTime.Now;
                                }
                                catch (Exception ex)
                                {
                                    OnClientDisconnected(this, "客户端 " + this.IPAddress + " 套接字已断开-1:" + ex.StackTrace + "\n" + ex.Message + (_socket == null).ToString() + "/" + (ValuesContainer.Qualities[blockName] == null).ToString());
                                    Thread.Sleep(Timeout.Infinite);
                                }
                            }
                            // 处理客户端的写入OPCITEM请求
                            else if (replyString.StartsWith("ESTSHOPCSVC.WRITE:"))
                            {
                                // 解析要更新的OPCITEM名称和要写入的新值
                                string blockName = replyString.Split(':')[1];
                                string value     = replyString.Split(':')[2];
                                string type      = replyString.Split(':')[3];

                                log.Debug("接收到客户端 " + this.IPAddress + " 的OPCITEM更新请求 " + blockName + "=" + value + ", 正在转发给上层处理");

                                // 发出请求更改OPC值的事件给分派线程
                                OnOPCItemUpdated(blockName, value, type, this);

                                try
                                {
                                    // 把更改的结果和连接品质发送给客户端

                                    _socket.Send(Encoding.UTF8.GetBytes("ESTSHOPCSVC.RESULT:" + value + ":" + ValuesContainer.Qualities[blockName].ToString()));
                                    log.Debug("向客户端 " + this.IPAddress + " 发送了写入响应 " + blockName + "=" + value);

                                    // 更新心跳时间戳
                                    this._heartbeat = DateTime.Now;
                                }
                                catch (Exception ex)
                                {
                                    OnClientDisconnected(this, "客户端 " + this.IPAddress + " 套接字已断开-2:" + ex.Message);
                                    Thread.Sleep(Timeout.Infinite);
                                }
                            }
                            else if (replyString.StartsWith("ESTSHOPCSVC.BYE"))
                            {
                                log.Info("客户端 " + this.IPAddress + " 已注销");
                                OnClientDisconnected(this, "客户端正常注销");
                                Thread.Sleep(Timeout.Infinite);
                            }
                            else if (replyString.StartsWith("ESTSHOPCSVC.READS:"))
                            {
                                // 解析要读取的OPCITEM名称
                                string xml = replyString.Split(':')[1];
                                try
                                {
                                    _doc.LoadXml(xml);
                                }
                                catch
                                {
                                    log.Info("客户端 " + this.IPAddress + " 发送了非法请求");
                                    OnClientDisconnected(this, "发送了非法请求");
                                    Thread.Sleep(Timeout.Infinite);
                                }

                                // 检查请求的数据库是否已经存在于全局结果集中
                                // (如果不存在代表配置文件中未配置此数据块)
                                foreach (XmlNode node in _doc.DocumentElement.SelectNodes("item"))
                                {
                                    string blockName = node.Attributes.GetNamedItem("name").InnerText;
                                    if (ValuesContainer.Values.ContainsKey(blockName))
                                    {
                                        node.InnerText = ValuesContainer.Values[blockName].ToString();
                                        ValuesContainer.ReadCounts[blockName] = (int)ValuesContainer.ReadCounts[blockName] + 1;
                                        try
                                        {
                                            node.Attributes.GetNamedItem("quality").InnerText = ValuesContainer.Qualities[blockName].ToString();
                                        } catch { }
                                    }
                                    else
                                    {
                                        log.Debug("服务器中未配置此地址块 " + blockName);
                                        OnClientDisconnected(this, "客户端 " + this.IPAddress + " 试图读取未配置的地址块:" + blockName);
                                        Thread.Sleep(Timeout.Infinite);
                                    }
                                }

                                try
                                {
                                    // 把获取到的值发送给客户端
                                    _socket.Send(Encoding.UTF8.GetBytes("ESTSHOPCSVC.RESULT:" + _doc.InnerXml));
                                    log.Debug("向客户端 " + this.IPAddress + " 发送了读取响应 " + _doc.InnerXml);

                                    // 更新心跳时间戳
                                    this._heartbeat = DateTime.Now;
                                }
                                catch (Exception ex)
                                {
                                    OnClientDisconnected(this, "客户端 " + this.IPAddress + " 套接字已断开-3: " + ex.Message);
                                    Thread.Sleep(Timeout.Infinite);
                                }
                            }
                            else if (replyString.StartsWith("ESTSHOPCSVC.WRITES:"))
                            {
                                // 解析要读取的OPCITEM名称
                                string xml = replyString.Split(':')[1];
                                try
                                {
                                    _doc.LoadXml(xml);
                                }
                                catch
                                {
                                    log.Info("客户端 " + this.IPAddress + " 发送了非法请求");
                                    OnClientDisconnected(this, "发送了非法请求");
                                    Thread.Sleep(Timeout.Infinite);
                                }

                                // 检查请求的数据库是否已经存在于全局结果集中
                                // (如果不存在代表配置文件中未配置此数据块)
                                foreach (XmlNode node in _doc.DocumentElement.SelectNodes("item"))
                                {
                                    string blockName = node.Attributes.GetNamedItem("name").InnerText;
                                    string value     = node.InnerText;
                                    try
                                    {
                                        node.Attributes.GetNamedItem("quality").InnerText = ValuesContainer.Qualities[blockName].ToString();
                                    }
                                    catch { }

                                    log.Debug("接收到客户端 " + this.IPAddress + " 的OPCITEM更新请求 " + blockName + "=" + value + ", 正在转发给上层处理");

                                    // 发出请求更改OPC值的事件给分派线程
                                    OnOPCItemUpdated(blockName, value, "STRING", this);
                                }

                                try
                                {
                                    // 把获取到的值发送给客户端
                                    _socket.Send(Encoding.UTF8.GetBytes("ESTSHOPCSVC.RESULT:" + _doc.InnerXml));
                                    log.Debug("向客户端 " + this.IPAddress + " 发送了读取响应 " + _doc.InnerXml);

                                    // 更新心跳时间戳
                                    this._heartbeat = DateTime.Now;
                                }
                                catch (Exception ex)
                                {
                                    OnClientDisconnected(this, "客户端 " + this.IPAddress + " 套接字已断开-4: " + ex.Message);
                                    Thread.Sleep(Timeout.Infinite);
                                }
                            }
                        }
                    }
                    else
                    {
                        Thread.Sleep(20);
                    }

                    // 踢掉连接后超过5秒仍未响应握手信号的客户端
                    if (_logon != 2 && DateTime.Now.Subtract(handshakeTime).TotalSeconds > 60)
                    {
                        OnClientDisconnected(this, "客户端 " + this.IPAddress + " 超时未发送握手信号");
                        Thread.Sleep(Timeout.Infinite);
                    }
                }
                else
                {
                    // 客户端套接字断开
                    OnClientDisconnected(this, "客户端 " + this.IPAddress + " 套接字已断开-5");
                    Thread.Sleep(Timeout.Infinite);
                }
            }
        }
コード例 #41
0
 public void Debug(object message)
 {
     _logProvider.Debug(message);
 }
コード例 #42
0
    protected void bindGridview(object sender, EventArgs e)
    {
        log.Debug("Inside bindGridview function");
        User_Mangement b  = new User_Mangement();
        DataSet        ds = b.GetHREmpData();

        if (ds.Tables[0].Rows.Count == 0)
        {
            log.Debug("No records to update or insert");
            ClientScript.RegisterStartupScript(Page.GetType(), "validation1", "<script language='javascript'>alert('No HR record exists to update or add')</script>");
            return;
        }
        else
        {
            string connectionString = "";
            string isfilegenerate   = ConfigurationManager.AppSettings["UserExcelFileGenerate"].ToString();
            if (isfilegenerate == "Y")
            {
                Microsoft.Office.Interop.Excel.Application xlApp =
                    new Microsoft.Office.Interop.Excel.Application();
                Workbook  xlWorkbook  = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
                Sheets    xlSheets    = null;
                Worksheet xlWorksheet = null;
                object    misValue    = System.Reflection.Missing.Value;


                System.Data.DataTable dataTable = ds.Tables[0];
                int rowNo    = dataTable.Rows.Count;
                int columnNo = dataTable.Columns.Count;
                int colIndex = 0;

                //Create Excel Sheets
                xlSheets    = xlWorkbook.Sheets;
                xlWorksheet = (Worksheet)xlSheets.Add(xlSheets[1],
                                                      Type.Missing, Type.Missing, Type.Missing);
                //xlWorksheet.Name = dataSet.DataSetName;

                //Generate Field Names
                foreach (DataColumn dataColumn in dataTable.Columns)
                {
                    colIndex++;
                    xlApp.Cells[1, colIndex] = dataColumn.ColumnName;
                }

                object[,] objData = new object[rowNo, columnNo];

                //Convert DataSet to Cell Data
                for (int row = 0; row < rowNo; row++)
                {
                    for (int col = 0; col < columnNo; col++)
                    {
                        objData[row, col] = dataTable.Rows[row][col];
                    }
                }

                //Add the Data
                Range range = xlWorksheet.Range[xlApp.Cells[2, 1], xlApp.Cells[rowNo + 1, columnNo]];
                range.Value2 = objData;



                //Remove the Default Worksheet
                ((Worksheet)xlApp.ActiveWorkbook.Sheets[xlApp.ActiveWorkbook.Sheets.Count]).Delete();

                string servername       = ConfigurationManager.AppSettings["ServerName"].ToString();
                string domainame        = ConfigurationManager.AppSettings["DomainName"].ToString();
                string username         = ConfigurationManager.AppSettings["UserName"].ToString();
                string password         = ConfigurationManager.AppSettings["Password"].ToString();
                string mainpath         = ConfigurationManager.AppSettings["UploadUserPath"].ToString();
                string timestamp        = DateTime.Now.ToString("yyyy-MM-dd-hh_mm_ss");
                string ExcelFileVersion = ConfigurationManager.AppSettings["ExcelFileVersion"].ToString();
                string FileName         = "HRUserData" + timestamp + ExcelFileVersion;
                using (NetworkShareAccesser.Access(servername, domainame, username, password))
                {
                    if (Directory.Exists(mainpath))
                    {
                        path = Path.Combine(mainpath, FileName);
                        //  xlWorkbook.SaveAs(FileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                        xlWorkbook.SaveAs(path,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value,
                                          XlSaveAsAccessMode.xlNoChange,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value);

                        xlWorkbook.Close();
                        xlApp.Quit();
                    }
                    else
                    {
                        Directory.CreateDirectory(mainpath);
                        path = Path.Combine(mainpath, FileName);
                        //  xlWorkbook.SaveAs(FileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                        xlWorkbook.SaveAs(path,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value,
                                          XlSaveAsAccessMode.xlNoChange,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value,
                                          System.Reflection.Missing.Value);

                        xlWorkbook.Close();
                        xlApp.Quit();
                    }
                }
            }
            //string query = "SELECT * FROM [Sheet2$]";
            //connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            //OleDbConnection conn = new OleDbConnection(connectionString);
            //if (conn.State == ConnectionState.Closed)
            //    conn.Open();
            //OleDbCommand cmd = new OleDbCommand(query, conn);
            //OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            //DataSet ds1 = new DataSet();
            //da.Fill(ds1);
            GridExcelData.DataSource = ds.Tables[0];
            GridExcelData.DataBind();
            //da.Dispose();
            //conn.Close();
            //conn.Dispose();
        }
    }
コード例 #43
0
 public static void Debug(object message)
 {
     SetLog4NetConfiguration();
     _log.Debug(message);
 }
コード例 #44
0
        private IDictionary <string, IList <KafkaMessageStream <TData> > > Consume <TData>(IDictionary <string, int> topicCountDict, IDecoder <TData> decoder)
        {
            Logger.Debug("entering consume");

            if (topicCountDict == null)
            {
                throw new ArgumentNullException();
            }

            var dirs   = new ZKGroupDirs(this.config.GroupId);
            var result = new Dictionary <string, IList <KafkaMessageStream <TData> > >();

            string consumerIdString = GetConsumerIdString();
            var    topicCount       = new TopicCount(consumerIdString, topicCountDict);

            //// create a queue per topic per consumer thread
            var consumerThreadIdsPerTopicMap = topicCount.GetConsumerThreadIdsPerTopic();

            foreach (var topic in consumerThreadIdsPerTopicMap.Keys)
            {
                var streamList = new List <KafkaMessageStream <TData> >();
                foreach (string threadId in consumerThreadIdsPerTopicMap[topic])
                {
                    var stream = new BlockingCollection <FetchedDataChunk>(new ConcurrentQueue <FetchedDataChunk>());
                    this.queues.Add(new Tuple <string, string>(topic, threadId), stream);
                    streamList.Add(new KafkaMessageStream <TData>(topic, stream, this.config.Timeout, decoder));
                }

                result.Add(topic, streamList);
                Logger.InfoFormat("adding topic {0} and stream to map...", topic);
            }

            // listener to consumer and partition changes
            var loadBalancerListener = new ZKRebalancerListener <TData>(
                this.config,
                consumerIdString,
                this.topicRegistry,
                this.GetZkClient(),
                this,
                queues,
                this.fetcher,
                result,
                topicCount);

            if (this.consumerRebalanceHandler != null)
            {
                loadBalancerListener.ConsumerRebalance += this.consumerRebalanceHandler;
            }

            stopAsyncRebalancing.Add(loadBalancerListener.StopRebalance);
            this.RegisterConsumerInZk(dirs, consumerIdString, topicCount);

            //// register listener for session expired event
            var zkSessionExpireListener = new ZKSessionExpireListener <TData>(dirs, consumerIdString, topicCount, loadBalancerListener, this);

            if (this.zkSessionDisconnectedHandler != null)
            {
                zkSessionExpireListener.ZKSessionDisconnected += this.zkSessionDisconnectedHandler;
            }

            if (this.zkSessionExpiredHandler != null)
            {
                zkSessionExpireListener.ZKSessionExpired += this.zkSessionExpiredHandler;
            }

            this.GetZkClient().Subscribe(zkSessionExpireListener);
            this.subscribedZookeeperStateCollection.Add(zkSessionExpireListener);

            this.GetZkClient().Subscribe(dirs.ConsumerRegistryDir, loadBalancerListener);
            this.subscribedChildCollection.Add(new Tuple <string, IZooKeeperChildListener>(dirs.ConsumerRegistryDir, loadBalancerListener));

            result.ForEach(topicAndStreams =>
            {
                // register on broker partition path changes
                string partitionPath = ZooKeeperClient.DefaultBrokerTopicsPath + "/" + topicAndStreams.Key;
                if (this.GetZkClient().Exists(partitionPath))
                {
                    this.GetZkClient().Subscribe(partitionPath, loadBalancerListener);
                    this.subscribedChildCollection.Add(new Tuple <string, IZooKeeperChildListener>(partitionPath, loadBalancerListener));
                    // Create a mapping of all topic partitions and their current leaders
                    var topicsAndPartitions = ZkUtils.GetPartitionsForTopics(this.GetZkClient(), new[] { topicAndStreams.Key });
                    Dictionary <string, int> partitionLeaderMap = new Dictionary <string, int>();
                    foreach (var partitionId in topicsAndPartitions[topicAndStreams.Key])
                    {
                        // Find/parse current partition leader for this partition and add it
                        // to the mapping object
                        var partitionStatePath = partitionPath + "/partitions/" + partitionId + "/state";
                        this.GetZkClient().MakeSurePersistentPathExists(partitionStatePath);
                        int?partitionLeader = ZkUtils.GetLeaderForPartition(this.GetZkClient(), topicAndStreams.Key, int.Parse(partitionId));
                        partitionLeaderMap.Add(partitionStatePath, partitionLeader.GetValueOrDefault(-1));
                    }

                    // listen for changes on the state nodes for the partitions
                    // this will indicate when a leader switches, or the in sync replicas change
                    var leaderListener = new ZkPartitionLeaderListener <TData>(loadBalancerListener, partitionLeaderMap);
                    foreach (var partitionId in topicsAndPartitions[topicAndStreams.Key])
                    {
                        var partitionStatePath = partitionPath + "/partitions/" + partitionId + "/state";
                        this.GetZkClient().Subscribe(partitionStatePath, leaderListener);
                        this.subscribedZookeeperDataCollection.Add(new Tuple <string, IZooKeeperDataListener>(partitionStatePath, leaderListener));
                    }
                }
                else
                {
                    Logger.WarnFormat("The topic path at {0}, does not exist.", partitionPath);
                }
            });

            //// explicitly trigger load balancing for this consumer
            Logger.Info("Performing rebalancing. A new consumer has been added to consumer group: " + dirs.ConsumerRegistryDir + ", consumer: " + consumerIdString);
            Logger.InfoFormat("Subscribe count: subscribedChildCollection:{0} , subscribedZookeeperStateCollection:{1} subscribedZookeeperDataCollection:{2} "
                              , subscribedChildCollection.Count, subscribedZookeeperStateCollection.Count, subscribedZookeeperDataCollection.Count);

            //// When a new consumer join, need wait for rebalance finish to make sure Fetcher thread started.
            loadBalancerListener.AsyncRebalance(DefaultWaitTimeForInitialRebalanceInSeconds * 1000);

            return(result);
        }
コード例 #45
0
 public override void Debug(string message)
 {
     _logger.Debug(message);
 }
コード例 #46
0
 public void LogDebug(string source, Exception ex = null)
 {
     Log.Debug(source, ex);
 }
コード例 #47
0
 public static void debug(string str, LoggerSource source)
 {
     logger.Debug(createMessage(str, source));
 }
 public ScratchListener1()
 {
     LogEvent.Debug($"{MethodInfo.GetCurrentMethod().Name}");
 }
コード例 #49
0
 public static void LogDebug(object message)
 {
     Configure();
     _log.Debug(message);
 }
コード例 #50
0
        public JObject powerShellScript(String script)
        {
            try
            {
                // Execute PowerShell Script for Result Value.
                PowerShell PowerShellInstance = PowerShell.Create();
                PowerShellInstance.AddScript(script);
                // invoke execution on the pipeline (collecting output)
                Collection <PSObject> PSOutput = PowerShellInstance.Invoke();
                log.Debug("실행된 스크립트: " + script);

                // check the other output streams (for example, the error stream)
                if (PowerShellInstance.Streams.Error.Count > 0)
                {
                    // error records were written to the error stream.
                    // do something with the items found.
                    JObject error    = new JObject();
                    String  logError = "";
                    foreach (System.Management.Automation.ErrorRecord record in PowerShellInstance.Streams.Error)
                    {
                        logError += record.ToString();
                    }
                    log.Error("에러 발생: " + logError);
                    error.Add("error", logError);
                    return(error);
                }

                // Warning 메세지도 로그에 남긴다.
                if (PowerShellInstance.Streams.Warning.Count > 0)
                {
                    // error records were written to the error stream.
                    // do something with the items found.
                    String logWarning = "";
                    foreach (System.Management.Automation.WarningRecord record in PowerShellInstance.Streams.Warning)
                    {
                        logWarning += record.ToString();
                    }
                    log.Warn("에러 발생: " + logWarning);
                }

                JObject result = new JObject();
                if (PSOutput.Count == 0)
                {
                    result = new JObject();
                }
                else if (PSOutput.Count == 1)
                {
                    JArray resultJArray = new JArray();
                    try
                    {
                        result = JObject.Parse(PSOutput[0].ToString());
                    }
                    catch (Newtonsoft.Json.JsonReaderException)
                    {
                        try
                        {
                            resultJArray = JArray.Parse(PSOutput[0].ToString());
                        }
                        catch (Newtonsoft.Json.JsonReaderException jarrerr)
                        {
                            result.Add("result", PSOutput[0].ToString());
                        }
                    }

                    if (resultJArray.Count > 0)
                    {
                        result.Add("resultArray", resultJArray);
                    }
                }
                else
                {
                    JArray returnArr = new JArray();
                    // loop through each output object item
                    foreach (PSObject outputItem in PSOutput)
                    {
                        // if null object was dumped to the pipeline during the script then a null
                        // object may be present here. check for null to prevent potential NRE.
                        if (outputItem != null)
                        {
                            //TODO: do something with the output item
                            // outputItem.BaseOBject
                            returnArr.Add(JToken.Parse(outputItem.BaseObject.ToString()));
                        }
                        result.Add("resultArray", returnArr);
                    }
                }

                return(result);
            }
            catch (InvalidOperationException e)
            {
                log.Error("InvalidOperationException: ", e);
                JObject error = new JObject();
                error.Add("error", e.Message);
                return(error);
            }
            catch (ScriptCallDepthException e)
            {
                log.Error("ScriptCallDepthException: ", e);
                JObject error = new JObject();
                error.Add("error", e.Message);
                return(error);
            }
            catch (RuntimeException e)
            {
                log.Error("RuntimeException: ", e);
                JObject error = new JObject();
                error.Add("error", e.Message);
                return(error);
            }
            catch (Exception e)
            {
                log.Error("RuntimeException: ", e);
                JObject error = new JObject();
                error.Add("error", e.Message);
                return(error);
            }
        }
コード例 #51
0
        public void SaveOrderSessionIDsToDB(int idSessao)
        {
            try
            {
                // Serialize Dictionary to dat file
                if (!_serializing)
                {
                    _serializing = true;
                    Dictionary <string, TOOrderSession> regs = new Dictionary <string, TOOrderSession>(_dicMsgsCl);
                    DbFix dbFix = new DbFix();
                    logger.Info("Inicio da Gravacao");

                    // Efetuar a limpeza para "re-gravar" os registros
                    if (!dbFix.LimparOrderSessionIDs(idSessao))
                    {
                        logger.Info("Problemas na limpeza dos OrderSessionIDs");
                        return;
                    }

                    foreach (KeyValuePair <string, TOOrderSession> item in regs)
                    {
                        TOMessageBackup to = new TOMessageBackup();

                        to.Key           = item.Key;
                        to.BeginString   = item.Value.Sessao.BeginString;
                        to.SenderCompID  = item.Value.Sessao.SenderCompID;
                        to.SenderSubID   = item.Value.Sessao.SenderSubID;
                        to.TargetCompID  = item.Value.Sessao.TargetCompID;
                        to.TargetSubID   = item.Value.Sessao.TargetSubID;
                        to.TipoExpiracao = item.Value.TipoExpiracao;
                        to.DataExpiracao = item.Value.DataExpiracao;
                        to.DataEnvio     = item.Value.DataEnvio;
                        to.MsgSeqNum     = item.Value.MsgSeqNum.ToString();
                        to.ClOrdID       = item.Value.ClOrdID;
                        to.OrigClOrdID   = item.Value.OrigClOrdID;
                        to.Account       = item.Value.Account.ToString();
                        int lenPid = item.Value.PartyIDs.Count;
                        for (int i = 0; i < lenPid; i++)
                        {
                            PartyIDBackup pId = new PartyIDBackup();
                            pId.PartyID       = item.Value.PartyIDs[i].GetField(Tags.PartyID);
                            pId.PartyIDSource = item.Value.PartyIDs[i].GetChar(Tags.PartyIDSource);
                            pId.PartyRole     = item.Value.PartyIDs[i].GetInt(Tags.PartyRole);
                            to.PartyIDs.Add(pId);
                        }
                        to.TipoLimite       = (int)item.Value.TipoLimite;
                        to.Order            = item.Value.Order;
                        to.MensagemQF       = item.Value.MensagemQF.ToString();
                        to.ExchangeNumberID = item.Value.ExchangeNumberID;
                        to.ExchangeSeqNum   = item.Value.ExchangeSeqNum;
                        dbFix.InserirOrderSessionItem(idSessao, to);
                        to = null;
                    }
                    logger.InfoFormat("Gravando OrderSessions da Sessao: [{0}] Registros: [{1}]", idSessao, regs.Count);
                    //BinaryFormatter bs = new BinaryFormatter();
                    //bs.Serialize(fs, lst);
                    //bs = null;
                    //fs.Close();
                    //fs = null;
                    regs.Clear();
                    regs         = null;
                    _serializing = false;
                }
                else
                {
                    if (_serializing)
                    {
                        logger.Debug("SaveSessionIDS(): Processo de serializacao já em execucao!!!");
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("SaveSessionIDS(): Erro na serializacao dos registros do dicionario: " + ex.Message, ex);
                _serializing = false; // mudar para false para tentar backupear no proximo "ciclo"
                //fs.Close();
                //fs = null;
            }
        }
コード例 #52
0
ファイル: TakeOutItemData.cs プロジェクト: TranTan90/hana
        /// <summary>
        ///
        /// </summary>
        /// <param name="takeOutItemDataCode"></param>
        /// <returns></returns>
        public TakeOutItemDataInfo  selectTakeOutItemData(string takeOutItemDataCode)
        {
            log.Debug("=================START selectTakeOutItemData=================");
            log.Debug("takeOutItemDataCode = " + takeOutItemDataCode);

            TakeOutItemDataInfo obj = new TakeOutItemDataInfo();

            StringBuilder sql_select = new StringBuilder();

            sql_select.Append(@"
							SELECT	a.takeOutItemDataCode as takeOutItemDataCode,
							a.takeOutDataCode as takeOutDataCode,
							c.takeOutItemCategoryCode as parentCategoryCode,
							c.codeNAme as parentCodeName,
							b.takeOutItemCategoryCode as subCategoryCode,
							b.codeNAme as subCodeName,
							a.takeOutItemName as takeOutItemName,
							a.takeOutItemType as takeOutItemType,
							a.account as account,
							a.unitCode as unitCode,
							d.codeName as unitName,
							a.regDate
					FROM	TakeOutItemData a,TakeOutItemCategory b ,TakeOutItemCategory c, Unit d
					WHERE	a.takeOutItemCategoryCode=b.takeOutItemCategoryCode
							AND b.groupID=c.takeOutItemCategoryCode
							AND a.unitCode=d.unitCode
							AND a.takeOutItemDataCode="                             + takeOutItemDataCode);

            using (SqlDataReader rdr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, sql_select.ToString(), null))
            {
                if (rdr.Read())
                {
                    obj = bindObject(rdr, obj);
                }
            }

            log.Debug(@"=================END selectTakeOutItemData=================");
            return(obj);
        }
コード例 #53
0
        public static List <route_table> GetRoutes()
        {
            //get method name
            string MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            //initialize entities
            var ctx = new rentalanguageteacherEntities();
            {
                ctx.Configuration.ProxyCreationEnabled = false;

                try
                {
                    log.Debug(MethodName + "**********************************************************************************************************");
                    log.Debug(MethodName + "() - Start");

                    // get user
                    var MyObject = (from s in ctx.route_table
                                    select s).ToList <route_table>();

                    //log
                    if (!object.ReferenceEquals(MyObject, null))
                    {
                        // log.Debug(MethodName + "() - The item for ID " + UserId + " was returned");
                    }

                    else
                    {
                        //  log.Debug(MethodName + "() - The item for ID " + UserId + " returned 0 results");
                    }

                    return(MyObject);
                }

                catch (NullReferenceException e)
                {
                    log.Error(MethodName + "() - " + e.Message);
                    log.Debug(MethodName + "() - " + e.StackTrace);
                    throw (e);
                }

                catch (Exception e)
                {
                    log.Error(MethodName + "() - " + e.Message);
                    log.Debug(MethodName + "() - " + e.StackTrace);
                    throw (e);
                }

                finally
                {
                    log.Debug(MethodName + "() - Finish");
                    log.Debug(MethodName + "**********************************************************************************************************");
                }
            }
        }
コード例 #54
0
ファイル: WKT.svc.cs プロジェクト: msruzy/hydronumerics
        /// <summary>
        /// GetSQLDataWKT
        ///     returns WKT with results of SQL Server query
        /// </summary>
        /// <param name="Parameters">WKTParameters required for query</param>
        public WKTResponse GetSQLDataWKT(WKTParameters Parameters)
        {
            DateTime queryStart = DateTime.Now;
            DateTime queryStop;
            int      recordCnt = 0;

            WKTResponse _WKTResponse = new WKTResponse();

            _WKTResponse.ErrorCode     = 0;
            _WKTResponse.OutputMessage = "Success";
            _WKTResponse.OutputShapes  = new List <WKTShape>();
            string        connStr = ConfigurationManager.ConnectionStrings["DataConnectionString"].ConnectionString;
            SqlConnection conn    = new SqlConnection(connStr);
            SqlDataReader rdr     = null;

            try
            {
                if (Parameters.querytype == null || Parameters.querytype.Length == 0)
                {
                    throw new ArgumentException("Invalid Parameters: querytype=\"" + Parameters.querytype + "\"");
                }
                if (Parameters.querytype.ToLower().Equals("buffer") && Parameters.radius <= 0)
                {
                    throw new ArgumentException("Invalid Parameters: querytype requires radius >0 - \"" + Parameters.radius + "\"");
                }
                if (Parameters.points.Length == 0 && Parameters.querytype.ToLower().Equals("buffer"))
                {
                    throw new ArgumentException("Invalid Parameters: points must contain at least one point for querytype buffer");
                }
                if (Parameters.points.Split(',').Length != 5 && Parameters.querytype.ToLower().Equals("bbox"))
                {
                    throw new ArgumentException("Invalid Parameters: points must contain 5 points for a closed querytype bbox");
                }

                StringBuilder query = new StringBuilder();

                if (Parameters.querytype.ToLower().Equals("bbox"))
                {   //BBox
                    query.Append("SELECT *," + geomField + ".Reduce(@reduce).STAsText() as " + geomField + "wkt FROM [dbo].[" + Parameters.table + "] WITH(INDEX(the_geo_sidx)) WHERE ");
                    query.Append(geomField + ".STIntersects(geography::STGeomFromText('POLYGON(('+@points+'))', @srid))=1");
                }
                else if (Parameters.querytype.ToLower().Equals("buffer"))
                {
                    query.Append("SELECT *," + geomField + ".Reduce(@reduce).STAsText() as " + geomField + "wkt FROM [dbo].[" + Parameters.table + "] WITH(INDEX(the_geo_sidx)) WHERE ");
                    if (Parameters.points.Split(',').Length > 1)
                    {   //Polyline Buffer
                        query.Append(geomField + ".STIntersects(geography::STGeomFromText('LINESTRING('+@points+')', @srid).STBuffer(@radius))=1");
                    }
                    else
                    {   //Point Buffer
                        query.Append(geomField + ".STIntersects(geography::STGeomFromText('POINT('+@points+')', @srid).STBuffer(@radius))=1");
                    }
                }
                log.Info(query);

                queryStart = DateTime.Now;
                SqlCommand cmd = new SqlCommand(query.ToString(), conn);
                cmd.Parameters.Add(new SqlParameter("reduce", Parameters.reduce));
                cmd.Parameters.Add(new SqlParameter("srid", srid));
                cmd.Parameters.Add(new SqlParameter("points", Parameters.points));
                cmd.Parameters.Add(new SqlParameter("radius", Parameters.radius));
                conn.Open();

                rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    WKTShape shp = new WKTShape();
                    shp.Fields = new Dictionary <string, string>();
                    for (int i = 0; i < rdr.FieldCount; i++)
                    {
                        log.Debug(rdr[i].GetType() + "  " + rdr.GetName(i));
                        if (rdr[i].GetType().Equals(typeof(SqlGeography)) ||
                            rdr[i].GetType().Equals(typeof(SqlGeometry))
                            )
                        { //skip
                            log.Debug("skip " + rdr[i].GetType());
                        }
                        else
                        {
                            if (rdr.GetName(i).Equals("ID"))
                            {
                                shp.ID = rdr[i].ToString();
                                log.Debug(rdr[i].GetType() + "  " + rdr.GetName(i) + "  " + rdr[i].ToString());
                            }
                            else if (rdr.GetName(i).Equals(geomField + "wkt"))
                            {
                                log.Debug(rdr[i].GetType() + "  " + rdr.GetName(i) + "  " + rdr[i].ToString());
                                shp.WKT = rdr[i].ToString();
                            }
                            else
                            {
                                shp.Fields.Add(rdr.GetName(i), rdr[i].ToString());
                                log.Debug(rdr.GetName(i) + " : " + rdr[i].ToString());
                            }
                        }
                    }
                    log.Debug(shp.ID + "  " + shp.WKT);
                    if (recordCnt++ > recordLimit)
                    {
                        throw new Exception("Query result exceeds limit " + recordLimit);
                    }
                    _WKTResponse.OutputShapes.Add(shp);
                }
            }
            catch (ArithmeticException e)
            {
                ServiceException(_WKTResponse, "ArithmeticException " + e.Message, 3);
            }
            catch (ArgumentException e)
            {
                ServiceException(_WKTResponse, "ArgumentException " + e.Message, 1);
            }
            catch (Exception e)
            {
                ServiceException(_WKTResponse, e.Message, 2);
            }
            finally
            {
                if (rdr != null)
                {
                    rdr.Close();
                }
                if (conn != null)
                {
                    conn.Close();
                }
            }
            queryStop = DateTime.Now;
            log.Debug(String.Format("Query Time: {0,0:0}ms", (queryStop - queryStart).TotalMilliseconds));
            _WKTResponse.QueryTime = (queryStop - queryStart).TotalMilliseconds;

            return(_WKTResponse);
        }
コード例 #55
0
        public Response Search()
        {
            Logger.Debug("Method called.");
            var user = UserSession.GetCurrent();

            {
                // User Securities
                Logger.Info(string.Format("Called by ({0},{1})", user.Username, user.IpsUserKey));

                // Called the SQL Query
                var taskResult = KioskCheckInService.View_Users();

                if (taskResult.Result.HasFailed)
                {
                    Logger.Error(string.Format("({0},{1}) [{2}] {3} Stack: {4}", user.Username, user.IpsUserKey, taskResult.Result.Code, taskResult.Result.Message, taskResult.Result.Stack));
                    Logger.Info("200 Success response sent with failure message.");
                    return(Response.Failure(taskResult.Result.Message));
                }

                Logger.Info("200 Success response sent.");
                return(Response.Success(taskResult.Data));
            }

            Logger.Info("401 Unauthorized response sent.");
            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        }
コード例 #56
0
 private void DebugConditional(object message)
 {
     _log.Debug(message);
 }
コード例 #57
0
 public void Debug(object msg)
 {
     log4.Debug(EncryptPassword(msg));
 }
コード例 #58
0
 public ActionResult Index()
 {
     Log.Debug("DBController.Index() started");
     return(GetFilesDataFromDB());
 }
コード例 #59
0
 public void Debug <T>(object message)
 {
     //log.LogDebug(message.ToString());
     log4.Debug(message);
 }
コード例 #60
0
 /// <summary>
 /// Log the message in Debug level
 /// </summary>
 /// <param name="message">the message to log</param>
 public void Debug(string message)
 {
     _logger.Debug(message);
 }