public ReadAsText ( Stream input ) : bool | ||
input | Stream | The input |
Résultat | bool |
/// <summary> /// Attempts to create an instance of <see cref="KeyValue"/> from the given input text. /// </summary> /// <param name="input">The input text to load.</param> /// <returns>a <see cref="KeyValue"/> instance if the load was successful, or <c>null</c> on failure.</returns> /// <remarks> /// This method will swallow any exceptions that occur when reading, use <see cref="ReadAsText"/> if you wish to handle exceptions. /// </remarks> public static KeyValue?LoadFromString(string input) { if (input == null) { throw new ArgumentNullException(nameof(input)); } byte[] bytes = Encoding.UTF8.GetBytes(input); using (MemoryStream stream = new MemoryStream(bytes)) { var kv = new KeyValue(); try { if (kv.ReadAsText(stream) == false) { return(null); } return(kv); } catch (Exception) { return(null); } } }
async Task <KeyValue> DoCommandAsync(Server server, HttpMethod method, string command, string data = null, bool doAuth = false, string args = "", string authtoken = null) { var resultData = await DoRawCommandAsync(server, method, command, data, doAuth, args, authtoken).ConfigureAwait(false); var dataKv = new KeyValue(); using (MemoryStream ms = new MemoryStream(resultData)) { try { dataKv.ReadAsText(ms); } catch (Exception ex) { throw new InvalidDataException("An internal error occurred while attempting to parse the response from the CS server.", ex); } } return(dataKv); }
KeyValue DoCommand(Server server, string command, string data = null, string method = WebRequestMethods.Http.Get, bool doAuth = false, string args = "") { byte[] resultData = DoRawCommand(server, command, data, method, doAuth, args); var dataKv = new KeyValue(); using (MemoryStream ms = new MemoryStream(resultData)) { try { dataKv.ReadAsText(ms); } catch (Exception ex) { throw new InvalidDataException("An internal error occurred while attempting to parse the response from the CS server.", ex); } } return(dataKv); }
public override void OnCommand(CommandArguments command) { using (var webClient = new WebClient()) { webClient.DownloadDataCompleted += delegate(object sender, DownloadDataCompletedEventArgs e) { var kv = new KeyValue(); using (var ms = new MemoryStream(e.Result)) { try { kv.ReadAsText(ms); } catch { CommandHandler.ReplyToCommand(command, "Something went horribly wrong and keyvalue parser died."); return; } } if (kv["bins_osx"].Children.Count == 0) { CommandHandler.ReplyToCommand(command, "Failed to find binaries in parsed response."); return; } kv = kv["bins_osx"]; CommandHandler.ReplyToCommand(command, "You're on your own:{0} {1}{2} {3}({4} MB)", Colors.DARKBLUE, CDN, kv["file"].AsString(), Colors.DARKGRAY, (kv["size"].AsLong() / 1048576.0).ToString("0.###")); }; webClient.DownloadDataAsync(new Uri(string.Format("{0}steam_client_publicbeta_osx?_={1}", CDN, DateTime.UtcNow.Ticks))); } }
static KeyValue?LoadFromFile(string path, bool asBinary) { if (File.Exists(path) == false) { return(null); } try { using (var input = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var kv = new KeyValue(); if (asBinary) { if (kv.TryReadAsBinary(input) == false) { return(null); } } else { if (kv.ReadAsText(input) == false) { return(null); } } return(kv); } } catch (Exception) { return(null); } }
KeyValue DoCommand( Server server, string command, string data = null, string method = WebRequestMethods.Http.Get, bool doAuth = false, string args = "" ) { byte[] resultData = DoRawCommand( server, command, data, method, doAuth, args ); var dataKv = new KeyValue(); using ( MemoryStream ms = new MemoryStream( resultData ) ) { try { dataKv.ReadAsText( ms ); } catch ( Exception ex ) { throw new InvalidDataException( "An internal error occurred while attempting to parse the response from the CS server.", ex ); } } return dataKv; }
/// <summary> /// Manually calls the specified Web API function with the provided details. /// </summary> /// <param name="func">The function name to call.</param> /// <param name="version">The version of the function to call.</param> /// <param name="args">A dictionary of string key value pairs representing arguments to be passed to the API.</param> /// <param name="method">The http request method. Either "POST" or "GET".</param> /// <param name="secure">if set to <c>true</c> this method will be called through the secure API.</param> /// <returns>A <see cref="Task{T}"/> that contains a <see cref="KeyValue"/> object representing the results of the Web API call.</returns> /// <exception cref="ArgumentNullException">The function name or request method provided were <c>null</c>.</exception> /// <exception cref="WebException">An network error occurred when performing the request.</exception> /// <exception cref="InvalidDataException">An error occured when parsing the response from the WebAPI.</exception> public Task<KeyValue> Call( string func, int version = 1, Dictionary<string, string> args = null, string method = WebRequestMethods.Http.Get, bool secure = false ) { if ( func == null ) throw new ArgumentNullException( "func" ); if ( args == null ) args = new Dictionary<string, string>(); if ( method == null ) throw new ArgumentNullException( "method" ); StringBuilder urlBuilder = new StringBuilder(); StringBuilder paramBuilder = new StringBuilder(); urlBuilder.Append( secure ? "https://" : "http://" ); urlBuilder.Append( API_ROOT ); urlBuilder.AppendFormat( "/{0}/{1}/v{2}", iface, func, version ); bool isGet = method.Equals( WebRequestMethods.Http.Get, StringComparison.OrdinalIgnoreCase ); if ( isGet ) { // if we're doing a GET request, we'll build the params onto the url paramBuilder = urlBuilder; paramBuilder.Append( "/?" ); // start our GET params } args.Add( "format", "vdf" ); if ( !string.IsNullOrEmpty( apiKey ) ) { args.Add( "key", apiKey ); } // append any args paramBuilder.Append( string.Join( "&", args.Select( kvp => { // TODO: the WebAPI is a special snowflake that needs to appropriately handle url encoding // this is in contrast to the steam3 content server APIs which use an entirely different scheme of encoding string key = WebHelpers.UrlEncode( kvp.Key ); string value = kvp.Value; // WebHelpers.UrlEncode( kvp.Value ); return string.Format( "{0}={1}", key, value ); } ) ) ); var task = Task.Factory.StartNew<KeyValue>( () => { byte[] data = null; if ( isGet ) { data = webClient.DownloadData( urlBuilder.ToString() ); } else { byte[] postData = Encoding.Default.GetBytes( paramBuilder.ToString() ); webClient.Headers.Add( HttpRequestHeader.ContentType, "application/x-www-form-urlencoded" ); data = webClient.UploadData( urlBuilder.ToString(), postData ); } KeyValue kv = new KeyValue(); using ( var ms = new MemoryStream( data ) ) { try { kv.ReadAsText( ms ); } catch ( Exception ex ) { throw new InvalidDataException( "An internal error occurred when attempting to parse the response from the WebAPI server. This can indicate a change in the VDF format.", ex ); } } return kv; } ); task.ContinueWith( t => { // we need to observe the exception in this OnlyOnFaulted continuation if our task throws an exception but we're not able to observe it // (such as when waiting for the task times out, and an exception is thrown later) // see: http://msdn.microsoft.com/en-us/library/dd997415.aspx DebugLog.WriteLine( "WebAPI", "Threw an unobserved exception: {0}", t.Exception ); }, TaskContinuationOptions.OnlyOnFaulted ); return task; }
/// <summary> /// Manually calls the specified Web API function with the provided details. /// </summary> /// <param name="func">The function name to call.</param> /// <param name="version">The version of the function to call.</param> /// <param name="args">A dictionary of string key value pairs representing arguments to be passed to the API.</param> /// <param name="method">The http request method. Either "POST" or "GET".</param> /// <param name="secure">if set to <c>true</c> this method will be called through the secure API.</param> /// <returns>A <see cref="Task{T}"/> that contains a <see cref="KeyValue"/> object representing the results of the Web API call.</returns> /// <exception cref="ArgumentNullException">The function name or request method provided were <c>null</c>.</exception> /// <exception cref="WebException">An network error occurred when performing the request.</exception> /// <exception cref="InvalidDataException">An error occured when parsing the response from the WebAPI.</exception> public Task <KeyValue> Call(string func, int version = 1, Dictionary <string, string> args = null, string method = WebRequestMethods.Http.Get, bool secure = false) { if (func == null) { throw new ArgumentNullException("func"); } if (args == null) { args = new Dictionary <string, string>(); } if (method == null) { throw new ArgumentNullException("method"); } StringBuilder urlBuilder = new StringBuilder(); StringBuilder paramBuilder = new StringBuilder(); urlBuilder.Append(secure ? "https://" : "http://"); urlBuilder.Append(API_ROOT); urlBuilder.AppendFormat("/{0}/{1}/v{2}", iface, func, version); bool isGet = method.Equals(WebRequestMethods.Http.Get, StringComparison.OrdinalIgnoreCase); if (isGet) { // if we're doing a GET request, we'll build the params onto the url paramBuilder = urlBuilder; paramBuilder.Append("/?"); // start our GET params } args.Add("format", "vdf"); if (!string.IsNullOrEmpty(apiKey)) { args.Add("key", apiKey); } // append any args paramBuilder.Append(string.Join("&", args.Select(kvp => { // TODO: the WebAPI is a special snowflake that needs to appropriately handle url encoding // this is in contrast to the steam3 content server APIs which use an entirely different scheme of encoding string key = WebHelpers.UrlEncode(kvp.Key); string value = kvp.Value; // WebHelpers.UrlEncode( kvp.Value ); return(string.Format("{0}={1}", key, value)); }))); var task = Task.Factory.StartNew <KeyValue>(() => { byte[] data = null; if (isGet) { data = webClient.DownloadData(urlBuilder.ToString()); } else { byte[] postData = Encoding.Default.GetBytes(paramBuilder.ToString()); webClient.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded"); data = webClient.UploadData(urlBuilder.ToString(), postData); } KeyValue kv = new KeyValue(); using (var ms = new MemoryStream(data)) { try { kv.ReadAsText(ms); } catch (Exception ex) { throw new InvalidDataException( "An internal error occurred when attempting to parse the response from the WebAPI server. This can indicate a change in the VDF format.", ex ); } } return(kv); }); task.ContinueWith(t => { // we need to observe the exception in this OnlyOnFaulted continuation if our task throws an exception but we're not able to observe it // (such as when waiting for the task times out, and an exception is thrown later) // see: http://msdn.microsoft.com/en-us/library/dd997415.aspx DebugLog.WriteLine("WebAPI", "Threw an unobserved exception: {0}", t.Exception); }, TaskContinuationOptions.OnlyOnFaulted); return(task); }
/// <summary> /// Manually calls the specified Web API function with the provided details. /// </summary> /// <param name="func">The function name to call.</param> /// <param name="version">The version of the function to call.</param> /// <param name="args">A dictionary of string key value pairs representing arguments to be passed to the API.</param> /// <param name="method">The http request method. Either "POST" or "GET".</param> /// <param name="secure">if set to <c>true</c> this method will be called through the secure API.</param> /// <returns>A <see cref="KeyValue"/> object representing the results of the Web API call.</returns> /// <exception cref="ArgumentNullException">The function name or request method provided were <c>null</c>.</exception> /// <exception cref="WebException">An network error occurred when performing the request.</exception> /// <exception cref="InvalidDataException">An error occured when parsing the response from the WebAPI.</exception> public KeyValue Call( string func, int version = 1, Dictionary<string, string> args = null, string method = WebRequestMethods.Http.Get, bool secure = false ) { if ( func == null ) throw new ArgumentNullException( "func" ); if ( args == null ) args = new Dictionary<string, string>(); if ( method == null ) throw new ArgumentNullException( "method" ); StringBuilder urlBuilder = new StringBuilder(); StringBuilder paramBuilder = new StringBuilder(); urlBuilder.Append( secure ? "https://" : "http://" ); urlBuilder.Append( API_ROOT ); urlBuilder.AppendFormat( "/{0}/{1}/v{2}", iface, func, version ); bool isGet = method.Equals( WebRequestMethods.Http.Get, StringComparison.OrdinalIgnoreCase ); if ( isGet ) { // if we're doing a GET request, we'll build the params onto the url paramBuilder = urlBuilder; paramBuilder.Append( "/?" ); // start our GET params } args.Add( "format", "vdf" ); if ( !string.IsNullOrEmpty( apiKey ) ) { args.Add( "key", apiKey ); } // append any args paramBuilder.Append( string.Join( "&", args.Select( kvp => { // TODO: the WebAPI is a special snowflake that needs to appropriately handle url encoding // this is in contrast to the steam3 content server APIs which use an entirely different scheme of encoding string key = WebHelpers.UrlEncode( kvp.Key ); string value = kvp.Value; // WebHelpers.UrlEncode( kvp.Value ); return string.Format( "{0}={1}", key, value ); } ) ) ); byte[] data = null; if ( isGet ) { data = webClient.DownloadData( urlBuilder.ToString() ); } else { byte[] postData = Encoding.Default.GetBytes( paramBuilder.ToString() ); webClient.Headers.Add( HttpRequestHeader.ContentType, "application/x-www-form-urlencoded" ); data = webClient.UploadData( urlBuilder.ToString(), postData ); } KeyValue kv = new KeyValue(); using ( var ms = new MemoryStream( data ) ) { try { kv.ReadAsText( ms ); } catch ( Exception ex ) { throw new InvalidDataException( "An internal error occurred when attempting to parse the response from the WebAPI server. This can indicate a change in the VDF format.", ex ); } } return kv; }
/// <summary> /// Manually calls the specified Web API function with the provided details. /// </summary> /// <param name="func">The function name to call.</param> /// <param name="version">The version of the function to call.</param> /// <param name="args">A dictionary of string key value pairs representing arguments to be passed to the API.</param> /// <param name="method">The http request method. Either "POST" or "GET".</param> /// <param name="secure">if set to <c>true</c> this method will be called through the secure API.</param> /// <returns>A <see cref="KeyValue"/> object representing the results of the Web API call.</returns> /// <exception cref="ArgumentNullException">The function name or request method provided were <c>null</c>.</exception> /// <exception cref="WebException">An network error occurred when performing the request.</exception> /// <exception cref="InvalidDataException">An error occured when parsing the response from the WebAPI.</exception> public KeyValue Call(string func, int version = 1, Dictionary <string, string> args = null, string method = WebRequestMethods.Http.Get, bool secure = false) { if (func == null) { throw new ArgumentNullException("func"); } if (args == null) { args = new Dictionary <string, string>(); } if (method == null) { throw new ArgumentNullException("method"); } StringBuilder urlBuilder = new StringBuilder(); StringBuilder paramBuilder = new StringBuilder(); urlBuilder.Append(secure ? "https://" : "http://"); urlBuilder.Append(API_ROOT); urlBuilder.AppendFormat("/{0}/{1}/v{2}", iface, func, version); bool isGet = method.Equals(WebRequestMethods.Http.Get, StringComparison.OrdinalIgnoreCase); if (isGet) { // if we're doing a GET request, we'll build the params onto the url paramBuilder = urlBuilder; paramBuilder.Append("/?"); // start our GET params } args.Add("format", "vdf"); if (!string.IsNullOrEmpty(apiKey)) { args.Add("key", apiKey); } // append any args paramBuilder.Append(string.Join("&", args.Select(kvp => { // TODO: the WebAPI is a special snowflake that needs to appropriately handle url encoding // this is in contrast to the steam3 content server APIs which use an entirely different scheme of encoding string key = WebHelpers.UrlEncode(kvp.Key); string value = kvp.Value; // WebHelpers.UrlEncode( kvp.Value ); return(string.Format("{0}={1}", key, value)); }))); byte[] data = null; if (isGet) { data = webClient.DownloadData(urlBuilder.ToString()); } else { byte[] postData = Encoding.Default.GetBytes(paramBuilder.ToString()); webClient.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded"); data = webClient.UploadData(urlBuilder.ToString(), postData); } KeyValue kv = new KeyValue(); using (var ms = new MemoryStream(data)) { try { kv.ReadAsText(ms); } catch (Exception ex) { throw new InvalidDataException( "An internal error occurred when attempting to parse the response from the WebAPI server. This can indicate a change in the VDF format.", ex ); } } return(kv); }
async Task <KeyValue> CallAsyncCore(HttpMethod method, string func, int version = 1, Dictionary <string, string> args = null) { if (method == null) { throw new ArgumentNullException(nameof(method)); } if (func == null) { throw new ArgumentNullException(nameof(func)); } if (args == null) { args = new Dictionary <string, string>(); } var urlBuilder = new StringBuilder(); var paramBuilder = new StringBuilder(); urlBuilder.AppendFormat("{0}/{1}/v{2}", iface, func, version); var isGet = HttpMethod.Get.Equals(method); if (isGet) { // if we're doing a GET request, we'll build the params onto the url paramBuilder = urlBuilder; paramBuilder.Append("/?"); // start our GET params } args.Add("format", "vdf"); if (!string.IsNullOrEmpty(apiKey)) { args.Add("key", apiKey); } // append any args paramBuilder.Append(string.Join("&", args.Select(kvp => { // TODO: the WebAPI is a special snowflake that needs to appropriately handle url encoding // this is in contrast to the steam3 content server APIs which use an entirely different scheme of encoding string key = WebHelpers.UrlEncode(kvp.Key); string value = kvp.Value; // WebHelpers.UrlEncode( kvp.Value ); return(string.Format("{0}={1}", key, value)); }))); var request = new HttpRequestMessage(method, urlBuilder.ToString()); if (!isGet) { request.Content = new StringContent(paramBuilder.ToString()); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); } var response = await httpClient.SendAsync(request).ConfigureAwait(false); var kv = new KeyValue(); using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { try { kv.ReadAsText(stream); } catch (Exception ex) { throw new InvalidDataException( "An internal error occurred when attempting to parse the response from the WebAPI server. This can indicate a change in the VDF format.", ex ); } } return(kv); }
/// <summary> /// Attempts to create an instance of <see cref="KeyValue"/> from the given input text. /// </summary> /// <param name="input">The input text to load.</param> /// <returns>a <see cref="KeyValue"/> instance if the load was successful, or <c>null</c> on failure.</returns> /// <remarks> /// This method will swallow any exceptions that occur when reading, use <see cref="ReadAsText"/> if you wish to handle exceptions. /// </remarks> public static KeyValue LoadFromString( string input ) { byte[] bytes = Encoding.UTF8.GetBytes( input ); using ( MemoryStream stream = new MemoryStream( bytes ) ) { var kv = new KeyValue(); try { if ( kv.ReadAsText( stream ) == false ) return null; return kv; } catch ( Exception ) { return null; } } }
static KeyValue LoadFromFile( string path, bool asBinary ) { if ( File.Exists( path ) == false ) { return null; } try { using ( var input = File.Open( path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ) ) { var kv = new KeyValue(); if ( asBinary ) { if ( kv.ReadAsBinary( input ) == false ) { return null; } } else { if ( kv.ReadAsText( input ) == false ) { return null; } } return kv; } } catch ( Exception ) { return null; } }
public static String ConvertVdf2Json(Stream inputFileStream) { var kv = new KeyValue(); kv.ReadAsText(inputFileStream); return Convert(kv,false); }
private static void OnCommandBinaries(CommandArguments command) { if (command.IsChatRoomCommand || !IRC.IsSenderOp(command.Channel, command.Nickname)) { return; } string cdn = "http://media.steampowered.com/client/"; using (var webClient = new WebClient()) { var manifest = webClient.DownloadData(string.Format("{0}steam_client_publicbeta_osx?_={1}", cdn, DateTime.UtcNow.Ticks)); var kv = new KeyValue(); using (var ms = new MemoryStream(manifest)) { try { kv.ReadAsText(ms); } catch { ReplyToCommand(command, "{0}{1}{2}: Something went horribly wrong and keyvalue parser died", Colors.OLIVE, command.Nickname, Colors.NORMAL); return; } } if (kv["bins_osx"].Children.Count == 0) { ReplyToCommand(command, "{0}{1}{2}: Failed to find binaries in parsed response.", Colors.OLIVE, command.Nickname, Colors.NORMAL); return; } kv = kv["bins_osx"]; ReplyToCommand(command, "{0}{1}{2}:{3} {4}{5} {6}({7} MB)", Colors.OLIVE, command.Nickname, Colors.NORMAL, Colors.DARK_BLUE, cdn, kv["file"].AsString(), Colors.DARK_GRAY, (kv["size"].AsLong() / 1048576.0).ToString("0.###")); } }