// // PostJson.cs // // Author: // Paul Schneider // // Copyright (c) 2015 Paul Schneider // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see . using System; using System.Net; using System.Text; using System.IO; using System.Runtime.Serialization.Json; namespace Yavsc.Model { /// /// Simple json post method. /// public class SimpleJsonPostMethod: IDisposable { internal HttpWebRequest request = null; internal HttpWebRequest Request { get { return request; } } string CharSet { get { return Request.TransferEncoding; } set { Request.TransferEncoding=value;} } string Method { get { return Request.Method; } } /// /// Gets the path. /// /// The path. public string Path { get{ return Request.RequestUri.ToString(); } } /// /// Sets the credential. /// /// Cred. public void SetCredential(string cred) { Request.Headers.Set(HttpRequestHeader.Authorization,cred); } /// /// Initializes a new instance of the Yavsc.Helpers.SimpleJsonPostMethod class. /// /// Path to method. public SimpleJsonPostMethod (string pathToMethod) { // ASSERT Request == null request = (HttpWebRequest) WebRequest.Create (pathToMethod); Request.Method = "POST"; Request.Accept = "application/json"; Request.ContentType = "application/json"; Request.SendChunked = true; Request.TransferEncoding = "UTF-8"; } /// /// Invoke the specified query. /// /// Query. public TAnswer Invoke(TQuery query) { DataContractJsonSerializer serquery = new DataContractJsonSerializer (typeof(TQuery)); DataContractJsonSerializer seransw = new DataContractJsonSerializer (typeof(TAnswer)); using (Stream streamQuery = request.GetRequestStream()) { serquery.WriteObject (streamQuery, query); } TAnswer ans = default (TAnswer); using (WebResponse response = Request.GetResponse ()) { using (Stream responseStream = response.GetResponseStream ()) { ans = (TAnswer) seransw.ReadObject(responseStream); } response.Close(); } return ans; } #region IDisposable implementation /// /// Releases all resource used by the Yavsc.Helpers.SimpleJsonPostMethod object. /// public void Dispose () { if (Request != null) Request.Abort (); } #endregion } }