using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Net; using System.Net.Sockets; using System.IO; using Microsoft.Extensions.Configuration; using ApiProcess.Models; using ApiProcess.Models.bet; using System.Collections; using Newtonsoft.Json; using System.Net.Http; using System.Data; using System.Text; using ResfullApi.Models.bet; namespace ResfullApi.Models { public class Common { static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(Common)); public static string GetErrMsgByCode(string code,string service,string channel,string language) { string result = ""; try { DataSet ds=DataAccess.GET_ERR_MSG_BY_CODE(code,service,channel,language); if (ds != null & ds.Tables[0].Rows.Count > 0) { result = ds.Tables[0].Rows[0]["mesage"].ToString(); } } catch (Exception ex) { } return result; } public static string SocketUnSyn(string msg, string host, int port, int timeout) { //log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //log4net.Config.XmlConfigurator.Configure(); string result = "-1000"; TcpClient client = null; NetworkStream stream = null; try { byte[] data = System.Text.Encoding.ASCII.GetBytes(msg); client = new TcpClient(host, port); client.SendTimeout = timeout; stream = client.GetStream(); BinaryWriter writer = new BinaryWriter(stream); writer.Write(data); String _readFromStream = String.Empty; byte[] data_read = new byte[1024]; using (MemoryStream ms = new MemoryStream()) { int numBytesRead; while ((numBytesRead = stream.Read(data_read, 0, data_read.Length)) > 0) { ms.Write(data_read, 0, numBytesRead); } _readFromStream = System.Text.Encoding.ASCII.GetString(ms.ToArray(), 0, (int)ms.Length); } //string _readFromStream = GetResponse(stream); /* data = new Byte[1024]; String responseData = String.Empty; Int32 bytes = stream.Read(data, 0, data.Length); responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); */ logger.Info("Response from:" + host + ":" + port + " is:" + _readFromStream); // Close everything. stream.Close(); client.Close(); //Phan tich data tra ve: result = _readFromStream; } catch (ArgumentNullException e) { logger.Info("ArgumentNullException and close connection:" + e.ToString()); stream.Close(); client.Close(); return "-1000"; } catch (SocketException e) { return "-1000"; } return result; } public static string GetResponse(NetworkStream stream) { byte[] data = new byte[1024]; using (MemoryStream memoryStream = new MemoryStream()) { do { stream.Read(data, 0, data.Length); memoryStream.Write(data, 0, data.Length); } while (stream.DataAvailable); return System.Text.Encoding.ASCII.GetString(memoryStream.ToArray(), 0, (int)memoryStream.Length); } } public static string checkToken(string ip,string channel,string token, out string msisdn,out string message) { string result = "1"; //check token ko thanh cong msisdn = ""; message = ""; try { DataSet ds_check = usersDataAccess.TKcheckToken(ip, channel, token); if (ds_check != null & ds_check.Tables[0].Rows.Count > 0) { msisdn = ds_check.Tables[0].Rows[0]["msisdn"].ToString(); result = ds_check.Tables[0].Rows[0]["status"].ToString(); message = ds_check.Tables[0].Rows[0]["mesage"].ToString(); } } catch (Exception ex) { int a = 1; } return result; } public static betProcessObj GetBetProcess(int id_process, string svId, ArrayList inputArrProcess, out ArrayList outputArrProcess) { betProcessObj result = null; outputArrProcess = inputArrProcess; ArrayList _temp = null; string ischeckMemoryCache = GetValuesAppSetting("webConfig", "ischeckMemoryCache"); if (inputArrProcess == null || ischeckMemoryCache == "1") _temp = getArrProcessActive(svId); else _temp = inputArrProcess; if (_temp.Count == 0) return null; int id = 0; if (id_process < 0 || id_process >= _temp.Count - 1) id = 0; else id = id_process + 1; result = (betProcessObj)_temp[id]; result.seq = id.ToString(); outputArrProcess = _temp; return result; } public static string GetErrMessageFromErrCode(string errCode, string language, string url, string _keyPost,string channel) { Random _rd = new Random(); string strRandom = _rd.Next(1, 999999).ToString("000000"); string request_process = strRandom + DateTime.Now.ToString("ddMMyyyyhhmmssfff"); string jsomPost = "{\"requestId\":\"#?rqeustID#\",\"serviceId\":\"10\",\"key\":\"#?key# \",\"cmd\":\"getErrCodeToMessage\",\"language\":\"#?language#\",\"channel\":\"#?channel#\",\"data\":\"#?errCode#\"}"; jsomPost = jsomPost.Replace("#?rqeustID#", request_process); jsomPost = jsomPost.Replace("#?key#", _keyPost); jsomPost = jsomPost.Replace("#?language#", language); jsomPost = jsomPost.Replace("#?errCode#", errCode); jsomPost = jsomPost.Replace("#?channel#", channel); string strResponse = Common.SendPost(url, jsomPost); ResCommnon response = JsonConvert.DeserializeObject(strResponse); return response.responseMessage; } public static String SendPost(string url, string str) { var data = new StringContent(str, Encoding.UTF8, "application/json"); //StringBuilder sb = new StringBuilder(); //sb.Append("Request: " + data); using (var client = new HttpClient()) { var response = client.PostAsync(url, data).Result; if (response.IsSuccessStatusCode) { var responseContent = response.Content; //sb.Append("\r\nResponse: " + responseContent); //log.Debug(sb.ToString()); // by calling .Result you are synchronously reading the result string responseString = responseContent.ReadAsStringAsync().Result; return responseString; } //sb.Append("\r\nResponse: " + response); //log.Debug(sb.ToString()); return response.StatusCode.ToString(); } } public static ArrayList getArrProcessActive(string svId) { ArrayList _arrListProcess = null; string keyOfBetType = ""; if (svId == "1") keyOfBetType = "betProcessListPower"; else if (svId == "2") keyOfBetType = "betProcessListDay"; else if (svId == "3") keyOfBetType = "betProcessListPlus"; string strBetList = GetValuesAppSetting("webConfig", keyOfBetType); string[] arrList = strBetList.Split('$'); if (arrList.Length == 0) return null; List listProcess = new List(); _arrListProcess = new ArrayList(); int j = 0; for (int i = 0; i < arrList.Length; i++) { string iteam = arrList[i]; string[] arrItem = iteam.Split(':'); betProcessObj temp = new betProcessObj(); temp.ip = (string)arrItem[0]; temp.port = (string)arrItem[1]; temp.timeout = (string)arrItem[2]; //if(CheckPort(temp.ip, temp.port)) if (CheckPortV2(temp.ip, temp.port)) { temp.seq = j.ToString(); _arrListProcess.Add(temp); j++; } } return _arrListProcess; } public static bool CheckPortV2(string ip, string port) { bool result = false; try { TcpClient c = new TcpClient(ip,Convert.ToInt32(port)); result = true; c.Close(); } catch (System.Net.Sockets.SocketException ex) { } return result; } public static bool CheckPort(string ip,string port) { bool result = false; string hostname = ip; int portno =Convert.ToInt32(port); IPAddress ipa = (IPAddress)Dns.GetHostAddresses(hostname)[0]; try { System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); sock.Connect(ipa, portno); if (sock.Connected == true) // Port is in use and connection is successful result = true; sock.Close(); } catch (System.Net.Sockets.SocketException ex) { } return result; } public static string GetValuesAppSetting(string key, string subkey) { IConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json")); var root = builder.Build(); var sampleConnectionString = root.GetSection(key)[subkey]; return sampleConnectionString; } } }