static IEnumerable <Post> GetPosts(string username, string password, string[] postIds) { string url = string.Format("http://www.cppblog.com/{0}/services/metaweblog.aspx", username); ICppblog cppblog = XmlRpcClient.Create <ICppblog>(url); int count = 0; foreach (var id in postIds) { Post post = null; try { post = cppblog.GetPost(id, username, password); Console.WriteLine("{0}/{1}", ++count, postIds.Length); } catch (Exception ex) { Console.WriteLine("Post {0}: {1}", id, ex.Message); } if (post != null) { yield return(post); } } }
private async Task <bool> NegotiateConnection(string xmlRpcUri) { int protos = 0; XmlRpcValue tcprosArray = new XmlRpcValue(), protosArray = new XmlRpcValue(), Params = new XmlRpcValue(); tcprosArray.Set(0, "TCPROS"); protosArray.Set(protos++, tcprosArray); Params.Set(0, ThisNode.Name); Params.Set(1, Name); Params.Set(2, protosArray); if (!Network.SplitUri(xmlRpcUri, out string peerHost, out int peerPort)) { logger.LogError($"Bad XML-RPC URI: [{xmlRpcUri}]"); return(false); } var client = new XmlRpcClient(peerHost, peerPort); var requestTopicTask = client.ExecuteAsync("requestTopic", Params); logger.LogDebug($"Began asynchronous XML RPC connection to http://{peerHost}:{peerPort}/ for topic [{Name}]"); var conn = new PendingConnection(client, requestTopicTask, xmlRpcUri); lock (pendingConnections) { pendingConnections.Add(conn); } await requestTopicTask.WhenCompleted().ConfigureAwait(false); PendingConnectionDone(conn, requestTopicTask); return(requestTopicTask.HasCompletedSuccessfully()); }
public NodeService(string name, Uri endPoint, ApiTypes api, ServiceTypes serviceType) : base(name) { // Default account icon PathIcon = "M12,19.2C9.5,19.2 7.29,17.92 6,16C6.03,14 10,12.9 12,12.9C14,12.9 17.97,14 18,16C16.71,17.92 14.5,19.2 12,19.2M12,5A3,3 0 0,1 15,8A3,3 0 0,1 12,11A3,3 0 0,1 9,8A3,3 0 0,1 12,5M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12C22,6.47 17.5,2 12,2Z"; EndPoint = endPoint; Api = api; ServiceType = serviceType; //Id = Guid.NewGuid().ToString(); Id = endPoint.AbsoluteUri; switch (api) { case ApiTypes.atAtomPub: Client = new AtomPubClient(UserName, UserPassword, EndPoint); break; case ApiTypes.atXMLRPC_MovableType: Client = new XmlRpcClient(UserName, UserPassword, EndPoint); break; case ApiTypes.atXMLRPC_WordPress: Client = new XmlRpcClient(UserName, UserPassword, EndPoint); break; case ApiTypes.atFeed: Client = new FeedClient(); break; //TODO: WP, AtomAPI } }
public XmlRpcWebShop(string urlDomainCtor, string classNameCtor) { this.urlDomain = urlDomainCtor; this.className = classNameCtor; this.clientXmlRpc = new XmlRpcClient(); clientXmlRpc.Url = this.urlDomain; }
//public XmlRpcValue stickaroundyouwench = null; public PendingConnection(XmlRpcClient client, Subscription s, string uri, XmlRpcValue chk) { this.client = client; this.chk = chk; parent = s; RemoteUri = uri; }
public NodeService(string name, string username, string password, Uri endPoint, ApiTypes api) : base(name) { UserName = username; UserPassword = password; EndPoint = endPoint; // Default account icon PathIcon = "M12,19.2C9.5,19.2 7.29,17.92 6,16C6.03,14 10,12.9 12,12.9C14,12.9 17.97,14 18,16C16.71,17.92 14.5,19.2 12,19.2M12,5A3,3 0 0,1 15,8A3,3 0 0,1 12,11A3,3 0 0,1 9,8A3,3 0 0,1 12,5M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12C22,6.47 17.5,2 12,2Z"; switch (api) { case ApiTypes.atAtomPub: Client = new AtomPubClient(UserName, UserPassword, EndPoint); break; case ApiTypes.atXMLRPC: Client = new XmlRpcClient(UserName, UserPassword, EndPoint); break; case ApiTypes.atAtomFeed: Client = new AtomFeedClient(EndPoint); break; //TODO: AtomAPI } Api = api; ID = Guid.NewGuid().ToString(); }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Methodes GBX //////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// #region "GBX Methods" void connectXmlRpc() { int cpt = 0; while (cpt < TRY_AUTH_NB && !Lama.connected && Lama.launched) { cpt++; try { this.client = new XmlRpcClient(this.adrs, this.port); GbxCall authAnsw = this.client.Request(Authenticate, this.login, this.passwd); if (authAnsw.Params[0].Equals(true)) //Auth success--------------------------------- { this.client.EnableCallbacks(true); this.client.EventGbxCallback += new GbxCallbackHandler(gbxCallBack); this.client.EventOnDisconnectCallback += new OnDisconnectHandler(gbxDisconnect); Lama.connected = true; //exit loop } } catch (Exception) { System.Threading.Thread.Sleep(WAIT_AUTH_TIME); } } }
public static void TestReadVersion() { XmlRpcClient client = new XmlRpcClient(); client.Url = Url; client.Path = "common"; XmlRpcResponse response = client.Execute("version"); Console.WriteLine("version"); Console.WriteLine("REQUEST: "); client.WriteRequest(Console.Out); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("RESPONSE: "); client.WriteResponse(Console.Out); Console.WriteLine(); Console.WriteLine(); if (response.IsFault()) { Console.WriteLine(response.GetFaultString()); } else { Console.WriteLine(response.GetString()); } }
public static void TestRequestXml() { XmlRpcRequest request = new XmlRpcRequest("version"); request.AddParam(false); request.AddParam(3); request.AddParam(4.9); request.AddParam(DateTime.Now); request.AddParam(DateTime.UtcNow); request.AddParam(Encoding.UTF8.GetBytes("hello")); Dictionary <string, object> dictest = new Dictionary <string, object>(); dictest.Add("hello", "hello"); // request.AddParam(dictest); List <object> listtest = new List <object>(); listtest.Add(3); listtest.Add("hello"); listtest.Add(dictest); request.AddParam(listtest); XmlDocument xmlRequest = RequestFactory.BuildRequest(request); xmlRequest.Save(Console.Out); XmlRpcClient client = new XmlRpcClient(); client.AppName = "Test"; Console.WriteLine("\n"); Console.WriteLine(client.GetUserAgent()); }
public override IReadOnlyCollection <TrackManiaPlayerInfo> GetPlayerInfo() { using (var requestClient = new XmlRpcClient(this.endPoint)) { return(this.GetPlayers(requestClient, 256, 0)); } }
public async Task <LoginResponse> Connect(string uri, Credential credential, Slurl slurl = null, bool getInventoryLibrary = true, bool godMode = false) { if (slurl == null) { slurl = new Slurl(Slurl.SIM_LOCATION_LAST); } Logger.LogDebug($"INFO Login.Connect: Connecting {credential.First} {credential.Last} using {uri}."); XmlRpcParameterArray parameters = CreateLoginParameters(credential, slurl, getInventoryLibrary, godMode); XmlRpcResponse response = await XmlRpcClient.Call(uri, "login_to_simulator", parameters); LoginResponse loginResponse = new LoginResponse(); if (response.FaultCode != 0) { loginResponse.LoginSucceeded = false; loginResponse.LoginFailReason = response.FaultCode.ToString(); loginResponse.Message = response.FaultString; loginResponse.MessageId = "XmlRpcError"; return(loginResponse); } if (response.Parameters.Count != 1 || (response.Parameters[0] is XmlRpcStruct == false)) { loginResponse.LoginSucceeded = false; loginResponse.LoginFailReason = "500"; loginResponse.Message = "Login response contained incorrect parameters."; loginResponse.MessageId = "XmlRpcError"; return(loginResponse); } XmlRpcStruct responseData = (XmlRpcStruct)response.Parameters[0]; if (responseData.Has("login") == false || (responseData["login"] is XmlRpcString == false) || ((XmlRpcString)responseData["login"]).Value != "true") { loginResponse.LoginSucceeded = false; loginResponse.LoginFailReason = responseData["reason"]?.AsString; loginResponse.Message = responseData["message"]?.AsString; loginResponse.MessageId = responseData["message_id"]?.AsString; return(loginResponse); } Logger.LogInfo("Login.Connect: Connection was successful."); if (ProcessLoginSuccessResponse(responseData, loginResponse)) { loginResponse.LoginSucceeded = true; return(loginResponse); } else { // Yet another error } return(loginResponse); }
public static void asyncRequest(this XmlRpcClient client, GbxCallCallbackHandler handler, String methodName, params object[] param) { if (param == null) { param = new object[] { } } ; client.AsyncRequest(methodName, param, handler); }
/// <summary> /// Initializes a new instance of the <see cref="DokuWikiClient"/> class. /// </summary> /// <param name="account">The account to use for the communication etc.</param> /// <exception cref="ArgumentNullException"> Is thrown when /// <para><paramref name="account"/> is a <see langword="null"/> reference</para> /// <para>- or -</para> /// <para><see cref="WikiAccount.WikiUrlRaw"/> is a <see langword="null"/> reference.</para> /// </exception> internal void InitializeDokuWikiClient(WikiAccount account) { if (account == null || account.WikiUrlRaw == null) { throw new ArgumentNullException("account"); } client = new XmlRpcClient(account.WikiUrl); this.ConnectToWiki(); }
private Hashtable GetCurrentMapInfo(XmlRpcClient client) { GbxCall gbxCall = client.Request("GetCurrentMapInfo", new object[0]); if (gbxCall.HasError == false) { return(gbxCall.Params[0] as Hashtable); } return(new Hashtable()); }
private CachedXmlRpcClient(XmlRpcClient c) { lock (client_lock) { client = c; client.Disposed += () => { client = null; }; } }
/// <summary> /// </summary> /// <param name="method"></param> /// <param name="request">Full request to send to the master </param> /// <param name="response">Full response including status code and status message. Initially empty.</param> /// <param name="payload">Location to store the actual data requested, if any.</param> /// <param name="wait_for_master">If you recieve an unseccessful status code, keep retrying.</param> /// <returns></returns> public static bool execute(string method, XmlRpcValue request, ref XmlRpcValue response, ref XmlRpcValue payload, bool wait_for_master) { try { DateTime startTime = DateTime.Now; string master_host = host; int master_port = port; //EDB.WriteLine("Trying to connect to master @ " + master_host + ":" + master_port); XmlRpcClient client = XmlRpcManager.Instance.getXMLRPCClient(master_host, master_port, "/"); bool printed = false; bool ok = true; while (!client.IsConnected && !ROS.shutting_down && !XmlRpcManager.Instance.shutting_down || !(ok = client.Execute(method, request, response) && XmlRpcManager.Instance.validateXmlrpcResponse(method, response, ref payload))) { if (!wait_for_master) { XmlRpcManager.Instance.releaseXMLRPCClient(client); return(false); } if (!printed) { EDB.WriteLine("[{0}] FAILED TO CONTACT MASTER AT [{1}:{2}]. {3}", method, master_host, master_port, (wait_for_master ? "Retrying..." : "")); printed = true; } if (retryTimeout.TotalSeconds > 0 && DateTime.Now.Subtract(startTime) > retryTimeout) { EDB.WriteLine("[{0}] Timed out trying to connect to the master after [{1}] seconds", method, retryTimeout.TotalSeconds); XmlRpcManager.Instance.releaseXMLRPCClient(client); return(false); } Thread.Sleep(10); } if (ok && !firstsucces) { firstsucces = true; //EDB.WriteLine(string.Format("CONNECTED TO MASTER AT [{0}:{1}]", master_host, master_port)); } XmlRpcManager.Instance.releaseXMLRPCClient(client); return(true); } catch (Exception e) { Console.WriteLine(e); } return(false); }
public void releaseXMLRPCClient(XmlRpcClient client) { lock (clients_mutex) { foreach (CachedXmlRpcClient c in clients) { if (client == c.client) { c.in_use = false; break; } } } }
public static void Test(String xmlcommand) { XmlRpcClient client = new XmlRpcClient(); client.Url = Url; //client.Path = "common"; XmlRpcRequest requestCreate = new XmlRpcRequest(xmlcommand); //XmlRpcResponse responseCreate = client.Execute(requestCreate); client.Execute(requestCreate); //xml malformed error client.WriteRequest(Console.Out); Console.ReadKey(); }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { lock (busyMutex) { if (refs != 0) { throw new Exception("XmlRpcClient disposed while in use!"); } } if (client != null) { client.Dispose(); client = null; } }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { lock (busyMutex) if (refs != 0) { EDB.WriteLine("warning: XmlRpcClient disposed with " + refs + " refs held"); } lock (client_lock) { if (client != null) { client.Dispose(); client = null; } } }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { lock (busyMutex) if (refs != 0) { Logger.LogWarning("XmlRpcClient disposed with " + refs + " refs held"); } lock (client_lock) { if (client != null) { client.Dispose(); client = null; } } }
private Tuple <string, ushort> GetServerOptions(XmlRpcClient client) { GbxCall gbxCall = client.Request("GetServerOptions", new object[0]); if (gbxCall.HasError == false) { var hashTable = gbxCall.Params[0] as Hashtable; if (hashTable != null) { return(new Tuple <string, ushort>(hashTable["Name"] as string, Convert.ToUInt16(hashTable["CurrentMaxPlayers"]))); } } return(new Tuple <string, ushort>(default(string), default(ushort))); }
private ushort?GetPlayerCount(XmlRpcClient client, int maxCount, int firstIndex, int structVersion = 1) { GbxCall gbxCall = client.Request("GetPlayerList", new object[] { maxCount, firstIndex, structVersion }); if (gbxCall.HasError == false) { return((ushort?)(gbxCall.Params[0] as ArrayList)?.Count); } return(0); }
public void example() { XmlRpcClient client = new XmlRpcClient(); //client.Url = url; //client.Path = UtilsApiTms.PATH_XML_API; //XmlRpcRequest requestLogin = new XmlRpcRequest(UtilsApiTms.METHOD_AUTHENTICATE); //requestLogin.AddParams(database, userName, password, XmlRpcParameter.EmptyStruct()); //XmlRpcResponse rps = client.Execute(requestLogin); client.WriteRequest(Console.Out); client.WriteResponse(Console.Out); //return !rps.IsFault() ? rps.GetString() : UtilsApiTms.LOGIN_FAILED; //""rps.GetFaultString(); }
public override TrackManiaServerInfo GetServerInfo() { using (var requestClient = new XmlRpcClient(this.endPoint)) { GbxCall gbxCall = requestClient.Request("Authenticate", new object[] { this.user, this.password }); if (gbxCall.HasError == false && gbxCall.Params[0].Equals(true)) { var count = this.GetPlayerCount(requestClient, 256, 0).GetValueOrDefault(0); var mapInfo = this.GetCurrentMapInfo(requestClient); var serverOptions = this.GetServerOptions(requestClient); if (mapInfo.Count > 0) { return(new TrackManiaServerInfo { Name = serverOptions.Item1, CurrentMapName = mapInfo["Name"] as string, CurrentMaxPlayers = serverOptions.Item2, CurrentPlayerCount = count, MapType = mapInfo["MapType"] as string, Mood = mapInfo["Mood"] as string, Environment = mapInfo["Environment"] as string, CopperPrice = Convert.ToUInt32(mapInfo["CopperPrice"]), LapRace = Convert.ToBoolean(mapInfo["LapRace"]), BronzeTime = Convert.ToUInt32(mapInfo["BronzeTime"]), SilverTime = Convert.ToUInt32(mapInfo["SilverTime"]), GoldTime = Convert.ToUInt32(mapInfo["GoldTime"]), UId = mapInfo["UId"] as string, NbCheckpoints = Convert.ToUInt16(mapInfo["NbCheckpoints"]), NbLaps = Convert.ToUInt16(mapInfo["NbLaps"]), FileName = mapInfo["FileName"] as string, Author = mapInfo["Author"] as string, MapStyle = mapInfo["MapStyle"] as string, AuthorTime = Convert.ToUInt32(mapInfo["AuthorTime"]) }); } } return(new TrackManiaServerInfo()); } }
public bool NegotiateConnection(string xmlrpc_uri) { int protos = 0; XmlRpcValue tcpros_array = new XmlRpcValue(), protos_array = new XmlRpcValue(), Params = new XmlRpcValue(); tcpros_array.Set(0, "TCPROS"); protos_array.Set(protos++, tcpros_array); Params.Set(0, this_node.Name); Params.Set(1, name); Params.Set(2, protos_array); string peer_host = ""; int peer_port = 0; if (!network.splitURI(xmlrpc_uri, ref peer_host, ref peer_port)) { EDB.WriteLine("Bad xml-rpc URI: [" + xmlrpc_uri + "]"); return(false); } // test // if ( peer_host == "udacity" ) // peer_host = "192.168.30.111"; // end test XmlRpcClient c = new XmlRpcClient(peer_host, peer_port); if (!c.IsConnected || !c.ExecuteNonBlock("requestTopic", Params)) { EDB.WriteLine("Failed to contact publisher [" + peer_host + ":" + peer_port + "] for topic [" + name + "]"); c.Dispose(); return(false); } #if DEBUG EDB.WriteLine("Began asynchronous xmlrpc connection to http://" + peer_host + ":" + peer_port + "/ for topic [" + name + "]"); #endif PendingConnection conn = new PendingConnection(c, this, xmlrpc_uri, Params); lock (pending_connections_mutex) { pending_connections.Add(conn); } XmlRpcManager.Instance.addAsyncConnection(conn); return(true); }
private IReadOnlyCollection <TrackManiaPlayerInfo> GetPlayers(XmlRpcClient client, int maxCount, int firstIndex, int structVersion = 1) { GbxCall gbxCall = client.Request("GetPlayerList", new object[] { maxCount, firstIndex, structVersion }); if (gbxCall.HasError == false) { var playerList = gbxCall.Params[0] as ArrayList; if (playerList != null) { var players = new List <TrackManiaPlayerInfo>(); for (byte i = 0; i < playerList.Count; i++) { var playerData = playerList[i] as Hashtable; if (playerData != null) { players.Add(new TrackManiaPlayerInfo { Index = i, Flags = playerData["Flags"] as int? ?? 0, TeamId = playerData["TeamId"] as int? ?? 0, Login = playerData["Login"] as string, NickName = playerData["NickName"] as string, SpectatorStatus = playerData["SpectatorStatus"] as byte? ?? 0, PlayerId = playerData["PlayerId"] as int? ?? 0, LadderRanking = playerData["LadderRanking"] as int? ?? 0 }); } } return(players); } } return(new List <TrackManiaPlayerInfo>()); }
public XmlRpcClient getXMLRPCClient(string host, int port, string uri) { XmlRpcClient c = null; lock (clients_mutex) { List <CachedXmlRpcClient> zombies = new List <CachedXmlRpcClient>(); foreach (CachedXmlRpcClient client in clients) { if (!client.in_use) { if (DateTime.Now.Subtract(client.last_use_time).TotalSeconds > 30 || !client.client.IsConnected) { client.client.Shutdown(); zombies.Add(client); } else if (client.client.CheckIdentity(host, port, uri)) { c = client.client; client.in_use = true; client.last_use_time = DateTime.Now; break; } } } foreach (CachedXmlRpcClient C in zombies) { clients.Remove(C); C.client.Dispose(); } if (c == null) { c = new XmlRpcClient(host, port, uri); clients.Add(new CachedXmlRpcClient(c) { in_use = true, last_use_time = DateTime.Now }); } } return(c); }
//============================================================ // CLASS SUMMARY //============================================================ /// <summary> /// Provides example code for the XmlRpcClient class. /// </summary> public static void ClassExample() { #region XmlRpcClient // Initialize the XML-RPC client XmlRpcClient client = new XmlRpcClient(); client.Host = new Uri("http://bob.example.net/xmlrpcserver"); // Construct a Pingback peer-to-peer notification XML-RPC message XmlRpcMessage message = new XmlRpcMessage("pingback.ping"); message.Encoding = Encoding.UTF8; message.Parameters.Add(new XmlRpcScalarValue("http://alice.example.org/#p123")); // sourceURI message.Parameters.Add(new XmlRpcScalarValue("http://bob.example.net/#foo")); // targetURI // Send a synchronous pingback ping XmlRpcResponse response = client.Send(message); // Verify response to the trackback ping if (response != null) { if (response.Fault != null) { XmlRpcStructureMember faultCode = response.Fault["faultCode"]; XmlRpcStructureMember faultMessage = response.Fault["faultString"]; if (faultCode != null && faultMessage != null) { // Handle the pingback ping error condition that occurred } } else { XmlRpcScalarValue successInformation = response.Parameter as XmlRpcScalarValue; if (successInformation != null) { // Pingback request was successful, return should be a string containing information the server deems useful. } } } #endregion }
public void ThreadStart() { foreach (string url in _pingUrls) { try { Uri uri = new Uri(url); if (uri.Scheme.ToLower(CultureInfo.InvariantCulture) == "http" || uri.Scheme.ToLower(CultureInfo.InvariantCulture) == "https") { XmlRpcClient client = new XmlRpcClient(url, ApplicationEnvironment.UserAgent); client.CallMethod("weblogUpdates.ping", _blogName, _blogUrl); } } catch (Exception e) { if (ApplicationDiagnostics.VerboseLogging) { Trace.Fail("Failure while pinging " + url + ": " + e.ToString()); } } } }