Ejemplo n.º 1
0
        private async void SendVerificationEmail(DeliveryMan newDeliveryMan, string userId, string code)
        {
            var ip          = UsefulMethods.GetLocalIPAddress();
            var callBackUrl = "http://" + ip + ":51044/api/ConfirmDeliveryManEmail?userId=" + userId + "&code=" + code;

            string parent = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
            string path;

            path = Path.Combine(parent, "DeliveryApp\\wwwroot\\Templates\\EmailTemplates\\ConfirmRegistration.html");


            var builder = new BodyBuilder();

            using (StreamReader SourceReader = System.IO.File.OpenText(path))
            {
                builder.HtmlBody = SourceReader.ReadToEnd();
            }

            string messageBody = string.Format(
                builder.HtmlBody,
                newDeliveryMan.FirstName + " " + newDeliveryMan.LastName,
                callBackUrl
                );

            await emailSenderService.SendUserConfirmationEmail(
                newDeliveryMan.Email,
                newDeliveryMan.FirstName + " " + newDeliveryMan.LastName,
                messageBody
                );
        }
Ejemplo n.º 2
0
        private void DateTimePickerLDGValueChanged(object sender, EventArgs e)
        {
            if (sender != dateTimePickerTakeOff && sender != dateTimePickerLDG)
            {
                return;
            }

            TimeSpan flightDifference =
                UsefulMethods.GetDifference(dateTimePickerLDG.Value.TimeOfDay,
                                            dateTimePickerTakeOff.Value.TimeOfDay);
            TimeSpan day =
                UsefulMethods.GetDifference(flightDifference,
                                            dateTimePickerNight.Value.TimeOfDay);

            textFlight.Text =
                UsefulMethods.TimeToString(flightDifference);
            textBoxDay.Text =
                UsefulMethods.TimeToString(day);

            if (sender == dateTimePickerTakeOff)
            {
                InvokeTakeOffTimeChanget(dateTimePickerTakeOff.Value);
            }
            if (sender == dateTimePickerLDG)
            {
                InvokeLDGTimeChanget(dateTimePickerLDG.Value);
            }
            InvokeFlightTimeChanget(flightDifference);
        }
Ejemplo n.º 3
0
        private void DateTimePickerAirTimeValueChanged(object sender, EventArgs e)
        {
            dateTimePickerLandTime.ValueChanged -= DateTimePickerLandTimeValueChanged;

            TimeSpan workTime =
                UsefulMethods.GetDifference(dateTimePickerOff.Value.TimeOfDay,
                                            dateTimePickerStart.Value.TimeOfDay);

            dateTimePickerWorkTime.Value = dateTimePickerStart.Value.Date.Add(workTime);

            TimeSpan land =
                UsefulMethods.GetDifference(workTime,
                                            dateTimePickerAirTime.Value.TimeOfDay);

            dateTimePickerLandTime.Value = dateTimePickerStart.Value.Date.Add(land);

            //общее время работы в воздухе с учетом 20% времени работы на земле за данный пуск
            TimeSpan work120Time = dateTimePickerAirTime.Value.TimeOfDay.Add(TimeSpan.FromMinutes(land.TotalMinutes * 0.2));

            dateTimePickerWork120.Value = dateTimePickerStart.Value.Date.Add(work120Time);

            SetLifelenght();

            dateTimePickerLandTime.ValueChanged += DateTimePickerLandTimeValueChanged;
        }
Ejemplo n.º 4
0
        private void SetWorkLandAirTime()
        {
            dateTimePickerAirTime.ValueChanged  -= DateTimePickerAirTimeValueChanged;
            dateTimePickerLandTime.ValueChanged -= DateTimePickerLandTimeValueChanged;

            TimeSpan air =
                UsefulMethods.GetDifference(_landingTime.TimeOfDay,
                                            _takeOffTime.TimeOfDay);

            dateTimePickerAirTime.Value = dateTimePickerStart.Value.Date.Add(air);

            TimeSpan workTime = UsefulMethods.GetDifference(dateTimePickerOff.Value.TimeOfDay, dateTimePickerStart.Value.TimeOfDay);

            dateTimePickerWorkTime.Value = dateTimePickerStart.Value.Date.Add(workTime);

            TimeSpan land =
                UsefulMethods.GetDifference(workTime, air);

            dateTimePickerLandTime.Value = dateTimePickerStart.Value.Date.Add(land);

            //общее время работы в воздухе с учетом 20% времени работы на земле за данный пуск
            TimeSpan work120Time = air.Add(TimeSpan.FromMinutes(land.TotalMinutes * 0.2));

            dateTimePickerWork120.Value = dateTimePickerStart.Value.Date.Add(work120Time);

            SetLifelenght();

            dateTimePickerAirTime.ValueChanged  += DateTimePickerAirTimeValueChanged;
            dateTimePickerLandTime.ValueChanged += DateTimePickerLandTimeValueChanged;
        }
        /// <summary>
        /// Обновляет информацию о директиве
        /// </summary>
        /// <param name="reloadDirective">Синхронизировать ли с базой данных</param>
        private void UpdateScreen(bool reloadDirective)
        {
            if (reloadDirective)
            {
                try
                {
                    directive.Reload();
                }
                catch (Exception ex)
                {
                    Program.Provider.Logger.Log("Error while loading data", ex);
                    return;
                }
            }
            statusLinkLabel.Status = (Statuses)directive.Condition;
            statusLinkLabel.Text   = "Status: " + UsefulMethods.EnumToString(statusLinkLabel.Status);

            generalInformationControl.UpdateInformation();
            referenceDataControl.UpdateItems();
            complianceDataControl.UpdateInformation();
            complianceTermsControl.UpdateInformation();
            incorporationPlaceControl.UpdateInformation();
            affectedDocumentsControl.UpdateItems();
            referenceDocumentsControl.UpdateItems();
            referenceDrawingsControl.UpdateItems();
            MJOControl.UpdateItems();
            sparePartKitControl.UpdateItems();
            consumableMaterialsControl.UpdateItems();
            equipmentToolsGSEControl.UpdateItems();
            specificNotesDataControl.UpdateInformation();
        }
Ejemplo n.º 6
0
        private void FillActualState()
        {
            Lifelength actualState;

            if (currentDetail != null)
            {
                if (currentDetail is BaseDetail)
                {
                    actualState        = currentDetail.GetLifelength(dateTimePickerDate.Value);
                    actualStateRecords = currentDetail.GetActualSettingRecords(dateTimePickerDate.Value);
                }
                else
                {
                    actualState        = ((BaseDetail)currentDetail.Parent).GetLifelength(dateTimePickerDate.Value);
                    actualStateRecords = ((BaseDetail)currentDetail.Parent).GetActualSettingRecords(dateTimePickerDate.Value);
                }
            }
            else
            {
                actualState        = ((BaseDetail)currentDirective.Parent).GetLifelength(dateTimePickerDate.Value);
                actualStateRecords = ((BaseDetail)currentDirective.Parent).GetActualSettingRecords(dateTimePickerDate.Value);
            }
            if (actualState != null)
            {
                textBoxHours.Text  = UsefulMethods.HoursToString(actualState.Hours);
                textBoxCycles.Text = actualState.Cycles.ToString();
            }
            actualStateChanged = false;
        }
Ejemplo n.º 7
0
        protected virtual void AddListViewItem(NextPerformance np)
        {
            string[] subs =
                new[]
            {
                np.WorkType,
                np.PerformanceDate != null
                                                ? SmartCore.Auxiliary.Convert.GetDateFormat(np.PerformanceDate)
                                                : "N/A",
                np.PerformanceSource.ToString(),
                np.PerformanceSourceC.ToString(),
                np?.NextLimit.Days != null?SmartCore.Auxiliary.Convert.GetDateFormat(np?.NextPerformanceDateNew) : "",
                    np.NextLimit.ToString(),
                    np.NextLimitC.ToString(),
                    "",
            };

            ListViewItem newItem = new ListViewItem(subs)
            {
                BackColor = UsefulMethods.GetColor(np),
                Group     = listViewCompliance.Groups[0],
                Tag       = np,
            };

            listViewCompliance.Items.Add(newItem);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Evento que se encarga de generar las estadisticas
        /// </summary>
        /// <history>
        /// [erosado] 08/Mar/2016 Created
        /// </history>
        private void imgButtonOk_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            imgButtonOk.Focus();
            if (lsbxLeadSources.SelectedItems.Count > 0 && lsbxSalesRooms.SelectedItems.Count > 0 &&
                lsbxCountries.SelectedItems.Count > 0 && lsbxAgencies.SelectedItems.Count > 0 &&
                lsbxMarkets.SelectedItems.Count > 0)
            {
                if (DateHelper.ValidateValueDate(dtpkFrom, dtpkTo))
                {
                    filterTuple = new List <Tuple <string, string> >();
                    StaStart("Loading Data...");
                    imgButtonOk.IsEnabled = false;
                    filterTuple.Add(new Tuple <string, string>("DateRange", DateHelper.DateRange(dtpkFrom.Value.Value, dtpkTo.Value.Value)));
                    filterTuple.Add(new Tuple <string, string>("LeadSource", UsefulMethods.SelectedItemsIdToString(lsbxLeadSources)));
                    filterTuple.Add(new Tuple <string, string>("SalesRooms", UsefulMethods.SelectedItemsIdToString(lsbxSalesRooms)));
                    filterTuple.Add(new Tuple <string, string>("Countries", chbxCountries.IsChecked == true ? "ALL" : UsefulMethods.SelectedItemsIdToString(lsbxCountries)));
                    filterTuple.Add(new Tuple <string, string>("Agencies", chbxAgencies.IsChecked == true ? "ALL" : UsefulMethods.SelectedItemsIdToString(lsbxAgencies)));
                    filterTuple.Add(new Tuple <string, string>("Markets", chbxMarkets.IsChecked == true ? "ALL" : UsefulMethods.SelectedItemsIdToString(lsbxMarkets)));

                    DoGetRptPrStats(dtpkFrom.Value.Value, dtpkTo.Value.Value, filterTuple);
                }
            }
            else
            {
                UIHelper.ShowMessage("Select at least one item from each catalog ", MessageBoxImage.Warning);
            }
        }
Ejemplo n.º 9
0
        /*
         * Перегруженные методы
         */

        #region public override void ApplyChanges()
        /// <summary>
        /// Применить к объекту сделанные изменения на контроле.
        /// Если не все данные удовлетворяют формату ввода (например при вводе чисел), свойства объекта не изменяются, возвращается false
        /// Вызов base.ApplyChanges() обязателен
        /// </summary>
        /// <returns></returns>
        public override void ApplyChanges()
        {
            if (Discrepancy != null)
            {
                Discrepancy.FilledBy = radioCrew.Checked ? DiscrepancyFilledByEnum.Crew : DiscrepancyFilledByEnum.MaintenanceStaff;

                // Если ATA глава не задана задаем N/A АТА главу
                Discrepancy.ATAChapter = ATAChapterCollection.GetATAChapterByName(textATA.Text);
                if (Discrepancy.ATAChapter == null)
                {
                    Discrepancy.ATAChapter = ATAChapterCollection.Instance.NotApplicableATAChapter;
                }

                Discrepancy.CorrectiveAction.ADDNo  = textADDNo.Text;
                Discrepancy.CorrectiveAction.Status = radioClose.Checked ? CorrectiveActionStatus.Close : CorrectiveActionStatus.Open;
                Discrepancy.Description             = textDescription.Text;

                Discrepancy.CorrectiveAction.Description                  = textCorrectiveAction.Text;
                Discrepancy.CorrectiveAction.PartNumberOn                 = textPNOn.Text;
                Discrepancy.CorrectiveAction.PartNumberOff                = textPNOff.Text;
                Discrepancy.CorrectiveAction.SerialNumberOn               = textSNOn.Text;
                Discrepancy.CorrectiveAction.SerialNumberOff              = textSNOff.Text;
                Discrepancy.CertificateOfReleaseToService.Station         = textStation.Text;
                Discrepancy.CertificateOfReleaseToService.Date            = UsefulMethods.StringToDate(textRTSDate.Text).Value;
                Discrepancy.CertificateOfReleaseToService.AuthorizationNo = textAuthNo.Text;
            }
            //
            base.ApplyChanges();
        }
Ejemplo n.º 10
0
 private void UpdateInformation()
 {
     dateTimePickerDate.Value = currentRecord.RecordDate;
     textBoxFlightHours.Text  = UsefulMethods.HoursToString(currentRecord.Lifelength.Hours);
     textBoxFlightCycles.Text = currentRecord.Lifelength.Cycles.ToString();
     textBoxRemarks.Text      = currentRecord.Description;
 }
Ejemplo n.º 11
0
 private void LinkLabelBrowseLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     if (string.IsNullOrEmpty(_fileName) &&
         ((_fileData == null && (_fileSize == null || _fileSize <= 0)) ||
          string.IsNullOrEmpty(_filePath)))
     {
         OpenFileDialog dialog = new OpenFileDialog();
         dialog.Filter = _filter;
         if (dialog.ShowDialog() == DialogResult.OK)
         {
             if (_file != null)
             {
                 _file.IsDeleted = false;
             }
             _fileData = UsefulMethods.GetByteArrayFromFile(dialog.FileName);
             _fileName = string.IsNullOrEmpty(dialog.SafeFileName) ? "" : dialog.SafeFileName;
             _filePath = dialog.FileName;
             _fileSize = _fileData.Length;
             UpdateInfo();
             if (FileChanged != null)
             {
                 FileChanged(_fileName.Substring(0, _fileName.LastIndexOf('.')));
             }
         }
     }
     else
     {
         progressBarLoad.Value   = 0;
         progressBarLoad.Visible = true;
         backgroundWorker.RunWorkerAsync();
     }
 }
Ejemplo n.º 12
0
        public override void EditItem(BaseDetailDirective oldItem, BaseDetailDirective modifiedItem)
        {
            string[]            itemsString = GetItemString(modifiedItem);
            BaseDetailDirective detail      = GetDirectiveReferenceByDirectiveID(modifiedItem.ID);

            if (detail == null)
            {
                return;
            }
            ListViewItem listViewItem = ItemsHash[detail];

            listViewItem.SubItems.Clear();
            if (!modifiedItem.Closed)
            {
                listViewItem.ForeColor = Color.Black;
            }
            listViewItem.Text = itemsString[0];
            for (int i = 1; i < itemsString.Length; i++)
            {
                listViewItem.SubItems.Add(itemsString[i]);
            }
            listViewItem.BackColor = UsefulMethods.GetDirectiveColor(modifiedItem);

            listViewItem.Tag = modifiedItem;
            ItemsHash.Remove(modifiedItem);
            ItemsHash.Add(modifiedItem, listViewItem);
            ItemsListView.Refresh();
            SetTotalText();
        }
Ejemplo n.º 13
0
    protected virtual void MoveWeapon()
    {
        if (_currentTarget == null)
        {
            DetonateWeapon();
            return;
        }

        Vector3 myPosition     = new Vector3(transform.position.x, transform.position.y, 0f);
        Vector3 targetPosition = new Vector3(_currentTarget.transform.position.x, _currentTarget.transform.position.y, 0f);

        Vector3    vectorToTarget = targetPosition - myPosition;
        float      angleToTarget  = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
        Quaternion q = Quaternion.AngleAxis(angleToTarget, Vector3.forward);

        transform.rotation  = q;
        transform.position += transform.right * Time.deltaTime * _weaponSpeed;

        float sqDistanceToWaypoint = UsefulMethods.CheapDistanceSquared(myPosition, targetPosition);

        if (sqDistanceToWaypoint <= (_detonationRadius * _detonationRadius))
        {
            DetonateWeapon();
        }
    }
Ejemplo n.º 14
0
 private void UpdateDocumentation()
 {
     foreach (Document document in _aircraftDocuments)
     {
         AutoCompleteStringCollection parameters = new AutoCompleteStringCollection
         {
             document.Description,
             document.ContractNumber,
             document.NextPerformanceDate != null
                                         ? UsefulMethods.NormalizeDate(document.IssueDateValidFrom)
                                         : "",
             document.IssueValidTo
                                         ? UsefulMethods.NormalizeDate(document.IssueDateValidTo)
                                         : "",
             document.Remains.ToString()
         };
         Action <AutoCompleteStringCollection> addLast = AddCertificateItem;
         if (InvokeRequired)
         {
             Invoke(addLast, parameters);
         }
         else
         {
             addLast.Invoke(parameters);
         }
     }
 }
Ejemplo n.º 15
0
        protected override void SetItemColor(ListViewItem listViewItem, BaseEntityObject item)
        {
            if (item is ComponentDirective)
            {
                listViewItem.ForeColor = Color.Gray;

                ComponentDirective dd = item as ComponentDirective;
                listViewItem.BackColor = dd.ItemRelations.Count > 0
                    ? Color.FromArgb(Highlight.Grey.Color)
                    : UsefulMethods.GetColor(item);
            }
            if (item is Component)
            {
                listViewItem.ForeColor = Color.Black;
                listViewItem.BackColor = UsefulMethods.GetColor(item);
            }
            if (item.IsDeleted)
            {
                //запись так же может быть удаленной

                //шрифт серым цветом
                listViewItem.ForeColor = Color.Gray;
                if (listViewItem.ToolTipText.Trim() != "")
                {
                    listViewItem.ToolTipText += "\n";
                }
                listViewItem.ToolTipText += $"This {item.SmartCoreObjectType} is deleted";
            }
        }
Ejemplo n.º 16
0
 public void play(Environment e, UsefulMethods odd, Player player)
 {
     Random rand = new Random();
     int randNum = rand.Next(0, 0); // update for number of missions
     if (randNum == 0)
         environment_1(e, odd, player);
 }
Ejemplo n.º 17
0
        protected override void AddListViewItem(NextPerformance np)
        {
            Directive d = np.Parent as Directive;

            string[] subs =
                new[]
            {
                np.WorkType + (d == null ? "" : " §:" + d.Paragraph),
                np.PerformanceDate != null
                            ? SmartCore.Auxiliary.Convert.GetDateFormat(np.PerformanceDate)
                            : "N/A",
                np.PerformanceSource.ToString(),
                np?.NextLimit.Days != null?SmartCore.Auxiliary.Convert.GetDateFormat(np?.NextPerformanceDateNew) : "",
                    np.NextLimit.ToString(),
                    "",
            };

            ListViewItem newItem = new ListViewItem(subs)
            {
                BackColor = UsefulMethods.GetColor(np),
                Group     = listViewCompliance.Groups[0],
                Tag       = np,
            };

            listViewCompliance.Items.Add(newItem);
        }
Ejemplo n.º 18
0
        public async Task <Object> ForgotPassword(EmailForForgotPasswordDto emailDto)
        {
            var ip   = UsefulMethods.GetLocalIPAddress();
            var user = await _userManager.FindByEmailAsync(emailDto.Email);

            if (user != null)
            {
                var token = await _userManager.GeneratePasswordResetTokenAsync(user);

                var callBackUrl = "http://" + ip + ":51044/api/resetPassword?userId=" + user.Id + "&token=" + token;

                string parent = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
                string path;

                path = Path.Combine(parent, "DeliveryApp\\wwwroot\\Templates\\EmailTemplates\\ResetPasswordEmail.html");


                var builder = new BodyBuilder();
                using (StreamReader SourceReader = System.IO.File.OpenText(path))
                {
                    builder.HtmlBody = SourceReader.ReadToEnd();
                }

                string messageBody = string.Format(
                    builder.HtmlBody,
                    callBackUrl
                    );

                await emailSenderService.SendResetPasswordEmail(emailDto.Email, messageBody);
            }
            return(Ok(new { message = "Email envoyé." }));
        }
Ejemplo n.º 19
0
        public List <string> cautaBaza(string xmlID)
        {
            List <string> id = new List <string>();

            con.Open();
            cmd.CommandText = "SELECT * FROM MCU_TYPES WHERE RAM_APL =" + xmlID + " ";

            reader = cmd.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    xmlID = UsefulMethods.getPerfectString(xmlID);
                    string xmlIdDb = reader[2].ToString();
                    xmlIdDb = UsefulMethods.getPerfectString(xmlIdDb);
                    if (xmlID == xmlIdDb)
                    {
                        string cpuId = reader[0].ToString();
                        id.Add(cpuId);
                    }
                }
            }
            con.Close();
            return(id);
        }
Ejemplo n.º 20
0
        protected override List <CustomCell> GetListViewSubItems(ATLB item)
        {
            AircraftFlightCollection flights;
            AircraftFlight           first;
            AircraftFlight           last;

            if (_parentAircraft != null)
            {
                flights = GlobalObjects.AircraftFlightsCore.GetAircraftFlightsByAircraftId(_parentAircraft.ItemId);
                first   = flights.GetFirstFlightInAtlb(item.ItemId);
                last    = flights.GetLastFlightInAtlb(item.ItemId);
            }
            else
            {
                first = GlobalObjects.AircraftFlightsCore.GetFirstFlight(item.ItemId);
                last  = GlobalObjects.AircraftFlightsCore.GetLastFlight(item.ItemId);
            }

            var pages = (first != null && first.PageNo != "" ? first.PageNo : "XXX") + " - " +
                        (last != null && last.PageNo != "" ? last.PageNo : "XXX");
            var dates = (first != null ? UsefulMethods.NormalizeDate(first.FlightDate.Date) : "YY:MM:DD") + " - " +
                        (last != null ? UsefulMethods.NormalizeDate(last.FlightDate.Date) : "YY:MM:DD");

            var author = GlobalObjects.CasEnvironment.GetCorrector(item);

            return(new List <CustomCell>()
            {
                CreateRow(item.AtlbStatus.ToString(), item.AtlbStatus),
                CreateRow(item.ATLBNo, item.ATLBNo),
                CreateRow(pages, pages),
                CreateRow(dates, last != null ? last.FlightDate : DateTimeExtend.GetCASMinDateTime()),
                CreateRow(author, author)
            });
        }
Ejemplo n.º 21
0
        /*
         * Перегружаемые методы
         */

        #region public override void ApplyChanges()
        /// <summary>
        /// Применить к объекту сделанные изменения на контроле.
        /// Если не все данные удовлетворяют формату ввода (например при вводе чисел), свойства объекта не изменяются, возвращается false
        /// Вызов base.ApplyChanges() обязателен
        /// </summary>
        /// <returns></returns>
        public override void ApplyChanges()
        {
            if (Flight != null && Flight.CertificateOfReleaseToService != null)
            {
                if (checkPFC.Checked)
                {
                    Flight.CertificateOfReleaseToService.CheckPerformed = "PFC";
                }
                else if (checkTC.Checked)
                {
                    Flight.CertificateOfReleaseToService.CheckPerformed = "TC";
                }
                else if (checkDY.Checked)
                {
                    Flight.CertificateOfReleaseToService.CheckPerformed = "DY";
                }
                else
                {
                    Flight.CertificateOfReleaseToService.CheckPerformed = "";
                }
                Flight.CertificateOfReleaseToService.Date            = UsefulMethods.StringToDate(textDate.Text).Value;
                Flight.CertificateOfReleaseToService.AuthorizationNo = textAuth.Text;
            }
            //
            base.ApplyChanges();
        }
        protected override void AddListViewItem(NextPerformance np)
        {
            string[] subs =
                new[]
            {
                np.WorkType,
                np.PerformanceDate != null
                        ? SmartCore.Auxiliary.Convert.GetDateFormat(np.PerformanceDate)
                        : "N/A",
                np.PerformanceSource.ToString(),
                np?.NextLimit.Days != null?SmartCore.Auxiliary.Convert.GetDateFormat(np?.NextPerformanceDateNew) : "",
                    np.NextLimit.ToString(),
                    "",
            };

            ListViewItem newItem = new ListViewItem(subs)
            {
                Group = listViewCompliance.Groups[0],
                Tag   = np,
            };

            newItem.BackColor = _currentDirective.MaintenanceCheck != null
                ? Color.FromArgb(Highlight.Grey.Color)
                : UsefulMethods.GetColor(np);

            listViewCompliance.Items.Add(newItem);
        }
Ejemplo n.º 23
0
        private void OpenReport(object parameter)
        {
            JobCard jobCard = (JobCard)parameter;
            string  path    = TermsProvider.GetTempFolderPath() + "\\" + jobCard.AirlineCardNumber + ".pdf";

            if (!File.Exists(path))
            {
                UsefulMethods.SaveFileFromByteArray(jobCard.AttachedFile.FileData, path);
            }
            Process tempProcess = new Process();

            tempProcess.StartInfo = new ProcessStartInfo(path);
            try
            {
                tempProcess.Start();
                tempProcess.WaitForExit();
            }
            catch (Exception ex)
            {
                Program.Provider.Logger.Log("Error while loading data", ex);
            }
            try
            {
                TryDeleteFile(path);
            }
            catch (Exception ex)
            {
                Program.Provider.Logger.Log("Error while deleting data", ex);
            }
        }
        /// <summary>
        /// Добавляется элемент в таблицу данных
        /// </summary>
        /// <param name="componentобавляемый агрегат</param>
        /// <param name="previousNumber">Порядковый номер агрегата</param>
        /// <param name="destinationDataSet">Таблица, в которую добавляется элемент</param>
        protected override void AddDetailToDataset(Component component, ref int previousNumber, DetailListDataSet destinationDataSet)
        {
            var ata                    = component.ATAChapter;
            var atachapter             = ata.ShortName;
            var componentNumber        = (previousNumber++).ToString();
            var atachapterfull         = ata.FullName;
            var partNumber             = component.PartNumber;
            var description            = component.Description;
            var serialNumber           = component.SerialNumber;
            var lastTransferRecord     = component.TransferRecords.GetLast();
            var positionNumber         = lastTransferRecord.Position;
            var instalationDate        = UsefulMethods.NormalizeDate(lastTransferRecord.TransferDate);
            var installationLifelength = lastTransferRecord.OnLifelength;
            var remarks                = component.Remarks;

            GlobalObjects.PerformanceCalculator.GetNextPerformance(component);
            var current            = GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength(component);
            var installationTsncsn = LifelengthFormatter.GetHoursData(installationLifelength, " hrs\r\n") +
                                     LifelengthFormatter.GetCyclesData(installationLifelength, " cyc\r\n");
            var currentTsncsn = LifelengthFormatter.GetHoursData(current, " hrs\r\n") +
                                LifelengthFormatter.GetCyclesData(current, " cyc\r\n");
            var condition = component.Condition.GetHashCode().ToString();
            var lifelengthAircraftTime = current;

            lifelengthAircraftTime.Substract(installationLifelength);
            var aircraftTime = LifelengthFormatter.GetHoursData(lifelengthAircraftTime, " hrs\r\n") +
                               LifelengthFormatter.GetCyclesData(lifelengthAircraftTime, " cyc\r\n");

            destinationDataSet.ItemsTable.AddItemsTableRow(componentNumber, atachapter, atachapterfull, partNumber, description, serialNumber, positionNumber, "",
                                                           instalationDate, "", "", "", "", "",
                                                           "", "", condition, aircraftTime, "", "", "", "", "", "",
                                                           installationTsncsn, remarks, currentTsncsn);
        }
Ejemplo n.º 25
0
        public void ImportAdTAskCArdOrCrateNew()
        {
            var env = GetEnviroment();

            var itemRelationCore = new ItemsRelationsDataAccess(env);
            var aircraftCore     = new AircraftsCore(env.Loader, env.NewKeeper, null);
            var directiveCore    = new DirectiveCore(env.NewKeeper, env.NewLoader, env.Keeper, env.Loader, itemRelationCore);
            var componentCore    = new ComponentCore(env, env.Loader, env.NewLoader, env.NewKeeper, aircraftCore, itemRelationCore);

            var aircraftId = 2336;

            var aircraft = env.NewLoader.GetObject <AircraftDTO, Aircraft>(new Filter("ItemId", aircraftId));

            var directiveList = directiveCore.GetDirectives(aircraft, DirectiveType.AirworthenessDirectives);
            var bd            = componentCore.GetAicraftBaseComponents(aircraftId, BaseComponentType.Frame.ItemId).LastOrDefault();

            var d     = new DirectoryInfo(@"D:\Work\doc\ALL AD 757 13 Feb 2019 1111\FAA 757");
            var files = d.GetFiles();

            foreach (var file in files)
            {
                var name      = file.Name.Replace(" ", "").Replace(".pdf", "");
                var directive = directiveList.FirstOrDefault(i => i.Title.Contains(name));

                if (directive != null)
                {
                    var _fileData    = UsefulMethods.GetByteArrayFromFile(file.FullName);
                    var attachedFile = new AttachedFile
                    {
                        FileData = _fileData,
                        FileName = file.Name,
                        FileSize = _fileData.Length
                    };
                    directive.ADNoFile = attachedFile;
                    env.NewKeeper.Save(directive);
                }
                else
                {
                    var newDirective = new Directive
                    {
                        Title               = name,
                        DirectiveType       = DirectiveType.AirworthenessDirectives,
                        ADType              = ADType.Airframe,
                        HiddenRemarks       = "NEW",
                        IsApplicability     = true,
                        ParentBaseComponent = bd
                    };

                    var _fileData    = UsefulMethods.GetByteArrayFromFile(file.FullName);
                    var attachedFile = new AttachedFile
                    {
                        FileData = _fileData,
                        FileName = file.Name,
                        FileSize = _fileData.Length
                    };
                    newDirective.ADNoFile = attachedFile;
                    env.NewKeeper.Save(newDirective);
                }
            }
        }
Ejemplo n.º 26
0
        public async Task <ActionResult> GeneratePassword(string id)
        {
            ApplicationDbContext UsersContext = new ApplicationDbContext();

            if (Session["traderID"] == null)
            {
                return(new HttpStatusCodeResult(5));
            }
            int traderId = Convert.ToInt32(Session["traderID"].ToString());

            var             Db          = new ApplicationDbContext();
            ApplicationUser userObj     = Db.Users.Where(j => j.TraderId == traderId && j.Id == id).First();
            string          createdPass = UsefulMethods.GenerateNewPassword();
            PasswordHasher  hasher      = new PasswordHasher();

            userObj.PasswordHash    = hasher.HashPassword(createdPass);
            userObj.NeedReset       = true;
            userObj.DefaultPassword = createdPass;
            //var result = await UserManager.UpdateAsync(userObj);

            Db.Entry(userObj).State = EntityState.Modified;
            await Db.SaveChangesAsync();

            int pageSize   = Convert.ToInt32(ConfigurationManager.AppSettings["DefaultPageSize"]);
            int pageNumber = 1;

            ViewBag.pageSize = pageSize;

            List <ApplicationUser> userList = UsersContext.Users.Where(j => j.TraderId == traderId).OrderBy(o => o.UserName).ToList();

            return(PartialView("_List", userList.ToPagedList(pageNumber, pageSize)));
        }
Ejemplo n.º 27
0
        public void ImportAdTAskCArd()
        {
            var env = GetEnviroment();

            var itemRelationCore = new ItemsRelationsDataAccess(env);
            var directiveCore    = new DirectiveCore(env.NewKeeper, env.NewLoader, env.Keeper, env.Loader, itemRelationCore);

            var aircraft = env.NewLoader.GetObject <AircraftDTO, Aircraft>(new Filter("ItemId", 2348));

            var directiveList = directiveCore.GetDirectives(aircraft, DirectiveType.AirworthenessDirectives);

            var d     = new DirectoryInfo(@"H:\CRJ200 27.02.18 AD");
            var files = d.GetFiles();

            foreach (var mpd in directiveList)
            {
                var file = files.FirstOrDefault(f => mpd.Title.Contains(f.Name.Replace(" ", "").Replace(".pdf", "")));
                if (file != null)
                {
                    var _fileData    = UsefulMethods.GetByteArrayFromFile(file.FullName);
                    var attachedFile = new AttachedFile
                    {
                        FileData = _fileData,
                        FileName = file.Name,
                        FileSize = _fileData.Length
                    };
                    mpd.ADNoFile = attachedFile;
                    env.NewKeeper.Save(mpd);
                }
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Проверяет введенные данные.
        /// Если какое-либо поле не подходит по формату, следует сразу кидать MessageBox, ставить курсор в необходимое поле и возвращать false в качестве результата метода
        /// </summary>
        /// <returns></returns>
        public override bool CheckData()
        {
            // Правильность ввода даты
            if (!ValidateEventDate())
            {
                MessageBox.Show("Event Date must be between 1 Jan 1950 and " + UsefulMethods.NormalizeDate(DateTime.Now),
                                (string)new GlobalTermsProvider()["SystemName"],
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
                return(false);
            }

            if (flowLayoutPanelConditions.Controls.OfType <SmsConditionControl>().Any(scc => !scc.CheckData()))
            {
                MessageBox.Show("Not specified event condition or " +
                                "\nthe selected item is not the end node of the tree",
                                (string)new GlobalTermsProvider()["SystemName"],
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);

                return(false);
            }

            return(true);
        }
Ejemplo n.º 29
0
 protected override void SetItemColor(GridViewRowInfo listViewItem, FlightPlanOpsRecords item)
 {
     foreach (GridViewCellInfo cell in listViewItem.Cells)
     {
         cell.Style.CustomizeFill = true;
         cell.Style.BackColor     = UsefulMethods.GetColor(item);
     }
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Применяет введенные данные к стойкам шасси
 /// </summary>
 /// <param name="condition"></param>
 /// <param name="textN1"></param>
 /// <param name="textN2"></param>
 private void ApplyBundle(LandingGearCondition condition, TextBox textN1, TextBox textN2)
 {
     if (condition.LandingGear != null)
     {
         condition.TirePressure1 = UsefulMethods.StringToDouble(textN1.Text);
         condition.TirePressure2 = UsefulMethods.StringToDouble(textN2.Text);
     }
 }
        static void Main(string[] args)
        {
            UsefulMethods methods = new UsefulMethods();
            String        Res     = methods.GetGreeting("Bren");

            Console.WriteLine("Debug:" + Res);
            Console.ReadKey();
        }
Ejemplo n.º 32
0
 public void setDefualtEnvironment(UsefulMethods odd)
 {
     int npclength = odd.npcList.Count;
     int weaponLength = odd.weaponList.Count;
     Random rand = new Random();
     //set random number of weapons and npc
     int randNum = rand.Next(0, 10);
     this.numNPC = randNum;
     randNum = rand.Next(0, 10);
     this.numWeapon = randNum;
     randNum = rand.Next(1, 1000);
     this.numMoney = randNum;
 }
Ejemplo n.º 33
0
    public void environment_1(Environment e, UsefulMethods odd, Player player)
    {
        House h1 = new House();
        Console.WriteLine(" You wake up in a wooded area, you are unsure of what happened or how you got there.");
        Console.WriteLine(" You look around and can see a small cabin off in the distance. how do you procced? ");
        Console.Write("1: Go to the cabin \n2: Walk in the opposite direction");
        int ans = Convert.ToInt32(Console.ReadLine());

        if (ans == 1)
            h1.cabin(odd, player);
        else if (ans == 2)
            throw new NotImplementedException();
        else
            Console.WriteLine("Please choose from an option above");
    }
Ejemplo n.º 34
0
    public void cabin(UsefulMethods odd, Player player)
    {
        NPC n = new NPC();
           n = odd.getRandomNPC();
           Console.Write("you knock on the door and a man appears\n 'Ah hello there stranger please come in! it has been sometime since i have had a visitor\n"+
                        " Have a seat, my name is  "+ n.name + " please have a drink, i made it myself\n");
           Console.Write("1: Drink from cup \n2:politly refuse");
           int ans = Convert.ToInt32(Console.ReadLine());

           if (ans == 1)
           throw new NotImplementedException();
           if (ans == 2)
           throw new NotImplementedException();
           else
           Console.WriteLine("please enter a valid choice");
    }
Ejemplo n.º 35
0
 //static List<NPC> npcList = new List<NPC>();
 static void Main(string[] args)
 {
     //==================Set up NPC's==================================================
     UsefulMethods odd = new UsefulMethods();
     XDocument npcPlayers = XDocument.Load("NPC.xml"); //Load NPC's in
     odd.addNpcToList(npcPlayers);
     NPC n = new NPC();
     n = odd.getRandomNPC();
     Console.WriteLine(n.name);
     //================================================================================
     //=================Set up Player==================================================
     Console.WriteLine("please select a name for your player:");
     string name = Console.ReadLine();
     Player player = new Player(name);
     //printPlayerStats(player);
     //=================================================================================
     //================Set up weapons===================================================
     //odd.saveWeaponData("Weapons.xml");
     XDocument weaponDoc = XDocument.Load("weapons.xml");
     odd.addWeaponToList(weaponDoc);
     //=================================================================================
     //===================Debug statements for weapons==================================
        // odd.displayWeapons();
     //Console.Clear();
     //int length = odd.weaponList.Count;
     //for (int i = 0; i < length; i++)
     //{
     //    Weapon w = odd.getRandomWeapon();
     //   // Console.WriteLine("random weapon = " + w.name);
     //    player.addItem(w);
     //}
     //player.showInventory();
     //=================================================================================
     //==================Set up missions================================================
     Mission m = new Mission();
     m.Mission_1(odd, player);
     Console.ReadLine();
     //================================================================================
     //================Debug statements for NPC's=======================================
     //odd.displayNpcs();
     //Console.Clear();
     //Console.WriteLine("Random NPC from list");
     //odd.getRandomNPC();
     //===================================================================================
 }
Ejemplo n.º 36
0
 public virtual void Mission_1(UsefulMethods odd, Player player)
 {
     Environment e1 = new Environment(odd);
     e1.play(e1, odd, player);
 }
Ejemplo n.º 37
0
 public Environment(UsefulMethods odd)
 {
     setDefualtEnvironment(odd);
 }