Beispiel #1
0
        public APIResult QureyOrderState([FromBody] PrintParameter parameter)
        {
            if (string.IsNullOrEmpty(parameter.OrderID))
            {
                return(Error("OrderID参数不能为空"));
            }
            PrinterBase @base  = PrinterFactory.Create(PrinterType.FEIE);//)
            string      result = @base.QureyOrderState(parameter.OrderID);

            return(Success(result));
        }
Beispiel #2
0
        public APIResult QueryPrinterStatus([FromBody] PrintParameter parameter)
        {
            if (string.IsNullOrEmpty(parameter.SN))
            {
                return(Error("Sn参数不能为空"));
            }
            PrinterBase @base  = PrinterFactory.Create(PrinterType.FEIE);//)
            string      result = @base.QueryPrinterStatus(parameter.SN);

            return(Success(result));
            // return new EmptyResult();
        }
Beispiel #3
0
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            // create activity data
            FirewallActivityData activityData = executionData.GetMetadata <FirewallActivityData>(CtcMetadataConverter.Converters);
            PrinterFamilies      family       = (PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), activityData.ProductFamily);

            // Instance for EWS adapter and Start WebDriver
            EwsWrapper.Instance().Create(family, activityData.ProductName, activityData.IPv4Address, Path.Combine(activityData.SitemapPath, activityData.SitemapsVersion), BrowserModel.Firefox);
            EwsWrapper.Instance().Start();
            EwsWrapper.Instance().WakeUpPrinter();
            EwsWrapper.Instance().SetWSDiscovery(true);
            EwsWrapper.Instance().SetDHCPv6OnStartup(true);
            EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();

            // Get All IPv6 Addresses

            Printer.Printer printer = PrinterFactory.Create(family, IPAddress.Parse(activityData.IPv4Address));
            activityData.IPv6LinkLocalAddress = printer.IPv6LinkLocalAddress?.ToString() ?? string.Empty;
            activityData.IPv6StatefulAddress  = printer.IPv6StateFullAddress?.ToString() ?? string.Empty;
            activityData.IPv6StatelessAddress = printer.IPv6StatelessAddresses.Count == 0 ? string.Empty : printer.IPv6StatelessAddresses[0].ToString();

            // Instance for SNMP wrapper
            SnmpWrapper.Instance().Create(activityData.IPv4Address);

            // Instance for Telnet wrapper
            TelnetWrapper.Instance().Create(activityData.IPv4Address);

            // Instance for Firewall Tests
            if (null == _tests)
            {
                _tests = new FirewallTests(activityData);
            }

            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                    _tests.RunTest(executionData, testNumber, IPAddress.Parse(activityData.IPv4Address), (ProductFamilies)Enum.Parse(typeof(ProductFamilies), activityData.ProductFamily));
                }
                catch (Exception exception)
                {
                    TraceFactory.Logger.Info("Error while executing test {0} with exception {1}. \n".FormatWith(testNumber, exception.Message));
                }
            }

            EwsWrapper.Instance().Stop();

            return(new PluginExecutionResult(PluginResult.Passed));
        }
Beispiel #4
0
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            // create activity data
            DiscoveryActivityData activityData = executionData.GetMetadata <DiscoveryActivityData>(CtcMetadataConverter.Converters);
            PrinterFamilies       family       = (PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), activityData.ProductFamily);

            // create instance of ews adapter
            EwsWrapper.Instance().Create(family, activityData.ProductName, activityData.IPv4Address, Path.Combine(activityData.SitemapPath,
                                                                                                                  activityData.SitemapsVersion), BrowserModel.Firefox);

            //create instance of SNMP wrapper
            SnmpWrapper.Instance().Create(activityData.IPv4Address);

            //create instance of Telnet wrapper
            TelnetWrapper.Instance().Create(activityData.IPv4Address);

            EwsWrapper.Instance().Start();

            EwsWrapper.Instance().WakeUpPrinter();

            EwsWrapper.Instance().SetAdvancedOptions();

            EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();

            BonjourServiceInstallation();

            Printer.Printer printer = PrinterFactory.Create(activityData.ProductFamily, activityData.IPv4Address);
            activityData.PrinterMacAddress = printer.MacAddress.Replace(":", string.Empty);

            // create network discovery tests
            if (null == _networkDiscoveryTests)
            {
                _networkDiscoveryTests = new DiscoveryTests(activityData);
            }

            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                    _networkDiscoveryTests.RunTest(executionData, testNumber, IPAddress.Parse(activityData.IPv4Address), (ProductFamilies)Enum.Parse(typeof(ProductFamilies), activityData.ProductFamily));
                }
                catch (Exception e)
                {
                    TraceFactory.Logger.Info("Error while executing test:{0}  \n ".FormatWith(testNumber, e.Message));
                }
            }

            return(new PluginExecutionResult(PluginResult.Passed));
        }
Beispiel #5
0
        public APIResult QueryOrderInfoByDate([FromBody] PrintParameter parameter)

        {
            if (string.IsNullOrEmpty(parameter.SN))
            {
                return(Error("Sn参数不能为空"));
            }
            if (string.IsNullOrEmpty(parameter.Date))
            {
                parameter.Date = DateTime.Now.ToString("yyyy-MM-dd");
            }
            PrinterBase @base  = PrinterFactory.Create(PrinterType.FEIE);//)
            string      result = @base.QueryOrderInfoByDate(parameter.SN, parameter.Date);

            return(Success(result));
            // return new EmptyResult();
        }
        /// <summary>
        /// Print all files in specified folder
        /// </summary>
        /// <param name="ipAddress">IP Address of Printer</param>
        /// <param name="printProtocol"><see cref=" Printer.Printer.PrintProtocol"/></param>
        /// <param name="portNo">Port number for installation</param>
        /// <param name="testNo">Test number</param>
        /// <returns>true if all files printed successfully, false otherwise</returns>
        public bool ComplexPrinting(string ipAddress, Printer.Printer.PrintProtocol printProtocol, int portNo, int testNo)
        {
            string[] files = Directory.GetFiles(_activityData.DocumentsPath);
            if (null == files || 0 == files.Length)
            {
                TraceFactory.Logger.Info("Complex Printing failed. No files available.");
                return(false);
            }

            string hostname = string.Empty;

            if (Printer.Printer.PrintProtocol.IPPS.Equals(printProtocol))
            {
                if (!CtcUtility.IPPS_Prerequisite(IPAddress.Parse(ipAddress), out hostname))
                {
                    TraceFactory.Logger.Info("Failed to perform pre-requisites for IPPS.");
                    return(false);
                }
            }

            PrinterFamilies family = (PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), Enum <ProductFamilies> .Value(_activityData.ProductFamily));

            Printer.Printer printer = PrinterFactory.Create(family, IPAddress.Parse(ipAddress));

            if (printer.Install(IPAddress.Parse(ipAddress), printProtocol, _activityData.DriverPackagePath, _activityData.DriverModel, portNo, hostname))
            {
                printer.Print(CtcUtility.CreateFile("Test {0} started.".FormatWith(testNo)));
                // Subscribing for Print Queue Event
                printer.PrintQueueError += printer_PrintQueueError;

                if (!printer.Print(files))
                {
                    TraceFactory.Logger.Info("Complex Printing failed. All jobs didn't print.");
                    return(false);
                }
            }
            else
            {
                TraceFactory.Logger.Info("Complex Printing failed.");
                return(false);
            }

            TraceFactory.Logger.Info("All jobs for Complex Printing printed successfully.");
            return(true);
        }
Beispiel #7
0
        private void btnGetSerial_Click(object sender, EventArgs e)
        {
            IFiscalPrinter fp = PrinterFactory.Create(Model);

            try
            {
                txtSerial.Text = fp.GetSerial(ComPort, Baud);
                if (txtSerial.Text.Length < 3 && !string.IsNullOrEmpty(txtSerial.Text))
                {
                    fp.getError(Convert.ToInt32(txtSerial.Text));
                }
                else
                {
                    savePrinterSettings();
                }
            }
            catch (Exception x) { MessageBox.Show(x.Message); }
            finally { fp.Dispose(); }
        }
Beispiel #8
0
        //kjo eshte vetem per kasat e vjetra kur ngel tastiera e bllokuar
        private void button4_Click(object sender, EventArgs e)
        {
            if (Model.Contains("W"))
            {
                return;
            }

            IFiscalPrinter fp     = PrinterFactory.Create(Model);
            int            answer = fp.OpenPort(Model, Key, ComPort, Baud);

            if (answer == 1)
            {
                fp.WriteLine("T,1,______,_,__;");

                if (activeKeyb)
                {
                    fp.WriteLine("F,1,______,_,__;");
                }
            }

            fp.Dispose();
        }
Beispiel #9
0
        private void btnCheckKey_Click(object sender, EventArgs e)
        {
            savePrinterSettings();
            loadPrinterSettings();

            IFiscalPrinter fp = PrinterFactory.Create(Model);

            try
            {
                int answer = fp.OpenPort(Model, Key, ComPort, Baud);
                if (answer == 1)
                {
                    MessageBox.Show("Key Registered Sucessfully");
                    savePrinterSettings();
                }
                else
                {
                    //MessageBox.Show(getError(answer), "Kujdes!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    MessageBox.Show(fp.getError(answer), "Cant Connect");
                }
            }
            catch { }
            finally { fp.Dispose(); }
        }
        /// <summary>
        /// Print all files in specified folder
        /// </summary>
        /// <param name="ipAddress">IP Address of Printer</param>
        /// <param name="testNo">Test number</param>
        /// <param name="isPassiveMode">Passive/ Active mode for FTP</param>
        /// <returns>true if all files printed successfully, false otherwise</returns>
        public bool ComplexPrinting(string ipAddress, int testNo, bool isPassiveMode = false)
        {
            string[] files = Directory.GetFiles(_activityData.DocumentsPath);
            if (null == files || 0 == files.Length)
            {
                TraceFactory.Logger.Info("Complex Printing failed. No files available.");
                return(false);
            }

            PrinterFamilies family = (PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), Enum <ProductFamilies> .Value(_activityData.ProductFamily));

            Printer.Printer printer = PrinterFactory.Create(family, IPAddress.Parse(ipAddress));

            if (printer.PrintWithFtp(IPAddress.Parse(ipAddress), string.Empty, string.Empty, files, isPassiveMode: isPassiveMode))
            {
                TraceFactory.Logger.Info("All jobs for Complex Printing printed successfully.");
                return(true);
            }
            else
            {
                TraceFactory.Logger.Info("Complex Printing failed. All jobs didn't print successfully.");
                return(false);
            }
        }
Beispiel #11
0
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            ConnectivityPrintActivityData activityData = executionData.GetMetadata <ConnectivityPrintActivityData>(CtcMetadataConverter.Converters);
            PrinterFamilies family = (PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), Enum <ProductFamilies> .Value(activityData.ProductFamily));

            Printer.Printer printer = PrinterFactory.Create(family, IPAddress.Parse(activityData.Ipv4Address));

            if (!NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.Ipv4Address), TimeSpan.FromSeconds(10)))
            {
                MessageBox.Show(string.Concat("Printer IPv4 Address is not accessible\n\n",
                                              "IPv4 address: {0}\n".FormatWith(activityData.Ipv4Address)),
                                @"IPv4 Address Not Accessible", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return(new PluginExecutionResult(PluginResult.Failed, "Printer IPv4 Address is not accessible"));
            }

            // create instance of ews adapter
            EwsWrapper.Instance().Create(family, activityData.ProductName, activityData.Ipv4Address, Path.Combine(activityData.SitemapPath, activityData.SiteMapVersion), BrowserModel.Firefox);
            EwsWrapper.Instance().Start();
            EwsWrapper.Instance().WakeUpPrinter();
            EwsWrapper.Instance().SetAdvancedOptions();
            EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();

            //Enabling IPV6 startup
            EwsWrapper.Instance().SetDHCPv6OnStartup(true);
            EwsWrapper.Instance().SetIPv6(false);
            EwsWrapper.Instance().SetIPv6(true);

            // If printer is not available, assign default IPAddress
            if (printer.PingUntilTimeout(IPAddress.Parse(activityData.Ipv4Address), 1))
            {
                // Get All Ipv6 Addresses
                activityData.Ipv6LinkLocalAddress = printer.IPv6LinkLocalAddress?.ToString() ?? string.Empty;
                activityData.Ipv6StateFullAddress = printer.IPv6StateFullAddress?.ToString() ?? string.Empty;
                activityData.Ipv6StatelessAddress = printer.IPv6StatelessAddresses.Count == 0 ? string.Empty : printer.IPv6StatelessAddresses[0].ToString();
            }
            else
            {
                activityData.Ipv6LinkLocalAddress = string.Empty;
                activityData.Ipv6StateFullAddress = string.Empty;
                activityData.Ipv6StatelessAddress = string.Empty;
            }

            foreach (Ipv6AddressTypes addressType in activityData.Ipv6AddressTypes)
            {
                if (Ipv6AddressTypes.LinkLocal == addressType)
                {
                    if (!NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.Ipv6LinkLocalAddress), TimeSpan.FromSeconds(10)))
                    {
                        MessageBox.Show(string.Concat("Printer Link Local Address is not accessible\n\n",
                                                      "Link local address: {0}\n".FormatWith(activityData.Ipv6LinkLocalAddress),
                                                      "Check if Stateless and Stateful address are pinging if you have selected it.\n",
                                                      "Stateless: {0}, Stateful: {1}".FormatWith(activityData.Ipv6StatelessAddress, activityData.Ipv6StateFullAddress)),
                                        @"Link Local Address Not Accessible", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        return(new PluginExecutionResult(PluginResult.Failed, "Printer Link Local Address is not accessible"));
                    }
                }
                else if (Ipv6AddressTypes.Stateless == addressType)
                {
                    if (!NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.Ipv6StatelessAddress), TimeSpan.FromSeconds(10)))
                    {
                        MessageBox.Show(string.Concat("Printer Stateless Address is not accessible\n\n",
                                                      "Stateless address: {0}\n".FormatWith(activityData.Ipv6StatelessAddress),
                                                      "Check if Stateful address is pinging if you have selected it.\n",
                                                      "Stateful: {0}".FormatWith(activityData.Ipv6StateFullAddress)),
                                        @"Stateless Address Not Accessible", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        return(new PluginExecutionResult(PluginResult.Failed, "Printer Stateless Address is not accessible"));
                    }
                }
                else if (Ipv6AddressTypes.Stateful == addressType)
                {
                    if (!NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.Ipv6StateFullAddress), TimeSpan.FromSeconds(10)))
                    {
                        MessageBox.Show(string.Concat("Printer Stateful Address is not accessible\n\n",
                                                      "Stateful address: {0}\n".FormatWith(activityData.Ipv6StateFullAddress)),
                                        @"Stateful Address Not Accessible", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        return(new PluginExecutionResult(PluginResult.Failed, "Printer Stateful Address is not accessible"));
                    }
                }
            }

            //Reservation for Primary Printer
            string value    = activityData.Ipv4Address.Split(new char[] { '.' })[2];
            string serverIp = DHCP_SERVER_IP_FORMAT.FormatWith(value);

            TraceFactory.Logger.Info("Server IP : {0}".FormatWith(serverIp));
            //string serverIp = Printer.Printer.GetDHCPServerIP(IPAddress.Parse(activityData.Ipv4Address)).ToString();
            string printerMacAddress = printer.MacAddress.Replace(":", string.Empty);

            using (DhcpApplicationServiceClient client = DhcpApplicationServiceClient.Create(serverIp))
            {
                string scope = client.Channel.GetDhcpScopeIP(serverIp);
                TraceFactory.Logger.Info("Scope : {0}".FormatWith(scope));
                client.Channel.DeleteReservation(serverIp, client.Channel.GetDhcpScopeIP(serverIp), activityData.Ipv4Address, printerMacAddress);

                if (client.Channel.CreateReservation(serverIp, client.Channel.GetDhcpScopeIP(serverIp), activityData.Ipv4Address, printerMacAddress, ReservationType.Both))
                {
                    TraceFactory.Logger.Info("Primary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP : Succeeded");
                }
                else
                {
                    TraceFactory.Logger.Info("Primary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed");
                    return(new PluginExecutionResult(PluginResult.Failed, "Primary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed"));
                }
            }

            EwsWrapper.Instance().SetAdvancedOptions();

            string documentsPath      = activityData.DocumentsPath;
            string documentsSharePath = Path.Combine(CtcSettings.ConnectivityShare, activityData.ProductFamily.ToString());

            // Combine the connectivity share path with the selected document
            // In case of Re-run, path is already constructed. Hence do not construct it again.
            if (!Directory.Exists(documentsPath))
            {
                if (!documentsPath.StartsWith(documentsSharePath, StringComparison.CurrentCulture))
                {
                    documentsPath = Path.Combine(documentsSharePath, activityData.DocumentsPath, ConnectivityPrintConfigurationControl.DIRECTORY_DOCUMENTS);

                    activityData.DocumentsPath = documentsPath;
                }
            }

            if (activityData.IsWspTestsSelected)
            {
                printer.NotifyWSPrinter += printer_NotifyWSPAddition;
                if (printer.Install(IPAddress.Parse(activityData.Ipv4Address), Printer.Printer.PrintProtocol.WSP, activityData.DriverPackagePath, activityData.DriverModel))
                {
                    MessageBox.Show(@"WS Printer was added successfully.", @"WS Printer Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show(@"WS Printer was not added successfully. All WS Print related tests will fail.", @"WS Printer Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            if (null == _printTests)
            {
                _printTests = new ConnectivityPrintTests(activityData);
            }

            foreach (int testNumber in activityData.SelectedTests)
            {
                ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                _printTests.RunTest(executionData, testNumber, IPAddress.Parse(activityData.Ipv4Address), activityData.ProductFamily);
            }

            return(new PluginExecutionResult(PluginResult.Passed));
        }
Beispiel #12
0
        public APIResult AddPrinter([FromBody] AddPrinter parameter)
        {
            if (string.IsNullOrEmpty(parameter.PrinterName))
            {
                return(Error("打印机名称不能为空"));
            }
            if (string.IsNullOrEmpty(parameter.sn))
            {
                return(Error("SnList(打印机#KEY)参数不能为空"));
            }
            if (!parameter.shopId.HasValue)
            {
                return(Error("商铺ID不能为空"));
            }
            if (!parameter.printerType.HasValue)
            {
                return(Error("打印机类型不能为空"));
            }
            if (!parameter.printWay.HasValue)
            {
                return(Error("打印机方式不能为空"));
            }
            Shop shop = shopDb.GetSingle <Shop>(parameter.shopId.Value);

            if (shop == null)
            {
                return(Error("商铺不存在"));
            }
            //表示是否已经添加过
            Data.Printer printer = printDb.Printer.FirstOrDefault(s => !s.IsDel && s.SN == parameter.sn &&
                                                                  s.SKey == parameter.skey && s.PrinterType == parameter.printerType);
            bool IsExists = printer != null;

            if (IsExists)
            {
                if (printer.ShopID == shop.Id)
                {
                    return(Error("该设备已经添加过"));
                }
                else
                {
                    return(Error("该设备已经被别的商家添加过"));
                }
            }
            PrinterBase @base  = PrinterFactory.Create(parameter.printerType.Value);//)
            string      result = @base.AddPrinter(new PrintParameter()
            {
                SnList = $"{parameter.sn}#{parameter.skey}#"
            });
            //添加之后保存到数据库中
            Dictionary <string, object> tempdic = JsonConvert.DeserializeObject <Dictionary <string, object> >(result);

            if (!tempdic.ContainsKey("data"))
            {
                return(Error("添加失败"));
            }

            Data.Printer _printermodel = new Data.Printer();
            #region 实体赋值
            _printermodel.ShopID      = parameter.shopId.Value;
            _printermodel.SN          = parameter.sn;
            _printermodel.PrinterName = parameter.PrinterName;
            _printermodel.SKey        = parameter.skey;
            _printermodel.AddTime     = DateTime.Now;
            _printermodel.PrinterType = parameter.printerType.Value;
            _printermodel.PrintWay    = parameter.printWay.Value;
            _printermodel.IsEnable    = true;
            _printermodel.IsSuccess   = true;
            //_printermodel.Times = string.IsNullOrEmpty(parameter.Times) || int.TryParse(parameter.Times, out int t) ? 1 : t == 0 ? 1 : t;
            Dictionary <string, object> datadic = JsonConvert.DeserializeObject <Dictionary <string, object> >(tempdic["data"].ToString());
            JArray ok = datadic["ok"] as JArray;
            JArray no = datadic["no"] as JArray;
            //验证打印机是否在接口添加成功
            //如果之前添加失败了, 将修改原来的数据,否则重新添加
            #endregion

            if (ok.Count > 0)
            {
                printDb.AddTo(_printermodel);
                printDb.SaveChanges();
                return(Success(_printermodel));
            }
            else if (no.Count > 0)
            {
                string mes   = no[0].Value <string>();
                Regex  regex = new Regex(@".*添加过.*");
                if (regex.IsMatch(mes))
                {
                    printDb.AddTo(_printermodel);
                    printDb.SaveChanges();
                    return(Success(_printermodel));
                }
                else
                {
                    return(Error(mes));
                }
            }
            else
            {
                return(Error("添加打印机到供应商后台失败"));
            }
        }
Beispiel #13
0
        private void testInv()
        {
            int length = 2; //nr rreshtave test qe duam te printojme si test

            loadPrinterSettings();

            //nese nuk po punojme me active keyboard, checkstatus nuk ka kuptim
            if (!activeKeyb)
            {
                checkStatus = false;
            }

            IFiscalPrinter fp = PrinterFactory.Create(Model, checkStatus, activeKeyb);

            try
            {
                if (string.IsNullOrEmpty(txtKey.Text))
                {
                    MessageBox.Show("Ju lutemi te vendosni numrin e licences!", "Kujdes!");
                    return;
                }
                int answer = fp.OpenPort(Model, Key, ComPort, Baud); //nese ku ka lidhje me kasen kjo then NULL dhe nuk kemi fare objekt fiskal
                if (answer == 1)
                {
                    try
                    {
                        string[] inv = { };
                        //read
                        if (!File.Exists("sample.txt"))
                        {
                            MessageBox.Show("Mungon file me komandat");
                            return;
                        }
                        inv = File.ReadAllLines("sample.txt");
                        // check the length of the file
                        if (inv.Length == 0)
                        {
                            MessageBox.Show("Mungon sample.txt file qe ka komenadat e kases");
                            return;
                        }
                        //print
                        string line, nextline = "";
                        for (int i = 0; i < inv.Length; i++)
                        {
                            line = inv[i];
                            //check if next line is discount
                            if (i < inv.Length - 1) //nese ka akoma rreshta
                            {
                                nextline = inv[i + 1];
                            }

                            //nese kemi hapur nje fature jotatimore me komanden J atehere duhet mbyllyr me cript dhe jo tek per tek
                            //pra e mira eshte nese kemi file me info jotatimore i gjithe file te excecutohet si nje script dhe jo tek per tek
                            if (inv[0].StartsWith(("J,1,______,_,__;")))
                            {
                                fp.ExecuteScript(inv);
                                return;
                            }

                            //nese rreshti dyte eshte me C qe nenkupton zbritje dergo te dy rreshtat bashke qe te aplikohet zbritja
                            if (nextline.StartsWith("C,1,______,_,__;", StringComparison.Ordinal))
                            {
                                fp.ExecuteScript(new string[] { line, nextline });
                                i++;                                 //i should be increased as two lines have been printed by the script
                            }

                            else if (fp.WriteLine(inv[i]) == 0)
                            {
                                Console.WriteLine("err: " + inv[i]);
                                MessageBox.Show($"Gabim kominikim me kasen!\rRreshti: {inv[i]}"
                                                , "Konfirmo!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);

                                return;
                            } //end check if next line is discount
                        }     //end loop
                    }         //end try
                    catch (Exception err)
                    {
                        Console.WriteLine(err.Message);
                    }
                    finally
                    {
                        //fp.stopReading = true;
                        Console.WriteLine("Port disconnected!");
                    }
                }
                else
                {
                    //MessageBox.Show(getError(answer), "Kujdes!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    MessageBox.Show(fp.getError(answer), "Cant Connect");
                    return;
                }
            }
            catch (Exception ex) { MessageBox.Show("Nuk ka lidhje me kasen. Ose kasa fikur ose COM port jo i rregullt. Err: " + ex.ToString()); } //ne kete rast FP nuk eshte inicaizluar fare si objekt se nuk ka patur lidhje me kasen dhe kthen null error
            finally { fp.Dispose(); }
        }
Beispiel #14
0
        public APIResult Print([FromBody] PrintParameter parameter)
        {
            if (string.IsNullOrEmpty(parameter.Title))
            {
                return(Error("标题是必须的内容"));
            }
            if (parameter.List.Count == 0)
            {
                return(Error("订单列表格式有误,[{Name:'xxxx',Price:10,Count:1},{}]"));
            }
            if (parameter.ShopID == 0 && string.IsNullOrEmpty(parameter.ShopFlag))
            {
                return(Error("商铺编号是必须的,ID Flag必须存在其一"));
            }
            Shop shop = parameter.ShopID != 0 ? shopDb.GetSingle <Shop>(parameter.ShopID) : shopDb.Shops.FirstOrDefault(s => s.Flag == parameter.ShopFlag);

            if (shop == null)
            {
                return(Error("商铺不存在"));
            }
            List <OrderInfo> orderlist = parameter.List; //JsonConvert.DeserializeObject<List<OrderInfo>>(parameter.List); //根据集合填充内容

            if (parameter.List == null || orderlist.Count == 0)
            {
                return(Error("无任何订单,无需打印"));
            }
            string stringorderlist = JsonConvert.SerializeObject(orderlist);

            foreach (OrderInfo item in orderlist)
            {
                parameter.TotalMoney += item.Money;
            }
            List <Data.Printer> printers = printDb.Printer.Where(s => s.ShopID == parameter.ShopID && s.IsEnable && s.IsSuccess).ToList();

            if (printers.Count == 0)
            {
                return(Error("暂未添加相关打印机"));
            }
            // string[] snarry = parameter.SN.TrimEnd('#').Split('#');
            StringBuilder result = new StringBuilder("[");

            foreach (Data.Printer item in printers)
            {
                //StringBuilder postData = new StringBuilder("sn=" + item.SN);
                parameter.SN = item.SN;
                PrinterBase @base = PrinterFactory.Create(item.PrinterType);//)
                string      temp  = @base.PrinterRequest(parameter, item);
                #region 数据库操作
                PrintRecord record = new PrintRecord();
                //处理接口返回数据
                Dictionary <string, object> dic = JsonConvert.DeserializeObject <Dictionary <string, object> >(temp);
                //实体赋值
                record.SN         = item.SN;
                record.OrderID    = @base.GetOrderID(temp);// dic.ContainsKey("data") && dic["msg"].Equals("ok") ? dic["data"].ToString() : "未能成功打印";
                record.Title      = parameter.Title;
                record.OrderList  = stringorderlist;
                record.TotalMoney = (float)parameter.TotalMoney;
                record.Address    = parameter.Address;
                record.OrderName  = parameter.OrderName;
                record.Mobile     = parameter.Mobile;
                record.OrderTime  = Convert.ToDateTime(parameter.OrderTime);
                record.QRAddress  = parameter.QRAddress;
                record.Remark     = parameter.Remark;
                printDb.PrintRecord.Add(record);
                result.Append(temp);
                #endregion
            }
            result.Append("]");
            return(Success(result.ToString()));
        }
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            // Create Activity Data
            IPConfigurationActivityData activityData = executionData.GetMetadata <IPConfigurationActivityData>(CtcMetadataConverter.Converters);

            // Check Printer Accessibility
            if (!(NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.WiredIPv4Address), TimeSpan.FromSeconds(20))) &&
                CtcUtility.IsClientConfiguredWithServerIP(activityData.SecondDhcpServerIPAddress, activityData.LinuxServerIPAddress))
            {
                MessageBox.Show(string.Concat("Printer IP Address is not accessible or Client is not configured with Server IP Address.\n\n",
                                              "Make sure you have provided valid Printer IP Address and is accessible.\n",
                                              "Check if Client has acquired IPv4 Address from Secondary DHCP Server.\n",
                                              "Check if Client has acquired IPv4 Address from Linux Server."),
                                @"IP Address Not Accessible", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(new PluginExecutionResult(PluginResult.Failed, "Printer IP Address is not accessible or Client is not configured with Server IP Address."));
            }

            // Check Services on DHCP Servers
            if (!IsServicesRunning(activityData.PrimaryDhcpServerIPAddress, activityData.SecondDhcpServerIPAddress))
            {
                return(new PluginExecutionResult(PluginResult.Failed, "Services are not running on DHCP server."));
            }

            // Server Configurations

            Printer.Printer printer = PrinterFactory.Create(activityData.ProductFamily, activityData.WiredIPv4Address);
            TraceFactory.Logger.Info("Printer : {0}".FormatWith(printer));
            TraceFactory.Logger.Info("printer.MacAddress :{0}".FormatWith(printer.MacAddress));
            activityData.PrinterMacAddress = printer.MacAddress.Replace(":", string.Empty);
            TraceFactory.Logger.Info("PrinterMacAddress : {0}".FormatWith(activityData.PrinterMacAddress));

            DhcpApplicationServiceClient serviceFunctionPrimaryServer = DhcpApplicationServiceClient.Create(activityData.PrimaryDhcpServerIPAddress);

            activityData.PrimaryDHCPServerIPv6Address = serviceFunctionPrimaryServer.Channel.GetIPv6Address();
            activityData.DHCPScopeIPAddress           = serviceFunctionPrimaryServer.Channel.GetDhcpScopeIP(activityData.PrimaryDhcpServerIPAddress);
            activityData.DHCPScopeIPv6Address         = serviceFunctionPrimaryServer.Channel.GetIPv6Scope(activityData.PrimaryDhcpServerIPAddress);

            DhcpApplicationServiceClient serviceFunctionSecondaryServer = DhcpApplicationServiceClient.Create(activityData.SecondDhcpServerIPAddress);

            activityData.SecondaryDHCPServerIPv6Address = serviceFunctionSecondaryServer.Channel.GetIPv6Address();
            activityData.SecondaryDHCPServerIPv4Scope   = serviceFunctionSecondaryServer.Channel.GetDhcpScopeIP(activityData.SecondDhcpServerIPAddress);
            activityData.SecondaryDHCPServerIPv6Scope   = serviceFunctionSecondaryServer.Channel.GetIPv6Scope(activityData.SecondDhcpServerIPAddress);

            ServerConfiguration(ref activityData);
            DhcpApplicationServiceClient serviceFunction = DhcpApplicationServiceClient.Create(activityData.PrimaryDhcpServerIPAddress);

            activityData.ServerDNSPrimaryIPAddress = serviceFunction.Channel.GetPrimaryDnsServer(activityData.PrimaryDhcpServerIPAddress, activityData.DHCPScopeIPAddress);
            activityData.SecondaryDnsIPAddress     = serviceFunction.Channel.GetSecondaryDnsServer(activityData.PrimaryDhcpServerIPAddress, activityData.DHCPScopeIPAddress);
            activityData.ServerHostName            = serviceFunction.Channel.GetHostName(activityData.PrimaryDhcpServerIPAddress, activityData.DHCPScopeIPAddress);
            activityData.DomainName            = serviceFunction.Channel.GetDomainName(activityData.PrimaryDhcpServerIPAddress, activityData.DHCPScopeIPAddress);
            activityData.ServerRouterIPAddress = serviceFunction.Channel.GetRouterAddress(activityData.PrimaryDhcpServerIPAddress, activityData.DHCPScopeIPAddress);
            activityData.ServerDNSSuffix       = serviceFunction.Channel.GetDnsSuffix(activityData.PrimaryDhcpServerIPAddress, activityData.DHCPScopeIPAddress);

            string ipv6Scope = serviceFunction.Channel.GetIPv6Scope(activityData.PrimaryDhcpServerIPAddress);

            if (string.IsNullOrEmpty(ipv6Scope))
            {
                MessageBox.Show(string.Concat("Unable to fetch IPv6 Scope \n\n",
                                              "Check whether DHCP IPv6 Scope is configured on DHCP server."),
                                @"IPv6 Scope Not found", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return(new PluginExecutionResult(PluginResult.Failed, "Check whether DHCP IPv6 Scope is configured on DHCP server."));
            }

            activityData.DHCPScopeIPv6Address = serviceFunction.Channel.GetIPv6Scope(activityData.PrimaryDhcpServerIPAddress);

            // Fetch and Validate the Switch VLAN details.
            GetVlanDetails(ref activityData);

            if (3 != activityData.VirtualLanDetails.Count)
            {
                MessageBox.Show(string.Concat("Unable to fetch Switch VLAN details\n\n",
                                              "Check whether Printer is connected to Network Switch.\n",
                                              "Switch should be configured with 3 network virtual LAN."),
                                @"Network switch not found", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return(new PluginExecutionResult(PluginResult.Failed, "Unable to fetch Switch VLAN details. Check whether Printer is connected to Network Switch. Switch should be configured with 3 network virtual LAN."));
            }

            // Fetching Router Details
            activityData.RouterIPv4Address = ROUTER_IP_FORMAT.FormatWith(activityData.WiredIPv4Address.Substring(0, activityData.WiredIPv4Address.LastIndexOf(".", StringComparison.CurrentCultureIgnoreCase)));
            var router = RouterFactory.Create(IPAddress.Parse(activityData.RouterIPv4Address), ROUTER_USERNAME, ROUTER_PASSWORD);
            Dictionary <int, IPAddress> routerVlans = router.GetAvailableVirtualLans();

            activityData.RouterVirtualLanId = routerVlans.FirstOrDefault(x => (null != x.Value) && (x.Value.IsInSameSubnet(IPAddress.Parse(activityData.RouterIPv4Address)))).Key;

            RouterVirtualLAN       routerVlan          = router.GetVirtualLanDetails(activityData.RouterVirtualLanId);
            Collection <IPAddress> routerIPv6Addresses = router.GetIPv6Addresses(routerVlan.IPv6Details);

            activityData.RouterIPv6Addresses = new Collection <string>(routerIPv6Addresses.Select(x => x.ToString()).ToList());

            // Add Source IP Address
            CtcUtility.AddSourceIPAddress(activityData.PrimaryDhcpServerIPAddress, activityData.LinuxServerIPAddress);

            // Create Instance of EWS Wrapper
            PrinterFamilies family = (PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), activityData.ProductFamily);

            EwsWrapper.Instance().Create(family, activityData.ProductName, activityData.WiredIPv4Address, Path.Combine(activityData.SitemapPath, activityData.SitemapsVersion), BrowserModel.Firefox);
            EwsWrapper.Instance().Start();
            EwsWrapper.Instance().WakeUpPrinter();
            EwsWrapper.Instance().SetAdvancedOptions();
            EwsWrapper.Instance().SetDefaultIPType(DefaultIPType.AutoIP);
            EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();

            // Create Instance of Telnet Wrapper
            TelnetWrapper.Instance().Create(activityData.WiredIPv4Address);

            // Create Instance of SNMP Wrapper
            SnmpWrapper.Instance().Create(activityData.WiredIPv4Address);

            // Delete Reservation is not validated to handle cases where reservation is not present
            serviceFunction.Channel.DeleteReservation(activityData.PrimaryDhcpServerIPAddress, activityData.DHCPScopeIPAddress, activityData.WiredIPv4Address, activityData.PrinterMacAddress);

            if (serviceFunction.Channel.CreateReservation(activityData.PrimaryDhcpServerIPAddress, activityData.DHCPScopeIPAddress, activityData.WiredIPv4Address, activityData.PrinterMacAddress, ReservationType.Both))
            {
                TraceFactory.Logger.Info("Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Succeeded");
            }
            else
            {
                TraceFactory.Logger.Info("Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed");
                return(new PluginExecutionResult(PluginResult.Failed, "Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed"));
            }

            TraceFactory.Logger.Info("The Server Configured Value retrieved from the DHCP Server are as follows:");
            TraceFactory.Logger.Info("MacAddress:{0}, DNSPrimaryIP:{1}, HostName:{2}, RouterIP:{3}, DNSSuffix:{4}".FormatWith(activityData.PrinterMacAddress, activityData.ServerDNSPrimaryIPAddress,
                                                                                                                              activityData.ServerHostName, activityData.ServerRouterIPAddress, activityData.ServerDNSSuffix));

            // assign the session id to activity id
            activityData.SessionId = executionData.SessionId;

            if (null == _ipConfigTests)
            {
                _ipConfigTests = new IPConfigurationTests(activityData);
            }

            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                    _ipConfigTests.RunTest(executionData, testNumber, IPAddress.Parse(activityData.WiredIPv4Address), (ProductFamilies)Enum.Parse(typeof(ProductFamilies), activityData.ProductFamily));
                }
                catch (Exception generalException)
                {
                    TraceFactory.Logger.Info("Test {0} failed with error: {1}".FormatWith(testNumber, generalException.Message));
                }
            }

            EwsWrapper.Instance().Stop();

            return(new PluginExecutionResult(PluginResult.Passed));
        }
Beispiel #16
0
        public static void PrintOrder(PrintDbContext printDbContext, ShopDbContext db, ShopOrder shopOrder, string shopname, ILogger _logger)
        {
            _logger.LogInformation($"Remark{shopOrder.Remark}");
            if (shopOrder.IsPrint)
            {
                return;
            }
            try
            {
                List <ShopOrderItem> items = db.Query <ShopOrderItem>()
                                             .Where(m => !m.IsDel)
                                             .Where(m => m.ShopOrderId == shopOrder.Id)
                                             .ToList();
                if (items.Count == 0)
                {
                    return;
                }
                List <OrderInfo> orderInfo = items.Select(s => new OrderInfo()
                {
                    Name        = $"{s.CommodityName}({s.SkuSummary})",
                    Price       = Math.Round(s.SalePrice / 100d, 2),
                    Count       = s.Count,
                    ComboConten = GetPrintComboContenParameter(db, s, _logger)
                }).ToList();
                string stringorderlist = JsonConvert.SerializeObject(orderInfo);

                List <Printer.Data.Printer> printers = printDbContext.Query <Printer.Data.Printer>()
                                                       .Where(s => !s.IsDel)
                                                       .Where(s => s.ShopID == shopOrder.ShopId && s.IsEnable).ToList();
                if (printers.Count == 0)
                {
                    return;
                }

                PrintParameter parameter = GetPrintParameter(db, shopOrder);
                parameter.ShopName  = shopname;
                parameter.List      = orderInfo;
                parameter.IsTakeOut = shopOrder.IsTakeOut;
                //获取优惠
                if (shopOrder.MoneyOffRuleId != null && shopOrder.MoneyOffRuleId != 0)
                {
                    var shopOrderMoneyOffRules = db.ShopOrderMoneyOffRules.Find(shopOrder.MoneyOffRuleId);
                    parameter.ShopOrderMoneyOffRule = new ShopOrderMoneyOffRuleModel()
                    {
                        Discount     = Math.Round(shopOrderMoneyOffRules.Discount / 100d, 2),
                        FullAmount   = Math.Round(shopOrderMoneyOffRules.FullAmount / 100d, 2),
                        MoneyOffId   = shopOrderMoneyOffRules.MoneyOffId,
                        MoneyOffName = db.ShopOrderMoneyOffs.Find(shopOrderMoneyOffRules.MoneyOffId).Name
                    };
                }
                //获取其他费用
                if (shopOrder.OtherFeeId != null && shopOrder.OtherFeeId != 0)
                {
                    var shopOrderMoneyOffs = db.ShopOrderOtherFees.Find(shopOrder.OtherFeeId);
                    parameter.ShopOrderOtherFee = new Dictionary <string, double>()
                    {
                        { "餐盒费", Math.Round(shopOrderMoneyOffs.BoxFee / 100d, 2) },
                        { "配送费", Math.Round(shopOrderMoneyOffs.DeliveryFee / 100d, 2) }
                    };
                    if (TakeWay.自提.ToString().Equals(parameter.TakeWay))
                    {
                        parameter.ShopOrderOtherFee.Remove("配送费");
                    }
                }
                if (shopOrder.ShopOrderSelfHelpId.HasValue)  //自助点餐
                {
                    var selfHelp = db.GetSingle <ShopOrderSelfHelp>(shopOrder.ShopOrderSelfHelpId.Value);
                    if (selfHelp != null)
                    {
                        parameter.SelfHelpPrintParameter = new SelfHelpPrintParameter()
                        {
                            SelfHelpNumber = selfHelp.Number,
                            DingingWay     = selfHelp.IsTakeOut ? "外带" : "堂食"
                        };
                    }
                }


                foreach (var item in printers)
                {
                    //StringBuilder postData = new StringBuilder("sn=" + item.SN);
                    parameter.SN    = item.SN;
                    parameter.Times = item.Times + "";
                    PrintModel model = printDbContext.Query <PrintModel>().FirstOrDefault(s => s.ID == item.ModelID);
                    if (model == null)
                    {
                        model = printDbContext.Set <PrintModel>().Find(2);
                    }
                    parameter.ModelContent = model.ModelContent;
                    PrinterBase @base = PrinterFactory.Create(item.PrinterType);//)
                    string      temp  = @base.PrinterRequest(parameter, item);
                    #region 数据库操作
                    PrintRecord record = new PrintRecord();
                    //处理接口返回数据
                    Dictionary <string, object> dic = JsonConvert.DeserializeObject <Dictionary <string, object> >(temp);
                    //实体赋值
                    record.SN         = item.SN;
                    record.OrderID    = @base.GetOrderID(temp);// dic.ContainsKey("data") && dic["msg"].Equals("ok") ? dic["data"].ToString() : "未能成功打印";
                    record.Title      = parameter.Title;
                    record.OrderList  = stringorderlist;
                    record.TotalMoney = (float)parameter.TotalMoney;
                    record.Address    = parameter.Address;
                    record.OrderName  = parameter.OrderName;
                    record.Mobile     = parameter.Mobile;
                    record.OrderTime  = Convert.ToDateTime(parameter.OrderTime);
                    record.QRAddress  = parameter.QRAddress;
                    record.Remark     = shopOrder.Remark;
                    printDbContext.AddTo(record);
                    #endregion
                }
                shopOrder.IsPrint = true;
            }
            catch (Exception e)
            {
                _logger.LogError("打印机错误:{0}", e.Message);
            }
        }
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            WebProxyActivityData activityData = executionData.GetMetadata <WebProxyActivityData>(CtcMetadataConverter.Converters);

            #region Scenario Prerequisites

            //Check the Windows Server Service is up and running on all servers
            CtcUtility.StartService("WindowsServerService", activityData.PrimaryDHCPServerIPAddress);
            CtcUtility.StartService("WindowsServerService", activityData.UnsecureWebProxyServerIPAddress);
            CtcUtility.StartService("WindowsServerService", activityData.SecureWebProxyServerIPAddress);
            CtcUtility.StartService("WindowsServerService", activityData.WPADServerIPAddress);

            //Add WPAD entry and Domain Name on the DHCP Server
            DhcpApplicationServiceClient serviceFunction = DhcpApplicationServiceClient.Create(activityData.PrimaryDHCPServerIPAddress);
            activityData.PrimaryDHCPScopeIPAddress = serviceFunction.Channel.GetDhcpScopeIP(activityData.PrimaryDHCPServerIPAddress);
            serviceFunction.Channel.SetWPADServer(activityData.PrimaryDHCPServerIPAddress, activityData.PrimaryDHCPScopeIPAddress, activityData.cURLPathIPAddress);
            activityData.DomainName = "lfpctc.com";

            string recordType = "A";
            serviceFunction.Channel.SetDomainName(activityData.PrimaryDHCPServerIPAddress, activityData.PrimaryDHCPScopeIPAddress, activityData.DomainName);

            // Retrieving hostnames of all servers

            SystemConfigurationClient secureProxy = SystemConfigurationClient.Create(activityData.SecureWebProxyServerIPAddress);
            activityData.SecureWebProxyServerHostName = secureProxy.Channel.GetHostName();
            TraceFactory.Logger.Info("Secure Web Proxy hostname is {0}".FormatWith(activityData.SecureWebProxyServerHostName));

            SystemConfigurationClient unsecureProxy = SystemConfigurationClient.Create(activityData.UnsecureWebProxyServerIPAddress);
            activityData.UnsecureWebProxyServerHostName = unsecureProxy.Channel.GetHostName();
            TraceFactory.Logger.Info("Unsecure Web Proxy hostname is {0}".FormatWith(activityData.UnsecureWebProxyServerHostName));

            SystemConfigurationClient wpadServer = SystemConfigurationClient.Create(activityData.WPADServerIPAddress);
            activityData.WPADServerHostName = wpadServer.Channel.GetHostName();
            TraceFactory.Logger.Info("WPAD hostname is {0}".FormatWith(activityData.WPADServerHostName));

            //Add DNS entry for all servers on the DHCP/DNS server
            DnsApplicationServiceClient dnsClient = DnsApplicationServiceClient.Create(activityData.PrimaryDHCPServerIPAddress);
            dnsClient.Channel.AddDomain(activityData.DomainName);
            dnsClient.Channel.AddRecord(activityData.DomainName, activityData.SecureWebProxyServerHostName, recordType, activityData.SecureWebProxyServerIPAddress);
            dnsClient.Channel.AddRecord(activityData.DomainName, activityData.UnsecureWebProxyServerHostName, recordType, activityData.UnsecureWebProxyServerIPAddress);
            dnsClient.Channel.AddRecord(activityData.DomainName, activityData.WPADServerHostName, recordType, activityData.WPADServerIPAddress);

            string curlFqdn = string.Concat(activityData.WPADServerHostName, activityData.DomainName);
            activityData.cURLPathFQDN             = string.Concat("http://", curlFqdn, ":80/wpad.dat");
            activityData.SecureWebProxyServerFQDN = string.Concat(activityData.SecureWebProxyServerHostName, activityData.DomainName);

            TraceFactory.Logger.Info(activityData.cURLPathFQDN);
            TraceFactory.Logger.Info(activityData.SecureWebProxyServerFQDN);

            PrinterFamilies family  = (PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), activityData.ProductFamily);
            Printer         printer = PrinterFactory.Create(family, IPAddress.Parse(activityData.WiredIPv4Address));

            // create instance of ews adapter
            EwsWrapper.Instance().Create(family, activityData.ProductName, activityData.WiredIPv4Address, Path.Combine(activityData.SitemapPath, activityData.SiteMapVersion), BrowserModel.Firefox);
            EwsWrapper.Instance().Start();

            //Create instance of SNMP Wrapper
            SnmpWrapper.Instance().Create(activityData.WiredIPv4Address);

            //Create instance of Telnet Wrapper
            TelnetWrapper.Instance().Create(activityData.WiredIPv4Address);

            //Wake up the printer and disable sleep mode
            EwsWrapper.Instance().WakeUpPrinter();
            printer.KeepAwake();

            EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();

            #endregion
            if (null == _webProxyTests)
            {
                _webProxyTests = new WebProxyTests(activityData);
            }

            // assign the session id to activity data
            activityData.SessionId = executionData.SessionId;

            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                    _webProxyTests.RunTest(executionData, testNumber, IPAddress.Parse(activityData.WiredIPv4Address), (ProductFamilies)Enum.Parse(typeof(ProductFamilies), activityData.ProductFamily));
                }
                catch (Exception generalException)
                {
                    TraceFactory.Logger.Info("Test {0} failed with error: {1}".FormatWith(testNumber, generalException.Message));
                }
            }

            EwsWrapper.Instance().Stop();

            return(new PluginExecutionResult(PluginResult.Passed));
        }
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            ComplexPrintActivityData activityData = executionData.GetMetadata <ComplexPrintActivityData>(CtcMetadataConverter.Converters);

            /* Complex printing plugin might use more than 1 client machine based on user scenario.
             * All inputs related to printer are maintained in a configuration file in share location (etlhubrepo\boi\CTC\<Product_Family>)
             * Since multiple machines are trying to access the config file, file is copied to local machine.
             * */

            // Get details from configuration file
            string configFilePath = Path.Combine(CtcSettings.ConnectivityShare, activityData.ProductFamily.ToString(), "CNP.xml");

            TraceFactory.Logger.Debug("Config File path: {0}".FormatWith(configFilePath));
            FileStream file = null;

            try
            {
                XmlDocument configFile   = new XmlDocument();
                string      tempFilePath = Path.Combine(Path.GetTempPath(), "CNP.xml");
                File.Copy(configFilePath, tempFilePath, true);

                file = new FileStream(tempFilePath, FileMode.Open, FileAccess.Read);
                configFile.Load(file);

                activityData.Ipv4Address         = configFile.DocumentElement.SelectSingleNode("IPv4Address").InnerText;
                activityData.DriverPackagePath   = configFile.DocumentElement.SelectSingleNode("DriverPath").InnerText;
                activityData.DriverModel         = configFile.DocumentElement.SelectSingleNode("DriverModel").InnerText;
                activityData.ProductName         = configFile.DocumentElement.SelectSingleNode("ProductName").InnerText;
                activityData.DocumentsPath       = configFile.DocumentElement.SelectSingleNode("FilesPath").InnerText;
                activityData.SitemapsVersion     = configFile.DocumentElement.SelectSingleNode("Sitemaps").InnerText;
                activityData.PrinterConnectivity = ConnectivityType.Wired;
            }
            catch (Exception exception)
            {
                TraceFactory.Logger.Fatal("Failed to read configuration from xml document. Exception details: {0}".FormatWith(exception.JoinAllErrorMessages()));
            }
            finally
            {
                if (null != file)
                {
                    file.Close();
                }
            }

            /* If a WS Print test is selected in user scenario, a pop-up needs to be shown to 'Add the printer'.
             * Read through all selected tests and keep track if WSP pop-up needs to be shown up.
             * */

            // Check if WSP test is selected by checking the test attributes for each test
            bool isWSPSelected = false;

            foreach (int testNumber in activityData.SelectedTests)
            {
                // Fetch the TestDetailsAttribute of the test method matching the testNumber
                var attributes = typeof(ComplexPrintTests).GetMethods().Where(item => item.GetCustomAttributes(new TestDetailsAttribute().GetType(), false).Length > 0 &&
                                                                              ((TestDetailsAttribute)item.GetCustomAttributes(new TestDetailsAttribute().GetType(), false)[0]).Id.Equals(testNumber))
                                 .Select(x => x.GetCustomAttributes(new TestDetailsAttribute().GetType(), false)[0]);

                TestDetailsAttribute testAttributes = (TestDetailsAttribute)attributes.FirstOrDefault();

                if (testAttributes.Category.Contains("WSP", StringComparison.CurrentCultureIgnoreCase))
                {
                    isWSPSelected = true;
                    break;
                }
            }

            if (isWSPSelected)
            {
                TraceFactory.Logger.Debug("Please add WS Printer on client machine: {0}".FormatWith(Environment.MachineName));
            }

            /* To keep track of whether a WSP test is added in any of the user scenario, a common file is maintained under shared location and all the clients need to update this file on WSP status.
             * Folder structure: etlhubrepo\boi\CTC\<Product_Family>temp\<Session_ID>.xml
             * Since many clients will be trying to write data to the xml file, check if xml is already created (by some other client), create if not.
             * If a WSP test is selected, an entry is made with 'Yes' as the value, else 'No' with machine hostname as the unique identifier for the node.
             * Status for the WS Print addition is maintained in 'Status' attribute. If scenario doesn't have a WSP test selected, 'Completed' status is added by default. Otherwise 'In Progress' is added.
             *
             * Locking mechanism:
             * Since its a shared file, a lock is applied when a file is in use by a machine. Lock file for writing the data and release once completed.
             * Acquire resource for max of 20 seconds to perform write operation. Wait for max of 3 minutes to use resource for writing into the file. (Waiting in Queue to write into the file)
             * */

            string configFolder = Path.Combine(CtcSettings.ConnectivityShare, activityData.ProductFamily.ToString(), "temp");

            // Check if folder exists already.
            if (!Directory.Exists(configFolder))
            {
                Directory.CreateDirectory(configFolder);
            }

            string   xmlFilePath = Path.Combine(configFolder, executionData.SessionId + ".xml");
            XElement machines    = null;

            // Check if file exists already. Create root node 'Machines' if file is not created else load the file
            if (!File.Exists(xmlFilePath))
            {
                machines = new XElement("Machines");
            }
            else
            {
                XDocument xmlDocument = XDocument.Load(xmlFilePath);
                machines = xmlDocument.Element("Machines");
            }

            ReaderWriterLock fileLock      = new ReaderWriterLock();
            bool             isFileWritten = false;
            DateTime         currentTime   = DateTime.Now;
            TimeSpan         waitTime      = TimeSpan.FromMinutes(3);
            Random           randomTime    = new Random();

            do
            {
                // Since many clients are trying to access the file, generate a random timeout for acquiring lock on the file.
                int timeOut = randomTime.Next(10, 20);

                if (!fileLock.IsWriterLockHeld)
                {
                    fileLock.AcquireWriterLock(TimeSpan.FromSeconds(timeOut));

                    XElement machine = new XElement("Machine", new XAttribute("VM_Name", Environment.MachineName),
                                                    new XAttribute("WSP_Print", isWSPSelected ? "Yes" : "No"),
                                                    new XAttribute("Status", isWSPSelected ? "In Progress" : "Completed"));

                    machines.Add(machine);
                    machines.Save(xmlFilePath);

                    // Wait for sometime to release the lock after saving file.
                    Thread.Sleep(TimeSpan.FromSeconds(10));
                    isFileWritten = true;
                    fileLock.ReleaseWriterLock();
                }
            } while (!isFileWritten && DateTime.Now.Subtract(waitTime) <= currentTime);

            /* Check if printer is accessible with IPv4 address and IPv6 addresses: Linklocal, Stateless and Stateful address.
             * Pop-up a message box if printer address is not pinging.
             * */

            PrinterFamilies family = (PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), Enum <ProductFamilies> .Value(activityData.ProductFamily));

            Printer.Printer printer = PrinterFactory.Create(family, IPAddress.Parse(activityData.Ipv4Address));

            // If printer is not available, assign default IPAddress
            if (printer.PingUntilTimeout(IPAddress.Parse(activityData.Ipv4Address), 1))
            {
                // Get All Ipv6 Addresses
                activityData.Ipv6LinkLocalAddress = printer.IPv6LinkLocalAddress == null ? string.Empty : printer.IPv6LinkLocalAddress.ToString();
                activityData.Ipv6StateFullAddress = printer.IPv6StateFullAddress == null ? string.Empty : printer.IPv6StateFullAddress.ToString();
                activityData.Ipv6StatelessAddress = printer.IPv6StatelessAddresses.Count == 0 ? string.Empty : printer.IPv6StatelessAddresses[0].ToString();
            }
            else
            {
                activityData.Ipv6LinkLocalAddress = string.Empty;
                activityData.Ipv6StateFullAddress = string.Empty;
                activityData.Ipv6StatelessAddress = string.Empty;
            }

            if (!NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.Ipv4Address), TimeSpan.FromSeconds(10)))
            {
                MessageBox.Show(string.Concat("Printer IPv4 Address is not accessible\n\n",
                                              "IPv4 address: {0}\n".FormatWith(activityData.Ipv4Address)),
                                "IPv4 Address Not Accessible", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(new PluginExecutionResult(PluginResult.Failed, "Printer IPv4 Address is not accessible"));
            }

            if (!NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.Ipv6LinkLocalAddress), TimeSpan.FromSeconds(10)))
            {
                MessageBox.Show(string.Concat("Printer Link Local Address is not accessible\n\n",
                                              "Link local address: {0}\n".FormatWith(activityData.Ipv6LinkLocalAddress),
                                              "Check if Stateless and Stateful address are pinging if you have selected it.\n",
                                              "Stateless: {0}, Stateful: {1}".FormatWith(activityData.Ipv6StatelessAddress, activityData.Ipv6StateFullAddress)),
                                "Link Local Address Not Accessible", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return(new PluginExecutionResult(PluginResult.Failed, "Printer Link Local Address is not accessible"));
            }

            if (!NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.Ipv6StatelessAddress), TimeSpan.FromSeconds(10)))
            {
                MessageBox.Show(string.Concat("Printer Stateless Address is not accessible\n\n",
                                              "Stateless address: {0}\n".FormatWith(activityData.Ipv6StatelessAddress),
                                              "Check if Stateful address is pinging if you have selected it.\n",
                                              "Stateful: {0}".FormatWith(activityData.Ipv6StateFullAddress)),
                                "Stateless Address Not Accessible", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return(new PluginExecutionResult(PluginResult.Failed, "Printer Stateless Address is not accessible"));
            }

            if (!NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.Ipv6StateFullAddress), TimeSpan.FromSeconds(10)))
            {
                MessageBox.Show(string.Concat("Printer Stateful Address is not accessible\n\n",
                                              "Stateful address: {0}\n".FormatWith(activityData.Ipv6StateFullAddress)),
                                "Stateful Address Not Accessible", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return(new PluginExecutionResult(PluginResult.Failed, "Printer Stateful Address is not accessible"));
            }

            /* Since multiple clients can access drivers, print driver is copied to local machine so as to avoid 'File in use' exception.
             * Driver path is updated to local temp directory for further use.
             * */

            string tempDriverDirectory = Path.Combine(Path.GetTempPath(), "PrintDriver");

            TraceFactory.Logger.Debug("Local printer driver location: {0}".FormatWith(tempDriverDirectory));

            if (Directory.Exists(tempDriverDirectory))
            {
                Directory.Delete(tempDriverDirectory, true);
            }

            foreach (string dirPath in Directory.GetDirectories(activityData.DriverPackagePath, "*", SearchOption.AllDirectories))
            {
                Directory.CreateDirectory(dirPath.Replace(activityData.DriverPackagePath, tempDriverDirectory));
            }

            foreach (string filePath in Directory.GetFiles(activityData.DriverPackagePath, "*.*", SearchOption.AllDirectories))
            {
                File.Copy(filePath, filePath.Replace(activityData.DriverPackagePath, tempDriverDirectory), true);
            }

            activityData.DriverPackagePath = tempDriverDirectory;

            // By default, adding P9100 printer so that driver installation is complete while adding WS Printer.
            printer.Install(IPAddress.Parse(activityData.Ipv4Address), Printer.Printer.PrintProtocol.RAW, activityData.DriverPackagePath, activityData.DriverModel, 9100);

            // If WSP test is selected, Show a pop-up to Add the printer.
            if (isWSPSelected)
            {
                /* If a WSP test is selected in any scenario created by user, pop a message box to add the printer.
                 * Status on whether a WSP test is selected are maintained in the config file (etlhubrepo\boi\CTC\<Product_Family>temp\<Session_ID>.xml) with attribute 'WSP_Print'.
                 * In case this scenario is added with WSP test, Pop-up message. Once the Ok button is clicked, updated the 'Status' on config file to 'Completed'.
                 * */

                XElement  localMachine = null;
                XDocument document     = XDocument.Load(xmlFilePath);
                XElement  element      = document.Element("Machines");

                foreach (var vm in element.Elements("Machine"))
                {
                    if (vm.Attribute("VM_Name").Value.Equals(Environment.MachineName))
                    {
                        localMachine = vm;
                        TraceFactory.Logger.Info("Machine: {0}".FormatWith(localMachine.Attribute("VM_Name").Value));
                        break;
                    }
                }

                MessageBox.Show("Add WS Printer and click 'OK'.", "Add WS Printer", MessageBoxButtons.OK, MessageBoxIcon.Information);
                localMachine.SetAttributeValue("Status", "Completed");
                element.Save(xmlFilePath);
            }

            /* Wait till all clients are ready for execution: If a client is configured with WSP test, wait till user adds the printer.
             * This case is handled with updation of the config file on status of WS Printer installation.
             * Traverse through all Elements and check for 'Status' attribute to know the status on installation of WS Printer.
             * */

            bool isWSPrinterInstalled = true;

            do
            {
                TraceFactory.Logger.Debug("Waiting for all clients to complete WS Printer installation.");

                // In case isWSPrinterInstalled is set to false while traversing through the config file, set it back to true for next iteration
                isWSPrinterInstalled = true;

                // Wait for some time so that other clients update the status on WS Printer installation
                Thread.Sleep(TimeSpan.FromSeconds(10));

                // Reload the file to get the most updated data
                XDocument xDocument = XDocument.Load(xmlFilePath);
                XElement  xElement  = xDocument.Element("Machines");

                foreach (var vm in xElement.Elements("Machine"))
                {
                    isWSPrinterInstalled &= "Completed".Equals(vm.Attribute("Status").Value);
                }
            } while (!isWSPrinterInstalled);

            if (null == _printTests)
            {
                _printTests = new ComplexPrintTests(activityData);
            }

            foreach (int testNumber in activityData.SelectedTests)
            {
                ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                _printTests.RunTest(executionData, testNumber, IPAddress.Parse(activityData.Ipv4Address), activityData.ProductFamily);
            }

            return(new PluginExecutionResult(PluginResult.Passed));
        }
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            NetworkNamingServiceActivityData activityData = executionData.GetMetadata <NetworkNamingServiceActivityData>(CtcMetadataConverter.Converters);

            #region Scenario Prerequisites

            //Check the Windows Server Service,Packet Capture service and Kiwi Syslog server is up and running
            CtcUtility.StartService("WindowsServerService", activityData.PrimaryDhcpServerIPAddress);
            CtcUtility.StartService("PacketCaptureService", activityData.PrimaryDhcpServerIPAddress);
            CtcUtility.StartService("Kiwi Syslog Server", activityData.PrimaryDhcpServerIPAddress);

            //Check dns and wins server is up and running on both primary and secondary dhcp server
            CtcUtility.StartService(@"dns", activityData.PrimaryDhcpServerIPAddress);
            CtcUtility.StartService("WINS", activityData.PrimaryDhcpServerIPAddress);
            CtcUtility.StartService(@"dns", activityData.SecondDhcpServerIPAddress);
            CtcUtility.StartService("WINS", activityData.SecondDhcpServerIPAddress);

            //Check the Wireless printer ip is accessible
            if (activityData.SelectedTests.Contains(678968))
            {
                if (!(NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.WirelessIPv4Address), TimeSpan.FromSeconds(20))))
                {
                    MessageBox.Show(string.Concat("Wireless Printer IP Address is not accessible\n\n"),
                                    "Wireless IP Address Not Accessible", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(new PluginExecutionResult(PluginResult.Failed, "Wireless Printer IP Address is not accessible"));
                }
            }

            //Check whether all devices are accesible and the server IP
            CtcUtility.CheckPrinterConnectivity(activityData.WiredIPv4Address, activityData.PrimaryDhcpServerIPAddress,
                                                activityData.SecondPrinterIPAddress, activityData.SecondDhcpServerIPAddress,
                                                activityData.LinuxServerIPAddress, activityData.SwitchIpAddress);

            // Fetch the VLAN details.
            GetVlanDetails(ref activityData);

            // Check if Switch VLAN details are fetched
            if (3 != activityData.VirtualLanDetails.Count)
            {
                MessageBox.Show(string.Concat("Unable to fetch Switch VLAN details\n\n",
                                              "Check whether Printer is connected to Network Switch.\n",
                                              "Switch should be configured with 3 network virtual LAN."),
                                "Network switch not found", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return(new PluginExecutionResult(PluginResult.Failed, "Unable to fetch Switch VLAN details"));
            }

            //Reservation for Primary Printer
            using (DhcpApplicationServiceClient client = DhcpApplicationServiceClient.Create(activityData.PrimaryDhcpServerIPAddress))
            {
                Printer.Printer printer = PrinterFactory.Create(activityData.ProductFamily, activityData.WiredIPv4Address);
                activityData.PrinterMacAddress = printer.MacAddress.Replace(":", string.Empty);
                client.Channel.DeleteReservation(activityData.PrimaryDhcpServerIPAddress, client.Channel.GetDhcpScopeIP(activityData.PrimaryDhcpServerIPAddress),
                                                 activityData.WiredIPv4Address, activityData.PrinterMacAddress);

                if (client.Channel.CreateReservation(activityData.PrimaryDhcpServerIPAddress, client.Channel.GetDhcpScopeIP(activityData.PrimaryDhcpServerIPAddress),
                                                     activityData.WiredIPv4Address, activityData.PrinterMacAddress, ReservationType.Both))
                {
                    TraceFactory.Logger.Info("Primary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP : Succeeded");
                }
                else
                {
                    TraceFactory.Logger.Info("Primary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed");
                    return(new PluginExecutionResult(PluginResult.Failed, "Primary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed"));
                }

                activityData.PrimaryDhcpIPv6Address = client.Channel.GetIPv6Address();
            }

            //Reservation for Secondary Printer[user may give input as primary server ip/secondary server ip ,so getting server ip based on the printer ipaddress]
            string secondDhcpServerIPAddress = Printer.Printer.GetDHCPServerIP(IPAddress.Parse(activityData.SecondPrinterIPAddress)).ToString();
            using (DhcpApplicationServiceClient client = DhcpApplicationServiceClient.Create(secondDhcpServerIPAddress))
            {
                Printer.Printer printer = PrinterFactory.Create(activityData.ProductFamily, activityData.SecondPrinterIPAddress);
                string          secondPrinterMacAddress = printer.MacAddress.Replace(":", string.Empty);
                client.Channel.DeleteReservation(secondDhcpServerIPAddress, client.Channel.GetDhcpScopeIP(secondDhcpServerIPAddress),
                                                 activityData.SecondPrinterIPAddress, secondPrinterMacAddress);

                if (client.Channel.CreateReservation(secondDhcpServerIPAddress, client.Channel.GetDhcpScopeIP(secondDhcpServerIPAddress),
                                                     activityData.SecondPrinterIPAddress, secondPrinterMacAddress, ReservationType.Both))
                {
                    TraceFactory.Logger.Info("Secondary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP : Succeeded");
                }
                else
                {
                    TraceFactory.Logger.Info("Secondary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed");
                    return(new PluginExecutionResult(PluginResult.Failed, "Secondary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed"));
                }
            }

            using (DhcpApplicationServiceClient client = DhcpApplicationServiceClient.Create(activityData.SecondDhcpServerIPAddress))
            {
                activityData.SecondaryDhcpIPv6Address = client.Channel.GetIPv6Address();
            }

            #endregion

            // create instance of ews adapter
            EwsWrapper.Instance().Create(Enum <PrinterFamilies> .Parse(activityData.ProductFamily), activityData.ProductName, activityData.WiredIPv4Address, Path.Combine(activityData.SitemapPath, activityData.SiteMapVersion), BrowserModel.Firefox);

            EwsWrapper.Instance().Start();
            EwsWrapper.Instance().WakeUpPrinter();
            EwsWrapper.Instance().SetAdvancedOptions();

            //create instance of SNMP wrapper
            SnmpWrapper.Instance().Create(activityData.WiredIPv4Address);

            //create instance of Telnet wrapper
            TelnetWrapper.Instance().Create(activityData.WiredIPv4Address);

            //Enabling IPV6 startup
            EwsWrapper.Instance().SetDHCPv6OnStartup(true);
            EwsWrapper.Instance().SetIPv6(false);
            EwsWrapper.Instance().SetIPv6(true);
            EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();

            if (null == _networkNamingTests)
            {
                _networkNamingTests = new NetworkNamingServiceTests(activityData);
            }

            // assign the session id to activity data
            activityData.SessionId = executionData.SessionId;

            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                    _networkNamingTests.RunTest(executionData, testNumber, IPAddress.Parse(activityData.WiredIPv4Address), (ProductFamilies)Enum.Parse(typeof(ProductFamilies), activityData.ProductFamily));
                }
                catch (Exception generalException)
                {
                    TraceFactory.Logger.Info("Test {0} failed with error: {1}".FormatWith(testNumber, generalException.Message));
                }
            }

            EwsWrapper.Instance().Stop();

            return(new PluginExecutionResult(PluginResult.Passed));
        }
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            // create activity data
            IPConfigurationActivityData activityData = executionData.GetMetadata <IPConfigurationActivityData>();

            // Check if printer is accessible

            if (!(NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.PrimaryWiredIPv4Address), TimeSpan.FromSeconds(20))) &&
                Utility.IsClientConfiguredWithServerIP(activityData.SecondDhcpServerIPAddress, activityData.LinuxServerIPAddress))
            {
                MessageBox.Show(string.Concat("Printer IP Address is not accessible or Client is not configured with Server IP Address.\n\n",
                                              "Make sure you have provided valid Printer IP Address and is accessible.\n",
                                              "Check if Client has acquired IPv4 Address from Secondary DHCP Server.\n",
                                              "Check if Client has acquired IPv4 Address from Linux Server."),
                                "IP Address Not Accessible", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(new PluginExecutionResult(PluginResult.Failed, "Printer IP Address is not accessible or Client is not configured with Server IP Address."));
            }

            // Check if the required services are running on DHCP server
            if (!IsServicesRunning(activityData.PrimaryDhcpServerIPAddress, activityData.SecondDhcpServerIPAddress))
            {
                return(new PluginExecutionResult(PluginResult.Failed, "Services are not running on DHCP server."));
            }

            // create instance of ews adapter
            EwsWrapper.Instance().Create(activityData.ProductFamily, activityData.ProductName, activityData.PrimaryWiredIPv4Address, activityData.SitemapsVersion,
                                         BrowserModel.Firefox, EwsAdapterType.WebDriverAdapter);

            EwsWrapper.Instance().Start();


            EwsWrapper.Instance().WakeUpPrinter();
            EwsWrapper.Instance().SetAdvancedOptions();

            IPAddress secondaryAddress = null;

            if (IPAddress.TryParse(activityData.SecondaryWiredIPv4Address, out secondaryAddress))
            {
                EwsWrapper.Instance().ChangeDeviceAddress(secondaryAddress);
                EwsWrapper.Instance().SetAdvancedOptions();
            }

            if (IPAddress.TryParse(activityData.WirelessIPv4Address, out secondaryAddress))
            {
                EwsWrapper.Instance().ChangeDeviceAddress(secondaryAddress);
                EwsWrapper.Instance().SetAdvancedOptions();
            }

            EwsWrapper.Instance().ChangeDeviceAddress(activityData.PrimaryWiredIPv4Address);

            Printer.Printer printer = PrinterFactory.Create(activityData.ProductFamily, activityData.PrimaryWiredIPv4Address);

            try
            {
                activityData.PrimaryMacAddress = printer.MacAddress.Replace(":", string.Empty);
            }
            catch
            { }

            if (string.IsNullOrEmpty(activityData.PrimaryMacAddress))
            {
                TraceFactory.Logger.Info("Could not get the mac address for Secondary wired interface.");
                return(new PluginExecutionResult(PluginResult.Failed, "Could not get the mac address for Secondary wired interface."));
            }

            if (activityData.PrinterInterfaceType == CtcBase.Controls.InterfaceType.Single)
            {
                if (IPAddress.TryParse(activityData.SecondaryWiredIPv4Address, out secondaryAddress))
                {
                    try
                    {
                        printer = PrinterFactory.Create(activityData.ProductFamily, activityData.SecondaryWiredIPv4Address);
                        activityData.SecondaryMacAddress = printer.MacAddress;
                    }
                    catch { }

                    if (string.IsNullOrEmpty(activityData.SecondaryMacAddress))
                    {
                        TraceFactory.Logger.Info("Could not get the mac address for Secondary wired interface.");
                        return(new PluginExecutionResult(PluginResult.Failed, "Could not get the mac address for Secondary wired interface."));
                    }
                }

                if (IPAddress.TryParse(activityData.WirelessIPv4Address, out secondaryAddress))
                {
                    try
                    {
                        printer = PrinterFactory.Create(activityData.ProductFamily, activityData.WirelessIPv4Address);
                        activityData.WirelessMacAddress = printer.MacAddress;
                    }catch { }

                    if (string.IsNullOrEmpty(activityData.WirelessMacAddress))
                    {
                        TraceFactory.Logger.Info("Could not get the mac address for Secondary wired interface.");
                        return(new PluginExecutionResult(PluginResult.Failed, "Could not get the mac address for wireless interface."));
                    }
                }
            }

            DhcpApplicationServiceClient serviceFunction = DhcpApplicationServiceClient.Create(activityData.PrimaryDhcpServerIPAddress);

            activityData.DHCPScopeIPAddress        = serviceFunction.Channel.GetDhcpScopeIP(activityData.PrimaryDhcpServerIPAddress);
            activityData.ServerDNSPrimaryIPAddress = serviceFunction.Channel.GetPrimaryDnsServer(activityData.PrimaryDhcpServerIPAddress, activityData.DHCPScopeIPAddress);
            activityData.SecondaryDnsIPAddress     = serviceFunction.Channel.GetSecondaryDnsServer(activityData.PrimaryDhcpServerIPAddress, activityData.DHCPScopeIPAddress);
            activityData.ServerHostName            = serviceFunction.Channel.GetHostName(activityData.PrimaryDhcpServerIPAddress, activityData.DHCPScopeIPAddress);
            activityData.DomainName            = serviceFunction.Channel.GetDomainName(activityData.PrimaryDhcpServerIPAddress, activityData.DHCPScopeIPAddress);
            activityData.ServerRouterIPAddress = serviceFunction.Channel.GetRouterAddress(activityData.PrimaryDhcpServerIPAddress, activityData.DHCPScopeIPAddress);
            activityData.ServerDNSSuffix       = serviceFunction.Channel.GetDnsSuffix(activityData.PrimaryDhcpServerIPAddress, activityData.DHCPScopeIPAddress);

            string ipv6Scope = serviceFunction.Channel.GetIPv6Scope(activityData.PrimaryDhcpServerIPAddress);

            if (string.IsNullOrEmpty(ipv6Scope))
            {
                MessageBox.Show(string.Concat("Unable to fetch IPv6 Scope \n\n",
                                              "Check whether DHCP IPv6 Scope is configured on DHCP server."),
                                "IPv6 Scope Not found", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return(new PluginExecutionResult(PluginResult.Failed, "Check whether DHCP IPv6 Scope is configured on DHCP server."));
            }

            activityData.DHCPScopeIPv6Address = serviceFunction.Channel.GetIPv6Scope(activityData.PrimaryDhcpServerIPAddress);

            // Fetch the VLAN details.
            GetVlanDetails(ref activityData);

            // Check if Switch VLAN details are fetched
            if (3 != activityData.VirtualLanDetails.Count)
            {
                MessageBox.Show(string.Concat("Unable to fetch Switch VLAN details\n\n",
                                              "Check whether Printer is connected to Network Switch.\n",
                                              "Switch should be configured with 3 network virtual LAN."),
                                "Network switch not found", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return(new PluginExecutionResult(PluginResult.Failed, "Unable to fetch Switch VLAN details. Check whether Printer is connected to Network Switch. Switch should be configured with 3 network virtual LAN."));
            }

            // Router Details: Address, Id, IPv6 Addresses
            IRouter router = null;

            activityData.RouterAddress = ROUTER_IP_FORMAT.FormatWith(activityData.PrimaryWiredIPv4Address.Substring(0, activityData.PrimaryWiredIPv4Address.LastIndexOf(".", StringComparison.CurrentCultureIgnoreCase)));
            router = RouterFactory.Create(IPAddress.Parse(activityData.RouterAddress), ROUTER_USERNAME, ROUTER_PASSWORD);

            Dictionary <int, IPAddress> routerVlans = router.GetAvailableVirtualLans();

            activityData.RouterVlanId = routerVlans.Where(x => (null != x.Value) && (x.Value.IsInSameSubnet(IPAddress.Parse(activityData.RouterAddress)))).FirstOrDefault().Key;

            RouterVirtualLAN       routerVlan          = router.GetVirtualLanDetails(activityData.RouterVlanId);
            Collection <IPAddress> routerIPv6Addresses = router.GetIPv6Addresses(routerVlan.IPv6Details);

            activityData.RouterIPv6Addresses = new Collection <string>(routerIPv6Addresses.Select(x => x.ToString()).ToList());

            // Add source IP Address
            Utility.AddSourceIPAddress(activityData.PrimaryDhcpServerIPAddress, activityData.LinuxServerIPAddress);

            //create instance of SNMP wrapper
            SnmpWrapper.Instance().Create(activityData.PrimaryWiredIPv4Address);

            //create instance of Telnet wrapper
            TelnetWrapper.Instance().Create(activityData.PrimaryWiredIPv4Address);

            if (!ManageReservation(activityData))
            {
                return(new PluginExecutionResult(PluginResult.Failed, "Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed"));
            }

            TraceFactory.Logger.Info("The Server Configured Value retrieved from the DHCP Server are as follows:");
            TraceFactory.Logger.Info("MacAddress:{0}, DNSPrimaryIP:{1}, HostName:{2}, RouterIP:{3}, DNSSuffix:{4}".FormatWith(activityData.PrimaryMacAddress, activityData.ServerDNSPrimaryIPAddress,
                                                                                                                              activityData.ServerHostName, activityData.ServerRouterIPAddress, activityData.ServerDNSSuffix));

            // assign the session id to activity id
            activityData.SessionId = executionData.SessionId;

            if (null == _ipConfigTests)
            {
                _ipConfigTests = new IPConfigurationTests(activityData);
            }

            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ApplicationFlowControl.Instance.CheckWait(LogPauseState, LogResumeState);
                    _ipConfigTests.RunTest(executionData, testNumber, activityData.PrimaryWiredIPv4Address, (ProductFamilies)Enum.Parse(typeof(ProductFamilies), activityData.ProductFamily));
                }
                catch (Exception generalException)
                {
                    TraceFactory.Logger.Info("Test {0} failed with error: {1}".FormatWith(testNumber, generalException.Message));
                }
            }

            EwsWrapper.Instance().Stop();

            return(new PluginExecutionResult(PluginResult.Passed));
        }
Beispiel #21
0
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            // create activity data
            SecurityActivityData activityData = executionData.GetMetadata <SecurityActivityData>(CtcMetadataConverter.Converters);

            Printer.Printer printer = PrinterFactory.Create(activityData.ProductFamily, activityData.WiredIPv4Address);
            activityData.WiredMacAddress = printer.MacAddress;

            TraceFactory.Logger.Info("Wired Mac Address: {0}".FormatWith(activityData.WiredMacAddress));

            if (activityData.ProductFamily.EqualsIgnoreCase(PrinterFamilies.VEP.ToString()))
            {
                IPAddress ipAddress;

                if (IPAddress.TryParse(activityData.SecondaryWiredIPv4Address, out ipAddress))
                {
                    printer = PrinterFactory.Create(activityData.ProductFamily, activityData.SecondaryWiredIPv4Address);
                    activityData.SecondaryWiredMacAddress = printer.MacAddress;
                    TraceFactory.Logger.Info("Secondary Wired Mac Address: {0}".FormatWith(activityData.SecondaryWiredMacAddress));
                }

                if (IPAddress.TryParse(activityData.WirelessIPv4Address, out ipAddress))
                {
                    printer = PrinterFactory.Create(activityData.ProductFamily, activityData.WirelessIPv4Address);
                    activityData.WirelessMacAddress = printer.MacAddress;

                    TraceFactory.Logger.Info("Wireless Mac Address: {0}".FormatWith(activityData.WirelessMacAddress));
                }
            }

            List <NetworkInterface> clientNetworks = NetworkInterface.GetAllNetworkInterfaces().Where(n => n.OperationalStatus == OperationalStatus.Up).ToList();
            List <IPAddress>        localAddresses = NetworkUtil.GetLocalAddresses().Where(x => x.AddressFamily == AddressFamily.InterNetwork).ToList();

            EwsWrapper.Instance().Create(Enum <PrinterFamilies> .Parse(activityData.ProductFamily), activityData.ProductName, activityData.WiredIPv4Address, Path.Combine(activityData.SitemapPath, activityData.SitemapsVersion), BrowserModel.Firefox);
            EwsWrapper.Instance().Start();
            EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();

            if (!SecurityScenarioPrerequisites(activityData, clientNetworks, localAddresses))
            {
                return(new PluginExecutionResult(PluginResult.Failed, "Failed in Scenario pre-requisites"));
            }
            //create instance of SNMP wrapper
            SnmpWrapper.Instance().Create(activityData.WiredIPv4Address);

            //create instance of Telnet wrapper
            TelnetWrapper.Instance().Create(activityData.WiredIPv4Address);

            if (null == _securitytests)
            {
                _securitytests = new SecurityTests(activityData);
            }

            // Execute the selected tests
            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                    _securitytests.RunTest(executionData, testNumber, IPAddress.Parse(activityData.WiredIPv4Address), (ProductFamilies)Enum.Parse(typeof(ProductFamilies), activityData.ProductFamily));
                }
                catch (Exception ex)
                {
                    TraceFactory.Logger.Fatal("Error while executing Test:{0} \n".FormatWith(testNumber, ex.Message));
                }
            }

            EwsWrapper.Instance().Stop();
            ManageClientReservation(clientNetworks, localAddresses, activityData, true);

            return(new PluginExecutionResult(PluginResult.Passed));
        }
Beispiel #22
0
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            // create activity data
            CertificateManagementActivityData activityData = executionData.GetMetadata <CertificateManagementActivityData>(CtcMetadataConverter.Converters);
            var             ipV4Address = IPAddress.Parse(activityData.Ipv4Address);
            PrinterFamilies family      = (PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), Enum <ProductFamilies> .Value(activityData.ProductFamily));

            // Create instance of ews adapter
            // Remember to give Combined sitemapPath + sitemapVersion
            EwsWrapper.Instance().Create(family, activityData.ProductName, activityData.Ipv4Address, Path.Combine(activityData.SitemapPath, activityData.SiteMapVersion), BrowserModel.Firefox);

            EwsWrapper.Instance().Start();
            EwsWrapper.Instance().WakeUpPrinter();
            EwsWrapper.Instance().SetAdvancedOptions();
            EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();

            SnmpWrapper.Instance().Create(activityData.Ipv4Address);
            SnmpWrapper.Instance().SetCommunityName("public");

            TelnetWrapper.Instance().Create(activityData.Ipv4Address);

            //  PrinterFamilies family = (PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), Enum<ProductFamilies>.Value(activityData.ProductFamily));
            Printer.Printer printer = PrinterFactory.Create(family, ipV4Address);
            activityData.MacAddress = printer.MacAddress;

            //Check the Windows Server Service,Packet Capture service and Kiwi Syslog server is up and running
            CtcUtility.StartService("WindowsServerService", activityData.DhcpServerIp);
            CtcUtility.StartService(@"dns", activityData.DhcpServerIp);

            using (DhcpApplicationServiceClient dhcpClient = DhcpApplicationServiceClient.Create(activityData.DhcpServerIp))
            {
                string scope = dhcpClient.Channel.GetDhcpScopeIP(activityData.DhcpServerIp);
                dhcpClient.Channel.DeleteReservation(activityData.DhcpServerIp, scope, activityData.Ipv4Address, activityData.MacAddress);

                if (dhcpClient.Channel.CreateReservation(activityData.DhcpServerIp, scope, ipV4Address.ToString(), activityData.MacAddress, ReservationType.Both))
                {
                    TraceFactory.Logger.Info("Successfully created reservation for IP address: {0}, Mac address: {1} for {2}".FormatWith(ipV4Address, activityData.MacAddress, ReservationType.Both));
                }
                else
                {
                    TraceFactory.Logger.Info("Failed to create reservation for IP address: {0}, Mac address: {1} for {2}".FormatWith(ipV4Address, activityData.MacAddress, ReservationType.Both));
                    return(new PluginExecutionResult(PluginResult.Failed, "Failed to create reservation for IP address: {0}, Mac address: {1} for {2}".FormatWith(ipV4Address, activityData.MacAddress, ReservationType.Both)));
                }
            }

            if (null == _tests)
            {
                _tests = new CertificateManagementTests(activityData);
            }

            // Execute the selected tests
            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                    _tests.RunTest(executionData, testNumber, ipV4Address, activityData.ProductFamily);
                }
                catch (Exception ex)
                {
                    TraceFactory.Logger.Fatal("** Error while executing Test:{0} \n".FormatWith(testNumber, ex.Message));
                    continue;
                }
            }

            EwsWrapper.Instance().Stop();

            return(new PluginExecutionResult(PluginResult.Passed));
        }
Beispiel #23
0
        public void TestMethod1()
        {
            using (PrintDbContext printDb = TPrintDbFactory.MarkShopDb())
            {
                var parameter = new ZRui.Web.Core.Printer.PrintAPIArgsModel.AddPrinter()
                {
                    shopId      = 4,
                    sn          = "817513721",
                    skey        = "ew64m5j4",
                    printerType = PrinterType.FEIE
                };

                using (ShopDbContext shopDb = TShopDbContxtFactory.MarkShopDb())
                {
                    if (string.IsNullOrEmpty(parameter.sn))
                    {
                        Error("SnList(打印机#KEY)参数不能为空");
                    }
                    if (!parameter.shopId.HasValue)
                    {
                        Error("商铺ID不能为空");
                    }
                    if (!parameter.printerType.HasValue)
                    {
                        Error("打印机类型不能为空");
                    }
                    Shop shop = shopDb.GetSingle <Shop>(parameter.shopId.Value);
                    if (shop == null)
                    {
                        Error("商铺不存在");
                    }
                    //表示是否已经添加过
                    Data.Printer printer = printDb.Printer.FirstOrDefault(s => !s.IsDel && s.ShopID == parameter.shopId && s.SN == parameter.sn &&
                                                                          s.SKey == parameter.skey && s.IsSuccess);
                    bool IsExists = printer != null;
                    if (IsExists)
                    {
                        Error("设备已经添加过");
                    }
                    PrinterBase @base  = PrinterFactory.Create(parameter.printerType.Value);//)
                    string      result = @base.AddPrinter(new PrintParameter()
                    {
                        SnList = $"{parameter.sn}#{parameter.skey}#"
                    });
                    //添加之后保存到数据库中
                    Dictionary <string, object> tempdic = JsonConvert.DeserializeObject <Dictionary <string, object> >(result);
                    if (!tempdic.ContainsKey("data"))
                    {
                        Error("添加失败");
                    }

                    Data.Printer _printermodel = new Data.Printer();
                    #region 实体赋值
                    _printermodel.ShopID      = parameter.shopId.Value;
                    _printermodel.SN          = parameter.sn;
                    _printermodel.SKey        = parameter.skey;
                    _printermodel.AddTime     = DateTime.Now;
                    _printermodel.PrinterType = parameter.printerType.Value;
                    _printermodel.IsEnable    = true;
                    //_printermodel.Times = string.IsNullOrEmpty(parameter.Times) || int.TryParse(parameter.Times, out int t) ? 1 : t == 0 ? 1 : t;
                    Dictionary <string, object> datadic = JsonConvert.DeserializeObject <Dictionary <string, object> >(tempdic["data"].ToString());
                    JArray ok = datadic["ok"] as JArray;
                    JArray no = datadic["no"] as JArray;
                    //验证打印机是否在接口添加成功
                    //如果之前添加失败了, 将修改原来的数据,否则重新添加
                    #endregion

                    if (ok.Count > 0)
                    {
                    }
                    else
                    {
                        Error(no[0].Value <string>());
                    }
                }
            }

            void Error(string s)
            {
            };
        }
Beispiel #24
0
        public static void PrintOrder(this PrintDbContext printDbContext, ShopDbContext db, ShopOrder shopOrder, string shopname)
        {
            try
            {
                if (shopOrder == null)
                {
                    throw new Exception("订单错误");
                }
                List <ShopOrderItem> items = db.Query <ShopOrderItem>()
                                             .Where(m => !m.IsDel)
                                             .Where(m => m.ShopOrderId == shopOrder.Id)
                                             .ToList();
                if (items.Count == 0)
                {
                    return;
                }
                List <OrderInfo> orderInfo = items.Select(s => new OrderInfo()
                {
                    Name  = $"{s.CommodityName}({s.SkuSummary})",
                    Price = Math.Round(s.SalePrice / 100d, 2),
                    Count = s.Count
                }).ToList();
                string stringorderlist = JsonConvert.SerializeObject(orderInfo);

                List <Printer> printers = printDbContext.Query <Printer>()
                                          .Where(s => !s.IsDel)
                                          .Where(s => s.ShopID == shopOrder.ShopId && s.IsEnable).ToList();
                if (printers.Count == 0)
                {
                    return;
                }

                PrintParameter parameter = GetPrintParameter(db, shopOrder);
                parameter.ShopName = shopname;
                parameter.List     = orderInfo;

                foreach (var item in printers)
                {
                    //StringBuilder postData = new StringBuilder("sn=" + item.SN);
                    parameter.SN    = item.SN;
                    parameter.Times = item.Times + "";
                    PrintModel model = printDbContext.Query <PrintModel>().FirstOrDefault(s => s.ID == item.ModelID);
                    if (model == null)
                    {
                        model = printDbContext.Set <PrintModel>().Find(2);
                    }
                    parameter.ModelContent = model.ModelContent;
                    PrinterBase @base = PrinterFactory.Create(item.PrinterType);//)
                    string      temp  = @base.PrinterRequest(parameter, item);
                    #region 数据库操作
                    PrintRecord record = new PrintRecord();
                    //处理接口返回数据
                    Dictionary <string, object> dic = JsonConvert.DeserializeObject <Dictionary <string, object> >(temp);
                    //实体赋值
                    record.SN         = item.SN;
                    record.OrderID    = @base.GetOrderID(temp);// dic.ContainsKey("data") && dic["msg"].Equals("ok") ? dic["data"].ToString() : "未能成功打印";
                    record.Title      = parameter.Title;
                    record.OrderList  = stringorderlist;
                    record.TotalMoney = (float)parameter.TotalMoney;
                    record.Address    = parameter.Address;
                    record.OrderName  = parameter.OrderName;
                    record.Mobile     = parameter.Mobile;
                    record.OrderTime  = Convert.ToDateTime(parameter.OrderTime);
                    record.QRAddress  = parameter.QRAddress;
                    record.Remark     = shopOrder.Remark;
                    printDbContext.AddTo(record);
                    #endregion
                }
                shopOrder.IsPrint = true;
            }
            catch (Exception e)
            {
                //_logger.LogError("打印机错误:{0}", e.Message);
            }
        }
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            // create activity data
            IPSecurityActivityData activityData = executionData.GetMetadata <IPSecurityActivityData>(CtcMetadataConverter.Converters);

            #region Scenario Prerequisites

            // TODO: Need to enable broadcast and multicast option in failsafe
            // TODO: Cleaning up the rules on client side and on the printer


            //Check the Windows Server Service,Packet Capture service and Kiwi Sys log server is up and running
            CtcUtility.StartService("WindowsServerService", activityData.PrimaryDhcpServerIPAddress);
            CtcUtility.StartService("PacketCaptureService", activityData.PrimaryDhcpServerIPAddress);

            Printer.Printer printer = PrinterFactory.Create(activityData.ProductFamily, activityData.WiredIPv4Address);
            //Reservation for Primary Printer
            using (DhcpApplicationServiceClient client = DhcpApplicationServiceClient.Create(activityData.PrimaryDhcpServerIPAddress))
            {
                activityData.PrinterMacAddress = printer.MacAddress.Replace(":", string.Empty);
                client.Channel.DeleteReservation(activityData.PrimaryDhcpServerIPAddress, client.Channel.GetDhcpScopeIP(activityData.PrimaryDhcpServerIPAddress),
                                                 activityData.WiredIPv4Address, activityData.PrinterMacAddress);

                if (client.Channel.CreateReservation(activityData.PrimaryDhcpServerIPAddress, client.Channel.GetDhcpScopeIP(activityData.PrimaryDhcpServerIPAddress),
                                                     activityData.WiredIPv4Address, activityData.PrinterMacAddress, ReservationType.Both))
                {
                    TraceFactory.Logger.Info("Primary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP : Succeeded");
                }
                else
                {
                    TraceFactory.Logger.Info("Primary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed");
                    return(new PluginExecutionResult(PluginResult.Failed, "Primary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed"));
                }
            }

            #endregion

            // create instance of EWS adapter
            EwsWrapper.Instance().Create(Enum <PrinterFamilies> .Parse(activityData.ProductFamily), activityData.ProductName, activityData.WiredIPv4Address, Path.Combine(activityData.SitemapPath, activityData.SitemapsVersion), BrowserModel.Firefox, EwsAdapterType.WebDriverAdapter);

            EwsWrapper.Instance().Start();
            EwsWrapper.Instance().WakeUpPrinter();

            //create instance of SNMP wrapper
            SnmpWrapper.Instance().Create(activityData.WiredIPv4Address);

            //create instance of Telnet wrapper
            TelnetWrapper.Instance().Create(activityData.WiredIPv4Address);

            //IPv6 and Dhcpv6 on startup should be enabled to get IPv6 addresses. Applicable only for VEP
            if (PrinterFamilies.VEP.ToString().EqualsIgnoreCase(activityData.ProductFamily) ||
                PrinterFamilies.LFP.ToString().EqualsIgnoreCase(activityData.ProductFamily))
            {
                EwsWrapper.Instance().SetDHCPv6(true);
                EwsWrapper.Instance().SetDHCPv6OnStartup(true);
                EwsWrapper.Instance().SetIPv6(false);
                EwsWrapper.Instance().SetIPv6(true);
                EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();
            }

            TraceFactory.Logger.Info("Collecting Ipv6 addresses of the printer");
            activityData.IPV6StatefullAddress = printer.IPv6StateFullAddress.ToString();
            activityData.IPV6StatelessAddress = printer.IPv6StatelessAddresses[0].ToString();
            activityData.LinkLocalAddress     = printer.IPv6LinkLocalAddress.ToString();

            // assign session id to activity data
            activityData.SessionId = executionData.SessionId;

            if (null == _ipSecuritytests)
            {
                _ipSecuritytests = new IPSecurityTests(activityData);
            }

            // Execute the selected tests
            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                    _ipSecuritytests.RunTest(executionData, testNumber, IPAddress.Parse(activityData.WiredIPv4Address), (ProductFamilies)Enum.Parse(typeof(ProductFamilies), activityData.ProductFamily));
                }
                catch (Exception ex)
                {
                    TraceFactory.Logger.Fatal("Error while executing Test:{0} \n".FormatWith(testNumber, ex.Message));
                    continue;
                }
            }

            EwsWrapper.Instance().Stop();

            return(new PluginExecutionResult(PluginResult.Passed));
        }
Beispiel #26
0
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            // create activity data
            DotOneXActivityData activityData = executionData.GetMetadata <DotOneXActivityData>(CtcMetadataConverter.Converters);
            PrinterFamilies     family       = (PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), activityData.ProductFamily);

            activityData.DotOneXUserName = DOT1X_USERNAME.FormatWith(activityData.RadiusServerType.ToString().ToLower(CultureInfo.CurrentCulture));
            activityData.DotOneXPassword = DOT1X_PASSWORD;
            activityData.SharedSecret    = SHARED_SECRET;
            activityData.PolicyName      = NETWORK_POLICY;

            bool continueTest = true;

            while (continueTest && !NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.Ipv4Address), TimeSpan.FromSeconds(30)))
            {
                continueTest = DotOneXTemplates.ShowErrorPopUp("Printer: {0} is not available.\nPlease cold reset the printer.".FormatWith(activityData.Ipv4Address));
            }

            if (!continueTest)
            {
                return(new PluginExecutionResult(PluginResult.Failed, "Printer: {0} is not available.\nPlease cold reset the printer.".FormatWith(activityData.Ipv4Address)));
            }

            // create instance of ews adapter
            EwsWrapper.Instance().Create(family, activityData.ProductName, activityData.Ipv4Address, Path.Combine(activityData.SitemapPath, activityData.SiteMapVersion), BrowserModel.Firefox);

            EwsWrapper.Instance().Start();

            EwsWrapper.Instance().WakeUpPrinter();

            EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();

            SnmpWrapper.Instance().Create(activityData.Ipv4Address);
            SnmpWrapper.Instance().SetCommunityName("public");

            TelnetWrapper.Instance().Create(activityData.Ipv4Address);

            //TODO: Migration issue even thought it is not migration issue why it is commented
            //EwsWrapper.Instance().SetWSDiscovery(true);

            Printer.Printer printer = PrinterFactory.Create(activityData.ProductFamily, activityData.Ipv4Address);
            activityData.MacAddress = printer.MacAddress;

            using (DhcpApplicationServiceClient dhcpClient = DhcpApplicationServiceClient.Create(activityData.DhcpServerIp))
            {
                string scope = dhcpClient.Channel.GetDhcpScopeIP(activityData.DhcpServerIp);
                dhcpClient.Channel.DeleteReservation(activityData.DhcpServerIp, scope, activityData.Ipv4Address, activityData.MacAddress);

                if (dhcpClient.Channel.CreateReservation(activityData.DhcpServerIp, scope, activityData.Ipv4Address, activityData.MacAddress, ReservationType.Both))
                {
                    TraceFactory.Logger.Info("Successfully created reservation for IP address: {0}, Mac address: {1} for {2}".FormatWith(activityData.Ipv4Address, activityData.MacAddress, ReservationType.Both));
                }
                else
                {
                    TraceFactory.Logger.Info("Failed to create reservation for IP address: {0}, Mac address: {1} for {2}".FormatWith(activityData.Ipv4Address, activityData.MacAddress, ReservationType.Both));
                    return(new PluginExecutionResult(PluginResult.Failed, "Failed to create reservation for IP address: {0}, Mac address: {1} for {2}".FormatWith(activityData.Ipv4Address, activityData.MacAddress, ReservationType.Both)));
                }
            }

            if (!ConfigureRadiusServer(activityData))
            {
                return(new PluginExecutionResult(PluginResult.Failed, "Failed to configure radius server"));
            }

            if (!ConfigureSwitch(activityData))
            {
                return(new PluginExecutionResult(PluginResult.Failed, "Failed to configure switch"));
            }

            activityData.SessionId = executionData.SessionId;

            if (null == _tests)
            {
                _tests = new DotOneXTests(activityData);
            }

            // Execute the selected tests
            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                    _tests.RunTest(executionData, testNumber, IPAddress.Parse(activityData.Ipv4Address), (ProductFamilies)Enum.Parse(typeof(ProductFamilies), activityData.ProductFamily));
                }
                catch (Exception ex)
                {
                    TraceFactory.Logger.Fatal("Error while executing Test:{0} \n".FormatWith(testNumber, ex.Message));
                }
            }

            EwsWrapper.Instance().Stop();

            return(new PluginExecutionResult(PluginResult.Passed));
        }
Beispiel #27
0
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            // create activity data
            WirelessActivityData activityData = executionData.GetMetadata <WirelessActivityData>(CtcMetadataConverter.Converters);

            string ipAddress = activityData.ProductFamily == ProductFamilies.VEP && activityData.PrinterInterfaceType == ProductType.MultipleInterface ? activityData.WirelessInterfaceAddress : activityData.PrimaryInterfaceAddress;


            bool continueTest = true;

            if (activityData.ProductFamily == ProductFamilies.VEP)
            {
                while (continueTest && !NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.WirelessInterfaceAddress), TimeSpan.FromSeconds(10)))
                {
                    continueTest = CtcUtility.ShowErrorPopup($"Printer: {activityData.WirelessInterfaceAddress} is not available.\n Please cold reset the printer.");
                }
            }

            while (continueTest && !NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.PrimaryInterfaceAddress), TimeSpan.FromSeconds(10)))
            {
                continueTest = CtcUtility.ShowErrorPopup($"Printer: {activityData.PrimaryInterfaceAddress} is not available.\n Please cold reset the printer.");
            }

            EwsWrapper.Instance().Create((PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), activityData.ProductFamily.ToString()), activityData.ProductName, ipAddress, Path.Combine(activityData.SitemapPath, activityData.SitemapVersion), BrowserModel.Firefox);

            EwsWrapper.Instance().Start();
            EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();

            SnmpWrapper.Instance().Create(ipAddress);

            TelnetWrapper.Instance().Create(ipAddress);

            string dhcpServerIp;

            if (activityData.ProductFamily == ProductFamilies.VEP)
            {
                Printer printer = PrinterFactory.Create(activityData.ProductFamily.ToString(), activityData.WirelessInterfaceAddress);

                if (string.IsNullOrEmpty(printer.MacAddress))
                {
                    TraceFactory.Logger.Info($"Failed to discover the mac address from IP address: {activityData.WirelessInterfaceAddress}");
                    return(new PluginExecutionResult(PluginResult.Failed, $"Failed to discover the mac address from IP address: {activityData.WirelessInterfaceAddress}"));
                }

                activityData.WirelessMacAddress = printer.MacAddress;

                string value = activityData.WirelessInterfaceAddress.Split('.')[2];

                dhcpServerIp = string.Format(CultureInfo.CurrentCulture, activityData.DhcpServerIp, value);

                using (DhcpApplicationServiceClient dhcpClient = DhcpApplicationServiceClient.Create(dhcpServerIp))
                {
                    string scope = dhcpClient.Channel.GetDhcpScopeIP(dhcpServerIp);
                    dhcpClient.Channel.DeleteReservation(dhcpServerIp, scope, activityData.WirelessInterfaceAddress, activityData.WirelessMacAddress);

                    if (dhcpClient.Channel.CreateReservation(dhcpServerIp, scope, activityData.WirelessInterfaceAddress, activityData.WirelessMacAddress, ReservationType.Both))
                    {
                        TraceFactory.Logger.Info($"Successfully created reservation for IP address: {activityData.WirelessInterfaceAddress}, Mac address: {activityData.WirelessMacAddress} for {ReservationType.Both}");
                    }
                    else
                    {
                        TraceFactory.Logger.Info($"Failed to create reservation for IP address: {activityData.WirelessInterfaceAddress}, Mac address: {activityData.WirelessMacAddress} for {ReservationType.Both}");
                        return(new PluginExecutionResult(PluginResult.Failed, $"Failed to create reservation for IP address: {activityData.WirelessInterfaceAddress}, Mac address: {activityData.WirelessMacAddress} for {ReservationType.Both}"));
                    }
                }
            }

            dhcpServerIp = activityData.DhcpServerIp.FormatWith(activityData.PrimaryInterfaceAddress.Split('.')[2]);

            using (DhcpApplicationServiceClient dhcpClient = DhcpApplicationServiceClient.Create(dhcpServerIp))
            {
                string wiredMacAddress = PrinterFactory.Create(activityData.ProductFamily.ToString(), activityData.PrimaryInterfaceAddress).MacAddress;


                if (string.IsNullOrEmpty(wiredMacAddress))
                {
                    TraceFactory.Logger.Info($"Failed to discover the mac address from IP address: {activityData.PrimaryInterfaceAddress}");
                    return(new PluginExecutionResult(PluginResult.Failed, $"Failed to discover the mac address from IP address: {activityData.PrimaryInterfaceAddress}"));
                }

                string scope = dhcpClient.Channel.GetDhcpScopeIP(dhcpServerIp);
                dhcpClient.Channel.DeleteReservation(dhcpServerIp, scope, activityData.PrimaryInterfaceAddress, wiredMacAddress);

                if (dhcpClient.Channel.CreateReservation(dhcpServerIp, scope, activityData.PrimaryInterfaceAddress, wiredMacAddress, ReservationType.Both))
                {
                    TraceFactory.Logger.Info($"Successfully created reservation for IP address: {activityData.PrimaryInterfaceAddress}, Mac address: {wiredMacAddress} for {ReservationType.Both}");
                }
                else
                {
                    TraceFactory.Logger.Info($"Failed to create reservation for IP address: {activityData.PrimaryInterfaceAddress}, Mac address: {wiredMacAddress} for {ReservationType.Both}");
                    return(new PluginExecutionResult(PluginResult.Failed, $"Failed to create reservation for IP address: {activityData.PrimaryInterfaceAddress}, Mac address: {wiredMacAddress} for {ReservationType.Both}"));
                }
            }

            activityData.SessionId = executionData.SessionId;

            if (null == _tests)
            {
                _tests = new WirelessTests(activityData);
            }

            // Execute the selected tests
            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                    _tests.RunTest(executionData, testNumber, IPAddress.Parse(ipAddress), (ProductFamilies)Enum.Parse(typeof(ProductFamilies), activityData.ProductFamily.ToString()));
                }
                catch (Exception ex)
                {
                    TraceFactory.Logger.Fatal($"Error while executing Test:{testNumber} {ex.Message}\n");
                }
            }

            EwsWrapper.Instance().Stop();

            return(new PluginExecutionResult(PluginResult.Passed));
        }