private string GetHideId(EwsRequest request, PayloadDefinition definition) { try { if (definition.IsHideRequired) { //Getting the HideID by making request to the URL provided string hideId = string.Empty; var hideUrl = new Uri(string.Format(CultureInfo.CurrentCulture, definition.HideUrl, Device.Address)); HttpWebRequest httpRequest = BuildRequest(hideUrl, HttpVerb.Post, definition, SessionId, definition.Payload); var hideResponse = HttpMessenger.ExecuteRequest(httpRequest); if (!string.IsNullOrEmpty(hideResponse.Body)) { int start = hideResponse.Body.IndexOf("name=\"Hide\" VALUE=\"", StringComparison.Ordinal) + 19; int end = hideResponse.Body.IndexOf("\"", start, StringComparison.Ordinal); hideId = (hideResponse.Body.Substring(start, (end - start))); } //Getting the session ID from the response recieved if (!string.IsNullOrEmpty(hideId)) { request.AddWithoutValidate("HideID", hideId); } return(hideId); } } catch (ArgumentOutOfRangeException ex) { throw new DeviceCommunicationException("Exception occurred while fetching the Hide Id ", ex.InnerException); } throw new DeviceCommunicationException("Could not get the Hide Id, please check the Hide Id URL."); }
/// <summary> /// Sends the Http request with the specified Uri and post data. /// </summary> /// <param name="uri">The Uri</param> /// <param name="stringData">The data</param> /// <returns><see cref="HttpResponse"/></returns> private static void SendRequest(Uri uri, string stringData) { var request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "POST"; request.ContentType = "application/xml; charset=utf-8"; request.KeepAlive = false; try { byte[] buffer = Encoding.ASCII.GetBytes(stringData); request.ContentLength = buffer.Length; Stream sw = request.GetRequestStream(); sw.Write(buffer, 0, buffer.Length); sw.Close(); var response = HttpMessenger.ExecuteRequest(request); if (response.StatusCode != HttpStatusCode.OK) { throw new WebException("Hpcr Solution Installation failed"); } } catch (Exception e) { throw new WebException("Hpcr Solution Installation failed", e); } }
protected virtual void Dispose(bool disposing) { if (disposing) { HttpMessenger.Dispose(); } }
public ComicVineClient(string apiKey, string?userAgent = null) { HttpMessenger = new HttpMessenger(userAgent); HttpConnection = new HttpConnection(HttpMessenger, apiKey); ApiConnection = new ApiConnection(HttpConnection); Character = new CharacterClient(ApiConnection); Series = new SeriesClient(ApiConnection); Issue = new IssueClient(ApiConnection); Volume = new VolumeClient(ApiConnection); Search = new SearchClient(ApiConnection); }
protected string GetSolutionId(string sessionId, string solutionName) { try { //Getting the session ID by making request to /hp/device/SolutionInstaller HttpWebRequest httpRequest = WebRequest.CreateHttp(new Uri(string.Format(CultureInfo.CurrentCulture, OmniDeviceSolutionUrl, Device.Address))); httpRequest.Method = "GET"; WebHeaderCollection headers = new WebHeaderCollection(); if (!string.IsNullOrEmpty(Device.AdminPassword)) { var plainTextBytes = Encoding.UTF8.GetBytes("admin:" + Device.AdminPassword); string authorization = Convert.ToBase64String(plainTextBytes); headers.Add(HttpRequestHeader.Authorization, "Basic " + authorization + ""); } if (!string.IsNullOrEmpty(sessionId)) { headers.Add(HttpRequestHeader.Cookie, $"sessionId={sessionId}"); } httpRequest.Headers = headers; var sessionResponse = HttpMessenger.ExecuteRequest(httpRequest); if (sessionResponse.StatusCode != HttpStatusCode.OK) { return(string.Empty); } //Getting the session ID from the response received HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(sessionResponse.Body); HtmlNode table = doc.DocumentNode.SelectSingleNode("//table[@id='SolutionsTable']"); if (table == null) { throw new WebException("Solution not installed"); } foreach (var cell in table.SelectNodes(".//tr/td")) // **notice the .** { if (cell.InnerText.StartsWith(solutionName, StringComparison.OrdinalIgnoreCase)) { if (cell.Id.EndsWith("_Name", StringComparison.OrdinalIgnoreCase)) { return(cell.Id.Substring(0, cell.Id.Length - 5)); } } } return(string.Empty); } catch (ArgumentOutOfRangeException ex) { throw new DeviceCommunicationException("Exception occurred while fetching the Solution Id ", ex.InnerException); } }
private void FillStateValues(EwsRequest request, string sessionId, PayloadDefinition definition) { if (definition.IsViewStateRequired) { Uri viewStateUrl = null; //Getting the viewstate by making request to the URL provided //Implemented the below functionality to get the tray ID for which the setting needs to be implemented if (request.RequestType.Equals("ManageTrays") && request.RequestSubtype.Equals("Tray")) { viewStateUrl = new Uri(string.Format(CultureInfo.CurrentCulture, definition.ViewStateUrl, Device.Address, request.PayloadValues["Tray"])); } else { viewStateUrl = new Uri(string.Format(CultureInfo.CurrentCulture, definition.ViewStateUrl, Device.Address)); } HttpWebRequest httpRequest = BuildRequest(viewStateUrl, HttpVerb.Get, definition, sessionId); var viewStateResponse = HttpMessenger.ExecuteRequest(httpRequest); //Getting the session ID from the response recieved string viewstate = GetViewState(viewStateResponse.Body); if (!string.IsNullOrEmpty(viewstate)) { //Manage trays expects HPViewState and not just ViewState in the payload if (request.RequestType.Equals("ManageTrays") && request.RequestSubtype.Equals("Tray")) { viewstate = System.Web.HttpUtility.HtmlDecode(viewstate); request.AddWithoutValidate("HPViewState", viewstate); } else { request.AddWithoutValidate("ViewState", viewstate); } } } if (definition.IsWizardIdRequired) { //Getting the viewstate by making request to the URL provided var wizardIdUrl = new Uri(string.Format(CultureInfo.CurrentCulture, definition.WizardIdUrl, Device.Address)); HttpWebRequest httpRequest = BuildRequest(wizardIdUrl, HttpVerb.Get, definition, sessionId); var wizardResponse = HttpMessenger.ExecuteRequest(httpRequest); //Getting the session ID from the response recieved string wizardId = GetWizardId(wizardResponse.Body); if (!string.IsNullOrEmpty(wizardId)) { request.AddWithoutValidate("WizardID", wizardId); } } }
protected override HttpWebRequest BuildRequest(Uri url, HttpVerb method, PayloadDefinition payloadDefinition, string sessionId, string payload = null, string hideId = null) { HttpMessenger messenger = new HttpMessenger() { ContentType = "application/x-www-form-urlencoded", Accept = "text/html, application/xhtml+xml, image/jxr, */*", AllowAutoRedirect = true, Encoding = Encoding.GetEncoding("iso-8859-1"), Expect100Continue = false }; WebHeaderCollection headers = new WebHeaderCollection(); foreach (var header in payloadDefinition.Headers.Keys) { headers.Add(header, payloadDefinition.Headers[header]); } if (!string.IsNullOrEmpty(Password)) { var plainTextBytes = Encoding.UTF8.GetBytes("admin:" + Password); string authorization = Convert.ToBase64String(plainTextBytes); headers.Add(HttpRequestHeader.Authorization, "Basic " + authorization + ""); } var cookieContainer = new CookieContainer(); if (!string.IsNullOrEmpty(sessionId)) { headers.Add(HttpRequestHeader.Cookie, $"sessionId={sessionId}"); cookieContainer.Add(new Cookie("sessionId", sessionId) { Domain = url.Host }); } if (!string.IsNullOrEmpty(hideId)) { headers.Add(HttpRequestHeader.Cookie, $"ipsecwizardid={hideId}"); cookieContainer.Add(new Cookie("ipsecwizardid", hideId) { Domain = url.Host }); } HttpWebRequest request = messenger.BuildRequest(url, method, headers, payload); request.CookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; return(request); }
private void Awake() { // Messenger taking care of processing outgoing and incoming data // as well as setting up and managing the HTTP requests messenger = new HttpMessenger(); messenger.RegisterCallback(this); // Allows to get direct access to request and response // For printing the result to the log. jsonPrintOptions = new JsonOptions(); jsonPrintOptions.CompactOutput = false; logBuilder = new StringBuilder(); btnSendRequest.onClick.AddListener(SendRequest); btnClearLog.onClick.AddListener(ClearLog); }
private string GetSessionId(string address) { try { //Getting the session ID by making request to /hp/device/DeviceStatus/Index HttpWebRequest signinRequest = (HttpWebRequest)WebRequest.Create($"https://{address}/hp/device/SignIn/Index"); var sessionResponse = HttpMessenger.ExecuteRequest(signinRequest); //Getting the session ID from the response recieved string sessionId = sessionResponse.Headers.GetValues("Set-Cookie")?.FirstOrDefault()?.Split(';').FirstOrDefault(); sessionId = sessionId?.Replace("sessionId=", string.Empty); return(sessionId); } catch (WebException) { return(string.Empty); } }
protected override string GetSessionId(PayloadDefinition definition) { try { var signInUri = new Uri(string.Format(CultureInfo.CurrentCulture, SiriusDeviceSignInUrl, Device.Address)); //Getting the session ID by making request to /hp/device/DeviceStatus/Index HttpWebRequest httpRequest = BuildRequest(signInUri, HttpVerb.Get, definition, null); var sessionResponse = HttpMessenger.ExecuteRequest(httpRequest); //Getting the session ID from the response recieved string sessionId = (sessionResponse.Headers.GetValues("Set-Cookie")?.FirstOrDefault()?.Split(';').FirstOrDefault()); sessionId = sessionId?.Replace("sid=", string.Empty); return(sessionId); } catch (WebException) { return(string.Empty); } }
protected string GetSolutionId(string sessionId, string solutionName) { try { PayloadDefinition payload = new PayloadDefinition { Headers = new Dictionary <string, string>() }; //Getting the session ID by making request to /hp/device/SolutionInstaller HttpWebRequest httpRequest = BuildRequest(new Uri(string.Format(CultureInfo.CurrentCulture, OmniDeviceHpacSolutionUrl, Device.Address)), HttpVerb.Get, payload, sessionId); var sessionResponse = HttpMessenger.ExecuteRequest(httpRequest); //Getting the session ID from the response recieved HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(sessionResponse.Body); CsrfToken = doc.GetElementbyId("CSRFToken").Attributes["value"].Value; //var nodes = doc.g HtmlNode table = doc.DocumentNode.SelectSingleNode("//table[@id='SolutionsTable']"); if (table == null) { throw new DeviceInvalidOperationException("Solution not installed"); } foreach (var cell in table.SelectNodes(".//tr/td")) // **notice the .** { if (cell.InnerText.StartsWith(solutionName, StringComparison.OrdinalIgnoreCase)) { if (cell.Id.EndsWith("_Name", StringComparison.OrdinalIgnoreCase)) { return(cell.Id.Substring(0, cell.Id.Length - 5)); } } } return(string.Empty); } catch (ArgumentOutOfRangeException ex) { throw new DeviceCommunicationException("Exception occurred while fetching the Solution Id ", ex.InnerException); } }
protected HttpResponse ExecuteRequest(Uri url, string payload, PayloadDefinition payloadDefinition, string hideId) { string solutionName = string.Empty; if (payloadDefinition.IsRemoveSolution) { solutionName = payload; payload = string.Empty; } var httpRequest = BuildRequest(url, payloadDefinition.HttpMethod, payloadDefinition, SessionId, payload, hideId); if (payloadDefinition.IsUpload) { FillUploadData(httpRequest, payload, "certificate", payloadDefinition.NameValuePairs); } else if (payloadDefinition.IsRemoveSolution) { FillRemoveSolutionData(httpRequest, solutionName, SessionId); } return(HttpMessenger.ExecuteRequest(httpRequest)); }
protected override string GetSessionId(PayloadDefinition definition) { try { //Getting the session ID by making request to PhoenixDeviceSignInURL var signInUri = new Uri(string.Format(CultureInfo.CurrentCulture, PhoenixDeviceSignInUrl, Device.Address)); HttpWebRequest httpRequest = BuildRequest(signInUri, HttpVerb.Get, definition, null); var sessionResponse = HttpMessenger.ExecuteRequest(httpRequest); //Getting the session ID from the response recieved string sessionId = string.Empty; if (sessionResponse.Headers.GetValues("Set-Cookie") != null) { sessionId = (sessionResponse.Headers.GetValues("Set-Cookie")?.FirstOrDefault()?.Split(';').FirstOrDefault()); } return(sessionId); } catch (WebException) { return(string.Empty); } }
/// <summary> /// Prints document using EWS /// </summary> /// <param name="ipAddress"></param> /// <param name="password"></param> /// <param name="localFileDocument"></param> private void PrintEws(string ipAddress, string password, FileInfo localFileDocument) { ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; string sessionId = SignInOmni(ipAddress, password); var csrfToken = GetCsrfToken($"https://{ipAddress}/hp/device/SignIn/Index", ref sessionId); var authenticatorRequest = (HttpWebRequest)WebRequest.Create($"https://{ipAddress}/hp/device/Print/Print"); authenticatorRequest.Method = "POST"; authenticatorRequest.Accept = "text/html, application/xhtml+xml, image/jxr, */*"; string boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x16", CultureInfo.CurrentCulture); authenticatorRequest.ContentType = "multipart/form-data; boundary=" + boundary; authenticatorRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate"); authenticatorRequest.KeepAlive = true; var cookieContainer = new CookieContainer(); cookieContainer.Add(new Cookie("sessionId", sessionId) { Domain = authenticatorRequest.RequestUri.Host }); authenticatorRequest.CookieContainer = cookieContainer; authenticatorRequest.Headers.Add(HttpRequestHeader.Cookie, $"sessionId={sessionId}"); using (Stream requestStream = authenticatorRequest.GetRequestStream()) { boundary = "--" + boundary; var boundarybytes = Encoding.ASCII.GetBytes(boundary + "\r\n"); requestStream.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"CSRFToken\"\r\n\r\n"; byte[] headerBytes = Encoding.UTF8.GetBytes(headerTemplate); requestStream.Write(headerBytes, 0, headerBytes.Length); headerBytes = Encoding.UTF8.GetBytes(csrfToken + "\r\n"); requestStream.Write(headerBytes, 0, headerBytes.Length); requestStream.Write(boundarybytes, 0, boundarybytes.Length); headerTemplate = "Content-Disposition: form-data; name=\"fileToPrint\"; filename=\"" + localFileDocument.Name + "\"\r\n"; headerBytes = Encoding.UTF8.GetBytes(headerTemplate); requestStream.Write(headerBytes, 0, headerBytes.Length); headerTemplate = "Content-Type: application/octet-stream\r\n\r\n"; headerBytes = Encoding.UTF8.GetBytes(headerTemplate); requestStream.Write(headerBytes, 0, headerBytes.Length); using (Stream stream = new FileStream(localFileDocument.FullName, FileMode.Open, FileAccess.Read)) { stream.CopyTo(requestStream); } headerTemplate = "\r\n"; headerBytes = Encoding.UTF8.GetBytes(headerTemplate); requestStream.Write(headerBytes, 0, headerBytes.Length); requestStream.Write(boundarybytes, 0, boundarybytes.Length); headerTemplate = "Content-Disposition: form-data; name=\"NumberOfCopies\"\r\n\r\n" + "1\r\n"; headerBytes = Encoding.UTF8.GetBytes(headerTemplate); requestStream.Write(headerBytes, 0, headerBytes.Length); requestStream.Write(boundarybytes, 0, boundarybytes.Length); headerTemplate = "Content-Disposition: form-data; name=\"EnableCollatedCopies\"\r\n\r\n" + "on\r\n"; headerBytes = Encoding.UTF8.GetBytes(headerTemplate); requestStream.Write(headerBytes, 0, headerBytes.Length); requestStream.Write(boundarybytes, 0, boundarybytes.Length); headerTemplate = "Content-Disposition: form-data; name=\"FormButtonSubmit\"\r\n\r\n" + "Print\r\n"; headerBytes = Encoding.UTF8.GetBytes(headerTemplate); requestStream.Write(headerBytes, 0, headerBytes.Length); var footerBoundary = boundary + "--\r\n"; boundarybytes = Encoding.ASCII.GetBytes(footerBoundary); requestStream.Write(boundarybytes, 0, boundarybytes.Length); } var configResponse = HttpMessenger.ExecuteRequest(authenticatorRequest); if (configResponse.StatusCode != HttpStatusCode.OK) { throw new WebException("Printing file through EWS failed."); } }