public void TestAddIndexed() { RequestMap map = new RequestMap(); map.Add("map[].name", "name1"); map.Add("map[].name", "name2"); map.Add("map[].name", "name3"); Assert.AreEqual(1, map.Count); Assert.AreNotSame(1, ((List <Dictionary <String, Object> >)map["map"]).Count); //checl is it finds the key Assert.IsTrue(map.ContainsKey("map")); Assert.IsTrue(map.ContainsKey("map[0]")); Assert.IsTrue(map.ContainsKey("map[1]")); Assert.IsTrue(map.ContainsKey("map[2]")); Assert.IsFalse(map.ContainsKey("map[3]")); Assert.AreEqual("name1", map ["map[0].name"]); Assert.AreEqual("name2", map ["map[1].name"]); Assert.AreEqual("name3", map ["map[2].name"]); // check if the first level map contains only one value Assert.AreNotSame(1, ((Dictionary <String, Object>)map ["map[0]"]).Count); Assert.AreNotSame(1, ((Dictionary <String, Object>)map ["map[1]"]).Count); Assert.AreNotSame(1, ((Dictionary <String, Object>)map ["map[2]"]).Count); }
public void TesNestedAdd() { RequestMap map = new RequestMap(); map.Add("key1.key1", "value1"); Assert.AreEqual(1, map.Count); //checl is it finds the key Assert.IsTrue(map.ContainsKey("key1")); //check if it find the nested keys Assert.IsTrue(map.ContainsKey("key1.key1")); // check if it find returns the correct value Assert.AreEqual("value1", map ["key1.key1"]); // check if the first level map contains only one value Assert.AreNotSame(1, ((Dictionary <String, Object>)map["key1"]).Count); map.Add("key1.key2", "value2"); Assert.AreEqual(1, map.Count); //checl is it finds the key Assert.IsTrue(map.ContainsKey("key1")); //check if it find the nested keys Assert.IsTrue(map.ContainsKey("key1.key2")); // check if it find returns the correct value Assert.AreEqual("value2", map ["key1.key2"]); // check if the first level map contains only one value Assert.AreNotSame(2, ((Dictionary <String, Object>)map["key1"]).Count); }
public void TestAddWithConstructor() { RequestMap map = new RequestMap("key1", "value1"); Assert.AreEqual(1, map.Count); Assert.IsTrue(map.ContainsKey("key1")); Assert.AreEqual("value1", map ["key1"]); //test negative Assert.IsFalse(map.ContainsKey("key2")); }
public void TestJson() { String tmpDict = " { \"user.name\":\"andrea\", \"user.surname\":\"rizzini\" }"; RequestMap map = new RequestMap(tmpDict); Assert.AreEqual(1, map.Count); Assert.IsTrue(map.ContainsKey("user")); Assert.IsTrue(map.ContainsKey("user.name")); Assert.IsTrue(map.ContainsKey("user.surname")); Assert.AreEqual("andrea", map ["user.name"]); Assert.AreEqual("rizzini", map ["user.surname"]); }
public void TestNestedAdd() { RequestMap map = new RequestMap(); map.Add("key1.key2", "value1"); Assert.AreEqual(1, map.Count); Assert.IsTrue(map.ContainsKey("key1")); Assert.IsTrue(map.ContainsKey("key1.key2")); Assert.AreEqual("value1", map ["key1.key2"]); Assert.AreNotSame(1, ((Dictionary <String, Object>)map["key1"]).Count); //test negative Assert.IsFalse(map.ContainsKey("key2")); Assert.IsFalse(map.ContainsKey("key2.key1")); }
public static Object resolveResponseValue(String overrideValue) { //arizzini: if plain value, return it if (overrideValue.StartsWith("val:")) { return(overrideValue.Substring(4)); } else { int i = overrideValue.IndexOf("."); String name = overrideValue.Substring(0, i); String key = overrideValue.Substring(i + 1); if (responses.ContainsKey(name)) { RequestMap response = responses[name]; if (response.ContainsKey(key)) { return((Object)response.Get(key)); } else { log.Error("Key: " + key + " is not found in the response"); } } else { log.Error("Example: " + name + " is not found in the response"); } return(null); } }
public void TestRemve() { RequestMap map = new RequestMap(); map.Add("key1", "value1"); Assert.AreEqual(1, map.Count); Assert.IsTrue(map.ContainsKey("key1")); Assert.AreEqual("value1", map ["key1"]); //test negative Assert.IsFalse(map.ContainsKey("key2")); map.Remove("key1"); Assert.AreEqual(0, map.Count); Assert.IsFalse(map.ContainsKey("key1")); }
public void Test200WithMap() { RequestMap responseMap = new RequestMap(" { \"user.name\":\"andrea\", \"user.surname\":\"rizzini\" }"); ApiController controller = new ApiController("0.0.1"); controller.SetRestClient(mockClient(HttpStatusCode.OK, responseMap)); IDictionary <String, Object> result = controller.Execute(new OperationConfig("/test1", "create", new List <string>(), headerList), new OperationMetadata("0.0.1", null), new TestBaseObject(responseMap)); RequestMap responseMapFromResponse = new RequestMap(result); Assert.IsTrue(responseMapFromResponse.ContainsKey("user")); Assert.IsTrue(responseMapFromResponse.ContainsKey("user.name")); Assert.IsTrue(responseMapFromResponse.ContainsKey("user.surname")); Assert.AreEqual("andrea", responseMapFromResponse["user.name"]); Assert.AreEqual("rizzini", responseMapFromResponse["user.surname"]); }
public void Test200WithMap() { RequestMap responseMap = new RequestMap(" { \"user.name\":\"andrea\", \"user.surname\":\"rizzini\" }"); ApiController controller = new ApiController(); controller.SetRestClient(mockClient(HttpStatusCode.OK, responseMap)); IDictionary <String, Object> result = controller.execute("create", "test1", new TestBaseObject(responseMap)); RequestMap responseMapFromResponse = new RequestMap(result); Assert.IsTrue(responseMapFromResponse.ContainsKey("user")); Assert.IsTrue(responseMapFromResponse.ContainsKey("user.name")); Assert.IsTrue(responseMapFromResponse.ContainsKey("user.surname")); Assert.AreEqual("andrea", responseMapFromResponse["user.name"]); Assert.AreEqual("rizzini", responseMapFromResponse["user.surname"]); }
public void TestAddAllAsConstructor() { Dictionary <String, Object> tmpDict = new Dictionary <String, Object> (); tmpDict.Add("user.name", "andrea"); tmpDict.Add("user.surname", "rizzini"); RequestMap map = new RequestMap(tmpDict); Assert.AreEqual(1, map.Count); Assert.IsTrue(map.ContainsKey("user")); Assert.IsTrue(map.ContainsKey("user.name")); Assert.IsTrue(map.ContainsKey("user.surname")); Assert.AreEqual("andrea", map ["user.name"]); Assert.AreEqual("rizzini", map ["user.surname"]); }
public void TestAdd4List() { RequestMap map = new RequestMap(); map.Add("key1", new List <String>() { "value1", "value2", "value3" }); Assert.IsTrue(map.ContainsKey("key1")); Assert.AreEqual(3, ((List <String>)map ["key1"]).Count); }
public void TestConstructorDictionary() { Dictionary <String, Object> testDictionary = new Dictionary <string, object> (); testDictionary.Add("boolean", true); testDictionary.Add("double", 0.5); testDictionary.Add("long", 1000); testDictionary.Add("int", 16); testDictionary.Add("list", new List <String>() { "one", "one", "one" }); testDictionary.Add("map", new Dictionary <String, String>() { { "0", "one" }, { "1", "one" }, { "2", "one" } }); RequestMap map = new RequestMap(testDictionary); Assert.AreEqual(6, map.Count); Assert.IsTrue(map.ContainsKey("boolean")); Assert.IsTrue(map.ContainsKey("double")); Assert.IsTrue(map.ContainsKey("long")); Assert.IsTrue(map.ContainsKey("int")); Assert.IsTrue(map.ContainsKey("list")); Assert.IsTrue(map.ContainsKey("map")); Assert.AreEqual(true, map ["boolean"]); Assert.AreEqual(0.5, map ["double"]); Assert.AreEqual(1000, map ["long"]); Assert.AreEqual(16, map ["int"]); Assert.AreEqual(3, ((List <String>)map ["list"]).Count); Assert.AreEqual(3, ((Dictionary <String, Object>)map ["map"]).Count); }
public void Test200WithList() { RequestMap responseMap = new RequestMap("[ { \"name\":\"andrea\", \"surname\":\"rizzini\" } ]"); ApiController controller = new ApiController(); controller.SetRestClient(mockClient(HttpStatusCode.OK, responseMap)); IDictionary <String, Object> result = controller.execute("create", "test1", new TestBaseObject()); RequestMap responseMapFromResponse = new RequestMap(result); Assert.IsTrue(responseMapFromResponse.ContainsKey("list")); Assert.AreEqual(typeof(List <Dictionary <String, Object> >), responseMapFromResponse ["list"].GetType()); Assert.AreEqual("andrea", responseMapFromResponse["list[0].name"]); Assert.AreEqual("rizzini", responseMapFromResponse["list[0].surname"]); }
private static async Task Client_OnReactionAdded(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction) { var message = await cache.GetOrDownloadAsync(); if (!reaction.User.Value.IsBot && RequestMap.ContainsKey(message.Id)) { SongData songData = RequestMap[message.Id]; if (reaction.Emote.Name == "👍") { BotTools.LogLine($"{songData.Requestor}'s request was approved by {reaction.User.Value.Username}"); await DJVettingChannelWebhook.SendMessageAsync($"*{songData.Requestor}'s request was approved by {reaction.User.Value.Username}*"); RequestMap.Remove(message.Id); try { Music.GetPlaylist("request").AddSong(songData); var placement = Music.GetPlaylist("request").Songs.Count; var placementWord = BotTools.GetPlacementWord(placement); TwitchBot.SendMessage($"@{songData.Requestor}, Your request is {placementWord} in the queue! razCool"); Music.QueuedSong = Music.DownloadedSong = null; Music.SavePlaylists(); await message.RemoveAllReactionsAsync(); } catch (ArgumentException) { BotTools.LogLine($"{songData.Requestor}'s request rejected: Already in queue"); TwitchBot.SendMessage($"Sorry @{songData.Requestor}, that request is already queued!"); } catch (FormatException) { BotTools.LogLine($"{songData.Requestor}'s request rejected: Bad url"); TwitchBot.SendMessage($"Sorry @{songData.Requestor}, I can't access any video with that url!"); } } else if (reaction.Emote.Name == "👎") { BotTools.LogLine($"{RequestMap[message.Id].Requestor}'s request was declined by {reaction.User.Value.Username}"); await DJVettingChannelWebhook.SendMessageAsync($"*{RequestMap[message.Id].Requestor}'s request was declined by {reaction.User.Value.Username}*"); TwitchBot.SendMessage($"@{songData.Requestor}, Your request was declined! razHands"); RequestMap.Remove(message.Id); await message.RemoveAllReactionsAsync(); } } }
private static async Task Client_OnMessageReceived(SocketMessage message) { var user = message.Author as SocketGuildUser; var requiredRole = (user as IGuildUser).Guild.Roles.FirstOrDefault(x => x.Name == "~Moderator~"); if (user.Roles.Contains(requiredRole)) { var messageSend = new TwitchMessage(message.Author.Username, message.Content); if (messageSend.BotResponse != null && messageSend.BotResponse.Length > 0) { if (!BotTools.Settings["debug_output"]) { await message.Channel.SendMessageAsync(String.Join("\n", messageSend.BotResponse)); } else { BotTools.LogLine("[D] RazBot: " + String.Join("\n", messageSend.BotResponse)); } } else if (messageSend.WitResponse != null && messageSend.WitResponse.Length > 0) { if (!BotTools.Settings["debug_output"]) { await message.Channel.SendMessageAsync(String.Join("\n", messageSend.WitResponse)); } else { BotTools.LogLine("[D] RazBot: " + String.Join("\n", messageSend.WitResponse)); } } } while (RequestPosting) { ; } if (RequestMap.ContainsKey(message.Id)) { foreach (var emoji in new[] { "👍", "👎" }) // "✅" "▶️" // "👍" "👎" // "⛔" "⏏️" { await message.AddReactionAsync(new Emoji(emoji)); } } }
public void Test200WithList() { RequestMap responseMap = new RequestMap("[ { \"name\":\"andrea\", \"surname\":\"rizzini\" } ]"); TestApiController controller = new TestApiController(); controller.SetRestClient(mockClient(HttpStatusCode.OK, responseMap)); var config = new OperationConfig("/test1", "create", headerList, queryList); var metadata = new OperationMetadata("0.0.1", "http://locahost:8081"); //new Tuple<string, string, List<string>, List<string>>("/test1", null, headerList, queryList); IDictionary <String, Object> result = controller.Execute(config, metadata, new TestBaseObject()); RequestMap responseMapFromResponse = new RequestMap(result); Assert.IsTrue(responseMapFromResponse.ContainsKey("list")); Assert.AreEqual(typeof(List <Dictionary <String, Object> >), responseMapFromResponse ["list"].GetType()); Assert.AreEqual("andrea", responseMapFromResponse["list[0].name"]); Assert.AreEqual("rizzini", responseMapFromResponse["list[0].surname"]); }
public static void DownLoad(object param) { ThreadParam tParam = param as ThreadParam; ManualResetEvent close = tParam.close; AutoResetEvent Wait = tParam.waitfor; try { while (bContinue) { Wait.WaitOne(); HttpRequest req = null; string strURI = null; while (bContinue) { req = null; strURI = null; lock (RequestMap) { if (RequestMap.Count == 0) { break; } bool bFindOrder = false; foreach (KeyValuePair <string, HttpRequest> each in RequestMap) { if (req == null) { req = each.Value; } if (strURI == null) { strURI = each.Key; } if (each.Value != null) { if (each.Value.order != RequestStatus.Pause) { req = each.Value; strURI = each.Key; bFindOrder = true; break; } else { continue; } } } if (strURI != null) { //may be is retry lock (DownloadMap) { if (!DownloadMap.ContainsKey(strURI)) { DownloadMap.Add(strURI, req); } } RequestMap.Remove(strURI); } } Socket sClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); //http1.1 download start string strHost = ""; string strPort = ""; string strRelativePath = ""; if (!ParseURI(strURI, ref strHost, ref strPort, ref strRelativePath)) { req.error = "404"; req.callback(ref req); break; } else { EndPoint server = new IPEndPoint(IPAddress.Parse(strHost), System.Convert.ToInt32(strPort)); try { connectDone.Reset(); sClient.BeginConnect(server, new AsyncCallback(ConnectCallback), sClient); connectDone.WaitOne(2000, false); if (!sClient.Connected) { Log.LogInfo("connect time out"); //repush to download again lock (RequestMap) { if (!RequestMap.ContainsKey(strURI)) { req.error = null; req.order = 0; RequestMap.Add(strURI, req); } } continue; } } catch { req.error = "connect failed"; req.callback(ref req); //repush to download again lock (RequestMap) { if (!RequestMap.ContainsKey(strURI)) { req.error = null; req.order = 0; RequestMap.Add(strURI, req); } } continue; } if (!sClient.Connected) { req.error = "connect failed"; req.callback(ref req); //repush to download again lock (RequestMap) { if (!RequestMap.ContainsKey(strURI)) { req.error = null; req.order = 0; RequestMap.Add(strURI, req); } } continue; } string strSend = string.Format(strHttpVer, strRelativePath, strHost, strPort, req.cbstart); Log.LogInfo("send packet:" + strSend); byte[] bySend = System.Text.Encoding.UTF8.GetBytes(string.Format(strHttpVer, strRelativePath, strHost, strPort, req.cbstart)); sClient.Send(bySend); int nByteRecved = 0; int nNewLine = 0; //recv http head MemoryStream ms = new MemoryStream(); byte[] byteRecved = new byte[1]; while (true) { if (!bContinue) { break; } try { nByteRecved = sClient.Receive(byteRecved, 1, 0); } catch (Exception exp) { break; } if (nByteRecved <= 0) { break; } ms.Write(byteRecved, 0, 1); if (byteRecved[0] == '\n') { nNewLine++; if (System.Text.Encoding.UTF8.GetString(ms.GetBuffer()).Contains("\r\n\r\n")) { break; } } } if (!sClient.Connected || !bContinue) { req.error = "recv interrupt"; req.callback(ref req); lock (RequestMap) { if (!RequestMap.ContainsKey(strURI)) { req.error = null; req.order = 0; RequestMap.Add(strURI, req); } } continue; } nByteRecved = 0; string strHead = System.Text.Encoding.UTF8.GetString(ms.GetBuffer()); Log.LogInfo("http recv:" + strHead); string strHeadLower = strHead.ToLower(); //check http1.1 return code int nReturnCode = 0; long nContentLength = 0; int nRangeStart = 0; int nRangeStop = 0; string[] strResponse = new string[nNewLine]; char[] split = { '\n' }; strResponse = strHeadLower.Split(split); for (int i = 0; i < strResponse.Length; ++i) { if (strResponse[i].Contains("http/")) { string strStatus = strResponse[i]; nReturnCode = System.Convert.ToInt32(strStatus.Substring(9, 3)); Log.LogInfo("http result:" + nReturnCode.ToString()); } else if (strResponse[i].Contains("content-length:")) { string strLength = strResponse[i]; string[] strSplit = strLength.Split(new char[] { ' ' }, 2); nContentLength = System.Convert.ToInt64(strSplit[1]); if (req.cbstart == 0) { req.cbsize = nContentLength; req.callback(ref req); } } else if (strResponse[i].Contains("tranfer-encoding:chunked")) { Log.LogInfo("error !!! can not read chunked data"); } if (nReturnCode != 0 && nContentLength != 0) { break; } } ms.Close(); ms = null; if (nReturnCode != 206 && nReturnCode != 200) { req.error = nReturnCode.ToString(); req.callback(ref req); lock (RequestMap) { if (!RequestMap.ContainsKey(strURI)) { req.error = null; req.order = 0; RequestMap.Add(strURI, req); } } sClient.Close(); continue; } FileStream fs = File.Open(req.strLocalPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); if (req.cbstart != 0) { fs.Seek(req.cbstart, SeekOrigin.Begin); } //calc kbps //total recved / total time => kbps long nTotalRecved = req.cbstart; int nLoop = 0; byte[] memory = new byte[10 * 1024]; while (true) { long nTickBegin = DateTime.Now.Ticks; if (!bContinue) { break; } try { nByteRecved = sClient.Receive(memory, 10 * 1024, SocketFlags.None); } catch (Exception exp) { break; } if (nByteRecved <= 0) { break; } nLoop++; //Loader.LogErr("recv bytes:" + nByteRecved.ToString()); fs.Write(memory, 0, nByteRecved); fs.Flush(); nTotalRecved += nByteRecved; req.cboffset = nTotalRecved; req.loadBytes += nByteRecved; if (nTotalRecved == nContentLength) { break; } if (nLoop >= 10) { req.callback(ref req); nLoop = 0; } } sClient.Close(); //Loader.LogErr("file transfer result:" + nByteRecved.ToString()); req.cboffset = fs.Seek(0, SeekOrigin.Current); fs.Flush(); fs.Close(); req.callback(ref req); req.bDone = true; } } } if (close != null) { Log.LogInfo("thread quit signal open"); close.Set(); close = null; } } catch (Exception exp) { Debug.LogError(exp.Message + "|" + exp.StackTrace + " download thread crashed"); } finally { if (close != null) { close.Set(); close = null; } } }