Esempio n. 1
0
        /// <summary>
        /// HTTP Web Request
        /// </summary>
        /// <param name="url"></param>
        /// <param name="webMethod">webMethod</param>
        /// <param name="cookies"></param>
        /// <param name="postDataValue"></param>
        /// <returns></returns>
        private static HttpWebResult PrepareInkWebRequest(HP.DeviceAutomation.IDevice device, Uri url, HttpVerb webMethod, string cookies, string postDataValue)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

            webRequest.Accept = "*/*";
            if (device is SiriusUIv3Device)
            {
                webRequest.Headers.Add("Accept-Language", "en-US");
                webRequest.ContentType = "text/xml";
            }
            else
            {
                webRequest.Headers.Add("Accept-Language", "en-US,en;q=0.5");
                webRequest.ContentType = "text/xml; charset=UTF-8";
            }
            webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            if (!string.IsNullOrEmpty(cookies))
            {
                webRequest.Headers.Add("Cookie", cookies);
            }

            webRequest.ServicePoint.Expect100Continue = false;
            webRequest.Method = webMethod.ToString();
            if (webMethod == HttpVerb.GET)
            {
                return(HttpWebEngine.Get(webRequest));
            }
            if (webMethod == HttpVerb.PUT)
            {
                return(HttpWebEngine.Put(webRequest, postDataValue));
            }
            return(null);
        }
Esempio n. 2
0
        /// <summary>
        /// Deletes CA certificate from inkjet printer
        /// </summary>
        /// <param name="printerIp"></param>
        /// <param name="authorization"></param>
        /// <param name="certificatePath"></param>
        public void DeleteCAFileInk(Uri printerIp, string authorization, string certificatePath)
        {
            //retrieve Url for deleting certificate
            string resourceUrl = GetCertificateUrl(printerIp, authorization, certificatePath);

            if (!string.IsNullOrEmpty(resourceUrl))
            {
                Uri            delCertUrl = new Uri($"{ (object)printerIp}{ (object)resourceUrl.TrimStart('/')}");
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(delCertUrl);
                webRequest.Accept  = "application/xml, text/xml, */*";
                webRequest.Referer = $"{printerIp}#hId-pgCertificates";
                webRequest.Headers.Add("X-Requested-With", "XMLHttpRequest");
                webRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
                webRequest.ContentLength = 0;
                if (!string.IsNullOrEmpty(authorization))
                {
                    webRequest.Headers.Add(HttpRequestHeader.Authorization, authorization);
                }

                var response = HttpWebEngine.Delete(webRequest, _userAgent);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    ExecutionServices.SystemTrace.LogDebug("Failed to delete certificate");
                    throw new WebException("Certificate deletion failed");
                }
                else
                {
                    ExecutionServices.SystemTrace.LogDebug("Deleted certificate");
                }
            }
            else
            {
                throw new WebException("Certificate does not exist on Printer");
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Retrieves certificate upload status
        /// </summary>
        /// <param name="printerIp"></param>
        /// <param name="authorization"></param>
        /// <returns></returns>
        private HttpWebResult GetUploadStatus(Uri printerIp, string authorization, string file)
        {
            Uri getCertInfo;

            if (Path.GetExtension(file).Contains("pfx", StringComparison.OrdinalIgnoreCase))
            {
                getCertInfo = new Uri(string.Format(Properties.Resources.UploadStatusPfx, printerIp));
            }
            else
            {
                getCertInfo = new Uri(string.Format(Properties.Resources.UploadStatus, printerIp));
            }

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(getCertInfo);

            webRequest.Headers.Add("X-Requested-With", "XMLHttpRequest");

            if (!string.IsNullOrEmpty(authorization))
            {
                webRequest.Headers.Add(HttpRequestHeader.Authorization, authorization);
            }

            var response = HttpWebEngine.Get(webRequest, _userAgent);

            return(response);
        }
Esempio n. 4
0
        /// <summary>
        /// Verifies if the certificate is installed/deleted for TPS printers
        /// </summary>
        /// <param name="printerIp"></param>
        /// <param name="authorization"></param>
        /// <param name="install">true if installed, false if deleted</param>
        /// <returns></returns>
        private bool VerifyCAUploadPhoenix(Uri printerIp, string authorization, bool install)
        {
            bool result = false;

            Uri certificateUrl = new Uri($"{printerIp}{Properties.Resources.URLPhoenixVerify}");

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(certificateUrl);

            if (!string.IsNullOrEmpty(authorization))
            {
                req.Headers.Add(HttpRequestHeader.Authorization, authorization);
            }

            // grab the response
            var verifyCertificate = HttpWebEngine.Get(req, _userAgent);

            if (verifyCertificate.StatusCode == HttpStatusCode.OK)
            {
                string source = verifyCertificate.Response;
                if (install)
                {
                    result = (source.Contains("class=\"buttonTxtSize\"") && source.Contains("name=\"ViewCACert\""));
                }
                else
                {
                    result = (source.Contains("class=\"buttonTxtSizeDisabled\"") && source.Contains("name=\"ViewCACert2\""));
                }
            }

            return(result);
        }
Esempio n. 5
0
        /// <summary>
        /// Installs CA certificate on Inkjet printer
        /// </summary>
        /// <param name="printerIp"></param>
        /// <param name="file"></param>
        /// <param name="authorization"></param>
        /// <param name="nameCollection"></param>
        public void InstallCAFileInk(Uri printerIp, string file, string authorization, NameValueCollection nameCollection)
        {
            Uri uploadUrl     = null;
            var fileExtension = Path.GetExtension(file);

            if (fileExtension != null && fileExtension.Equals(".cer", StringComparison.OrdinalIgnoreCase))
            {
                uploadUrl = new Uri($"{ (object)printerIp}{ (object)Properties.Resources.URLInstallInkCer}");
            }
            else
            {
                uploadUrl = new Uri($"{printerIp}{Properties.Resources.URLInstallInkPfx}");
            }

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uploadUrl);

            webRequest.Accept = "text/html, application/xhtml+xml, */*";
            webRequest.Headers.Add(HttpRequestHeader.Pragma, "no-cache");
            if (!string.IsNullOrEmpty(authorization))
            {
                webRequest.Headers.Add(HttpRequestHeader.Authorization, authorization);
            }
            try
            {
                var response = HttpWebEngine.UploadFile(webRequest, file, "certificate", nameCollection, _userAgent);

                if ((response.StatusCode == HttpStatusCode.OK) || (response.StatusCode == HttpStatusCode.Created))
                {
                    if (fileExtension != null && fileExtension.Equals(".cer", StringComparison.OrdinalIgnoreCase))
                    {
                        ExecutionServices.SystemTrace.LogDebug("Certificate installed!");
                        VerifyCAUploadInk(printerIp);
                    }
                    else
                    {
                        XmlDocument xDoc = new XmlDocument();
                        xDoc.LoadXml(response.Response);

                        string certError = xDoc.DocumentElement.GetElementsByTagName("cert:InterfaceError").Item(0).InnerText;
                        if (certError.Contains("invalidCertData"))
                        {
                            ExecutionServices.SystemTrace.LogDebug("File is unsupported file format");
                            throw new SiriusInvalidOperationException("Certificate is invalid");
                        }
                    }
                }
                else
                {
                    ExecutionServices.SystemTrace.LogDebug("Upload Failed");
                    throw new WebException("Upload Failed");
                }
            }
            catch (WebException ex)
            {
                ExecutionServices.SystemTrace.LogDebug("Upload Failed");
                throw new WebException("Upload Failed", ex);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Installs CA certificate on the printer
        /// </summary>
        /// <param name="printerIp"></param>
        /// <param name="file"></param>
        /// <param name="authorization"></param>
        /// <param name="nameCollection"></param>
        public void InstallCAFilePhoenix(Uri printerIp, string file, string authorization, NameValueCollection nameCollection)
        {
            Uri            uploadUrl  = new Uri($"{printerIp}{Properties.Resources.URLInstallPhoenix}");
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uploadUrl);

            webRequest.Accept = "text/html, application/xhtml+xml, */*";
            webRequest.Headers.Add(HttpRequestHeader.Pragma, "no-cache");
            if (!string.IsNullOrEmpty(authorization))
            {
                webRequest.Headers.Add(HttpRequestHeader.Authorization, authorization);
                webRequest.AllowAutoRedirect = false;
            }

            try
            {
                var response = HttpWebEngine.UploadFile(webRequest, file, "upFile", nameCollection, _userAgent);

                if (!string.IsNullOrEmpty(authorization))
                {
                    if (response.StatusCode == HttpStatusCode.Found)
                    {
                        response = GetUploadStatus(printerIp, authorization, file);
                        if (response.Response.Contains("The format of the file is invalid."))
                        {
                            ExecutionServices.SystemTrace.LogDebug("The format of the file is invalid.");
                            throw new FormatException("The format of the file is invalid.");
                        }
                    }
                }

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    response = GetUploadStatus(printerIp, authorization, file);
                    if (response.Response.Contains("The format of the file is invalid."))
                    {
                        ExecutionServices.SystemTrace.LogDebug("The format of the file is invalid.");
                        throw new FormatException("The format of the file is invalid.");
                    }

                    ExecutionServices.SystemTrace.LogDebug("Certificate installed!");

                    if (!VerifyCAUploadPhoenix(printerIp, authorization, true))
                    {
                        ExecutionServices.SystemTrace.LogDebug("Certificate upload verification failed");
                        throw new WebException("Certificate upload verification failed");
                    }
                }
                else
                {
                    throw new WebException("Upload Failed");
                }
            }
            catch (WebException ex)
            {
                throw new WebException("Upload Failed", ex);
            }
        }
Esempio n. 7
0
        private HttpWebResult ExecuteLoginWebService(Uri eprintLoginUrl)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(eprintLoginUrl);

            webRequest.Accept = "*/*";
            webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            webRequest.ContentType = "application/json; charset=UTF-8";
            webRequest.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8");
            string        postData    = $"{{\"userName\":\"{_activityData.ePrintAdminUser}\",\"password\":\"{_activityData.ePrintAdminPassword}\",\"createPersistentCookie\":false}}";
            HttpWebResult loginResult = HttpWebEngine.Post(webRequest, postData);

            return(loginResult);
        }
Esempio n. 8
0
        /// <summary>
        /// Deletes CA certificate from the printer
        /// </summary>
        /// <param name="printerIp"></param>
        /// <param name="authorizationPassword"></param>
        public void DeleteCAFilePhoenix(Uri printerIp, string authorizationPassword)
        {
            if (!VerifyCAUploadPhoenix(printerIp, authorizationPassword, true))
            {
                throw new InvalidOperationException("Printer does not have a CA Certificate");
            }

            string         postData   = "Finish=Finish";
            Uri            uploadUrl  = new Uri($"{printerIp}{Properties.Resources.URLPhoenixDelete}");
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uploadUrl);

            webRequest.ContentType = "application/x-www-form-urlencoded";
            if (!string.IsNullOrEmpty(authorizationPassword))
            {
                webRequest.Headers.Add(HttpRequestHeader.Authorization, authorizationPassword);
                webRequest.AllowAutoRedirect = false;
            }
            try
            {
                var postResponse = HttpWebEngine.Post(webRequest, postData, _userAgent);
                if (postResponse.StatusCode == HttpStatusCode.SeeOther)
                {
                    int    startindex  = postResponse.Response.IndexOf("A HREF=\"", StringComparison.OrdinalIgnoreCase) + 8;
                    int    stopindex   = postResponse.Response.IndexOf("\">Moved</A>", StringComparison.OrdinalIgnoreCase);
                    string redirectUrl = postResponse.Response.Substring(startindex, stopindex - startindex);

                    HttpWebRequest redirectRequest = (HttpWebRequest)WebRequest.Create(new Uri($"{printerIp}{redirectUrl.TrimStart('/')}"));
                    redirectRequest.Headers.Add(HttpRequestHeader.Authorization, authorizationPassword);
                    redirectRequest.Accept = "text/html, application/xhtml+xml, */*";
                    redirectRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
                    postResponse = HttpWebEngine.Get(redirectRequest, _userAgent);
                }

                if (postResponse.StatusCode == HttpStatusCode.OK)
                {
                    if (!VerifyCAUploadPhoenix(printerIp, authorizationPassword, false))
                    {
                        throw new WebException("Certificate delete verification failed");
                    }
                }
                else
                {
                    throw new WebException("Certificate delete failed");
                }
            }
            catch (WebException ex)
            {
                throw new WebException("Certificate delete failed", ex);
            }
        }
Esempio n. 9
0
        private void ePrintSendPrintJob(EprintAdminTask eprintTask, CookieCollection loginCookie)
        {
            //Get Request
            Uri            getsendPrintUrl = new Uri($@"{_ePrintServerType}://{_ePrintServerIp}//cloudprintadmin/services/SubmitTest.aspx");
            HttpWebRequest getsendPrint    = (HttpWebRequest)WebRequest.Create(getsendPrintUrl);

            getsendPrint.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8");
            getsendPrint.Accept          = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            getsendPrint.CookieContainer = new CookieContainer();
            getsendPrint.CookieContainer.Add(loginCookie);
            getsendPrint.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
            getsendPrint.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            HttpWebResult getsendPrintResponse = HttpWebEngine.Get(getsendPrint);

            ExecutionServices.SystemTrace.LogInfo($"Requesting to Print {Environment.UserName} as a {eprintTask.Operation} ");
            //get admin cookie
            CookieCollection adminCookie   = new CookieCollection();
            string           setCookie     = getsendPrintResponse.Headers.Get("Set-Cookie");
            string           trimmedcookie = setCookie.Substring(12, setCookie.IndexOf(";", StringComparison.Ordinal) - 12);

            adminCookie.Add(new Cookie("AdminCookie", trimmedcookie)
            {
                Domain = _ePrintServerIp
            });
            //Post request
            Uri            sendPrintUrl = new Uri($@"{_ePrintServerType}://{_ePrintServerIp}/cloudprintadmin/services/SubmitTest.aspx");
            HttpWebRequest sendPrintReq = (HttpWebRequest)WebRequest.Create(sendPrintUrl);

            sendPrintReq.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8");
            sendPrintReq.Accept          = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            sendPrintReq.ContentType     = "application/x-www-form-urlencoded";
            sendPrintReq.CookieContainer = new CookieContainer();
            sendPrintReq.CookieContainer.Add(loginCookie);
            sendPrintReq.CookieContainer.Add(adminCookie);
            sendPrintReq.Headers.Add("Accept-Encoding", "gzip, deflate");
            string postData = string.Format(Properties.Resources.SendPrintJobPostData, (HttpUtility.UrlEncode(ExtractViewState(getsendPrintResponse.Response))), _device.Address);

            getsendPrintResponse = HttpWebEngine.Post(sendPrintReq, postData);
            if (getsendPrintResponse.StatusCode.Equals(HttpStatusCode.OK))
            {
                ExecutionServices.SystemTrace.LogInfo($"Successfully sent print job to { (object)_device.Address} ");
                eprintTask.Status = "Passed";
            }
            else
            {
                ExecutionServices.SystemTrace.LogError($"Could not send print job to IP {_device.Address} ERROR:Status Code:{getsendPrintResponse.StatusCode} ");

                eprintTask.Status = "Failed";
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Verifies if the certificate is installed for inkjet printers
        /// </summary>
        /// <param name="printerIp"></param>
        private void VerifyCAUploadInk(Uri printerIp)
        {
            Uri            certificateUrl = new Uri($"{printerIp}{Properties.Resources.URLInkVerify}");
            HttpWebRequest req            = (HttpWebRequest)WebRequest.Create(certificateUrl);

            var verifyCertificate = HttpWebEngine.Get(req, _userAgent);

            if (verifyCertificate.StatusCode == HttpStatusCode.NoContent)
            {
                throw new WebException("Certificate upload verification failed");
            }

            ExecutionServices.SystemTrace.LogDebug("Certificate upload verified");
        }
Esempio n. 11
0
        public HttpWebResult GetSessionIdRequest(Uri printerIp, string authorization)
        {
            Uri statusUrl = new Uri($"{printerIp}{Properties.Resources.URLJediHome}");

            HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(statusUrl);

            getRequest.ContentType = "application/x-www-form-urlencoded";
            getRequest.Headers.Add(HttpRequestHeader.Pragma, "no-cache");
            getRequest.Accept = Properties.Resources.GetRequestAccept;
            getRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");

            if (!string.IsNullOrEmpty(authorization))
            {
                getRequest.Headers.Add(HttpRequestHeader.Authorization, authorization);
                getRequest.AllowAutoRedirect = false;
            }

            return(HttpWebEngine.Get(getRequest, _userAgent));
        }
Esempio n. 12
0
        /// <summary>
        /// Close the Wizard page of CA certificate installation for VEP printers
        /// </summary>
        /// <param name="printerIp"></param>
        /// <param name="authorization"></param>
        /// <param name="wizardid"></param>
        private void CloseWizard(Uri printerIp, string authorization, string wizardid)
        {
            Uri            uploadUrl = new Uri($"{printerIp}{Properties.Resources.URLJediClose}");
            HttpWebRequest oKRequest = (HttpWebRequest)WebRequest.Create(uploadUrl);

            oKRequest.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
            CookieCollection cookies = new CookieCollection {
                new Cookie("wizardid", wizardid)
                {
                    Domain = "localhost"
                }
            };

            oKRequest.CookieContainer = new CookieContainer();
            oKRequest.CookieContainer.Add(cookies);
            oKRequest.Accept      = Properties.Resources.WebRequestAccept;
            oKRequest.ContentType = "application/x-www-form-urlencoded";
            oKRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            oKRequest.Headers.Add("Accept-Language", "en-US");
            oKRequest.Host      = uploadUrl.Host;
            oKRequest.KeepAlive = true;

            string optionData = "ok=OK";

            if (!string.IsNullOrEmpty(authorization))
            {
                oKRequest.Headers.Add(HttpRequestHeader.Authorization, authorization);
                oKRequest.AllowAutoRedirect = false;
            }
            try
            {
                var request = HttpWebEngine.Post(oKRequest, optionData, _userAgent);
                if (request.StatusCode != HttpStatusCode.OK)
                {
                    throw new WebException("Certificate Wizard closure failed");
                }
            }
            catch (WebException ex)
            {
                throw new WebException("Certificate Wizard closure failed", ex);
            }
        }
        private static void SendNewLicenseRequest(License license, FrameworkServer server)
        {
            if (license.Owners.Count == 0)
            {
                LogError($"Unable to request new license for '{server.HostName}'.  No contacts specified.");
                return;
            }

            LicenseOwner owner          = license.Owners.FirstOrDefault();
            string       formattedOwner = owner.Contact.Split('@')[0];
            string       requestData    = string.Format(Resource.LicenseRequestData, formattedOwner, BuildRequestDetails(license, server));

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Resource.LicenseTicketURL + "?" + requestData);

            webRequest.ContentType           = "application/x-www-form-urlencoded";
            webRequest.Proxy                 = null;
            webRequest.UseDefaultCredentials = true; // Uses Windows Credentials to verify user
            HttpWebResult webResult = HttpWebEngine.Get(webRequest);

            LogInfo($"Response from ACT Solution Support Ticket System: {webResult.Response}");
        }
Esempio n. 14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="printerIp"></param>
        /// <param name="authorization"></param>
        /// <param name="cookieCollection"></param>
        /// <returns></returns>
        private string GetCertificateUrl(string printerIp, string authorization, out CookieCollection cookieCollection)
        {
            Uri getCertInfo = new Uri($"{printerIp}/Security/CACertificate/Info");

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(getCertInfo);

            webRequest.Headers.Add("X-Requested-With", "XMLHttpRequest");
            if (!string.IsNullOrEmpty(authorization))
            {
                webRequest.Headers.Add(HttpRequestHeader.Authorization, authorization);
            }

            cookieCollection = new CookieCollection();
            var response = HttpWebEngine.Get(webRequest, _userAgent);

            XmlDocument xDoc = new XmlDocument();

            xDoc.LoadXml(response.Response);

            return(xDoc.DocumentElement.GetElementsByTagName("cert:ResourceURL").Item(0).InnerText);
        }
        /// <summary>
        /// Checks whether Printer is in ready state
        /// </summary>
        /// <param name="address">address</param>
        private bool IsPrinterAwake(string address)
        {
            if (!string.IsNullOrEmpty(address))
            {
                var navigateUrl = new Uri($"https://{ (object)address}{ (object)"/hp/device/SignIn/Index"}");
                var webRequest  = HttpWebRequestValidate(navigateUrl);
                webRequest.CookieContainer = new CookieContainer();
                webRequest.Headers.Add(HttpRequestHeader.Authorization, "Basic " + _strAuthorization);
                HttpWebEngine.Post(webRequest, string.Format(GetKey("SignInIndexConfig"), UserName));

                navigateUrl = new Uri($"https://{address}");
                webRequest  = HttpWebRequestValidate(navigateUrl);
                var webResult = HttpWebEngine.Get(webRequest);
                ExecutionServices.SystemTrace.LogDebug("Status Code: " + webResult.StatusCode);
                if (webResult.StatusCode.Equals(HttpStatusCode.OK))
                {
                    return(true);
                }
            }
            return(false);
        }
Esempio n. 16
0
        /// <summary>
        /// Checks if the certificate is already installed and retrieves the Url
        /// </summary>
        /// <param name="printerIp"></param>
        /// <param name="authorization"></param>
        /// <param name="certificatePath"></param>
        /// <returns></returns>
        private string GetCertificateUrl(Uri printerIp, string authorization, string certificatePath)
        {
            if (Path.GetExtension(certificatePath).Contains("cer", StringComparison.OrdinalIgnoreCase))
            {
                X509Certificate2 certificateOptions      = new X509Certificate2(X509Certificate2.CreateFromCertFile(certificatePath));
                string           certificateSerialNumber = certificateOptions.SerialNumber;

                Uri certificateUrl = new Uri($"{printerIp}Security/CACertificate/Info");

                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(certificateUrl);
                webRequest.Headers.Add("X-Requested-With", "XMLHttpRequest");
                if (!string.IsNullOrEmpty(authorization))
                {
                    webRequest.Headers.Add(HttpRequestHeader.Authorization, authorization);
                }

                var response = HttpWebEngine.Get(webRequest, _userAgent);

                if (string.IsNullOrEmpty(response.Response))
                {
                    return(null);
                }

                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(response.Response);

                int count = xDoc.DocumentElement.GetElementsByTagName("cert:SerialNumber").Count;
                for (int index = 0; index < count; index++)
                {
                    string text = xDoc.DocumentElement.GetElementsByTagName("cert:SerialNumber").Item(index).InnerText;
                    string printerSerialNumber = Regex.Replace(text.Trim().ToLower(CultureInfo.InvariantCulture), ":", "");
                    if (certificateSerialNumber.Equals(printerSerialNumber)) //EqualsIgnoreCase
                    {
                        return(xDoc.DocumentElement.GetElementsByTagName("cert:ResourceURL").Item(index).InnerText);
                    }
                }
            }
            return(null);
        }
Esempio n. 17
0
        public HttpWebResult GetWizardIdResponse(Uri printerIp, string authorization, CookieCollection cookieCollection)
        {
            Uri uploadUrl = new Uri($"{printerIp}{Properties.Resources.URLJediWizard}");

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uploadUrl);

            webRequest.Accept = Properties.Resources.WebRequestAccept;
            webRequest.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
            webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            webRequest.ContentType = "application/x-www-form-urlencoded";

            if (!string.IsNullOrEmpty(authorization))
            {
                webRequest.Headers.Add(HttpRequestHeader.Authorization, authorization);
                webRequest.AllowAutoRedirect = false;
            }

            string postData = string.Format(Properties.Resources.WizardRequest);

            webRequest.CookieContainer = new CookieContainer();
            webRequest.CookieContainer.Add(cookieCollection);
            return(HttpWebEngine.Post(webRequest, postData, _userAgent));
        }
Esempio n. 18
0
        /// <summary>
        /// VEP HTTP Web Request
        /// </summary>
        /// <param name="url"></param>
        /// <param name="webMethod">webMethod</param>
        /// <param name="cookies"></param>
        /// <param name="profilesValue"></param>
        /// <returns></returns>
        private static HttpWebResult PrepareVEPWebRequest(Uri url, HttpVerb webMethod, string cookies, string profilesValue = null)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

            webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            webRequest.Headers.Add("Accept-Language", "en-US,en;q=0.5");
            webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            if (!string.IsNullOrEmpty(cookies))
            {
                webRequest.Headers.Add("Cookie", cookies);
            }
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method      = webMethod.ToString();
            if (webMethod == HttpVerb.GET)
            {
                return(HttpWebEngine.Get(webRequest));
            }
            if (webMethod == HttpVerb.POST)
            {
                return(HttpWebEngine.Post(webRequest, profilesValue));
            }
            return(null);
        }
Esempio n. 19
0
        private bool VerifyCAUploadJedi(Uri printerIp, string authorization, bool install)
        {
            bool result;

            Uri certificateUrl = new Uri($"{printerIp}{Properties.Resources.URLJediVerify}");

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(certificateUrl);

            if (!string.IsNullOrEmpty(authorization))
            {
                req.Headers.Add(HttpRequestHeader.Authorization, authorization);
            }

            // grab the response
            try
            {
                var verifyCertificate = HttpWebEngine.Get(req, _userAgent);
                if (verifyCertificate.StatusCode == HttpStatusCode.OK)
                {
                    string source = verifyCertificate.Response;
                    result = source.Contains(install ? "name=\"CAview\"" : "disabled=\"disabled\" name=\"CAviewdis\"");
                }
                else
                {
                    string errorStatus = "Certificate upload verification failed. Status Code: " + verifyCertificate.StatusCode;
                    throw new WebException(errorStatus);
                }
            }
            catch (WebException ex)
            {
                string errorStatus = "Certificate upload verification failed.";
                throw new WebException(errorStatus, ex);
            }

            return(result);
        }
Esempio n. 20
0
        /// <summary>
        /// Executes the Capella webservice for HPAC
        /// </summary>
        /// <param name="url">The domain of the webservice</param>
        /// <param name="service">The service name or location</param>
        /// <param name="function">The function of the webservice</param>
        /// <param name="args">Arguments that the webservice uses to process requests</param>
        /// <returns>A string of XML data about the response</returns>
        private static XDocument ExecuteWebService(string url, string service, string function, string args)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create($"{url}/{service}/{function}");

            webRequest.ContentType           = "application/x-www-form-urlencoded";
            webRequest.Proxy                 = null;
            webRequest.UseDefaultCredentials = true; // Uses Windows Credentials to verify user
            byte[] bytes = Encoding.ASCII.GetBytes(args);

            // Get the response
            try
            {
                string response = HttpWebEngine.Post(webRequest, bytes).Response;
                if (response?.StartsWith("<") != true)
                {
                    response = string.Format("<response>{0}</response>", response);
                }
                return(XDocument.Parse(response));
            }
            catch (WebException ex)
            {
                throw new WebException($"Unable to get webResponse object for {webRequest.RequestUri.ToString()}", ex);
            }
        }
        private string ExecuteRestApi(int pinNumber, bool pinStatus)
        {
            Uri url = new Uri(_baseUri, $"?pinId={pinNumber}&status={Convert.ToInt32(pinStatus)}");

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

            webRequest.ContentType   = "application/x-www-form-urlencoded";
            webRequest.ContentLength = 0;

            try
            {
                var webResult = HttpWebEngine.Post(webRequest, string.Empty);

                if (webResult.StatusCode == HttpStatusCode.OK || webResult.StatusCode == HttpStatusCode.Accepted)
                {
                    return(string.IsNullOrEmpty(webResult.Response)? "OK": webResult.Response);
                }
            }
            catch (WebException)
            {
            }

            return(string.Empty);
        }
Esempio n. 22
0
        /// <summary>
        /// Close the Wizard page of CA certificate installation for VEP printers
        /// </summary>
        /// <param name="printerIp"></param>
        /// <param name="authorization"></param>
        /// <param name="wizardid"></param>
        /// <param name="paramName"></param>
        /// <param name="hideValue"></param>
        private void CloseWizard(Uri printerIp, string authorization, string wizardid, string paramName, string hideValue)
        {
            Uri            uploadUrl = new Uri($"{printerIp}{Properties.Resources.URLJediError}");
            HttpWebRequest oKRequest = (HttpWebRequest)WebRequest.Create(uploadUrl);

            oKRequest.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
            CookieCollection cookies = new CookieCollection {
                new Cookie("wizardid", wizardid)
                {
                    Domain = "localhost"
                }
            };

            oKRequest.CookieContainer = new CookieContainer();
            oKRequest.CookieContainer.Add(cookies);
            oKRequest.Accept      = Properties.Resources.WebRequestAccept;
            oKRequest.ContentType = "application/x-www-form-urlencoded";
            oKRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            oKRequest.Headers.Add("Accept-Language", "en-US");
            oKRequest.Host      = uploadUrl.Host;
            oKRequest.KeepAlive = true;

            string optionData = "ok=OK";

            if (!string.IsNullOrEmpty(authorization))
            {
                oKRequest.Headers.Add(HttpRequestHeader.Authorization, authorization);
                oKRequest.AllowAutoRedirect = false;
            }
            try
            {
                var request = HttpWebEngine.Post(oKRequest, optionData, _userAgent);
                if (request.StatusCode != HttpStatusCode.OK)
                {
                    throw new WebException("Certificate Wizard closure failed");
                }
            }
            catch (WebException ex)
            {
                throw new WebException("Certificate Wizard closure failed", ex);
            }

            //Step 2 : Upload Empty File
            NameValueCollection nvc = new NameValueCollection {
                { "Hide", hideValue }, { "Cancel", "Cancel" }
            };

            uploadUrl = new Uri($"{printerIp}{Properties.Resources.URLJediUpload}");
            HttpWebRequest cancelRequest = (HttpWebRequest)WebRequest.Create(uploadUrl);

            cancelRequest.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
            cancelRequest.CookieContainer = new CookieContainer();
            cancelRequest.CookieContainer.Add(cookies);

            cancelRequest.Accept = Properties.Resources.WebRequestAccept;
            cancelRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            cancelRequest.ContentType = "application/x-www-form-urlencoded";
            cancelRequest.Headers.Add("Accept-Language", "en-US");
            cancelRequest.Host      = uploadUrl.Host;
            cancelRequest.KeepAlive = true;
            cancelRequest.ServicePoint.Expect100Continue = false;
            if (!string.IsNullOrEmpty(authorization))
            {
                cancelRequest.Headers.Add(HttpRequestHeader.Authorization, authorization);
                cancelRequest.AllowAutoRedirect = false;
            }

            try
            {
                var uploadResponse = HttpWebEngine.UploadFile(cancelRequest, "", paramName, nvc, _userAgent);
                if (uploadResponse.StatusCode != HttpStatusCode.OK)
                {
                    throw new WebException("Certificate Wizard closure failed");
                }
            }
            catch (WebException ex)
            {
                throw new WebException("Certificate Wizard closure failed", ex);
            }
        }
        /// <summary>
        /// Navigate to Settings Configuration Page to fetch values
        /// </summary>
        /// <param name="baseUrl"></param>
        private void NavigateSettingsConfiguration(Uri baseUrl)
        {
            _cookies = new CookieCollection();

            Uri targetUrl  = new Uri($"{baseUrl}{"hp/device/SignIn/Index"}");
            var webRequest = HttpWebRequestValidate(targetUrl);

            webRequest.CookieContainer = new CookieContainer();
            webRequest.CookieContainer.Add(_cookies);
            HttpWebEngine.Post(webRequest, string.Format(GetKey("SignInIndexConfig"), UserName));

            string authorization = ConvertToBase64Encoding("admin:public");

            targetUrl  = new Uri($"{baseUrl}{"hp/jetdirect"}");
            webRequest = HttpWebRequestValidate(targetUrl);
            webRequest.Headers.Add(HttpRequestHeader.Authorization, "Basic " + authorization);
            webRequest.CookieContainer = new CookieContainer();
            webRequest.CookieContainer.Add(_cookies);
            HttpWebEngine.Get(webRequest);

            targetUrl  = new Uri($"{baseUrl}{"security_status.html"}");
            webRequest = HttpWebRequestValidate(targetUrl);
            webRequest.Headers.Add(HttpRequestHeader.Authorization, "Basic " + authorization);
            webRequest.CookieContainer = new CookieContainer();
            webRequest.CookieContainer.Add(_cookies);
            var webResult = HttpWebEngine.Get(webRequest);

            HtmlDocument htmlDoc = new HtmlDocument
            {
                OptionFixNestedTags = true,
                OptionOutputAsXml   = true
            };

            // There are various options, set as needed

            string cleanedHtmlResult = webResult.Response.Replace("&nbsp", "").Trim();

            cleanedHtmlResult = cleanedHtmlResult.Replace(Environment.NewLine, string.Empty).Replace("\n", "").Trim();
            cleanedHtmlResult = cleanedHtmlResult.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?> ", "");
            cleanedHtmlResult = cleanedHtmlResult.Replace("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"> ", "");

            // Get all tables in the document
            htmlDoc.LoadHtml(cleanedHtmlResult.Trim());
            // Get all tables in the document

            HtmlNodeCollection tdNodes = htmlDoc.DocumentNode.SelectNodes("//td[@class='noWrapPadRt']");
            int count = 1;

            foreach (var node in tdNodes)
            {
                if (!string.IsNullOrEmpty(node.InnerText))
                {
                    if (!_pairedValues.ContainsKey(node.InnerText.Trim()))
                    {
                        _pairedValues.Add(node.InnerText.Trim(), node.ParentNode.ChildNodes[3].InnerText.Trim());
                        ExecutionServices.SystemTrace.LogDebug(node.InnerText.Trim() + "->" + node.ParentNode.ChildNodes[3].InnerText.Trim());
                    }
                    else
                    {
                        _pairedValues.Add(node.InnerText.Trim() + "_" + count, node.ParentNode.ChildNodes[3].InnerText.Trim());
                        ExecutionServices.SystemTrace.LogDebug(node.InnerText.Trim() + "_" + count + "->" + node.ParentNode.ChildNodes[3].InnerText.Trim());
                        count++;
                    }
                }
            }
        }
        /// <summary>
        /// Setting Basic/Enhanced Security Settings
        /// </summary>
        /// <param name="printer">printer Info</param>
        /// <param name="securityType"> Security Configuration Type</param>
        private void BasicEnhancedSecurityConfig(PrintDeviceInfo printer, SecurityConfigurationType securityType)
        {
            _cookies = new CookieCollection();
            Uri baseUri = new Uri($"https://{printer.Address}");

            if (!string.IsNullOrEmpty(printer.AdminPassword))
            {
                _authorizationRequired = true;
                Uri url = new Uri(baseUri, "hp/device/SignIn/Index");
                _webRequest = HttpWebRequestValidate(url);
                _webRequest.CookieContainer = new CookieContainer();
                _webRequest.CookieContainer.Add(_cookies);
                _webRequest.Headers.Add(HttpRequestHeader.Authorization, "Basic " + _strAuthorization);
                _result = HttpWebEngine.Post(_webRequest, string.Format(GetKey("SignInIndexConfig"), UserName));
            }
            else
            {
                _configUrl  = new Uri(baseUri, "welcome.html");
                _webRequest = PrepareHttpWebRequest(_configUrl);
                _result     = HttpWebEngine.Get(_webRequest);
                if (_result.StatusCode == 0)
                {
                    _authorizationRequired = true;
                    _webRequest            = PrepareHttpWebRequest(_configUrl);
                    _result = HttpWebEngine.Get(_webRequest);
                }
            }

            _cookies   = _result.Cookies;
            _configUrl = new Uri(baseUri, "welcome.html/config");

            _webRequest = PrepareHttpWebRequest(_configUrl);
            _result     = HttpWebEngine.Post(_webRequest, GetKey("WelcomeConfig"));

            ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");

            int    startindex        = _result.Response.IndexOf("Hide\" VALUE=\"", StringComparison.OrdinalIgnoreCase) + 13;
            string truncatedResponse = _result.Response.Substring(startindex);
            int    endIndex          = truncatedResponse.IndexOf("\">", StringComparison.OrdinalIgnoreCase);
            string hideValue         = truncatedResponse.Substring(0, endIndex);

            _configUrl  = new Uri(baseUri, "level.html/config");
            _webRequest = PrepareHttpWebRequest(_configUrl);
            _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("LevelConfig"), securityType, hideValue));
            ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");

            _configUrl  = new Uri(baseUri, "password.html/config");
            _webRequest = PrepareHttpWebRequest(_configUrl);
            _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("PasswordConfig"), printer.AdminPassword, hideValue));
            ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");

            if (securityType == SecurityConfigurationType.Enhanced)
            {
                _configUrl  = new Uri(baseUri, "snmp.html/config");
                _webRequest = PrepareHttpWebRequest(_configUrl);
                _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("SNMPConfig"), _activityData.SnmpV3Enhanced, hideValue));
                ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{ (object)_configUrl.AbsoluteUri} Status:{ (object)_result.StatusCode}");

                _configUrl  = new Uri(baseUri, "snmpv3_creds.html/config");
                _webRequest = PrepareHttpWebRequest(_configUrl);
                _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("SNMPV3Config"), _activityData.Snmpv3UserName, _activityData.AuthenticationPassphraseProtocol, _activityData.PrivacyPassphraseProtocol, hideValue));
                ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{ (object)_configUrl.AbsoluteUri} Status:{ (object)_result.StatusCode}");

                _configUrl  = new Uri(baseUri, "snmp_legacy.html/config");
                _webRequest = PrepareHttpWebRequest(_configUrl);
                _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("SNMPLegacy"), _activityData.Snmpv1v2ReadOnlyAccess, hideValue));
                ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");
            }

            _configUrl  = new Uri(baseUri, "review.html/config");
            _webRequest = PrepareHttpWebRequest(_configUrl);
            _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("ReviewConfig"), hideValue));
            ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");

            PowerCyclePrinter(printer.Address);

            ValidateEncryption(baseUri, securityType);
        }
        /// <summary>
        /// Setting Custom Security Settings
        /// </summary>
        /// <param name="printer">printer Info</param>
        /// <param name="securityType"> Security Configuration Type</param>
        private void CustomSecurityConfiguration(PrintDeviceInfo printer, SecurityConfigurationType securityType)
        {
            _cookies = new CookieCollection();
            Uri baseUri = new Uri($"https://{printer.Address}");

            if (!string.IsNullOrEmpty(printer.AdminPassword))
            {
                _authorizationRequired = true;
                Uri url = new Uri(baseUri, "hp/device/SignIn/Index");
                _webRequest = HttpWebRequestValidate(url);
                _webRequest.CookieContainer = new CookieContainer();
                _webRequest.CookieContainer.Add(_cookies);
                _webRequest.Headers.Add(HttpRequestHeader.Authorization, "Basic " + _strAuthorization);
                _result = HttpWebEngine.Post(_webRequest, string.Format(GetKey("SignInIndexConfig"), UserName));
            }
            else
            {
                _configUrl = new Uri(baseUri, "welcome.html");

                _webRequest = PrepareHttpWebRequest(_configUrl);
                _result     = HttpWebEngine.Get(_webRequest);
                if (_result.StatusCode == 0)
                {
                    _authorizationRequired = true;
                    _webRequest            = PrepareHttpWebRequest(_configUrl);
                    _result = HttpWebEngine.Get(_webRequest);
                }
            }
            _cookies = _result.Cookies;

            _configUrl  = new Uri(baseUri, "welcome.html/config");
            _webRequest = PrepareHttpWebRequest(_configUrl);
            _result     = HttpWebEngine.Post(_webRequest, GetKey("WelcomeConfig"));
            ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");

            int    startindex        = _result.Response.IndexOf("Hide\" VALUE=\"", StringComparison.OrdinalIgnoreCase) + 13;
            string truncatedResponse = _result.Response.Substring(startindex);
            int    endIndex          = truncatedResponse.IndexOf("\">", StringComparison.OrdinalIgnoreCase);
            string hideValue         = truncatedResponse.Substring(0, endIndex);

            _configUrl  = new Uri(baseUri, "level.html/config");
            _webRequest = PrepareHttpWebRequest(_configUrl);
            _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("LevelConfig"), securityType, hideValue));
            ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");

            _configUrl  = new Uri(baseUri, "password.html/config");
            _webRequest = PrepareHttpWebRequest(_configUrl);
            _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("PasswordConfig"), printer.AdminPassword, hideValue));
            ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");

            _configUrl  = new Uri(baseUri, "websecurity/http_mgmt.html/config");
            _webRequest = PrepareHttpWebRequest(_configUrl);
            _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("WebSecurityConfig"), _activityData.EncryptionStrength.ToLower(CultureInfo.InvariantCulture), hideValue));
            ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");

            _configUrl  = new Uri(baseUri, "mgmt_protocols.html/config");
            _webRequest = PrepareHttpWebRequest(_configUrl);
            _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("MgmtConfig"), hideValue));
            ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");

            _configUrl  = new Uri(baseUri, "snmp.html/config");
            _webRequest = PrepareHttpWebRequest(_configUrl);
            _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("SNMPCustomConfig"), hideValue));
            ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");

            _configUrl  = new Uri(baseUri, "snmpv1v2_creds.html/config");
            _webRequest = (HttpWebRequest)WebRequest.Create(_configUrl);
            _webRequest = PrepareHttpWebRequest(_configUrl);
            _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("SNMPV1V2Config"), hideValue));
            ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");

            _configUrl  = new Uri(baseUri, "acl.html/config");
            _webRequest = PrepareHttpWebRequest(_configUrl);
            _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("ACLConfig"), _activityData.AccessControlIpv4, _activityData.Mask, hideValue));
            ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");

            _configUrl  = new Uri(baseUri, "protocols.html/config");
            _webRequest = PrepareHttpWebRequest(_configUrl);
            _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("ProtocolConfig"), hideValue));
            ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");

            int    startIndex   = _result.Response.IndexOf("SuserID\">", StringComparison.OrdinalIgnoreCase) + 9;
            string tempResponse = _result.Response.Substring(startIndex);

            endIndex     = tempResponse.IndexOf(" / ", StringComparison.OrdinalIgnoreCase);
            tempResponse = tempResponse.Substring(0, endIndex);

            _configUrl  = new Uri(baseUri, "dot1x_config.htm/config");
            _webRequest = PrepareHttpWebRequest(_configUrl);
            _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("Dot1xConfig"), tempResponse, _activityData.AuthenticationPassword, _activityData.AuthenticationPassword, hideValue));
            ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");

            _configUrl  = new Uri(baseUri, "review.html/config");
            _webRequest = PrepareHttpWebRequest(_configUrl);
            _result     = HttpWebEngine.Post(_webRequest, string.Format(GetKey("ReviewConfig"), hideValue));
            ExecutionServices.SystemTrace.LogDebug($"Navigating to Url:{_configUrl.AbsoluteUri} Status:{_result.StatusCode}");

            PowerCyclePrinter(printer.Address);

            ValidateEncryption(baseUri, securityType);
        }
Esempio n. 26
0
        /// <summary>
        /// Deletes CA certificate from the printer
        /// </summary>
        /// <param name="printerIp"></param>
        /// <param name="authorizationPassword"></param>
        /// <param name="hostName"></param>
        public void DeleteCAFileJedi(Uri printerIp, string authorizationPassword, string hostName)
        {
            if (!VerifyCAUploadJedi(printerIp, authorizationPassword, true))
            {
                throw new InvalidOperationException("Printer does not have a CA Certificate");
            }

            //Retrieve Session ID
            Uri statusUrl = new Uri($"{printerIp}{Properties.Resources.URLJediHome}");

            HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(statusUrl);

            getRequest.ContentType = "application/x-www-form-urlencoded";
            getRequest.Headers.Add(HttpRequestHeader.Pragma, "no-cache");
            getRequest.Accept = Properties.Resources.GetRequestAccept;
            getRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");

            if (!string.IsNullOrEmpty(authorizationPassword))
            {
                getRequest.Headers.Add(HttpRequestHeader.Authorization, authorizationPassword);
                getRequest.AllowAutoRedirect = false;
            }

            HttpWebResult webResultGetReqeust = HttpWebEngine.Get(getRequest, _userAgent);

            var cookies = webResultGetReqeust.Cookies;

            for (int i = 0; i < webResultGetReqeust.Headers.Count; i++)
            {
                if (webResultGetReqeust.Headers.Get(i).Contains("sessionId"))
                {
                    string strTemp = webResultGetReqeust.Headers.Get(i);
                    strTemp = strTemp.Replace("sessionId=", "");
                    strTemp = strTemp.Replace("; path=/;", "");
                    cookies.Add(new Cookie("sessionId", strTemp)
                    {
                        Domain = "localhost"
                    });
                }
            }

            //Retrieve WizardID and HideValue
            Uri uploadUrl = new Uri($"{printerIp}{Properties.Resources.URLJediDeleteWizard}");

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uploadUrl);

            webRequest.Accept = Properties.Resources.WebRequestAccept;
            webRequest.Headers.Add(HttpRequestHeader.Pragma, "no-cache");
            webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            webRequest.ContentType = "application/x-www-form-urlencoded";

            if (!string.IsNullOrEmpty(authorizationPassword))
            {
                webRequest.Headers.Add(HttpRequestHeader.Authorization, authorizationPassword);
                webRequest.AllowAutoRedirect = false;
            }

            string postData = string.Format(Properties.Resources.ConfigRequestJediDelete, hostName);

            var getResponse = HttpWebEngine.Post(webRequest, postData, _userAgent);

            string wizardid          = getResponse.Headers.Get("Set-Cookie");
            int    startindex        = getResponse.Response.IndexOf("Hide\" VALUE=\"", StringComparison.OrdinalIgnoreCase) + 13;
            string truncatedResponse = getResponse.Response.Substring(startindex);
            int    endIndex          = truncatedResponse.IndexOf("\">", StringComparison.OrdinalIgnoreCase);
            string hideValue         = truncatedResponse.Substring(0, endIndex);

            //Step 1
            uploadUrl = new Uri($"{printerIp}{Properties.Resources.URLJediCookie}");
            HttpWebRequest optionRequest = (HttpWebRequest)WebRequest.Create(uploadUrl);

            optionRequest.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
            wizardid = wizardid.Replace("wizardid=", "");
            wizardid = wizardid.Replace(";PATH=/;SECURE", "");
            cookies.Add(new Cookie("wizardid", wizardid)
            {
                Domain = "localhost"
            });

            optionRequest.CookieContainer = new CookieContainer();
            optionRequest.CookieContainer.Add(cookies);

            optionRequest.Accept      = Properties.Resources.WebRequestAccept;
            optionRequest.ContentType = "application/x-www-form-urlencoded";
            optionRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            optionRequest.Headers.Add("Accept-Language", "en-US");
            optionRequest.Host      = uploadUrl.Host;
            optionRequest.KeepAlive = true;

            string postData1 = Properties.Resources.OptionRequestJediDelete + hideValue;

            if (!string.IsNullOrEmpty(authorizationPassword))
            {
                optionRequest.Headers.Add(HttpRequestHeader.Authorization, authorizationPassword);
                optionRequest.AllowAutoRedirect = false;
            }

            try
            {
                var optionResponse = HttpWebEngine.Post(optionRequest, postData1, _userAgent);

                if (optionResponse.StatusCode != HttpStatusCode.OK)
                {
                    throw new WebException("Certificate option POST failed");
                }
            }
            catch (WebException ex)
            {
                throw new WebException("Certificate option POST failed", ex);
            }

            //Step 2
            uploadUrl = new Uri($"{printerIp}{Properties.Resources.URLJediFinish}");
            HttpWebRequest delRequest = (HttpWebRequest)WebRequest.Create(uploadUrl);

            delRequest.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
            wizardid = wizardid.Replace("wizardid=", "");
            wizardid = wizardid.Replace(";PATH=/", "");
            cookies.Add(new Cookie("wizardid", wizardid)
            {
                Domain = "localhost"
            });

            delRequest.CookieContainer = new CookieContainer();
            delRequest.CookieContainer.Add(cookies);

            delRequest.Accept      = Properties.Resources.WebRequestAccept;
            delRequest.ContentType = "application/x-www-form-urlencoded";
            delRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            delRequest.Headers.Add("Accept-Language", "en-US");
            delRequest.Host      = uploadUrl.Host;
            delRequest.KeepAlive = true;
            delRequest.ServicePoint.Expect100Continue = false;

            string postData2 = Properties.Resources.FinishData + hideValue;

            if (!string.IsNullOrEmpty(authorizationPassword))
            {
                delRequest.Headers.Add(HttpRequestHeader.Authorization, authorizationPassword);
                delRequest.AllowAutoRedirect = false;
            }

            try
            {
                var postResponse = HttpWebEngine.Post(delRequest, postData2, _userAgent);

                if (postResponse.StatusCode == HttpStatusCode.OK)
                {
                    CloseWizard(printerIp, authorizationPassword, wizardid);
                    ExecutionServices.SystemTrace.LogDebug("Deleted certificate from printer");
                    if (!VerifyCAUploadJedi(printerIp, authorizationPassword, false))
                    {
                        throw new WebException("Certificate delete verification failed");
                    }
                }
                else
                {
                    throw new WebException("Certificate delete failed");
                }
            }
            catch (WebException ex)
            {
                throw new WebException("Certificate delete failed", ex);
            }
        }
Esempio n. 27
0
        private void AddUser(EprintAdminTask eprintTask, CookieCollection loginCookie)
        {
            //GET previous response to extract view state
            string         postData;
            Uri            getAddUser    = new Uri($@"{_ePrintServerType}://{_ePrintServerIp}/cloudprintadmin/users/Edit.aspx");
            HttpWebRequest getAddUserReq = (HttpWebRequest)WebRequest.Create(getAddUser);

            getAddUserReq.Accept = "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
            getAddUserReq.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US");
            getAddUserReq.Headers.Add("Accept-Encoding", "gzip, deflate");
            getAddUserReq.CookieContainer = new CookieContainer();
            getAddUserReq.CookieContainer.Add(loginCookie);
            getAddUserReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            HttpWebResult importResponse = HttpWebEngine.Get(getAddUserReq);

            ExecutionServices.SystemTrace.LogInfo($"Requesting to add {Environment.UserName} as a {eprintTask.Operation} ");
            //POST
            CookieCollection adminCookie   = new CookieCollection();
            string           setCookie     = importResponse.Headers.Get("Set-Cookie");
            string           trimmedcookie = setCookie.Substring(12, setCookie.IndexOf(";", StringComparison.Ordinal) - 12);

            adminCookie.Add(new Cookie("AdminCookie", trimmedcookie)
            {
                Domain = _ePrintServerIp
            });
            Uri            addUserUrl = new Uri($@"{_ePrintServerType}://{_ePrintServerIp}/cloudprintadmin/users/Edit.aspx");
            HttpWebRequest addUserReq = (HttpWebRequest)WebRequest.Create(addUserUrl);

            addUserReq.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8");
            addUserReq.Accept          = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            addUserReq.ContentType     = "application/x-www-form-urlencoded";
            addUserReq.CookieContainer = new CookieContainer();
            addUserReq.CookieContainer.Add(loginCookie);
            addUserReq.CookieContainer.Add(adminCookie);
            addUserReq.Headers.Add("Accept-Encoding", "gzip, deflate");
            addUserReq.Headers.Add(HttpRequestHeader.CacheControl, "max-age=0");

            if (eprintTask.Operation.Equals(EprintAdminToolOperation.GuestUser))
            {
                //guest user

                postData = string.Format(Properties.Resources.GuestUserPostData, HttpUtility.UrlEncode(ExtractViewState(importResponse.Response)), _credential.UserName, _userDnsName, DateTime.Today.ToString("MM-dd-yyyy"), DateTime.Today.AddMonths(1).ToString("MM-dd-yyyy"));
            }
            else
            {
                //regular user
                postData = string.Format(Properties.Resources.RegularUserPostData, HttpUtility.UrlEncode(ExtractViewState(importResponse.Response)), _credential.UserName, _userDnsName, DateTime.Today.ToString("MM-dd-yyyy"), DateTime.Today.AddDays(30).ToString("MM-dd-yyyy"));
            }
            HttpWebResult addUserResponse = HttpWebEngine.Post(addUserReq, postData);


            if (addUserResponse.StatusCode != HttpStatusCode.OK)
            {
                ExecutionServices.SystemTrace.LogError($"Failed to  add { (object)Environment.UserName} as a { (object)eprintTask.Operation} ");
                eprintTask.Status = "Failed";
            }
            else
            {
                ExecutionServices.SystemTrace.LogInfo($"Successfully added {Environment.UserName} as a {eprintTask.Operation} ");
                eprintTask.Status = "Passed";
            }
        }
Esempio n. 28
0
        private void ePrintAddPrinter(EprintAdminTask eprintTask, CookieCollection loginCookie)
        {
            string assetId = eprintTask.TargetObject;
            //GET previous response to extract viewstate
            Uri            getaddPrinterUrl = new Uri($@"{_ePrintServerType}://{_ePrintServerIp}/cloudprintadmin/printers/Insert.aspx");
            HttpWebRequest getaddPrinter    = (HttpWebRequest)WebRequest.Create(getaddPrinterUrl);

            getaddPrinter.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8");
            getaddPrinter.Accept          = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            getaddPrinter.CookieContainer = new CookieContainer();
            getaddPrinter.CookieContainer.Add(loginCookie);
            getaddPrinter.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
            getaddPrinter.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            HttpWebResult getaddPrinterResponse = HttpWebEngine.Get(getaddPrinter);

            if (getaddPrinterResponse.StatusCode != HttpStatusCode.OK)
            {
                ExecutionServices.SystemTrace.LogError("Unable to Login to ePrint . Please check Credentials");
                //throw new PluginExecutionResult(PluginResult.Failed, "Unable to Login to ePrint . Please check Credentials");
            }
            CookieCollection adminCookie   = new CookieCollection();
            string           setCookie     = getaddPrinterResponse.Headers.Get("Set-Cookie");
            string           trimmedcookie = setCookie.Substring(12, setCookie.IndexOf(";", StringComparison.Ordinal) - 12);

            adminCookie.Add(new Cookie("AdminCookie", trimmedcookie)
            {
                Domain = _ePrintServerIp
            });
            //Add the Printer: POST
            Uri            addPrinterUrl = new Uri($@"{_ePrintServerType}://{_ePrintServerIp}/cloudprintadmin/printers/Insert.aspx");
            HttpWebRequest addPrinterReq = (HttpWebRequest)WebRequest.Create(addPrinterUrl);
            HttpWebResult  addPrinterResponse;

            //ipv4 printer or HPAC printer
            if (eprintTask.Operation.Equals(EprintAdminToolOperation.AddPrinteripv4))
            {
                addPrinterReq.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US");
                addPrinterReq.Accept          = "text/html, application/xhtml+xml, */*";
                addPrinterReq.ContentType     = "application/x-www-form-urlencoded";
                addPrinterReq.CookieContainer = new CookieContainer();
                addPrinterReq.CookieContainer.Add(adminCookie);
                addPrinterReq.CookieContainer.Add(loginCookie);
                addPrinterReq.Headers.Add("Accept-Encoding", "gzip, deflate");
                addPrinterReq.Headers.Add(HttpRequestHeader.Pragma, "no-cache");

                string postData = string.Format(Properties.Resources.AddPrinterIPV4PostData, (HttpUtility.UrlEncode(ExtractViewState(getaddPrinterResponse.Response))), assetId, _device.GetDeviceInfo().ModelName, _device.Address);

                addPrinterResponse = HttpWebEngine.Post(addPrinterReq, postData);
                if (addPrinterResponse.StatusCode.Equals(HttpStatusCode.OK))
                {
                    ExecutionServices.SystemTrace.LogInfo($"Successfully added printer { (object)assetId} IP { (object)_device.Address} ");
                    eprintTask.Status = "Passed";
                }
                else
                {
                    ExecutionServices.SystemTrace.LogError($"Could not add printer { (object)assetId} IP { (object)_device.Address} ERROR:Status Code:{ (object)addPrinterResponse.StatusCode} ");

                    eprintTask.Status = "Failed";
                }
            }
            else if (eprintTask.Operation.Equals(EprintAdminToolOperation.AddPrinterHpac))
            {
                addPrinterReq.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8");
                addPrinterReq.Accept          = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                addPrinterReq.ContentType     = "application/x-www-form-urlencoded";
                addPrinterReq.CookieContainer = new CookieContainer();
                addPrinterReq.CookieContainer.Add(loginCookie);
                addPrinterReq.Headers.Add("Accept-Encoding", "gzip, deflate");
                addPrinterReq.Headers.Add(HttpRequestHeader.CacheControl, "max-age=0");

                string postData = string.Format(Properties.Resources.AddPrinterHPACPostdata, (HttpUtility.UrlEncode(ExtractViewState(getaddPrinterResponse.Response))), eprintTask.HpacInputValue.PrinterName, eprintTask.HpacInputValue.NetworkAddress, eprintTask.HpacInputValue.QueueName, eprintTask.HpacInputValue.DomainUser, eprintTask.HpacInputValue.DomainPassword);
                addPrinterResponse = HttpWebEngine.Post(addPrinterReq, postData);
                if (addPrinterResponse.StatusCode.Equals(HttpStatusCode.OK))
                {
                    ExecutionServices.SystemTrace.LogInfo($"Successfully added printer using HPAC { (object)eprintTask.HpacInputValue.NetworkAddress} and Queue { (object)eprintTask.HpacInputValue.QueueName} ");
                    eprintTask.Status = "Passed";
                }
                else
                {
                    ExecutionServices.SystemTrace.LogInfo($"Could not add printer { (object)eprintTask.HpacInputValue.PrinterName} ERROR:Status Code:{ (object)addPrinterResponse.StatusCode} ");
                    eprintTask.Status = "Failed";
                }
            }
            else
            {
                addPrinterReq.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8");
                addPrinterReq.Accept          = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                addPrinterReq.ContentType     = "application/x-www-form-urlencoded";
                addPrinterReq.CookieContainer = new CookieContainer();
                addPrinterReq.CookieContainer.Add(adminCookie);
                addPrinterReq.CookieContainer.Add(loginCookie);
                addPrinterReq.Headers.Add("Accept-Encoding", "gzip, deflate");
                addPrinterReq.Headers.Add(HttpRequestHeader.CacheControl, "max-age=0");

                string postData = string.Format(Properties.Resources.AddPrinterSAFECOMPostdata, (HttpUtility.UrlEncode(ExtractViewState(getaddPrinterResponse.Response))), eprintTask.HpacInputValue.PrinterName, eprintTask.HpacInputValue.NetworkAddress, eprintTask.HpacInputValue.QueueName, eprintTask.HpacInputValue.DomainUser, eprintTask.HpacInputValue.DomainPassword);
                addPrinterResponse = HttpWebEngine.Post(addPrinterReq, postData);
                if (addPrinterResponse.StatusCode.Equals(HttpStatusCode.OK))
                {
                    ExecutionServices.SystemTrace.LogInfo($"Successfully added printer using HPAC { (object)eprintTask.HpacInputValue.NetworkAddress} and Queue { (object)eprintTask.HpacInputValue.QueueName} ");
                    eprintTask.Status = "Passed";
                }
                else
                {
                    ExecutionServices.SystemTrace.LogInfo($"Could not add printer {eprintTask.HpacInputValue.PrinterName} ERROR:Status Code:{addPrinterResponse.StatusCode} ");
                    eprintTask.Status = "Failed";
                }
            }
        }
Esempio n. 29
0
        private void ePrintImportPrinter(EprintAdminTask eprintTask, CookieCollection loginCookie)
        {
            //GET previous response to extract view state
            Uri            getImport = new Uri($@"{_ePrintServerType}://{_ePrintServerIp}/cloudprintadmin/printers/Import.aspx");
            HttpWebRequest importReq = (HttpWebRequest)WebRequest.Create(getImport);

            importReq.Accept = "text/html, application/xhtml+xml, */*";
            importReq.Headers.Add("Accept-Encoding", "gzip, deflate");
            importReq.CookieContainer = new CookieContainer();
            importReq.CookieContainer.Add(loginCookie);
            importReq.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US");
            HttpWebResult importPrinterResponse = HttpWebEngine.Get(importReq);

            string file = eprintTask.TargetObject;

            ExecutionServices.SystemTrace.LogInfo($"Requesting to upload file {file}");
            NameValueCollection nvc = new NameValueCollection();

            nvc.Add("ctl00$BodyContentPlaceHolder$PrinterImportMessagePanel$ctl00$ImportButton", "Proceed");

            //POST request to upload file

            Uri            importPrinterUrl = new Uri($@"{_ePrintServerType}://{_ePrintServerIp}/cloudprintadmin/printers/Import.aspx");
            HttpWebRequest importPrinterReq = (HttpWebRequest)WebRequest.Create(importPrinterUrl);

            importPrinterReq.Method = "POST";
            importPrinterReq.Accept = "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, */*";
            importPrinterReq.Headers.Add("Accept-Encoding", "gzip, deflate");
            importPrinterReq.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US");
            importPrinterReq.CookieContainer = new CookieContainer();
            importPrinterReq.Headers.Add(HttpRequestHeader.Pragma, "no-cache");
            importPrinterReq.CookieContainer.Add(loginCookie);

            //Forming postdata
            HttpWebResult tempResult;
            string        contentType = "application/vnd.ms-excel";

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return(true); });
            ServicePointManager.Expect100Continue = false;
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

            byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            importPrinterReq.ContentType = "multipart/form-data; boundary=" + boundary;
            using (Stream requestStream = importPrinterReq.GetRequestStream())
            {
                requestStream.Write(boundarybytes, 0, boundarybytes.Length);
                string headerTemplate = string.Format(Properties.Resources.ImportPrinterHeaderTemplate, boundary, ExtractViewState(importPrinterResponse.Response), Path.GetFileName(file), contentType);

                byte[] headerBytes = Encoding.UTF8.GetBytes(headerTemplate);
                requestStream.Write(headerBytes, 0, headerBytes.Length);
                ExecutionServices.SystemTrace.LogDebug("Writing file bytes to Stream");
                if (string.IsNullOrEmpty(file))
                {
                    byte[] buffer = new byte[4096];
                    requestStream.Write(buffer, 0, 0);
                }
                else
                {
                    using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
                    {
                        byte[] buffer = new byte[4096];
                        int    bytesRead;
                        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            requestStream.Write(buffer, 0, bytesRead);
                        }
                    }
                }
                string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                foreach (string key in nvc.Keys)
                {
                    requestStream.Write(boundarybytes, 0, boundarybytes.Length);
                    string formitem      = string.Format(formdataTemplate, key, nvc[key]);
                    byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
                    requestStream.Write(formitembytes, 0, formitembytes.Length);
                }

                byte[] trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                requestStream.Write(trailer, 0, trailer.Length);
                tempResult = HttpWebEngine.Execute(importPrinterReq);
            }
            eprintTask.Status = tempResult.StatusCode == HttpStatusCode.OK ? "Passed" : "Failed";
        }
Esempio n. 30
0
        private void ePrintDeletePrinter(EprintAdminTask eprintTask, CookieCollection loginCookie)
        {
            // get the list of printers and extract the unique id to get the unique internal id of the required printer
            Uri            getPrinterList = new Uri($@"{_ePrintServerType}://{_ePrintServerIp}/cloudprintadmin/printers/List.aspx");
            HttpWebRequest getPrintersReq = (HttpWebRequest)WebRequest.Create(getPrinterList);

            getPrintersReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            getPrintersReq.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8");
            getPrintersReq.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
            getPrintersReq.CookieContainer = new CookieContainer();
            getPrintersReq.CookieContainer.Add(loginCookie);
            getPrintersReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            HttpWebResult getPrintersRes       = HttpWebEngine.Get(getPrintersReq);
            string        printersListResponse = getPrintersRes.Response;

            // TraceFactory.Logger.Info("Load the printer list");
            ExecutionServices.SystemTrace.LogInfo("Load the printer list");

            //get the request id for the printer from the response
            string substringFromPrinterIp = printersListResponse.Substring(printersListResponse.IndexOf(_device.Address, StringComparison.Ordinal));
            string printerCode            = substringFromPrinterIp.Substring(substringFromPrinterIp.IndexOf("PrinterListGrid", StringComparison.OrdinalIgnoreCase) + "PrinterListGrid".Length, 7);

            ExecutionServices.SystemTrace.LogInfo("Retrieving the printer list");
            // POST the unique id to get the redirect url of the selected printer
            Uri            postPrinterDetails = new Uri($@"{_ePrintServerType}://{_ePrintServerIp}/cloudprintadmin/printers/List.aspx");
            HttpWebRequest postPrinterDetReq  = (HttpWebRequest)WebRequest.Create(postPrinterDetails);

            postPrinterDetReq.Accept      = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            postPrinterDetReq.ContentType = "application/x-www-form-urlencoded";
            postPrinterDetReq.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8");
            postPrinterDetReq.Headers.Add("Accept-Encoding", "gzip, deflate");
            postPrinterDetReq.CookieContainer = new CookieContainer();
            postPrinterDetReq.CookieContainer.Add(loginCookie);
            //postdata
            string postData = string.Format(Properties.Resources.DeletePrinterRedirectURL, HttpUtility.UrlEncode(printerCode), HttpUtility.UrlEncode(ExtractViewState(printersListResponse)));

            postPrinterDetReq.AllowAutoRedirect = false;
            HttpWebResult postPrinterDetResponse = HttpWebEngine.Post(postPrinterDetReq, postData);

            if (postPrinterDetResponse.StatusCode != HttpStatusCode.Redirect)
            {
                ExecutionServices.SystemTrace.LogDebug($"Unable to find printer {_device.Address} ERROR: Status code {postPrinterDetResponse.StatusCode}");
                eprintTask.Status = "Failed";
            }

            //GET details of printer by sending the unique url with printers ID to get viewstate
            Uri            getPrinterDetails = new Uri($@"{_ePrintServerType}://{_ePrintServerIp}{postPrinterDetResponse.Headers.Get("Location")}");
            HttpWebRequest getPrinterDetReq  = (HttpWebRequest)WebRequest.Create(getPrinterDetails);

            getPrinterDetReq.Headers.Add(HttpRequestHeader.CacheControl, " max-age=0");
            getPrinterDetReq.Accept      = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            getPrinterDetReq.ContentType = "application/x-www-form-urlencoded";
            getPrinterDetReq.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8");
            getPrinterDetReq.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
            getPrinterDetReq.CookieContainer = new CookieContainer();
            getPrinterDetReq.CookieContainer.Add(loginCookie);
            getPrinterDetReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            HttpWebResult getPrinterDetResponse = HttpWebEngine.Get(getPrinterDetReq);

            ExecutionServices.SystemTrace.LogInfo($"Redirecting to URL:{postPrinterDetResponse.Headers.Get("Location")}");
            //delete selected printer
            Uri            deletePrinter = new Uri($@"{_ePrintServerType}://{_ePrintServerIp}{postPrinterDetResponse.Headers.Get("Location")}");
            HttpWebRequest delPrinterReq = (HttpWebRequest)WebRequest.Create(deletePrinter);

            delPrinterReq.Headers.Add(HttpRequestHeader.CacheControl, " max-age=0");
            delPrinterReq.Accept      = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            delPrinterReq.ContentType = "application/x-www-form-urlencoded";
            delPrinterReq.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8");
            delPrinterReq.Headers.Add("Accept-Encoding", "gzip, deflate");
            delPrinterReq.CookieContainer = new CookieContainer();
            delPrinterReq.CookieContainer.Add(loginCookie);
            //postdata
            string        delpostData        = string.Format(Properties.Resources.DeletePrinterPostData, HttpUtility.UrlEncode(ExtractViewState(getPrinterDetResponse.Response)));
            HttpWebResult delPrinterResponse = HttpWebEngine.Post(delPrinterReq, delpostData);

            if (delPrinterResponse.StatusCode != HttpStatusCode.OK)
            {
                ExecutionServices.SystemTrace.LogInfo($"Failed to Delete the printer ERROR:{delPrinterResponse.StatusCode}");

                eprintTask.Status = "Failed";
            }
            else
            {
                ExecutionServices.SystemTrace.LogInfo($"Successfully deleted the printer {_device.Address}");

                eprintTask.Status = "Passed";
            }
        }