public void DisConnectServer(ServerType serverType)
 {
     try
     {
         if (ProtocolManager[serverType.ToString()].State == ChannelState.Opened)
         {
             ProtocolManager[serverType.ToString()].Close();
         }
         ProtocolManager.Unregister(serverType.ToString());
     }
     catch { }
 }
Exemplo n.º 2
0
    // ToString
    public override string ToString()
    {
        var playerList =
            from p in players
            select p.ToString();

        var playerListString = string.Join(", ", playerList.ToArray());

        if (instance != null)
        {
            return(string.Format("[{0}] {1}\n * {2}:{3}\n * Players: [{4}]\n{5}", _serverType.ToString(), _mapName, instance.node.publicAddress, instance.port, playerListString, cmdLine));
        }

        return(string.Format("[{0}] {1}\n * Players: [{2}]\n{3}", _serverType.ToString(), _mapName, playerListString, cmdLine));
    }
Exemplo n.º 3
0
 protected BaseServer(ServerType _serverType, int _maxConnections = 0, ushort _port = 6256)
 {
     serverType     = _serverType;
     serverTypeName = Utilities.SplitByPascalCase(serverType.ToString());
     maxConnections = _maxConnections;
     port           = _port == 0 ? (ushort)6256 : _port;
 }
Exemplo n.º 4
0
        public List <ServerItem> GetItems(ServerType serverType)
        {
            var result  = new List <ServerItem>();
            var xmlNode = _xmlDoc.GetElementsByTagName(serverType.ToString());

            if (xmlNode.Count == 0)
            {
                return(result);
            }
            var childNodes = xmlNode[0].ChildNodes;

            for (var i = 0; i <= childNodes.Count - 1; i++)
            {
                var xmlAttributeCollection = childNodes[i].Attributes;
                if (xmlAttributeCollection == null)
                {
                    continue;
                }

                var id   = xmlAttributeCollection["id"].Value;
                var file = xmlAttributeCollection["file"]?.Value;
                result.Add(new ServerItem(id, file));
            }
            return(result);
        }
Exemplo n.º 5
0
        public void Save(XmlWriter writer)
        {
            writer.WriteStartElement(OPTIONS);

            writer.WriteStartElement(ROUNDS);
            writer.WriteValue(m_rounds.ToString(CultureInfo.InvariantCulture));
            writer.WriteEndElement();

            writer.WriteStartElement(SERVER);
            writer.WriteValue(m_server.ToString());
            writer.WriteEndElement();

            writer.WriteStartElement(BARACK);
            writer.WriteValue(m_baracksLevel.ToString(CultureInfo.InvariantCulture));
            writer.WriteEndElement();

            writer.WriteStartElement(BREAD_LOSSES);
            writer.WriteValue(m_breadLosses.ToString(CultureInfo.InvariantCulture));
            writer.WriteEndElement();

            writer.WriteStartElement(MULTI_WAVE_BATTLE_TYPE);
            writer.WriteValue(((int)m_multiWaveBattleType).ToString(CultureInfo.InvariantCulture));
            writer.WriteEndElement();

            writer.WriteEndElement();
        }
Exemplo n.º 6
0
        private static string SkipIfServerIsNotSupportedOnThisOS(ServerType server)
        {
            var skip = false;

            switch (server)
            {
            case ServerType.IIS:
            case ServerType.IISExpress:
            case ServerType.HttpSys:
                skip = !OperatingSystem.IsWindows();
                break;

            case ServerType.Kestrel:
                break;

            case ServerType.Nginx:
                // Technically it's possible but we don't test it.
                skip = OperatingSystem.IsWindows();
                break;

            default:
                throw new ArgumentException(server.ToString());
            }

            return(skip ? "This server is not supported on this operating system." : null);
        }
Exemplo n.º 7
0
        /// <summary>
        /// 创建数据库实例。
        /// </summary>
        /// <param name="serverType">数据服务器类型</param>
        /// <param name="connString">数据连接字符串</param>
        /// <returns></returns>
        public static IDbHelper Create(ServerType serverType, string connString)
        {
            //检查缓存
            string key = serverType.ToString() + "|" + connString;

            if (_helperList.ContainsKey(key))
            {
                return(_helperList[key].CloneNew());
            }

            //反射实例化对象
            string    className = GetInstanceClassName(serverType) + "Helper";
            Assembly  ass       = Assembly.GetExecutingAssembly();
            IDbHelper helper    = ass.CreateInstance(className, false, BindingFlags.Default, null, new object[] { serverType, connString }, null, null) as IDbHelper;

            if (helper == null)
            {
                throw new DataObjectException("未能实例化数据库 Helper 对象!");
            }
            if (!_helperList.ContainsKey(key))
            {
                _helperList[key] = helper;
            }
            return(helper.CloneNew());
            //throw new DataObjectException("配置文件 ConnectionString 节的 ProviderName 信息不正确!没有实现关于此数据连接类型的 DbHelper 插件!");
        }
Exemplo n.º 8
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="serverType">Server type</param>
        /// <param name="serverName">Server name</param>
        /// <param name="trusted">true if connection is trused. If true user name and password are ignored</param>
        /// <param name="userName">User name for not trusted connections</param>
        /// <param name="password">Password for not trusted connections</param>
        /// <param name="xmlParameters">XML string with parameters</param>
        public CDataContainer(ServerType serverType, string serverName, bool trusted, string userName, SecureString password, string databaseName, string xmlParameters, string azureAccountToken = null)
        {
            this.serverType = serverType;
            this.serverName = serverName;

            if (serverType == ServerType.SQL)
            {
                // does some extra initialization
                ApplyConnectionInfo(GetTempSqlConnectionInfoWithConnection(serverName, trusted, userName, password, databaseName, azureAccountToken), true);

                // NOTE: ServerConnection property will constuct the object if needed
                m_server = new Server(ServerConnection);
            }
            else
            {
                throw new ArgumentException(SR.UnknownServerType(serverType.ToString()));
            }

            if (xmlParameters != null)
            {
                this.Document = GenerateXmlDocumentFromString(xmlParameters);
            }

            if (ServerType.SQL == serverType)
            {
                this.InitializeObjectNameAndSchema();
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Функция инициализации подключения к базе данных.
        /// </summary>
        /// <returns>Если успешно, то true</returns>
        private bool ConnectionInitDataBase()
        {
            //Далее только если подключение не через сервер приложений:
            this.DatabaseLoginDecrypt = Crypto.DecryptAES(DatabaseLogin);
            this.DatabasePassDecrypt  = Crypto.DecryptAES(DatabasePass);

            try
            {
                if (serverType == ServerType.Postgre)
                {
                    ConnectStringPostgre = "Server=" + ServerName + ";User Id=" + DatabaseLoginDecrypt + ";Password="******";Database=" + DatabaseName + ";";
                    Npgsql.NpgsqlConnection connection1 = null;
                    connection1 = new Npgsql.NpgsqlConnection(ConnectStringPostgre);
                    connection1.Open();
                }

                if (serverType == ServerType.MSSQL)
                {
                    if (DatabaseLogin == "")
                    {
                        ConnectStringMSSQL = @"Data Source=" + ServerName + ";Initial Catalog=" + DatabaseName + ";Integrated Security=True";
                    }
                    else
                    {
                        ConnectStringMSSQL = "Server=" + ServerName + ";User Id=" + DatabaseLoginDecrypt + ";Password="******";Database=" + DatabaseName + ";";        //Connection Timeout=2;
                    }
                    System.Data.SqlClient.SqlConnection connection2;
                    connection2 = new System.Data.SqlClient.SqlConnection(ConnectStringMSSQL);
                    connection2.Open();
                }

                if (serverType == ServerType.SQLite)
                {
                    if ((sys.ErrorCheck(!File.Exists(ServerName), "Не найден файл базы данных.")))
                    {
                        return(false);
                    }
                    ConnectStringSQLite = @"Data Source=" + ServerName + @";New=False;Version=3;";
                    System.Data.SQLite.SQLiteConnection connection;
                    connection = new System.Data.SQLite.SQLiteConnection(ConnectStringSQLite);
                    connection.Open();
                    //connection3.BindFunction(CloseToSQLiteFunction.GetAttribute(), new CloseToSQLiteFunction());
                }
                serverTypeRemote = serverType;
                ConnectionActive = true;
                ConnectionDirect = true;
                return(true);
            }
            catch (Exception e)
            {
                sys.SM("Ошибка подключения: " + e.Message + " к серверу " + serverType.ToString());
                ConnectionActive = false;
                ConnectionDirect = false;
                return(false);
            }
        }
        public NewServer()
        {
            InitializeComponent();

            for (int i = 0; i < Enum.GetValues(typeof(ServerType)).Length; i++)
            {
                ServerType type = (ServerType)i;
                comboBox_ServerJarType.Items.Add(type.ToString());
            }
        }
Exemplo n.º 11
0
 public NecQueueConsumer(ServerType serverType, NecSetting setting, AsyncEventSettings socketSetting) : base(
         socketSetting, serverType.ToString())
 {
     _serverType         = serverType;
     _setting            = setting;
     _lock               = new object();
     _clientHandlers     = new Dictionary <int, IClientHandler>();
     _connectionHandlers = new Dictionary <int, IConnectionHandler>();
     _connections        = new Dictionary <ITcpSocket, NecConnection>();
 }
        /// <summary>
        /// Gets the type of the server.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public FrameworkServerType GetServerType(ServerType serverType)
        {
            string type = serverType.ToString();

            return
                ((
                     from x in _context.FrameworkServerTypes
                     where x.Name.Equals(type.ToString(), StringComparison.OrdinalIgnoreCase)
                     select x
                     ).FirstOrDefault());
        }
        /// <summary>
        /// Gets the servers based on the server type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public IQueryable <FrameworkServer> GetServersByType(ServerType type)
        {
            string serverType = type.ToString();

            return
                (from x in _context.FrameworkServers
                 where x.ServerTypes.Any(e => e.Name.Equals(serverType, StringComparison.OrdinalIgnoreCase)) &&
                 x.Active
                 orderby x.HostName ascending
                 select x);
        }
    public static string ToString(this string text, ServerType ServerType)
    {
        switch (ServerType)
        {
        case ServerType.Database:
            return("Database server");

        case ServerType.Web:
            return("Web server");
        }
        // other ones, just use the base method
        return(ServerType.ToString());
    }
Exemplo n.º 15
0
        private bool IsResponseValid(IHttpResponse httpResponse, ServerType serverType)
        {
            switch (serverType)
            {
            case ServerType.MainServer:
                return(IsStatusCodeOk(httpResponse.StatusCode));

            case ServerType.CacheServer:
                return(httpResponse.StatusCode == HttpStatusCode.OK);

            default:
                throw new ArgumentOutOfRangeException(serverType.ToString(), serverType, null);
            }
        }
Exemplo n.º 16
0
        protected override void WriteDataXML(XElement ele, ElderScrollsPlugin master)
        {
            XElement subEle;

            ele.TryPathTo("HackingDifficulty", true, out subEle);
            subEle.Value = HackingDifficulty.ToString();

            ele.TryPathTo("Flags", true, out subEle);
            subEle.Value = Flags.ToString();

            ele.TryPathTo("ServerType", true, out subEle);
            subEle.Value = ServerType.ToString();

            WriteUnusedXML(ele, master);
        }
Exemplo n.º 17
0
        private bool IsResponseUnexpectedError(IHttpResponse httpResponse, ServerType serverType)
        {
            switch (serverType)
            {
            case ServerType.MainServer:
                return(!IsStatusCodeOk(httpResponse.StatusCode) &&
                       !IsStatusCodeServerError(httpResponse.StatusCode));

            case ServerType.CacheServer:
                return(false);    // ignore any api cache error

            default:
                throw new ArgumentOutOfRangeException(serverType.ToString(), serverType, null);
            }
        }
Exemplo n.º 18
0
        public static string [] ServerTypeArray(int Value)
        {
            string []  values;
            string     value_list;
            ServerType st_mask = (ServerType)Value;

            value_list = st_mask.ToString("G");
            values     = value_list.Split(',');

            for (int i = 0; i < values.Length; i++)
            {
                values[i] = values[i].Trim();
            }

            return(values);
        }
Exemplo n.º 19
0
        public DbSource(XElement xml)
            : base(xml)
        {
            // Setup type include default port
            var attributeSafe = xml.AttributeSafe("ServerType");

            switch (attributeSafe.ToLowerInvariant())
            {
            case "sqldatabase":
                ServerType = enSourceType.SqlDatabase;
                Port       = 1433;
                break;

            case "mysqldatabase":
                ServerType = enSourceType.MySqlDatabase;
                break;

            case "oracle":
                ServerType = enSourceType.Oracle;
                Port       = 1521;
                break;

            case "odbc":
                ServerType = enSourceType.ODBC;
                break;

            case "postgresql":
                ServerType = enSourceType.PostgreSQL;
                break;

            case "sqlite":
                ServerType = enSourceType.SQLiteDatabase;
                break;

            default:
                ResourceType = "DbSource";
                ServerType   = enSourceType.Unknown;
                break;
            }

            var conString        = xml.AttributeSafe("ConnectionString");
            var connectionString = conString.CanBeDecrypted() ? DpapiWrapper.Decrypt(conString) : conString;

            ResourceType     = ServerType.ToString();
            ConnectionString = connectionString;
        }
        private void ConfigureDisplay()
        {
            string stringValue = _serverType.ToString();

            this.Text = "{0} Server Management".FormatWith(stringValue);
            servers_ToolStripLabel.Text = "{0} Servers".FormatWith(stringValue);
            queues_ToolStripLabel.Text  = "{0} Queues".FormatWith(stringValue);

            // Set Users ability to automatically refresh queues
            newServer_ToolStripButton.Enabled   =
                refresh_ToolStripButton.Enabled =
                    (_serverType != ServerType.ePrint);

            // Set Users ability to manually edit Queues
            newQueue_ToolStripButton.Visible          =
                removeQueue_ToolStripButton.Visible   =
                    editQueue_ToolStripButton.Visible =
                        (_serverType == ServerType.ePrint);
        }
        public void Run()
        {
            if (IsRunning)
            {
                KillServer();
                return;
            }

            if (!Directory.Exists(GetWorkingDirectory()))
            {
                Directory.CreateDirectory(GetWorkingDirectory());
            }

            string pathToJar = Directory.GetCurrentDirectory() + "\\jars\\" + type.ToString().ToLower() + ".jar";

            Console.WriteLine("Searching for jar in: " + pathToJar);
            if (!File.Exists(pathToJar))
            {
                Console.WriteLine("Could not find jar file.");
                return;
            }

            Process = new Process();
            Process.StartInfo.UseShellExecute        = false;
            Process.StartInfo.CreateNoWindow         = true;
            Process.StartInfo.RedirectStandardOutput = true;
            Process.StartInfo.RedirectStandardInput  = true;
            Process.StartInfo.RedirectStandardError  = true;
            Process.EnableRaisingEvents        = true;
            Process.StartInfo.FileName         = "java.exe";
            Process.StartInfo.Arguments        = "-Xmx" + Memory + "M -jar " + "\"" + pathToJar + "\" -nojline";
            Process.StartInfo.WorkingDirectory = GetWorkingDirectory();

            Process.OutputDataReceived += Process_OutputDataReceived;
            Process.ErrorDataReceived  += Process_OutputDataReceived;

            Process.Start();

            Process.BeginOutputReadLine();
            Process.BeginErrorReadLine();
        }
Exemplo n.º 22
0
        private void setServerType(ServerType type)
        {
            Console.WriteLine("...Setting server type to <" + type.ToString() + ">");

            ServerTypeInput serverTypeInput = ServerTypeInput.CreateBuilder()
                                              .SetServertype(MapServerType(type)).Build();

            ApiInput apiInput = ApiInput.CreateBuilder()
                                .SetMsgType(ApiInput.Types.MessageType.SERVER_TYPE)
                                .SetMsgData(serverTypeInput.ToByteString()).Build();

            this.send(apiInput);

            /*
             * EzeResult result = null;
             *
             * while (true)
             * {
             *  result = this.getResult(this.receive());
             *  if (result.getEventName() == EventName.SET_SERVER_TYPE) break;
             * }*/
        }
Exemplo n.º 23
0
        /// <summary>
        /// connect to API
        /// подсоединиться к апи
        /// </summary>
        public void Connect()
        {
            if (_client == null)
            {
                _client = new LivecoinClient(((ServerParameterString)ServerParameters[0]).Value,
                                             ((ServerParameterPassword)ServerParameters[1]).Value,
                                             ServerType.ToString());
                _client.Connected         += Client_Connected;
                _client.UpdatePairs       += Client_UpdatePairs;
                _client.Disconnected      += Client_Disconnected;
                _client.NewPortfolio      += Client_NewPortfolio;
                _client.UpdatePortfolio   += Client_UpdatePortfolio;
                _client.NewMarketDepth    += Client_NewMarketDepth;
                _client.UpdateMarketDepth += Client_UpdateMarketDepth;
                _client.NewTradesEvent    += Client_NewTradesEvent;
                _client.MyTradeEvent      += Client_MyTradeEvent;
                _client.MyOrderEvent      += Client_MyOrderEvent;
                _client.LogMessageEvent   += SendLogMessage;
            }

            _client.Connect();
        }
Exemplo n.º 24
0
        /// <summary>
        /// contructs the object and initializes its SQL ConnectionInfo and ServerConnection properties
        /// using the specified connection info containing live connection.
        ///
        /// in addition creates a server of the given server type
        /// </summary>
        /// <param name="ci">connection info containing live connection</param>
        public CDataContainer(ServerType serverType, object ciObj, bool ownConnection)
        {
            SqlConnectionInfoWithConnection ci = (SqlConnectionInfoWithConnection)ciObj;

            if (ci == null)
            {
                throw new ArgumentNullException("ci");
            }

            this.serverType = serverType;
            ApplyConnectionInfo(ci, ownConnection);

            if (serverType == ServerType.SQL)
            {
                //NOTE: ServerConnection property will constuct the object if needed
                m_server = new Server(ServerConnection);
            }
            else
            {
                throw new ArgumentException(SR.UnknownServerType(serverType.ToString()));
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Gets the URL.
        /// </summary>
        /// <param name="serverType">Type of the server.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException">Invalid url for  + serverType.ToString()</exception>
        public static string GetUrl(ServerType serverType)
        {
            switch (serverType)
            {
            case ServerType.Payments:

                return(string.IsNullOrEmpty(PayuNetSdk.PayU.Api.PayU.PaymentsUrl) ?
                       string.Format("{0}{1}", Enviroment.PAYMENTS_URL, Enviroment.POST_VERSION) :
                       string.Format("{0}{1}", PayuNetSdk.PayU.Api.PayU.PaymentsUrl, Enviroment.POST_VERSION));

            case ServerType.Reports:

                return(string.IsNullOrEmpty(PayuNetSdk.PayU.Api.PayU.ReportsUrl) ?
                       string.Format("{0}{1}", Enviroment.REPORTS_URL, Enviroment.POST_VERSION) :
                       string.Format("{0}{1}", PayuNetSdk.PayU.Api.PayU.ReportsUrl, Enviroment.POST_VERSION));

            case ServerType.RecurringPayment:
                return(string.IsNullOrEmpty(PayuNetSdk.PayU.Api.PayU.PaymentsUrl) ?
                       string.Format("{0}{1}", Enviroment.RECURRING_PAYMENT_URL, Enviroment.REST_VERSION) :
                       string.Format("{0}{1}", PayuNetSdk.PayU.Api.PayU.PaymentsUrl, Enviroment.REST_VERSION));
            }
            throw new NotImplementedException("Invalid url for " + serverType.ToString());
        }
Exemplo n.º 26
0
        /// <summary>
        /// 保存连接参数至配置文件MyDB.xml
        /// </summary>
        /// <returns></returns>
        public bool SaveSettings()
        {
            bool bSuccessSaved = false;

            try
            {
                string DbConfigFile = Directory.GetCurrentDirectory() + "\\" + DB_CONFIG_FILE;

                MyXml.XmlWrite(DbConfigFile, "DbConfig", "ServerType", ServerType.ToString());
                MyXml.XmlWrite(DbConfigFile, "DbConfig", "Server", Server);
                MyXml.XmlWrite(DbConfigFile, "DbConfig", "Port", Port);
                MyXml.XmlWrite(DbConfigFile, "DbConfig", "WindowsAuthentication", WindowsAuthentication.ToString());
                MyXml.XmlWrite(DbConfigFile, "DbConfig", "UserId", UserId);
                MyXml.XmlWrite(DbConfigFile, "DbConfig", "Password", DES.Encrypt(Password, MES_KEY, MES_IV));  //加密
                MyXml.XmlWrite(DbConfigFile, "DbConfig", "Database", Database);
                bSuccessSaved = true;
            }
            catch (Exception ex)
            {
                throw (new Exception(ex.Message));
            }
            return(bSuccessSaved);
        }
Exemplo n.º 27
0
        private void setServerType(ServerType type)
        {
            Console.WriteLine("...Setting server type to <" + type.ToString() + ">");

            ServerTypeInput serverTypeInput = ServerTypeInput.CreateBuilder()
                            .SetServertype(MapServerType(type)).Build();

            ApiInput apiInput = ApiInput.CreateBuilder()
                            .SetMsgType(ApiInput.Types.MessageType.SERVER_TYPE)
                            .SetMsgData(serverTypeInput.ToByteString()).Build();

            this.send(apiInput);

            /*
            EzeResult result = null;

            while (true)
            {
                result = this.getResult(this.receive());
                if (result.getEventName() == EventName.SET_SERVER_TYPE) break;
            }*/
        }
Exemplo n.º 28
0
        private static Process StartSelfHost(ServerType hostType, string applicationPath, string identityDbName)
        {
            Console.WriteLine(string.Format("Executing klr.exe --appbase {0} \"Microsoft.Framework.ApplicationHost\" {1}", applicationPath, hostType.ToString()));

            var startInfo = new ProcessStartInfo
            {
                FileName = "klr.exe",
                Arguments = string.Format("--appbase {0} \"Microsoft.Framework.ApplicationHost\" {1}", applicationPath, hostType.ToString()),
                UseShellExecute = true,
                CreateNoWindow = true
            };

            var hostProcess = Process.Start(startInfo);
            //Sometimes reading MainModule returns null if called immediately after starting process.
            Thread.Sleep(1 * 1000);

            try
            {
                Console.WriteLine("Started {0}. Process Id : {1}", hostProcess.MainModule.FileName, hostProcess.Id);
            }
            catch (Win32Exception ex)
            {
                Console.WriteLine("Cannot access 64 bit modules from a 32 bit process");
            }

            WaitTillDbCreated(identityDbName);

            return hostProcess;
        }
Exemplo n.º 29
0
        public void SendPacket(byte[] data)
        {
            if (m_disposed)
            {
                return;
            }

            lock (m_sendSync)
            {
                if (m_disposed)
                {
                    return;
                }

                byte[] ret;
                byte[] header;

                switch (serverType)
                {
                case ServerType.LoginServer:
                {
                    ret    = new byte[data.Length + 6];
                    header = new byte[4] {
                        0xAA, 0x55, (byte)(data.Length & 0xFF), (byte)((data.Length >> 8) & 0xFF)
                    };
                    Buffer.BlockCopy(header, 0, ret, 0, 4);         // copy header to ret
                    Buffer.BlockCopy(data, 0, ret, 4, data.Length); // copy packet to ret
                    Buffer.BlockCopy(new byte[2] {
                            0x55, 0xAA
                        }, 0, ret, data.Length + 4, 2);                                           // copy end to ret
                    break;
                }

                case ServerType.CharServer:
                case ServerType.GameServer:
                {
                    ret = new byte[data.Length + 2];
                    int a   = 0x4D;
                    int b   = (data[0]) + (data[1] << 8);
                    int c   = ret.Length;
                    int crc = a + b + c;
                    header = new byte[8] {
                        0x4D, 0x00,
                        data[0], data[1],
                        (byte)(ret.Length & 0xFF), (byte)((ret.Length >> 8) & 0xFF),
                        (byte)(crc & 0xFF), (byte)((crc >> 8) & 0xFF)
                    };
                    Buffer.BlockCopy(header, 0, ret, 0, 8);             // copy header to ret
                    Buffer.BlockCopy(data, 6, ret, 8, data.Length - 6); // copy packet to ret
                    break;
                }

                default:
                {
                    ret = new byte[data.Length + 2];
                    int a   = 0x4D;
                    int b   = (data[0]) + (data[1] << 8);
                    int c   = ret.Length;
                    int crc = a + b + c;
                    header = new byte[8] {
                        0x4D, 0x00,
                        data[0], data[1],
                        (byte)(ret.Length & 0xFF), (byte)((ret.Length >> 8) & 0xFF),
                        (byte)(crc & 0xFF), (byte)((crc >> 8) & 0xFF)
                    };
                    Buffer.BlockCopy(header, 0, ret, 0, 8);             // copy header to ret
                    Buffer.BlockCopy(data, 6, ret, 8, data.Length - 6); // copy packet to ret
                    Console.WriteLine("{0} 為未設定的伺服器型態。", serverType.ToString());
                    break;
                }
                }
                SendRawPacket(ret);
            }
        }
Exemplo n.º 30
0
        public void Createreport(string sRDGFile, string sOutputFile)
        {
            StringBuilder sbDetails = new StringBuilder();

            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            int     row = 2, col = 1;
            DataSet ds = new DataSet();

            ds.ReadXml(sRDGFile);

            System.Data.DataTable Groups = ds.Tables["properties"];
            System.Data.DataTable Servers = ds.Tables["server"];

            var query =
                from groups in Groups.AsEnumerable()
                join servers in Servers.AsEnumerable()
                on groups.Field <int?>("group_Id") equals
                servers.Field <int?>("group_Id")
                select new
            {
                GroupName =
                    groups.Field <string>("Name"),
                ServerName =
                    servers.Field <string>("Name"),
                ServerDisplayName =
                    servers.Field <string>("displayName")
            };


            if (xlApp == null)
            {
                Console.WriteLine("Excel is not properly installed!!");
                return;
            }

            Microsoft.Office.Interop.Excel.Workbook  xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlApp.Visible = true;

            xlWorkBook  = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets[1];

            if (xlWorkSheet == null)
            {
                Console.WriteLine("Worksheet could not be created. Check that your office installation and project references are correct.");
            }
            //xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            xlWorkSheet.Cells[1, 1]  = "Server Name";
            xlWorkSheet.Cells[1, 2]  = "Environment";
            xlWorkSheet.Cells[1, 3]  = "Release";
            xlWorkSheet.Cells[1, 4]  = "Server Type";
            xlWorkSheet.Cells[1, 5]  = "Legacy Status";
            xlWorkSheet.Cells[1, 6]  = "NextGen Status";
            xlWorkSheet.Cells[1, 7]  = "DXI Status";
            xlWorkSheet.Cells[1, 8]  = "Mobile Status";
            xlWorkSheet.Cells[1, 9]  = "TLMServices Status";
            xlWorkSheet.Cells[1, 10] = "Dispatcher";

            Range firstRow = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Rows[1];

            firstRow.Activate();
            firstRow.Select();
            firstRow.Font.Bold = true;
            firstRow.AutoFilter(1, Type.Missing,
                                Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlAnd, Type.Missing, true);

            //xlWorkBook.Worksheets.Add(xlWorkSheet);

            //xlWorkBook.SaveAs("C:\\Work\\SVN_Source\\Utilities\\RemoteDesktopConnectionManager\\CreateServerList\\CreateServerList\\bin\\Debug\\ServerList.xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            //xlWorkBook.Save();


            foreach (var server in query)
            {
                col = 1;
                xlWorkSheet.Cells[row, col++] = server.ServerName;
                xlWorkSheet.Cells[row, col++] = server.GroupName.Contains("-") ? server.GroupName.Substring(0, server.GroupName.IndexOf("-")) : server.GroupName;
                xlWorkSheet.Cells[row, col++] = server.GroupName.Contains("-") ? server.GroupName.Substring(server.GroupName.IndexOf("-"),
                                                                                                            server.GroupName.Length - server.GroupName.IndexOf("-")).Replace("_", ".").Replace(",", " ").Replace("-", "").Trim() : string.Empty;

                ServerType eServerType = GetServerType(server.ServerDisplayName, server.ServerName);

                xlWorkSheet.Cells[row, col++] = eServerType == ServerType.UnKnown ? "" : eServerType.ToString();

                switch (eServerType)
                {
                case ServerType.Web:
                    col = 5;
                    break;

                case ServerType.Proc:
                    break;

                case ServerType.MP:
                    col = 7;
                    break;

                case ServerType.MPMax:
                    col = 7;
                    break;

                case ServerType.DXI:
                    col = 7;
                    break;

                case ServerType.DXM:
                    col = 8;
                    break;

                case ServerType.DXIR:
                    col = 7;
                    break;

                case ServerType.ES:
                    col = 10;
                    break;

                case ServerType.EventRouter:
                    col = 10;
                    break;

                case ServerType.REDIR:
                    col = 5;
                    break;

                case ServerType.v18All:
                    col = 5;
                    break;

                default:
                    break;
                }

                string[] strArry = CreateStatusLinks(eServerType, server.ServerName);
                if (strArry != null && strArry.Length > 0)
                {
                    foreach (string str in strArry)
                    {
                        if (str != "")
                        {
                            string[] strLinks = str.ToString().Split(',');
                            //string strLink = "=HYPERLINK(\"" + strLinks[1] + "\",\"\"Infragistics\"\")";
                            if (eServerType == ServerType.v18All)
                            {
                                if (col == 6)
                                {
                                    col = 7;
                                }
                                else if (col == 9)
                                {
                                    col = 10;
                                }
                            }
                            xlWorkSheet.Hyperlinks.Add(xlWorkSheet.Cells[row, col++], strLinks[1], misValue, misValue, strLinks[0]);
                        }
                    }
                }
                row++;
            }

            // xlWorkBook.SaveAs("C:\\Work\\SVN_Source\\Utilities\\RemoteDesktopConnectionManager\\CreateServerList\\CreateServerList\\bin\\Debug\\ServerList.xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);


            //using (System.IO.StreamWriter file = new System.IO.StreamWriter(sOutputFile, true))
            //{
            //    file.WriteLine(sbDetails.ToString());
            //}

            ds.Clear();
        }
Exemplo n.º 31
0
        private bool TrySendRequest(ApiConnectionServer server, Request request, ServerType serverType,
                                    out IApiResponse response)
        {
            Logger.LogDebug(
                string.Format(
                    "Trying to get response from server ({0}): '{1}:{2}' (uses HTTPS: {3})...",
                    serverType,
                    server.Host,
                    server.RealPort,
                    server.UseHttps));

            response = null;

            List <Exception> exceptionsList;

            switch (serverType)
            {
            case ServerType.MainServer:
                exceptionsList = request.MainServerExceptions;
                break;

            case ServerType.CacheServer:
                exceptionsList = request.CacheServersExceptions;
                break;

            default:
                throw new ArgumentOutOfRangeException(serverType.ToString(), serverType, null);
            }

            try
            {
                var uri = new UriBuilder
                {
                    Scheme = server.UseHttps ? "https" : "http",
                    Host   = server.Host,
                    Path   = request.Path,
                    Query  = request.Query,
                    Port   = server.RealPort
                }.Uri;

                var httpResponse = MakeResponse(uri, request);

                Logger.LogDebug("Received response. Checking whether it is valid...");
                Logger.LogTrace(
                    string.Format(
                        "Response status code: {0}",
                        httpResponse.StatusCode));

                if (IsResponseValid(httpResponse, serverType))
                {
                    Logger.LogDebug("Response is valid.");
                    response = new ApiResponse(httpResponse);
                    return(true);
                }

                Logger.LogWarning("Response is not valid.");

                if (IsResponseUnexpectedError(httpResponse, serverType))
                {
                    throw new ApiResponseException((int)httpResponse.StatusCode);
                }

                throw new ApiServerConnectionException(
                          string.Format(
                              "Server \'{0}\' returned code {1}",
                              server.Host,
                              (int)httpResponse.StatusCode));
            }
            catch (WebException webException)
            {
                Logger.LogWarning("Error while connecting to the API server.", webException);
                exceptionsList.Add(webException);
                return(false);
            }
            catch (ApiServerConnectionException e)
            {
                Logger.LogWarning("Error while connecting to the API server.", e);
                exceptionsList.Add(e);
                return(false);
            }
        }
Exemplo n.º 32
0
        public static bool Execute(string[] args)
        {
            try
            {
                bool                 useBufferedSockets = false, useFramed = false, useEncryption = false, compact = false, json = false;
                ServerType           serverType           = ServerType.TSimpleServer;
                ProcessorFactoryType processorFactoryType = ProcessorFactoryType.TSingletonProcessorFactory;
                int    port = 9090;
                string pipe = null;
                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] == "-pipe")  // -pipe name
                    {
                        pipe = args[++i];
                    }
                    else if (args[i].Contains("--port="))
                    {
                        port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1));
                    }
                    else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
                    {
                        useBufferedSockets = true;
                    }
                    else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
                    {
                        useFramed = true;
                    }
                    else if (args[i] == "--compact" || args[i] == "--protocol=compact")
                    {
                        compact = true;
                    }
                    else if (args[i] == "--json" || args[i] == "--protocol=json")
                    {
                        json = true;
                    }
                    else if (args[i] == "--threaded" || args[i] == "--server-type=threaded")
                    {
                        serverType = ServerType.TThreadedServer;
                    }
                    else if (args[i] == "--threadpool" || args[i] == "--server-type=threadpool")
                    {
                        serverType = ServerType.TThreadPoolServer;
                    }
                    else if (args[i] == "--prototype" || args[i] == "--processor=prototype")
                    {
                        processorFactoryType = ProcessorFactoryType.TPrototypeProcessorFactory;
                    }
                    else if (args[i] == "--ssl")
                    {
                        useEncryption = true;
                    }
                }

                // Transport
                TServerTransport trans;
                if (pipe != null)
                {
                    trans = new TNamedPipeServerTransport(pipe);
                }
                else
                {
                    if (useEncryption)
                    {
                        string certPath = "../keys/server.p12";
                        trans = new TTLSServerSocket(port, 0, useBufferedSockets, new X509Certificate2(certPath, "thrift"), null, null, SslProtocols.Tls);
                    }
                    else
                    {
                        trans = new TServerSocket(port, 0, useBufferedSockets);
                    }
                }

                TProtocolFactory proto;
                if (compact)
                {
                    proto = new TCompactProtocol.Factory();
                }
                else if (json)
                {
                    proto = new TJSONProtocol.Factory();
                }
                else
                {
                    proto = new TBinaryProtocol.Factory();
                }

                TProcessorFactory processorFactory;
                if (processorFactoryType == ProcessorFactoryType.TPrototypeProcessorFactory)
                {
                    processorFactory = new TPrototypeProcessorFactory <ThriftTest.Processor, TestHandler>();
                }
                else
                {
                    // Processor
                    TestHandler          testHandler   = new TestHandler();
                    ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler);
                    processorFactory = new TSingletonProcessorFactory(testProcessor);
                }

                TTransportFactory transFactory;
                if (useFramed)
                {
                    transFactory = new TFramedTransport.Factory();
                }
                else
                {
                    transFactory = new TTransportFactory();
                }

                TServer serverEngine;
                switch (serverType)
                {
                case ServerType.TThreadPoolServer:
                    serverEngine = new TThreadPoolServer(processorFactory, trans, transFactory, proto);
                    break;

                case ServerType.TThreadedServer:
                    serverEngine = new TThreadedServer(processorFactory, trans, transFactory, proto);
                    break;

                default:
                    serverEngine = new TSimpleServer(processorFactory, trans, transFactory, proto);
                    break;
                }

                //Server event handler
                TradeServerEventHandler serverEvents = new TradeServerEventHandler();
                serverEngine.setEventHandler(serverEvents);

                // Run it
                string where = (pipe != null ? "on pipe " + pipe : "on port " + port);
                Console.WriteLine("Starting the " + serverType.ToString() + " " + where +
                                  (processorFactoryType == ProcessorFactoryType.TPrototypeProcessorFactory ? " with processor prototype factory " : "") +
                                  (useBufferedSockets ? " with buffered socket" : "") +
                                  (useFramed ? " with framed transport" : "") +
                                  (useEncryption ? " with encryption" : "") +
                                  (compact ? " with compact protocol" : "") +
                                  (json ? " with json protocol" : "") +
                                  "...");
                serverEngine.Serve();
            }
            catch (Exception x)
            {
                Console.Error.Write(x);
                return(false);
            }
            Console.WriteLine("done.");
            return(true);
        }