Inheritance: MonoBehaviour
Example #1
0
    public BXSSMainWindow()
    {
        _settings = new BXSSSettings();
        _settings.Load();
        _screenshot = new Screenshot(
            KSPUtil.ApplicationRootPath + "PluginData/BXSS/",
            () =>
                {
                    _prevUIState = Visible;
                    Visible = false;
                    if(_mainUIEnabled)
                        RenderingManager.ShowUI(false);
                },
            () =>
                {
                    Visible = _prevUIState;
                    if(_mainUIEnabled)
                        RenderingManager.ShowUI(true);
                });

        _collapsed = true;
        _mainUIEnabled = true;
        _autoIntervalEnabled = false;

        _autoIntervalStopwatch = new Stopwatch();

        WindowPosition = _settings.WindowPosition;

        Caption = "B.X.S.S";

        SetupControls();
    }
 public static ScreenshotModel From(Screenshot screenshot) 
 {
     return new ScreenshotModel()
     {
         ScreenshotId = screenshot.Id,
         Base64ImageString = screenshot.Base64ImageString,
         CreatedDate = screenshot.CreatedDate
     };
 }
Example #3
0
 // Use this for initialization
 void Awake()
 {
     if(_instance == null) {
         _instance = this;
         DontDestroyOnLoad(gameObject);
         #if UNITY_EDITOR
         InvokeRepeating("Take",3.0f,3.0f);
         #endif
     } else {
         Destroy(gameObject);
     }
 }
 public void StoreScreenshot(Screenshot screenshot)
 {
     using (var context = new AppCampusContext())
     {
         context.Screenshots.Add(
             new ScreenshotTable()
             {
                 Id = screenshot.Id,
                 DeviceId = screenshot.DeviceId,
                 CreatedDate = DateTime.UtcNow,
                 Base64ImageString = screenshot.Base64ImageString
             });
         context.SaveChanges();
     }
 }
Example #5
0
        private void Settings_Shown(object sender, EventArgs e)
        {
            exampleScreenshot = Screenshot.FromActiveWindow();

            var format = formatDropdown.Text;
            formatExample.Text = exampleScreenshot.GetFileName(format);
        }
        private static void SaveFullScreenShot(Guid guid, Screenshot screenshot)
        {
            CreateFolderIfNotExists();

            screenshot.SaveAsFile(string.Format("scr//octocat-full-{0}.png", guid), ScreenshotImageFormat.Png);
        }
Example #7
0
        /// <summary>
        ///     Process the capture based on the requested format.
        /// </summary>
        /// <param name="width">image width</param>
        /// <param name="height">image height</param>
        /// <param name="pitch">data pitch (bytes per row)</param>
        /// <param name="format">target format</param>
        /// <param name="pBits">IntPtr to the image data</param>
        /// <param name="request">The original requets</param>
        protected void ProcessCapture(int width, int height, int pitch, PixelFormat format, IntPtr pBits,
            ScreenshotRequest request)
        {
            if (request == null)
                return;

            if (format == PixelFormat.Undefined)
            {
                DebugMessage("Unsupported render target format");
                return;
            }

            // Copy the image data from the buffer
            var size = height*pitch;
            var data = new byte[size];
            Marshal.Copy(pBits, data, 0, size);

            // Prepare the response
            Screenshot response = null;

            if (request.Format == Direct3DHookLib.Interface.ImageFormat.PixelData)
            {
                // Return the raw data
                response = new Screenshot(request.RequestId, data)
                {
                    Format = request.Format,
                    PixelFormat = format,
                    Height = height,
                    Width = width,
                    Stride = pitch
                };
            }
            else
            {
                // Return an image
                using (var bm = data.ToBitmap(width, height, pitch, format))
                {
                    var imgFormat = ImageFormat.Bmp;
                    switch (request.Format)
                    {
                        case Direct3DHookLib.Interface.ImageFormat.Jpeg:
                            imgFormat = ImageFormat.Jpeg;
                            break;
                        case Direct3DHookLib.Interface.ImageFormat.Png:
                            imgFormat = ImageFormat.Png;
                            break;
                    }

                    response = new Screenshot(request.RequestId, bm.ToByteArray(imgFormat))
                    {
                        Format = request.Format,
                        Height = bm.Height,
                        Width = bm.Width
                    };
                }
            }

            // Send the response
            SendResponse(response);
        }
 public void SendScreenshotResponse(Screenshot screenshot)
 {
     if (_requestId != null && screenshot != null && screenshot.RequestId == _requestId.Value)
     {
         if (_completeScreenshot != null)
         {
             _completeScreenshot(screenshot);
         }
     }
 }
        public void pushScreenshot(Screenshot screenshot)
        {
            int last_index = lastScreenshotIndex;

            for (int i = 0; i < screenshots.Length - 1; i++)
            {
                screenshots[i + 1] = screenshots[i];
            }

            screenshots[0] = screenshot;
            screenshots[0].index = last_index + 1;
        }
Example #10
0
        public void HandleMessage(int clientIndex, KLFCommon.ClientMessageID id, byte[] data)
        {
            if (!ValidClient(clientIndex))
                return;
            DebugConsoleWriteLine("Message id: " + id.ToString() + " data: " + (data != null ? data.Length.ToString() : "0"));
            UnicodeEncoding encoder = new UnicodeEncoding();

            switch (id)
            {
                case KLFCommon.ClientMessageID.Handshake:
                    if (data != null)
                    {
                        StringBuilder sb = new StringBuilder();
                        //Read username
                        Int32 usernameLength = KLFCommon.BytesToInt(data, 0);
                        String username = encoder.GetString(data, 4, usernameLength);
                        int offset = 4 + usernameLength;
                        String version = encoder.GetString(data, offset, data.Length - offset);
                        String usernameLower = username.ToLower();
                        bool accepted = true;
                        //Ensure no other players have the same username
                        for (int i = 0; i < Clients.Length; i++)
                        {
                            if (i != clientIndex && ClientIsReady(i) && Clients[i].Username.ToLower() == usernameLower)
                            {
                                //Disconnect the player
                                DisconnectClient(clientIndex, "Your username is already in use.");
                                StampedConsoleWriteLine("Rejected client due to duplicate username: "******"There is currently 1 other user on this server: ");
                            for (int i = 0; i < Clients.Length; i++)
                            {
                                if (i != clientIndex && ClientIsReady(i))
                                {
                                    sb.Append(Clients[i].Username);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            sb.Append("There are currently ");
                            sb.Append(NumClients - 1);
                            sb.Append(" other users on this server.");
                            if (NumClients > 1)
                                sb.Append(" Enter /list to see them.");
                        }
                        Clients[clientIndex].Username = username;
                        Clients[clientIndex].ReceivedHandshake = true;
                        SendServerMessage(clientIndex, sb.ToString());
                        SendServerSettings(clientIndex);
                        StampedConsoleWriteLine(username + " ("+GetClientIP(clientIndex).ToString()+") has joined the server using client version " + version);
                        if (!Clients[clientIndex].MessagesThrottled)
                        {//Build join message
                            sb.Clear();
                            sb.Append("User ");
                            sb.Append(username);
                            sb.Append(" has joined the server.");
                            //Send the join message to all other Clients
                            SendServerMessageToAll(sb.ToString(), clientIndex);
                        }
                        MessageFloodIncrement(clientIndex);
                    }
                    break;

                case KLFCommon.ClientMessageID.PrimaryPluginUpdate:
                case KLFCommon.ClientMessageID.SecondaryPluginUpdate:
                    if (data != null && ClientIsReady(clientIndex))
                    {
            #if SEND_UPDATES_TO_SENDER
                        SendPluginUpdateToAll(data, id == KLFCommon.ClientMessageID.SecondaryPluginUpdate);
            #else
                        SendPluginUpdateToAll(data, id == KLFCommon.ClientMessageID.SecondaryPluginUpdate, clientIndex);
            #endif
                    }
                    break;

                case KLFCommon.ClientMessageID.TextMessage:
                    if (data != null && ClientIsReady(clientIndex))
                        HandleClientTextMessage(clientIndex, encoder.GetString(data, 0, data.Length));
                    break;

                case KLFCommon.ClientMessageID.ScreenWatchPlayer:
                    if(!ClientIsReady(clientIndex)
                    || data == null
                    || data.Length < 9)
                        break;
                    bool sendScreenshot = data[0] != 0;
                    int watchIndex = KLFCommon.BytesToInt(data, 1);
                    int currentIndex = KLFCommon.BytesToInt(data, 5);
                    String watchName = encoder.GetString(data, 9, data.Length - 9);
                    bool watchNameChanged = false;
                    lock (Clients[clientIndex].WatchPlayerNameLock)
                    {
                        if(watchName != Clients[clientIndex].WatchPlayerName
                        || watchIndex != Clients[clientIndex].WatchPlayerIndex)
                        {//Set the watch player name
                            Clients[clientIndex].WatchPlayerIndex = watchIndex;
                            Clients[clientIndex].WatchPlayerName = watchName;
                            watchNameChanged = true;
                        }
                    }

                    if (sendScreenshot && watchNameChanged && watchName.Length > 0)
                    {//Try to find the player the client is watching and send that player's current screenshot
                        int watchedIndex = GetClientIndexByName(watchName);
                        if (ClientIsReady(watchedIndex))
                        {
                            Screenshot screenshot = null;
                            lock (Clients[watchedIndex].ScreenshotLock)
                            {
                                screenshot = Clients[watchedIndex].GetScreenshot(watchIndex);
                                if (screenshot == null && watchIndex == -1)
                                    screenshot = Clients[watchedIndex].LastScreenshot;
                            }
                            if(screenshot != null
                            && screenshot.Index != currentIndex)
                                SendScreenshot(clientIndex, screenshot);
                        }
                    }
                    break;

                case KLFCommon.ClientMessageID.ScreenshotShare:
                    if (data != null && data.Length <= Configuration.ScreenshotSettings.MaxNumBytes && ClientIsReady(clientIndex))
                    {
                        if (!Clients[clientIndex].ScreenshotsThrottled)
                        {
                            StringBuilder sb = new StringBuilder();
                            Screenshot screenshot = new Screenshot();
                            screenshot.SetFromByteArray(data);
                            //Set the screenshot for the player
                            lock (Clients[clientIndex].ScreenshotLock)
                            {
                                Clients[clientIndex].PushScreenshot(screenshot);
                            }
                            sb.Append(Clients[clientIndex].Username);
                            sb.Append(" has shared a screenshot.");
                            SendTextMessageToAll(sb.ToString());
                            StampedConsoleWriteLine(sb.ToString());
                            //Send the screenshot to every client watching the player
                            SendScreenshotToWatchers(clientIndex, screenshot);
                            if (Configuration.SaveScreenshots)
                                saveScreenshot(screenshot, Clients[clientIndex].Username);
                        }
                        bool throttled = Clients[clientIndex].ScreenshotsThrottled;
                        Clients[clientIndex].ScreenshotFloodIncrement();
                        if (!throttled && Clients[clientIndex].ScreenshotsThrottled)
                        {
                            long throttleSeconds = Configuration.ScreenshotFloodThrottleTime / 1000;
                            SendServerMessage(clientIndex, "You have been restricted from sharing screenshots for " + throttleSeconds + " seconds.");
                            StampedConsoleWriteLine(Clients[clientIndex].Username + " has been restricted from sharing screenshots for " + throttleSeconds + " seconds.");
                        }
                        else if (Clients[clientIndex].CurrentThrottle.MessageFloodCounter == Configuration.ScreenshotFloodLimit - 1)
                            SendServerMessage(clientIndex, "Warning: You are sharing too many screenshots.");

                    }

                    break;

                case KLFCommon.ClientMessageID.ConnectionEnd:
                    String message = String.Empty;
                    if (data != null)
                        message = encoder.GetString(data, 0, data.Length); //Decode the message
                    DisconnectClient(clientIndex, message); //Disconnect the client
                    break;

                case KLFCommon.ClientMessageID.ShareCraftFile:
                    if(ClientIsReady(clientIndex)
                    && data != null
                    && data.Length > 5
                    && (data.Length - 5) <= KLFCommon.MaxCraftFileBytes)
                    {
                        if (Clients[clientIndex].MessagesThrottled)
                        {
                            MessageFloodIncrement(clientIndex);
                            break;
                        }
                        MessageFloodIncrement(clientIndex);

                        //Read craft name length
                        byte craftType = data[0];
                        int craftNameLength = KLFCommon.BytesToInt(data, 1);
                        if (craftNameLength < data.Length - 5)
                        {
                            //Read craft name
                            String craftName = encoder.GetString(data, 5, craftNameLength);
                            //Read craft bytes
                            byte[] craftBytes = new byte[data.Length - craftNameLength - 5];
                            Array.Copy(data, 5 + craftNameLength, craftBytes, 0, craftBytes.Length);

                            lock (Clients[clientIndex].SharedCraftLock)
                            {
                                Clients[clientIndex].SharedCraftName = craftName;
                                Clients[clientIndex].SharedCraftFile = craftBytes;
                                Clients[clientIndex].SharedCraftType = craftType;
                            }

                            //Send a message to players informing them that a craft has been shared
                            StringBuilder sb = new StringBuilder();
                            sb.Append(Clients[clientIndex].Username);
                            sb.Append(" shared ");
                            sb.Append(craftName);
                            switch (craftType)
                            {
                                case KLFCommon.CraftTypeVab:
                                    sb.Append(" (VAB)");
                                    break;
                                case KLFCommon.CraftTypeSph:
                                    sb.Append(" (SPH)");
                                    break;
                            }
                            StampedConsoleWriteLine(sb.ToString());
                            sb.Append(" . Enter " + KLFCommon.GetCraftCommand);
                            sb.Append(Clients[clientIndex].Username);
                            sb.Append(" to get it.");
                            SendTextMessageToAll(sb.ToString());
                        }
                    }
                    break;

                case KLFCommon.ClientMessageID.ActivityUpdateInFlight:
                    Clients[clientIndex].UpdateActivity(ServerClient.Activity.InFlight);
                    break;

                case KLFCommon.ClientMessageID.ActivityUpdateInGame:
                    Clients[clientIndex].UpdateActivity(ServerClient.Activity.InGame);
                    break;

                case KLFCommon.ClientMessageID.Ping:
                    Clients[clientIndex].QueueOutgoingMessage(KLFCommon.ServerMessageID.PingReply, null);
                    break;
            }
            DebugConsoleWriteLine("Handled message");
        }
Example #11
0
 public void ShouldCreateAFileNameThatEndsWithTheCorrectImageFormatExtension()
 {
     var s = new Screenshot(".", ImageFormat.Png);
     Assert.IsTrue(s.FileName.EndsWith(".png"));
 }
Example #12
0
        public void GenerateReports(int iStep, string iTestNum, bool iResult, string iMessage = "-")
        {
            iMessage = iMessage.Replace("<", "&lt;").Replace(">", "&lt");
            iMessage = iMessage.Replace("\n", "/br");
            string       iTime = String.Format("{0:HH:mm:ss}", DateTime.Now);
            FileStream   fs    = new FileStream(iPathReportFile, FileMode.Append, FileAccess.Write);
            StreamWriter sw    = new StreamWriter(fs);

            if (iStep == 0)
            {
                iTestCountGood = 0;
                iTestCountFail = 0;
                sw.WriteLine(@"<!DOCTYPE html>" + "\n" +
                             @"<html lang='ru-RU'>" + "\n" +
                             @"<head>" + "\n" +
                             @"<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />" + "\n" +
                             @"<title>Отчёт о тестировании</title>" + "\n" +
                             @"</head>" + "\n" +
                             @"<body>" + "\n" +
                             @"<div style='font-size:22px;' align='center'><strong>Тест начат: " + String.Format("{0:dd.MM.yyyy HH:mm:ss}", DateTime.Now) + @"</strong></div></br>" + "\n" +
                             @"<table border='1' align='center' cellpadding='5' cellspacing='0' width='100%'>" + "\n" +
                             @"<tr style='text-align:center;'>" + "\n" +
                             @"<td width='100px'><strong>Тест</strong></td>" + "\n" +
                             @"<td width='70px'><strong>Результат</strong></td>" + "\n" +
                             @"<td width='70px'><strong>Время</strong></td>" + "\n" +
                             @"<td width='70px'><strong>Снимок</strong></td>" + "\n" +
                             @"<td><strong>Сообщение</strong></td>" + "\n" +
                             @"</tr>");
            }
            if (iResult == true & iStep == 1)
            {
                iTestCountGood += 1;
                sw.WriteLine(@"<tr style='color: green;'>" + "\n" +
                             @"<td>" + iTestNum + @"</td>" + "\n" +
                             @"<td>Успех</td>" + "\n" +
                             @"<td>" + iTime + @"</td>" + "\n" +
                             @"<td>-</td>" + "\n" +
                             @"<td>" + iMessage + @"</td>" + "\n" +
                             @"</tr>" + "\n");
            }
            if (iResult == false & iStep == 1)
            {
                iTestCountFail += 1;
                ITakesScreenshot screenshootdrivers = Test.Browser as ITakesScreenshot;
                Screenshot       screenshot         = screenshootdrivers.GetScreenshot();
                //string iNameScreen = iTestNum + "_" + String.Format("{0:yyyy:-MM-dd_HH--mm-ss}", DateTime.Now);
                //screenshot.SaveAsFile("1213.png", OpenQA.Selenium.ScreenshotImageFormat.Png);
                //screenshot.SaveAsFile("d:\\page.png", OpenQA.Selenium.ScreenshotImageFormat.Png);
                screenshot.SaveAsFile(iFolderScreen + @"\" + iTestNum + ".png", OpenQA.Selenium.ScreenshotImageFormat.Png);
                sw.WriteLine(@"<tr style='color: red;'>" + "\n" +
                             @"<td>" + iTestNum + @"</td>" + "\n" +
                             @"<td>Провал</td>" + "\n" +
                             @"<td>" + iTime + @"</td>" + "\n" +
                             @"<td><center><a target='_blank' href='screen/" + iTestNum + ".png" + @"'>скриншот</a><br/><br/><a href='" + Browser.Url + @"' target='_blank'>URL</a></center></td>" + "\n" +
                             @"<td>" + iMessage + @"</td>" + "\n" +
                             @"</tr>" + "\n");
            }
            if (iStep == 9)
            {
                Decimal iProcent = 0;
                if (iTestCountGood > 0 || iTestCountFail > 0)
                {
                    iProcent = ((100 * iTestCountGood) / (iTestCountGood + iTestCountFail));
                }
                sw.WriteLine(@"<tr style='text-align:center;'>" + "\n" +
                             @"<td colspan='5'>&nbsp;</center></td>" + "\n" +
                             @"</tr>" + "\n" +
                             @"<tr style='text-align:center;'>" + "\n" +
                             @"<td colspan='5'>Всего тестов запущено: " + (iTestCountGood + iTestCountFail) + " || <span style='color: green;'>Успешно: " + iTestCountGood +
                             "</span> || <span style='color: red;'>Провалено: " + iTestCountFail + "</span> || Процент пройденных: " + iProcent + "% || Тест завершён: " + String.Format("{0:dd.MM.yyyy HH:mm:ss}", DateTime.Now) + "</td>" + "\n" +
                             @"</tr>" + "\n" +
                             @"</table>" + "\n" +
                             @"</body>" + "\n" +
                             @"</html>");
            }
            sw.Close();
        }
Example #13
0
        /// <summary>
        /// Scrolls the current window and takes screenshot
        /// </summary>
        /// <param name="inputDriverName"></param>
        /// <param name="inputDriver"></param>
        /// <param name="path"></param>
        /// <param name="fileName"></param>
        public static void SaveScreenShot(string inputDriverName, IWebDriver inputDriver, string path, string fileName)
        {
            if (screenShotFlag == "Y")
            {
                IJavaScriptExecutor js1 = (IJavaScriptExecutor)inputDriver;
                js1.ExecuteScript("window.scrollTo(0,0)");


                IJavaScriptExecutor js2 = (IJavaScriptExecutor)inputDriver;

                Int64 VPHeight = (Int64)js2.ExecuteScript("return window.innerHeight");

                Int64 PageAHeight = (Int64)js2.ExecuteScript("return document.documentElement.clientHeight");

                Int64 PageBHeight = (Int64)js2.ExecuteScript("return document.body.clientHeight");
                Int64 PageHeight;

                if (PageAHeight < PageBHeight)
                {
                    PageHeight = PageBHeight;
                }
                else
                {
                    PageHeight = PageAHeight;
                }

                //Top Screenshot
                String strDate = DateTime.Now.ToString("ddMMMyyyy hhmmss.fff").ToUpper();
                if (inputDriverName.Contains("Browser") == true)
                {
                    Thread.Sleep(6000);
                }
                Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
                string     screenPath = string.Format("{0}/" + strDate + "_Screenshot_1_" + fileName, path);
                screenshot.SaveAsFile(screenPath, ScreenshotImageFormat.Jpeg);
                if (inputDriverName.Contains("Browser") == true)
                {
                    Thread.Sleep(6000);
                }
                Thread.Sleep(3000);
                decimal Iteration = PageHeight / (VPHeight - 50);

                int Iterator = (int)Math.Ceiling(Iteration);

                int i;
                for (i = 2; i <= Iterator + 1; i = i + 1)
                {
                    strDate = DateTime.Now.ToString("ddMMMyyyy hhmmss.fff").ToUpper();
                    if (inputDriverName.Contains("Browser") == true)
                    {
                        Thread.Sleep(6000);
                    }
                    IJavaScriptExecutor js3 = (IJavaScriptExecutor)inputDriver;
                    js3.ExecuteScript("window.scrollBy(0,arguments[0])", VPHeight - 50);
                    Thread.Sleep(2000);
                    Screenshot screenshotRep = ((ITakesScreenshot)driver).GetScreenshot();
                    string     screenPathRep = string.Format("{0}/" + strDate + "_Screenshot_" + i + "_" + fileName, path);
                    screenshotRep.SaveAsFile(screenPathRep, ScreenshotImageFormat.Jpeg);
                    Thread.Sleep(3000);
                }
            }
        }
        public void ScreenshotTestCase()
        {
            Screenshot screenshot = driver.GetScreenshot();

            Assert.IsNotNull(screenshot);
        }
        public Bitmap GetActiveScreenImage()
        {
            Screenshot ss = ((ITakesScreenshot)Driver).GetScreenshot();

            return(Base64StringToBitmap(ss.AsBase64EncodedString));
        }
Example #16
0
        public void HandleMouseOpsTest()
        {
            driver = new ChromeDriver(@"C:\Selenium_Csharp_LatestBackup\UnitTestProject14June2018\UnitTestProject14June2018\drivers");


            //***************************************************************************
            //6.1 Simulating Mouse & Keyboard Operations
            //***************************************************************************
            driver.Navigate().GoToUrl("http://demo.opencart.com/");
            driver.Manage().Window.Maximize();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
            //Click on Components Menu
            driver.FindElement(By.XPath("//*[@id='menu']/div[2]/ul/li[3]/a")).Click();
            Actions action = new Actions(driver);
            //Finding the Printer Element in the Components Menu
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));

            wait.Until(ExpectedConditions.ElementExists(By.XPath("//*[@id='menu']/div[2]/ul/li[3]/div/div/ul/li[3]/a")));
            IWebElement printerElement = driver.FindElement(By.XPath("//*[@id='menu']/div[2]/ul/li[3]/div/div/ul/li[3]/a"));

            //Moving the mouse to the Printer Element
            action.MoveToElement(printerElement).Build().Perform();
            //Performing click operation on the Printer Element
            printerElement.Click();

            //***************************************************************************
            //6.2 Capture Screenshots
            //***************************************************************************
            String     fileName = "screenshot.jpeg";
            Screenshot ss       = ((ITakesScreenshot)driver).GetScreenshot();

            ss.SaveAsFile(@"C:\Selenium_Csharp_LatestBackup\UnitTestProject14June2018\UnitTestProject14June2018\" + fileName, System.Drawing.Imaging.ImageFormat.Jpeg);

            //***************************************************************************
            //6.3 Drag and Drop Operations
            //***************************************************************************
            driver.Navigate().GoToUrl("http://jqueryui.com/droppable/");
            //Wait for the frame to be available and switch to it
            WebDriverWait wait2 = new WebDriverWait(driver, TimeSpan.FromSeconds(30));

            wait2.Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(By.CssSelector(".demo-frame")));
            IWebElement Sourcelocator      = driver.FindElement(By.CssSelector(".ui-draggable"));
            IWebElement Destinationlocator = driver.FindElement(By.CssSelector(".ui-droppable"));

            dragAndDrop(Sourcelocator, Destinationlocator);
            String actualText = driver.FindElement(By.CssSelector("#droppable>p")).Text;

            //Assert.assertEquals(actualText, "Dropped!");

            //***************************************************************************
            //6.4 List Sub menu Items
            //***************************************************************************
            driver.Navigate().GoToUrl("https://demo.opencart.com/");
            driver.FindElement(By.XPath("//*[@id='menu']/div[2]/ul/li[3]/a")).Click();
            //Finding the Printer Element in the Components Menu
            WebDriverWait wait3 = new WebDriverWait(driver, TimeSpan.FromSeconds(30));

            wait3.Until(ExpectedConditions.ElementExists(By.XPath("//*[@id='menu']/div[2]/ul/li[3]/div/div/ul/li[1]/a")));
            IList <IWebElement> subMenuList = driver.FindElements(By.XPath("//*[@id='menu']/div[2]/ul/li[3]/div/div/ul/li"));

            for (int i = 1; i <= subMenuList.Count; i++)
            {
                Console.WriteLine(driver.FindElement(By.XPath("//*[@id='menu']/div[2]/ul/li[3]/div/div/ul/li[" + i + "]/a")).Text);
            }
            //***************************************************************************
            //6.5 Calendar Control
            //**************************************************************************
            //driver.Navigate().GoToUrl("http://spicejet.com/");
            //driver.Manage().Window.Maximize();
            //driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
            //for explicit Wait
            //driver.FindElement(By.XPath("//*[@id='flightSearchContainer']/div[3]/button")).Click();
            //WebDriverWait  wait1 = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
            //wait1.Until(ExpectedConditions.ElementExists(By.XPath("//*[@id='ui-datepicker-div']/table/tbody/tr[5]/td[6]/a")));
            //IWebElement caldateElementJun29 = driver.FindElement(By.XPath("//*[@id='ui-datepicker-div']/table/tbody/tr[5]/td[6]/a"));
            //caldateElementJun29.Click();
        }
Example #17
0
        public void CheckSelenium1()
        {
            IWebDriver driver = new ChromeDriver();

            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
            driver.Navigate().GoToUrl("https://www.google.com.ua/");
            Thread.Sleep(1000);
            //
            driver.FindElement(By.Id("lst-ib")).Clear();
            driver.FindElement(By.Id("lst-ib")).SendKeys("Selenium" + Keys.Enter);
            Thread.Sleep(1000);
            //
            //driver.FindElement(By.Name("btnK")).Click();
            //Thread.Sleep(1000);
            //
            // MoveToElement
            Actions action = new Actions(driver);
            //action.MoveToElement(driver.FindElement(By.XPath("//a[text()='2']"))).Perform();
            //
            // Use JavaScript Injection
            IJavaScriptExecutor js = (IJavaScriptExecutor)driver;

            js.ExecuteScript("arguments[0].scrollIntoView(true);", driver.FindElement(By.XPath("//a[text()='2']")));
            Thread.Sleep(2000);
            //
            // TakesScreenshot
            ITakesScreenshot takesScreenshot = driver as ITakesScreenshot;
            Screenshot       screenshot      = takesScreenshot.GetScreenshot();

            screenshot.SaveAsFile("d:/ScreenshotGoogle1.png", ScreenshotImageFormat.Png);
            //
            driver.FindElement(By.LinkText("Selenium - Web Browser Automation")).Click();
            Thread.Sleep(1000);
            //
            driver.FindElement(By.LinkText("Download")).Click();
            //
            IWebElement actual = driver.FindElement(By.CssSelector("a[name='selenium_ide'] > p"));

            Assert.AreEqual("Selenium IDE is a Chrome and Firefox plugin which records and plays back user interactions with the browser. Use this to either create simple scripts or assist in exploratory testing.",
                            actual.Text);
            Thread.Sleep(1000);
            //
            IWebElement legacy   = driver.FindElement(By.CssSelector("a[name = 'side_plugins'] > h3"));
            IWebElement legacyJs = (IWebElement)js.ExecuteScript("return document.getElementsByName('side_plugins')[0];", new object[1] {
                ""
            });

            //
            //js.ExecuteScript("arguments[0].scrollIntoView(true);", legacy);
            action.MoveToElement(legacy).Perform();
            Thread.Sleep(2000);
            //
            screenshot = takesScreenshot.GetScreenshot();
            screenshot.SaveAsFile("d:/ScreenshotSelen1.png", ScreenshotImageFormat.Png);
            //
            Assert.AreEqual("Legacy Selenium IDE Plugins", legacy.Text);
            Assert.AreEqual("Legacy Selenium IDE Plugins", legacyJs.Text);
            Thread.Sleep(2000);
            //
            driver.Quit();
        }
Example #18
0
 private void SalvarScreenShot(Screenshot screenshot, string fileName)
 {
     screenshot.SaveAsFile($"{Configuration.FolderPicture}{fileName}", ScreenshotImageFormat.Png);
 }
Example #19
0
        private void sendScreenshotToWatchers(int client_index, Screenshot screenshot)
        {
            //Create a list of valid watchers
            List<int> watcher_indices = new List<int>();

            for (int i = 0; i < clients.Length; i++)
            {
            if (clientIsReady(i) && clients[i].activityLevel != ServerClient.ActivityLevel.INACTIVE)
            {
                bool match = false;

                lock (clients[i].watchPlayerNameLock)
                {
                    match = clients[i].watchPlayerName == clients[client_index].username;
                }

                if (match)
                    watcher_indices.Add(i);
            }
            }

            if (watcher_indices.Count > 0)
            {
            //Build the message and send it to all watchers
            byte[] message_bytes = buildMessageArray(KLFCommon.ServerMessageID.SCREENSHOT_SHARE, screenshot.toByteArray());
            foreach (int i in watcher_indices)
            {
                clients[i].queueOutgoingMessage(message_bytes);
            }
            }
        }
Example #20
0
        public void Screenshot(string Path)
        {
            Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();

            ss.SaveAsFile(Path, System.Drawing.Imaging.ImageFormat.Png);
        }
Example #21
0
 private void SendScreenshot(int clientIndex, Screenshot screenshot)
 {
     Clients[clientIndex].QueueOutgoingMessage(KLFCommon.ServerMessageID.ScreenshotShare, screenshot.ToByteArray());
 }
Example #22
0
        static void Main(string[] args)
        {
            string randomEmail             = new Internet().Email();
            string randomFirstName         = new Name().FirstName();
            string randomLastName          = new Name().LastName();
            string randomPassword          = new Internet().Password();
            string randomCompany           = new Company().CompanyName();
            string randomAddress1          = new Address().StreetAddress();
            string randomAddress2          = new Address().SecondaryAddress();
            string randomCity              = new Address().City();
            string randomOther             = new Lorem().Text();
            string randomHomePhoneNumber   = new PhoneNumbers().PhoneNumberFormat(1);
            string randomMobilePhoneNumber = new PhoneNumbers().PhoneNumberFormat(1);

            string folder = "";

            IWebDriver _driver;

            if (ConfigurationManager.AppSettings["key"] == "FirefoxDriver")
            {
                _driver = new FirefoxDriver();
                folder  = "Firefox";
            }
            else
            {
                _driver = new ChromeDriver(); folder = "Chrome";
            }


            _driver.Manage().Window.Maximize();
            _driver.Url = "http://automationpractice.com/index.php";

            void TakeScreenShot(string path)

            {
                Screenshot sreenShot = ((ITakesScreenshot)_driver).GetScreenshot();

                sreenShot.SaveAsFile(path, ScreenshotImageFormat.Png);
            }

            void CreateAccount()
            {
                TakeScreenShot($@"D:\{folder}\CreateAccountStep_1.png");

                var btnLogin = _driver.FindElement(By.ClassName("login"));

                btnLogin.Click();
                Task.Delay(3500).Wait();

                var txtEmail = _driver.FindElement(By.ClassName("account_input"));

                txtEmail.SendKeys(randomEmail);
                TakeScreenShot($@"D:\{folder}\CreateAccountStep_2.png");
                Task.Delay(3500).Wait();

                var btnCreateAccount = _driver.FindElement(By.Id("SubmitCreate"));

                btnCreateAccount.Click();
                Task.Delay(3500).Wait();

                var chkGender = _driver.FindElement(By.Id("id_gender1"));

                chkGender.Click();

                var txtFirstName = _driver.FindElement(By.Id("customer_firstname"));

                txtFirstName.SendKeys(randomFirstName);

                var txtLastName = _driver.FindElement(By.Id("customer_lastname"));

                txtLastName.SendKeys(randomLastName);

                var txtPassword = _driver.FindElement(By.Id("passwd"));

                txtPassword.SendKeys(randomPassword);

                var comboDay      = _driver.FindElement(By.Id("days"));
                var selectElement = new SelectElement(comboDay);

                selectElement.SelectByValue("22");

                var comboMonth     = _driver.FindElement(By.Id("months"));
                var selectElement2 = new SelectElement(comboMonth);

                selectElement2.SelectByValue("1");

                var comboYear      = _driver.FindElement(By.Id("years"));
                var selectElement3 = new SelectElement(comboYear);

                selectElement3.SelectByValue("1999");


                var txtCompanyName = _driver.FindElement(By.Id("company"));

                txtCompanyName.SendKeys(randomCompany);

                var txtAddress = _driver.FindElement(By.Id("address1"));

                txtAddress.SendKeys(randomAddress1);

                var txtAddress2 = _driver.FindElement(By.Id("address2"));

                txtAddress2.SendKeys(randomAddress2);

                var txtCity = _driver.FindElement(By.Id("city"));

                txtCity.SendKeys(randomCity);

                var comboState     = _driver.FindElement(By.Id("id_state"));
                var selectElement4 = new SelectElement(comboState);

                selectElement4.SelectByValue("1");

                var txtPostcode = _driver.FindElement(By.Id("postcode"));

                txtPostcode.SendKeys("36523");

                var comboContry    = _driver.FindElement(By.Id("id_country"));
                var selectElement5 = new SelectElement(comboContry);

                selectElement5.SelectByValue("21");

                var txtOther = _driver.FindElement(By.Id("other"));

                txtOther.SendKeys(randomOther);

                var txtHomePhone = _driver.FindElement(By.Id("phone"));

                txtHomePhone.SendKeys(randomHomePhoneNumber);

                var txtMobilePhone = _driver.FindElement(By.Id("phone_mobile"));

                txtMobilePhone.SendKeys(randomMobilePhoneNumber);

                //SCREENSHOT STEP 1
                TakeScreenShot($@"D:\{folder}\CreateAccountStep_3.png");
                Task.Delay(3500).Wait();

                var btnRegister = _driver.FindElement(By.Id("submitAccount"));

                btnRegister.Click();
                Task.Delay(3500).Wait();
            }

            void Login()
            {
                var btnLogout = _driver.FindElement(By.ClassName("logout"));

                btnLogout.Click();
                Task.Delay(3500).Wait();

                var txtEmailLogin = _driver.FindElement(By.Id("email"));

                txtEmailLogin.SendKeys(randomEmail);

                var txtPasswordLogin = _driver.FindElement(By.Id("passwd"));

                txtPasswordLogin.SendKeys(randomPassword);

                var btnRegisterLogin = _driver.FindElement(By.Id("SubmitLogin"));

                //SCREENSHOT STEP 2
                TakeScreenShot($@"D:\{folder}\LoginStep.png");
                btnRegisterLogin.Click();
                Task.Delay(3500).Wait();
            }

            void Buy()
            {
                var btnWomen = _driver.FindElement(By.ClassName("sf-with-ul"));

                TakeScreenShot($@"D:\{folder}\OrderStep_1.png");
                btnWomen.Click();
                Task.Delay(3500).Wait();

                WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));
                //var element = wait.Until(ExpectedConditions.ElementIsVisible(By.ClassName("first-item-of-tablet-line")));
                var element = wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("/html/body/div/div[2]/div/div[3]/div[2]/ul/li[1]")));

                IJavaScriptExecutor js = (IJavaScriptExecutor)_driver;

                js.ExecuteScript("arguments[0].scrollIntoView()", element);

                Task.Delay(3500).Wait();
                Actions action = new Actions(_driver);

                action.MoveToElement(element).Perform();
                TakeScreenShot($@"D:\{folder}\OrderStep_2.png");
                Task.Delay(3500).Wait();

                var btnAddCart1 = _driver.FindElement(By.XPath("//*[@id='center_column']/ul/li[1]/div/div[2]/div[2]/a[1]"));

                TakeScreenShot($@"D:\{folder}\OrderStep_3.png");
                btnAddCart1.Click();
                Task.Delay(3500).Wait();

                var btnProccedToCheckout1 = _driver.FindElement(By.XPath("//*[@id='layer_cart']/div[1]/div[2]/div[4]/a"));

                TakeScreenShot($@"D:\{folder}\OrderStep_4.png");
                btnProccedToCheckout1.Click();
                Task.Delay(3500).Wait();

                var btnProccedToCheckout2 = _driver.FindElement(By.XPath("//*[@id='center_column']/p[2]/a[1]"));

                TakeScreenShot($@"D:\{folder}\OrderStep_5.png");
                btnProccedToCheckout2.Click();
                Task.Delay(3500).Wait();

                var btnProccedToCheckout3 = _driver.FindElement(By.XPath("//*[@id='center_column']/form/p/button"));

                TakeScreenShot($@"D:\{folder}\OrderStep_6.png");
                btnProccedToCheckout3.Click();
                Task.Delay(3500).Wait();

                var chkAgree = _driver.FindElement(By.Id("cgv"));

                TakeScreenShot($@"D:\{folder}\OrderStep_7.png");
                chkAgree.Click();

                var btnProccedToCheckout4 = _driver.FindElement(By.XPath("//*[@id='form']/p/button"));

                TakeScreenShot($@"D:\{folder}\OrderStep_8.png");
                btnProccedToCheckout4.Click();
                Task.Delay(3500).Wait();

                var btnPayBankWire = _driver.FindElement(By.ClassName("bankwire"));

                TakeScreenShot($@"D:\{folder}\OrderStep_9.png");
                btnPayBankWire.Click();
                Task.Delay(3500).Wait();

                var btnConfirm = _driver.FindElement(By.XPath("//*[@id='cart_navigation']/button"));

                TakeScreenShot($@"D:\{folder}\OrderStep_10.png");
                btnConfirm.Click();
                Task.Delay(3500).Wait();

                //SCREENSHOT STEP 3
                TakeScreenShot($@"D:\{folder}\OrderStep_final.png");
            }

            CreateAccount();
            Login();
            Buy();
            _driver.Quit();
        }
Example #23
0
        private unsafe void ProcessCapture()
        {
            try
            {
                Screenshot         ssht = _capture.Capture();
                Image <Gray, byte> process;

                fixed(byte *p = ssht.Data)
                {
                    IntPtr ptr = (IntPtr)p;

                    Screen = new Image <Bgra, byte>(ssht.Width, ssht.Height, ssht.Stride, ptr)
                    {
                        ROI = BOX_SIZE
                    };
                    process = Screen.Convert <Gray, byte>();
                }
                ssht.Dispose();

                _force = new Vec2();

                // Read player position from memory
                _playerPos = GetPlayerPosition();

                Rectangle powerDetectionROI = new Rectangle(
                    (int)Math.Max(_playerPos.X - 100, 0),
                    (int)Math.Max(_playerPos.Y - 75, 0),
                    (int)Math.Min(BOX_SIZE.Width - (_playerPos.X - 100), 200),
                    (int)Math.Min(BOX_SIZE.Height - (_playerPos.Y - 75), 100));
                // Look for power
                process.ROI = powerDetectionROI;

                // Processing bounding box
                Rectangle bulletDetectionROI = new Rectangle(
                    (int)Math.Max(_playerPos.X - INITIAL_DETECTION_RADIUS, 0),
                    (int)Math.Max(_playerPos.Y - INITIAL_DETECTION_RADIUS, 0),
                    (int)Math.Min(BOX_SIZE.Width - ((int)_playerPos.X - INITIAL_DETECTION_RADIUS), INITIAL_DETECTION_RADIUS * 2),
                    (int)Math.Min(BOX_SIZE.Height - ((int)_playerPos.Y - INITIAL_DETECTION_RADIUS), INITIAL_DETECTION_RADIUS * 2));
                process.ROI = bulletDetectionROI;


                if (TEST_MODE)
                {
                    return;
                }
                Vec2 _playerVec = new Vec2(_playerPos.X, _playerPos.Y);

                var binthresh = process.SmoothBlur(3, 3).ThresholdBinary(new Gray(240), new Gray(255)); //220
                // Detect blobs (bullets) on screen
                CvBlobs resultingImgBlobs = new CvBlobs();
                uint    noBlobs           = _bDetect.Detect(binthresh, resultingImgBlobs);
                int     blobCount         = 0;
                resultingImgBlobs.FilterByArea(10, 500);
                foreach (CvBlob targetBlob in resultingImgBlobs.Values)
                {
                    if (DO_DRAWING)
                    {
                        Screen.ROI = new Rectangle(process.ROI.X + BOX_SIZE.X, process.ROI.Y + BOX_SIZE.Y,
                                                   process.ROI.Width,
                                                   process.ROI.Height);
                        Screen.FillConvexPoly(targetBlob.GetContour(), new Bgra(0, 0, 255, 255));
                    }
                    // Find closest point on blob contour to player
                    Point  minPoint = targetBlob.GetContour()[0];
                    double minDist  = double.MaxValue;
                    foreach (var point in targetBlob.GetContour())
                    {
                        Point  adj  = new Point(point.X + process.ROI.X, point.Y + process.ROI.Y);
                        double dist =
                            (adj.X - _playerPos.X) * (adj.X - _playerPos.X) +
                            (adj.Y - _playerPos.Y) * (adj.Y - _playerPos.Y);

                        if (dist < minDist)
                        {
                            minPoint = adj;
                            minDist  = dist;
                        }
                    }
                    // Ensure the bullet is in the correct range
                    if (minDist < _detectionRadius * _detectionRadius)
                    {
                        // Calculate forces
                        Vec2 acc = Vec2.CalculateForce(new Vec2(minPoint.X, minPoint.Y),
                                                       _playerVec, -5000);
                        _force += acc;
                        if (DO_DRAWING)
                        {
                            Screen.ROI = BOX_SIZE;
                            Screen.Draw(new LineSegment2DF(_playerPos, minPoint), new Bgra(0, 255, 128, 255), 1);
                        }
                        blobCount++;
                    }
                }
                Screen.ROI  = BOX_SIZE;
                process.ROI = Rectangle.Empty;

                // Calculate new detection orb radius
                //float nRad = Math.Max(20.0f, INITIAL_DETECTION_RADIUS/(1 + blobCount*0.3f));
                if (blobCount >= 1)
                {
                    _detectionRadius = (_detectionRadius * 29 + 5.0f) / 30.0f;
                }
                else
                {
                    _detectionRadius = (_detectionRadius * 59 + INITIAL_DETECTION_RADIUS) / 60.0f;
                }

                // Account for border force, to prevent cornering
                //if (BOX_SIZE.Width - _playerPos.X < 120)
                _force += new Vec2(Vec2.CalculateForce(BOX_SIZE.Width - _playerPos.X, -4000), 0);
                //if (_playerPos.X < 120)
                _force += new Vec2(Vec2.CalculateForce(_playerPos.X, 4000), 0);
                if (BOX_SIZE.Height - _playerPos.Y < 50)
                {
                    _force += new Vec2(0, Vec2.CalculateForce(BOX_SIZE.Height - _playerPos.Y, -2000));
                }
                if (_playerPos.Y < 200)
                {
                    _force += new Vec2(0, Vec2.CalculateForce(_playerPos.Y, 2000));
                }
                // Corners are the devil
                _force += Vec2.CalculateForce(new Vec2(BOX_SIZE.Width, BOX_SIZE.Height),
                                              _playerVec, -2000);
                _force += Vec2.CalculateForce(new Vec2(0, BOX_SIZE.Height),
                                              _playerVec, -2000);
                _force += Vec2.CalculateForce(new Vec2(0, 0),
                                              _playerVec, -2000);
                _force += Vec2.CalculateForce(new Vec2(BOX_SIZE.Width, 0),
                                              _playerVec, -2000);

                // Assist force
                if (ShouldAssist)
                {
                    Vec2   sub  = new Vec2(AssistPoint.X, AssistPoint.Y) - _playerVec;
                    double dist = sub.Length();
                    _force += new Vec2(sub.X / dist * 2, sub.Y / dist * 2);
                }
                //imageToShow.Draw("BLOB_AREA: " + percBlob, new Point(10, 20), FontFace.HersheyPlain, 1, new Bgra(255, 255, 255, 255), 1);

                if (DO_DRAWING)
                {
                    Screen.Draw(
                        new Rectangle((int)(_playerPos.X - 3), (int)(_playerPos.Y - 3), 6, 6),
                        new Bgra(0, 255, 0, 255),
                        2);

                    Screen.Draw(new CircleF(_playerPos, _detectionRadius), new Bgra(0, 255, 255, 255), 1);
                    if (ShouldAssist)
                    {
                        Screen.Draw(
                            new LineSegment2DF(_playerPos, AssistPoint),
                            new Bgra(128, 0, 255, 255), 2);
                        Screen.Draw("ASSIST", new Point(10, 40), FontFace.HersheyPlain, 1, new Bgra(0, 255, 0, 255), 1);
                    }
                    // Draw force vector
                    Screen.Draw(
                        new LineSegment2DF(_playerPos,
                                           new PointF((float)(_playerPos.X + _force.X), (float)(_playerPos.Y + _force.Y))),
                        new Bgra(0, 128, 255, 255), 5);
                    Screen.Draw(powerDetectionROI, new Bgra(255, 255, 0, 255), 1);
                    Screen.Draw(bulletDetectionROI, new Bgra(0, 0, 255, 255), 1);
                    if (DoMovement)
                    {
                        Screen.Draw("DO_MOVEMENT", new Point(10, 20), FontFace.HersheyPlain, 1, new Bgra(0, 255, 0, 255),
                                    1);
                    }
                    _form.imageBox.Image = Screen;
                }
                process.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        /// <summary>
        /// Process the capture based on the requested format.
        /// </summary>
        /// <param name="width">image width</param>
        /// <param name="height">image height</param>
        /// <param name="pitch">data pitch (bytes per row)</param>
        /// <param name="format">target format</param>
        /// <param name="pBits">IntPtr to the image data</param>
        /// <param name="request">The original requets</param>
        protected void ProcessCapture(int width, int height, int pitch, PixelFormat format, IntPtr pBits, ScreenshotRequest request)
        {
            if (request == null)
            {
                return;
            }

            if (format == PixelFormat.Undefined)
            {
                DebugMessage("Unsupported render target format");
                return;
            }

            // Copy the image data from the buffer
            int size = height * pitch;
            var data = new byte[size];

            Marshal.Copy(pBits, data, 0, size);

            // Prepare the response
            Screenshot response = null;

            if (request.Format == Capture.Interface.ImageFormat.PixelData)
            {
                // Return the raw data
                response = new Screenshot(request.RequestId, data)
                {
                    Format      = request.Format,
                    PixelFormat = format,
                    Height      = height,
                    Width       = width,
                    Stride      = pitch
                };
            }
            else
            {
                // Return an image
                using (var bm = data.ToBitmap(width, height, pitch, format))
                {
                    System.Drawing.Imaging.ImageFormat imgFormat = System.Drawing.Imaging.ImageFormat.Bmp;
                    switch (request.Format)
                    {
                    case Capture.Interface.ImageFormat.Jpeg:
                        imgFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
                        break;

                    case Capture.Interface.ImageFormat.Png:
                        imgFormat = System.Drawing.Imaging.ImageFormat.Png;
                        break;
                    }

                    response = new Screenshot(request.RequestId, bm.ToByteArray(imgFormat))
                    {
                        Format = request.Format,
                        Height = bm.Height,
                        Width  = bm.Width
                    };
                }
            }

            // Send the response
            SendResponse(response);
        }
Example #25
0
 public void ShouldUseDefaultDirectoryIfInvalidDirectoryIsGiven()
 {
     var s = new Screenshot("asdfasdfasdfasdfasdfasdfasdfasdfadsf", null);
     Assert.AreEqual(".", actual: s.SaveDirectory);
 }
 public static CoordsPreparationStrategy intersectingWith(Screenshot screenshot)
 {
     return(new _CoordsPreparationStrategy_28(screenshot));
 }
Example #27
0
        private void shareScreenshot()
        {
            //Determine the scaled-down dimensions of the screenshot
            int w = 0;
            int h = 0;

            KLFScreenshotDisplay.screenshotSettings.getBoundedDimensions(Screen.width, Screen.height, ref w, ref h);

            //Read the screen pixels into a texture
            Texture2D full_screen_tex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
            full_screen_tex.filterMode = FilterMode.Bilinear;
            full_screen_tex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, false);
            full_screen_tex.Apply();

            RenderTexture render_tex = new RenderTexture(w, h, 24);
            render_tex.useMipMap = false;

            if (KLFGlobalSettings.instance.smoothScreens && (Screen.width > w * 2 || Screen.height > h * 2))
            {
                //Blit the full texture to a double-sized texture to improve final quality
                RenderTexture resize_tex = new RenderTexture(w * 2, h * 2, 24);
                Graphics.Blit(full_screen_tex, resize_tex);

                //Blit the double-sized texture to normal-sized texture
                Graphics.Blit(resize_tex, render_tex);
            }
            else
                Graphics.Blit(full_screen_tex, render_tex); //Blit the screen texture to a render texture

            full_screen_tex = null;

            RenderTexture.active = render_tex;

            //Read the pixels from the render texture into a Texture2D
            Texture2D resized_tex = new Texture2D(w, h, TextureFormat.RGB24, false);
            resized_tex.ReadPixels(new Rect(0, 0, w, h), 0, 0);
            resized_tex.Apply();

            RenderTexture.active = null;

            byte[] data = resized_tex.EncodeToPNG();

            Screenshot screenshot = new Screenshot();
            screenshot.player = playerName;
            if (FlightGlobals.ready && FlightGlobals.ActiveVessel != null)
                screenshot.description = FlightGlobals.ActiveVessel.vesselName;
            screenshot.image = data;

            Debug.Log("Sharing screenshot");
            enqueuePluginInteropMessage(KLFCommon.PluginInteropMessageID.SCREENSHOT_SHARE, screenshot.toByteArray());
        }
 public _CoordsPreparationStrategy_28(Screenshot screenshot)
 {
     this.screenshot = screenshot;
 }
Example #29
0
 /// <summary>
 /// Save screenshot in screenshots directory with specified file name
 /// </summary>
 /// <param name="reference"></param>
 /// <param name="filename"></param>
 private void SaveReferenceScreenshot(Screenshot reference, string filename)
 {
     reference.SaveAsFile($"{ReferencesDirectory}/{filename}.jpg", ScreenshotImageFormat.Jpeg);
 }
 /// <exception cref="System.IO.IOException" />
 public static byte[] toByteArray(Screenshot screenshot)
 {
     return(toByteArray(screenshot.getImage()));
 }
Example #31
0
        /// <summary>
        /// Load the Screenshots Embedded Screenshot data
        /// </summary>
        public void LoadScreenshot()
        {
            _shotScreenshot = new Screenshot();

            _shotStream.SeekTo(0x1664);
            _shotScreenshot.SizeOfEmbeddedScreenshot = _shotStream.ReadInt32() - 0x10;

            _shotStream.SeekTo(0x1670);
            byte[] screenshot = new byte[_shotScreenshot.SizeOfEmbeddedScreenshot];
            _shotStream.ReadBlock(screenshot, 0, _shotScreenshot.SizeOfEmbeddedScreenshot);

            _shotScreenshot.EmbeddedScreenshot = new List<byte>();
            foreach (byte screenshotByte in screenshot)
                _shotScreenshot.EmbeddedScreenshot.Add(screenshotByte);
        }
Example #32
0
        private ScreenshotResource CaptureDirectX(IntPtr wnd)
        {
            if (!AttachHookToProcess())
            {
                throw new ScreenshotCaptureException("Error attaching to DirectX");
            }
            ScreenshotResource result = null;

            // Bitmap img = null;
            // captureProcess.BringProcessWindowToFront();
            // Initiate the screenshot of the CaptureInterface, the appropriate event handler within the target process will take care of the rest

            if (captureConfig.Direct3DVersion == Direct3DVersion.Direct3D9
                ||
                captureConfig.Direct3DVersion == Direct3DVersion.Direct3D9Simple)
            {
                var start = DateTime.Now.Ticks;
                var task  = Task <Screenshot> .Factory.FromAsync(
                    (rect, timeout, callback, ctxt) => captureProcess.CaptureInterface.BeginGetScreenshot(rect, timeout, callback),
                    captureProcess.CaptureInterface.EndGetScreenshot,
                    emptyRect,
                    waitForScreenshotTimeout,
                    null);

                Screenshot screen = null;
                try
                {
                    task.Wait();
                    screen = task.Result;

                    var stop = DateTime.Now.Ticks;
                    var proc = TimeSpan.FromTicks(stop - start).Milliseconds;
                    TraceLog.Log("DX Capture speed: {0}", proc);

                    if (screen == null &&
                        directxRetryCount == 0)
                    {
                        Log.Debug("No data received from DirectX hook, retrying once.");
                        directxRetryCount++;
                        return(CaptureDirectX(wnd));
                    }
                    else if (screen == null)
                    {
                        Log.Debug("No data received from DirectX hook.");
                        return(null);
                    }
                    directxRetryCount = 0;

                    task.Dispose();
                    try
                    {
                        var width      = screen.Width;
                        var height     = screen.Height;
                        var bitmapData = screen.CapturedBitmap;
                        var img        = new Bitmap(width, height, PixelFormat.Format32bppRgb);
                        var bmpData    = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), ImageLockMode.WriteOnly, img.PixelFormat);

                        Marshal.Copy(bitmapData, 0, bmpData.Scan0, bitmapData.Length);
                        img.UnlockBits(bmpData);

                        result = new ScreenshotResource(img);
                    }
                    catch (Exception ex)
                    {
                        Log.Debug(ex, "Error decoding DirectX pixels: {0}");
                        return(null);
                    }
                }
                finally
                {
                    if (screen != null)
                    {
                        screen.Dispose();
                    }
                }
            }
            else if (captureConfig.Direct3DVersion == Direct3DVersion.Direct3D9SharedMem)
            {
                try
                {
                    if (!hookReadyWaitHandle.WaitOne(2000))
                    {
                        Log.Debug("Waiting for DirectX hook initialization.");
                        return(null);
                    }

                    captureDxWaitHandle.Set();
                    if (copyDataMem == null)
                    {
                        try
                        {
                            copyDataMem       = MemoryMappedFile.OpenExisting("CaptureHookSharedMemData", MemoryMappedFileRights.Read);
                            copyDataMemAccess = copyDataMem.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read);
                            copyDataMemAccess.SafeMemoryMappedViewHandle.AcquirePointer(ref copyDataMemPtr);
                        }
                        catch (FileNotFoundException)
                        {
                            // not hooked
                            Log.Debug("Shared memory not found");
                            return(null);
                        }
                    }
                    if (copyDataMemAccess == null)
                    {
                        // not hooked
                        Log.Debug("Shared memory not opened yet");
                        return(null);
                    }

                    int lastRendered;
                    var copyData = (*((CopyData *)copyDataMemPtr));
                    if (copyData.height <= 0 ||
                        copyData.textureId == Guid.Empty)
                    {
                        return(null);
                    }
                    lastRendered = copyData.lastRendered;

                    if (lastRendered != -1)
                    {
                        if (!sharedMemMutexes[lastRendered].WaitOne(1000))
                        {
                            Log.Warn("Failed acquiring shared texture lock in time (1000).");
                            return(null);
                        }
                        if (lastKnownTextureId != copyData.textureId)
                        {
                            for (var i = 0; i < 2; i++)
                            {
                                if (sharedTexturesAccess[i] != null)
                                {
                                    sharedTexturesAccess[i].SafeMemoryMappedViewHandle.ReleasePointer();
                                    sharedTexturesAccess[i].Dispose();
                                    sharedTexturesAccess[i] = null;
                                }
                                if (sharedTextures[i] != null)
                                {
                                    sharedTextures[i].Dispose();
                                    sharedTextures[i] = null;
                                }
                            }
                        }

                        if (sharedTextures[lastRendered] == null)
                        {
                            sharedTextures[lastRendered]       = MemoryMappedFile.OpenExisting(copyData.textureId.ToString() + lastRendered, MemoryMappedFileRights.ReadWrite);
                            sharedTexturesAccess[lastRendered] = sharedTextures[lastRendered].CreateViewAccessor(
                                0,
                                copyData.height * copyData.pitch,
                                MemoryMappedFileAccess.ReadWrite);
                            sharedTexturesAccess[lastRendered].SafeMemoryMappedViewHandle.AcquirePointer(ref sharedTexturesPtr[lastRendered]);
                        }

                        var img = new Bitmap(
                            copyData.width,
                            copyData.height,
                            copyData.pitch,
                            PixelFormat.Format32bppRgb,
                            new IntPtr(sharedTexturesPtr[lastRendered]));
                        lastKnownTextureId = copyData.textureId;
                        result             = new DxScreenshotResource(img, sharedMemMutexes[lastRendered]);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
            }

            return(result);
        }
Example #33
0
 protected void SendResponse(Screenshot response)
 {
     Task.Factory.StartNew(() =>
     {
         try
         {
             Interface.SendScreenshotResponse(response);
             LastCaptureTime = Timer.Elapsed;
         }
         catch (RemotingException)
         {
             // Ignore remoting exceptions
             // .NET Remoting will throw an exception if the host application is unreachable
         }
         catch (Exception e)
         {
             DebugMessage(e.ToString());
         }
     });
 }
Example #34
0
        public void RemoteSelenium(string Name, string DriverPort, string VNCPort, int TTL)
        {
            string[] SearchDict = new string[4] {
                "World Cup", "Mac Miller", "Donald Trump", "Kate Spade"
            };


            try
            {
                var aTimer = new CustomTimer
                {
                    _name          = Name,
                    _DC            = DC,
                    _containerID   = ContainerID_1,
                    _currentThread = Thread.CurrentThread,
                    _driver        = driver,
                    Interval       = TTL * 1000 //ms
                };

                Random r = new Random();
                SearchString = SearchDict[r.Next(0, 4)];

                aTimer.Elapsed += aTimer.OnTimedEvent;
                aTimer.Start();


                driver.Manage().Timeouts().PageLoad = TimeSpan.FromMinutes(5);

                driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromMinutes(5);

                driver.Manage().Window.Maximize(); // WINDOWS, DO NOT WORK FOR LINUX/firefox. If Linux/firefox set window size, max 1920x1080, like driver.Manage().Window.Size = new Size(1920, 1080);
                                                   // driver.Manage().Window.Size = new Size(1920, 1080); // LINUX/firefox

                driver.Navigate().GoToUrl("https://www.bing.com/");

                var wait = new WebDriverWait(driver, TimeSpan.FromMinutes(5));

                wait.Until(ExpectedConditions.ElementExists((By.XPath("//input[@id='sb_form_q']"))));


                IJavaScriptExecutor ex = (IJavaScriptExecutor)driver;

                string str = driver.PageSource;

                IWebElement element = driver.FindElement(By.XPath("//input[@id='sb_form_q']"));

                element.Click();
                element.Clear();
                //Enter some text in search text box
                element.SendKeys(SearchString);

                wait.Until(ExpectedConditions.ElementExists((By.XPath("//input[@id='sb_form_go']"))));
                element = driver.FindElement(By.XPath("//input[@id='sb_form_go']"));
                element.Submit();


                wait.Until(ExpectedConditions.ElementExists((By.Id("b_content"))));

                if (!DoneTakeSS)
                {
                    try
                    {
                        Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
                        ss.SaveAsFile(@"D:\data\SS\" + Name + ".jpg", ScreenshotImageFormat.Jpeg);
                        DoneTakeSS = true;
                    }
                    catch (Exception exSS) { }
                }
                for (int i = 0; i < 50; i++)
                {
                    int triesNo = 0;

                    for (int j = 0; j < 4; j++)
                    {
                        try
                        {
                            IWebElement NextPageElement = wait.Until(ExpectedConditions.ElementToBeClickable((By.XPath("//a[contains(@title,'Next page')]"))));
                            ex.ExecuteScript("arguments[0].click();", NextPageElement);
                            break;
                        }
                        catch (Exception ex1)
                        {
                            driver.Navigate().Refresh();
                            wait.Until(ExpectedConditions.ElementExists((By.Id("b_content"))));
                            triesNo++;
                        }
                    }

                    if (triesNo > 2)
                    {
                        break;
                    }

                    wait.Until(ExpectedConditions.ElementExists((By.Id("b_results"))));
                    Thread.Sleep(1000);

                    var webElements = driver.FindElements(By.TagName("h2"));
                    for (int j = 0; j < webElements.Count; j++)
                    {
                        using (System.IO.StreamWriter file =
                                   new System.IO.StreamWriter(@"D:\data\" + Name + ".log", true))
                        {
                            file.WriteLine($"{webElements[j].GetAttribute("innerText")}");
                        }
                    }

                    Thread.Sleep(10000);
                }


                Console.WriteLine($"{Name}:{VNCPort} done capturing!");

                Thread.Sleep(3600000);

                driver.Quit();
                Task d = DC.DisposeContainerAsync(ContainerID_1);
                d.Wait();
            }
            catch (Exception ex)
            {
                if (ex is ThreadAbortException)
                {
                }
                else
                {
                    if (driver != null)
                    {
                        driver.Quit();
                    }
                }
                Task d = DC.DisposeContainerAsync(ContainerID_1);
                d.Wait();

                Console.WriteLine($"{Name}:{VNCPort} {ex.Message}");
            }
        }
Example #35
0
 private void sendScreenshot(int client_index, Screenshot screenshot)
 {
     clients[client_index].queueOutgoingMessage(KLFCommon.ServerMessageID.SCREENSHOT_SHARE, screenshot.toByteArray());
 }
        public static void TakeScreenshot(IWebDriver driver)
        {
            Screenshot ss   = ((ITakesScreenshot)driver).GetScreenshot();
            string     path = Directory.GetParent(Environment.CurrentDirectory).ToString();

            ss.SaveAsFile(Path.GetFullPath(Path.Combine(path, @$ "..\..\Screenshots\{GetTimestamp(DateTime.Now)}.png")));
Example #37
0
        public void handleMessage(int client_index, KLFCommon.ClientMessageID id, byte[] data)
        {
            if (!clientIsValid(client_index))
            return;

            debugConsoleWriteLine("Message id: " + id.ToString() + " data: " + (data != null ? data.Length.ToString() : "0"));

            UnicodeEncoding encoder = new UnicodeEncoding();

            switch (id)
            {
            case KLFCommon.ClientMessageID.HANDSHAKE:

            if (data != null)
            {
                StringBuilder sb = new StringBuilder();

                //Read username
                Int32 username_length = KLFCommon.intFromBytes(data, 0);
                String username = encoder.GetString(data, 4, username_length);

                int offset = 4 + username_length;

                String version = encoder.GetString(data, offset, data.Length - offset);

                String username_lower = username.ToLower();

                bool accepted = true;

                //Ensure no other players have the same username
                for (int i = 0; i < clients.Length; i++)
                {
                    if (i != client_index && clientIsReady(i) && clients[i].username.ToLower() == username_lower)
                    {
                        //Disconnect the player
                        disconnectClient(client_index, "Your username is already in use.");
                        stampedConsoleWriteLine("Rejected client due to duplicate username: "******"Your Client is Outdated Please Update");
                        stampedConsoleWriteLine("Rejected client due to wrong version : " + version + " New "+ KLFCommon.PROGRAM_VERSION);
                        accepted = false;
                        break;
                }
                if (!accepted)
                    break;

                //Send the active user count to the client
                if (numClients == 2)
                {
                    //Get the username of the other user on the server
                    sb.Append("There is currently 1 other user on this server: ");
                    for (int i = 0; i < clients.Length; i++)
                    {
                        if (i != client_index && clientIsReady(i))
                        {
                            sb.Append(clients[i].username);
                            break;
                        }
                    }
                }
                else
                {
                    sb.Append("There are currently ");
                    sb.Append(numClients - 1);
                    sb.Append(" other users on this server.");
                    if (numClients > 1)
                    {
                        sb.Append(" Enter !list to see them.");
                    }
                }

                clients[client_index].username = username;
                clients[client_index].receivedHandshake = true;

                sendServerMessage(client_index, sb.ToString());
                sendServerSettings(client_index);

                stampedConsoleWriteLine(username + " ("+getClientIP(client_index).ToString()+") has joined the server using client version " + version);

                if (!clients[client_index].messagesThrottled)
                {

                    //Build join message
                    sb.Clear();
                    sb.Append("User ");
                    sb.Append(username);
                    sb.Append(" has joined the server.");

                    //Send the join message to all other clients
                    sendServerMessageToAll(sb.ToString(), client_index);
                }

                messageFloodIncrement(client_index);

            }

            break;

            case KLFCommon.ClientMessageID.PRIMARY_PLUGIN_UPDATE:
            case KLFCommon.ClientMessageID.SECONDARY_PLUGIN_UPDATE:

            if (data != null && clientIsReady(client_index))
            {
            #if SEND_UPDATES_TO_SENDER
                sendPluginUpdateToAll(data, id == KLFCommon.ClientMessageID.SECONDARY_PLUGIN_UPDATE);
            #else
                sendPluginUpdateToAll(data, id == KLFCommon.ClientMessageID.SECONDARY_PLUGIN_UPDATE, client_index);
            #endif
            }

            break;

            case KLFCommon.ClientMessageID.TEXT_MESSAGE:

            if (data != null && clientIsReady(client_index))
                handleClientTextMessage(client_index, encoder.GetString(data, 0, data.Length));

            break;

            case KLFCommon.ClientMessageID.SCREEN_WATCH_PLAYER:

            if (!clientIsReady(client_index) || data == null || data.Length < 9)
                break;

            bool send_screenshot = data[0] != 0;
            int watch_index = KLFCommon.intFromBytes(data, 1);
            int current_index = KLFCommon.intFromBytes(data, 5);
            String watch_name = encoder.GetString(data, 9, data.Length - 9);

            bool watch_name_changed = false;

            lock (clients[client_index].watchPlayerNameLock)
            {
                if (watch_name != clients[client_index].watchPlayerName || watch_index != clients[client_index].watchPlayerIndex)
                {
                    //Set the watch player name
                    clients[client_index].watchPlayerIndex = watch_index;
                    clients[client_index].watchPlayerName = watch_name;
                    watch_name_changed = true;
                }
            }

            if (send_screenshot && watch_name_changed && watch_name.Length > 0)
            {
                //Try to find the player the client is watching and send that player's current screenshot
                int watched_index = getClientIndexByName(watch_name);
                if (clientIsReady(watched_index))
                {
                    Screenshot screenshot = null;
                    lock (clients[watched_index].screenshotLock)
                    {
                        screenshot = clients[watched_index].getScreenshot(watch_index);
                        if (screenshot == null && watch_index == -1)
                            screenshot = clients[watched_index].lastScreenshot;
                    }

                    if (screenshot != null && screenshot.index != current_index)
                    {
                        sendScreenshot(client_index, screenshot);
                    }
                }
            }

            break;

            case KLFCommon.ClientMessageID.SCREENSHOT_SHARE:

            if (data != null && data.Length <= settings.screenshotSettings.maxNumBytes && clientIsReady(client_index))
            {
                if (!clients[client_index].screenshotsThrottled)
                {
                    StringBuilder sb = new StringBuilder();

                    Screenshot screenshot = new Screenshot();
                    screenshot.setFromByteArray(data);

                    //Set the screenshot for the player
                    lock (clients[client_index].screenshotLock)
                    {
                        clients[client_index].pushScreenshot(screenshot);
                    }

                    sb.Append(clients[client_index].username);
                    sb.Append(" has shared a screenshot.");

                    sendTextMessageToAll(sb.ToString());
                    stampedConsoleWriteLine(sb.ToString());

                    //Send the screenshot to every client watching the player
                    sendScreenshotToWatchers(client_index, screenshot);

                    if (settings.saveScreenshots)
                        saveScreenshot(screenshot, clients[client_index].username);
                    SHARED_SCREEN_SHOTS += 1;
                }

                bool was_throttled = clients[client_index].screenshotsThrottled;

                clients[client_index].screenshotFloodIncrement();

                if (!was_throttled && clients[client_index].screenshotsThrottled)
                {
                    long throttle_secs = settings.screenshotFloodThrottleTime / 1000;
                    sendServerMessage(client_index, "You have been restricted from sharing screenshots for " + throttle_secs + " seconds.");
                    stampedConsoleWriteLine(clients[client_index].username + " has been restricted from sharing screenshots for " + throttle_secs + " seconds.");
                }
                else if (clients[client_index].throttleState.messageFloodCounter == settings.screenshotFloodLimit - 1)
                    sendServerMessage(client_index, "Warning: You are sharing too many screenshots.");

            }

            break;

            case KLFCommon.ClientMessageID.CONNECTION_END:

            String message = String.Empty;
            if (data != null)
                message = encoder.GetString(data, 0, data.Length); //Decode the message

            disconnectClient(client_index, message); //Disconnect the client
            break;

            case KLFCommon.ClientMessageID.SHARE_CRAFT_FILE:

            if (clientIsReady(client_index) && data != null
                    && data.Length > 5 && (data.Length - 5) <= KLFCommon.MAX_CRAFT_FILE_BYTES)
            {
                if (clients[client_index].messagesThrottled)
                {
                    messageFloodIncrement(client_index);
                    break;
                }

                messageFloodIncrement(client_index);

                //Read craft name length
                byte craft_type = data[0];
                int craft_name_length = KLFCommon.intFromBytes(data, 1);
                if (craft_name_length < data.Length - 5)
                {
                    //Read craft name
                    String craft_name = encoder.GetString(data, 5, craft_name_length);

                    //Read craft bytes
                    byte[] craft_bytes = new byte[data.Length - craft_name_length - 5];
                    Array.Copy(data, 5 + craft_name_length, craft_bytes, 0, craft_bytes.Length);

                    lock (clients[client_index].sharedCraftLock)
                    {
                        clients[client_index].sharedCraftName = craft_name;
                        clients[client_index].sharedCraftFile = craft_bytes;
                        clients[client_index].sharedCraftType = craft_type;
                    }

                    //Send a message to players informing them that a craft has been shared
                    StringBuilder sb = new StringBuilder();
                    sb.Append(clients[client_index].username);
                    sb.Append(" shared ");
                    sb.Append(craft_name);

                    switch (craft_type)
                    {
                    case KLFCommon.CRAFT_TYPE_VAB:
                        sb.Append(" (VAB)");
                        break;

                    case KLFCommon.CRAFT_TYPE_SPH:
                        sb.Append(" (SPH)");
                        break;
                    }

                    stampedConsoleWriteLine(sb.ToString());

                    sb.Append(" . Enter !getcraft ");
                    sb.Append(clients[client_index].username);
                    sb.Append(" to get it.");
                    sendTextMessageToAll(sb.ToString());
                }
            }
            break;

            case KLFCommon.ClientMessageID.ACTIVITY_UPDATE_IN_FLIGHT:
            clients[client_index].updateActivityLevel(ServerClient.ActivityLevel.IN_FLIGHT);
            break;

            case KLFCommon.ClientMessageID.ACTIVITY_UPDATE_IN_GAME:
            clients[client_index].updateActivityLevel(ServerClient.ActivityLevel.IN_GAME);
            break;

            case KLFCommon.ClientMessageID.PING:
            clients[client_index].queueOutgoingMessage(KLFCommon.ServerMessageID.PING_REPLY, null);
            break;

            }

            debugConsoleWriteLine("Handled message");
        }
Example #38
0
        private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
        {
            int port = Config.portToCheck;

            if (Config.usePowerShell)
            {
                string   cmdOutput = Command.ExecutePowerShell(@"& Test-NetConnection 127.0.0.1 -PORT " + port);
                string[] splited   = cmdOutput.Replace("TcpTestSucceeded", "|").Split('|');
                if (splited.Length > 0 && splited[1].Contains("True"))
                {
                    hostStatus = true;
                }
                else
                {
                    hostStatus = false;
                }
            }
            else
            {
                hostStatus = Connection.PingHost("127.0.0.1", port);
            }


            string hostname = Dns.GetHostEntry("").HostName;

            if (hostStatus == false)
            {
                int status = Session.checkSession(hostname);
                failedCount++;
                if (
                    (failedCount >= Config.restartThreshold && (status <= (int)BPStatus.Running || status == (int)BPStatus.Warning)) ||
                    (failedCount >= Config.restartThresholdIdle && (status > (int)BPStatus.Running) && (status < (int)BPStatus.Warning))
                    )
                {
                    Command.killTask(Config.targetExe);
                    Command.ExecuteCommand(Config.batchFileName);
                }
                LogFile.WriteToFile("Check Status : " + hostStatus.ToString() + " (Session Status = " + status + ")");
            }
            else
            {
                failedCount = 0;
                LogFile.WriteToFile("Check Status : " + hostStatus.ToString());
            }


            // StartClient(hostname + "," + port.ToString() + ","+ hostStatus.ToString() + "<EOF>");
            if (restCount >= 12)
            {
                float[]  perf   = Performance.getPerformaceCounter();
                OscarLog logObj = new OscarLog();
                logObj.hostName    = hostname;
                logObj.status      = hostStatus.ToString();
                logObj.timestamps  = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                logObj.statusCount = statusCount;
                logObj.cpuUsage    = perf[0];
                logObj.ramUsage    = perf[1];
                logObj.diskUsage   = perf[2];
                for (int i = 3; i < perf.Length; i++)
                {
                    PropertyInfo propertyInfo = logObj.GetType().GetProperty("cpu" + (i - 2).ToString());
                    var          t            = typeof(float?);
                    t = Nullable.GetUnderlyingType(t);
                    propertyInfo.SetValue(logObj, Convert.ChangeType(perf[i], t), null);
                }

                //var app = new Outlook.Application();
                //Outlook.NameSpace NSpace = app.GetNamespace("MAPI");
                logObj.outlookOffline = "False";

                string logData = JsonConvert.SerializeObject(logObj, Newtonsoft.Json.Formatting.None,
                                                             new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                });
                LogFile.WriteToFile("Log Status to Server. Outlook Status : " + logObj.outlookOffline);
                _ = HttpReq.CurlRequestAsync(Config.logServer, Config.logMethod, logData);
                string filename = Screenshot.Capture();
                _           = HttpReq.UploadImage(Config.screenshotServer, filename);
                restCount   = 0;
                statusCount = 0;
                //app.Quit();
            }
            {
                restCount++;
                if (hostStatus)
                {
                    statusCount += restCount;
                }
            }
        }
Example #39
0
        private void SendScreenshotToWatchers(int clientIndex, Screenshot screenshot)
        {
            //Create a list of valid watchers
            List<int> watcherIndices = new List<int>();

            for (int i = 0; i < Clients.Length; i++)
                if (ClientIsReady(i) && Clients[i].CurrentActivity != ServerClient.Activity.Inactive)
                {
                    bool match = false;
                    lock (Clients[i].WatchPlayerNameLock)
                    {
                        match = Clients[i].WatchPlayerName == Clients[clientIndex].Username;
                    }
                    if (match)
                        watcherIndices.Add(i);
                }

            if (watcherIndices.Count > 0)
            {
                //Build the message and send it to all watchers
                byte[] messageBytes = BuildMessageArray(KLFCommon.ServerMessageID.ScreenshotShare, screenshot.ToByteArray());
                foreach (int i in watcherIndices)
                    Clients[i].QueueOutgoingMessage(messageBytes);
            }
        }
Example #40
0
 private void SaveScreenshot(Screenshot screenshot, string fileName)
 {
     screenshot.SaveAsFile(string.Format("{0}{1}", ConfigurationHelper.FolderPicture, fileName), ImageFormat.Png);
 }
Example #41
0
        public void saveScreenshot(Screenshot screenshot, String player)
        {
            if (!Directory.Exists(ScreenshotDirectory))
            {
                //Create the screenshot directory
                try
                {
                    if (!Directory.CreateDirectory(ScreenshotDirectory).Exists)
                        return;
                }
                catch (Exception)
                {
                    return;
                }
            }

            //Build the filename
            StringBuilder sb = new StringBuilder();
            sb.Append(ScreenshotDirectory);
            sb.Append('/');
            sb.Append(KLFCommon.FilteredFileName(player));
            sb.Append(' ');
            sb.Append(System.DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"));
            sb.Append(".png");

            //Write the screenshot to file
            String filename = sb.ToString();
            if (!File.Exists(filename))
            {
                try
                {
                    File.WriteAllBytes(filename, screenshot.Image);
                }
                catch (Exception) {}
            }
        }
Example #42
0
        public void TestCase_5()
        {
            string stepName = "";
            string testname = "3.PCParts";
            string datum    = Time.GetFormatedDateNow(testname);
            // scroll down java
            IJavaScriptExecutor js = driver as IJavaScriptExecutor;

            try
            {
                // 1.Navigacija drivera do PCPIKER-a
                stepName   = "1.Navigacija drivera do PCPIKER-a";
                driver.Url = "https://pcpartpicker.com/";
                driver.Manage().Window.Maximize();
                Thread.Sleep(5000);
                LogStatus.LogSuccess(stepName, testname, datum);

                // 2.Klik na Listu
                stepName = "2.Klik na Listu";
                driver.FindElement(By.ClassName("nav-build")).Click();
                Thread.Sleep(2000);
                LogStatus.LogSuccess(stepName, testname, datum);

                // 3.Pick CPU
                stepName = "3.Pick Elements CPU";
                js.ExecuteScript("window.scrollBy(0,450);");
                Thread.Sleep(2000);
                driver.FindElement(By.ClassName("btn-mds")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.Id("part_category_search")).SendKeys("4460");
                Thread.Sleep(2000);
                driver.FindElement(By.Id("px_30757")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.LinkText("Add")).Click();
                Thread.Sleep(2000);
                LogStatus.LogSuccess(stepName, testname, datum);

                // 4.Pick GPU
                stepName = "4.Pick GPU";
                js.ExecuteScript("window.scrollBy(0,450);");
                Thread.Sleep(2000);
                driver.FindElement(By.LinkText("Choose A CPU Cooler")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.Id("part_category_search")).SendKeys("Noctua NH-L9i");
                Thread.Sleep(2000);
                driver.FindElement(By.Id("px_14597")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.LinkText("Add")).Click();
                Thread.Sleep(2000);
                LogStatus.LogSuccess(stepName, testname, datum);

                // 6. Pick RAM Memory
                stepName = "6. Pick RAM Memory";
                js.ExecuteScript("window.scrollBy(0,450);");
                Thread.Sleep(2000);
                driver.FindElement(By.LinkText("Choose Memory")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.Id("part_category_search")).SendKeys("G.Skill Aegis");
                Thread.Sleep(2000);
                driver.FindElement(By.Id("px_52162")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.XPath("//a[@href='#YRvZxr']")).Click();
                Thread.Sleep(2000);
                LogStatus.LogSuccess(stepName, testname, datum);

                // 7. Pick Storage
                stepName = "6. Pick Element Memory";
                js.ExecuteScript("window.scrollBy(0,450);");
                Thread.Sleep(2000);
                driver.FindElement(By.LinkText("Choose Storage")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.Id("part_category_search")).SendKeys("970 evo");
                Thread.Sleep(2000);
                driver.FindElement(By.Id("px_174613")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.XPath("//a[@href='#JLdxFT']")).Click();
                Thread.Sleep(2000);
                LogStatus.LogSuccess(stepName, testname, datum);

                // 8.Pick Video Card
                stepName = "8. Pick Video Card";
                js.ExecuteScript("window.scrollBy(0,450);");
                Thread.Sleep(2000);
                driver.FindElement(By.LinkText("Choose A Video Card")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.Id("part_category_search")).SendKeys("1080ti");
                Thread.Sleep(2000);
                driver.FindElement(By.Id("px_102640")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.XPath("//a[@href='#YNVBD3']")).Click();
                Thread.Sleep(2000);
                LogStatus.LogSuccess(stepName, testname, datum);

                // 9. Pick Case
                stepName = "9.Pick Case";
                js.ExecuteScript("window.scrollBy(0,450);");
                Thread.Sleep(2000);
                driver.FindElement(By.LinkText("Choose A Case")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.LinkText("List")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.Id("part_category_search")).SendKeys("NZXT H700i ATX Mid Tower");
                Thread.Sleep(2000);
                driver.FindElement(By.Id("px_136584")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.XPath("//a[@href='#CVtWGX']")).Click();
                Thread.Sleep(2000);
                LogStatus.LogSuccess(stepName, testname, datum);

                // 10. Pick Power Supply
                stepName = "Pick Power Supply";
                js.ExecuteScript("window.scrollBy(0,450);");
                Thread.Sleep(2000);
                driver.FindElement(By.LinkText("Choose A Power Supply")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.Id("part_category_search")).SendKeys("EVGA SuperNOVA 850");
                Thread.Sleep(2000);
                driver.FindElement(By.Id("px_69896")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.LinkText("Add")).Click();
                Thread.Sleep(2000);
                LogStatus.LogSuccess(stepName, testname, datum);

                // 11. Pick OS
                stepName = "Pick OS";
                js.ExecuteScript("window.scrollBy(0,450);");
                Thread.Sleep(2000);
                driver.FindElement(By.LinkText("Choose An Operating System")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.Id("part_category_search")).SendKeys("Microsoft Windows 10 Pro (64-bit)");
                Thread.Sleep(2000);
                driver.FindElement(By.Id("px_47046")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.LinkText("Add")).Click();
                Thread.Sleep(2000);
                LogStatus.LogSuccess(stepName, testname, datum);

                // 12. Pick Monitor
                stepName = "Pick Monitor";
                js.ExecuteScript("window.scrollBy(0,550);");
                Thread.Sleep(2000);
                driver.FindElement(By.LinkText("Monitor")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.Id("part_category_search")).SendKeys("Acer Predator X34");
                Thread.Sleep(2000);
                driver.FindElement(By.Id("px_163366")).Click();
                Thread.Sleep(2000);
                driver.FindElement(By.LinkText("Add")).Click();
                Thread.Sleep(2000);
                js.ExecuteScript("window.scrollBy(0,350);");
                Thread.Sleep(2000);
                driver.Manage().Window.FullScreen();
                Thread.Sleep(2000);
                Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
                ss.SaveAsFile(@"D:\\PCParts.Jpeg", ScreenshotImageFormat.Jpeg);
                Thread.Sleep(5000);
                LogStatus.LogSuccess(stepName, testname, datum);
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
                LogStatus.LogError(stepName, testname, datum, msg);
                Assert.Fail(msg);
            }
        }
Example #43
0
 public void ShouldBuildAValidFilePathToSaveScreenshot()
 {
     var s = new Screenshot(Path.GetTempPath(), ImageFormat.Png);
     Assert.IsTrue(s.FilePath.StartsWith(Path.GetTempPath()));
 }
        public override CrawlerStatus Execute(out object result)
        {
            try
            {
                using (var driver = WebDriverService.CreateWebDriver(WebBrowser.Firefox))
                {
                    IWait <IWebDriver> wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30.00));

                    driver.Navigate().GoToUrl(@"http://ec2-18-231-116-58.sa-east-1.compute.amazonaws.com/login");

                    // page 1
                    driver.FindElement(By.Id("username")).SendKeys("fiap");
                    driver.FindElement(By.Id("password")).SendKeys("mpsp");
                    driver.FindElement(By.CssSelector(".btn")).Click();


                    driver.Navigate().GoToUrl(@"http://ec2-18-231-116-58.sa-east-1.compute.amazonaws.com/infocrim/login.html");

                    //page 1

                    wait.Until(driver1 =>
                               ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState")
                               .Equals("complete"));


                    driver.FindElement(By.CssSelector("#wrapper > tbody:nth-child(1) > tr:nth-child(4) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(2) > tr:nth-child(1) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(3) > input:nth-child(1)"))
                    .SendKeys(_usuario);
                    driver.FindElement(By.CssSelector("#wrapper > tbody:nth-child(1) > tr:nth-child(4) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(2) > tr:nth-child(1) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(3) > input:nth-child(1)"))
                    .SendKeys(_senha);
                    driver.FindElement(By.CssSelector("#wrapper > tbody:nth-child(1) > tr:nth-child(4) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(2) > tr:nth-child(1) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(4) > a:nth-child(1)"))
                    .Click();

                    //page 2
                    var agora = DateTime.Now.ToString("ddmmyyyy");
                    driver.FindElement(By.Id("dtIni")).SendKeys(agora);
                    driver.FindElement(By.Id("dtFim")).SendKeys(agora);
                    driver.FindElement(By.Id("enviar")).Click();

                    //page 3
                    var nome = driver.FindElement(By.CssSelector("body > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(1) > table:nth-child(3) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(5) > font:nth-child(2)")).Text;
                    driver.FindElement(By.CssSelector("body > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(1) > table:nth-child(3) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2) > a:nth-child(2)")).Click();
                    nome = nome.Replace(" ", "");
                    //page 4

                    var downloadFolderPath = $@"{AppDomain.CurrentDomain.BaseDirectory}temp\infocrim\";
                    if (!Directory.Exists(downloadFolderPath))
                    {
                        Directory.CreateDirectory(downloadFolderPath);
                    }

                    var datahora = DateTime.Now.ToString("yyyyMMddhhmm");


                    var arquivoBO = $"{downloadFolderPath}/BO_{nome}_{datahora}.png";
                    ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
                    Screenshot       screenshot       = screenshotDriver.GetScreenshot();
                    screenshot.SaveAsFile(arquivoBO, ScreenshotImageFormat.Png);

                    var resultados = new InfocrimModel
                    {
                        BO = arquivoBO
                    };

                    result = resultados;

                    Console.WriteLine("InfocrimCrawler OK");

                    return(CrawlerStatus.Success);
                }
            }
            catch (NotSupportedException e)
            {
                Console.WriteLine("Fail loading browser caught: {0}", e.Message);
                SetErrorMessage(typeof(InfocrimCrawler), e.Message);
                result = null;
                return(CrawlerStatus.Skipped);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception caught: {0}", e.Message);
                SetErrorMessage(typeof(InfocrimCrawler), e.Message);
                result = null;
                return(CrawlerStatus.Error);
            }
        }
Example #45
0
 public void ShouldNotHaveAFileNameWithDirectoryInformation()
 {
     var s = new Screenshot(Path.GetTempPath(), ImageFormat.Png);
     Assert.IsFalse(s.FileName.StartsWith(Path.GetTempPath()));
 }
Example #46
0
        public void GoThroughBasketSteps()
        {
            CheckIfLoadedXpath("//div[@class='wholeBasket']");
            System.Threading.Thread.Sleep(2000);
            Click("cphContent_cphContentMain_ctl00_ctl00_lnkOrder");
            System.Threading.Thread.Sleep(4000);

            CheckIfLoadedXpath("//label[@for='fc_differs']");
            driver.FindElement(By.XPath("//label[@for='fc_differs']")).Click();
            System.Threading.Thread.Sleep(2000);

            //fill in input
            AddInputFromDataTable();

            System.Threading.Thread.Sleep(2000);

            ValidateInputForBasket("first_name", "Invalid input data for firstname");
            ValidateInputForBasket("last_name", "Invalid input data for lastname");
            ValidateInputForBasket("Postcode", "Invalid input data for postcode number");
            ValidateInputForBasket("house_nr", "Invalid input data for house number");
            ValidateInputForBasket("email", "Invalid input data for Email address");
            ValidateInputForBasket("Telefoonnummer", "Invalid input data for telephone");
            ValidateInputForBasket("b_firstname", "Invalid input data for delivery - firstname");
            ValidateInputForBasket("b_lastname", "Invalid input data for delivery - lastname");
            ValidateInputForBasket("b_postcode", "Invalid input data for delivery - postcode");
            ValidateInputForBasket("b_housenumber", "Invalid input data for delivery - house number");
            ValidateInputForBasket("b_street", "Invalid input data for street name");
            ValidateInputForBasket("b_city", "Invalid input data for city name");

            if (listOfErrors != null && listOfErrors.Count > 0)
            {
                test.Log(Status.Info, listOfErrors.Count + " Invalid data entries. Can not reach Thank you page!");

                ITakesScreenshot screenshot = driver as ITakesScreenshot;
                Screenshot       screen     = screenshot.GetScreenshot();
                screen.SaveAsFile("D:\\NUnit Unit Test\\NUnit.Tests1\\NUnit.Tests1\\Screenshot\\AdvisorRequest\\screen7.jpeg", ScreenshotImageFormat.Jpeg);
                test.Log(Status.Info, "Snapshot below:" + test.AddScreenCaptureFromPath("D:\\NUnit Unit Test\\NUnit.Tests1\\NUnit.Tests1\\Screenshot\\AdvisorRequest\\screen7.jpeg"));
                listOfErrors.Clear();

                driver.Quit();
            }
            else
            {
                CheckIfLoaded("cphContent_cphContentMain_ctl00_ctl00_hlPayment");
                Click("cphContent_cphContentMain_ctl00_ctl00_hlPayment");

                //select the payment list
                CheckIfLoadedXpath("//div[@class='payment-container clearfix']");
                System.Threading.Thread.Sleep(2000);
                Dropdown("iDeal-select", "0721");
                Click("cphContent_cphContentMain_ctl00_ctl00_hlThankYou");
                CheckIfLoadedXpath("//div[@id='content']");
                driver.FindElement(By.XPath("//tr/td/input[@class='idealButton' and @value='1121']")).Click();

                driver.FindElement(By.XPath("//input[@class='btnLink']")).Click();
                System.Threading.Thread.Sleep(2000);

                CheckIfLoadedXpath("//div[@class='title-thank-you']");
                driver.FindElement(By.ClassName("title-thank-you"));

                test.Log(Status.Pass, "Success");
            }
        }
        /// <summary>
        /// Gets a <see cref="Screenshot"/> object representing the image of the page on the screen.
        /// </summary>
        /// <returns>A <see cref="Screenshot"/> object containing the image.</returns>
        public Screenshot GetScreenshot()
        {
            Screenshot currentScreenshot = null;
            SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle();
            WebDriverResult result = NativeDriverLibrary.Instance.CaptureScreenshotAsBase64(handle, ref stringHandle);
            ResultHandler.VerifyResultCode(result, "Unable to get screenshot");
            string screenshotValue = string.Empty;
            using (StringWrapper wrapper = new StringWrapper(stringHandle))
            {
                screenshotValue = wrapper.Value;
            }

            if (!string.IsNullOrEmpty(screenshotValue))
            {
                currentScreenshot = new Screenshot(screenshotValue);
            }

            return currentScreenshot;
        }
Example #48
0
 void Awake()
 {
     Screenshot.instance = this;
 }
Example #49
0
        /// <summary>
        /// Load the Screenshots Embedded Screenshot data
        /// </summary>
        public void LoadScreenshot()
        {
            _shotScreenshot = new Screenshot();

            // Read Screenshot Length
            _shotStream.SeekTo(0x2B4);
            _shotScreenshot.SizeOfEmbeddedScreenshot = _shotStream.ReadInt32();

            // Read Screenshot into buffer
            byte[] screenshot = new byte[_shotScreenshot.SizeOfEmbeddedScreenshot];
            _shotStream.ReadBlock(screenshot, 0, _shotScreenshot.SizeOfEmbeddedScreenshot);

            // Read Screenshot into List
            _shotScreenshot.EmbeddedScreenshot = new List<byte>();
            foreach (byte screenshotByte in screenshot)
                _shotScreenshot.EmbeddedScreenshot.Add(screenshotByte);

            // Read Footer Length
            _shotStream.SeekTo(_shotStream.Length - 0x0D);
            _shotScreenshot.BLFFooter = new byte[_shotStream.ReadInt32()];

            // Read Footer into storage
            _shotStream.SeekTo(_shotStream.Length - 0x11);
            _shotStream.ReadBlock(_shotScreenshot.BLFFooter, 0, 0x11);
        }
Example #50
0
    protected void handleMessage(KLFCommon.ServerMessageID id, byte[] data)
    {
        switch (id)
        {
            case KLFCommon.ServerMessageID.HANDSHAKE:

                Int32 protocol_version = KLFCommon.intFromBytes(data);

                if (data.Length >= 8)
                {
                    Int32 server_version_length = KLFCommon.intFromBytes(data, 4);

                    if (data.Length >= 12 + server_version_length)
                    {
                        String server_version = encoder.GetString(data, 8, server_version_length);
                        clientID = KLFCommon.intFromBytes(data, 8 + server_version_length);

                        Console.WriteLine("Handshake received. Server is running version: " + server_version);
                    }
                }

                //End the session if the protocol versions don't match
                if (protocol_version != KLFCommon.NET_PROTOCOL_VERSION)
                {
                    Console.WriteLine("Server version is incompatible with client version.");
                    endSession = true;
                    intentionalConnectionEnd = true;
                }
                else
                {
                    sendHandshakeMessage(); //Reply to the handshake
                    lock (udpTimestampLock)
                    {
                        lastUDPMessageSendTime = stopwatch.ElapsedMilliseconds;
                    }
                    handshakeCompleted = true;
                }

                break;

            case KLFCommon.ServerMessageID.HANDSHAKE_REFUSAL:

                String refusal_message = encoder.GetString(data, 0, data.Length);

                endSession = true;
                intentionalConnectionEnd = true;

                enqueuePluginChatMessage("Server refused connection. Reason: " + refusal_message, true);

                break;

            case KLFCommon.ServerMessageID.SERVER_MESSAGE:
            case KLFCommon.ServerMessageID.TEXT_MESSAGE:

                if (data != null)
                {

                    InTextMessage in_message = new InTextMessage();

                    in_message.fromServer = (id == KLFCommon.ServerMessageID.SERVER_MESSAGE);
                    in_message.message = encoder.GetString(data, 0, data.Length);

                    //Queue the message
                    enqueueTextMessage(in_message);
                }

                break;

            case KLFCommon.ServerMessageID.PLUGIN_UPDATE:

            if (data != null)
                    sendClientInteropMessage(KLFCommon.ClientInteropMessageID.PLUGIN_UPDATE, data);

                break;

            case KLFCommon.ServerMessageID.SERVER_SETTINGS:

                lock (serverSettingsLock)
                {
                    if (data != null && data.Length >= KLFCommon.SERVER_SETTINGS_LENGTH && handshakeCompleted)
                    {

                        updateInterval = KLFCommon.intFromBytes(data, 0);
                        screenshotInterval = KLFCommon.intFromBytes(data, 4);

                        lock (clientDataLock)
                        {
                            int new_screenshot_height = KLFCommon.intFromBytes(data, 8);
                            if (screenshotSettings.maxHeight != new_screenshot_height)
                            {
                                screenshotSettings.maxHeight = new_screenshot_height;
                                lastClientDataChangeTime = stopwatch.ElapsedMilliseconds;
                                enqueueTextMessage("Screenshot Height has been set to " + screenshotSettings.maxHeight);
                            }

                            if (inactiveShipsPerUpdate != data[12])
                            {
                                inactiveShipsPerUpdate = data[12];
                                lastClientDataChangeTime = stopwatch.ElapsedMilliseconds;
                            }
                        }
                    }
                }

                break;

            case KLFCommon.ServerMessageID.SCREENSHOT_SHARE:
                if (data != null && data.Length > 0 && data.Length < screenshotSettings.maxNumBytes
                    && watchPlayerName.Length > 0)
                {
                    //Cache the screenshot
                    Screenshot screenshot = new Screenshot();
                    screenshot.setFromByteArray(data);
                    cacheScreenshot(screenshot);

                    //Send the screenshot to the client
                    sendClientInteropMessage(KLFCommon.ClientInteropMessageID.SCREENSHOT_RECEIVE, data);
                }
                break;

            case KLFCommon.ServerMessageID.CONNECTION_END:

                if (data != null)
                {
                    String message = encoder.GetString(data, 0, data.Length);

                    endSession = true;

                    //If the reason is not a timeout, connection end is intentional
                    intentionalConnectionEnd = message.ToLower() != "timeout";

                    enqueuePluginChatMessage("Server closed the connection: " + message, true);
                }

                break;

            case KLFCommon.ServerMessageID.UDP_ACKNOWLEDGE:
                lock (udpTimestampLock)
                {
                    lastUDPAckReceiveTime = stopwatch.ElapsedMilliseconds;
                }
                break;

            case KLFCommon.ServerMessageID.CRAFT_FILE:

                if (data != null && data.Length > 4)
                {
                    //Read craft name length
                    byte craft_type = data[0];
                    int craft_name_length = KLFCommon.intFromBytes(data, 1);
                    if (craft_name_length < data.Length - 5)
                    {
                        //Read craft name
                        String craft_name = encoder.GetString(data, 5, craft_name_length);

                        //Read craft bytes
                        byte[] craft_bytes = new byte[data.Length - craft_name_length - 5];
                        Array.Copy(data, 5 + craft_name_length, craft_bytes, 0, craft_bytes.Length);

                        //Write the craft to a file
                        String filename = getCraftFilename(craft_name, craft_type);
                        if (filename != null)
                        {
                            try
                            {
                                File.WriteAllBytes(filename, craft_bytes);
                                enqueueTextMessage("Received craft file: " + craft_name);
                            }
                            catch
                            {
                                enqueueTextMessage("Error saving received craft file: " + craft_name);
                            }
                        }
                        else
                            enqueueTextMessage("Unable to save received craft file.");
                    }
                }

                break;

            case KLFCommon.ServerMessageID.PING_REPLY:
                if (pingStopwatch.IsRunning)
                {
                    enqueueTextMessage("Ping Reply: " + pingStopwatch.ElapsedMilliseconds + "ms");
                    pingStopwatch.Stop();
                    pingStopwatch.Reset();
                }
                break;
        }
    }
Example #51
0
        public void TakeAPicture(string pictureName)
        {
            Screenshot screenShot = ((ITakesScreenshot)driver).GetScreenshot();

            screenShot.SaveAsFile($@"C:\Screenshots\${pictureName}.jpg", ScreenshotImageFormat.Jpeg);
        }
Example #52
0
File: Main.cs Project: kleril/Lemma
		protected override void LoadContent()
		{
			this.MapContent = new ContentManager(this.Services);
			this.MapContent.RootDirectory = this.Content.RootDirectory;

			GeeUIMain.Font = this.Content.Load<SpriteFont>(this.Font);

			if (this.firstLoadContentCall)
			{
				this.firstLoadContentCall = false;

				if (!Directory.Exists(this.MapDirectory))
					Directory.CreateDirectory(this.MapDirectory);
				string challengeDirectory = Path.Combine(this.MapDirectory, "Challenge");
				if (!Directory.Exists(challengeDirectory))
					Directory.CreateDirectory(challengeDirectory);

#if VR
				if (this.VR)
				{
					this.vrLeftMesh.Load(this, Ovr.Eye.Left, this.vrLeftFov);
					this.vrRightMesh.Load(this, Ovr.Eye.Right, this.vrRightFov);
					new CommandBinding(this.ReloadedContent, (Action)this.vrLeftMesh.Reload);
					new CommandBinding(this.ReloadedContent, (Action)this.vrRightMesh.Reload);
					this.reallocateVrTargets();

					this.vrCamera = new Camera();
					this.AddComponent(this.vrCamera);
				}
#endif

				this.GraphicsDevice.PresentationParameters.PresentationInterval = PresentInterval.Immediate;
				this.GeeUI = new GeeUIMain();
				this.AddComponent(GeeUI);

				this.ConsoleUI = new ConsoleUI();
				this.AddComponent(ConsoleUI);

				this.Console = new Console.Console();
				this.AddComponent(Console);

				Lemma.Console.Console.BindType(null, this);
				Lemma.Console.Console.BindType(null, Console);

				// Initialize Wwise
				AkGlobalSoundEngineInitializer initializer = new AkGlobalSoundEngineInitializer(Path.Combine(this.Content.RootDirectory, "Wwise"));
				this.AddComponent(initializer);

				this.Listener = new AkListener();
				this.Listener.Add(new Binding<Vector3>(this.Listener.Position, this.Camera.Position));
				this.Listener.Add(new Binding<Vector3>(this.Listener.Forward, this.Camera.Forward));
				this.Listener.Add(new Binding<Vector3>(this.Listener.Up, this.Camera.Up));
				this.AddComponent(this.Listener);

				// Create the renderer.
				this.LightingManager = new LightingManager();
				this.AddComponent(this.LightingManager);
				this.Renderer = new Renderer(this, true, true, true, true, true);

				this.AddComponent(this.Renderer);
				this.Renderer.ReallocateBuffers(this.ScreenSize);

				this.renderParameters = new RenderParameters
				{
					Camera = this.Camera,
					IsMainRender = true
				};

				// Load strings
				this.Strings.Load(Path.Combine(this.Content.RootDirectory, "Strings.xlsx"));

				this.UI = new UIRenderer();
				this.UI.GeeUI = this.GeeUI;
				this.AddComponent(this.UI);

				PCInput input = new PCInput();
				this.AddComponent(input);

				Lemma.Console.Console.BindType(null, input);
				Lemma.Console.Console.BindType(null, UI);
				Lemma.Console.Console.BindType(null, Renderer);
				Lemma.Console.Console.BindType(null, LightingManager);

				input.Add(new CommandBinding(input.GetChord(new PCInput.Chord { Modifier = Keys.LeftAlt, Key = Keys.S }), delegate()
				{
					// High-resolution screenshot
					bool originalModelsVisible = Editor.EditorModelsVisible;
					Editor.EditorModelsVisible.Value = false;
					Screenshot s = new Screenshot();
					this.AddComponent(s);
					s.Take(new Point(4096, 2304), delegate()
					{
						string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
						string path;
						int i = 0;
						do
						{
							path = Path.Combine(desktop, string.Format("lemma-screen{0}.png", i));
							i++;
						}
						while (File.Exists(path));

						Screenshot.SavePng(s.Buffer, path);

						Editor.EditorModelsVisible.Value = originalModelsVisible;

						s.Delete.Execute();
					});
				}));

				this.performanceMonitor = new ListContainer();
				this.performanceMonitor.Add(new Binding<Vector2, Point>(performanceMonitor.Position, x => new Vector2(x.X, 0), this.ScreenSize));
				this.performanceMonitor.AnchorPoint.Value = new Vector2(1, 0);
				this.performanceMonitor.Visible.Value = false;
				this.performanceMonitor.Name.Value = "PerformanceMonitor";
				this.UI.Root.Children.Add(this.performanceMonitor);

				Action<string, Property<double>> addTimer = delegate(string label, Property<double> property)
				{
					TextElement text = new TextElement();
					text.FontFile.Value = this.Font;
					text.Add(new Binding<string, double>(text.Text, x => label + ": " + (x * 1000.0).ToString("F") + "ms", property));
					this.performanceMonitor.Children.Add(text);
				};

				Action<string, Property<int>> addCounter = delegate(string label, Property<int> property)
				{
					TextElement text = new TextElement();
					text.FontFile.Value = this.Font;
					text.Add(new Binding<string, int>(text.Text, x => label + ": " + x.ToString(), property));
					this.performanceMonitor.Children.Add(text);
				};

				TextElement frameRateText = new TextElement();
				frameRateText.FontFile.Value = this.Font;
				frameRateText.Add(new Binding<string, float>(frameRateText.Text, x => "FPS: " + x.ToString("0"), this.frameRate));
				this.performanceMonitor.Children.Add(frameRateText);

				addTimer("Physics", this.physicsTime);
				addTimer("Update", this.updateTime);
				addTimer("Render", this.renderTime);
				addCounter("Draw calls", this.drawCalls);
				addCounter("Triangles", this.triangles);
				addCounter("Working set", this.workingSet);

				Lemma.Console.Console.AddConCommand(new ConCommand("perf", "Toggle the performance monitor", delegate(ConCommand.ArgCollection args)
				{
					this.performanceMonitor.Visible.Value = !this.performanceMonitor.Visible;
				}));

				try
				{
					IEnumerable<string> globalStaticScripts = Directory.GetFiles(Path.Combine(this.Content.RootDirectory, "GlobalStaticScripts"), "*", SearchOption.AllDirectories).Select(x => Path.Combine("..\\GlobalStaticScripts", Path.GetFileNameWithoutExtension(x)));
					foreach (string scriptName in globalStaticScripts)
						this.executeStaticScript(scriptName);
				}
				catch (IOException)
				{

				}

				this.UIFactory = new UIFactory();
				this.AddComponent(this.UIFactory);
				this.AddComponent(this.Menu); // Have to do this here so the menu's Awake can use all our loaded stuff

				this.Spawner = new Spawner();
				this.AddComponent(this.Spawner);

				this.UI.IsMouseVisible.Value = true;

				AKRESULT akresult = AkBankLoader.LoadBank("SFX_Bank_01.bnk");
				if (akresult != AKRESULT.AK_Success)
					Log.d(string.Format("Failed to load main sound bank: {0}", akresult));

#if ANALYTICS
				this.SessionRecorder = new Session.Recorder(this);

				this.SessionRecorder.Add("Position", delegate()
				{
					Entity p = PlayerFactory.Instance;
					if (p != null && p.Active)
						return p.Get<Transform>().Position;
					else
						return Vector3.Zero;
				});

				this.SessionRecorder.Add("Health", delegate()
				{
					Entity p = PlayerFactory.Instance;
					if (p != null && p.Active)
						return p.Get<Player>().Health;
					else
						return 0.0f;
				});

				this.SessionRecorder.Add("Framerate", delegate()
				{
					return this.frameRate;
				});

				this.SessionRecorder.Add("WorkingSet", delegate()
				{
					return this.workingSet;
				});
				this.AddComponent(this.SessionRecorder);
				this.SessionRecorder.Add(new Binding<bool, Config.RecordAnalytics>(this.SessionRecorder.EnableUpload, x => x == Config.RecordAnalytics.On, this.Settings.Analytics));
#endif

				this.DefaultLighting();

				new SetBinding<float>(this.Settings.SoundEffectVolume, delegate(float value)
				{
					AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.VOLUME_SFX, MathHelper.Clamp(value, 0.0f, 1.0f));
				});

				new SetBinding<float>(this.Settings.MusicVolume, delegate(float value)
				{
					AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.VOLUME_MUSIC, MathHelper.Clamp(value, 0.0f, 1.0f));
				});

				new TwoWayBinding<LightingManager.DynamicShadowSetting>(this.Settings.DynamicShadows, this.LightingManager.DynamicShadows);
				new TwoWayBinding<float>(this.Settings.MotionBlurAmount, this.Renderer.MotionBlurAmount);
				new TwoWayBinding<float>(this.Settings.Gamma, this.Renderer.Gamma);
				new TwoWayBinding<bool>(this.Settings.Bloom, this.Renderer.EnableBloom);
				new TwoWayBinding<bool>(this.Settings.SSAO, this.Renderer.EnableSSAO);
				new Binding<float>(this.Camera.FieldOfView, this.Settings.FieldOfView);

				foreach (string file in Directory.GetFiles(this.MapDirectory, "*.xlsx", SearchOption.TopDirectoryOnly))
					this.Strings.Load(file);

				new Binding<string, Config.Lang>(this.Strings.Language, x => x.ToString(), this.Settings.Language);
				new NotifyBinding(this.SaveSettings, this.Settings.Language);

				new CommandBinding(this.MapLoaded, delegate()
				{
					this.Renderer.BlurAmount.Value = 0.0f;
					this.Renderer.Tint.Value = new Vector3(1.0f);
				});

#if VR
				if (this.VR)
				{
					Action loadVrEffect = delegate()
					{
						this.vrEffect = this.Content.Load<Effect>("Effects\\Oculus");
					};
					loadVrEffect();
					new CommandBinding(this.ReloadedContent, loadVrEffect);

					this.UI.Add(new Binding<Point>(this.UI.RenderTargetSize, this.ScreenSize));

					this.VRUI = new Lemma.Components.ModelNonPostProcessed();
					this.VRUI.MapContent = false;
					this.VRUI.DrawOrder.Value = 100000; // On top of everything
					this.VRUI.Filename.Value = "Models\\plane";
					this.VRUI.EffectFile.Value = "Effects\\VirtualUI";
					this.VRUI.Add(new Binding<Microsoft.Xna.Framework.Graphics.RenderTarget2D>(this.VRUI.GetRenderTarget2DParameter("Diffuse" + Lemma.Components.Model.SamplerPostfix), this.UI.RenderTarget));
					this.VRUI.Add(new Binding<Matrix>(this.VRUI.Transform, delegate()
					{
						Matrix rot = this.Camera.RotationMatrix;
						Matrix mat = Matrix.Identity;
						mat.Forward = rot.Right;
						mat.Right = rot.Forward;
						mat.Up = rot.Up;
						mat *= Matrix.CreateScale(7);
						mat.Translation = this.Camera.Position + rot.Forward * 4.0f;
						return mat;
					}, this.Camera.Position, this.Camera.RotationMatrix));
					this.AddComponent(this.VRUI);

					this.UI.Setup3D(this.VRUI.Transform);
				}
#endif

#if ANALYTICS
				bool editorLastEnabled = this.EditorEnabled;
				new CommandBinding<string>(this.LoadingMap, delegate(string newMap)
				{
					if (this.MapFile.Value != null && !editorLastEnabled)
					{
						this.SessionRecorder.RecordEvent("ChangedMap", newMap);
						if (!this.IsChallengeMap(this.MapFile) && this.MapFile.Value != Main.MenuMap)
							this.SaveAnalytics();
					}
					this.SessionRecorder.Reset();
					editorLastEnabled = this.EditorEnabled;
				});
#endif
				new CommandBinding<string>(this.LoadingMap, delegate(string newMap)
				{
					this.CancelScheduledSave();
				});

#if !DEVELOPMENT
				IO.MapLoader.Load(this, MenuMap);
				this.Menu.Show(initial: true);
#endif

#if ANALYTICS
				if (this.Settings.Analytics.Value == Config.RecordAnalytics.Ask)
				{
					this.Menu.ShowDialog("\\analytics prompt", "\\enable analytics", delegate()
					{
						this.Settings.Analytics.Value = Config.RecordAnalytics.On;
					},
					"\\disable analytics", delegate()
					{
						this.Settings.Analytics.Value = Config.RecordAnalytics.Off;
					});
				}
#endif

#if VR
				if (this.oculusNotFound)
					this.Menu.HideMessage(null, this.Menu.ShowMessage(null, "Error: no Oculus found."), 6.0f);

				if (this.VR)
				{
					this.Menu.EnableInput(false);
					Container vrMsg = this.Menu.BuildMessage("\\vr message", 300.0f);
					vrMsg.AnchorPoint.Value = new Vector2(0.5f, 0.5f);
					vrMsg.Add(new Binding<Vector2, Point>(vrMsg.Position, x => new Vector2(x.X * 0.5f, x.Y * 0.5f), this.ScreenSize));
					this.UI.Root.Children.Add(vrMsg);
					input.Bind(this.Settings.RecenterVRPose, PCInput.InputState.Down, this.VRHmd.RecenterPose);
					input.Bind(this.Settings.RecenterVRPose, PCInput.InputState.Down, delegate()
					{
						if (vrMsg != null)
						{
							vrMsg.Delete.Execute();
							vrMsg = null;
						}
						this.Menu.EnableInput(true);
					});
				}
				else
#endif
				{
					input.Bind(this.Settings.ToggleFullscreen, PCInput.InputState.Down, delegate()
					{
						if (this.Settings.Fullscreen) // Already fullscreen. Go to windowed mode.
							this.ExitFullscreen();
						else // In windowed mode. Go to fullscreen.
							this.EnterFullscreen();
					});
				}

				input.Bind(this.Settings.QuickSave, PCInput.InputState.Down, delegate()
				{
					this.SaveWithNotification(true);
				});
			}
			else
			{
				this.ReloadingContent.Execute();
				foreach (IGraphicsComponent c in this.graphicsComponents)
					c.LoadContent(true);
				this.ReloadedContent.Execute();
			}

			this.GraphicsDevice.RasterizerState = new RasterizerState { MultiSampleAntiAlias = false };

			if (this.spriteBatch != null)
				this.spriteBatch.Dispose();
			this.spriteBatch = new SpriteBatch(this.GraphicsDevice);
		}
Example #53
0
        public void IniciarPortal(string url, string placas)
        {
            placa[0]         = placas;
            BarraEstado.Text = "Iniciando navegador";
            objNu4.ReportarLog(rutalog, "Iniciando navegador");
            ChromeOptions options = new ChromeOptions();

            options.AddArgument("--window-size=600,800");
            var driverService = ChromeDriverService.CreateDefaultService();

            driverService.HideCommandPromptWindow = true;
            driver = new ChromeDriver(driverService, options);
            driver.Navigate().GoToUrl(url);
            Wait("Nombre", "jcaptcha");
            Thread.Sleep(2000);
            for (int a = 0; a < placa.Length; a++)
            {
                Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
                ss.SaveAsFile("file_name_string.Png", ScreenshotImageFormat.Png);
                Bitmap bitmap;
                bitmap = new Bitmap(Directory.GetCurrentDirectory() + @"\file_name_string.Png");
                Rectangle   cloneRect = new Rectangle(14, 382, 206, 93);
                PixelFormat format    = bitmap.PixelFormat;
                Bitmap      clone     = bitmap.Clone(cloneRect, format);
                bitmap.Dispose();
                clone.Save(Directory.GetCurrentDirectory() + @"\file_name_string2.Png", System.Drawing.Imaging.ImageFormat.Png);
                Image  imagi        = procesarImagen(clone, 220);
                string valorcaptcha = reconhecerCaptcha(imagi);
                imagi.Dispose();
                valorcaptcha = valorcaptcha.Replace("\n", "").Replace("\r", "").Replace("\t", "").Replace(" ", "");
                if (valorcaptcha != "" && valorcaptcha.Length >= 6)
                {
                    driver.FindElement(By.Name("jcaptcha")).Click();
                    driver.FindElement(By.Name("jcaptcha")).SendKeys(valorcaptcha);
                    Thread.Sleep(1000);

                    ReadOnlyCollection <IWebElement> tags = driver.FindElements(By.TagName("a"));
                    foreach (IWebElement item in tags)
                    {
                        string tex = item.Text;
                        if (tex == "BUSCAR")
                        {
                            item.Click();
                            break;
                        }
                    }
                    var hecho = driver.FindElements(By.Name("placa"));
                    if (hecho.Count == 0)
                    {
                        MessageBox.Show("Esta hecho :)");
                    }
                    else
                    {
                        a--;
                        driver.Navigate().Refresh();
                    }
                }
                else
                {
                    a--;
                    driver.Navigate().Refresh();
                }
            }
        }
Example #54
0
 /// <summary>
 /// Save screenshot in screenshots directory with specified file name
 /// </summary>
 /// <param name="ss"></param>
 /// <param name="filename"></param>
 private void SaveCurrentScreenshot(Screenshot ss, string filename)
 {
     ss.SaveAsFile($"{ScreenshotsDirectory}/{filename}.jpg", ScreenshotImageFormat.Jpeg);
 }
Example #55
0
    protected void cacheScreenshot(Screenshot screenshot)
    {
        foreach (Screenshot cached_screenshot in cachedScreenshots)
        {
            if (cached_screenshot.index == screenshot.index && cached_screenshot.player == screenshot.player)
                return;
        }

        cachedScreenshots.Add(screenshot);
        while (cachedScreenshots.Count > MAX_CACHED_SCREENSHOTS)
            cachedScreenshots.RemoveAt(0);
    }
Example #56
0
        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt && e.KeyCode == Keys.F4)
            {
                if (Client != null && IsOnServer())
                {
                    Client.Disconnect("Quit");
                }
                CEFManager.Draw = false;
                CEFManager.Dispose();
                CEFManager.DisposeCef();

                Process.GetProcessesByName("GTA5")[0].Kill();
                Process.GetCurrentProcess().Kill();
            }
            Chat.OnKeyDown(e.KeyCode);
            switch (e.KeyCode)
            {
            case Keys.Escape:
                if (IsOnServer())
                {
                    if (_isGoingToCar)
                    {
                        Game.Player.Character.Task.ClearAll();
                        _isGoingToCar = false;
                    }
                }
                if (Client != null && Client.ConnectionStatus == NetConnectionStatus.Disconnected)
                {
                    Client.Disconnect("Quit");
                }
                break;

            case Keys.P:
                if (IsOnServer() && !MainMenu.Visible && !Chat.IsFocused && !CefController.ShowCursor)
                {
                    _mainWarning = new Warning("Disabled feature", "Game settings menu has been disabled while connected.\nDisconnect from the server first.")
                    {
                        OnAccept = () => { _mainWarning.Visible = false; }
                    };
                }
                break;

            case Keys.F10:
                if (!Chat.IsFocused && !_mainWarning.Visible)
                {
                    MainMenu.Visible = !MainMenu.Visible;
                    if (!IsOnServer())
                    {
                        World.RenderingCamera = MainMenu.Visible ? MainMenuCamera : null;
                    }
                    else if (MainMenu.Visible)
                    {
                        RebuildPlayersList();
                    }
                    MainMenu.RefreshIndex();
                }
                break;

            case Keys.F7:
                if (IsOnServer())
                {
                    ChatVisible = !ChatVisible;
                    UIVisible   = !UIVisible;
                    Function.Call(Hash.DISPLAY_RADAR, UIVisible);
                    Function.Call(Hash.DISPLAY_HUD, UIVisible);
                }
                break;

            case Keys.T:
                if (IsOnServer() && UIVisible && ChatVisible && ScriptChatVisible && CanOpenChatbox && !_mainWarning.Visible)
                {
                    if (!_oldChat)
                    {
                        Chat.IsFocused = true;
                        _wasTyping     = true;
                    }
                    else
                    {
                        var message = Game.GetUserInput();
                        if (string.IsNullOrEmpty(message))
                        {
                            break;
                        }

                        var obj = new ChatData {
                            Message = message,
                        };
                        var data = SerializeBinary(obj);

                        var msg = Client?.CreateMessage();
                        msg?.Write((byte)PacketType.ChatData);
                        msg?.Write(data.Length);
                        msg?.Write(data);
                        Client?.SendMessage(msg, NetDeliveryMethod.ReliableOrdered, (int)ConnectionChannel.SyncEvent);
                    }
                }
                break;

            case Keys.G:
                if (IsOnServer() && !Game.Player.Character.IsInVehicle() && !Chat.IsFocused)
                {
                    //var veh = new Vehicle(StreamerThread.StreamedInVehicles[0].LocalHandle);
                    List <Vehicle> vehs;
                    if (!(vehs = World.GetAllVehicles().OrderBy(v => v.Position.DistanceToSquared(Game.Player.Character.Position)).Take(1).ToList()).Any())
                    {
                        break;
                    }

                    Vehicle veh;
                    if (!(veh = vehs[0]).Exists())
                    {
                        break;
                    }
                    if (!Game.Player.Character.IsInRangeOfEx(veh.Position, 6f))
                    {
                        break;
                    }

                    var playerChar = Game.Player.Character;
                    var relPos     = veh.GetOffsetFromWorldCoords(playerChar.Position);
                    var seat       = VehicleSeat.Any;

                    if (veh.PassengerCapacity > 1)
                    {
                        if (relPos.X < 0 && relPos.Y > 0)
                        {
                            seat = VehicleSeat.LeftRear;
                        }
                        else if (relPos.X >= 0 && relPos.Y > 0)
                        {
                            seat = VehicleSeat.RightFront;
                        }
                        else if (relPos.X < 0 && relPos.Y <= 0)
                        {
                            seat = VehicleSeat.LeftRear;
                        }
                        else if (relPos.X >= 0 && relPos.Y <= 0)
                        {
                            seat = VehicleSeat.RightRear;
                        }
                    }
                    else
                    {
                        seat = VehicleSeat.Passenger;
                    }

                    //else if (veh.PassengerCapacity > 2 && veh.GetPedOnSeat(seat).Handle != 0)
                    //{
                    //    switch (seat)
                    //    {
                    //        case VehicleSeat.LeftRear:
                    //            for (int i = 3; i < veh.PassengerCapacity; i += 2)
                    //            {
                    //                if (veh.GetPedOnSeat((VehicleSeat) i).Handle != 0) continue;
                    //                seat = (VehicleSeat) i;
                    //                break;
                    //            }
                    //            break;
                    //        case VehicleSeat.RightRear:
                    //            for (int i = 4; i < veh.PassengerCapacity; i += 2)
                    //            {
                    //                if (veh.GetPedOnSeat((VehicleSeat) i).Handle != 0) continue;
                    //                seat = (VehicleSeat) i;
                    //                break;
                    //            }
                    //            break;
                    //    }
                    //}

                    if (WeaponDataProvider.DoesVehicleSeatHaveGunPosition((VehicleHash)veh.Model.Hash, 0, true) && playerChar.IsIdle && !Game.Player.IsAiming)
                    {
                        playerChar.SetIntoVehicle(veh, seat);
                    }
                    else
                    {
                        //TODO садиться в тачку
                        //veh.GetPedOnSeat(seat).CanBeDraggedOutOfVehicle = true;
                        playerChar.Task.EnterVehicle(veh, seat, -1, 2f);
                        //Function.Call(Hash.KNOCK_PED_OFF_VEHICLE, veh.GetPedOnSeat(seat).Handle);
                        //Function.Call(Hash.SET_PED_CAN_BE_KNOCKED_OFF_VEHICLE, veh.GetPedOnSeat(seat).Handle, true); // 7A6535691B477C48 8A251612
                        //_isGoingToCar = true;
                    }
                }
                break;

            default:
                if (e.KeyCode == PlayerSettings.ScreenshotKey && IsOnServer())
                {
                    Screenshot.TakeScreenshot();
                }
                break;
            }
        }
Example #57
0
File: Main.cs Project: kleril/Lemma
		public Main(int monitor)
		{
#endif
			Factory<Main>.Initialize();
			Voxel.States.Init();
			Editor.SetupDefaultEditorComponents();

#if STEAMWORKS
			if (!SteamWorker.Init())
				Log.d("Failed to initialize Steamworks.");
#if VR
			if (SteamWorker.Initialized && Steamworks.SteamUtils.IsSteamRunningInVR())
				this.VR = vr = true;
#endif
#endif

#if VR
			if (this.VR)
			{
				if (!Ovr.Hmd.Initialize(new Ovr.InitParams()))
					throw new Exception("Failed to initialize Oculus runtime.");
				this.VRHmd = new Ovr.Hmd(0);
				if (this.VRHmd == null)
				{
					Log.d("Error: no Oculus found.");
					this.VR = false;
					this.oculusNotFound = true;
				}
				else
				{
					if (!this.VRHmd.ConfigureTracking(
						(uint)Ovr.TrackingCaps.Orientation
						| (uint)Ovr.TrackingCaps.MagYawCorrection
						| (uint)Ovr.TrackingCaps.Position, 0))
						throw new Exception("Failed to configure head tracking.");
					this.vrHmdDesc = this.VRHmd.GetDesc();
					this.vrLeftFov = this.vrHmdDesc.MaxEyeFov[0];
					this.vrRightFov = this.vrHmdDesc.MaxEyeFov[1];
					Ovr.FovPort maxFov = new Ovr.FovPort();
					maxFov.UpTan = Math.Max(this.vrLeftFov.UpTan, this.vrRightFov.UpTan);
					maxFov.DownTan = Math.Max(this.vrLeftFov.DownTan, this.vrRightFov.DownTan);
					maxFov.LeftTan = Math.Max(this.vrLeftFov.LeftTan, this.vrRightFov.LeftTan);
					maxFov.RightTan = Math.Max(this.vrLeftFov.RightTan, this.vrRightFov.RightTan);
					float combinedTanHalfFovHorizontal = Math.Max(maxFov.LeftTan, maxFov.RightTan);
					float combinedTanHalfFovVertical = Math.Max(maxFov.UpTan, maxFov.DownTan);
					this.vrLeftEyeRenderDesc = this.VRHmd.GetRenderDesc(Ovr.Eye.Left, this.vrLeftFov);
					this.vrRightEyeRenderDesc = this.VRHmd.GetRenderDesc(Ovr.Eye.Right, this.vrRightFov);
				}
			}
#endif

			this.Space = new Space();
			this.Space.TimeStepSettings.TimeStepDuration = 1.0f / (float)maxPhysicsFramerate;
			this.ScreenSize.Value = new Point(this.Window.ClientBounds.Width, this.Window.ClientBounds.Height);

			// Give the space some threads to work with.
			// Just throw a thread at every processor. The thread scheduler will take care of where to put them.
			for (int i = 0; i < Environment.ProcessorCount - 1; i++)
				this.Space.ThreadManager.AddThread();
			this.Space.ForceUpdater.Gravity = new Vector3(0, -18.0f, 0);

			this.IsFixedTimeStep = false;

			this.Window.AllowUserResizing = true;
			this.Window.ClientSizeChanged += new EventHandler<EventArgs>(delegate(object obj, EventArgs e)
			{
				if (!this.Settings.Fullscreen)
				{
					Rectangle bounds = this.Window.ClientBounds;
					this.ScreenSize.Value = new Point(bounds.Width, bounds.Height);
					this.resize = new Point(bounds.Width, bounds.Height);
				}
			});

			this.Graphics = new GraphicsDeviceManager(this);

			this.Content = new ContentManager(this.Services);
			this.Content.RootDirectory = "Content";

			this.Entities = new ListProperty<Entity>();

			this.Camera = new Camera();
			this.AddComponent(this.Camera);

			Lemma.Console.Console.AddConVar(new ConVar("player_speed", "Player speed.", s =>
			{
				Entity playerData = PlayerDataFactory.Instance;
				if (playerData != null)
					playerData.Get<PlayerData>().MaxSpeed.Value = (float)Lemma.Console.Console.GetConVar("player_speed").GetCastedValue();
			}, "10") { TypeConstraint = typeof(float), Validate = o => (float)o > 0 && (float)o < 200 });

			Lemma.Console.Console.AddConCommand(new ConCommand("help", "List all commands or get info about a specific command.",
			delegate(ConCommand.ArgCollection args)
			{
				string cmd = (string)args.Get("command");
				if (string.IsNullOrEmpty(cmd))
					Lemma.Console.Console.Instance.ListAllConsoleStuff();
				else
					Lemma.Console.Console.Instance.PrintConCommandDescription(cmd);
			},
			new ConCommand.CommandArgument() { Name = "command", Optional = true }));

			Lemma.Console.Console.AddConVar(new ConVar("time_scale", "Time scale (percentage).", s =>
			{
				float result;
				if (float.TryParse(s, out result))
					this.BaseTimeMultiplier.Value = result / 100.0f;
			}, "100") { TypeConstraint = typeof(int), Validate = o => (int)o > 0 && (int)o <= 400 });

			Lemma.Console.Console.AddConCommand(new ConCommand
			(
				"load", "Load a map.", collection =>
				{
					ConsoleUI.Showing.Value = false;
					this.Menu.Toggle();
					IO.MapLoader.Transition(this, collection.ParsedArgs[0].StrValue);
				},
				new ConCommand.CommandArgument { Name = "map", CommandType = typeof(string), Optional = false }
			));

			Lemma.Console.Console.AddConVar(new ConVar("blocks", "Player block cheat (white, yellow, blue)", s =>
			{
				Entity player = PlayerFactory.Instance;
				if (player != null && player.Active)
				{
					Voxel.t result = Voxel.t.Empty;
					switch (s.ToLower())
					{
						case "white":
							result = Voxel.t.WhitePermanent;
							break;
						case "yellow":
							result = Voxel.t.GlowYellow;
							break;
						case "blue":
							result = Voxel.t.GlowBlue;
							break;
						default:
							break;
					}
					BlockCloud cloud = player.Get<BlockCloud>();
					cloud.Blocks.Clear();
					cloud.Type.Value = result;
				}
			}, "none"));

			Lemma.Console.Console.AddConCommand(new ConCommand("moves", "Enable all parkour moves.", delegate(ConCommand.ArgCollection args)
			{
				if (PlayerDataFactory.Instance != null)
				{
					PlayerData playerData = PlayerDataFactory.Instance.Get<PlayerData>();
					playerData.EnableRoll.Value = true;
					playerData.EnableKick.Value = true;
					playerData.EnableWallRun.Value = true;
					playerData.EnableWallRunHorizontal.Value = true;
					playerData.EnableMoves.Value = true;
					playerData.EnableCrouch.Value = true;
					playerData.EnableSlowMotion.Value = true;
				}
			}));

#if DEVELOPMENT
			Lemma.Console.Console.AddConCommand(new ConCommand("diavar", "Set a dialogue variable.", delegate(ConCommand.ArgCollection args)
			{
				if (args.ParsedArgs.Length == 2)
				{
					if (PlayerDataFactory.Instance != null)
					{
						Phone phone = PlayerDataFactory.Instance.Get<Phone>();
						phone[args.ParsedArgs[0].StrValue] = args.ParsedArgs[1].StrValue;
					}
				}
			},
			new ConCommand.CommandArgument { Name = "variable", CommandType = typeof(string), Optional = false, },
			new ConCommand.CommandArgument { Name = "value", CommandType = typeof(string), Optional = false }
			));
#endif

			Lemma.Console.Console.AddConCommand(new ConCommand("specials", "Enable all special abilities.", delegate(ConCommand.ArgCollection args)
			{
				if (PlayerDataFactory.Instance != null)
				{
					PlayerData playerData = PlayerDataFactory.Instance.Get<PlayerData>();
					playerData.EnableEnhancedWallRun.Value = true;
				}
			}));

			new SetBinding<float>(this.PauseAudioEffect, delegate(float value)
			{
				AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.PAUSE_PARAMETER, MathHelper.Clamp(value, 0.0f, 1.0f));
			});

			new CommandBinding(this.MapLoaded, delegate()
			{
				this.mapLoaded = true;
			});

#if DEVELOPMENT
			this.EditorEnabled.Value = true;
#else
			this.EditorEnabled.Value = false;
#endif

			if (!Directory.Exists(Main.DataDirectory))
				Directory.CreateDirectory(Main.DataDirectory);
			this.settingsFile = Path.Combine(Main.DataDirectory, "settings.json");
			this.SaveDirectory = Path.Combine(Main.DataDirectory, "saves");
			if (!Directory.Exists(this.SaveDirectory))
				Directory.CreateDirectory(this.SaveDirectory);
			this.analyticsDirectory = Path.Combine(Main.DataDirectory, "analytics");
			if (!Directory.Exists(this.analyticsDirectory))
				Directory.CreateDirectory(this.analyticsDirectory);
			this.CustomMapDirectory = Path.Combine(Main.DataDirectory, "maps");
			if (!Directory.Exists(this.CustomMapDirectory))
				Directory.CreateDirectory(this.CustomMapDirectory);
			this.MapDirectory = Path.Combine(this.Content.RootDirectory, IO.MapLoader.MapDirectory);

			this.timesFile = Path.Combine(Main.DataDirectory, "times.dat");
			try
			{
				using (Stream fs = new FileStream(this.timesFile, FileMode.Open, FileAccess.Read, FileShare.None))
				using (Stream stream = new GZipInputStream(fs))
				using (StreamReader reader = new StreamReader(stream))
					this.times = JsonConvert.DeserializeObject<Dictionary<string, float>>(reader.ReadToEnd());
			}
			catch (Exception)
			{
			}

			if (this.times == null)
				this.times = new Dictionary<string, float>();

			try
			{
				// Attempt to load previous window state
				this.Settings = JsonConvert.DeserializeObject<Config>(File.ReadAllText(this.settingsFile));
				if (this.Settings.Version != Main.ConfigVersion)
					throw new Exception();
			}
			catch (Exception) // File doesn't exist, there was a deserialization error, or we are on a new version. Use default window settings
			{
				this.Settings = new Config();
			}

			if (string.IsNullOrEmpty(this.Settings.UUID))
				this.Settings.UUID = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 32);
			this.Settings.MinimizeCameraMovementVR.Value |= this.Settings.MinimizeCameraMovement;
			this.MinimizeCameraMovement = this.VR ? this.Settings.MinimizeCameraMovementVR : this.Settings.MinimizeCameraMovement;
			this.Settings.GodModeProperty.Value = this.Settings.GodMode;
			this.Settings.LevelIndexProperty.Value = this.Settings.LevelIndex;
			new NotifyBinding(delegate() { this.Settings.GodMode = this.Settings.GodModeProperty; }, this.Settings.GodModeProperty);
			new NotifyBinding(delegate() { this.Settings.LevelIndex = this.Settings.LevelIndexProperty; }, this.Settings.LevelIndexProperty);
			
			TextElement.BindableProperties.Add("Forward", this.Settings.Forward);
			TextElement.BindableProperties.Add("Left", this.Settings.Left);
			TextElement.BindableProperties.Add("Backward", this.Settings.Backward);
			TextElement.BindableProperties.Add("Right", this.Settings.Right);
			TextElement.BindableProperties.Add("Jump", this.Settings.Jump);
			TextElement.BindableProperties.Add("Parkour", this.Settings.Parkour);
			TextElement.BindableProperties.Add("RollKick", this.Settings.RollKick);
			TextElement.BindableProperties.Add("TogglePhone", this.Settings.TogglePhone);
			TextElement.BindableProperties.Add("QuickSave", this.Settings.QuickSave);
			TextElement.BindableProperties.Add("ToggleFullscreen", this.Settings.ToggleFullscreen);
			TextElement.BindableProperties.Add("RecenterVRPose", this.Settings.RecenterVRPose);
			TextElement.BindableProperties.Add("ToggleConsole", this.Settings.ToggleConsole);

			new NotifyBinding
			(
				this.updateTimesteps,
				this.BaseTimeMultiplier, this.TimeMultiplier, this.Settings.FPSLimit
			);
			this.updateTimesteps();

			if (this.Settings.FullscreenResolution.Value.X == 0)
				this.Settings.FullscreenResolution.Value = new Point(this.nativeDisplayMode.Width, this.nativeDisplayMode.Height);

			// Have to create the menu here so it can catch the PreparingDeviceSettings event
			// We call AddComponent(this.Menu) later on in LoadContent.
			this.Menu = new Menu();
			this.Graphics.PreparingDeviceSettings += delegate(object sender, PreparingDeviceSettingsEventArgs args)
			{
				args.GraphicsDeviceInformation.Adapter = GraphicsAdapter.Adapters[this.monitor];

				args.GraphicsDeviceInformation.PresentationParameters.PresentationInterval = PresentInterval.Immediate;

				List<DisplayMode> supportedDisplayModes = args.GraphicsDeviceInformation.Adapter.SupportedDisplayModes.Where(x => x.Width <= 4096 && x.Height <= 4096).ToList();
				int displayModeIndex = 0;
				foreach (DisplayMode mode in supportedDisplayModes)
				{
					if (mode.Format == SurfaceFormat.Color && mode.Width == this.Settings.FullscreenResolution.Value.X && mode.Height == this.Settings.FullscreenResolution.Value.Y)
						break;
					displayModeIndex++;
				}
				this.Menu.SetupDisplayModes(supportedDisplayModes, displayModeIndex);
			};

			this.Screenshot = new Screenshot();
			this.AddComponent(this.Screenshot);

			this.Graphics.SynchronizeWithVerticalRetrace = this.Settings.Vsync;
			new NotifyBinding(delegate()
			{
				this.Graphics.SynchronizeWithVerticalRetrace = this.Settings.Vsync;
				if (this.Settings.Fullscreen)
					this.Graphics.ApplyChanges();
			}, this.Settings.Vsync);

#if VR
			if (this.VR)
				this.ResizeViewport(this.nativeDisplayMode.Width, this.nativeDisplayMode.Height, true, false, false);
			else
#endif
			if (this.Settings.Fullscreen)
				this.ResizeViewport(this.Settings.FullscreenResolution.Value.X, this.Settings.FullscreenResolution.Value.Y, true, this.Settings.Borderless, false);
			else
				this.ResizeViewport(this.Settings.Size.Value.X, this.Settings.Size.Value.Y, false, this.Settings.Borderless, false);
		}
Example #58
0
        private void TakeFullScreenshot(IWebDriver driver, string filename, ScreenshotImageFormat format)
        {
            Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();

            screenshot.SaveAsFile(filename, format);
        }
Example #59
0
    protected void HandleMessage(KLFCommon.ServerMessageID id, byte[] data)
    {
        switch (id)
        {
        case KLFCommon.ServerMessageID.Handshake:
            Int32 protocolVersion = KLFCommon.BytesToInt(data);
            if (data.Length >= 8)
            {
                Int32 server_version_length = KLFCommon.BytesToInt(data, 4);
                if (data.Length >= 12 + server_version_length)
                {
                    String server_version = Encoder.GetString(data, 8, server_version_length);
                    ClientID = KLFCommon.BytesToInt(data, 8 + server_version_length);
                    Console.WriteLine("Handshake received. Server is running version: " + server_version);
                }
            }
            //End the session if the protocol versions don't match
            if (protocolVersion != KLFCommon.NetProtocolVersion)
            {
                Console.WriteLine("Server version is incompatible with client version.");
                EndSession = true;
                IntentionalConnectionEnd = true;
            }
            else
            {
                SendHandshakeMessage(); //Reply to the handshake
                lock (UdpTimestampLock)
                {
                    LastUdpMessageSendTime = ClientStopwatch.ElapsedMilliseconds;
                }
                HandshakeComplete = true;
            }
            break;

        case KLFCommon.ServerMessageID.HandshakeRefusal:
            String refusal_message = Encoder.GetString(data, 0, data.Length);
            EndSession = true;
            IntentionalConnectionEnd = true;
            EnqueuePluginChatMessage("Server refused connection. Reason: " + refusal_message, true);
            break;

        case KLFCommon.ServerMessageID.ServerMessage:
        case KLFCommon.ServerMessageID.TextMessage:
            if (data != null)
            {
                InTextMessage inMessage = new InTextMessage();
                inMessage.FromServer = (id == KLFCommon.ServerMessageID.ServerMessage);
                inMessage.message = Encoder.GetString(data, 0, data.Length);
                //Queue the message
                EnqueueTextMessage(inMessage);
            }
            break;

        case KLFCommon.ServerMessageID.PluginUpdate:
            if (data != null)
                SendClientInteropMessage(KLFCommon.ClientInteropMessageID.PluginUpdate, data);
            break;

        case KLFCommon.ServerMessageID.ServerSettings:
            lock (ServerSettingsLock)
            {
                if (data != null && data.Length >= KLFCommon.ServerSettingsLength && HandshakeComplete)
                {
                    UpdateInterval = KLFCommon.BytesToInt(data, 0);
                    ScreenshotInterval = KLFCommon.BytesToInt(data, 4);
                    lock (ClientDataLock)
                    {
                        int new_screenshot_height = KLFCommon.BytesToInt(data, 8);
                        if (ScreenshotConfiguration.MaxHeight != new_screenshot_height)
                        {
                            ScreenshotConfiguration.MaxHeight = new_screenshot_height;
                            LastClientDataChangeTime = ClientStopwatch.ElapsedMilliseconds;
                            EnqueueTextMessage("Screenshot Height has been set to " + ScreenshotConfiguration.MaxHeight);
                        }
                        if (InactiveShipsPerUpdate != data[12])
                        {
                            InactiveShipsPerUpdate = data[12];
                            LastClientDataChangeTime = ClientStopwatch.ElapsedMilliseconds;
                        }
                    }
                }
            }
            break;

        case KLFCommon.ServerMessageID.ScreenshotShare:
            if (data != null
            && data.Length > 0
            && data.Length < ScreenshotConfiguration.MaxNumBytes
            && WatchPlayerName.Length > 0)
            {
                //Cache the screenshot
                Screenshot screenshot = new Screenshot();
                screenshot.SetFromByteArray(data);
                CacheScreenshot(screenshot);
                //Send the screenshot to the client
                SendClientInteropMessage(KLFCommon.ClientInteropMessageID.ScreenshotReceive, data);
            }
            break;

        case KLFCommon.ServerMessageID.ConnectionEnd:
            if (data != null)
            {
                String message = Encoder.GetString(data, 0, data.Length);
                EndSession = true;
                //If the reason is not a timeout, connection end is intentional
                IntentionalConnectionEnd = message.ToLower() != "timeout";
                EnqueuePluginChatMessage("Server closed the connection: " + message, true);
            }

            break;

        case KLFCommon.ServerMessageID.UdpAcknowledge:
            lock (UdpTimestampLock)
            {
                LastUdpAckReceiveTime = ClientStopwatch.ElapsedMilliseconds;
            }
            break;

        case KLFCommon.ServerMessageID.CraftFile:
            if (data != null && data.Length > 4)
            {
                //Read craft name length
                byte craftType = data[0];
                int craftName_length = KLFCommon.BytesToInt(data, 1);
                if (craftName_length < data.Length - 5)
                {
                    //Read craft name
                    String craftName = Encoder.GetString(data, 5, craftName_length);
                    //Read craft bytes
                    byte[] craft_bytes = new byte[data.Length - craftName_length - 5];
                    Array.Copy(data, 5 + craftName_length, craft_bytes, 0, craft_bytes.Length);
                    //Write the craft to a file
                    String filename = GetCraftFilename(craftName, craftType);
                    if (filename != null)
                    {
                        try
                        {
                            File.WriteAllBytes(filename, craft_bytes);
                            EnqueueTextMessage("Received craft file: " + craftName);
                        }
                        catch
                        {
                            EnqueueTextMessage("Error saving received craft file: " + craftName);
                        }
                    }
                    else
                        EnqueueTextMessage("Unable to save received craft file.");
                }
            }
            break;

        case KLFCommon.ServerMessageID.PingReply:
            if (PingStopwatch.IsRunning)
            {
                EnqueueTextMessage("Ping Reply: " + PingStopwatch.ElapsedMilliseconds + "ms");
                PingStopwatch.Stop();
                PingStopwatch.Reset();
            }
            break;
        }
    }
Example #60
0
        internal static void TakeScreenShot(IWebDriver driver, string fileName)
        {
            Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();

            ss.SaveAsFile($"{fileName}-{DateTime.Now:yyyyMMddss}.png", ScreenshotImageFormat.Png);
        }