Esempio n. 1
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. 2
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. 3
0
        /// <summary>
        /// Inkjet WPA2 config
        /// </summary>
        /// <param name="profilesValue"></param>
        /// <param name="postDataValue"></param>
        private void InkJetWPA2Config(string profilesValue, string postDataValue)
        {
            string cookiesValue = string.Empty;

            try
            {
                if (profilesValue != null)
                {
                    ExecutionServices.SystemTrace.LogDebug("Profiles Value  : " + profilesValue);

                    Uri url = new Uri($"https://{ (object)_device.Address}");

                    HttpWebResult result = PrepareInkWebRequest(_device, url, HttpVerb.GET, cookiesValue, postDataValue);

                    ExecutionServices.SystemTrace.LogDebug($"Navigating to URL https://{ (object)_device.Address} Result:{ (object)result.StatusCode}");
                    if (result.StatusCode != 0)
                    {
                        cookiesValue = result.Headers.GetValues("Set-Cookie").FirstOrDefault().Split(';').FirstOrDefault();
                        ExecutionServices.SystemTrace.LogDebug("Cookies Value: " + cookiesValue);

                        url = new Uri($"https://{ (object)_device.Address}/{ (object)"IoMgmt/Adapters/Wifi0/Profiles/1"}");

                        result = PrepareInkWebRequest(_device, url, HttpVerb.PUT, cookiesValue, profilesValue);
                        ExecutionServices.SystemTrace.LogDebug($"Navigating to URL https://{ (object)_device.Address}/{ (object)"IoMgmt/Adapters/Wifi0/Profiles/1"}  Result:{ (object)result.StatusCode}");
                        if (result.StatusCode != 0)
                        {
                            url    = new Uri($"https://{ (object)_device.Address}/{ (object)"IoMgmt/Adapters/Wifi0"}");
                            result = PrepareInkWebRequest(_device, url, HttpVerb.PUT, cookiesValue, postDataValue);
                            ExecutionServices.SystemTrace.LogDebug($"Navigating to URL https://{_device.Address}/{"IoMgmt/Adapters/Wifi0"}  Result:{result.StatusCode}");
                        }
                    }
                    else
                    {
                        ExecutionServices.SystemTrace.LogDebug("Time out exception occurred. Please re-run it.");
                    }
                }
                else
                {
                    ExecutionServices.SystemTrace.LogDebug("This feature is not supported in this device.");
                }
            }
            catch (HttpListenerException exception)
            {
                ExecutionServices.SystemTrace.LogDebug(exception.Message);
            }
        }
        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. 5
0
        /// <summary>
        /// VEP WPA2 config
        /// </summary>
        /// <param name="profilesValue"></param>
        private void VEPWPA2Config(string profilesValue)
        {
            string cookiesValue = string.Empty;

            ExecutionServices.SystemTrace.LogDebug("Profiles Value  : " + profilesValue);

            Uri           url    = new Uri($"https://{_device.Address}/dot11_config.htm");
            HttpWebResult result = PrepareVEPWebRequest(url, HttpVerb.GET, cookiesValue);

            ExecutionServices.SystemTrace.LogDebug($"Navigating to URL https://{_device.Address}/dot11_config.htm Result:{result.StatusCode}");

            if (result.StatusCode == HttpStatusCode.OK)
            {
                // cookiesValue = result.Headers.GetValues("Cookie").ToString();
                //TraceFactory.Logger.Info("Cookies Value: " + cookiesValue);

                url    = new Uri($"https://{_device.Address}/dot11_config.htm/config");
                result = PrepareVEPWebRequest(url, HttpVerb.POST, cookiesValue, profilesValue);
                ExecutionServices.SystemTrace.LogDebug($"Navigating to URL https://{_device.Address}/dot11_config.htm/config Result:{result.StatusCode}");

                if (result.StatusCode == HttpStatusCode.OK)
                {
                    url    = new Uri($"https://{_device.Address}/success_result.htm/config");
                    result = PrepareVEPWebRequest(url, HttpVerb.POST, cookiesValue, Properties.Resources.VEPWPA2PostDataValue);
                    ExecutionServices.SystemTrace.LogDebug($"Navigating to URL https://{_device.Address}/success_result.htm/config Result:{result.StatusCode}");

                    if (result.StatusCode == HttpStatusCode.OK)
                    {
                        if (_activityData.PowerCycleRequired)
                        {
                            PowerCyclePrinter();
                        }
                    }
                }
            }
        }
        /// <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);
        }
        /// <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);
        }
Esempio n. 8
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. 9
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";
            }
        }
Esempio n. 10
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. 11
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. 12
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. 13
0
        /// <summary>
        /// Installs CA certificate on VEP printer
        /// </summary>
        /// <param name="printerIp"></param>
        /// <param name="file"></param>
        /// <param name="authorization"></param>
        /// <param name="allowIntermediate"></param>
        public void InstallCAFileJedi(Uri printerIp, string file, string authorization, bool allowIntermediate)
        {
            //Retrieve Session ID
            HttpWebResult webResultGetReqeust = GetSessionIdRequest(printerIp, authorization);
            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
            var getResponse = GetWizardIdResponse(printerIp, authorization, cookies);

            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 : Post Wizard page
            Uri            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 postOptionData = Properties.Resources.OptionRequestJediInstall + hideValue;

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

            try
            {
                var optionResponse = HttpWebEngine.Post(optionRequest, postOptionData, _userAgent);
                if (optionResponse.StatusCode != HttpStatusCode.OK)
                {
                    throw new WebException("Certificate option page POST failed");
                }
            }
            catch (WebException ex)
            {
                throw new WebException("Certificate option page POST failed", ex);
            }

            //Step 2 : Upload File
            NameValueCollection nvc = new NameValueCollection();

            if (allowIntermediate)
            {
                nvc.Add("Intermediate_CA", "on");
            }
            nvc.Add("Hide", hideValue);
            nvc.Add("Finish", "Finish");
            uploadUrl = new Uri($"{printerIp}{Properties.Resources.URLJediUpload}");
            HttpWebRequest installRequest = (HttpWebRequest)WebRequest.Create(uploadUrl);

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

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

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

            try
            {
                var uploadResponse = HttpWebEngine.UploadFile(installRequest, file, ".Install_FileName_handle", nvc, _userAgent);
                if (uploadResponse.StatusCode == HttpStatusCode.OK)
                {
                    var responseError = !allowIntermediate ? "The format of the file is invalid." : "The certificate entered was invalid. Please try again and be sure to include the entire certificate correctly.";
                    if (uploadResponse.Response.Contains(responseError))
                    {
                        CloseWizard(printerIp, authorization, wizardid, ".Install_FileName_handle", hideValue);
                        ExecutionServices.SystemTrace.LogDebug(responseError);
                        return;
                    }

                    CloseWizard(printerIp, authorization, wizardid);

                    ExecutionServices.SystemTrace.LogDebug("Certificate installed!");
                    if (!VerifyCAUploadJedi(printerIp, authorization, true))
                    {
                        throw new WebException("Certificate upload verification failed");
                    }
                }
                else
                {
                    throw new WebException("Upload Failed");
                }
            }
            catch (WebException ex)
            {
                throw new WebException("Upload Failed", ex);
            }
        }