public static AbstractLogger CreateChain()
        {
            ErrorLogger errorLogger = new ErrorLogger(AbstractLogger.LogLevel.Error);
            DebugLogger debugLogger = new DebugLogger(AbstractLogger.LogLevel.Debug, errorLogger);
            InfoLogger  infoLogger  = new InfoLogger(AbstractLogger.LogLevel.Info, debugLogger);

            return(infoLogger);
        }
Ejemplo n.º 2
0
        public static BaseLogger Build()
        {
            BaseLogger errorLogger = new ErrorLogger(LogLevel.Error);
            BaseLogger infoLogger  = new InfoLogger(LogLevel.Info);

            errorLogger.SetNext(infoLogger).SetNext(errorLogger);

            return(errorLogger);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Cluster"/> class.
        /// </summary>
        /// <param name="system">The actor system that hosts the cluster.</param>
        /// <exception cref="ConfigurationException">
        /// This exception is thrown if the <paramref name="system"/> does not have a <see cref="ClusterActorRefProvider"/> enabled in the configuration.
        /// </exception>
        public Cluster(ActorSystemImpl system)
        {
            System   = system;
            Settings = new ClusterSettings(system.Settings.Config, system.Name);

            if (!(system.Provider is IClusterActorRefProvider provider))
            {
                throw new ConfigurationException(
                          $"ActorSystem {system} needs to have a 'IClusterActorRefProvider' enabled in the configuration, currently uses {system.Provider.GetType().FullName}");
            }
            SelfUniqueAddress = new UniqueAddress(provider.Transport.DefaultAddress, AddressUidExtension.Uid(system));

            _log = Logging.GetLogger(system, "Cluster");

            CurrentInfoLogger = new InfoLogger(_log, Settings, SelfAddress);

            LogInfo("Starting up...");

            var clusterCoreTaskSource = new TaskCompletionSource <IActorRef>();

            _clusterCoreTask = clusterCoreTaskSource.Task;

            FailureDetector = new DefaultFailureDetectorRegistry <Address>(() => FailureDetectorLoader.Load(Settings.FailureDetectorImplementationClass, Settings.FailureDetectorConfig,
                                                                                                            system));

            Scheduler = CreateScheduler(system);

            // it has to be lazy - otherwise if downing provider will init a cluster itself, it will deadlock
            _downingProvider = new Lazy <IDowningProvider>(() => Akka.Cluster.DowningProvider.Load(Settings.DowningProviderType, system), LazyThreadSafetyMode.ExecutionAndPublication);

            //create supervisor for daemons under path "/system/cluster"
            _clusterDaemons = system.SystemActorOf(Props.Create(() => new ClusterDaemon(Settings)).WithDeploy(Deploy.Local), "cluster");

            _readView = new ClusterReadView(this);

            // force the underlying system to start
            _ = Task.Run(async() =>
            {
                try
                {
                    _clusterCore = await _clusterDaemons.Ask <IActorRef>(new InternalClusterAction.GetClusterCoreRef(this), System.Settings.CreationTimeout).ConfigureAwait(false);
                    clusterCoreTaskSource.SetResult(_clusterCore);

                    system.RegisterOnTermination(Shutdown);
                    LogInfo("Started up successfully");
                }
                catch (Exception ex)
                {
                    _log.Error(ex, "Failed to startup Cluster. You can try to increase 'akka.actor.creation-timeout'.");
                    Shutdown();
                    System.DeadLetters.Tell(ex); //don't re-throw the error. Just log it.

                    _clusterCore = System.DeadLetters;
                    clusterCoreTaskSource.SetResult(_clusterCore);
                }
            });
        }
        /// <summary>
        /// Methode pour lire l object dans le répertoire XML
        /// Impossible d utilisr WindowsBase System.IO.Packaging car ZIP n'est pas implémenté dans toutes ses versions
        /// </summary>
        private Object[] GetAllPackageClassesInZIPFile(string rootPath, XSDSpec[] xsdSpec, string zipFile)
        {
            InfoLogger.Info("StreamOpen '" + zipFile + "', search all files nb='" + xsdSpec.Length);

            Object[] output = new Object[xsdSpec.Length];
            int      i      = 0;
            Dictionary <string, XmlSerializer> xsd = new Dictionary <string, XmlSerializer>(xsdSpec.Length);

            foreach (XSDSpec xsdS in xsdSpec)
            {
                xsd.Add(xsdS.xsdFile, new XmlSerializer(xsdS.xsdClass));
            }
            ZipArchive package = new ZipArchive(rootPath + @"\" + zipFile, FileAccess.Read);

            foreach (ZipArchiveFile part in package.Files)
            {
                StreamReader sr = part.OpenText();

                using (XmlTextReader xmlReader = new XmlTextReader(sr))
                {
                    while (xmlReader.Read())
                    {
                        //looking for a XML element like this
                        //xsi:schemaLocation="http://sample.com/sample/contentExchange sample.0.6.2.xsd "

                        string schemaLocation;
                        if (xmlReader.NodeType.Equals(XmlNodeType.Element) &&
                            (schemaLocation = xmlReader.GetAttribute("xsi:schemaLocation")) != null)
                        {
                            InfoLogger.Info(schemaLocation);

                            // make a search for the corresponding XSD Class
                            foreach (XSDSpec xsdS in xsdSpec)
                            {
                                if (schemaLocation.EndsWith(xsdS.xsdFile))
                                {
                                    XmlSerializer x = xsd[xsdS.xsdFile];
                                    // the class object has only one field : a List object
                                    Object datas = x.Deserialize(xmlReader);
                                    output[i++] = datas;
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
                InfoLogger.Info("Extracted " + part.Name);
            }
            return(output);
        }
Ejemplo n.º 5
0
 private void _disconnect(Exception e)
 {
     if (!_connected)
     {
         return;
     }
     InfoLogger.SendInfo(_roomid, "INFO", "连接断开");
     _connected = false;
     _client.Close();
     _netStream = null;
     OnDisconnected?.Invoke(this, new DisconnectEvtArgs {
         Error = e
     });
 }
Ejemplo n.º 6
0
        static public Task <string> GetTrueUrl(string roomid)
        {
            return(Task.Run(() => {
                if (roomid == null)
                {
                    InfoLogger.SendInfo(roomid, "ERROR", "房间号获取错误。");
                    throw new Exception("No roomid");
                }
                var apiUrl = "https://api.live.bilibili.com/room/v1/Room/playUrl?cid=" + roomid + "&otype=json&qn=10000&platform=web";
                SendStat(roomid);

                //访问API获取结果
                var wc = new WebClient();
                wc.Headers.Add("Accept: */*");
                wc.Headers.Add("User-Agent: " + Ver.UA);
                wc.Headers.Add("Accept-Language: zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4");

                string resultString;

                try
                {
                    resultString = wc.DownloadString(apiUrl);
                }
                catch (WebException e0)
                {
                    InfoLogger.SendInfo(roomid, "ERROR", "发送解析请求失败<net>:" + e0.Message);
                    throw;
                }
                catch (Exception e)
                {
                    InfoLogger.SendInfo(roomid, "ERROR", "发送解析请求失败:" + e.Message);
                    throw;
                }

                //解析结果
                try
                {
                    var jsonResult = JObject.Parse(resultString);
                    var trueUrl = jsonResult["data"]["durl"][0]["url"].ToString();
                    InfoLogger.SendInfo(roomid, "INFO", "地址解析成功:" + trueUrl);
                    return trueUrl;
                }
                catch (Exception e)
                {
                    InfoLogger.SendInfo(roomid, "ERROR", "视频流地址解析失败:" + e.Message);
                    throw;
                }
            }));
        }
Ejemplo n.º 7
0
        /// <summary>
        ///Remplit la table destination en mergeant avec le contenu du fichier csv fournie
        ///
        /// Voir en MS SQL 2012 , pour utiliser la nouvelle instruction MERGE
        ///
        /// </summary>
        /// <returns></returns>
        public void BulkUpsertCsv(string CsvFileName, DatabaseTable targetTableName, string csvFileEncoding = "UTF8", string dateFormat = "DMY", int connectionTimeout = -1)
        {
            Encoding enc = null;

            switch (csvFileEncoding)
            {
            case "UTF8": enc = Encoding.UTF8; break;

            case "ASCII": enc = Encoding.ASCII; break;

            case "BigEndianUnicode": enc = Encoding.BigEndianUnicode; break;

            case "Unicode": enc = Encoding.Unicode; break;

            case "UTF32": enc = Encoding.UTF32; break;

            case "UTF7": enc = Encoding.UTF7; break;

            default: enc = Encoding.Default; break;
            }
            ;

            DatabaseTable usingTableName = new DatabaseTable(targetTableName.schema, "#" + targetTableName.table);

            List <string> columns = new List <string>();

            using (var reader = new CsvReader(new StreamReader(CsvFileName, enc), true, ';'))
            {
                try
                {
                    DestinationConnection.Open();

                    CsvDataAdapter adapter          = new CsvDataAdapter(reader);
                    int            nbTobeMergedRows = adapter.Fill(DestinationConnection, usingTableName);

                    InfoLogger.Info(String.Format("MERGE Table: {0}, using File {1} : nb rows: {2}", targetTableName, CsvFileName, nbTobeMergedRows));

                    this.BulkUpsert(targetTableName, usingTableName, dateFormat, connectionTimeout);
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    DestinationConnection.Close();
                }
            }
        }
Ejemplo n.º 8
0
        public async void Start(string savepath)
        {
            try
            {
                if (IsRunning)
                {
                    InfoLogger.SendInfo(_roomid, "ERROR", "已经是运行状态了。");
                    return;
                }
                //设置运行状态。
                IsRunning = true;

                //读取设置
                var config = Config.Instance;
                _downloadCommentOption = config.IsDownloadComment;
                _autoRetry             = config.IsAutoRetry;

                int.TryParse(config.Timeout ?? "2000", out _streamTimeout);

                //获取真实下载地址
                try
                {
                    _flvUrl = await PathFinder.GetTrueUrl(_roomid);
                }
                catch
                {
                    InfoLogger.SendInfo(_roomid, "ERROR", "未取得下载地址");
                    Stop();
                    return; //停止并退出
                }

                flvDownloader       = new FlvDownloader(_roomid, savepath, _downloadCommentOption, _commentProvider);
                flvDownloader.Info += _flvDownloader_Info;
                CheckStreaming();
                try
                {
                    flvDownloader.Start(_flvUrl);
                }
                catch (Exception e)
                {
                    InfoLogger.SendInfo(_roomid, "ERROR", "下载视频流时出错:" + e.Message);
                    Stop();
                }
            }catch (Exception e)
            {
                InfoLogger.SendInfo(_roomid, "ERROR", "未知错误:" + e.Message);
                Stop();
            }
        }
Ejemplo n.º 9
0
 private async void HeartbeatLoop()
 {
     try
     {
         while (_connected)
         {
             SendHeartbeatAsync();
             await Task.Delay(30000);
         }
     }
     catch (Exception e)
     {
         InfoLogger.SendInfo(_roomid, "ERROR", e.Message);
         _disconnect(e);
     }
 }
Ejemplo n.º 10
0
        public async Task Start(string readNodesPath, string readLinksPath, int numberOfLinkChannels)
        {
            await InfoLogger.LogInformation($"Starting RoutingAndSpectrumAllocation\n");

            await InfoLogger.LogInformation($"Nodes Path: \"{readNodesPath}\"\n");

            await InfoLogger.LogInformation($"Links Path: \"{readLinksPath}\"\n");

            Graph graph = ReadGraph(readNodesPath, readLinksPath);

            await StorageLogger.WriteLog("graph", graph);

            List <Demand> demands = GetDemands(graph);

            await StorageLogger.WriteLog("demands", demands);

            await ApplyRSA(graph, demands, numberOfLinkChannels);
        }
Ejemplo n.º 11
0
        private Task <string> GetCmtServer()
        {
            return(Task.Run(() => {
                //获取真实弹幕服务器地址。
                InfoLogger.SendInfo(_roomid, "INFO", "开始解析弹幕服务器");

                var chatWc = new WebClient();
                chatWc.Headers.Add("Accept: */*");
                chatWc.Headers.Add("User-Agent: " + Ver.UA);
                chatWc.Headers.Add("Accept-Language: zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4");

                var chatApi = "http://live.bilibili.com/api/player?id=cid:" + _roomid;
                string chatXmlString;
                try
                {
                    chatXmlString = chatWc.DownloadString(chatApi);
                }
                catch (Exception e)
                {
                    InfoLogger.SendInfo(_roomid, "ERROR", "无法解析弹幕服务器:" + e.Message);
                    throw;
                }

                //解析弹幕信息Xml
                chatXmlString = "<root>" + chatXmlString + "</root>";
                var chatXml = new XmlDocument();
                try
                {
                    chatXml.LoadXml(chatXmlString);
                }
                catch (Exception e)
                {
                    InfoLogger.SendInfo(_roomid, "ERROR", "解析XML失败:" + e.Message);
                    throw;
                }

                //取得弹幕服务器Url
                var serverNode = chatXml.DocumentElement?.SelectSingleNode("/root/dm_server");
                var cmtServerUrl = serverNode?.InnerText;

                InfoLogger.SendInfo(_roomid, "INFO", "解析弹幕服务器地址成功:" + cmtServerUrl);
                return cmtServerUrl;
            }));
        }
Ejemplo n.º 12
0
 public void Stop()
 {
     if (IsRunning)
     {
         IsRunning     = false;
         _recordedSize = 0;
         if (flvDownloader != null)
         {
             flvDownloader.Stop();
             flvDownloader = null;
         }
         InfoLogger.SendInfo(_roomid, "INFO", "停止");
         OnStop?.Invoke(this);
     }
     else
     {
         InfoLogger.SendInfo(_roomid, "ERROR", "已经是停止状态了");
     }
 }
Ejemplo n.º 13
0
        public async void Connect()
        {
            try
            {
                var cmtServer = await GetCmtServer();

                var cmtHost = cmtServer.Item1;
                var cmtPort = cmtServer.Item2;

                if (cmtHost == null)
                {
                    throw new Exception("无法获得弹幕服务器地址");
                }

                //连接弹幕服务器
                _client = new TcpClient();
                await _client.ConnectAsync(cmtHost, cmtPort);

                _netStream = _client.GetStream();

                int.TryParse(_roomid, out int roomIdNumber);
                if (SendJoinChannel(roomIdNumber))
                {
                    _connected = true;
                    HeartbeatLoop();
                    var thread = new Thread(ReceiveMessageLoop)
                    {
                        IsBackground = true
                    };
                    thread.Start();
                }
                else
                {
                    InfoLogger.SendInfo(_roomid, "ERROR", "加入频道失败");
                    throw new Exception("Could't add the channel");
                }
            }catch (Exception e)
            {
                InfoLogger.SendInfo(_roomid, "ERROR", e.Message);
                _disconnect(e);
            }
        }
Ejemplo n.º 14
0
 public void Stop(bool isNetError = false)
 {
     if (IsRunning)
     {
         IsRunning     = false;
         _recordedSize = 0;
         if (flvDownloader != null)
         {
             flvDownloader.Stop();
             flvDownloader = null;
         }
         InfoLogger.SendInfo(_roomid, "INFO", "停止");
         OnStop?.Invoke(this, isNetError);
         _timer?.Dispose();
     }
     else
     {
         InfoLogger.SendInfo(_roomid, "ERROR", "已经是停止状态了");
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        /// 职责链模式
        /// </summary>
        static void ChainOfResponsibility()
        {
            Console.WriteLine($"职责链模式{Environment.NewLine}-------------------------------------------");

            ILoggerHandler infoLogger  = new InfoLogger();
            ILoggerHandler debugLogger = new DebugLogger();
            ILoggerHandler warnLogger  = new WarnLogger();
            ILoggerHandler errorLogger = new ErrorLogger();

            infoLogger.Successor  = debugLogger;
            debugLogger.Successor = errorLogger;
            //errorLogger.Successor = warnLogger;

            infoLogger.Record("AAAAAAAAAAAA", LogLevelEmun.INFO);
            infoLogger.Record("BBBBBBBBBBBB", LogLevelEmun.DEBUG);
            infoLogger.Record("CCCCCCCCCCCC", LogLevelEmun.WARN);
            infoLogger.Record("DDDDDDDDDDDD", LogLevelEmun.ERROR);

            Console.ReadKey();
        }
Ejemplo n.º 16
0
        private async void CheckStreaming()
        {
            await Task.Delay(_streamTimeout);

            try
            {
                if (flvDownloader == null)
                {
                    return;
                }
                if (_recordedSize <= 1)
                {
                    InfoLogger.SendInfo(_roomid, "INFO", "接收流超时。");
                    Stop();
                }
            }catch (Exception ex)
            {
                InfoLogger.SendInfo(_roomid, "ERROR", "在检查直播状态时发生未知错误:" + ex.Message);
                Stop();
            }
        }
        private async Task <RSATable> FillTable(RSATable table, Graph graph, Demand demand, List <Tuple <GraphPath, GraphPath> > paths)
        {
            bool filled = false;

            foreach (var path in paths)
            {
                var tableMemory = table.CopyObject <RSATable>();

                await InfoLogger.LogInformation($"trying main path: {string.Join("->", path.Item1.Path)} distance: {path.Item1.ToLinks(graph.Links).Sum(r=>r.Length)}");

                List <AvailableSlot> availableTableSlots = base.GetAvailableTableSlots(graph, path.Item1, tableMemory);

                if (RSATableFill.FillDemandOnTable(ref tableMemory, graph, demand, path.Item1, availableTableSlots))
                {
                    availableTableSlots = GetAdditionalAvailableTableSlots(graph, path, tableMemory);

                    await InfoLogger.LogInformation($"trying secundary path: {string.Join("->", path.Item2.Path)} distance: {path.Item2.ToLinks(graph.Links).Sum(r => r.Length)}");

                    if (RSATableFill.FillDemandOnTable(ref tableMemory, graph, demand, path.Item2, availableTableSlots, true))
                    {
                        DemandSupplyMemory.Add(new DemandLinkPair(demand, path));
                        filled = true;
                        await InfoLogger.LogInformation($"demand supplied\n");

                        table = tableMemory;
                        await InfoLogger.LogInformation(table.ToStringTable());

                        supplied++;
                        break;
                    }
                }
            }

            if (filled == false)
            {
                await InfoLogger.LogInformation($"It's not possible to supply demand of {demand.Slots}  from {demand.NodeIdFrom} to {demand.NodeIdTo}\n");
            }
            return(table);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// BulkUpsert (update and insert) ou BulkMerge
        ///Remplit la table destination en mergeant avec le contenu du fichier csv fournie
        ///
        /// Execute un UPDATE et ensuite un INSERT sur la connection Target
        ///
        /// Voir en MS SQL 2012 , pour utiliser la nouvelle instruction MERGE
        ///
        /// </summary>
        /// <returns></returns>
        public void BulkUpsert(DatabaseTable targetTableName, DatabaseTable usingTableName, string dateFormat = "DMY", int connection_timeout = -1)
        {
            try
            {
                DestinationConnection.Open();

                string tmpUpdatedPKs = "#updatedPK";

                int nbUpdatedRows    = DestinationConnection.Update(targetTableName, usingTableName, updated_PKs_Table: tmpUpdatedPKs, date_format: dateFormat);
                int nbInsertedNewRow = DestinationConnection.Insert(targetTableName, usingTableName, excluded_PKs_Table: tmpUpdatedPKs);

                InfoLogger.Info(String.Format("MERGE Table: {0}, using {1} : updatedRows: {2}, new Rows:{3} ", targetTableName, usingTableName, nbUpdatedRows, nbInsertedNewRow));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DestinationConnection.Close();
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 获取弹幕服务器地址和端口。
        /// </summary>
        /// <returns>Tuple&lt;string, int>(弹幕服务器地址, 端口)</returns>
        private Task <Tuple <string, int> > GetCmtServer()
        {
            return(Task.Run(() => {
                //获取真实弹幕服务器地址。
                InfoLogger.SendInfo(_roomid, "INFO", "开始解析弹幕服务器");

                var chatWc = new WebClient();
                chatWc.Headers.Add("Accept: */*");
                chatWc.Headers.Add("User-Agent: " + Ver.UA);
                chatWc.Headers.Add("Accept-Language: zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4");

                var chatApi = "https://api.live.bilibili.com/room/v1/Danmu/getConf?room_id=" + _roomid;
                string chatConfString;
                try
                {
                    chatConfString = chatWc.DownloadString(chatApi);
                }
                catch (Exception e)
                {
                    InfoLogger.SendInfo(_roomid, "ERROR", "无法解析弹幕服务器:" + e.Message);
                    throw;
                }

                //解析弹幕信息
                try
                {
                    var chatConf = JObject.Parse(chatConfString);
                    var cmtServerHost = chatConf["data"]["host"].ToString();
                    int.TryParse(chatConf["data"]["port"].ToString(), out int cmtServerPort);
                    InfoLogger.SendInfo(_roomid, "INFO", $"解析弹幕服务器地址成功:{cmtServerHost}:{cmtServerPort}");
                    return new Tuple <string, int>(cmtServerHost, cmtServerPort);
                }
                catch (Exception e)
                {
                    InfoLogger.SendInfo(_roomid, "ERROR", "解析弹幕服务器失败:" + e.Message);
                    throw;
                }
            }));
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Cluster"/> class.
        /// </summary>
        /// <param name="system">The actor system that hosts the cluster.</param>
        /// <exception cref="ConfigurationException">
        /// This exception is thrown if the <paramref name="system"/> does not have a <see cref="ClusterActorRefProvider"/> enabled in the configuration.
        /// </exception>
        public Cluster(ActorSystemImpl system)
        {
            System   = system;
            Settings = new ClusterSettings(system.Settings.Config, system.Name);

            if (!(system.Provider is IClusterActorRefProvider provider))
            {
                throw new ConfigurationException(
                          $"ActorSystem {system} needs to have a 'IClusterActorRefProvider' enabled in the configuration, currently uses {system.Provider.GetType().FullName}");
            }
            SelfUniqueAddress = new UniqueAddress(provider.Transport.DefaultAddress, AddressUidExtension.Uid(system));

            _log = Logging.GetLogger(system, "Cluster");

            CurrentInfoLogger = new InfoLogger(_log, Settings, SelfAddress);

            LogInfo("Starting up...");

            FailureDetector = new DefaultFailureDetectorRegistry <Address>(() => FailureDetectorLoader.Load(Settings.FailureDetectorImplementationClass, Settings.FailureDetectorConfig,
                                                                                                            system));

            Scheduler = CreateScheduler(system);

            // it has to be lazy - otherwise if downing provider will init a cluster itself, it will deadlock
            _downingProvider = new Lazy <IDowningProvider>(() => Akka.Cluster.DowningProvider.Load(Settings.DowningProviderType, system), LazyThreadSafetyMode.ExecutionAndPublication);

            //create supervisor for daemons under path "/system/cluster"
            _clusterDaemons = system.SystemActorOf(Props.Create(() => new ClusterDaemon(Settings)).WithDeploy(Deploy.Local), "cluster");

            _readView = new ClusterReadView(this);

            // force the underlying system to start
            _clusterCore = GetClusterCoreRef().Result;

            system.RegisterOnTermination(Shutdown);

            LogInfo("Started up successfully");
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Execute a prepare statement for performance reason, keep and reuse the SqlCommand object
        /// </summary>
        /// <param name="command">by reference , an objet SqlCommand</param>
        /// <param name="parameters">Request parameters</param>
        /// <param name="connection_timeout"></param>
        public override void Execute(ref IDbCommand command, IDataParameter[] parameters = null, int connection_timeout = -1)
        {
            InfoLogger.Debug("La requete utilisée est \n" + command.CommandText);
            try
            {
                if (Connection != null)
                {
                    if (command.Connection == null)
                    {
                        command.Connection = (SqlConnection)Connection;
                    }
                    else
                    {
                        command.Parameters.Clear();
                    }

                    if (connection_timeout > 0)
                    {
                        command.CommandTimeout = connection_timeout;
                    }
                    if (parameters != null)
                    {
                        foreach (IDataParameter param in parameters)
                        {
                            command.Parameters.Add(param);
                        }
                    }
                    int nbLignes = command.ExecuteNonQuery();
                    InfoLogger.Debug("La requete affecte :" + nbLignes + " Lignes");
                }
            }
            catch (Exception e)
            {
                ExceptionLogger.Fatal("Impossible d executer la requete: " + command, e);
                throw e;
            }
        }
        public static void ACTION_PROCESS(DateTime d, Arguments CommandLine)
        {
            string date = d.ToString("dd/MM/yyyy");

            InfoLogger.Error("PROCESSING DATE" + date);
            //------------------------------------------------------------------------------------------
            if (CommandLine["histo"] != null)
            {
                string root     = CommandLine["factsetPath"] ?? @"\\vill1\Partage\TQA\Datas Factset pour Guillaume";
                string filepath = root + @"\" + CommandLine["histo"];
                ACTION_PROCESS_BulkCopy_DATA_FACTSET_DATA_1(filepath);
            }

            //------------------------------------------------------------------------------------------
            if (CommandLine["step1"] != null)
            {
                string root     = CommandLine["factsetPath"] ?? @"\\vill1\Partage\,FGA MarketData\FACTSET";
                string filepath = root + @"\" + d.ToString("yyyyMM") + @"\base_" + d.ToString("yyyyMMdd") + @".csv";
                ACTION_PROCESS_BulkCopy_DATA_FACTSET_DATA_1(filepath);
            }
            //------------------------------------------------------------------------------------------
            if (CommandLine["step2"] != null)
            {
                string filepath = CommandLine["modelClassificationPath"] ?? @"\\vill1\Partage\,FGA Front Office\02_Gestion_Actions\00_BASE\Base 2.0\Modele_Classification.xlsx";

                ACTION_PROCESS_BulkCopy_FACTSET_MODELE_CLASSIFICATION_2(date, filepath);
            }


            //------------------------------------------------------------------------------------------
            if (CommandLine["step3"] != null)
            {
                string filepath = CommandLine["notationISR"] ?? @"\\vill1\Partage\,FGA ISR\Notation Fédéris\NotationISRbase.xlsx";
                try
                {
                    ACTION_PROCESS_BulkCopy_IMPORT_ISR_3(filepath);
                }
                catch (System.Data.SqlClient.SqlException sqle)
                {
                    if (sqle.ErrorCode == 2627) // violation Primary Key
                    {
                        InfoLogger.Info("Data already inserted");
                    }
                    InfoLogger.Error("Problem on " + filepath, sqle);
                }
                catch (Exception e)
                {
                    InfoLogger.Error("Problem on " + filepath, e);
                }
            }
            //------------------------------------------------------------------------------------------
            if (CommandLine["step4"] != null)
            {
                string filePath = CommandLine["actPtfAlimSQSLrequest"] ?? @"\\vill1\Partage\,FGA Soft\SQL_SCRIPTS\AUTOMATE\GESTION_ACTION\FCP_Action_BaseTitresDirects.sql";
                ACTION_PROCESS_BulkCopy_Import_ACT_PTF_BaseTitreDirects_4(filePath, date);
            }

            if (CommandLine["step5"] != null)
            {
                ACTION_PROCESS_BulkCopy_Enrich_5(date);
            }
            if (CommandLine["calculate"] != null)
            {
                int to;
                if (!Int32.TryParse(CommandLine["timeout"], out to))
                {
                    to = 60 * 60 * 3; // 3 heures par defaut
                }
                ACTION_PROCESS_BulkCopy_Calculate_6(date, to);
            }
        }
Ejemplo n.º 23
0
 public void InfoMessage(InfoLogger log) {
     this.Invoke("InfoMessage", new object[] {
                 log});
 }
Ejemplo n.º 24
0
        /// <summary>
        ///Copie les données de la bdd Source vers la Destination
        ///note1: Identity column: copy as it from source to destination, using KeepIdentity option
        ///note2: Null values: copy as it even if column has default value, using KeepNulls option
        /// </summary>
        /// <param name="mode">Aucune pour ne pas prendre en compte la liste. Include si la liste est une liste de table à inclure et exclude  si la copie est sur toute la base sauf les tables de la liste</param>
        /// <param name="ListTableName">La liste des noms de tables</param>
        /// <param name="requestSelect">la requete utilisée pour recupérer les données sur chaque table, paramètres {0} pour le schema et {1} pour le nom de table</param>
        public void bulkcopyData(ListeMode mode, List <DatabaseTable> ListTableName, string RequestSelect)
        {
            // Open a sourceConnection to the first database
            SourceConnection.Open();

            //SMO Server object setup with SQLConnection.

            Server server = new Server(new ServerConnection((SqlConnection)SourceConnection.Connection));
            string dbName = SourceConnection.Connection.Database.ToString();

            //Set Database to the database
            Database db = server.Databases[dbName];

            //connection en destination
            DestinationConnection.Open();
            SqlBulkCopyOptions Options     = SqlBulkCopyOptions.KeepNulls | SqlBulkCopyOptions.KeepIdentity;
            SqlTransaction     Transaction = ((SqlConnection)DestinationConnection.Connection).BeginTransaction();

            SqlBulkCopy bulkCopy = new SqlBulkCopy((SqlConnection)DestinationConnection.Connection, Options, Transaction);

            bulkCopy.BulkCopyTimeout = 120;
            bulkCopy.BatchSize       = 1500;

            string        requestSelectToExecute = null;
            Table         table  = null;
            SqlDataReader reader = null;

            try
            {
                foreach (Table myTable in db.Tables)
                {
                    // si il y a une liste
                    if (mode.Equals(ListeMode.Include))// if this table t is in our parameter list => include it
                    {
                        if (!ListTableName.Contains(myTable.Name, myTable.Schema))
                        {
                            continue;
                        }
                    }
                    else if (mode.Equals(ListeMode.Exclude)) // if this table t is in our parameter list => do not include it
                    {
                        if (ListTableName.Contains(myTable.Name, myTable.Schema))
                        {
                            continue;
                        }
                    }
                    table = myTable;

                    //InfoLogger.Debug("Desactivation des cles identity sur la table : " + table.Name);
                    string     requestSet        = String.Format(SET_IDENTITY_ONOFF, table.Schema, table.Name, "ON");
                    SqlCommand SqlCmdSetIdentity = new SqlCommand(requestSet, (SqlConnection)DestinationConnection.Connection, Transaction);
                    int        nb = SqlCmdSetIdentity.ExecuteNonQuery();
                    InfoLogger.Debug("Desactivation des cles identity sur la table : OK " + nb);

                    InfoLogger.Debug("Obtention des données table : " + table.Name);
                    // Get data from the source table as a SqlDataReader.
                    requestSelectToExecute = String.Format(RequestSelect, table.Schema, table.Name);
                    SqlCommand commandSourceData = new SqlCommand(
                        requestSelectToExecute, (SqlConnection)
                        SourceConnection.Connection);
                    reader = commandSourceData.ExecuteReader();
                    InfoLogger.Debug(" -- OK");

                    InfoLogger.Debug("Ecriture des données nouvelle BDD");

                    // Write from the source to the destination.
                    bulkCopy.DestinationTableName = table.Schema + "." + table.Name;
                    bulkCopy.WriteToServer(reader);

                    InfoLogger.Debug(" -- OK");
                    reader.Close();

                    InfoLogger.Debug("reactivation des cles identity sur la table : " + table.Name);
                    requestSet        = String.Format(SET_IDENTITY_ONOFF, table.Schema, table.Name, "OFF");
                    SqlCmdSetIdentity = new SqlCommand(requestSet, (SqlConnection)DestinationConnection.Connection, Transaction);
                    nb = SqlCmdSetIdentity.ExecuteNonQuery();
                    InfoLogger.Debug("reactivation des cles identity sur la table : OK " + nb);
                }//Fin foreach

                // Transaction OK : commit all stuff: for all tables
                Transaction.Commit();
            }
            catch (Exception ex)
            {
                if (table != null)
                {
                    ExceptionLogger.Error("BULK IMPOSSIBLE " + requestSelectToExecute + " DANS " + table.Schema + "." + table.Name);
                }
                ExceptionLogger.Error(ex);

                // cancel all modif
                Transaction.Rollback();
                throw ex;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                Transaction.Dispose();
            }

            DestinationConnection.Close();
            SourceConnection.Close();
        }
Ejemplo n.º 25
0
 /// <remarks/>
 public void InfoMessageAsync(InfoLogger log) {
     this.InfoMessageAsync(log, null);
 }
Ejemplo n.º 26
0
        static public Task <RoomInfo> GetRoomInfo(string originalRoomId)
        {
            return(Task.Run(() => {
                //InfoLogger.SendInfo(originalRoomId, "DEBUG", "正在刷新信息");

                var roomWebPageUrl = "https://api.live.bilibili.com/room/v1/Room/get_info?id=" + originalRoomId;
                var wc = new WebClient();
                wc.Headers.Add("Accept: */*");
                wc.Headers.Add("User-Agent: " + Ver.UA);
                wc.Headers.Add("Accept-Language: zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4");

                //发送HTTP请求
                byte[] roomHtml;

                try
                {
                    roomHtml = wc.DownloadData(roomWebPageUrl);
                }
                catch (Exception e)
                {
                    InfoLogger.SendInfo(originalRoomId, "ERROR", "获取房间信息失败:" + e.Message);
                    return null;
                }

                //解析返回结果
                try
                {
                    var roomJson = Encoding.UTF8.GetString(roomHtml);
                    var result = JObject.Parse(roomJson);
                    var uid = result["data"]["uid"].ToString();

                    var userInfoUrl = "https://api.bilibili.com/x/web-interface/card?mid=" + uid;
                    var uwc = new WebClient();
                    uwc.Headers.Add("Accept: */*");
                    uwc.Headers.Add("User-Agent: " + Ver.UA);
                    uwc.Headers.Add("Accept-Language: zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4");

                    byte[] userHtml;
                    try
                    {
                        userHtml = uwc.DownloadData(userInfoUrl);
                    }
                    catch (Exception e)
                    {
                        InfoLogger.SendInfo(originalRoomId, "ERROR", "获取用户信息失败:" + e.Message);
                        return null;
                    }

                    var userJson = Encoding.UTF8.GetString(userHtml);
                    var userResult = JObject.Parse(userJson);
                    var userName = userResult["data"]["card"]["name"].ToString();

                    var roominfo = new RoomInfo
                    {
                        realRoomid = result["data"]["room_id"].ToString(),
                        title = result["data"]["title"].ToString(),
                        liveStatus = result["data"]["live_status"].ToString() == "1" ? true : false,
                        username = userName
                    };
                    return roominfo;
                }
                catch (Exception e)
                {
                    InfoLogger.SendInfo(originalRoomId, "ERROR", "房间信息解析失败:" + e.Message);
                    return null;
                }
            }));
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            //Question 1
            Context ctx = new Context(new ShipSafe(0));

            ctx.LevelUp();
            ctx.LevelUp();
            ctx.TakeDamage();
            ctx.LevelUp();
            ctx.LevelUp();
            ctx.LevelUp();
            ctx.TakeDamage();
            ctx.TakeDamage();
            //Question 2
            Component root      = new Composite(2);
            Component circle1   = new Leaf(1);
            Component rectangle = new Leaf(2);

            root.AddChild(circle1);
            root.AddChild(rectangle);

            Component container1 = new Composite(1);
            Component circle2    = new Leaf(3);
            Component circle3    = new Leaf(1);

            container1.AddChild(circle2);
            container1.AddChild(circle3);

            root.AddChild(container1);

            Component container2 = new Composite(1);
            Component t1         = new Leaf(5);
            Component t2         = new Leaf(1);
            Component t3         = new Leaf(1);

            container2.AddChild(t1);
            container2.AddChild(t2);
            container2.AddChild(t3);
            root.AddChild(container2);

            root.Draw("");

            Console.WriteLine(root.countLeaf());
            //Console.WriteLine(container1.countLeaf());
            //Console.WriteLine(container2.countLeaf());
            //Console.WriteLine(t1.countLeaf());

            Console.WriteLine(isZugi(root));
            //Question 3
            CarProxy car = new CarProxy();

            // Drive the car

            car.StartDriving();
            car.showLocation();

            //Question 5
            FatalLogger fatal = new FatalLogger();
            ErrorLogger error = new ErrorLogger();
            InfoLogger  info  = new InfoLogger();

            LogBase chainRoot = fatal;

            fatal.SetNext(error);
            error.SetNext(info);
            info.SetNext(null);

            chainRoot.Log("tell me why", 2);
            Console.WriteLine("==================");

            //Question 8
            GymAccessObject gymthings = new GymBase();

            gymthings.Run();

            //Question 10
            IWindow window = new BaseWindow();

            IWindow Tlatmeimad = new TlatMeimadWindow(window);
            IWindow super      = new FlashingWindow(Tlatmeimad);

            Console.WriteLine(super.GetDetails());

            IWindow myfavoriteWindow = new Colors(new TlatMeimadWindow(new FlashingWindow(new BaseWindow())));

            Console.WriteLine(myfavoriteWindow.GetDetails());
            //Question 12
            ComputerFactoryMethod cf = new ComputerFactoryMethod();

            Computer v1 = cf.GetComputer("Gaming");
        }
Ejemplo n.º 28
0
 public static void Info(string message)
 {
     InfoLogger.Info(message);
 }
        public void Execute(Arguments CommandLine)
        {
            string[] inutile = CommandLine.Intercept(new string[] { "dateStart", "dateEnd", "step1", "step2", "step3", "step4", "step5", "calculate", "factsetPath", "modelClassificationPath", "notationISR", "actPtfAlimSQSLrequest", "env" });
            // afficher les parametres passés et inutiles
            // prendre ceux qui commencent par @xxx ou #xxx qui représentent les variables
            if (inutile.Length > 0)
            {
                if (InfoLogger.IsInfoEnabled)
                {
                    string liste = "(";
                    foreach (string s in inutile)
                    {
                        if (!s.StartsWith("@") && !s.StartsWith("#"))
                        {
                            liste += s + " ";
                        }
                    }
                    liste += ")";
                    if (liste.Length > 2)
                    {
                        InfoLogger.Info("Les parametres suivants ne sont pas exploitees: " + liste);
                    }
                }
            }
            //------------------------------------------------------------------------------------------
            if (CommandLine["env"] != null)
            {
                ENV = CommandLine["env"];
            }
            //------------------------------------------------------------------------------------------
            // 2 configurations: dateStart et dateEnd au format JJ/MM/AAAA , donc toutes les dates comprises entre Start et End, sauf les WE
            //                   dateStart et dateEnd au format MM/AAAA , donc toutes les fins de mois comprises entre Start et End
            //------------------------------------------------------------------------------------------
            DateTime dStart, dEnd, dEom;
            bool     eom_config = false;

            DateTime.TryParse(CommandLine["dateStart"], out dStart);
            if (!DateTime.TryParse(CommandLine["dateEnd"], out dEnd))
            {
                dEnd = dStart;
            }
            if (CommandLine["dateStart"].Length <= 7)
            {
                eom_config = true;
                if (CommandLine["dateEnd"].Length <= 7)
                {
                    // take the next 1rst day of month
                    dEnd = dEnd.AddMonths(1);
                    if (dEnd.DayOfWeek == DayOfWeek.Saturday)
                    {
                        dEnd = dEnd.AddDays(2);
                    }
                    else if (dEnd.DayOfWeek == DayOfWeek.Sunday)
                    {
                        dEnd = dEnd.AddDays(1);
                    }
                }
            }

            dEom = dStart;

            for (DateTime dateOfData = dStart; dateOfData <= dEnd; dateOfData = dateOfData.AddDays(1))
            {
                InfoLogger.Info("Donnees du " + dateOfData + " en cours: " + DateTime.Now.ToString());

                if (dateOfData.DayOfWeek == DayOfWeek.Saturday || dateOfData.DayOfWeek == DayOfWeek.Sunday)
                {
                    InfoLogger.Info("La date est un WE. Pas d integration " + dateOfData);
                    continue;
                }
                if (eom_config)
                {
                    // if the date end of month is the previous month,
                    if ((dateOfData.Month == 1 && dEom.Month == 12) || dateOfData.Month > dEom.Month)
                    {
                        try
                        {
                            ACTION_PROCESS(dEom, CommandLine);
                        }
                        catch (DirectoryNotFoundException e)
                        {
                            InfoLogger.Error("File not found ... continue", e);
                        }
                    }
                }
                else
                {
                    ACTION_PROCESS(dateOfData, CommandLine);
                }
                dEom = dateOfData;
            }
        }
Ejemplo n.º 30
0
        public CommentModel(string json, long time, int version = 1)
        {
            Time        = time;
            RawData     = json;
            JsonVersion = version;
            switch (version)
            {
            case 1:
            {
                var obj = JArray.Parse(json);

                CommentText = obj[1].ToString();
                CommentUser = obj[2][1].ToString();
                MsgType     = MsgTypeEnum.Comment;
                break;
            }

            case 2:
            {
                var obj = JObject.Parse(json);

                var cmd = obj["cmd"].ToString();
                if (cmd.StartsWith("LIVE"))
                {
                    MsgType = MsgTypeEnum.LiveStart;
                    RoomId  = obj["roomid"].ToString();
                }
                else if (cmd.StartsWith("PREPARING"))
                {
                    MsgType = MsgTypeEnum.LiveEnd;
                    RoomId  = obj["roomid"].ToString();
                }
                else if (cmd.StartsWith("DANMU_MSG"))
                {
                    CommentText   = obj["info"][1].ToString();
                    CommentUser   = obj["info"][2][1].ToString();
                    IsAdmin       = obj["info"][2][2].ToString() == "1";
                    IsVip         = obj["info"][2][3].ToString() == "1";
                    DmType        = Convert.ToInt32(obj["info"][0][1]);
                    Fontsize      = Convert.ToInt32(obj["info"][0][2]);
                    Color         = Convert.ToInt32(obj["info"][0][3]);
                    SendTimestamp = Convert.ToInt64(obj["info"][0][4]);
                    UserHash      = obj["info"][0][7].ToString();
                    MsgType       = MsgTypeEnum.Comment;
                }
                else if (cmd.StartsWith("SEND_GIFT"))
                {
                    MsgType   = MsgTypeEnum.GiftSend;
                    GiftName  = obj["data"]["giftName"].ToString();
                    GiftUser  = obj["data"]["uname"].ToString();
                    Giftrcost = obj["data"]["rcost"].ToString();
                    GiftNum   = obj["data"]["num"].ToString();
                }
                else if (cmd.StartsWith("GIFT_TOP"))
                {
                    MsgType = MsgTypeEnum.GiftTop;
                }
                else if (cmd.StartsWith("WELCOME"))
                {
                    MsgType     = MsgTypeEnum.Welcome;
                    CommentUser = obj["data"]["uname"].ToString();
                    IsVip       = true;
                    IsAdmin     = obj["data"]["isadmin"].ToString() == "1";
                }
                else if (cmd == "SUPER_CHAT_MESSAGE")
                {
                    MsgType = MsgTypeEnum.SuperChatMessage;
                    var price = obj["data"]["price"].ToString();
                    CommentText   = $"SC ¥{price} " + obj["data"]["message"].ToString();
                    CommentUser   = obj["data"]["user_info"]["uname"].ToString();
                    Fontsize      = 40;
                    SendTimestamp = Convert.ToInt64(obj["data"]["ts"]);
                    InfoLogger.SendInfo("debug", "superchat", CommentText);
                }
                else
                {
                    MsgType = MsgTypeEnum.Unknown;
                }
                break;
            }

            default:
                throw new Exception("无法解析的弹幕数据");
            }
        }
        /// <summary>
        /// PROGRAMME EXECUTE
        /// Parametres: fichier_cours_xls et/ou fichier_prix_xls pour les extractions en cours devises et prix des composants
        /// msci_files_path pour le chemin vers les fichiers sources (par defaut:G:\,FGA Systèmes\PRODUCTION\FTP\INDICES\MSCI\)
        /// date pour la date utilisée
        /// liste_exclusion_prix pour une liste des tickers bloomberg à exclure
        /// </summary>
        /// <param name="args"></param>
        public void Execute(Arguments CommandLine)
        {
            string[] inutile = CommandLine.Intercept(new string[] { "fichier_cours_csv", "fichier_cours_xls", "fichier_devises_csv", "fichier_devises_xls", "date", "msci_files_path", "liste_exclusion_prix" });
            // afficher les parametres passés et inutiles
            // prendre ceux qui commencent par @xxx ou #xxx qui représentent les variables
            if (inutile.Length > 0)
            {
                if (InfoLogger.IsInfoEnabled)
                {
                    string liste = "(";
                    foreach (string s in inutile)
                    {
                        if (!s.StartsWith("@") && !s.StartsWith("#"))
                        {
                            liste += s + " ";
                        }
                    }
                    liste += ")";
                    if (liste.Length > 2)
                    {
                        InfoLogger.Info("Les parametres suivants ne sont pas exploitees: " + liste);
                    }
                }
            }

            DataSet DS_fichier_cours   = null;
            DataSet DS_fichier_devises = null;

            //------------------------------------------------------------------------------------------
            if (CommandLine["date"] != null)
            {
                if (CommandLine["msci_files_path"] != null)
                {
                    this.MSCI_Settings = this.GetPathSettings(CommandLine["date"], CommandLine["msci_files_path"]);
                }
                else
                {
                    this.MSCI_Settings = this.GetPathSettings(CommandLine["date"]);
                }


                // Soit extraction des cours MSCI
                if ((CommandLine["fichier_cours_xls"] != null) || (CommandLine["fichier_cours_csv"] != null))
                {
                    if (CommandLine["liste_exclusion_prix"] != null)
                    {
                        string [] excluded = CommandLine["liste_exclusion_prix"].Split(new char[] { ',', ';', ':' });
                        this.excluded_security_ticker = new HashSet <string>(excluded);
                    }
                    DS_fichier_cours = this.Extract_ZIPFile_MSCI_Indexes_Daily_Security();
                }

                if (CommandLine["fichier_cours_xls"] != null)
                {
                    string outputFileName = this.ParameterFileNameWithDateTime(CommandLine["fichier_cours_xls"], this.MSCI_Settings.RUNNING_TIME);
                    ExcelFile.CreateWorkbook(DS_fichier_cours, outputFileName);
                }
                if (CommandLine["fichier_cours_csv"] != null)
                {
                    string outputFileName = this.ParameterFileNameWithDateTime(CommandLine["fichier_cours_csv"], this.MSCI_Settings.RUNNING_TIME);
                    CSVFile.WriteToCSV(DS_fichier_cours, outputFileName);
                }

                // Soit extraction des devises MSCI
                if ((CommandLine["fichier_devises_xls"] != null) || (CommandLine["fichier_devises_csv"] != null))
                {
                    DS_fichier_devises = this.Extract_ZIPFile_MSCI_Indexes_Daily_ForexRate();
                }


                if (CommandLine["fichier_devises_xls"] != null)
                {
                    string outputFileName = this.ParameterFileNameWithDateTime(CommandLine["fichier_devises_xls"], this.MSCI_Settings.RUNNING_TIME);
                    ExcelFile.CreateWorkbook(DS_fichier_devises, outputFileName);
                }
                if (CommandLine["fichier_devises_csv"] != null)
                {
                    string outputFileName = this.ParameterFileNameWithDateTime(CommandLine["fichier_devises_csv"], this.MSCI_Settings.RUNNING_TIME);
                    CSVFile.WriteToCSV(DS_fichier_devises, outputFileName);
                }
            }
        }
Ejemplo n.º 32
0
 /// <remarks/>
 public void InfoMessageAsync(InfoLogger log, object userState) {
     if ((this.InfoMessageOperationCompleted == null)) {
         this.InfoMessageOperationCompleted = new System.Threading.SendOrPostCallback(this.OnInfoMessageOperationCompleted);
     }
     this.InvokeAsync("InfoMessage", new object[] {
                 log}, this.InfoMessageOperationCompleted, userState);
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Copie les métata data (schema, tables, PK et FK, ProcStock d'une BDD dans un tableau à 4 entrées:
        /// <list type="dd">TABLE</list>
        /// <list type="dd">SCHEMA</list>
        /// <list type="dd">FK</list>
        /// <list type="dd">PROCSTOC</list>
        /// </summary>
        /// <param name="ListMode">rien ou vide pour ne pas tenir compte de la liste , toutes les tables de la source sont concernées / "exclude" pour donner une liste de tables à exclure / "include" pour donner le nom des tables à inclure</param>
        /// <param name="ListTableName">la liste des noms des tables à considerer dns un mode exclude ou include </param>
        public override DataSet GetMetatDataDBScripts(ListeMode mode = ListeMode.Aucune, List <DatabaseTable> ListTableName = null)
        {
            // nom de la base de source
            string dbName = Connection.Database.ToString();

            // structure de retour contenant les scripts
            DataSet ds = new DataSet("SCRIPTS");

            DataTable tableDT = new DataTable("TABLE");

            tableDT.Columns.Add("sql");
            ds.Tables.Add(tableDT);

            DataTable fkDT = new DataTable("FK");

            fkDT.Columns.Add("sql");
            ds.Tables.Add(fkDT);

            DataTable procstocDT = new DataTable("PROCSTOC");

            procstocDT.Columns.Add("sql");
            ds.Tables.Add(procstocDT);

            DataTable schemaDT = new DataTable("SCHEMA");

            schemaDT.Columns.Add("sql");
            ds.Tables.Add(schemaDT);

            //SMO Server object setup with SQLConnection.
            Server server = new Server(new ServerConnection((SqlConnection)Connection));

            //Set Database to the database
            Database db = server.Databases[dbName];
            //----------------------------------------------------------------------------------------------------------------

            /*Option pour la creation des tables
             * inclus les cles primaires, les contraintes nonclustered et
             * if not exist pour ne pas creer une table qui existe deja*/
            ScriptingOptions tablesScriptOptions = new ScriptingOptions();

            tablesScriptOptions.DriPrimaryKey      = true;
            tablesScriptOptions.IncludeIfNotExists = true;
            tablesScriptOptions.DriNonClustered    = true;

            /*Option pour les foreign key de chaque table,
             * préposé de leur schéma*/
            ScriptingOptions fkScriptOptions = new ScriptingOptions();

            fkScriptOptions.SchemaQualifyForeignKeysReferences = true;
            fkScriptOptions.DriForeignKeys = true;

            InfoLogger.Debug("Obtention metadonnees tables et clefs");

            StringCollection schemaCollection = new StringCollection();

            foreach (Table myTable in db.Tables)
            {
                // si il y a une liste
                if (mode.Equals(ListeMode.Include))
                {
                    if (!ListTableName.Contains(myTable.Name, myTable.Schema))
                    {
                        continue;
                    }
                }
                else if (mode.Equals(ListeMode.Exclude))
                {
                    if (ListTableName.Contains(myTable.Name, myTable.Schema))
                    {
                        continue;
                    }
                }

                //Si c'est un nouveau schéma on retient son nom
                if (!schemaCollection.Contains("[" + myTable.Schema + "]"))
                {
                    schemaCollection.Add("[" + myTable.Schema + "]");
                }

                //On ajoute le script de la table à tableCol
                StringCollection tableScripts = myTable.Script(tablesScriptOptions);
                // maj de la Dataset
                DataRow dr = tableDT.NewRow();
                foreach (string scriptLine in tableScripts)
                {
                    dr["sql"] += scriptLine + System.Environment.NewLine;
                }
                tableDT.Rows.Add(dr);


                //On ajoute le script des foreign keys à foreignKeyCol
                ForeignKeyCollection fk = myTable.ForeignKeys;
                foreach (ForeignKey myFk in fk)
                {
                    StringCollection stmp = myFk.Script(fkScriptOptions);
                    // maj de la Dataset
                    DataRow fkDr = fkDT.NewRow();
                    foreach (string scriptLine in stmp)
                    {
                        fkDr["sql"] += scriptLine + System.Environment.NewLine;
                    }
                    fkDT.Rows.Add(fkDr);
                }
            }
            //Enleve le schéma par défault
            schemaCollection.Remove("[dbo]");


            InfoLogger.Debug("Obtention des Procédures stockées");
            ScriptingOptions scrOptProcStoc = new ScriptingOptions()
            {
                NoCommandTerminator = false, ScriptBatchTerminator = true, IncludeIfNotExists = true
            };

            foreach (StoredProcedure sp in db.StoredProcedures)
            {
                if (!sp.Schema.Equals("sys") && !sp.IsSystemObject)
                {
                    StringCollection scsp = sp.Script(scrOptProcStoc);
                    // maj de la Dataset
                    DataRow pcDr = procstocDT.NewRow();
                    foreach (string scriptLine in scsp)
                    {
                        pcDr["sql"] += scriptLine + System.Environment.NewLine;
                    }
                    procstocDT.Rows.Add(pcDr);
                }
            }

            InfoLogger.Debug("Obtention Metadonnees schemas");
            SchemaCollection sc            = db.Schemas;
            ScriptingOptions scrOpt_Schema = new ScriptingOptions()
            {
                IncludeIfNotExists = true
            };

            foreach (Schema schem in sc)
            {
                if (schemaCollection.Contains(schem.ToString()))
                {
                    StringCollection schemaScripts = schem.Script(scrOpt_Schema);
                    // maj de la Dataset
                    DataRow schemaDr = schemaDT.NewRow();
                    foreach (string scriptLine in schemaScripts)
                    {
                        schemaDr["sql"] += scriptLine + System.Environment.NewLine;
                    }
                    schemaDT.Rows.Add(schemaDr);
                }
            }
            Connection.Close();

            return(ds);
        }