Exemplo n.º 1
0
        public Task <int> Add(int a, int b)
        {
            ILog log = new DefaultLog(Current.GetLogger <ClientTestController>());

            log.Info($"server request {a}+{b}");
            return(Task.FromResult(a + b));
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            ILog log1 = new DefaultLog("ModbusTCPClientHanderTask")
            {
                Handle = LogHandle.writeFile
            };

            ILog log2 = new DefaultLog("ModbusServerHanderTask")
            {
                Handle = LogHandle.debug, ByteSteamLogSwicth = true
            };
            var client = new ModbusTCPClientHanderTask(log1);

            if (client.OnInit())
            {
                client.OnStart();
            }

            var server = new ModbusServerHanderTask(log2);

            if (server.OnInit())
            {
                server.OnStart();
            }
            Console.ReadKey();
        }
Exemplo n.º 3
0
        public static void Main(string[] args)
        {
            // Init KLog
            DefaultLog.Log = new ColouredConsoleLog(LogLevel.All);

            DefaultLog.Info("Tweetinvi Request Signer Demo Application");

            // Set up Remote Authorisation
            TwitterQueryRemoteAuth.Register();
            Requester.ServerUrl = "http://localhost:50154/";

            // Set up credentials as you usually would for Tweetinvi, just using null for the consumer secret
            Auth.SetUserCredentials(CONSUMER_KEY, null,
                                    CLIENT_TOKEN, CLIENT_SECRET);

            // Send a request to Twitter
            IEnumerable <ITweet> tweets = Search.SearchTweets("test");

            // Check response
            if (tweets == null)
            {
                DefaultLog.Error("An error occurred whilst running the search");

                IEnumerable <ITwitterException> exceptions = ExceptionHandler.GetExceptions();
                foreach (ITwitterException e in exceptions)
                {
                    DefaultLog.Error("Tweetinvi Twitter Exception:\n{0}", e);
                }
            }
            else
            {
                DefaultLog.Info("Successfully fetched {0} Tweets", tweets.Count());
            }
        }
Exemplo n.º 4
0
        public CloudServer(IContainer container)
        {
            Container = container;

            var timeoutoption = container.Resolve <TimeOutOptions>();

            TokenWaitClecrTime      = timeoutoption.TokenWaitClecrTime;
            ReadOutTimeMilliseconds = timeoutoption.ReadOutTimeMilliseconds;
            IsCheckReadTimeOut      = timeoutoption.IsCheckReadOutTime;
            var bufferoption = container.Resolve <BufferSizeOptions>();

            MaxPacksize = bufferoption.MaxPackSize;
            var decodeoption = container.Resolve <DataEncodeOptions>();

            if (container.IsRegistered <IConnectfilter>())
            {
                ConnectFilter = container.Resolve <IConnectfilter>();
            }

            Server = container.Resolve <ISocketServer>();

            LoggerFactory = container.Resolve <ILoggerFactory>();
            Log           = new DefaultLog(LoggerFactory?.CreateLogger <CloudServer>());
            Init();
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            EthernetSetUp setup = new EthernetSetUp("192.168.1.240", 102);
            ILog          log   = new DefaultLog("S7CommomClient")
            {
                ByteSteamLogSwicth = true, Handle = LogHandle.debug
            };
            TimeOut      timeout = new TimeOut("S7CommomClient", 1000, log);
            S7CommClient client  = new S7CommClient(setup, timeout, log, 1);

            if (client.Connect())
            {
                //DB块编号,地址,访问数据块的类型:0x81-input ,0x82-output ,0x83-flag , 0x84-DB;
                var address = new DeviceAddress(30, 0, 0x84, ByteOrder.BigEndian);

                var temp = client.ReadUShorts(address, 2);
                Thread.Sleep(1000);
                var temp1 = client.ReadBytes(address, 3);

                var address1 = new DeviceAddress(14, 0, 0x84, ByteOrder.BigEndian);
                var result   = client.WriteUShort(address1, 12);
                var temp3    = client.ReadUShorts(address1, 1);
            }
            Console.ReadKey();
        }
Exemplo n.º 6
0
Arquivo: Actor.cs Projeto: luyikk/NetX
        public Actor(IServiceProvider container, IActorGet actorGet, ActorScheduler actorScheduler, ActorController instance)
        {
            this.ActorGet        = actorGet;
            this.ActorController = instance;

            var options = instance.GetType().GetCustomAttributes <ActorOptionAttribute>(false);

            Option = new ActorOptionAttribute();
            foreach (var attr in options)
            {
                if (attr is ActorOptionAttribute option)
                {
                    Option = option;
                }
            }

            this.ActorScheduler = Option.SchedulerType switch
            {
                SchedulerType.None => actorScheduler,
                SchedulerType.LineByLine => ActorScheduler.LineByLine,
                SchedulerType.TaskFactory => ActorScheduler.TaskFactory,
                SchedulerType.TaskRun => ActorScheduler.TaskRun,
                _ => actorScheduler
            };


            maxQueuelen = Option.MaxQueueCount;
            ActorController.ActorGet = ActorGet;
            ActorController.Status   = this;
            this.Container           = container;

            actorRunQueue = new Lazy <ConcurrentQueue <ActorMessage> >();
            Log           = new DefaultLog(container.GetRequiredService <ILoggerFactory>().CreateLogger($"Actor-{instance.GetType().Name}"));
            this.CmdDict  = LoadRegister(instance.GetType());
        }
Exemplo n.º 7
0
 public Repository(string connStr, AccessUser accessUser)
 {
     this._accessUser = accessUser;
     tableInfo        = TableInfo.GetTableInfo <T>();
     _connStr         = connStr;
     Logger           = DefaultLog.GetLogger(this.GetType());
     MonitorLogger    = DefaultLog.GetMonitorLogger(this.GetType());
 }
Exemplo n.º 8
0
        public SayShowModel(ListView listView, IMessageAdd messageAdd, byte type, long fromId = -1, string target = null)
        {
            ListMessages           = new ObservableRangeCollection <MessageTable>();
            messageAdd.MessageAdd += MessageAdd_MessageAdd;

            Current = DependencyService.Get <ClientService>().Client;
            Log     = new DefaultLog(Current.GetLogger <SayShowModel>());
            Loading(type, fromId);

            this.type         = type;
            this.fromId       = fromId;
            this.ShowListView = listView;
            SelectItemCommand = new Command(() => { });
            SendCommand       = new Command(async() =>
            {
                try
                {
                    if (!string.IsNullOrEmpty(OutText))
                    {
                        var(succ, msg) = await Current.Get <IServer>().Say(fromId, OutText);

                        if (!succ)
                        {
                            Log.Error(msg);
                        }
                        else
                        {
                            var database = DependencyService.Get <ChaTDataBaseManager>();

                            if (type != 0)
                            {
                                var t_msg = new MessageTable()
                                {
                                    FromId         = messageAdd.My.UserId,
                                    FromName       = messageAdd.My.NickName,
                                    TargetId       = fromId,
                                    TargetName     = target,
                                    MessageContext = OutText,
                                    MsgType        = type,
                                    Time           = DateTime.Now
                                };

                                await database.SaveMessage(t_msg);

                                ListMessages.Add(t_msg);
                                MoveEnd();
                            }

                            OutText = null;
                        }
                    }
                }
                catch (Exception er)
                {
                    Log.Error(er);
                }
            });
        }
Exemplo n.º 9
0
 public void Creation()
 {
     using (DefaultLog File = new DefaultLog("Test", "~/Logs/"))
     {
         Assert.NotNull(File);
         Assert.True(new FileInfo(File.FileName).Exists);
     }
     new DirectoryInfo("~/Logs/").Delete();
 }
Exemplo n.º 10
0
        public ServiceBase(IServiceProvider container)
        {
            LoggerFactory = container.GetRequiredService <ILoggerFactory>();
            Log           = new DefaultLog(LoggerFactory.CreateLogger("NetxService"));
            SerializationPacker.Serialization = container.GetRequiredService <ISerialization>();
            Container = container;

            ServiceOption = container.GetRequiredService <IOptions <ServiceOption> >().Value;
        }
Exemplo n.º 11
0
 public AsyncBase(IServiceProvider container, IFiberRw <AsyncToken> fiberRw, long sessionId)
 {
     Container  = container;
     SessionId  = sessionId;
     FiberRw    = fiberRw;
     IsConnect  = true;
     IWrite     = fiberRw;
     Log        = new DefaultLog(container.GetRequiredService <ILogger <AsyncToken> >());
     IdsManager = container.GetRequiredService <IIds>();
 }
 /// <summary>
 /// Adds a log to the logger
 /// </summary>
 /// <param name="Name">Name of the log</param>
 public override void AddLog(string Name = "Default")
 {
     if (!Logs.ContainsKey(Name))
         Logs.Add(Name, new DefaultLog(Name));
     else
     {
         Logs[Name].Dispose();
         Logs[Name] = new DefaultLog(Name);
     }
 }
Exemplo n.º 13
0
        public NetxClientBase(IServiceProvider container)
        {
            Container     = container;
            Log           = new DefaultLog(container.GetRequiredService <ILogger <NetxSClient> >());
            ConnectOption = container.GetRequiredService <IOptions <ConnectOption> >().Value;
            Session       = container.GetRequiredService <ISessionStore>();
            SerializationPacker.Serialization = container.GetRequiredService <ISerialization>();
            IdsManager = container.GetRequiredService <IIds>();

            Task.Factory.StartNew(RunRequestCheck);
        }
Exemplo n.º 14
0
 public void LogMessage()
 {
     using (DefaultLog File = new DefaultLog("Test", "~/Logs/"))
     {
         foreach (MessageType Type in Enum.GetValues(typeof(MessageType)))
         {
             File.LogMessage("TestMessage", Type);
         }
         Assert.Contains("\r\nGeneral: TestMessage\r\nDebug: TestMessage\r\nTrace: TestMessage\r\nInfo: TestMessage\r\nWarn: TestMessage\r\nError: TestMessage\r\n", new FileInfo(File.FileName).Read());
     }
     new DirectoryInfo("~/Logs/").Delete();
 }
Exemplo n.º 15
0
        private static IDefaultLog CreateDefaultLog()
        {
            var logForScheduler = LogManager.GetLogger(Constants.SCHEDULER_LOGGER);

            var log = new DefaultLog();

            log.SetLogDebug(msg => logForScheduler.Debug(msg));
            log.SetLogInfo(msg => logForScheduler.Info(msg));
            log.SetLogError((msg, ex) => logForScheduler.Error(msg, ex));

            return(log);
        }
Exemplo n.º 16
0
        public IFSController(IUserVerification verification, IOptions <IFSOption> options, ILogger <IFSController> logger)
        {
            Log    = new DefaultLog(logger);
            Option = options.Value;

            Verification = verification;

            if (!Directory.Exists(Option.Path))
            {
                Log.Info($"Create base path {Option.Path}");
                Directory.CreateDirectory(Option.Path);
            }
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            /*LogReader MyReader = new LogReader(@"C:\Users\benba\Documents\Visual Studio 2017\Projects\BenLog\log.txt");
             * //MyReader.DisplayLog();
             * MyReader.DisplayParsedLog();*/



            //DefaultLog.Break();
            DefaultLog.Info("Hello world!");

            LogReader MyLogReader = new LogReader(DefaultLog.LogFileDir);

            if (MyLogReader.)
            {
                Console.ReadLine();
            }
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            ILog log = new DefaultLog("FreedomServer");

            PointMapping <bool> boolMaping = PointMapping <bool> .GetInstance(log);

            PointMapping <byte> byteMaping = PointMapping <byte> .GetInstance(log);

            PointMapping <ushort> ushortMaping = PointMapping <ushort> .GetInstance(log);

            PointMapping <short> shortMaping = PointMapping <short> .GetInstance(log);

            PointMapping <int> intMaping = PointMapping <int> .GetInstance(log);

            PointMapping <uint> uintMaping = PointMapping <uint> .GetInstance(log);

            PointMapping <float> floatMaping = PointMapping <float> .GetInstance(log);

            for (int i = 0; i < 1000; i++)
            {
                var bpoint = new VirtulPoint <bool>(string.Concat("boolSignal", i), DataServer.ValueType.Bool, new bool[] { true });
                boolMaping.Register(bpoint.Name, bpoint);
                var bypoint = new VirtulPoint <byte>(string.Concat("byteSignal", i), DataServer.ValueType.Byte, new byte[] { 10 });
                byteMaping.Register(bypoint.Name, bypoint);
                var ushortpoint = new VirtulPoint <ushort>(string.Concat("ushortSignal", i), DataServer.ValueType.UInt16, new ushort[] { Convert.ToUInt16(i) });
                ushortMaping.Register(ushortpoint.Name, ushortpoint);
                var shortpoint = new VirtulPoint <short>(string.Concat("shortSignal", i), DataServer.ValueType.Int16, new short[] { Convert.ToInt16(i) });
                shortMaping.Register(shortpoint.Name, shortpoint);
                var intpoint = new VirtulPoint <int>(string.Concat("intSignal", i), DataServer.ValueType.Int32, new int[] { i });
                intMaping.Register(intpoint.Name, intpoint);
                var uintpoint = new VirtulPoint <uint>(string.Concat("uintSignal", i), DataServer.ValueType.UInt32, new uint[] { Convert.ToUInt32(i) });
                uintMaping.Register(uintpoint.Name, uintpoint);
            }

            EthernetSetUp setup   = new EthernetSetUp("127.0.0.1", 9527);
            TimeOut       timeout = new TimeOut("FreedomeServer", 1000, log);

            FreedomDrivers.FreedomServer fs = new FreedomDrivers.FreedomServer(setup, timeout, log);
            if (fs.Init())
            {
                fs.Start();
            }
            Console.ReadKey();
        }
Exemplo n.º 19
0
        private UpdatesViewModel CreateUpdatesViewModel()
        {
            var log = new DefaultLog();

            var contentService        = new NuGetPackageContentService(log);
            var packageSources        = new NuGetPackageSourceCollection(new PackageSourceProvider(new Settings(Environment.CurrentDirectory)));
            var packageSourceSelector = new AllPackageSourceSelector(packageSources);
            var versionService        = new NuGetPackageVersionService(contentService, log);

            var repositoryFactory        = new NuGetSourceRepositoryFactory();
            var installService           = new NuGetInstallService(repositoryFactory, log, Args.Path, contentService, versionService);
            var searchService            = new NuGetSearchService(repositoryFactory, log, contentService, versionService);
            var selfPackageConfiguration = new SelfPackageConfiguration(Args.SelfPackageId);
            var selfUpdateService        = new SelfUpdateService(this, new ProcessService(this, Array.Empty <string>()));

            UpdatesViewModel viewModel = new UpdatesViewModel(packageSourceSelector, installService, searchService, selfPackageConfiguration, selfUpdateService, NuGetPackageVersionComparer.Instance);

            return(viewModel);
        }
Exemplo n.º 20
0
        private void init()
        {
            //数据配置
            pointMetaData = new List <PointMetadata>();

            //Meu窗口配置
            searchWin = new SearchWindow()
            {
                SignalDisplayList = signalList, ClientAsync = clientAsync
            };
            connectWindow = new ConnectWindow();
            SignalMeItem.AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler(signalMeItemMouseLeftButtonDown), true);
            ConnectMeItem.AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler(ConnectMeItemMouseLeftButtonDown), true);


            ///连接到服务端配置
            EthernetSetUp setUp   = new EthernetSetUp("127.0.0.1", 9527);
            ILog          log     = new DefaultLog("SignalMonitor");
            TimeOut       timeOut = new TimeOut("SignalMonitor", 1000, log);

            clientAsync = new FreedomClientAsync(setUp, timeOut, log);


            //读服务器元数据
            clientAsync.AsyncReadMetaData += asyncReadMetaData;

            //订阅client操作事件
            clientAsync.AsyncReadOrSubsEvent += asyncReadOrSubsEvent;
            clientAsync.AsyncWriteEvent      += ayncWriteEvent;
            clientAsync.DisconnectEvent      += disconnectEvent;

            //断线重连事件
            reTime          = new System.Timers.Timer(3000);
            reTime.Elapsed += ReTime_Elapsed;

            if (clientAsync.Connect())
            {
                clientAsync.ReadMetaData();
            }
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            ILog log = new DefaultLog("ModbusTCPServer");
            ModbusPointMapping mapping = ModbusPointMapping.GetInstance(log);

            for (int i = 1; i < 1001; i++)
            {
                var key = string.Format("{0:D5}", 40000 + i);
                mapping.Register(key, new VirtulPoint <ushort>(key, "ushort", new ushort[] { (ushort)i }));
                var key1 = string.Format("{0:D5}", 00000 + i);
                mapping.Register(key1, new VirtulPoint <bool>(key1, "bool", new bool[] { true }));
                var key2 = string.Format("{0:D5}", 10000 + i);
                mapping.Register(key2, new VirtulPoint <bool>(key2, "bool", new bool[] { true }));
                var key3 = string.Format("{0:D5}", 30000 + i);
                mapping.Register(key3, new VirtulPoint <ushort>(key3, "ushort", new ushort[] { (ushort)(i * 2) }));
            }
            ModbusTCPServer server = new ModbusTCPServer(new EthernetSetUp("127.0.0.1", 502), new TimeOut("ModbusServer", 10000, log), log, 5, 1);

            server.Init();
            server.Start();
            Console.ReadKey();
        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            //EthernetSetUp _setup  = new EthernetSetUp("127.0.0.1", 502);
            SerialportSetUp _setup   = new SerialportSetUp("com3", 9600, 8, StopBits.One);
            ILog            _log     = new DefaultLog("ModbusTCPClient");
            TimeOut         _timeout = new TimeOut("ModbusTCPClient", 1000, _log);
            //ModbusTCPClient _client = new ModbusTCPClient(_setup,_timeout,_log);
            var _client = new ModbusRTUMaster(_setup, _timeout, _log);

            if (_client.Connect())//先判断是否能连接到客户端
            {
                //var boolvalue = _client.ReadBool(new DeviceAddress(1, 00001));
                //var boolvalues = _client.ReadBools(new DeviceAddress(1, 00001),10);

                //var boolvalue1 = _client.ReadBool(new DeviceAddress(1, 10001));
                //var boolvalue1s = _client.ReadBools(new DeviceAddress(1, 10001), 10);

                //var shortvalue = _client.ReadShort(new DeviceAddress(1, 30001));
                //var shortvalues = _client.ReadShorts(new DeviceAddress(1, 30001), 10);

                //var shortvalue1 = _client.ReadUShort(new DeviceAddress(1, 40001));
                //var ushortvalue1s = _client.ReadUShorts(new DeviceAddress(1, 40001), 10);

                //var intvalue = _client.ReadInt(new DeviceAddress(1, 30001));
                //var intvalues = _client.ReadInts(new DeviceAddress(1, 30001), 10);

                var intvalue1  = _client.ReadInt(new DeviceAddress(1, 40001, byteOrder: ByteOrder.BigEndian));
                var intvalue1s = _client.ReadInts(new DeviceAddress(1, 40001, byteOrder: ByteOrder.BigEndian), 5);

                //var floatvalue = _client.Readfloat(new DeviceAddress(1, 30001));
                //var floatvalues = _client.Readfloats(new DeviceAddress(1, 30001),10);

                //var floatvalue1 = _client.Readfloat(new DeviceAddress(1, 40001));
                //var floatvalue1s = _client.Readfloats(new DeviceAddress(1, 40001), 10);
            }

            Console.ReadKey();
        }
Exemplo n.º 23
0
 /// <summary>
 ///     Write a message to the log.
 /// </summary>
 /// <param name="level">Importance of this logged message.</param>
 /// <param name="maskDebug">If true, debug output will not be written.</param>
 /// <param name="message">Message to write, which can include string formatting tokens.</param>
 /// <param name="substitutions">
 ///     When message includes string formatting tokens, these are the values to
 ///     inject into the formatted string.
 /// </param>
 public void Write(LogMessageLevel level, bool maskDebug, string message, params object[] substitutions)
 {
     DefaultLog.Write(level, maskDebug, message, substitutions);
 }
Exemplo n.º 24
0
 public UserActorController(ILogger <UserActorController> logger, UserDatabaseContext userDatabaseContext)
 {
     Log          = new DefaultLog(logger);
     UserDatabase = userDatabaseContext;
     UserDatabase.Database.EnsureCreated();
 }
Exemplo n.º 25
0
 internal ServiceTokenFactory(IServiceProvider container)
 {
     Container = container;
     Rand      = new Random();
     Log       = new DefaultLog(container.GetRequiredService <ILogger <ServiceTokenFactory> >());
 }
Exemplo n.º 26
0
 public SitecoreLogProvider(string logLevel) : base(logLevel)
 {
     this.logger = new DefaultLog();
 }
Exemplo n.º 27
0
        private bool setUp()
        {
            //bool flag;
            _configs = ReaderXMLUtil.ReadXMLConfig <TaskConfig>(_configFath, ConfigUtilly.ReadConfig, _nodeElement, _handler);
            if (_configs != null)
            {
                _log.NormalLog(string.Format("{0}:Down=>Creating", "SetUp()"));

                //创建外部task
                var taskFactory = new ts.TaskFactory(_configFath);
                //task类型配置
                foreach (var config in _configs)
                {
                    ILog log = new DefaultLog(config.TaskName)
                    {
                        Handle = LogHandle.debug, ByteSteamLogSwicth = true
                    };
                    //根据task类型配置创建具体的task列表
                    var tasks = taskFactory.CreateTasks(config, log);
                    foreach (var task in tasks)
                    {
                        if (task != null)
                        {
                            task.InitLevel = config.InitLevel;
                            _log.NormalLog(string.Format("{0}:Task<{1}>,Creating=>Created", "SetUp()", config.TaskName));
                            addTask(task);
                        }
                    }
                }

                //创建内部Task

                //自定义协议,用于信号监控及界面通讯
                string            freeTaskName   = "FreedomServerTaskHandler";
                ILog              freelog        = new DefaultLog(freeTaskName);
                TimeOut           freeTimeout    = new TimeOut(freeTaskName, 1000, freelog);
                EthernetSetUp     freeSetup      = new EthernetSetUp("127.0.0.1", 9527);
                FreedomServerTask freeServerTask = new FreedomServerTask(freeTaskName, freelog, freeTimeout, freeSetup);
                _log.NormalLog(string.Format("{0}:Task<{1}>,Creating=>Created", "SetUp()", freeServerTask.TaskName));
                addTask(freeServerTask);

                sortTasks();
                foreach (var t in _tasks)
                {
                    ChangInitLevel(t.InitLevel);
                    if (t.OnInit())
                    {
                        continue;
                    }
                    else
                    {
                        _log.ErrorLog(string.Format("Task<{0}> Inited failed!", t.TaskName));
                        return(false);
                    }
                }
            }
            else
            {
                _log.ErrorLog("Tasks config Error!");
                return(false);
            }
            return(true);
        }
Exemplo n.º 28
0
 public UserAsyncController(ILogger <UserAsyncController> logger, UserManager userManager)
 {
     Log            = new DefaultLog(logger);
     this.UserLines = userManager;
 }
Exemplo n.º 29
0
        /// <summary>
        /// This is the original "LoadDb" method. It downloads the id's for everything in the database, then uses the
        /// corresponding class' "DbSelect" method to download the rest of the data. With many (thousands) of records,
        /// this was very slow. My hypothesis is that since this process involves opening, closing and disposing of
        /// thousands of connections, this could be quite taxing. Therfore I have decided to redesign the method.
        /// Classes will now have a protected constructor method which takes all of it's properties. The method will
        /// get all of the properties for each object usint one Sql query for each and a single connection for all!
        /// I think this will be much more efficient and therfore significantly quicker. Let's see!
        /// </summary>
        /// <returns></returns>

        public static bool LoadDb()
        {
            DefaultLog.Info("Loading all data from database");
            //bool Success = true;

            string CurrentAction = "";

            try
            {
                using (SqlConnection conn = new SqlConnection(ConnectionString))
                {
                    CurrentAction = "opening connection";
                    conn.Open();
                    DefaultLog.Info("Connection opened");

                    SelectPeople();
                    SelectGovernments();
                    SelectBusinesses();
                    SelectBanks();
                    SelectPersonalAccounts();
                    SelectBusinessAccounts();



                    bool SelectPeople()
                    {
                        CurrentAction = "getting ALL People from database";
                        SqlCommand GetPeople = new SqlCommand("SELECT * FROM t_People;", conn);

                        using (SqlDataReader reader = GetPeople.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                Guid   TempId           = new Guid(reader[0].ToString());
                                Guid   TempGovernmentId = new Guid(reader[1].ToString());
                                string TempForename     = reader[2].ToString();
                                string TempSurname      = reader[3].ToString();

                                DataStore.People.Add(new Person(TempId, TempForename, TempSurname, TempGovernmentId));
                            }
                        }

                        DefaultLog.Info("ALL People downloaded from database");
                        return(true);
                    }

                    bool SelectGovernments()
                    {
                        CurrentAction = "getting ALL Governments from database";
                        SqlCommand GetGovernments = new SqlCommand("SELECT * FROM t_Governments;", conn);

                        using (SqlDataReader reader = GetGovernments.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                Guid TempId = new Guid(reader[0].ToString());

                                string TempName = reader[2].ToString();

                                Guid TempPresidentId = new Guid(reader[0].ToString());

                                Person TempPresident = null;


                                CurrentAction = "getting ALL Governments from database - Getting President from BankAPI.People";
                                int PresidentIndex = DataStore.People.FindIndex(f => f.Id.ToString() == TempPresidentId.ToString());

                                if (PresidentIndex >= 0)
                                {
                                    DefaultLog.Info("The Government's President has already been loaded from the database. " +
                                                    "Using this instance of President.");

                                    TempPresident = DataStore.People[PresidentIndex];
                                }
                                else
                                {
                                    /*throw new Exception("The Government's President has not already been loaded from the database. " +
                                     *  "All People *should* already have been loaded.");*/
                                    //Got rid of this because not all Governments have a
                                    //President
                                    DefaultLog.Info("The Government either has no President OR the Government's President has not " +
                                                    "already been loaded from the database. ");
                                }

                                Government TempGovernment;
                                if (TempPresident != null)
                                {
                                    TempGovernment = new Government(TempId, TempName, TempPresident);
                                }
                                else
                                {
                                    TempGovernment = new Government(TempId, TempName);
                                }

                                DataStore.Governments.Add(TempGovernment);
                            }
                        }
                        DefaultLog.Info("ALL Governments downloaded from database");
                        return(true);
                    }

                    bool SelectBusinesses()
                    {
                        CurrentAction = "getting businesses";
                        SqlCommand GetBusinesses = new SqlCommand("SELECT * FROM t_Businesses;", conn);

                        using (SqlDataReader reader = GetBusinesses.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                Guid TempId = new Guid(reader[0].ToString());

                                Guid       TempGovernmentId = new Guid(reader[3].ToString());
                                Government TempGovernment;

                                string TempOwnerId = reader[2].ToString();
                                Person TempOwner;



                                string TempName = reader[1].ToString();


                                CurrentAction = "getting ALL Businesses from database - Getting Business's Government from BankAPI.Governments";
                                int GovernmentIndex = DataStore.Governments.FindIndex(f => f.Id.ToString() == TempGovernmentId.ToString());

                                if (GovernmentIndex >= 0)
                                {
                                    DefaultLog.Info("The Business's Government has already been loaded from the database. " +
                                                    "Using this instance of Government.");

                                    TempGovernment = DataStore.Governments[GovernmentIndex];
                                }
                                else
                                {
                                    throw new Exception("The Business's Government has not already been loaded from the database. " +
                                                        "All Governments *should* already have been loaded.");
                                }

                                CurrentAction = "getting ALL Businesses from database - Getting Business's owner from BusinessAPI.People";
                                int BusinessOwnerIndex = DataStore.People.FindIndex(f => f.Id.ToString() == TempOwnerId.ToString());

                                if (BusinessOwnerIndex >= 0)
                                {
                                    DefaultLog.Info("The Business's owner has already been loaded from the database. " +
                                                    "Using this instance of owner.");

                                    TempOwner = DataStore.People[BusinessOwnerIndex];
                                }
                                else
                                {
                                    throw new Exception("The Business's owner has not already been loaded from the database. " +
                                                        "All People *should* already have been loaded.");
                                }
                                DataStore.Businesses.Add(new Business(TempId, TempGovernment, TempOwner, TempName));
                            }
                        }
                        DefaultLog.Info("Businesses downloaded (excluding banks which were already downloaded)");


                        DefaultLog.Debug("BUSINESS ID'S START");
                        foreach (Business MyBusiness in DataStore.Businesses)
                        {
                            DefaultLog.Debug("BusinessId  = " + MyBusiness.Id);
                        }
                        DefaultLog.Debug("BUSINESS ID'S END");
                        return(true);
                    }

                    bool SelectBanks()
                    {
                        CurrentAction = "getting banks";
                        SqlCommand GetBanks = new SqlCommand("SELECT * FROM t_Banks;", conn);

                        using (SqlDataReader reader = GetBanks.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                Guid     TempId = new Guid(reader[0].ToString());
                                Business TempMyBusiness;
                                decimal  TempSavingsInterestRate = Convert.ToDecimal(reader[1]);
                                decimal  TempLoanInterestRate    = Convert.ToDecimal(reader[2]);

                                DefaultLog.Debug("Searching for business with Id = " + TempId);

                                CurrentAction = "getting ALL Banks from database - Getting Bank's Business from BankAPI.Businesses";
                                int BusinessIndex = DataStore.Businesses.FindIndex(f => f.Id.ToString() == TempId.ToString());
                                //DefaultLog.Debug("TempId = " + TempId);
                                if (BusinessIndex >= 0)
                                {
                                    DefaultLog.Info("The Bank's Business has already been loaded from the database. " +
                                                    "Using this instance of Business.");

                                    TempMyBusiness = DataStore.Businesses[BusinessIndex];
                                }
                                else
                                {
                                    DefaultLog.Debug("BusinessIndex = " + BusinessIndex);
                                    throw new Exception("The Bank's Business has not already been loaded from the database. " +
                                                        "All Businesses *should* already have been loaded.");
                                }
                                DataStore.Banks.Add(new Bank(TempMyBusiness, TempSavingsInterestRate, TempLoanInterestRate));
                                DefaultLog.Info("Removing Bank's Business from _Businesses");
                                DataStore.Businesses.Remove(TempMyBusiness);
                            }
                        }
                        DefaultLog.Info("ALL Banks downloaded from database");
                        return(true);
                    }

                    bool SelectPersonalAccounts()
                    {
                        CurrentAction = "getting ALL PersonalAccounts from database";
                        SqlCommand GetPersonalAccounts = new SqlCommand("SELECT * FROM t_Accounts WHERE IsBusiness = 'false';",
                                                                        conn);

                        using (SqlDataReader reader = GetPersonalAccounts.ExecuteReader())
                        {
                            DefaultLog.Debug("ALL BANKS START");
                            foreach (Bank MyBank in DataStore.Banks)
                            {
                                DefaultLog.Debug("Id = " + MyBank.Id);
                            }
                            DefaultLog.Debug("ALL BANKS END");

                            while (reader.Read())
                            {
                                Guid TempPersonalAccountId;

                                Guid TempBankId;
                                Bank TempBank;

                                Guid   TempOwnerId;
                                Person TempOwner;

                                int  TempBal;
                                bool TempIsActive;
                                //bool TempIsBusiness = false; N/A, defined by datatype

                                TempPersonalAccountId = new Guid(reader[0].ToString());
                                TempBankId            = new Guid(reader[1].ToString());
                                TempOwnerId           = new Guid(reader[2].ToString());
                                TempBal      = Convert.ToInt32(reader[3]);
                                TempIsActive = Convert.ToBoolean(reader[4]);
                                //_IsBusiness = Convert.ToBoolean(reader[5]); N/A, defined by datatype

                                DefaultLog.Debug("TempBankId = " + TempBankId);

                                /////
                                CurrentAction = "getting ALL PersonalAccounts from database - Getting PersonalAccount's Bank from BankAPI.Banks";
                                int BankIndex = DataStore.Banks.FindIndex(f => f.Id.ToString() == TempBankId.ToString());

                                /*Console.WriteLine(BankIndex);
                                 * //Console.WriteLine(BankAPI.Banks[BankIndex].Name);
                                 * Console.ReadLine();*/

                                if (BankIndex >= 0)
                                {
                                    DefaultLog.Info("The PersonalAccount's Bank has already been loaded from the database. " +
                                                    "Using this instance of Bank.");

                                    TempBank = DataStore.Banks[BankIndex];
                                }
                                else
                                {
                                    throw new Exception("The PersonalAccount's Bank has not already been loaded from the database. " +
                                                        "All Banks *should* already have been loaded.");
                                }

                                CurrentAction = "getting ALL PersonalAccounts from database - Getting PersonalAccount's Owner from BankAPI.People";
                                int BusinessOwnerIndex = DataStore.People.FindIndex(f => f.Id.ToString() == TempOwnerId.ToString());

                                if (BusinessOwnerIndex >= 0)
                                {
                                    DefaultLog.Info("The PersonalAccount's owner has already been loaded from the database. " +
                                                    "Using this instance of owner.");

                                    TempOwner = DataStore.People[BusinessOwnerIndex];
                                }
                                else
                                {
                                    throw new Exception("The PersonalAccount's owner has not already been loaded from the database. " +
                                                        "All People *should* already have been loaded.");
                                }
                                //
                                DataStore.PersonalAccounts.Add(new PersonalAccount(TempPersonalAccountId, TempBank, TempOwner, TempBal,
                                                                                   TempIsActive));
                            }
                        }
                        DefaultLog.Info("ALL PersonalAccounts downloaded from database");
                        return(true);
                    }

                    bool SelectBusinessAccounts()
                    {
                        CurrentAction = "getting ALL BusinessAccounts from database";
                        SqlCommand GetBusinessAccounts = new SqlCommand("SELECT * FROM t_Accounts WHERE IsBusiness = 'true';",
                                                                        conn);

                        using (SqlDataReader reader = GetBusinessAccounts.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                Guid TempBusinessAccountId;

                                Guid TempBankId;
                                Bank TempBank;

                                Guid     TempBusinessId;
                                Business TempBusiness;

                                int  TempBal;
                                bool TempIsActive;
                                //bool TempIsBusiness = true; N/A, defined by datatype

                                TempBusinessAccountId = new Guid(reader[0].ToString());
                                TempBankId            = new Guid(reader[1].ToString());
                                TempBusinessId        = new Guid(reader[2].ToString());
                                TempBal      = Convert.ToInt32(reader[3]);
                                TempIsActive = Convert.ToBoolean(reader[4]);
                                //_IsBusiness = Convert.ToBoolean(reader[5]); N/A, defined by datatype

                                /////
                                CurrentAction = "getting ALL BusinessAccounts from database - Getting BusinessAccount's Bank from BankAPI.Banks";
                                int BankIndex = DataStore.Banks.FindIndex(f => f.Id.ToString() == TempBankId.ToString());

                                if (BankIndex >= 0)
                                {
                                    DefaultLog.Info("The BusinessAccount's Bank has already been loaded from the database. " +
                                                    "Using this instance of Bank.");

                                    TempBank = DataStore.Banks[BankIndex];
                                }
                                else
                                {
                                    throw new Exception("The BusinessAccount's Bank has not already been loaded from the database. " +
                                                        "All Banks *should* already have been loaded.");
                                }

                                CurrentAction = "getting ALL BusinessAccounts from database - Getting BusinessAccount's Business from BankAPI.Businesses";
                                int BusinessOwnerIndex = DataStore.Businesses.FindIndex(f => f.Id.ToString() == TempBusinessId.ToString());

                                if (BusinessOwnerIndex >= 0)
                                {
                                    DefaultLog.Info("The BusinessAccount's Business has already been loaded from the database. " +
                                                    "Using this instance of Business.");

                                    TempBusiness = DataStore.Businesses[BusinessOwnerIndex];
                                }
                                else
                                {
                                    throw new Exception("The BusinessAccount's Business has not already been loaded from the database. " +
                                                        "All Businesses *should* already have been loaded.");
                                }
                                //
                                DataStore.BusinessAccounts.Add(new BusinessAccount(TempBusinessAccountId, TempBank, TempBusiness, TempBal,
                                                                                   TempIsActive));
                            }
                        }
                        DefaultLog.Info("All BusinessAccounts downloaded from database");
                        return(true);
                    }
                }
            }
            catch (Exception e)
            {
                DefaultLog.Error("There was an exception while " + CurrentAction);
                DefaultLog.Error("Exception = " + e);
                return(false);
            }
            DefaultLog.Info("All data loaded from database successfully!");
            DefaultLog.Info(String.Format("{0} personal accounts, {1} business accounts, " +
                                          "{3} businesses of which {2} are banks, " +
                                          "{4} people & {5} governments", DataStore.PersonalAccounts.Count(), DataStore.BusinessAccounts.Count(), DataStore.Banks.Count(),
                                          DataStore.Businesses.Count(), DataStore.People.Count(), DataStore.Governments.Count()));
            return(true);
        }
Exemplo n.º 30
0
 //注册日志回调
 public static void RegisterLogCallback(DefaultLog dLog, WarnLog wLog, ErrorLog eLog)
 {
     _defaultLogFunc = dLog;
     _warnLogFunc    = wLog;
     _errorLogFunc   = eLog;
 }
Exemplo n.º 31
0
 /// 日志回调注册
 /// </summary>
 /// <param name="log1"></param>
 /// <param name="log2"></param>
 /// <param name="log3"></param>
 public void RegisterLog(DefaultLog log1, WarnLog log2, ErrorLog log3)
 {
     UpdateLog.RegisterLogCallback(log1, log2, log3);
 }