Common.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.IO;
  8. using Microsoft.Extensions.Configuration;
  9. using ApiProcess.Models;
  10. using ApiProcess.Models.bet;
  11. using System.Collections;
  12. using Newtonsoft.Json;
  13. using System.Net.Http;
  14. using System.Data;
  15. using System.Text;
  16. using ResfullApi.Models.bet;
  17. namespace ResfullApi.Models
  18. {
  19. public class Common
  20. {
  21. static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(Common));
  22. public static string GetErrMsgByCode(string code,string service,string channel,string language)
  23. {
  24. string result = "";
  25. try
  26. {
  27. DataSet ds=DataAccess.GET_ERR_MSG_BY_CODE(code,service,channel,language);
  28. if (ds != null & ds.Tables[0].Rows.Count > 0)
  29. {
  30. result = ds.Tables[0].Rows[0]["mesage"].ToString();
  31. }
  32. }
  33. catch (Exception ex)
  34. {
  35. }
  36. return result;
  37. }
  38. public static string SocketUnSyn(string msg, string host, int port, int timeout)
  39. {
  40. //log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  41. //log4net.Config.XmlConfigurator.Configure();
  42. string result = "-1000";
  43. TcpClient client = null;
  44. NetworkStream stream = null;
  45. try
  46. {
  47. byte[] data = System.Text.Encoding.ASCII.GetBytes(msg);
  48. client = new TcpClient(host, port);
  49. client.SendTimeout = timeout;
  50. stream = client.GetStream();
  51. BinaryWriter writer = new BinaryWriter(stream);
  52. writer.Write(data);
  53. String _readFromStream = String.Empty;
  54. byte[] data_read = new byte[1024];
  55. using (MemoryStream ms = new MemoryStream())
  56. {
  57. int numBytesRead;
  58. while ((numBytesRead = stream.Read(data_read, 0, data_read.Length)) > 0)
  59. {
  60. ms.Write(data_read, 0, numBytesRead);
  61. }
  62. _readFromStream = System.Text.Encoding.ASCII.GetString(ms.ToArray(), 0, (int)ms.Length);
  63. }
  64. //string _readFromStream = GetResponse(stream);
  65. /*
  66. data = new Byte[1024];
  67. String responseData = String.Empty;
  68. Int32 bytes = stream.Read(data, 0, data.Length);
  69. responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
  70. */
  71. logger.Info("Response from:" + host + ":" + port + " is:" + _readFromStream);
  72. // Close everything.
  73. stream.Close();
  74. client.Close();
  75. //Phan tich data tra ve:
  76. result = _readFromStream;
  77. }
  78. catch (ArgumentNullException e)
  79. {
  80. logger.Info("ArgumentNullException and close connection:" + e.ToString());
  81. stream.Close();
  82. client.Close();
  83. return "-1000";
  84. }
  85. catch (SocketException e)
  86. {
  87. return "-1000";
  88. }
  89. return result;
  90. }
  91. public static string GetResponse(NetworkStream stream)
  92. {
  93. byte[] data = new byte[1024];
  94. using (MemoryStream memoryStream = new MemoryStream())
  95. {
  96. do
  97. {
  98. stream.Read(data, 0, data.Length);
  99. memoryStream.Write(data, 0, data.Length);
  100. } while (stream.DataAvailable);
  101. return System.Text.Encoding.ASCII.GetString(memoryStream.ToArray(), 0, (int)memoryStream.Length);
  102. }
  103. }
  104. public static string checkToken(string ip,string channel,string token, out string msisdn,out string message)
  105. {
  106. string result = "1"; //check token ko thanh cong
  107. msisdn = "";
  108. message = "";
  109. try
  110. {
  111. DataSet ds_check = usersDataAccess.TKcheckToken(ip, channel, token);
  112. if (ds_check != null & ds_check.Tables[0].Rows.Count > 0)
  113. {
  114. msisdn = ds_check.Tables[0].Rows[0]["msisdn"].ToString();
  115. result = ds_check.Tables[0].Rows[0]["status"].ToString();
  116. message = ds_check.Tables[0].Rows[0]["mesage"].ToString();
  117. }
  118. }
  119. catch (Exception ex)
  120. {
  121. int a = 1;
  122. }
  123. return result;
  124. }
  125. public static betProcessObj GetBetProcess(int id_process, string svId, ArrayList inputArrProcess, out ArrayList outputArrProcess)
  126. {
  127. betProcessObj result = null;
  128. outputArrProcess = inputArrProcess;
  129. ArrayList _temp = null;
  130. string ischeckMemoryCache = GetValuesAppSetting("webConfig", "ischeckMemoryCache");
  131. if (inputArrProcess == null || ischeckMemoryCache == "1")
  132. _temp = getArrProcessActive(svId);
  133. else
  134. _temp = inputArrProcess;
  135. if (_temp.Count == 0)
  136. return null;
  137. int id = 0;
  138. if (id_process < 0 || id_process >= _temp.Count - 1)
  139. id = 0;
  140. else
  141. id = id_process + 1;
  142. result = (betProcessObj)_temp[id];
  143. result.seq = id.ToString();
  144. outputArrProcess = _temp;
  145. return result;
  146. }
  147. public static string GetErrMessageFromErrCode(string errCode, string language, string url, string _keyPost,string channel)
  148. {
  149. Random _rd = new Random();
  150. string strRandom = _rd.Next(1, 999999).ToString("000000");
  151. string request_process = strRandom + DateTime.Now.ToString("ddMMyyyyhhmmssfff");
  152. string jsomPost = "{\"requestId\":\"#?rqeustID#\",\"serviceId\":\"10\",\"key\":\"#?key# \",\"cmd\":\"getErrCodeToMessage\",\"language\":\"#?language#\",\"channel\":\"#?channel#\",\"data\":\"#?errCode#\"}";
  153. jsomPost = jsomPost.Replace("#?rqeustID#", request_process);
  154. jsomPost = jsomPost.Replace("#?key#", _keyPost);
  155. jsomPost = jsomPost.Replace("#?language#", language);
  156. jsomPost = jsomPost.Replace("#?errCode#", errCode);
  157. jsomPost = jsomPost.Replace("#?channel#", channel);
  158. string strResponse = Common.SendPost(url, jsomPost);
  159. ResCommnon response = JsonConvert.DeserializeObject<ResCommnon>(strResponse);
  160. return response.responseMessage;
  161. }
  162. public static String SendPost(string url, string str)
  163. {
  164. var data = new StringContent(str, Encoding.UTF8, "application/json");
  165. //StringBuilder sb = new StringBuilder();
  166. //sb.Append("Request: " + data);
  167. using (var client = new HttpClient())
  168. {
  169. var response = client.PostAsync(url, data).Result;
  170. if (response.IsSuccessStatusCode)
  171. {
  172. var responseContent = response.Content;
  173. //sb.Append("\r\nResponse: " + responseContent);
  174. //log.Debug(sb.ToString());
  175. // by calling .Result you are synchronously reading the result
  176. string responseString = responseContent.ReadAsStringAsync().Result;
  177. return responseString;
  178. }
  179. //sb.Append("\r\nResponse: " + response);
  180. //log.Debug(sb.ToString());
  181. return response.StatusCode.ToString();
  182. }
  183. }
  184. public static ArrayList getArrProcessActive(string svId)
  185. {
  186. ArrayList _arrListProcess = null;
  187. string keyOfBetType = "";
  188. if (svId == "1")
  189. keyOfBetType = "betProcessListPower";
  190. else if (svId == "2")
  191. keyOfBetType = "betProcessListDay";
  192. else if (svId == "3")
  193. keyOfBetType = "betProcessListPlus";
  194. string strBetList = GetValuesAppSetting("webConfig", keyOfBetType);
  195. string[] arrList = strBetList.Split('$');
  196. if (arrList.Length == 0)
  197. return null;
  198. List<betProcessObj> listProcess = new List<betProcessObj>();
  199. _arrListProcess = new ArrayList();
  200. int j = 0;
  201. for (int i = 0; i < arrList.Length; i++)
  202. {
  203. string iteam = arrList[i];
  204. string[] arrItem = iteam.Split(':');
  205. betProcessObj temp = new betProcessObj();
  206. temp.ip = (string)arrItem[0];
  207. temp.port = (string)arrItem[1];
  208. temp.timeout = (string)arrItem[2];
  209. //if(CheckPort(temp.ip, temp.port))
  210. if (CheckPortV2(temp.ip, temp.port))
  211. {
  212. temp.seq = j.ToString();
  213. _arrListProcess.Add(temp);
  214. j++;
  215. }
  216. }
  217. return _arrListProcess;
  218. }
  219. public static bool CheckPortV2(string ip, string port)
  220. {
  221. bool result = false;
  222. try
  223. {
  224. TcpClient c = new TcpClient(ip,Convert.ToInt32(port));
  225. result = true;
  226. c.Close();
  227. }
  228. catch (System.Net.Sockets.SocketException ex)
  229. {
  230. }
  231. return result;
  232. }
  233. public static bool CheckPort(string ip,string port)
  234. {
  235. bool result = false;
  236. string hostname = ip;
  237. int portno =Convert.ToInt32(port);
  238. IPAddress ipa = (IPAddress)Dns.GetHostAddresses(hostname)[0];
  239. try
  240. {
  241. System.Net.Sockets.Socket sock =
  242. new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
  243. System.Net.Sockets.SocketType.Stream,
  244. System.Net.Sockets.ProtocolType.Tcp);
  245. sock.Connect(ipa, portno);
  246. if (sock.Connected == true) // Port is in use and connection is successful
  247. result = true;
  248. sock.Close();
  249. }
  250. catch (System.Net.Sockets.SocketException ex)
  251. {
  252. }
  253. return result;
  254. }
  255. public static string GetValuesAppSetting(string key, string subkey)
  256. {
  257. IConfigurationBuilder builder = new ConfigurationBuilder();
  258. builder.AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"));
  259. var root = builder.Build();
  260. var sampleConnectionString = root.GetSection(key)[subkey];
  261. return sampleConnectionString;
  262. }
  263. }
  264. }