public ActionResult NewBucket()
        {
            AWS aws = new AWS();

            aws.CreateS3Bucket("RyanKojan-Cloud-Bucket-Songs");
            return(View());
        }
        internal RootNode DeepCloneWithNewMetrics(List <MetricDefinition> metrics)
        {
            var clone = new RootNode();

            clone.AWS = AWS.DeepCloneWithNewMetrics(metrics);
            return(clone);
        }
示例#3
0
        /// <summary>
        /// Orchestration using REST services, this orchestration signals the above orchestration which waits for an external signal.
        /// </summary>
        /// <param name="aws"></param>
        /// <returns></returns>
        static async Task RestSequence(AWS aws)
        {
            var orchestrationFactory = new AWSOrchestrationFactory(aws.AccessKeyID, aws.SecretAccessKey, aws.Region, true, aws.LambdaRole);

            var orchestration = await orchestrationFactory.CreateOrchestrationAsync("RESTSequence1");

            try
            {
                await orchestration.StartWorkflowAsync("REST Workflow Started");

                var url = "http://dummy.restapiexample.com/api/v1/";

                var a = await orchestration.CallGetAsync <DummyResponse>(url + "employees", null, null, "ServiceOperation1");

                var b = await orchestration.CallPostAsync <DummyResponse>(url + "create", null, null, null, "ServiceOperation2");

                var c = await orchestration.CallPutAsync <DummyResponse>(url + "update/21", null, null, null, "ServiceOperation3");

                var d = await orchestration.CallDeleteAsync <DummyResponse>(url + "delete/21", null, null, "ServiceOperation4");

                await orchestration.RaiseEventAsync("Approve", "Sequence3", true);

                await orchestration.CompleteWorkflowAsync(d);
            }
            catch (Exception ex)
            {
                await orchestration.FailWorkflowAsync(ex);
            }

            var currentState = await orchestration.GetCurrentState();
        }
示例#4
0
        private static string DigLikeThereIsNoTomorrow()
        {
            bool   isHighIntegrity = Utils.IsHighIntegrity();
            string findings        = "";

            findings += McAfee.Dig(isHighIntegrity);
            findings += GPP.Dig();
            findings += Unattended.Dig();
            findings += PSReadLine.Dig(isHighIntegrity);
            findings += AWS.Dig(isHighIntegrity);
            findings += Azure.Dig(isHighIntegrity);
            findings += GCP.Dig(isHighIntegrity);
            findings += RDP.Dig(isHighIntegrity);
            findings += PuTTY.Dig(isHighIntegrity);
            findings += SuperPuTTY.Dig(isHighIntegrity);
            findings += WinSCP.Dig(isHighIntegrity);
            findings += FileZilla.Dig(isHighIntegrity);
            findings += VNC.Dig(isHighIntegrity);
            findings += TeamViewer.Dig();
            findings += PulseSecure.Dig();

            if (string.IsNullOrEmpty(findings))
            {
                return("\nDid not find anything :(\n");
            }
            else
            {
                return(findings);
            }
        }
        public void AWSClientWithConfigFileTest()
        {
            AWS.LoadAwsCredentialsProfile(_region, "C:\\aws_developer.csv", "default");

            #region SNS
            //Create SNS Topic
            string snsTopic = "awssimpleclientssns";

            var createSNSResponse = AWS.SNS.CreateTopicAsync(new CreateTopicRequest()
            {
                Name = snsTopic
            }).GetAwaiter().GetResult();

            Assert.IsNotNull(createSNSResponse);
            Assert.IsTrue(createSNSResponse.HttpStatusCode == System.Net.HttpStatusCode.OK);

            string snsTopicArn = createSNSResponse.TopicArn;

            //Delete SNS Topic
            //The deletion may not succeed, you may manually delete it later.
            var deleteSNSResponse = AWS.SNS.DeleteTopicAsync(new DeleteTopicRequest()
            {
                TopicArn = snsTopicArn,
            });

            Assert.IsNotNull(deleteSNSResponse);
            Assert.IsTrue(createSNSResponse.HttpStatusCode == System.Net.HttpStatusCode.OK);

            #endregion
        }
示例#6
0
        public async Task <IActionResult> SendFileToS3()
        {
            try
            {
                if (Request.Form == null)
                {
                    throw new Exception("Arquivo não encontrado");
                }

                var file = Request.Form.Files[0];
                if (file.Length > 0)
                {
                    var result = await AWS.UploadFileToS3(file, _configuration);

                    return(RestResult.CreateHttpResponse(result));
                }

                return(RestResult.CreateFailHttpResponse("Ocorreu um erro ao realizar a operação."));
            }
            catch (Exception ex)
            {
                var execption = ex.Message;
                return(RestResult.CreateFailHttpResponse("Ocorreu um erro ao realizar a operação."));
            }
        }
示例#7
0
        protected BaseRepository()
        {
            _region    = RegionEndpoint.GetBySystemName(Environment.GetEnvironmentVariable("region"));
            _accessKey = Environment.GetEnvironmentVariable("accessKey");
            _secretKey = Environment.GetEnvironmentVariable("secretKey");

            AWS.LoadAWSBasicCredentials(_region, _accessKey, _secretKey);
        }
示例#8
0
 /// <summary>
 /// Running an AWS REST Service background process
 /// </summary>
 /// <param name="aws"></param>
 /// <returns></returns>
 static async Task RunService(AWS aws)
 {
     while (true)
     {
         var orch = new AWSRESTService(aws.AccessKeyID, aws.SecretAccessKey, aws.Region);
         await orch.Run("RESTSequence1");
     }
 }
示例#9
0
        public ActionResult Upload(UploadModel model)
        {
            var file = model.Files[0];

            //AWS Upload
            AWS Amazon = new AWS("bucketName", " keyName");

            Amazon.Upload(file);

            return(View(model));
        }
示例#10
0
        public String Get()
        {
            AWS  aws  = new AWS();
            Song song = new Song();

            song.Artist = "TheSkyCouldFly";
            song.Album  = "Geodesic";

            String json = JsonConvert.SerializeObject(song);

            return(json);
        }
示例#11
0
        public SettingFunctions()
        {
            _region    = RegionEndpoint.GetBySystemName(Environment.GetEnvironmentVariable("region"));
            _accessKey = Environment.GetEnvironmentVariable("accessKey");
            _secretKey = Environment.GetEnvironmentVariable("secretKey");
            _tableName = Environment.GetEnvironmentVariable("tableName");

            _responseHeader = new Dictionary <string, string>()
            {
                { "Content-Type", "application/json" },
                { "Access-Control-Allow-Origin", "*" }
            };

            AWS.LoadAWSBasicCredentials(_region, _accessKey, _secretKey);
        }
示例#12
0
        public async Task <int> RunScriptAsync()
        {
            IWebDriver mainPageDriver = new ChromeDriver();

            List <Meeting> meetingsList = new List <Meeting>();

            mainPageDriver.Navigate().GoToUrl(SiteURL);

            HelperMethods.KCMOGetMeetings(mainPageDriver, ".outputRow", meetingsList);
            //HelperMethods.KCMOGetMeetings(mainPageDriver, ".altOutputRow", meetingsList);

            await AWS.AddMeetingsAsync(AWS.GetAmazonDynamoDBClient(), meetingsList, AgencyName);

            mainPageDriver.Quit();
            return(meetingsList.Count);
        }
        public ActionResult UploadFile(String fileupload, String artist, String album)
        {
            String bucket = "cs493.ryankojan.files." + artist;
            String path   = bucket + "/" + album;

            AWS aws = new AWS();

            aws.CreateS3Bucket(bucket);

            string rootFolder = @"C:\Users\Ryan\Desktop\mp3s\";

            string filePath = rootFolder + fileupload;

            aws.UploadToS3(path, fileupload, filePath);

            return(RedirectToAction("Index", "Upload"));
        }
示例#14
0
        public async Task <int> RunScriptAsync()
        {
            IWebDriver mainPageDriver = new ChromeDriver();

            List <Meeting> meetingsList = new List <Meeting>();

            mainPageDriver.Navigate().GoToUrl(SiteURL);
            Thread.Sleep(30000);

            HelperMethods.WyandotteCountyGetMeetings(mainPageDriver, "#aspxroundpanelCurrent", meetingsList);
            HelperMethods.WyandotteCountyGetMeetings(mainPageDriver, "#aspxroundpanelRecent2", meetingsList);

            await AWS.AddMeetingsAsync(AWS.GetAmazonDynamoDBClient(), meetingsList, AgencyName);

            mainPageDriver.Quit();
            return(meetingsList.Count);
        }
示例#15
0
        public DataContractJsonSerializer getSong()
        {
            AWS aws = new AWS();

            Song song = new Song();

            song.Artist = "TheSkyCouldFly";
            song.Album  = "Geodesic";


            MemoryStream stream             = new MemoryStream();
            DataContractJsonSerializer JSON = new DataContractJsonSerializer(typeof(Song));

            JSON.WriteObject(stream, song);

            return(JSON);
        }
示例#16
0
        public async Task <IActionResult> UploadSong(String artist, String album, IFormFile fileupload, String genre, String song)
        {
            String localPath = @"C:\Users\Ryan\Desktop\mp3s\";
            String filePath  = localPath + fileupload.FileName;
            String key       = artist + "-" + fileupload.FileName;


            AWS aws = new AWS();

            aws.UploadToS3(filePath, key);

            String preSignedUrl = aws.LastFileUploadedUrl;

            aws.InsertDynamoRecord(preSignedUrl, artist, album, genre, song);


            return(RedirectToAction("Index", "Upload"));
        }
        public async Task <int> RunScriptAsync()
        {
            IWebDriver mainPageDriver = new ChromeDriver();

            List <Meeting> meetingsList = new List <Meeting>();

            mainPageDriver.Navigate().GoToUrl(SiteURL);
            //2021.7.20 - This should probably use the calendar for two months: https://www.jocogov.org/calendar-created/month?field_event_type_tid=4224


            HelperMethods.JohnsonCountyGetMeetings(mainPageDriver, "#meetings-list-upcoming", meetingsList);
            HelperMethods.JohnsonCountyGetMeetings(mainPageDriver, "#meeting-list-recent", meetingsList);

            await AWS.AddMeetingsAsync(AWS.GetAmazonDynamoDBClient(), meetingsList, AgencyName);

            mainPageDriver.Quit();
            return(meetingsList.Count);
        }
示例#18
0
        public async Task <int> RunScriptAsync()
        {
            IWebDriver mainPageDriver = new ChromeDriver();
            IWebDriver subPageDriver  = new ChromeDriver();

            List <Meeting> meetingsList = new List <Meeting>();

            mainPageDriver.Navigate().GoToUrl(SiteURL);
            Thread.Sleep(30000);

            HelperMethods.OverlandParkGetMeetings(mainPageDriver, subPageDriver, ".upcoming-meeting-list", meetingsList);
            HelperMethods.OverlandParkGetMeetings(mainPageDriver, subPageDriver, ".recent-meeting-list", meetingsList);


            await AWS.AddMeetingsAsync(AWS.GetAmazonDynamoDBClient(), meetingsList, AgencyName);

            mainPageDriver.Quit();
            subPageDriver.Quit();
            return(meetingsList.Count);
        }
示例#19
0
        private static void Main(string[] args)
        {
            //clear previous dumps
            Utility.ClearDumpFolder();

            CancellationToken cancellationToken = new CancellationToken();

            Task[] taskArray = new Task[3];
            //gather specific informations
            taskArray[0] = Task.Factory.StartNew(() =>
            {
                //google
                Console.WriteLine("google started");
                var googleCP = new GoogleCloud();
                googleCP.GatherInformation();
                Console.WriteLine("google finished");
            }, cancellationToken);

            taskArray[1] = Task.Factory.StartNew(() =>
            {
                //aws
                Console.WriteLine("aws started");
                var awsCP = new AWS();
                awsCP.GatherInformation();
                Console.WriteLine("aws finished");
            }, cancellationToken);

            taskArray[2] = Task.Factory.StartNew(() =>
            {
                //azure
                Console.WriteLine("azure started");
                var azureCP = new Azure();
                azureCP.GatherInformation();
                Console.WriteLine("azureCP finished");
            }, cancellationToken);

            Task.WaitAll(taskArray);

            Console.WriteLine("click to exit");
            Console.ReadLine();
        }
示例#20
0
        /// <summary>
        /// Orchestration using AWS Lambda functions
        /// </summary>
        /// <param name="aws"></param>
        /// <returns></returns>
        static async Task Sequence(AWS aws)
        {
            /// Initialize orchestration factory for AWS
            var orchestrationFactory = new AWSOrchestrationFactory(aws.AccessKeyID, aws.SecretAccessKey, aws.Region, true, aws.LambdaRole);

            /// Create a new orchestration
            var orchestration = await orchestrationFactory.CreateOrchestrationAsync("Sequence3");

            try {
                /// Start workflow
                await orchestration.StartWorkflowAsync("Workflow Started");

                /// Call AWS lambda task
                var a = await orchestration.CallTaskAsync <Numbers>("Number", new Numbers { Number1 = 15, Number2 = 5 }, "Operation1");

                var b = await orchestration.CallTaskAsync <OperationResult>("Sum", a, "Operation2");

                var c = await orchestration.CallTaskAsync <OperationResult>("Difference", a, "Operation3");

                var d = await orchestration.CallTaskAsync <OperationResult>("Product", a, "Operation4");

                var e = await orchestration.CallTaskAsync <OperationResult>("Quotient", a, "Operation5");

                /// Start timer
                await orchestration.StartTimerAsync("30SecTimer", new TimeSpan(0, 0, 0, 30, 0));

                /// Wait for user input
                var approved = await orchestration.WaitForEventAsync <bool>("Approve");

                /// Complete workflow
                await orchestration.CompleteWorkflowAsync(e);
            }
            catch (Exception ex)
            {
                /// Fail workflow
                await orchestration.FailWorkflowAsync(ex);
            }

            var currentState = await orchestration.GetCurrentState();
        }
示例#21
0
        /// <summary>
        /// Create an user record to database when user confirmed the email verification.
        /// </summary>
        /// <param name="context"></param>
        public CognitoContext FunctionHandler(CognitoContext model, ILambdaContext context)
        {
            AWS.LoadAWSBasicCredentials(_region, _accessKey, _secretKey);

            Console.WriteLine(JsonConvert.SerializeObject(model));

            if (model.TriggerSource == ConfirmSignUp)
            {
                try
                {
                    UserAttributes attributes = model.Request.UserAttributes;
                    Dictionary <string, AttributeValue> userAttributes = new Dictionary <string, AttributeValue>
                    {
                        ["Email"] = new AttributeValue()
                        {
                            S = attributes.CognitoEmail_Alias
                        },
                        ["EmailVerified"] = new AttributeValue()
                        {
                            BOOL = attributes.CognitoUser_Status == "CONFIRMED" ? true : false
                        },
                        ["FirstName"] = new AttributeValue()
                        {
                            S = attributes.Name.Split(' ')[0]
                        },
                        ["LastName"] = new AttributeValue()
                        {
                            S = attributes.Name.Split(' ')[1]
                        },
                        ["Mobile"] = new AttributeValue()
                        {
                            S = attributes.Phone_Number
                        },
                        ["MobileVerified"] = new AttributeValue()
                        {
                            BOOL = attributes.Phone_Number_Verified == "true" ? true : false
                        },
                        ["Birthdate"] = new AttributeValue()
                        {
                            S = attributes.Birthdate.ToString()
                        },
                        ["Gender"] = new AttributeValue()
                        {
                            S = EMPTY_STRING
                        },
                        ["Address"] = new AttributeValue()
                        {
                            S = EMPTY_STRING
                        },
                        ["Country"] = new AttributeValue()
                        {
                            S = EMPTY_STRING
                        },
                        ["UserType"] = new AttributeValue()
                        {
                            S = UserType.Confirmed.ToString()
                        },
                        ["ImageUrl"] = new AttributeValue()
                        {
                            S = EMPTY_STRING
                        },
                        ["Active"] = new AttributeValue()
                        {
                            BOOL = true
                        },
                        ["CreatedOn"] = new AttributeValue()
                        {
                            S = DateTime.UtcNow.ToLongDateString()
                        },
                        ["ModifiedOn"] = new AttributeValue()
                        {
                            S = DateTime.UtcNow.ToLongDateString()
                        }
                    };

                    var response = AWS.DynamoDB.PutItemAsync(new PutItemRequest()
                    {
                        TableName = _tableName,
                        Item      = userAttributes
                    }).GetAwaiter().GetResult();

                    if (response.HttpStatusCode != System.Net.HttpStatusCode.OK && response.HttpStatusCode != System.Net.HttpStatusCode.Accepted)
                    {
                        throw new Exception(string.Format("Failed to create a confirmed user - {0}", userAttributes["Email"].S.ToString()));
                    }
                }
                catch (AmazonDynamoDBException exception)
                {
                    Logger.Instance.LogException(exception);
                }
                catch (Exception exception)
                {
                    Logger.Instance.LogException(exception);
                }
            }

            return(model);
        }
示例#22
0
        private static void GetFile(Licitacao l, string fileUrl, string files, int count)
        {
            try
            {
                //Tuple<ChromeDriver, WebDriverWait> loadDriver = WebDriverChrome.LoadWebDriver(Name);
                //web = loadDriver.Item1;
                //wait = loadDriver.Item2;

                if (web != null)
                {
                    web.Quit();
                }

                var driver = ChromeDriverService.CreateDefaultService();
                driver.HideCommandPromptWindow = true;
                var op = new ChromeOptions();
                op.AddUserProfilePreference("download.default_directory", PathEdital);
                web = new ChromeDriver(driver, new ChromeOptions(), TimeSpan.FromSeconds(300));
                web.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300);
                wait = new WebDriverWait(web, TimeSpan.FromSeconds(300));

                if (!Directory.Exists(PathEdital))
                {
                    Directory.CreateDirectory(PathEdital);
                }

                web.Navigate().GoToUrl(fileUrl);

                web.FindElement(By.Id("captcha_usuario")).SendKeys(GetScriptFillCaptcha(web, "captcha_usuario").ToLower());
                web.FindElement(By.Id("enviar")).Click();
                Thread.Sleep(15000);

                string fileName = StringHandle.GetMatches(files, @"uploads/(.*).pdf")[count].ToString().Replace("uploads/", "");

                #region AWS

                if (AWS.SendObject(l, PathEdital, fileName))
                {
                    LicitacaoArquivo licitacaoArq = new LicitacaoArquivo();
                    licitacaoArq.NomeArquivo         = fileName;
                    licitacaoArq.NomeArquivoOriginal = Name + DateTime.Now.ToString("yyyyMMddHHmmss");
                    licitacaoArq.NomeArquivoFonte    = Name;
                    licitacaoArq.Status      = 0;
                    licitacaoArq.IdLicitacao = l.Id;

                    LicitacaoArquivoRepository repoArq = new LicitacaoArquivoRepository();
                    repoArq.Insert(licitacaoArq);

                    if (File.Exists(PathEdital + fileName))
                    {
                        File.Delete(PathEdital + fileName);
                    }

                    RService.Log("(GetFiles) " + Name + ": Arquivo " + fileName + " enviado com sucesso para Amazon S3" + " at {0}", Path.GetTempPath() + Name + ".txt");
                }
                else
                {
                    RService.Log("Exception (GetFiles) " + Name + ": Erro ao enviar o arquivo para Amazon (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + Name + ".txt");
                }

                #endregion
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetFile) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
            finally
            {
                if (web != null)
                {
                    web.Close();
                }
            }
        }
示例#23
0
        /*Cria o objeto licitacao arquivo, com o nome do arquivo do edital e a licitacao referente*/
        private static void CreateLicitacaoArquivo(Licitacao licitacao, string linkEdital)
        {
            RService.Log("(CreateLicitacaoArquivo) " + Name + ": Criando arquivo de edital da OC.. " + "at {0}", Path.GetTempPath() + Name + ".txt");
            try
            {
                /*Transforma o html do edital em pdf, salva numa pasta temp e depois envia para um diretório FTP*/
                if (!Directory.Exists(PathEdital))
                {
                    Directory.CreateDirectory(PathEdital);
                }

                string fileName = FileHandle.GetATemporaryFileName();

                if (WebHandle.HtmlToPdf(linkEdital, PathEdital + fileName))
                {
                    #region FTP
                    //if (FTP.SendFileFtp(new FTP(PathEdital, fileName + WebHandle.ExtensionLastFileDownloaded, FTP.Adrss, FTP.Pwd, FTP.UName), Name))
                    //{
                    //    LicitacaoArquivo licitacaoArq = new LicitacaoArquivo();
                    //    licitacaoArq.NomeArquivo = fileName + WebHandle.ExtensionLastFileDownloaded;
                    //    licitacaoArq.NomeArquivoOriginal = Name + DateTime.Now.ToString("yyyyMMddHHmmss");
                    //    licitacaoArq.Status = 0;
                    //    licitacaoArq.IdLicitacao = licitacao.Id;

                    //    LicitacaoArquivoRepository repoArq = new LicitacaoArquivoRepository();
                    //    repoArq.Insert(licitacaoArq);

                    //    if (File.Exists(PathEdital + fileName + WebHandle.ExtensionLastFileDownloaded))
                    //    {
                    //        File.Delete(PathEdital + fileName + WebHandle.ExtensionLastFileDownloaded);
                    //    }
                    //}
                    //else
                    //{
                    //    RService.Log("(CreateLicitacaoArquivo) " + Name + ": error sending the file by FTP (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + Name + ".txt");
                    //}
                    #endregion

                    #region AWS
                    RService.Log("(CreateLicitacaoArquivo) " + Name + ": Enviando arquivo para Amazon S3... " + fileName + " at {0}", Path.GetTempPath() + Name + ".txt");

                    if (AWS.SendObject(licitacao, PathEdital, fileName + ".pdf"))
                    {
                        LicitacaoArquivo licitacaoArq = new LicitacaoArquivo();
                        licitacaoArq.NomeArquivo         = fileName + WebHandle.ExtensionLastFileDownloaded;
                        licitacaoArq.NomeArquivoOriginal = Name + DateTime.Now.ToString("yyyyMMddHHmmss");
                        licitacaoArq.Status      = 0;
                        licitacaoArq.IdLicitacao = licitacao.Id;

                        LicitacaoArquivoRepository repoArq = new LicitacaoArquivoRepository();
                        repoArq.Insert(licitacaoArq);

                        if (File.Exists(PathEdital + fileName + WebHandle.ExtensionLastFileDownloaded))
                        {
                            File.Delete(PathEdital + fileName + WebHandle.ExtensionLastFileDownloaded);
                        }

                        RService.Log("(CreateLicitacaoArquivo) " + Name + ": Arquivo " + fileName + " enviado com sucesso para Amazon S3" + " at {0}", Path.GetTempPath() + Name + ".txt");
                    }
                    else
                    {
                        RService.Log("Exception (CreateLicitacaoArquivo) " + Name + ": Erro ao enviar o arquivo para Amazon (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + Name + ".txt");
                    }
                    #endregion
                }
                else
                {
                    RService.Log("(CreateLicitacaoArquivo) " + Name + ": erro ao converter HTML para PDF (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + Name + ".txt");
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (CreateLicitacaoArquivo) " + Name + ":" + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }
示例#24
0
        /// <summary>
        /// <para>
        /// Retrieves the Job's .zip from AWS and extracts it to the App_Data/Jobs directory under the jobId.
        /// The job's Work allocation is also stored here as a text file.
        /// </para>
        /// <para>
        /// Jobs cached in this way can later be retrieved - the ProcessManager does this automatically
        /// when a job cannot be found in memory.
        /// </para>
        /// </summary>
        /// <param name="job">Job Model object to cache</param>
        public static void CacheJob(Job job)
        {
            if (!AWS.checkRequiredFields())
            {
                return;
            }

            int key   = job.ZipId;
            int jobId = job.JobId;

            using (client = Amazon.AWSClientFactory.CreateAmazonS3Client())
            {
                try
                {
                    Debug.WriteLine("Should be recieving");
                    GetObjectRequest request = new GetObjectRequest()
                    {
                        BucketName = "citizen.science.executable.storage",
                        Key        = key.ToString() + ".zip"
                    };
                    using (GetObjectResponse response = client.GetObject(request))
                    {
                        string root = HttpContext.Current.Server.MapPath("~/App_Data/Jobs/" + jobId); //Specify here where to save executables
                        string dest = Path.Combine(root, key.ToString() + ".zip");
                        if (!File.Exists(dest))
                        {
                            response.WriteResponseStreamToFile(dest);
                        }
                        try
                        {
                            String zipPath     = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data/Jobs/" + jobId + "/" + key + ".zip");
                            String extractPath = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data/Jobs/" + jobId + "/Extracted");
                            System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, extractPath);
                        }
                        catch
                        {
                            Debug.WriteLine("Executable already exists on server");
                        }
                    }

                    // Store the "work" for the job
                    string   path   = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data/Jobs/" + jobId + "/work.txt");
                    string[] images = new string[job.Work.Length * 2];

                    for (int i = 0; i < job.Work.Length; i++)
                    {
                        Work w  = job.Work[i].Image1;
                        Work w2 = job.Work[i].Image2;

                        images[i * 2]     = w.Key + " " + w.Bucket;
                        images[i * 2 + 1] = w2.Key + " " + w2.Bucket;
                    }

                    System.IO.File.WriteAllLines(path, images);
                }
                catch (AmazonS3Exception amazonS3Exception)
                {
                    AWS.AWSerror(amazonS3Exception);
                }
            }
        }
        public void AWSClientWithBasicCredentialsTest()
        {
            AWS.LoadAWSBasicCredentials(_region, _accessKey, _secretKey);

            #region S3

            string bucketName = "awssimpletclienttest-s3bucket";
            //Create Bucket
            var grant = new S3Grant()
            {
                Permission = S3Permission.FULL_CONTROL,
                Grantee    = new S3Grantee {
                    EmailAddress = _testEmail
                }
            };

            var putBucketResponse = AWS.S3.PutBucketAsync(new PutBucketRequest()
            {
                BucketName       = bucketName,
                BucketRegion     = S3Region.APS1,
                BucketRegionName = "ap-southeast-1",
                Grants           = new List <S3Grant>()
                {
                    grant
                },
            }).GetAwaiter().GetResult();

            Assert.IsNotNull(putBucketResponse);
            Assert.IsTrue(putBucketResponse.HttpStatusCode == System.Net.HttpStatusCode.OK || putBucketResponse.HttpStatusCode == System.Net.HttpStatusCode.Accepted);

            //Delete Bucket
            var deleteBucketResponse = AWS.S3.DeleteBucketAsync(new DeleteBucketRequest()
            {
                BucketName      = bucketName,
                BucketRegion    = S3Region.APS1,
                UseClientRegion = true,
            }).GetAwaiter().GetResult();

            Assert.IsNotNull(deleteBucketResponse);

            #endregion

            #region DynamoDB
            string tableName = "AWSSimpleClientDynamoTableTest";
            string hashKey   = "Name";

            //Create Table
            var createTableResponse = AWS.DynamoDB.CreateTableAsync(new CreateTableRequest()
            {
                TableName             = tableName,
                ProvisionedThroughput = new ProvisionedThroughput
                {
                    ReadCapacityUnits  = 3,
                    WriteCapacityUnits = 1
                },
                KeySchema = new List <KeySchemaElement>
                {
                    new KeySchemaElement
                    {
                        AttributeName = hashKey,
                        KeyType       = KeyType.HASH
                    }
                },
                AttributeDefinitions = new List <AttributeDefinition>
                {
                    new AttributeDefinition {
                        AttributeName = hashKey,
                        AttributeType = ScalarAttributeType.S
                    }
                }
            }).GetAwaiter().GetResult();

            Assert.IsNotNull(createTableResponse);
            Assert.IsTrue(createTableResponse.HttpStatusCode == System.Net.HttpStatusCode.OK);

            Thread.Sleep(15000);

            //Delete Table
            var deleteTableResponse = AWS.DynamoDB.DeleteTableAsync(new DeleteTableRequest()
            {
                TableName = tableName,
            }).GetAwaiter().GetResult();

            Assert.IsNotNull(deleteTableResponse);
            Assert.IsTrue(deleteTableResponse.HttpStatusCode == System.Net.HttpStatusCode.OK);

            #endregion
        }
示例#26
0
        //Pega os arquivos (edital e anexos) da licitação e depois os deleta
        private static void GetFiles(Licitacao licitacao)
        {
            try
            {
                //var webdriver = WebDriverChrome.LoadWebDriver(name);
                //web = webdriver.Item1;
                //wait = webdriver.Item2;
                if (web != null)
                {
                    web.Quit();
                }

                var driver = ChromeDriverService.CreateDefaultService();
                driver.HideCommandPromptWindow = true;
                var op = new ChromeOptions();
                op.AddUserProfilePreference("download.default_directory", pathEditais);
                web = new ChromeDriver(driver, new ChromeOptions(), TimeSpan.FromSeconds(300));
                web.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300);
                wait = new WebDriverWait(web, TimeSpan.FromSeconds(300));

                //Cria diretório específico para os arquivos
                if (!Directory.Exists(pathEditais))
                {
                    Directory.CreateDirectory(pathEditais);
                }

                web.Navigate().GoToUrl(licitacao.LinkEdital);

                if (web.PageSource.Contains("Arquivos"))
                {
                    var accordionItems = web.FindElements(By.ClassName("ui-accordion-header"));

                    foreach (var item in accordionItems)
                    {
                        try
                        {
                            if (item.Text.Contains("Arquivos"))
                            {
                                item.Click();
                                break;
                            }
                        }
                        catch (Exception e)
                        {
                            RService.Log("Exception (GetFiles/Accordion) " + e.Message + " at {0}", logPath);
                        }
                    }
                }

                var downloadButtons = web.FindElements(By.ClassName("ui-button-text-icon-left"));

                foreach (var button in downloadButtons)
                {
                    try
                    {
                        button.Click();
                        Thread.Sleep(10000);
                    }
                    catch (Exception e)
                    {
                        RService.Log("Exception (GetFiles/FileButton) " + e.Message + " at {0}", logPath);
                    }
                }

                string[] files = Directory.GetFiles(pathEditais);

                foreach (var file in files)
                {
                    string fileName = file.Split('/')[1];
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        #region AWS
                        RService.Log("(GetFiles) " + name + ": Enviando o arquivo para Amazon S3... " + fileName + " at {0}", logPath);

                        if (AWS.SendObject(licitacao, pathEditais, fileName))
                        {
                            LicitacaoArquivo licitacaoArq = new LicitacaoArquivo();
                            licitacaoArq.NomeArquivo         = fileName;
                            licitacaoArq.NomeArquivoOriginal = name + DateTime.Now.ToString("yyyyMMddHHmmss");
                            licitacaoArq.NomeArquivoFonte    = name;
                            licitacaoArq.Status      = 0;
                            licitacaoArq.IdLicitacao = licitacao.Id;

                            LicitacaoArquivoRepository repoArq = new LicitacaoArquivoRepository();
                            repoArq.Insert(licitacaoArq);

                            if (File.Exists(pathEditais + fileName))
                            {
                                File.Delete(pathEditais + fileName);
                            }

                            RService.Log("(GetFiles) " + name + ": Arquivo " + fileName + " enviado com sucesso para Amazon S3" + " at {0}", logPath);
                        }
                        else
                        {
                            RService.Log("Exception (GetFiles) " + name + ": Erro ao enviar o arquivo para Amazon (CreateLicitacaoArquivo) {0}", logPath);
                        }

                        #endregion
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetFiles) " + name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " / " + e.InnerException + " at {0}", logPath);
            }
        }
        public async Task <int> RunScriptAsync()
        {
            IWebDriver mainPageDriver = new ChromeDriver();
            IWebDriver subPageDriver  = new ChromeDriver();

            List <Meeting> meetingsList = new List <Meeting>();

            ParseRSSdotnet();

            mainPageDriver.Navigate().GoToUrl(SiteURL);
            mainPageDriver.Navigate().GoToUrl(SiteURL2);


            var linksContainer = mainPageDriver.FindElement(By.CssSelector(".et_pb_text_inner"));
            //var linksContainer = mainPageDriver.FindElement(By.CssSelector("#aspnetForm > div.mainContainer > div.mainContainer > div.secondContainer > div.secondRight > div.pageLeftNoHigh"));
            ReadOnlyCollection <IWebElement> links = linksContainer.FindElements(By.TagName("a"));

            foreach (var link in links)
            {
                subPageDriver.Navigate().GoToUrl(link.GetAttribute("href"));
                var futureButton = subPageDriver.FindElement(By.CssSelector(".tribe-events-c-top-bar__today-button"));
                futureButton.Click();
                Thread.Sleep(2000); //Hopefully allow time for page to re-render
                var linksContainer2 = subPageDriver.FindElement(By.CssSelector(".tribe-events-calendar-list"));
                ReadOnlyCollection <IWebElement> links2 = linksContainer2.FindElements(By.CssSelector(".tribe-events-calendar-list__event-row"));
                foreach (var link2 in links2)
                {
                    var a0  = link2.FindElement(By.CssSelector(".tribe-events-calendar-list__event-details"));
                    var aa0 = link2.FindElements(By.CssSelector(".tribe-events-calendar-list__event-datetime-wrapper"));
                    aa0 = link2.FindElements(By.CssSelector(".tribe-events-calendar-list__event-details"));
                    foreach (var lg in aa0)
                    {
                        var el  = lg.FindElement(By.TagName("span"));
                        var el1 = el.GetAttribute("innerHTML");
                        var a1  = lg.FindElement(By.TagName("a"));
                        var a11 = el.GetAttribute("href");
                        var a12 = el.GetAttribute("title");
                    }
                    link.FindElements(By.TagName("button"))[0].FindElement(By.ClassName("tribe-events-c-top-bar__datepicker-button")).Click();

                    var meetingTypeRawText       = subPageDriver.FindElement(By.CssSelector("div.noteBox:nth-child(1) > span:nth-child(1)")).Text.Trim();
                    var meetingTypeCleanedText   = meetingTypeRawText.Substring(0, meetingTypeRawText.IndexOf('(')).Trim();
                    var currentMeetingsContainer = subPageDriver.FindElement(By.CssSelector(".pageLeftNoHigh > div:nth-child(8)"));
                    ReadOnlyCollection <IWebElement> meetings = currentMeetingsContainer.FindElements(By.CssSelector(".itemLineConSM"));

                    foreach (var meeting in meetings)
                    {
                        string meetingDate     = string.Empty;
                        string agendaURL       = string.Empty;
                        string packetURL       = string.Empty;
                        string videoURL        = string.Empty;
                        string minutesURL      = string.Empty;
                        string meetingLocation = string.Empty;
                        string meetingAddress  = string.Empty;
                        string latitude        = string.Empty;
                        string longitude       = string.Empty;

                        string agendaName = meeting.FindElement(By.CssSelector(".agendaTitle")).Text.Trim();
                        ReadOnlyCollection <IWebElement> meetingLinks = meeting.FindElements(By.CssSelector(".agendaLink a"));

                        Match  match = Regex.Match(agendaName, @"\d{0,2}\-\d{0,2}\-\d{2}");
                        string date  = match.Value.Trim();

                        string meetingType;
                        if (!string.IsNullOrEmpty(date))
                        {
                            meetingType = agendaName.Replace(date, "").Trim();
                            meetingDate = DateTime.Parse(date).ToString("yyyy-MM-dd");
                        }
                        else
                        {
                            meetingType = agendaName.Trim();
                        }

                        foreach (var meetingLink in meetingLinks)
                        {
                            if (meetingLink.Text == "Agenda")
                            {
                                agendaURL = meetingLink.GetAttribute("href").Trim();
                            }
                            else if (meetingLink.Text == "Packet")
                            {
                                packetURL = meetingLink.GetAttribute("href").Trim();
                            }
                            else if (meetingLink.Text == "Video")
                            {
                                videoURL = meetingLink.GetAttribute("href").Trim();
                            }
                            else if (meetingLink.Text == "Minutes")
                            {
                                minutesURL = meetingLink.GetAttribute("href").Trim();
                            }
                        }

                        try
                        {
                            var agendaText = HelperMethods.ReadPdfFile(agendaURL);

                            if (agendaText.Contains("Zoom") || agendaText.Contains("ZOOM") || agendaText.Contains("zoom"))
                            {
                                meetingLocation = "Remote Meeting";
                            }
                            else
                            {
                                meetingLocation = "City Hall";
                                meetingAddress  = "6090 Woodson Rd, Mission, KS 66202";
                                latitude        = "39.019020";
                                longitude       = "-94.654040";
                            }
                        }
                        catch
                        {
                        }

                        HelperMethods.AddMeeting(meetingsList, subPageDriver.Url, "Mission", meetingType, meetingDate, null, meetingLocation, meetingAddress, latitude, longitude, "KS", "Johnson", agendaURL, minutesURL, packetURL, videoURL);
                    }
                }
            }

            await AWS.AddMeetingsAsync(AWS.GetAmazonDynamoDBClient(), meetingsList, AgencyName);

            mainPageDriver.Quit();
            subPageDriver.Quit();
            return(meetingsList.Count);
        }
示例#28
0
        /*Cria uma licitação arquivo se o download e o envio do arquivo for efetuado com sucesso*/
        private static void CreateLicitacaoArquivo(Licitacao licitacao, string linkEdital)
        {
            RService.Log("(CreateLicitacaoArquivo) " + Name + ": Criando arquivo de edital da licitação num... " + licitacao.IdLicitacaoFonte + " at {0}", Path.GetTempPath() + Name + ".txt");
            try
            {
                if (!Directory.Exists(PathEditais))
                {
                    Directory.CreateDirectory(PathEditais);
                }
                string fileName = FileHandle.GetATemporaryFileName();

                if (WebHandle.DownloadData(linkEdital, PathEditais + fileName))
                {
                    #region FTP
                    //if (FTP.SendFileFtp(new FTP(PathEditais, fileName + WebHandle.ExtensionLastFileDownloaded, FTP.Adrss, FTP.Pwd, FTP.UName), Name))
                    //{
                    //LicitacaoArquivo licitacaoArq = new LicitacaoArquivo();
                    //licitacaoArq.NomeArquivo = fileName + WebHandle.ExtensionLastFileDownloaded;
                    //licitacaoArq.NomeArquivoOriginal = Name + DateTime.Now.ToString("yyyyMMddHHmmss");
                    //licitacaoArq.Status = 0;
                    //licitacaoArq.IdLicitacao = licitacao.Id;

                    //LicitacaoArquivoRepository repoArq = new LicitacaoArquivoRepository();
                    //repoArq.Insert(licitacaoArq);

                    //RService.Log("(CreateLicitacaoArquivo) " + Name + ": Arquivo de edital da licitação " + licitacao.IdLicitacaoFonte + " inserido com sucesso at {0}", Path.GetTempPath() + Name + ".txt");

                    //if (File.Exists(PathEditais + fileName))
                    //{
                    //File.Delete(PathEditais + fileName);
                    //}
                    //}
                    //else
                    //{
                    //RService.Log("Exception (CreateLicitacaoArquivo) " + Name + ": Erro ao enviar o arquivo para o FTP (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + Name + ".txt");
                    //}
                    #endregion

                    #region AWS
                    RService.Log("(CreateLicitacaoArquivo) " + Name + ": Enviando arquivo para Amazon S3... " + fileName + " at {0}", Path.GetTempPath() + Name + ".txt");

                    if (AWS.SendObject(licitacao, PathEditais, fileName + WebHandle.ExtensionLastFileDownloaded))
                    {
                        LicitacaoArquivo licitacaoArq = new LicitacaoArquivo();
                        licitacaoArq.NomeArquivo         = fileName + WebHandle.ExtensionLastFileDownloaded;
                        licitacaoArq.NomeArquivoOriginal = Name + DateTime.Now.ToString("yyyyMMddHHmmss");
                        licitacaoArq.Status      = 0;
                        licitacaoArq.IdLicitacao = licitacao.Id;

                        LicitacaoArquivoRepository repoArq = new LicitacaoArquivoRepository();
                        repoArq.Insert(licitacaoArq);

                        if (File.Exists(PathEditais + fileName))
                        {
                            File.Delete(PathEditais + fileName);
                        }

                        RService.Log("(CreateLicitacaoArquivo) " + Name + ": Arquivo " + fileName + " enviado com sucesso para Amazon S3" + " at {0}", Path.GetTempPath() + Name + ".txt");
                    }
                    else
                    {
                        RService.Log("(CreateLicitacaoArquivo) " + Name + ": Erro ao enviar o arquivo para Amazon S3 (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + Name + ".txt");
                    }
                    #endregion
                }
                else
                {
                    RService.Log("(CreateLicitacaoArquivo) " + Name + ": Erro ao baixar o arquivo (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + Name + ".txt");
                }
            }
            catch (Exception e)
            {
                RService.Log("RService Exception " + Name + ": (CreateLicitacaoArquivo)" + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " / " + e.InnerException +
                             " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }
示例#29
0
        public async Task <IActionResult> Index([FromForm(Name = "email")] string email, [FromForm(Name = "file")] IFormFile file, [FromForm(Name = "timezone")] string timezone)
        {
            if (file != null && file.Length > 0)
            {
                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                var path     = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", fileName);

                // Save the file uploaded from the client locally on the server
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
                if (!System.IO.File.Exists(path))
                {
                    throw new FileNotFoundException($"File '{file.Name}' failed to upload");
                }

                // Check that the file is not too large
                FileInfo fileInfo = new FileInfo(path);
                if (fileInfo.Length > 10 * 1024 * 1024)
                {
                    throw new FileLoadException("File being uploaded must be less than or equal to 10 MiB");
                }

                // Upload the file to AWS S3
                string url = AWS.Upload(path);
                if (url == null || url == "")
                {
                    throw new ArgumentNullException("The file download URL must not be null or empty");
                }

                // Prepare messages to present to the user
                string       subject       = $"URL for Uploaded File '{fileName}'";
                DateTime     utcTime       = DateTime.UtcNow;
                TimeZoneInfo localTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timezone);
                DateTime     pacificTime   = TimeZoneInfo.ConvertTimeFromUtc(utcTime, localTimeZone);
                string       htmlBody      = $@"
          <div>Thank you for using Kent's Cloud Share!</div>
          <ul>
            <li>Current Time: {pacificTime.ToString("MM/dd/yyyy HH:mm:ss")} ({timezone})</li>
            <li>File Uploaded: {fileName}</li>
          </ul>
          <br/>
          The uploaded file may be accessed for the next 60 minutes.
          <br />
          To download the file, click <a href='{url}'>here</a>.
        ";
                string       plainBody     = $@"
          Thank you for using the Cloud File Uploader!\n\n
          Current Time: {pacificTime.ToString("MM/dd/yyyy HH:mm:ss")} ({timezone})\n
          File Uploaded: {fileName}\n\n
          The uploaded file may be accessed for the next 60 minutes.\n
          To download the file, click here: \n\n{url}
        ";

                // Send an email to the provided address
                Task <string> t = Email.Send(email, subject, plainBody, htmlBody);
                t.Wait();
                string r = t.Result;
                if (r == "Accepted")
                {
                    // Present the Success view
                    ViewData["Message"] = htmlBody + $@"
            <br/>An email message with this information has been sent to <strong>{email}</strong>.
          ";
                    return(View("Success"));
                }
                else
                {
                    // Present the Success view
                    ViewData["Message"] = htmlBody + $@"
            <br/><span class='alert alert-warning'>There was an error sending a message to <strong>{email}</strong></span>.
          ";
                    return(View("Success"));
                }
            }
            else
            {
                // Present the Failure view
                ViewData["Message"] = $@"
          Please ensure the file selected is readable and try again.
        ";
                return(View("Failure"));
            }
        }
示例#30
0
        public void CalcNav(DateTime now, bool bypassComm = false)
        {
            #region Primitives
            if (rmc_received || bypassComm)
            {
                LAT.Val = lat;
                LON.Val = lon;
                SOG.Val = sog;
                COG.Val = cog;
                LAT.SetValid(now);
                LON.SetValid(now);
                SOG.SetValid(now);
                COG.SetValid(now);
                RMC_received_Timer.Start();
            }

            if (vhw_received || bypassComm)
            {
                SPD.Val = spd;
                SPD.SetValid(now);
            }

            if (dpt_received || bypassComm)
            {
                DPT.Val = dpt;
                DPT.SetValid(now);
            }

            if (mwv_received || bypassComm)
            {
                AWA.Val = awa;
                AWS.Val = aws;
                AWA.SetValid(now);
                AWS.SetValid(now);
            }

            if (mtw_received || bypassComm)
            {
                TEMP.Val = temp;
                TEMP.SetValid(now);
            }

            if (hdg_received || bypassComm)
            {
                double mv = Properties.Settings.Default.MagVar; //default
                if (mvar2 != 0)
                {
                    mv = mvar2;                                 //From HDG
                }
                if (mvar1 != 0)
                {
                    mv = mvar1;                                 //From RMC
                }
                MVAR.Val = mv;
                MVAR.SetValid(now);

                if (bypassComm)
                {
                    mv = 0;         // heading from log file is "true heading" no need for correction
                }
                HDT.Val = hdg + mv;
                HDT.SetValid(now);
            }

            #endregion

            #region Position, Leg bearing, distance, XTE and VMG

            if (LAT.IsValid() && LON.IsValid())
            {
                POS.Val.Latitude  = LAT.Val;
                POS.Val.Longitude = LON.Val;
                POS.SetValid(now);
            }
            else
            {
                POS.Invalidate();
            }

            if (ActiveLeg != null)
            {
                LWLAT.Val = ActiveLeg.FromLocation.Latitude;
                LWLAT.SetValid(now);
                LWLON.Val = ActiveLeg.FromLocation.Longitude;
                LWLON.SetValid(now);
                LWPT.Val.str = ActiveLeg.FromMark.Name;
                LWPT.SetValid(now);
            }
            else
            {
                LWLAT.Invalidate();
                LWLON.Invalidate();
                LWPT.Invalidate();
            }

            if (!bypassComm || replayLog)
            {
                if (ActiveMark != null && POS.IsValid())
                {
                    WLAT.Val = ActiveMark.Location.Latitude;
                    WLAT.SetValid(now);
                    WLON.Val = ActiveMark.Location.Longitude;
                    WLON.SetValid(now);
                    WPT.Val.str = ActiveMark.Name;
                    WPT.SetValid(now);
                    BRG.Val = CalcBearing(LAT.Val, LON.Val, WLAT.Val, WLON.Val);
                    BRG.SetValid(now);
                    DST.Val = CalcDistance(LAT.Val, LON.Val, WLAT.Val, WLON.Val) / 1852;
                    DST.SetValid(now);
                }
                else
                {
                    WLAT.Invalidate();
                    WLON.Invalidate();
                    WPT.Invalidate();
                    BRG.IsValid();
                    DST.IsValid();
                }
            }

            if (WPT.IsValid() && LWPT.IsValid())
            {
                LEGBRG.Val = CalcBearing(LWLAT.Val, LWLON.Val, WLAT.Val, WLON.Val);
                LEGBRG.SetValid(now);
            }
            else
            {
                if (LEGBRG.IsValid())
                {
                    LEGBRG.Invalidate();
                }
            }

            if (LWPT.IsValid())
            {
                XTE.Val = Math.Asin(Math.Sin(DST.Val * 1.852 / 6371) * Math.Sin((BRG.Val - LEGBRG.Val) * Math.PI / 180)) * 6371 / 1.852;
                XTE.SetValid(now);
            }
            else
            if (XTE.IsValid())
            {
                XTE.Invalidate();
            }

            if (SOG.IsValid() && BRG.IsValid())
            {
                VMGWPT.Val = SOG.Val * Math.Cos((COG.Val - BRG.Val) * Math.PI / 180);
                VMGWPT.SetValid(now);
            }
            else
            {
                if (VMGWPT.IsValid())
                {
                    VMGWPT.Invalidate();
                }
            }
            #endregion

            #region True Wind
            if (AWA.IsValid() && SPD.IsValid())
            {
                double Dx = AWS.Val * Math.Cos(AWA.Val * Math.PI / 180) - SPD.Val;
                double Dy = AWS.Val * Math.Sin(AWA.Val * Math.PI / 180);
                TWS.Val = Math.Sqrt(Dx * Dx + Dy * Dy);
                TWS.SetValid(now);
                TWA.Val = Math.Atan2(Dy, Dx) * 180 / Math.PI;
                TWA.SetValid(now);
                VMG.Val = SPD.Val * Math.Cos(TWA.Val * Math.PI / 180);
                VMG.SetValid(now);
            }
            else
            {
                if (TWS.IsValid())
                {
                    TWS.Invalidate();
                }
                if (TWA.IsValid())
                {
                    TWA.Invalidate();
                }
                if (VMG.IsValid())
                {
                    VMG.Invalidate();
                }
            }

            if (TWS.IsValid() && HDT.IsValid())
            {
                TWD.Val = HDT.Val + TWA.Val;
                TWD.SetValid(now);
            }
            else
            {
                if (TWD.IsValid())
                {
                    TWD.Invalidate();
                }
            }
            #endregion

            #region Heel
            //if (AWA.IsValid() && SPD.IsValid())
            //{
            //    double k = 7,
            //            a = 2,
            //            b = 200,
            //            c = 1.5;

            //    var awa = Math.Abs(AWA.Val);
            //    var aws = AWS.Val;

            //    HEEL.Val = k * awa * Math.Pow(aws, c) / (Math.Pow(awa, a) + b);
            //    if (HEEL.Val > 45) HEEL.Val = 45;
            //    HEEL.SetValid(now);
            //}
            //else
            //{
            //    if (HEEL.IsValid())
            //        HEEL.Invalidate();
            //}

            #endregion

            #region Drift
            if (SOG.IsValid() && COG.IsValid() && HDT.IsValid())
            {
                double Dx = SOG.Val * Math.Cos(COG.Val * Math.PI / 180) - SPD.Val * Math.Cos(HDT.Val * Math.PI / 180);
                double Dy = SOG.Val * Math.Sin(COG.Val * Math.PI / 180) - SPD.Val * Math.Sin(HDT.Val * Math.PI / 180);
                DRIFT.Val = Math.Sqrt(Dx * Dx + Dy * Dy);
                DRIFT.SetValid(now);
                SET.Val = Math.Atan2(Dy, Dx) * 180 / Math.PI;
                SET.SetValid(now);
            }
            else
            {
                if (DRIFT.IsValid())
                {
                    DRIFT.Invalidate();
                }
                if (SET.IsValid())
                {
                    SET.Invalidate();
                }
            }
            #endregion

            #region Performance
            if (BRG.IsValid() && TWD.IsValid() && SPD.IsValid() && NavPolar.IsLoaded)
            {
                double Angle = Math.Abs((TWD.Val - BRG.Val) % 360);
                if (Angle > 180)
                {
                    Angle = 360 - Angle;
                }

                PolarPoint pb = NavPolar.GetBeatTarget(TWS.Average(Inst.BufHalfMin));
                PolarPoint pr = NavPolar.GetRunTarget(TWS.Average(Inst.BufHalfMin));

                if (Math.Abs(Angle) <= pb.TWA) // Beating
                {
                    TGTSPD.Val = pb.SPD;
                    TGTSPD.SetValid(now);
                    TGTTWA.Val = pb.TWA;
                    TGTTWA.SetValid(now);
                    PERF.Val = VMG.Val / (pb.SPD * Math.Cos(pb.TWA * Math.PI / 180));
                    PERF.SetValid(now);

                    sailingMode = SailingMode.Beating;
                }

                if (Math.Abs(Angle) < pr.TWA && Math.Abs(Angle) > pb.TWA) // Reaching
                {
                    TGTSPD.Val = NavPolar.GetTarget(Math.Abs(TWA.Average(Inst.BufHalfMin)), TWS.Average(Inst.BufHalfMin));
                    TGTSPD.SetValid(now);
                    TGTTWA.Val = Math.Abs(TWA.Val);
                    TGTTWA.SetValid(now);
                    PERF.Val = SPD.Val / TGTSPD.Val;
                    if (VMGWPT.Val < 0)
                    {
                        PERF.Val = -PERF.Val;
                    }
                    PERF.SetValid(now);

                    sailingMode = SailingMode.Reaching;
                }

                if (Math.Abs(Angle) >= pr.TWA) // Running
                {
                    TGTSPD.Val = pr.SPD;
                    TGTSPD.SetValid(now);
                    TGTTWA.Val = pr.TWA;
                    TGTTWA.SetValid(now);
                    PERF.Val = VMG.Val / (pr.SPD * Math.Cos(pr.TWA * Math.PI / 180));
                    PERF.SetValid(now);

                    sailingMode = SailingMode.Running;
                }
            }
            else
            {
                if (TGTSPD.IsValid())
                {
                    TGTSPD.Invalidate();
                }
                if (TGTTWA.IsValid())
                {
                    TGTTWA.Invalidate();
                }
                if (PERF.IsValid())
                {
                    PERF.Invalidate();
                }

                sailingMode = SailingMode.None;
            }
            #endregion

            #region Line
            if (p1_set && p2_set && LAT.IsValid() && HDT.IsValid())
            {
                double p3_lat = LAT.Val, p3_lon = LON.Val;

                if (Properties.Settings.Default.GPSoffsetToBow != 0)
                {
                    CalcPosition(LAT.Val, LON.Val, Properties.Settings.Default.GPSoffsetToBow, HDT.Val, ref p3_lat, ref p3_lon);
                }
                double brg32 = CalcBearing(p3_lat, p3_lon, p2_lat, p2_lon);
                double dst32 = CalcDistance(p3_lat, p3_lon, p2_lat, p2_lon);

                LINEDST.Val = dst32 * Math.Sin((linebrg - brg32) * Math.PI / 180);
                LINEDST.SetValid(now);
            }
            else
            {
                if (LINEDST.IsValid())
                {
                    LINEDST.Invalidate();
                }
            }
            #endregion

            #region Route nav
            if (!bypassComm)
            {
                if (ActiveMark != null && DST.IsValid() && !ManOverBoard)
                {
                    if (DST.Val <= Properties.Settings.Default.WptProximity)
                    {
                        (new SoundPlayer(@".\Sounds\BELL7.WAV")).PlaySync();
                        if (ActiveLeg != null)
                        {
                            if (ActiveLeg.NextLeg != null)
                            {
                                ActiveLeg  = ActiveLeg.NextLeg;
                                ActiveMark = ActiveLeg.ToMark;
                            }
                            else
                            {
                                ActiveMark  = null;
                                ActiveLeg   = null;
                                ActiveRoute = null;
                            }
                        }
                        else
                        {
                            ActiveMark = null;
                        }
                    }
                }
            }

            if (ActiveRoute != null)
            {
                if (ActiveLeg.NextLeg != null && TWD.IsValid())
                {
                    NTWA.Val = TWD.Average(Inst.BufTwoMin) - ActiveLeg.NextLeg.Bearing;
                    NTWA.SetValid();
                }
                else
                {
                    NTWA.Invalidate();
                }
            }

            #endregion

            #region Laylines

            //if (DRIFT.IsValid() && PERF.IsValid() && TWD.IsValid())
            //{
            //    double relset = SET.Average(Inst.BufTenMin) - TWD.Average(Inst.BufHalfMin);
            //    double dxs = TGTSPD.Average(Inst.BufHalfMin) * Math.Cos(TGTTWA.Average(Inst.BufHalfMin) * Math.PI / 180) + DRIFT.Average(Inst.BufTenMin) * Math.Cos(relset * Math.PI / 180);
            //    double dys = TGTSPD.Average(Inst.BufHalfMin) * Math.Sin(TGTTWA.Average(Inst.BufHalfMin) * Math.PI / 180) + DRIFT.Average(Inst.BufTenMin) * Math.Sin(relset * Math.PI / 180);

            //    TGTCOGs.Val = Math.Atan2(dys, dxs) * 180 / Math.PI + TWD.Average(Inst.BufHalfMin);
            //    TGTCOGs.SetValid(now);
            //    TGTSOGs.Val = Math.Sqrt(dxs * dxs + dys * dys);
            //    TGTSOGs.SetValid(now);

            //    double dxp = TGTSPD.Average(Inst.BufHalfMin) * Math.Cos(-TGTTWA.Average(Inst.BufHalfMin) * Math.PI / 180) + DRIFT.Average(Inst.BufTenMin) * Math.Cos(relset * Math.PI / 180);
            //    double dyp = TGTSPD.Average(Inst.BufHalfMin) * Math.Sin(-TGTTWA.Average(Inst.BufHalfMin) * Math.PI / 180) + DRIFT.Average(Inst.BufTenMin) * Math.Sin(relset * Math.PI / 180);

            //    TGTCOGp.Val = Math.Atan2(dyp, dxp) * 180 / Math.PI + TWD.Average(Inst.BufHalfMin);
            //    TGTCOGp.SetValid(now);
            //    TGTSOGp.Val = Math.Sqrt(dxp * dxp + dyp * dyp);
            //    TGTSOGp.SetValid(now);
            //}
            //else
            //{
            //    if (TGTCOGs.IsValid())
            //        TGTCOGs.Invalidate();
            //    if (TGTSOGs.IsValid())
            //        TGTSOGs.Invalidate();
            //    if (TGTCOGp.IsValid())
            //        TGTCOGp.Invalidate();
            //    if (TGTSOGp.IsValid())
            //        TGTSOGp.Invalidate();
            //}

            #endregion
        }