public override void ExecuteOption(OptionReport report)
        {
            string urlLoginName = _databaseExportContactToMailrelay.urlLoginName;

            Guid?crmListId = _databaseExportContactToMailrelay.listId;

            DatabaseUrlLogin      login = DatabaseUrlLogin.GetUrlLogin(Connection, urlLoginName);
            DynamicsCrmConnection dynamicsCrmConnection = DynamicsCrmConnection.GetConnection(login.Url, login.Username, login.Password);

            PagingInformation pagingInformation = new PagingInformation();

            while (pagingInformation.FirstRun || pagingInformation.MoreRecords)
            {
                MarketingList marketingList = MarketingList.GetListForMailrelayUpdate(dynamicsCrmConnection, pagingInformation, crmListId);

                if (marketingList != null)
                {
                    UpdateReport <Guid> result = ExportMailrelayContactFromList(dynamicsCrmConnection, marketingList);
                    Log.Write(Connection, result.AsLogText($"ExportContactToMailrelay {marketingList.new_mailrelaygroupid.Value}"), typeof(ExportContactToMailrelay), DataLayer.MongoData.Config.LogLevelEnum.OptionReport);
                }
            }

            report.Success = true;

            return;
        }
Esempio n. 2
0
        private UpdateReport <int> UpdateMailrelayGroupFromList(DynamicsCrmConnection dynamicsCrmConnection, MarketingList marketingList)
        {
            int?id = marketingList.new_mailrelaygroupid;

            if (id.HasValue == false)
            {
                id = Subscriber.CreateGroup(_mailrelayConnection, $"crm_{marketingList.listname}", "crm kontrolleret gruppe");

                marketingList.new_mailrelaygroupid = id;

                marketingList.UpdateMailrelaygroupid(dynamicsCrmConnection);
            }

            bool needsUpdate = marketingList.RecalculateMarketingListCheck();

            if (needsUpdate == false)
            {
                return(new UpdateReport <int>());
            }

            UpdateReport <int> report = AddOrRemoveMembersFromMailrelayGroup(dynamicsCrmConnection, marketingList, id.Value);

            marketingList.UpdateMailrelaycheck(dynamicsCrmConnection);

            return(report);
        }
Esempio n. 3
0
        private UpdateReport <int> RemoveFromMailrelayGroup(UpdateReport <int> report, List <getSubscribersReply> subscribersToRemoveFromMailrelay, Subscriber subscriber, int groupInCrm)
        {
            foreach (getSubscribersReply reply in subscribersToRemoveFromMailrelay)
            {
                reply.groups.RemoveAll(groupString => groupString == groupInCrm.ToString());

                if (reply.groups.Any() == false)
                {
                    reply.groups.Add("1");
                }

                MailrelayBoolReply updateReply = subscriber.UpdateFromReply(reply);

                if (updateReply.status == 0)
                {
                    report.CollectUpdate(UpdateResultEnum.Failed, int.Parse(reply.id));
                }
                else
                {
                    report.CollectUpdate(UpdateResultEnum.Updated, int.Parse(reply.id));
                }
            }

            return(report);
        }
Esempio n. 4
0
 private void btnDownloadUpdate_Click(object sender, RoutedEventArgs e)
 {
     updateReport = threatController.AutomationUpdate();
     InitializeThreadList(threatController.GetAllShortThreats());
     btnUpdateReport.IsEnabled = true;
     new InfoWindow().Show();
 }
Esempio n. 5
0
        private UpdateReport <int> AddOrRemoveMembersFromMailrelayGroup(DynamicsCrmConnection dynamicsCrmConnection, MarketingList marketingList, int groupId)
        {
            List <KeyValueEntity <Guid, int?> > crmIdsAndSubscriberIds = marketingList.CrmIdsAndSubscriberIds;

            List <getSubscribersReply> subscribersToRemoveFromMailrelay = new List <getSubscribersReply>();

            Subscriber subscriber = new Subscriber(_mailrelayConnection);

            getSubscribers getSubscribersFunction = new getSubscribers()
            {
                groups = new List <int>()
                {
                    groupId
                },
            };

            IEnumerable <getSubscribersReply> subscribersInMailrelay = subscriber.GetMailrelaySubscribers(getSubscribersFunction, 100);

            foreach (getSubscribersReply currentInMailrelay in subscribersInMailrelay)
            {
                int removed = crmIdsAndSubscriberIds.RemoveAll(idInCrm => currentInMailrelay.id == idInCrm.value.ToString());

                if (removed == 0)
                {
                    subscribersToRemoveFromMailrelay.Add(currentInMailrelay);
                }
            }

            UpdateReport <int> report = new UpdateReport <int>();

            RemoveFromMailrelayGroup(report, subscribersToRemoveFromMailrelay, subscriber, groupId);
            AddToMailrelayGroup(dynamicsCrmConnection, report, subscriber, crmIdsAndSubscriberIds, groupId);

            return(report);
        }
        public override void ExecuteOption(OptionReport report)
        {
            string urlLoginName = _databaseUpdateMailrelayFromContact.urlLoginName;
            int    pageSize     = _databaseUpdateMailrelayFromContact.pageSize;
            Guid?  contactId    = _databaseUpdateMailrelayFromContact.contactId;

            DatabaseUrlLogin      login = DatabaseUrlLogin.GetUrlLogin(Connection, urlLoginName);
            DynamicsCrmConnection dynamicsCrmConnection = DynamicsCrmConnection.GetConnection(login.Url, login.Username, login.Password);

            PagingInformation pagingInformation = new PagingInformation();

            List <MailrelayInformation> mailrelayInformations = new List <MailrelayInformation>();

            UpdateReport <int> intReport = new UpdateReport <int>();

            while (pagingInformation.FirstRun || pagingInformation.MoreRecords)
            {
                mailrelayInformations = MailrelayInformation.GetMailrelayFromContact(dynamicsCrmConnection, Config.GetResourcePath, pagingInformation, pageSize, contactId);
                mailrelayInformations.ForEach(information => UpdateIfNeeded(dynamicsCrmConnection, information, intReport));
            }

            Log.Write(Connection, intReport.AsLogText("UpdateMailrelayFromContact"), typeof(UpdateMailrelayFromContact), DataLayer.MongoData.Config.LogLevelEnum.OptionReport);

            report.Success = true;
            return;
        }
Esempio n. 7
0
        public void sendUpdateReport(oadrReportType report, oadrReportRequestType reportRequest)
        {
            UpdateReport request = new UpdateReport();

            string requestBody = request.createUpdateReport("venID", "requestID", report, reportRequest.reportRequestID);

            Assert.IsTrue(request.request.oadrReport[0].intervals[0].streamPayloadBase.Length > 0);

            Console.Out.WriteLine(reportRequest.reportSpecifier.reportSpecifierID);
            Console.Out.WriteLine(requestBody);
            Console.Out.WriteLine("");
        }
        public UpdateReportWindow(UpdateReport updateReport)
        {
            InitializeComponent();
            var statusAsText = updateReport.IsSuccessed ? "Успешно." : "Не успешно.";

            tbStatus.Text += $" {statusAsText}";
            if (!updateReport.IsSuccessed)
            {
                tbErrorMessage.Text = $"Ошибка в процессе обновления. {updateReport.ErrorMessage}";
            }
            else
            {
                tbCountOfChanges.Text = $"Количество изменений: {updateReport.Logs.Count}";
                DataContext           = updateReport.Logs;
            }
        }
Esempio n. 10
0
        public IApiResult Update(UpdateReport operation)
        {
            var result = operation.Execute().Result;

            if (result is ValidationsOutput)
            {
                return(new ApiResult <List <ValidationItem> >()
                {
                    Data = ((ValidationsOutput)result).Errors
                });
            }
            else
            {
                return(new ApiResult <object>()
                {
                    Status = ApiResult <object> .ApiStatus.Success
                });
            }
        }
        public IActionResult Edit([FromBody] UpdateReport model, int id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var record = _reportsRepository.GetById(id);

            if (record == null)
            {
                return(NotFound());
            }

            record.Mark    = model.Mark;
            record.Comment = model.Comment;

            _reportsRepository.Update(record);

            return(Ok());
        }
Esempio n. 12
0
        public void R1_3010_TH_VTN_1()
        {
            VEN2b ven = new VEN2b(new HttpWebRequestWrapper(false, System.Net.SecurityProtocolType.Tls12), TestProperties.vtnURL, TestProperties.venName, "", TestProperties.venPassword);

            QueryRegistration queryRegistration = ven.queryRegistration();

            OadrPoll poll = ven.poll();

            poll.responseTypeIs(typeof(oadrCreateReportType));

            oadrCreateReportType createReport = poll.getCreateReportResponse();

            Console.Out.WriteLine(poll.responseBody);

            ReportDescription reportDescription = new ReportDescription();

            reportDescription.addReport(createReport.oadrReportRequest[0].reportSpecifier.reportSpecifierID, ReportName.TELEMETRY_STATUS, 0, DurationModifier.MINUTES);

            DateTime dtstart = DateTime.UtcNow;

            reportDescription.addIntervalResourceStatus(createReport.oadrReportRequest[0].reportSpecifier.reportSpecifierID, dtstart,
                                                        0, DurationModifier.SECONDS, "rid", 1, (float)1.0, DataQuality.qualityGoodNonSpecific, true, false, (float)1.0, (float)1.0, (float)1.0, (float)1.0,
                                                        (float)1.0, (float)1.0, (float)1.0, (float)1.0, (float)1.0, (float)1.0, (float)1.0, (float)1.0, (float)1.0, (float)1.0,
                                                        (float)1.0, (float)1.0);

            CreatedReport createdReport = ven.createdReport(createReport.requestID, 200, "OK");

            Assert.IsNotNull(createdReport.response);

            List <string> reportSpecifierIDs = new List <string>();

            reportSpecifierIDs.Add(createReport.oadrReportRequest[0].reportSpecifier.reportSpecifierID);

            UpdateReport updateReport = ven.updateReport(createReport.requestID, reportDescription, reportSpecifierIDs, dtstart);

            Assert.IsNotNull(updateReport.response);
        }
        private UpdateReport <Guid> ExportMailrelayContactFromList(DynamicsCrmConnection dynamicsCrmConnection, MarketingList marketingList)
        {
            if (marketingList.new_mailrelaygroupid.HasValue == false)
            {
                marketingList.new_mailrelaygroupid = Subscriber.CreateGroup(_mailrelayConnection, $"crm_{marketingList.listname}", "crm kontrolleret gruppe");

                marketingList.UpdateMailrelaygroupid(dynamicsCrmConnection);
            }

            IEnumerable <Guid> contactIdsToUpdate = marketingList.ContentIdsForNonMailrelaySubscribers;

            UpdateReport <Guid> updateReport = new UpdateReport <Guid>();

            foreach (Guid contactId in contactIdsToUpdate)
            {
                MailrelayInformation mailrelayInformation = MailrelayInformation.GetInformationNotInMailrelayFromContact(dynamicsCrmConnection, Config.GetResourcePath, contactId);

                UpdateResultEnum result = AddToMailrelay(dynamicsCrmConnection, mailrelayInformation, marketingList.new_mailrelaygroupid.Value);

                updateReport.CollectUpdate(result, contactId);
            }

            return(null);
        }
Esempio n. 14
0
        /**********************************************************/

        public void processUpdateReport(UpdateReport updateReport)
        {
            updateError(updateReport);
            ucLog1.addOadrMessage(updateReport, chkAutoScroll.Checked);
        }
        /// <summary>
        ///     Store a <see cref="UpdateReport" /> in a <see cref="ZipFile" />.
        /// </summary>
        /// <param name="zip"><see cref="ZipFile" /> to write to.</param>
        /// <param name="report"><see cref="UpdateReport" /> to store.</param>
        private static void StoreReport(ZipFile zip, UpdateReport report)
        {
            var textTarget = string.Format(UpdateReportTextFile, report.PreviousVersion, report.UpdateVersion);
            zip.UpdateEntry(textTarget, string.Join(Environment.NewLine, report.Changes.Select(_ => _.ToString())),
                ZipEncoding);

            var yamlTarget = string.Format(UpdateReportYamlFile, report.PreviousVersion, report.UpdateVersion);
            var serializer = new Serializer();
            byte[] yamlBuffer;
            using (var ms = new MemoryStream()) {
                using (TextWriter writer = new StreamWriter(ms, ZipEncoding)) {
                    serializer.Serialize(writer, report);
                    writer.Flush();
                    yamlBuffer = ms.ToArray();
                }
            }
            zip.UpdateEntry(yamlTarget, yamlBuffer);

            var binTarget = string.Format(UpdateReportBinFile, report.PreviousVersion, report.UpdateVersion);
            var formatter = new BinaryFormatter();
            byte[] binBuffer;

            using (var ms = new MemoryStream()) {
                formatter.Serialize(ms, report);
                binBuffer = ms.ToArray();
            }

            zip.UpdateEntry(binTarget, binBuffer);
        }
        /// <summary>
        ///     Update to the current version.
        /// </summary>
        /// <param name="detectDataChanges">Boolean indicating whether the update should also look for changes in data.</param>
        /// <param name="progress">Optional object to which update progress is reported.</param>
        /// <returns>Returns the <see cref="UpdateReport" /> containing all changes.</returns>
        /// <exception cref="InvalidOperationException">Definition is up-to-date.</exception>
        public UpdateReport Update(bool detectDataChanges, IProgress<UpdateProgress> progress = null)
        {
            if (DefinitionVersion == GameVersion)
                throw new InvalidOperationException();

            var previousVersion = DefinitionVersion;

            var exdPackId = new PackIdentifier("exd", PackIdentifier.DefaultExpansion, 0);
            var exdPack = Packs.GetPack(exdPackId);
            var exdOldKeepInMemory = exdPack.KeepInMemory;
            exdPack.KeepInMemory = true;

            string tempPath = null;
            UpdateReport report;
            try {
                using (var zip = new ZipFile(StateFile.FullName, ZipEncoding)) {
                    tempPath = ExtractPacks(zip, previousVersion);
                    var previousPack = new PackCollection(Path.Combine(tempPath, previousVersion));
                    previousPack.GetPack(exdPackId).KeepInMemory = true;
                    var previousDefinition = ReadDefinition(zip);

                    var updater = new RelationUpdater(previousPack, previousDefinition, Packs, GameVersion, progress);

                    var changes = updater.Update(detectDataChanges);
                    report = new UpdateReport(previousVersion, GameVersion, changes);

                    var definition = updater.Updated;

                    StorePacks(zip);
                    StoreDefinition(zip, definition, DefinitionFile);
                    StoreDefinition(zip, definition, string.Format("{0}/{1}", definition.Version, DefinitionFile));
                    StoreReport(zip, report);
                    zip.Save();

                    GameData.Definition = definition;
                    GameData.Definition.Compile();
                }
            } finally {
                if (exdPack != null)
                    exdPack.KeepInMemory = exdOldKeepInMemory;
                if (tempPath != null) {
                    try {
                        Directory.Delete(tempPath, true);
                    } catch {
                        Console.Error.WriteLine("Failed to delete temporary directory {0}.", tempPath);
                    }
                }
            }
            return report;
        }
Esempio n. 17
0
        public UpdateReport AutomationUpdate()
        {
            //TODO: доделать успешность обновления
            var report = new UpdateReport()
            {
                IsSuccessed = true
            };

            using (var client = new WebClient())
            {
                try
                {
                    client.DownloadFile(sourceFileUrl, sourceFileName);
                }
                catch (ArgumentNullException)
                {
                    report.IsSuccessed  = false;
                    report.ErrorMessage = "Отсутствует Url адреса для скачивания файла.";
                    return(report);
                }
                catch (WebException)
                {
                    report.IsSuccessed  = false;
                    report.ErrorMessage = "Возможные проблемы: отсутствие интернета, некорректный Url адрес для скачивания файла, файл для сохранения уже существует и используется другой программой.";
                    return(report);
                }
                catch (Exception ex)
                {
                    report.IsSuccessed  = false;
                    report.ErrorMessage = ex.Message;
                    return(report);
                }
            }

            var oldThreatsAsEnumerable = threatRepository.GetAllThreats();

            List <Threat> oldThreats = oldThreatsAsEnumerable != null? new List <Threat>(oldThreatsAsEnumerable):null;

            var newThreats = new List <Threat>();

            ExcelPackage package;

            try
            {
                package = new ExcelPackage(new FileInfo(sourceFileName));
            }
            catch (Exception)
            {
                report.IsSuccessed  = false;
                report.ErrorMessage = "Загруженный файл повреждён или имеет неверный формат.";
                return(report);
            }
            var sheet = package.Workbook.Worksheets.FirstOrDefault();
            int row   = 3;

            while (true)
            {
                var cells = sheet.Cells;

                if (cells[row, 1].Value == null)
                {
                    break;
                }

                Threat threat;

                try
                {
                    var id                       = int.Parse(cells[row, 1].Value.ToString());
                    var name                     = cells[row, 2].Value.ToString();
                    var description              = cells[row, 3].Value.ToString();
                    var source                   = cells[row, 4].Value.ToString();
                    var influenceObject          = cells[row, 5].Value.ToString();
                    var confidentialityViolation = int.Parse(cells[row, 6].Value.ToString()) == 1;
                    var integrityViolation       = int.Parse(cells[row, 7].Value.ToString()) == 1;
                    var accessibilityViolation   = int.Parse(cells[row, 8].Value.ToString()) == 1;

                    threat = new Threat()
                    {
                        Id                       = id,
                        Name                     = name,
                        Description              = description,
                        Source                   = source,
                        InfluenceObject          = influenceObject,
                        ConfidentialityViolation = confidentialityViolation,
                        IntegrityViolation       = integrityViolation,
                        AccessibilityViolation   = accessibilityViolation
                    };
                }
                catch (Exception)
                {
                    report.IsSuccessed  = false;
                    report.ErrorMessage = "Загруженный файл повреждён или имеет неверный формат.";
                    return(report);
                }

                if (oldThreats != null && row - 3 < oldThreats.Count)
                {
                    var index = row - 3;
                    if (index < oldThreats.Count && !oldThreats[index].Equals(threat))
                    {
                        report.Logs.Add(new ModifiedThreatLog()
                        {
                            NewThreat = threat.ToString(), OldThreat = oldThreats[index].ToString(), ThreatId = threat.Id
                        });
                    }
                }
                else
                {
                    report.Logs.Add(new ModifiedThreatLog()
                    {
                        NewThreat = threat.ToString(), OldThreat = null, ThreatId = threat.Id
                    });
                }

                newThreats.Add(threat);

                row++;
            }

            if (oldThreats != null && row - 3 < oldThreats.Count)
            {
                for (int i = row - 3; i < oldThreats.Count; i++)
                {
                    report.Logs.Add(new ModifiedThreatLog()
                    {
                        NewThreat = null, OldThreat = oldThreats[i].ToString(), ThreatId = oldThreats[i].Id
                    });
                }
            }

            SaveThreats(newThreats);

            return(report);
        }
Esempio n. 18
0
 public async Task <IActionResult> Update(Guid reportId, [FromBody] UpdateReport updateReport)
 {
     updateReport.UserId = UserId;
     return(new OkObjectResult(await mediator.Send(updateReport)));
 }
        private void UpdateIfNeeded(DynamicsCrmConnection dynamicsCrmConnection, MailrelayInformation information, UpdateReport <int> report)
        {
            bool needsUpdate = information.RecalculateContactCheck();
            int  id          = information.new_mailrelaysubscriberid.Value;

            if (needsUpdate == false)
            {
                report.CollectUpdate(UpdateResultEnum.AlreadyUpToDate, id);
                return;
            }

            information.UpdateContactMailrelaycheck(dynamicsCrmConnection);

            Subscriber       subscriber = new Subscriber(_mailrelayConnection);
            UpdateResultEnum result     = subscriber.UpdateIfNeeded(id, information.fullname, information.emailaddress1, information.GetCustomFields());

            report.CollectUpdate(result, id);
        }
Esempio n. 20
0
        public void R1_3020_TH_VTN_1()
        {
            VEN2b ven = new VEN2b(new HttpWebRequestWrapper(false, System.Net.SecurityProtocolType.Tls12), TestProperties.vtnURL, TestProperties.venName, TestProperties.venID, TestProperties.venPassword);

            OadrPoll poll = ven.poll();

            poll.responseTypeIs(typeof(oadrCreateReportType));

            oadrCreateReportType createReport = poll.getCreateReportResponse();

            Console.Out.WriteLine(poll.responseBody);

            ReportDescription reportDescription = new ReportDescription();

            reportDescription.addReport(createReport.oadrReportRequest[0].reportSpecifier.reportSpecifierID, ReportName.TELEMETRY_STATUS, 0, DurationModifier.MINUTES);


            CreatedReport createdReport = ven.createdReport(createReport.requestID, 200, "OK");

            Assert.IsNotNull(createdReport.response);

            List <string> reportSpecifierIDs = new List <string>();

            int sleepTime = (int)(createReport.oadrReportRequest[0].reportSpecifier.reportInterval.properties.dtstart.datetime - DateTime.UtcNow).TotalSeconds;

            if (sleepTime > 0)
            {
                System.Threading.Thread.Sleep(sleepTime * 1000);
            }

            reportSpecifierIDs.Add(createReport.oadrReportRequest[0].reportSpecifier.reportSpecifierID);

            DateTime endTime = createReport.oadrReportRequest[0].reportSpecifier.reportInterval.properties.dtstart.datetime +
                               System.Xml.XmlConvert.ToTimeSpan(createReport.oadrReportRequest[0].reportSpecifier.reportInterval.properties.duration.duration);

            // convert ISO8601 duration to timespan
            // http://stackoverflow.com/questions/62804/how-to-convert-iso-8601-duration-to-timespan-in-vb-net
            // http://msdn.microsoft.com/en-us/library/system.xml.xmlconvert.totimespan.aspx
            int sleepDelay = (int)System.Xml.XmlConvert.ToTimeSpan(createReport.oadrReportRequest[0].reportSpecifier.reportBackDuration.duration).TotalSeconds;

            // the test should continue until the end time has passed, but the test set exits after it receives 2 updates
            // while (DateTime.Now < endTime)
            for (int count = 0; count < 2; count++)
            {
                DateTime dtstart = DateTime.UtcNow;

                reportDescription.addIntervalResourceStatus(createReport.oadrReportRequest[0].reportSpecifier.reportSpecifierID, dtstart,
                                                            0, DurationModifier.SECONDS, "rid", 1, (float)1.0, DataQuality.qualityGoodNonSpecific, true, false, (float)1.0, (float)1.0, (float)1.0, (float)1.0,
                                                            (float)1.0, (float)1.0, (float)1.0, (float)1.0, (float)1.0, (float)1.0, (float)1.0, (float)1.0, (float)1.0, (float)1.0,
                                                            (float)1.0, (float)1.0);

                UpdateReport updateReport = ven.updateReport(createReport.requestID, reportDescription, reportSpecifierIDs, dtstart);

                Assert.IsNotNull(updateReport.response);

                if (count == 0)
                {
                    System.Threading.Thread.Sleep(sleepDelay * 1000);
                }
            }
        }
Esempio n. 21
0
        private void AddToMailrelayGroup(DynamicsCrmConnection dynamicsCrmConnection, UpdateReport <int> report, Subscriber subscriber, List <KeyValueEntity <Guid, int?> > crmIdsAndSubscriberIds, int groupInCrm)
        {
            foreach (KeyValueEntity <Guid, int?> idPair in crmIdsAndSubscriberIds)
            {
                MailrelayInformation mailrelayInformation = MailrelayInformation.GetMailrelayFromContact(dynamicsCrmConnection, Config.GetResourcePath, new PagingInformation(), 1, idPair.key).Single();

                UpdateResultEnum result = subscriber.UpdateIfNeeded(idPair.value.Value, mailrelayInformation.fullname, mailrelayInformation.emailaddress1, mailrelayInformation.GetCustomFields(), groupInCrm);

                report.CollectUpdate(result, idPair.value.Value);
            }
        }